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
modm-io/modm
845840ec08566a3aa9c04167b1a18a56255afa4f
tools/xpcc_generator/xmlparser/event.py
python
Event.update
(self, other)
Update events with the values from another event Events are guaranteed to be unique within the evaluted tree. Therefore an update demand can only be issued for the same events, one declared in the super-class and the other in the sub-class. The assert statement checks this, nothing else needs to be done.
Update events with the values from another event
[ "Update", "events", "with", "the", "values", "from", "another", "event" ]
def update(self, other): """ Update events with the values from another event Events are guaranteed to be unique within the evaluted tree. Therefore an update demand can only be issued for the same events, one declared in the super-class and the other in the sub-class. The assert statement checks this, nothing else needs to be done. """ assert id(self) == id(other)
[ "def", "update", "(", "self", ",", "other", ")", ":", "assert", "id", "(", "self", ")", "==", "id", "(", "other", ")" ]
https://github.com/modm-io/modm/blob/845840ec08566a3aa9c04167b1a18a56255afa4f/tools/xpcc_generator/xmlparser/event.py#L59-L68
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/HeppyCore/python/utils/eostools.py
python
runXRDCommand
(path, cmd, *args)
return runner.runCommand(command)
Run an xrd command. !!! Will, what is happening in case of problem? ??? At some point, should return a list of lines instead of a string.
Run an xrd command.
[ "Run", "an", "xrd", "command", "." ]
def runXRDCommand(path, cmd, *args): """Run an xrd command. !!! Will, what is happening in case of problem? ??? At some point, should return a list of lines instead of a string.""" lfn = eosToLFN(path) #print "lfn:", lfn, cmd tokens = cmsIO.splitPFN(lfnToPFN(lfn)) command = ['xrd', tokens[1], cmd, tokens[2]] command.extend(args) runner = cmsIO.cmsFileManip() # print ' '.join(command) return runner.runCommand(command)
[ "def", "runXRDCommand", "(", "path", ",", "cmd", ",", "*", "args", ")", ":", "lfn", "=", "eosToLFN", "(", "path", ")", "#print \"lfn:\", lfn, cmd", "tokens", "=", "cmsIO", ".", "splitPFN", "(", "lfnToPFN", "(", "lfn", ")", ")", "command", "=", "[", "'x...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/HeppyCore/python/utils/eostools.py#L23-L37
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py
python
_showwarning
(message, category, filename, lineno, file=None, line=None)
Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING.
Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING.
[ "Implementation", "of", "showwarnings", "which", "redirects", "to", "logging", "which", "will", "first", "check", "to", "see", "if", "the", "file", "parameter", "is", "None", ".", "If", "a", "file", "is", "specified", "it", "will", "delegate", "to", "the", ...
def _showwarning(message, category, filename, lineno, file=None, line=None): """ Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. """ if file is not None: if _warnings_showwarning is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger("py.warnings") if not logger.handlers: logger.addHandler(NullHandler()) logger.warning("%s", s)
[ "def", "_showwarning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "file", "=", "None", ",", "line", "=", "None", ")", ":", "if", "file", "is", "not", "None", ":", "if", "_warnings_showwarning", "is", "not", "None", ":", "_war...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py#L1694-L1710
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/ValidationKit/common/utils.py
python
readFile
(sFile, sMode = 'rb')
return sRet
Reads the entire file.
Reads the entire file.
[ "Reads", "the", "entire", "file", "." ]
def readFile(sFile, sMode = 'rb'): """ Reads the entire file. """ oFile = open(sFile, sMode); sRet = oFile.read(); oFile.close(); return sRet;
[ "def", "readFile", "(", "sFile", ",", "sMode", "=", "'rb'", ")", ":", "oFile", "=", "open", "(", "sFile", ",", "sMode", ")", "sRet", "=", "oFile", ".", "read", "(", ")", "oFile", ".", "close", "(", ")", "return", "sRet" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/ValidationKit/common/utils.py#L379-L386
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/io/matlab/miobase.py
python
get_matfile_version
(fileobj)
Return major, minor tuple depending on apparent mat file type Where: #. 0,x -> version 4 format mat files #. 1,x -> version 5 format mat files #. 2,x -> version 7.3 format mat files (HDF format) Parameters ---------- fileobj : file_like object implementing seek() and read() Returns ------- major_version : {0, 1, 2} major MATLAB File format version minor_version : int minor MATLAB file format version Raises ------ MatReadError If the file is empty. ValueError The matfile version is unknown. Notes ----- Has the side effect of setting the file read pointer to 0
Return major, minor tuple depending on apparent mat file type
[ "Return", "major", "minor", "tuple", "depending", "on", "apparent", "mat", "file", "type" ]
def get_matfile_version(fileobj): """ Return major, minor tuple depending on apparent mat file type Where: #. 0,x -> version 4 format mat files #. 1,x -> version 5 format mat files #. 2,x -> version 7.3 format mat files (HDF format) Parameters ---------- fileobj : file_like object implementing seek() and read() Returns ------- major_version : {0, 1, 2} major MATLAB File format version minor_version : int minor MATLAB file format version Raises ------ MatReadError If the file is empty. ValueError The matfile version is unknown. Notes ----- Has the side effect of setting the file read pointer to 0 """ # Mat4 files have a zero somewhere in first 4 bytes fileobj.seek(0) mopt_bytes = fileobj.read(4) if len(mopt_bytes) == 0: raise MatReadError("Mat file appears to be empty") mopt_ints = np.ndarray(shape=(4,), dtype=np.uint8, buffer=mopt_bytes) if 0 in mopt_ints: fileobj.seek(0) return (0,0) # For 5 format or 7.3 format we need to read an integer in the # header. Bytes 124 through 128 contain a version integer and an # endian test string fileobj.seek(124) tst_str = fileobj.read(4) fileobj.seek(0) maj_ind = int(tst_str[2] == b'I'[0]) maj_val = byteord(tst_str[maj_ind]) min_val = byteord(tst_str[1-maj_ind]) ret = (maj_val, min_val) if maj_val in (1, 2): return ret raise ValueError('Unknown mat file type, version %s, %s' % ret)
[ "def", "get_matfile_version", "(", "fileobj", ")", ":", "# Mat4 files have a zero somewhere in first 4 bytes", "fileobj", ".", "seek", "(", "0", ")", "mopt_bytes", "=", "fileobj", ".", "read", "(", "4", ")", "if", "len", "(", "mopt_bytes", ")", "==", "0", ":",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/matlab/miobase.py#L187-L241
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TNEANet.AddEdge
(self, *args)
return _snap.TNEANet_AddEdge(self, *args)
AddEdge(TNEANet self, int const & SrcNId, int const & DstNId, int EId=-1) -> int Parameters: SrcNId: int const & DstNId: int const & EId: int AddEdge(TNEANet self, int const & SrcNId, int const & DstNId) -> int Parameters: SrcNId: int const & DstNId: int const & AddEdge(TNEANet self, TNEANet::TEdgeI const & EdgeI) -> int Parameters: EdgeI: TNEANet::TEdgeI const &
AddEdge(TNEANet self, int const & SrcNId, int const & DstNId, int EId=-1) -> int
[ "AddEdge", "(", "TNEANet", "self", "int", "const", "&", "SrcNId", "int", "const", "&", "DstNId", "int", "EId", "=", "-", "1", ")", "-", ">", "int" ]
def AddEdge(self, *args): """ AddEdge(TNEANet self, int const & SrcNId, int const & DstNId, int EId=-1) -> int Parameters: SrcNId: int const & DstNId: int const & EId: int AddEdge(TNEANet self, int const & SrcNId, int const & DstNId) -> int Parameters: SrcNId: int const & DstNId: int const & AddEdge(TNEANet self, TNEANet::TEdgeI const & EdgeI) -> int Parameters: EdgeI: TNEANet::TEdgeI const & """ return _snap.TNEANet_AddEdge(self, *args)
[ "def", "AddEdge", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TNEANet_AddEdge", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L21778-L21799
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
txjsonrpc/jsonrpc.py
python
Introspection.jsonrpc_methodSignature
(self, method)
return getattr(method, 'signature', None) or ''
Return a list of type signatures. Each type signature is a list of the form [rtype, type1, type2, ...] where rtype is the return type and typeN is the type of the Nth argument. If no signature information is available, the empty string is returned.
Return a list of type signatures.
[ "Return", "a", "list", "of", "type", "signatures", "." ]
def jsonrpc_methodSignature(self, method): """ Return a list of type signatures. Each type signature is a list of the form [rtype, type1, type2, ...] where rtype is the return type and typeN is the type of the Nth argument. If no signature information is available, the empty string is returned. """ method = self._jsonrpc_parent._getFunction(method) return getattr(method, 'signature', None) or ''
[ "def", "jsonrpc_methodSignature", "(", "self", ",", "method", ")", ":", "method", "=", "self", ".", "_jsonrpc_parent", ".", "_getFunction", "(", "method", ")", "return", "getattr", "(", "method", ",", "'signature'", ",", "None", ")", "or", "''" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/txjsonrpc/jsonrpc.py#L186-L196
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/common.py
python
ensure_str
(value: Union[bytes, Any])
return value
Ensure that bytes and non-strings get converted into ``str`` objects.
Ensure that bytes and non-strings get converted into ``str`` objects.
[ "Ensure", "that", "bytes", "and", "non", "-", "strings", "get", "converted", "into", "str", "objects", "." ]
def ensure_str(value: Union[bytes, Any]) -> str: """ Ensure that bytes and non-strings get converted into ``str`` objects. """ if isinstance(value, bytes): value = value.decode("utf-8") elif not isinstance(value, str): value = str(value) return value
[ "def", "ensure_str", "(", "value", ":", "Union", "[", "bytes", ",", "Any", "]", ")", "->", "str", ":", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "value", "=", "value", ".", "decode", "(", "\"utf-8\"", ")", "elif", "not", "isinstance",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/common.py#L107-L115
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/debug/wrappers/framework.py
python
OnRunStartRequest.__init__
(self, fetches, feed_dict, run_options, run_metadata, run_call_count, is_callable_runner=False)
Constructor of `OnRunStartRequest`. Args: fetches: Fetch targets of the run() call. feed_dict: The feed dictionary to the run() call. run_options: RunOptions input to the run() call. run_metadata: RunMetadata input to the run() call. The above four arguments are identical to the input arguments to the run() method of a non-wrapped TensorFlow session. run_call_count: 1-based count of how many run calls (including this one) has been invoked. is_callable_runner: (bool) whether a runner returned by Session.make_callable is being run.
Constructor of `OnRunStartRequest`.
[ "Constructor", "of", "OnRunStartRequest", "." ]
def __init__(self, fetches, feed_dict, run_options, run_metadata, run_call_count, is_callable_runner=False): """Constructor of `OnRunStartRequest`. Args: fetches: Fetch targets of the run() call. feed_dict: The feed dictionary to the run() call. run_options: RunOptions input to the run() call. run_metadata: RunMetadata input to the run() call. The above four arguments are identical to the input arguments to the run() method of a non-wrapped TensorFlow session. run_call_count: 1-based count of how many run calls (including this one) has been invoked. is_callable_runner: (bool) whether a runner returned by Session.make_callable is being run. """ self.fetches = fetches self.feed_dict = feed_dict self.run_options = run_options self.run_metadata = run_metadata self.run_call_count = run_call_count self.is_callable_runner = is_callable_runner
[ "def", "__init__", "(", "self", ",", "fetches", ",", "feed_dict", ",", "run_options", ",", "run_metadata", ",", "run_call_count", ",", "is_callable_runner", "=", "False", ")", ":", "self", ".", "fetches", "=", "fetches", "self", ".", "feed_dict", "=", "feed_...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/wrappers/framework.py#L195-L216
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ToolBar.__init__
(self, *args, **kwargs)
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxNO_BORDER|wxTB_HORIZONTAL, String name=wxPyToolBarNameStr) -> ToolBar
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxNO_BORDER|wxTB_HORIZONTAL, String name=wxPyToolBarNameStr) -> ToolBar
[ "__init__", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "wxNO_BORDER|wxTB_HORIZONTAL", "String", "name", "=", "wxPyToolBarNameStr", ")", "-", ">"...
def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxNO_BORDER|wxTB_HORIZONTAL, String name=wxPyToolBarNameStr) -> ToolBar """ _controls_.ToolBar_swiginit(self,_controls_.new_ToolBar(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_controls_", ".", "ToolBar_swiginit", "(", "self", ",", "_controls_", ".", "new_ToolBar", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOOR...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L3938-L3945
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/data/transform/vision/functional.py
python
resize
(input, size, interpolation=cv2.INTER_LINEAR)
return cv2.resize(input, size[::-1], interpolation=interpolation)
r"""Resize the input data to given size. Args: input: input data, could be image or masks, with `(H, W, C)` shape. size: target size of input data, with (height, width) shape. interpolation: interpolation method. Returns: resized data, with `(H, W, C)` shape.
r"""Resize the input data to given size.
[ "r", "Resize", "the", "input", "data", "to", "given", "size", "." ]
def resize(input, size, interpolation=cv2.INTER_LINEAR): r"""Resize the input data to given size. Args: input: input data, could be image or masks, with `(H, W, C)` shape. size: target size of input data, with (height, width) shape. interpolation: interpolation method. Returns: resized data, with `(H, W, C)` shape. """ if len(size) != 2: raise ValueError("resize needs (h, w), but got {}".format(size)) if isinstance(interpolation, collections.abc.Sequence): interpolation = random.choice(interpolation) return cv2.resize(input, size[::-1], interpolation=interpolation)
[ "def", "resize", "(", "input", ",", "size", ",", "interpolation", "=", "cv2", ".", "INTER_LINEAR", ")", ":", "if", "len", "(", "size", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"resize needs (h, w), but got {}\"", ".", "format", "(", "size", ")", ...
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/data/transform/vision/functional.py#L106-L122
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
demo/HuggingFace/T5/T5ModelConfig.py
python
T5Metadata.add_args
(parser: argparse.ArgumentParser)
Add commandline interface parser.
Add commandline interface parser.
[ "Add", "commandline", "interface", "parser", "." ]
def add_args(parser: argparse.ArgumentParser) -> None: """Add commandline interface parser.""" network_group = parser.add_argument_group("T5 network") network_group.add_argument( "--variant", help="T5 variant to generate", choices=T5ModelTRTConfig.TARGET_MODELS, required=True, ) network_group.add_argument( "--enable-kv-cache", help="T5 enable KV cache", action="store_true", default=False, )
[ "def", "add_args", "(", "parser", ":", "argparse", ".", "ArgumentParser", ")", "->", "None", ":", "network_group", "=", "parser", ".", "add_argument_group", "(", "\"T5 network\"", ")", "network_group", ".", "add_argument", "(", "\"--variant\"", ",", "help", "=",...
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/demo/HuggingFace/T5/T5ModelConfig.py#L35-L49
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/math_ops.py
python
reduce_sum
(input_tensor, axis=None, keepdims=False, name=None)
return reduce_sum_with_dims(input_tensor, axis, keepdims, name, _ReductionDims(input_tensor, axis))
Computes the sum of elements across dimensions of a tensor. This is the reduction operation for the elementwise `tf.math.add` op. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each of the entries in `axis`, which must be unique. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned. For example: >>> # x has a shape of (2, 3) (two rows and three columns): >>> x = tf.constant([[1, 1, 1], [1, 1, 1]]) >>> x.numpy() array([[1, 1, 1], [1, 1, 1]], dtype=int32) >>> # sum all the elements >>> # 1 + 1 + 1 + 1 + 1+ 1 = 6 >>> tf.reduce_sum(x).numpy() 6 >>> # reduce along the first dimension >>> # the result is [1, 1, 1] + [1, 1, 1] = [2, 2, 2] >>> tf.reduce_sum(x, 0).numpy() array([2, 2, 2], dtype=int32) >>> # reduce along the second dimension >>> # the result is [1, 1] + [1, 1] + [1, 1] = [3, 3] >>> tf.reduce_sum(x, 1).numpy() array([3, 3], dtype=int32) >>> # keep the original dimensions >>> tf.reduce_sum(x, 1, keepdims=True).numpy() array([[3], [3]], dtype=int32) >>> # reduce along both dimensions >>> # the result is 1 + 1 + 1 + 1 + 1 + 1 = 6 >>> # or, equivalently, reduce along rows, then reduce the resultant array >>> # [1, 1, 1] + [1, 1, 1] = [2, 2, 2] >>> # 2 + 2 + 2 = 6 >>> tf.reduce_sum(x, [0, 1]).numpy() 6 Args: input_tensor: The tensor to reduce. Should have numeric type. axis: The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor)]`. keepdims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor, of the same dtype as the input_tensor. @compatibility(numpy) Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to int64 while tensorflow returns the same dtype as the input. @end_compatibility
Computes the sum of elements across dimensions of a tensor.
[ "Computes", "the", "sum", "of", "elements", "across", "dimensions", "of", "a", "tensor", "." ]
def reduce_sum(input_tensor, axis=None, keepdims=False, name=None): """Computes the sum of elements across dimensions of a tensor. This is the reduction operation for the elementwise `tf.math.add` op. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each of the entries in `axis`, which must be unique. If `keepdims` is true, the reduced dimensions are retained with length 1. If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned. For example: >>> # x has a shape of (2, 3) (two rows and three columns): >>> x = tf.constant([[1, 1, 1], [1, 1, 1]]) >>> x.numpy() array([[1, 1, 1], [1, 1, 1]], dtype=int32) >>> # sum all the elements >>> # 1 + 1 + 1 + 1 + 1+ 1 = 6 >>> tf.reduce_sum(x).numpy() 6 >>> # reduce along the first dimension >>> # the result is [1, 1, 1] + [1, 1, 1] = [2, 2, 2] >>> tf.reduce_sum(x, 0).numpy() array([2, 2, 2], dtype=int32) >>> # reduce along the second dimension >>> # the result is [1, 1] + [1, 1] + [1, 1] = [3, 3] >>> tf.reduce_sum(x, 1).numpy() array([3, 3], dtype=int32) >>> # keep the original dimensions >>> tf.reduce_sum(x, 1, keepdims=True).numpy() array([[3], [3]], dtype=int32) >>> # reduce along both dimensions >>> # the result is 1 + 1 + 1 + 1 + 1 + 1 = 6 >>> # or, equivalently, reduce along rows, then reduce the resultant array >>> # [1, 1, 1] + [1, 1, 1] = [2, 2, 2] >>> # 2 + 2 + 2 = 6 >>> tf.reduce_sum(x, [0, 1]).numpy() 6 Args: input_tensor: The tensor to reduce. Should have numeric type. axis: The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor)]`. keepdims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor, of the same dtype as the input_tensor. @compatibility(numpy) Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to int64 while tensorflow returns the same dtype as the input. @end_compatibility """ return reduce_sum_with_dims(input_tensor, axis, keepdims, name, _ReductionDims(input_tensor, axis))
[ "def", "reduce_sum", "(", "input_tensor", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ",", "name", "=", "None", ")", ":", "return", "reduce_sum_with_dims", "(", "input_tensor", ",", "axis", ",", "keepdims", ",", "name", ",", "_ReductionDims", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_ops.py#L2250-L2312
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
TextBoxAttr.Apply
(*args, **kwargs)
return _richtext.TextBoxAttr_Apply(*args, **kwargs)
Apply(self, TextBoxAttr style, TextBoxAttr compareWith=None) -> bool
Apply(self, TextBoxAttr style, TextBoxAttr compareWith=None) -> bool
[ "Apply", "(", "self", "TextBoxAttr", "style", "TextBoxAttr", "compareWith", "=", "None", ")", "-", ">", "bool" ]
def Apply(*args, **kwargs): """Apply(self, TextBoxAttr style, TextBoxAttr compareWith=None) -> bool""" return _richtext.TextBoxAttr_Apply(*args, **kwargs)
[ "def", "Apply", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "TextBoxAttr_Apply", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L544-L546
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/zipfile.py
python
ZipFile.read
(self, name, pwd=None)
return self.open(name, "r", pwd).read()
Return file bytes (as a string) for name.
Return file bytes (as a string) for name.
[ "Return", "file", "bytes", "(", "as", "a", "string", ")", "for", "name", "." ]
def read(self, name, pwd=None): """Return file bytes (as a string) for name.""" return self.open(name, "r", pwd).read()
[ "def", "read", "(", "self", ",", "name", ",", "pwd", "=", "None", ")", ":", "return", "self", ".", "open", "(", "name", ",", "\"r\"", ",", "pwd", ")", ".", "read", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/zipfile.py#L956-L958
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
PyApp.FilterEvent
(*args, **kwargs)
return _core_.PyApp_FilterEvent(*args, **kwargs)
FilterEvent(self, Event event) -> int Filters all events. `SetCallFilterEvent` controls whether or not your override is called.
FilterEvent(self, Event event) -> int
[ "FilterEvent", "(", "self", "Event", "event", ")", "-", ">", "int" ]
def FilterEvent(*args, **kwargs): """ FilterEvent(self, Event event) -> int Filters all events. `SetCallFilterEvent` controls whether or not your override is called. """ return _core_.PyApp_FilterEvent(*args, **kwargs)
[ "def", "FilterEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_FilterEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L7988-L7995
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/network/network.py
python
Edges.get_accesslevel
(self, id_edge, id_mode)
return self.parent.lanes.get_accesslevel(self.ids_lanes[id_edge], id_mode)
Returns access level of mode on edge id_edge: -1 = No access 0 = all modes can access 1 = mode can access with a restricted number of other modes 2 = exclusive access for id_mode
Returns access level of mode on edge id_edge: -1 = No access 0 = all modes can access 1 = mode can access with a restricted number of other modes 2 = exclusive access for id_mode
[ "Returns", "access", "level", "of", "mode", "on", "edge", "id_edge", ":", "-", "1", "=", "No", "access", "0", "=", "all", "modes", "can", "access", "1", "=", "mode", "can", "access", "with", "a", "restricted", "number", "of", "other", "modes", "2", "...
def get_accesslevel(self, id_edge, id_mode): """ Returns access level of mode on edge id_edge: -1 = No access 0 = all modes can access 1 = mode can access with a restricted number of other modes 2 = exclusive access for id_mode """ # print 'get_accesslevel',id_edge,self.ids_sumo[id_edge] return self.parent.lanes.get_accesslevel(self.ids_lanes[id_edge], id_mode)
[ "def", "get_accesslevel", "(", "self", ",", "id_edge", ",", "id_mode", ")", ":", "# print 'get_accesslevel',id_edge,self.ids_sumo[id_edge]", "return", "self", ".", "parent", ".", "lanes", ".", "get_accesslevel", "(", "self", ".", "ids_lanes", "[", "id_edge", "]", ...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/network/network.py#L1903-L1912
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TFlt.__idiv__
(self, *args)
return _snap.TFlt___idiv__(self, *args)
__idiv__(TFlt self, double const & Flt) -> TFlt Parameters: Flt: double const &
__idiv__(TFlt self, double const & Flt) -> TFlt
[ "__idiv__", "(", "TFlt", "self", "double", "const", "&", "Flt", ")", "-", ">", "TFlt" ]
def __idiv__(self, *args): """ __idiv__(TFlt self, double const & Flt) -> TFlt Parameters: Flt: double const & """ return _snap.TFlt___idiv__(self, *args)
[ "def", "__idiv__", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TFlt___idiv__", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L14341-L14349
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
utils/vim-lldb/python-vim-lldb/lldb_controller.py
python
LLDBController.doAttach
(self, process_name)
Handle process attach.
Handle process attach.
[ "Handle", "process", "attach", "." ]
def doAttach(self, process_name): """ Handle process attach. """ error = lldb.SBError() self.processListener = lldb.SBListener("process_event_listener") self.target = self.dbg.CreateTarget('') self.process = self.target.AttachToProcessWithName( self.processListener, process_name, False, error) if not error.Success(): sys.stderr.write("Error during attach: " + str(error)) return self.ui.activate() self.pid = self.process.GetProcessID() print("Attached to %s (pid=%d)" % (process_name, self.pid))
[ "def", "doAttach", "(", "self", ",", "process_name", ")", ":", "error", "=", "lldb", ".", "SBError", "(", ")", "self", ".", "processListener", "=", "lldb", ".", "SBListener", "(", "\"process_event_listener\"", ")", "self", ".", "target", "=", "self", ".", ...
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/vim-lldb/python-vim-lldb/lldb_controller.py#L154-L169
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pyparsing/py3/pyparsing/core.py
python
ParserElement.matches
( self, test_string: str, parse_all: bool = True, *, parseAll: bool = True )
Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser. Parameters: - ``test_string`` - to test against this expression for a match - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests Example:: expr = Word(nums) assert expr.matches("100")
Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser.
[ "Method", "for", "quick", "testing", "of", "a", "parser", "against", "a", "test", "string", ".", "Good", "for", "simple", "inline", "microtests", "of", "sub", "expressions", "while", "building", "up", "larger", "parser", "." ]
def matches( self, test_string: str, parse_all: bool = True, *, parseAll: bool = True ) -> bool: """ Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser. Parameters: - ``test_string`` - to test against this expression for a match - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests Example:: expr = Word(nums) assert expr.matches("100") """ parseAll = parseAll and parse_all try: self.parse_string(str(test_string), parse_all=parseAll) return True except ParseBaseException: return False
[ "def", "matches", "(", "self", ",", "test_string", ":", "str", ",", "parse_all", ":", "bool", "=", "True", ",", "*", ",", "parseAll", ":", "bool", "=", "True", ")", "->", "bool", ":", "parseAll", "=", "parseAll", "and", "parse_all", "try", ":", "self...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py3/pyparsing/core.py#L1920-L1941
facebook/hermes
b1b1a00ab468ec1b397b31b71587110044830970
external/llvh/utils/lit/lit/discovery.py
python
find_tests_for_inputs
(lit_config, inputs)
return tests
find_tests_for_inputs(lit_config, inputs) -> [Test] Given a configuration object and a list of input specifiers, find all the tests to execute.
find_tests_for_inputs(lit_config, inputs) -> [Test]
[ "find_tests_for_inputs", "(", "lit_config", "inputs", ")", "-", ">", "[", "Test", "]" ]
def find_tests_for_inputs(lit_config, inputs): """ find_tests_for_inputs(lit_config, inputs) -> [Test] Given a configuration object and a list of input specifiers, find all the tests to execute. """ # Expand '@...' form in inputs. actual_inputs = [] for input in inputs: if input.startswith('@'): f = open(input[1:]) try: for ln in f: ln = ln.strip() if ln: actual_inputs.append(ln) finally: f.close() else: actual_inputs.append(input) # Load the tests from the inputs. tests = [] test_suite_cache = {} local_config_cache = {} for input in actual_inputs: prev = len(tests) tests.extend(getTests(input, lit_config, test_suite_cache, local_config_cache)[1]) if prev == len(tests): lit_config.warning('input %r contained no tests' % input) # If there were any errors during test discovery, exit now. if lit_config.numErrors: sys.stderr.write('%d errors, exiting.\n' % lit_config.numErrors) sys.exit(2) return tests
[ "def", "find_tests_for_inputs", "(", "lit_config", ",", "inputs", ")", ":", "# Expand '@...' form in inputs.", "actual_inputs", "=", "[", "]", "for", "input", "in", "inputs", ":", "if", "input", ".", "startswith", "(", "'@'", ")", ":", "f", "=", "open", "(",...
https://github.com/facebook/hermes/blob/b1b1a00ab468ec1b397b31b71587110044830970/external/llvh/utils/lit/lit/discovery.py#L212-L251
vesoft-inc/nebula
25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35
.linters/cpp/cpplint.py
python
_SetVerboseLevel
(level)
return _cpplint_state.SetVerboseLevel(level)
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level)
[ "def", "_SetVerboseLevel", "(", "level", ")", ":", "return", "_cpplint_state", ".", "SetVerboseLevel", "(", "level", ")" ]
https://github.com/vesoft-inc/nebula/blob/25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35/.linters/cpp/cpplint.py#L1194-L1196
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
urllib3/fields.py
python
format_header_param
(name, value)
return value
Helper function to format and quote a single header parameter. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows RFC 2231, as suggested by RFC 2388 Section 4.4. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string.
Helper function to format and quote a single header parameter.
[ "Helper", "function", "to", "format", "and", "quote", "a", "single", "header", "parameter", "." ]
def format_header_param(name, value): """ Helper function to format and quote a single header parameter. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows RFC 2231, as suggested by RFC 2388 Section 4.4. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. """ if not any(ch in value for ch in '"\\\r\n'): result = '%s="%s"' % (name, value) try: result.encode('ascii') except UnicodeEncodeError: pass else: return result if not six.PY3: # Python 2: value = value.encode('utf-8') value = email.utils.encode_rfc2231(value, 'utf-8') value = '%s*=%s' % (name, value) return value
[ "def", "format_header_param", "(", "name", ",", "value", ")", ":", "if", "not", "any", "(", "ch", "in", "value", "for", "ch", "in", "'\"\\\\\\r\\n'", ")", ":", "result", "=", "'%s=\"%s\"'", "%", "(", "name", ",", "value", ")", "try", ":", "result", "...
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/urllib3/fields.py#L27-L52
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Alignment/OfflineValidation/scripts/submitPVResolutionJobs.py
python
getFilesForRun
(blob)
return outputList
returns the list of list files associated with a given dataset for a certain run
returns the list of list files associated with a given dataset for a certain run
[ "returns", "the", "list", "of", "list", "files", "associated", "with", "a", "given", "dataset", "for", "a", "certain", "run" ]
def getFilesForRun(blob): ############################################## """ returns the list of list files associated with a given dataset for a certain run """ cmd2 = ' dasgoclient -limit=0 -query \'file run='+blob[0]+' dataset='+blob[1]+'\'' q = Popen(cmd2 , shell=True, stdout=PIPE, stderr=PIPE) out, err = q.communicate() outputList = out.decode().split('\n') outputList.pop() return outputList
[ "def", "getFilesForRun", "(", "blob", ")", ":", "##############################################", "cmd2", "=", "' dasgoclient -limit=0 -query \\'file run='", "+", "blob", "[", "0", "]", "+", "' dataset='", "+", "blob", "[", "1", "]", "+", "'\\''", "q", "=", "Popen...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/OfflineValidation/scripts/submitPVResolutionJobs.py#L77-L88
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/input.py
python
DependencyGraphNode.DeepDependencies
(self, dependencies=None)
return dependencies
Returns an OrderedSet of all of a target's dependencies, recursively.
Returns an OrderedSet of all of a target's dependencies, recursively.
[ "Returns", "an", "OrderedSet", "of", "all", "of", "a", "target", "s", "dependencies", "recursively", "." ]
def DeepDependencies(self, dependencies=None): """Returns an OrderedSet of all of a target's dependencies, recursively.""" if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref is None: continue if dependency.ref not in dependencies: dependency.DeepDependencies(dependencies) dependencies.add(dependency.ref) return dependencies
[ "def", "DeepDependencies", "(", "self", ",", "dependencies", "=", "None", ")", ":", "if", "dependencies", "is", "None", ":", "# Using a list to get ordered output and a set to do fast \"is it", "# already added\" checks.", "dependencies", "=", "OrderedSet", "(", ")", "for...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/input.py#L1678-L1693
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/protobuf/python/google/protobuf/internal/encoder.py
python
_ModifiedSizer
(compute_value_size, modify_value)
return SpecificSizer
Like SimpleSizer, but modify_value is invoked on each value before it is passed to compute_value_size. modify_value is typically ZigZagEncode.
Like SimpleSizer, but modify_value is invoked on each value before it is passed to compute_value_size. modify_value is typically ZigZagEncode.
[ "Like", "SimpleSizer", "but", "modify_value", "is", "invoked", "on", "each", "value", "before", "it", "is", "passed", "to", "compute_value_size", ".", "modify_value", "is", "typically", "ZigZagEncode", "." ]
def _ModifiedSizer(compute_value_size, modify_value): """Like SimpleSizer, but modify_value is invoked on each value before it is passed to compute_value_size. modify_value is typically ZigZagEncode.""" def SpecificSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) if is_packed: local_VarintSize = _VarintSize def PackedFieldSize(value): result = 0 for element in value: result += compute_value_size(modify_value(element)) return result + local_VarintSize(result) + tag_size return PackedFieldSize elif is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: result += compute_value_size(modify_value(element)) return result return RepeatedFieldSize else: def FieldSize(value): return tag_size + compute_value_size(modify_value(value)) return FieldSize return SpecificSizer
[ "def", "_ModifiedSizer", "(", "compute_value_size", ",", "modify_value", ")", ":", "def", "SpecificSizer", "(", "field_number", ",", "is_repeated", ",", "is_packed", ")", ":", "tag_size", "=", "_TagSize", "(", "field_number", ")", "if", "is_packed", ":", "local_...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/google/protobuf/internal/encoder.py#L152-L178
llvm-mirror/libcxx
78d6a7767ed57b50122a161b91f59f19c9bd0d19
utils/merge_archives.py
python
execute_command
(cmd, cwd=None)
return out, err, exitCode
Execute a command, capture and return its output.
Execute a command, capture and return its output.
[ "Execute", "a", "command", "capture", "and", "return", "its", "output", "." ]
def execute_command(cmd, cwd=None): """ Execute a command, capture and return its output. """ kwargs = { 'stdin': subprocess.PIPE, 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, 'cwd': cwd, 'universal_newlines': True } p = subprocess.Popen(cmd, **kwargs) out, err = p.communicate() exitCode = p.wait() if exitCode == -signal.SIGINT: raise KeyboardInterrupt return out, err, exitCode
[ "def", "execute_command", "(", "cmd", ",", "cwd", "=", "None", ")", ":", "kwargs", "=", "{", "'stdin'", ":", "subprocess", ".", "PIPE", ",", "'stdout'", ":", "subprocess", ".", "PIPE", ",", "'stderr'", ":", "subprocess", ".", "PIPE", ",", "'cwd'", ":",...
https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/utils/merge_archives.py#L45-L61
crystax/android-platform-ndk
d86e23c826179a1c46b0576d42501ed234bf1a50
sources/host-tools/gdb-pretty-printers/stlport/gppfs-0.2/stlport/printers.py
python
lookup_stlport_priv_type
(typename)
Look up a type in the private STLport namespace.
Look up a type in the private STLport namespace.
[ "Look", "up", "a", "type", "in", "the", "private", "STLport", "namespace", "." ]
def lookup_stlport_priv_type (typename): "Look up a type in the private STLport namespace." namespaces = ['std::priv::', 'stlpd_std::priv::', 'stlp_priv::', 'stlp_std::priv::', 'stlpd_std::', 'stlp_std::', '_STL::'] for namespace in namespaces: try: return gdb.lookup_type (namespace + typename) except RuntimeError: pass
[ "def", "lookup_stlport_priv_type", "(", "typename", ")", ":", "namespaces", "=", "[", "'std::priv::'", ",", "'stlpd_std::priv::'", ",", "'stlp_priv::'", ",", "'stlp_std::priv::'", ",", "'stlpd_std::'", ",", "'stlp_std::'", ",", "'_STL::'", "]", "for", "namespace", "...
https://github.com/crystax/android-platform-ndk/blob/d86e23c826179a1c46b0576d42501ed234bf1a50/sources/host-tools/gdb-pretty-printers/stlport/gppfs-0.2/stlport/printers.py#L49-L58
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
TextEntryBase.GetSelection
(*args, **kwargs)
return _core_.TextEntryBase_GetSelection(*args, **kwargs)
GetSelection() -> (from, to) If the return values from and to are the same, there is no selection.
GetSelection() -> (from, to)
[ "GetSelection", "()", "-", ">", "(", "from", "to", ")" ]
def GetSelection(*args, **kwargs): """ GetSelection() -> (from, to) If the return values from and to are the same, there is no selection. """ return _core_.TextEntryBase_GetSelection(*args, **kwargs)
[ "def", "GetSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "TextEntryBase_GetSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13307-L13313
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/layers/python/layers/utils.py
python
two_element_tuple
(int_or_tuple)
Converts `int_or_tuple` to height, width. Several of the functions that follow accept arguments as either a tuple of 2 integers or a single integer. A single integer indicates that the 2 values of the tuple are the same. This functions normalizes the input value by always returning a tuple. Args: int_or_tuple: A list of 2 ints, a single int or a `TensorShape`. Returns: A tuple with 2 values. Raises: ValueError: If `int_or_tuple` it not well formed.
Converts `int_or_tuple` to height, width.
[ "Converts", "int_or_tuple", "to", "height", "width", "." ]
def two_element_tuple(int_or_tuple): """Converts `int_or_tuple` to height, width. Several of the functions that follow accept arguments as either a tuple of 2 integers or a single integer. A single integer indicates that the 2 values of the tuple are the same. This functions normalizes the input value by always returning a tuple. Args: int_or_tuple: A list of 2 ints, a single int or a `TensorShape`. Returns: A tuple with 2 values. Raises: ValueError: If `int_or_tuple` it not well formed. """ if isinstance(int_or_tuple, (list, tuple)): if len(int_or_tuple) != 2: raise ValueError('Must be a list with 2 elements: %s' % int_or_tuple) return int(int_or_tuple[0]), int(int_or_tuple[1]) if isinstance(int_or_tuple, int): return int(int_or_tuple), int(int_or_tuple) if isinstance(int_or_tuple, tensor_shape.TensorShape): if len(int_or_tuple) == 2: return int_or_tuple[0], int_or_tuple[1] raise ValueError('Must be an int, a list with 2 elements or a TensorShape of ' 'length 2')
[ "def", "two_element_tuple", "(", "int_or_tuple", ")", ":", "if", "isinstance", "(", "int_or_tuple", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "len", "(", "int_or_tuple", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Must be a list with 2 elem...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/layers/python/layers/utils.py#L251-L279
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetVSMacroEnv
(self, base_to_build=None, config=None)
return replacements
Get a dict of variables mapping internal VS macro names to their gyp equivalents.
Get a dict of variables mapping internal VS macro names to their gyp equivalents.
[ "Get", "a", "dict", "of", "variables", "mapping", "internal", "VS", "macro", "names", "to", "their", "gyp", "equivalents", "." ]
def GetVSMacroEnv(self, base_to_build=None, config=None): """Get a dict of variables mapping internal VS macro names to their gyp equivalents.""" target_platform = self.GetTargetPlatform(config) target_platform = {'x86': 'Win32'}.get(target_platform, target_platform) replacements = { '$(VSInstallDir)': self.vs_version.Path(), '$(VCInstallDir)': os.path.join(self.vs_version.Path(), 'VC') + '\\', '$(OutDir)\\': base_to_build + '\\' if base_to_build else '', '$(IntDir)': '$!INTERMEDIATE_DIR', '$(InputPath)': '${source}', '$(InputName)': '${root}', '$(ProjectName)': self.spec['target_name'], '$(PlatformName)': target_platform, '$(ProjectDir)\\': '', } # Chromium uses DXSDK_DIR in include/lib paths, but it may or may not be # set. This happens when the SDK is sync'd via src-internal, rather than # by typical end-user installation of the SDK. If it's not set, we don't # want to leave the unexpanded variable in the path, so simply strip it. replacements['$(DXSDK_DIR)'] = self.dxsdk_dir if self.dxsdk_dir else '' replacements['$(WDK_DIR)'] = self.wdk_dir if self.wdk_dir else '' return replacements
[ "def", "GetVSMacroEnv", "(", "self", ",", "base_to_build", "=", "None", ",", "config", "=", "None", ")", ":", "target_platform", "=", "self", ".", "GetTargetPlatform", "(", "config", ")", "target_platform", "=", "{", "'x86'", ":", "'Win32'", "}", ".", "get...
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/msvs_emulation.py#L165-L187
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/ndimage/interpolation.py
python
geometric_transform
(input, mapping, output_shape=None, output=None, order=3, mode='constant', cval=0.0, prefilter=True, extra_arguments=(), extra_keywords={})
return return_value
Apply an arbritrary geometric transform. The given mapping function is used to find, for each point in the output, the corresponding coordinates in the input. The value of the input at those coordinates is determined by spline interpolation of the requested order. Parameters ---------- input : array_like The input array. mapping : callable A callable object that accepts a tuple of length equal to the output array rank, and returns the corresponding input coordinates as a tuple of length equal to the input array rank. output_shape : tuple of ints, optional Shape tuple. output : ndarray or dtype, optional The array in which to place the output, or the dtype of the returned array. order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5. mode : str, optional Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default is 'constant'. cval : scalar, optional Value used for points outside the boundaries of the input if ``mode='constant'``. Default is 0.0 prefilter : bool, optional The parameter prefilter determines if the input is pre-filtered with `spline_filter` before interpolation (necessary for spline interpolation of order > 1). If False, it is assumed that the input is already filtered. Default is True. extra_arguments : tuple, optional Extra arguments passed to `mapping`. extra_keywords : dict, optional Extra keywords passed to `mapping`. Returns ------- return_value : ndarray or None The filtered input. If `output` is given as a parameter, None is returned. See Also -------- map_coordinates, affine_transform, spline_filter1d Examples -------- >>> from scipy import ndimage >>> a = np.arange(12.).reshape((4, 3)) >>> def shift_func(output_coords): ... return (output_coords[0] - 0.5, output_coords[1] - 0.5) ... >>> ndimage.geometric_transform(a, shift_func) array([[ 0. , 0. , 0. ], [ 0. , 1.362, 2.738], [ 0. , 4.812, 6.187], [ 0. , 8.263, 9.637]])
Apply an arbritrary geometric transform.
[ "Apply", "an", "arbritrary", "geometric", "transform", "." ]
def geometric_transform(input, mapping, output_shape=None, output=None, order=3, mode='constant', cval=0.0, prefilter=True, extra_arguments=(), extra_keywords={}): """ Apply an arbritrary geometric transform. The given mapping function is used to find, for each point in the output, the corresponding coordinates in the input. The value of the input at those coordinates is determined by spline interpolation of the requested order. Parameters ---------- input : array_like The input array. mapping : callable A callable object that accepts a tuple of length equal to the output array rank, and returns the corresponding input coordinates as a tuple of length equal to the input array rank. output_shape : tuple of ints, optional Shape tuple. output : ndarray or dtype, optional The array in which to place the output, or the dtype of the returned array. order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5. mode : str, optional Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default is 'constant'. cval : scalar, optional Value used for points outside the boundaries of the input if ``mode='constant'``. Default is 0.0 prefilter : bool, optional The parameter prefilter determines if the input is pre-filtered with `spline_filter` before interpolation (necessary for spline interpolation of order > 1). If False, it is assumed that the input is already filtered. Default is True. extra_arguments : tuple, optional Extra arguments passed to `mapping`. extra_keywords : dict, optional Extra keywords passed to `mapping`. Returns ------- return_value : ndarray or None The filtered input. If `output` is given as a parameter, None is returned. See Also -------- map_coordinates, affine_transform, spline_filter1d Examples -------- >>> from scipy import ndimage >>> a = np.arange(12.).reshape((4, 3)) >>> def shift_func(output_coords): ... return (output_coords[0] - 0.5, output_coords[1] - 0.5) ... >>> ndimage.geometric_transform(a, shift_func) array([[ 0. , 0. , 0. ], [ 0. , 1.362, 2.738], [ 0. , 4.812, 6.187], [ 0. , 8.263, 9.637]]) """ if order < 0 or order > 5: raise RuntimeError('spline order not supported') input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') if output_shape is None: output_shape = input.shape if input.ndim < 1 or len(output_shape) < 1: raise RuntimeError('input and output rank must be > 0') mode = _extend_mode_to_code(mode) if prefilter and order > 1: filtered = spline_filter(input, order, output=numpy.float64) else: filtered = input output, return_value = _ni_support._get_output(output, input, shape=output_shape) _geometric_transform(filtered, mapping, None, None, None, output, order, mode, cval, extra_arguments, extra_keywords) return return_value
[ "def", "geometric_transform", "(", "input", ",", "mapping", ",", "output_shape", "=", "None", ",", "output", "=", "None", ",", "order", "=", "3", ",", "mode", "=", "'constant'", ",", "cval", "=", "0.0", ",", "prefilter", "=", "True", ",", "extra_argument...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/ndimage/interpolation.py#L140-L227
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
PseudoDC.DrawIcon
(*args, **kwargs)
return _gdi_.PseudoDC_DrawIcon(*args, **kwargs)
DrawIcon(self, Icon icon, int x, int y) Draw an icon on the display (does nothing if the device context is PostScript). This can be the simplest way of drawing bitmaps on a window.
DrawIcon(self, Icon icon, int x, int y)
[ "DrawIcon", "(", "self", "Icon", "icon", "int", "x", "int", "y", ")" ]
def DrawIcon(*args, **kwargs): """ DrawIcon(self, Icon icon, int x, int y) Draw an icon on the display (does nothing if the device context is PostScript). This can be the simplest way of drawing bitmaps on a window. """ return _gdi_.PseudoDC_DrawIcon(*args, **kwargs)
[ "def", "DrawIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_DrawIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L8043-L8051
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/text_format.py
python
PrintFieldValue
(field, value, out, indent=0, as_utf8=False, as_one_line=False, use_short_repeated_primitives=False, pointy_brackets=False, use_index_order=False, float_format=None, double_format=None, message_formatter=None, print_unknown_fields=False, force_colon=False)
Print a single field value (not including name).
Print a single field value (not including name).
[ "Print", "a", "single", "field", "value", "(", "not", "including", "name", ")", "." ]
def PrintFieldValue(field, value, out, indent=0, as_utf8=False, as_one_line=False, use_short_repeated_primitives=False, pointy_brackets=False, use_index_order=False, float_format=None, double_format=None, message_formatter=None, print_unknown_fields=False, force_colon=False): """Print a single field value (not including name).""" printer = _Printer(out, indent, as_utf8, as_one_line, use_short_repeated_primitives, pointy_brackets, use_index_order, float_format, double_format, message_formatter=message_formatter, print_unknown_fields=print_unknown_fields, force_colon=force_colon) printer.PrintFieldValue(field, value)
[ "def", "PrintFieldValue", "(", "field", ",", "value", ",", "out", ",", "indent", "=", "0", ",", "as_utf8", "=", "False", ",", "as_one_line", "=", "False", ",", "use_short_repeated_primitives", "=", "False", ",", "pointy_brackets", "=", "False", ",", "use_ind...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/text_format.py#L276-L297
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/fife_settings.py
python
Setting.setAvailableScreenResolutions
(self, reslist)
A list of valid default screen resolutions. This should be called once right after you instantiate Settings. Valid screen resolutions must be strings in the form of: WIDTHxHEIGHT Example: settings.setAvailableScreenResolutions(["800x600", "1024x768"])
A list of valid default screen resolutions. This should be called once right after you instantiate Settings.
[ "A", "list", "of", "valid", "default", "screen", "resolutions", ".", "This", "should", "be", "called", "once", "right", "after", "you", "instantiate", "Settings", "." ]
def setAvailableScreenResolutions(self, reslist): """ A list of valid default screen resolutions. This should be called once right after you instantiate Settings. Valid screen resolutions must be strings in the form of: WIDTHxHEIGHT Example: settings.setAvailableScreenResolutions(["800x600", "1024x768"]) """ self._resolutions = reslist
[ "def", "setAvailableScreenResolutions", "(", "self", ",", "reslist", ")", ":", "self", ".", "_resolutions", "=", "reslist" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/fife_settings.py#L498-L508
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/models.py
python
PreparedRequest.prepare_body
(self, data, files, json=None)
Prepares the given HTTP body data.
Prepares the given HTTP body data.
[ "Prepares", "the", "given", "HTTP", "body", "data", "." ]
def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: # urllib3 requires a bytes-like body. Python 2's json.dumps # provides this natively, but Python 3 gives a Unicode string. content_type = 'application/json' body = complexjson.dumps(json) if not isinstance(body, bytes): body = body.encode('utf-8') is_stream = all([ hasattr(data, '__iter__'), not isinstance(data, (basestring, list, tuple, Mapping)) ]) if is_stream: try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None body = data if getattr(body, 'tell', None) is not None: # Record the current file position before reading. # This will allow us to rewind a file in the event # of a redirect. try: self._body_position = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body self._body_position = object() if files: raise NotImplementedError('Streamed bodies and files are mutually exclusive.') if length: self.headers['Content-Length'] = builtin_str(length) else: self.headers['Transfer-Encoding'] = 'chunked' else: # Multi-part file uploads. if files: (body, content_type) = self._encode_files(files, data) else: if data: body = self._encode_params(data) if isinstance(data, basestring) or hasattr(data, 'read'): content_type = None else: content_type = 'application/x-www-form-urlencoded' self.prepare_content_length(body) # Add content-type if it wasn't explicitly provided. if content_type and ('content-type' not in self.headers): self.headers['Content-Type'] = content_type self.body = body
[ "def", "prepare_body", "(", "self", ",", "data", ",", "files", ",", "json", "=", "None", ")", ":", "# Check if file, fo, generator, iterator.", "# If not, run through normal process.", "# Nottin' on you.", "body", "=", "None", "content_type", "=", "None", "if", "not",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/models.py#L909-L1043
mickem/nscp
79f89fdbb6da63f91bc9dedb7aea202fe938f237
scripts/python/lib/google/protobuf/internal/python_message.py
python
_AddMergeFromStringMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddMergeFromStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def MergeFromString(self, serialized): length = len(serialized) try: if self._InternalParse(serialized, 0, length) != length: # The only reason _InternalParse would return early is if it # encountered an end-group tag. raise message_mod.DecodeError('Unexpected end-group tag.') except IndexError: raise message_mod.DecodeError('Truncated message.') except struct.error, e: raise message_mod.DecodeError(e) return length # Return this for legacy reasons. cls.MergeFromString = MergeFromString local_ReadTag = decoder.ReadTag local_SkipField = decoder.SkipField decoders_by_tag = cls._decoders_by_tag def InternalParse(self, buffer, pos, end): self._Modified() field_dict = self._fields while pos != end: (tag_bytes, new_pos) = local_ReadTag(buffer, pos) field_decoder = decoders_by_tag.get(tag_bytes) if field_decoder is None: new_pos = local_SkipField(buffer, new_pos, end, tag_bytes) if new_pos == -1: return pos pos = new_pos else: pos = field_decoder(buffer, new_pos, end, self, field_dict) return pos cls._InternalParse = InternalParse
[ "def", "_AddMergeFromStringMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "MergeFromString", "(", "self", ",", "serialized", ")", ":", "length", "=", "len", "(", "serialized", ")", "try", ":", "if", "self", ".", "_InternalParse", "(", "seri...
https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/internal/python_message.py#L750-L784
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/wheel.py
python
format_command
( command_args, # type: List[str] command_output, # type: str )
return text
Format command information for logging.
Format command information for logging.
[ "Format", "command", "information", "for", "logging", "." ]
def format_command( command_args, # type: List[str] command_output, # type: str ): # type: (...) -> str """ Format command information for logging. """ text = 'Command arguments: {}\n'.format(command_args) if not command_output: text += 'Command output: None' elif logger.getEffectiveLevel() > logging.DEBUG: text += 'Command output: [use --verbose to show]' else: if not command_output.endswith('\n'): command_output += '\n' text += ( 'Command output:\n{}' '-----------------------------------------' ).format(command_output) return text
[ "def", "format_command", "(", "command_args", ",", "# type: List[str]", "command_output", ",", "# type: str", ")", ":", "# type: (...) -> str", "text", "=", "'Command arguments: {}\\n'", ".", "format", "(", "command_args", ")", "if", "not", "command_output", ":", "tex...
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/_internal/wheel.py#L789-L811
eomahony/Numberjack
53fa9e994a36f881ffd320d8d04158097190aad8
Numberjack/__init__.py
python
NBJ_STD_Solver.getNumVariables
(self)
return self.solver.getNumVariables()
Get the number of variables that have been created in the underlying solver. This figure can be different to the number of variables that you created in your model. For SAT and MIP solvers, this figure will be the number of Boolean variables which had to be created during the encoding step, including any auxiliary variables.
Get the number of variables that have been created in the underlying solver. This figure can be different to the number of variables that you created in your model. For SAT and MIP solvers, this figure will be the number of Boolean variables which had to be created during the encoding step, including any auxiliary variables.
[ "Get", "the", "number", "of", "variables", "that", "have", "been", "created", "in", "the", "underlying", "solver", ".", "This", "figure", "can", "be", "different", "to", "the", "number", "of", "variables", "that", "you", "created", "in", "your", "model", "...
def getNumVariables(self): """ Get the number of variables that have been created in the underlying solver. This figure can be different to the number of variables that you created in your model. For SAT and MIP solvers, this figure will be the number of Boolean variables which had to be created during the encoding step, including any auxiliary variables. """ return self.solver.getNumVariables()
[ "def", "getNumVariables", "(", "self", ")", ":", "return", "self", ".", "solver", ".", "getNumVariables", "(", ")" ]
https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/__init__.py#L3813-L3821
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/datetime.py
python
timedelta.seconds
(self)
return self._seconds
seconds
seconds
[ "seconds" ]
def seconds(self): """seconds""" return self._seconds
[ "def", "seconds", "(", "self", ")", ":", "return", "self", ".", "_seconds" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/datetime.py#L612-L614
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/frame.py
python
Frame.size
(self)
return self._num_columns * self._num_rows
Return the number of elements in the underlying data. Returns ------- size : Size of the DataFrame / Index / Series / MultiIndex Examples -------- Size of an empty dataframe is 0. >>> import cudf >>> df = cudf.DataFrame() >>> df Empty DataFrame Columns: [] Index: [] >>> df.size 0 >>> df = cudf.DataFrame(index=[1, 2, 3]) >>> df Empty DataFrame Columns: [] Index: [1, 2, 3] >>> df.size 0 DataFrame with values >>> df = cudf.DataFrame({'a': [10, 11, 12], ... 'b': ['hello', 'rapids', 'ai']}) >>> df a b 0 10 hello 1 11 rapids 2 12 ai >>> df.size 6 >>> df.index RangeIndex(start=0, stop=3) >>> df.index.size 3 Size of an Index >>> index = cudf.Index([]) >>> index Float64Index([], dtype='float64') >>> index.size 0 >>> index = cudf.Index([1, 2, 3, 10]) >>> index Int64Index([1, 2, 3, 10], dtype='int64') >>> index.size 4 Size of a MultiIndex >>> midx = cudf.MultiIndex( ... levels=[["a", "b", "c", None], ["1", None, "5"]], ... codes=[[0, 0, 1, 2, 3], [0, 2, 1, 1, 0]], ... names=["x", "y"], ... ) >>> midx MultiIndex([( 'a', '1'), ( 'a', '5'), ( 'b', <NA>), ( 'c', <NA>), (<NA>, '1')], names=['x', 'y']) >>> midx.size 5
Return the number of elements in the underlying data.
[ "Return", "the", "number", "of", "elements", "in", "the", "underlying", "data", "." ]
def size(self): """ Return the number of elements in the underlying data. Returns ------- size : Size of the DataFrame / Index / Series / MultiIndex Examples -------- Size of an empty dataframe is 0. >>> import cudf >>> df = cudf.DataFrame() >>> df Empty DataFrame Columns: [] Index: [] >>> df.size 0 >>> df = cudf.DataFrame(index=[1, 2, 3]) >>> df Empty DataFrame Columns: [] Index: [1, 2, 3] >>> df.size 0 DataFrame with values >>> df = cudf.DataFrame({'a': [10, 11, 12], ... 'b': ['hello', 'rapids', 'ai']}) >>> df a b 0 10 hello 1 11 rapids 2 12 ai >>> df.size 6 >>> df.index RangeIndex(start=0, stop=3) >>> df.index.size 3 Size of an Index >>> index = cudf.Index([]) >>> index Float64Index([], dtype='float64') >>> index.size 0 >>> index = cudf.Index([1, 2, 3, 10]) >>> index Int64Index([1, 2, 3, 10], dtype='int64') >>> index.size 4 Size of a MultiIndex >>> midx = cudf.MultiIndex( ... levels=[["a", "b", "c", None], ["1", None, "5"]], ... codes=[[0, 0, 1, 2, 3], [0, 2, 1, 1, 0]], ... names=["x", "y"], ... ) >>> midx MultiIndex([( 'a', '1'), ( 'a', '5'), ( 'b', <NA>), ( 'c', <NA>), (<NA>, '1')], names=['x', 'y']) >>> midx.size 5 """ return self._num_columns * self._num_rows
[ "def", "size", "(", "self", ")", ":", "return", "self", ".", "_num_columns", "*", "self", ".", "_num_rows" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/frame.py#L198-L272
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/Execute/ExecuteTabPlugin.py
python
ExecuteTabPlugin.closing
(self)
Gets called when the user tries to quit. Make sure things are saved before quitting.
Gets called when the user tries to quit.
[ "Gets", "called", "when", "the", "user", "tries", "to", "quit", "." ]
def closing(self): """ Gets called when the user tries to quit. Make sure things are saved before quitting. """ self.ExecuteRunnerPlugin.closing()
[ "def", "closing", "(", "self", ")", ":", "self", ".", "ExecuteRunnerPlugin", ".", "closing", "(", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Execute/ExecuteTabPlugin.py#L131-L137
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/urllib3/connectionpool.py
python
HTTPSConnectionPool._prepare_proxy
(self, conn)
Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy's IP:port.
Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy's IP:port.
[ "Establish", "tunnel", "connection", "early", "because", "otherwise", "httplib", "would", "improperly", "set", "Host", ":", "header", "to", "proxy", "s", "IP", ":", "port", "." ]
def _prepare_proxy(self, conn): """ Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy's IP:port. """ conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers) conn.connect()
[ "def", "_prepare_proxy", "(", "self", ",", "conn", ")", ":", "conn", ".", "set_tunnel", "(", "self", ".", "_proxy_host", ",", "self", ".", "port", ",", "self", ".", "proxy_headers", ")", "conn", ".", "connect", "(", ")" ]
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/urllib3/connectionpool.py#L799-L805
TkTech/pysimdjson
908a8499fe1333a2b3d2b1fd5249ab22edca249e
scripts/coverage.py
python
Plugin._read_source_lines
(self, c_file, sourcefile)
return self._c_files_map[sourcefile][1:]
Parse a Cython generated C/C++ source file and find the executable lines. Each executable line starts with a comment header that states source file and line number, as well as the surrounding range of source code lines.
Parse a Cython generated C/C++ source file and find the executable lines. Each executable line starts with a comment header that states source file and line number, as well as the surrounding range of source code lines.
[ "Parse", "a", "Cython", "generated", "C", "/", "C", "++", "source", "file", "and", "find", "the", "executable", "lines", ".", "Each", "executable", "line", "starts", "with", "a", "comment", "header", "that", "states", "source", "file", "and", "line", "numb...
def _read_source_lines(self, c_file, sourcefile): """ Parse a Cython generated C/C++ source file and find the executable lines. Each executable line starts with a comment header that states source file and line number, as well as the surrounding range of source code lines. """ if self._parsed_c_files is None: self._parsed_c_files = {} if c_file in self._parsed_c_files: code_lines = self._parsed_c_files[c_file] else: code_lines = self._parse_cfile_lines(c_file) self._parsed_c_files[c_file] = code_lines if self._c_files_map is None: self._c_files_map = {} for filename, code in code_lines.items(): abs_path = _find_dep_file_path(c_file, filename, relative_path_search=True) self._c_files_map[abs_path] = (c_file, filename, code) if sourcefile not in self._c_files_map: return (None,) * 2 # e.g. shared library file return self._c_files_map[sourcefile][1:]
[ "def", "_read_source_lines", "(", "self", ",", "c_file", ",", "sourcefile", ")", ":", "if", "self", ".", "_parsed_c_files", "is", "None", ":", "self", ".", "_parsed_c_files", "=", "{", "}", "if", "c_file", "in", "self", ".", "_parsed_c_files", ":", "code_l...
https://github.com/TkTech/pysimdjson/blob/908a8499fe1333a2b3d2b1fd5249ab22edca249e/scripts/coverage.py#L358-L383
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
native_client_sdk/src/build_tools/build_utils.py
python
BotAnnotator.Print
(self, message)
Display a message to the output stream and flush so the bots see it
Display a message to the output stream and flush so the bots see it
[ "Display", "a", "message", "to", "the", "output", "stream", "and", "flush", "so", "the", "bots", "see", "it" ]
def Print(self, message): '''Display a message to the output stream and flush so the bots see it''' self._stream.write("%s\n" % message) self._stream.flush()
[ "def", "Print", "(", "self", ",", "message", ")", ":", "self", ".", "_stream", ".", "write", "(", "\"%s\\n\"", "%", "message", ")", "self", ".", "_stream", ".", "flush", "(", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/build_utils.py#L226-L229
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_multientryexit.py
python
MultiEntryExitDomain.getLastIntervalMeanHaltsPerVehicle
(self, detID)
return self._getUniversal(tc.VAR_LAST_INTERVAL_MEAN_HALTING_NUMBER, detID)
getLastIntervalMeanHaltsPerVehicle(string) -> double Returns the average number of halts of vehicles that passed the detector in the previous measurement interval
getLastIntervalMeanHaltsPerVehicle(string) -> double
[ "getLastIntervalMeanHaltsPerVehicle", "(", "string", ")", "-", ">", "double" ]
def getLastIntervalMeanHaltsPerVehicle(self, detID): """getLastIntervalMeanHaltsPerVehicle(string) -> double Returns the average number of halts of vehicles that passed the detector in the previous measurement interval """ return self._getUniversal(tc.VAR_LAST_INTERVAL_MEAN_HALTING_NUMBER, detID)
[ "def", "getLastIntervalMeanHaltsPerVehicle", "(", "self", ",", "detID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_LAST_INTERVAL_MEAN_HALTING_NUMBER", ",", "detID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_multientryexit.py#L71-L77
3drobotics/ardupilot-solo
05a123b002c11dccc905d4d7703a38e5f36ee723
mk/PX4/Tools/genmsg/src/genmsg/msg_loader.py
python
load_msg_from_string
(msg_context, text, full_name)
return spec
Load message specification from a string. NOTE: this will register the message in the *msg_context*. :param msg_context: :class:`MsgContext` for finding loaded dependencies :param text: .msg text , ``str`` :returns: :class:`MsgSpec` specification :raises: :exc:`InvalidMsgSpec` If syntax errors or other problems are detected in file
Load message specification from a string.
[ "Load", "message", "specification", "from", "a", "string", "." ]
def load_msg_from_string(msg_context, text, full_name): """ Load message specification from a string. NOTE: this will register the message in the *msg_context*. :param msg_context: :class:`MsgContext` for finding loaded dependencies :param text: .msg text , ``str`` :returns: :class:`MsgSpec` specification :raises: :exc:`InvalidMsgSpec` If syntax errors or other problems are detected in file """ log("load_msg_from_string", full_name) package_name, short_name = package_resource_name(full_name) types = [] names = [] constants = [] for orig_line in text.split('\n'): clean_line = _strip_comments(orig_line) if not clean_line: continue #ignore empty lines if CONSTCHAR in clean_line: constants.append(_load_constant_line(orig_line)) else: field_type, name = _load_field_line(orig_line, package_name) types.append(field_type) names.append(name) spec = MsgSpec(types, names, constants, text, full_name, package_name) msg_context.register(full_name, spec) return spec
[ "def", "load_msg_from_string", "(", "msg_context", ",", "text", ",", "full_name", ")", ":", "log", "(", "\"load_msg_from_string\"", ",", "full_name", ")", "package_name", ",", "short_name", "=", "package_resource_name", "(", "full_name", ")", "types", "=", "[", ...
https://github.com/3drobotics/ardupilot-solo/blob/05a123b002c11dccc905d4d7703a38e5f36ee723/mk/PX4/Tools/genmsg/src/genmsg/msg_loader.py#L238-L266
Caffe-MPI/Caffe-MPI.github.io
df5992af571a2a19981b69635115c393f18d1c76
scripts/cpp_lint.py
python
CheckForFunctionLengths
(filename, clean_lines, linenum, function_state, error)
Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found.
Reports for long function bodies.
[ "Reports", "for", "long", "function", "bodies", "." ]
def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] raw = clean_lines.raw_lines raw_line = raw[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count()
[ "def", "CheckForFunctionLengths", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "function_state", ",", "error", ")", ":", "lines", "=", "clean_lines", ".", "lines", "line", "=", "lines", "[", "linenum", "]", "raw", "=", "clean_lines", ".", "raw_l...
https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/scripts/cpp_lint.py#L2384-L2451
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/simpledialog.py
python
Dialog.__init__
(self, parent, title = None)
Initialize a dialog. Arguments: parent -- a parent window (the application window) title -- the dialog title
Initialize a dialog.
[ "Initialize", "a", "dialog", "." ]
def __init__(self, parent, title = None): '''Initialize a dialog. Arguments: parent -- a parent window (the application window) title -- the dialog title ''' Toplevel.__init__(self, parent) self.withdraw() # remain invisible for now # If the master is not viewable, don't # make the child transient, or else it # would be opened withdrawn if parent.winfo_viewable(): self.transient(parent) if title: self.title(title) self.parent = parent self.result = None body = Frame(self) self.initial_focus = self.body(body) body.pack(padx=5, pady=5) self.buttonbox() if not self.initial_focus: self.initial_focus = self self.protocol("WM_DELETE_WINDOW", self.cancel) if self.parent is not None: self.geometry("+%d+%d" % (parent.winfo_rootx()+50, parent.winfo_rooty()+50)) self.deiconify() # become visible now self.initial_focus.focus_set() # wait for window to appear on screen before calling grab_set self.wait_visibility() self.grab_set() self.wait_window(self)
[ "def", "__init__", "(", "self", ",", "parent", ",", "title", "=", "None", ")", ":", "Toplevel", ".", "__init__", "(", "self", ",", "parent", ")", "self", ".", "withdraw", "(", ")", "# remain invisible for now", "# If the master is not viewable, don't", "# make t...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/simpledialog.py#L121-L169
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/calibrate.py
python
RobotExtrinsicCalibration.setMarkerTransform
(self, marker : Key, T : RigidTransform, world=False)
Sets the transform / coordinates for the specified marker. World coordinates use the robot's current configuration.
Sets the transform / coordinates for the specified marker. World coordinates use the robot's current configuration.
[ "Sets", "the", "transform", "/", "coordinates", "for", "the", "specified", "marker", ".", "World", "coordinates", "use", "the", "robot", "s", "current", "configuration", "." ]
def setMarkerTransform(self, marker : Key, T : RigidTransform, world=False): """Sets the transform / coordinates for the specified marker. World coordinates use the robot's current configuration. """ m = self.markers[marker] if world: if isinstance(m,TransformMarker): T = _localTransform(m.link,self.robot,T) else: T = _localPosition(m.link,self.robot,T) m.local_coordinates = T
[ "def", "setMarkerTransform", "(", "self", ",", "marker", ":", "Key", ",", "T", ":", "RigidTransform", ",", "world", "=", "False", ")", ":", "m", "=", "self", ".", "markers", "[", "marker", "]", "if", "world", ":", "if", "isinstance", "(", "m", ",", ...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/calibrate.py#L579-L589
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/reverse-prefix-of-word.py
python
Solution.reversePrefix
(self, word, ch)
return word[:i+1][::-1]+word[i+1:]
:type word: str :type ch: str :rtype: str
:type word: str :type ch: str :rtype: str
[ ":", "type", "word", ":", "str", ":", "type", "ch", ":", "str", ":", "rtype", ":", "str" ]
def reversePrefix(self, word, ch): """ :type word: str :type ch: str :rtype: str """ i = word.find(ch) return word[:i+1][::-1]+word[i+1:]
[ "def", "reversePrefix", "(", "self", ",", "word", ",", "ch", ")", ":", "i", "=", "word", ".", "find", "(", "ch", ")", "return", "word", "[", ":", "i", "+", "1", "]", "[", ":", ":", "-", "1", "]", "+", "word", "[", "i", "+", "1", ":", "]" ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/reverse-prefix-of-word.py#L5-L12
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Wm.wm_iconbitmap
(self, bitmap=None, default=None)
Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given. Under Windows, the DEFAULT parameter can be used to set the icon for the widget and any descendents that don't have an icon set explicitly. DEFAULT can be the relative path to a .ico file (example: root.iconbitmap(default='myicon.ico') ). See Tk documentation for more information.
Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given.
[ "Set", "bitmap", "for", "the", "iconified", "widget", "to", "BITMAP", ".", "Return", "the", "bitmap", "if", "None", "is", "given", "." ]
def wm_iconbitmap(self, bitmap=None, default=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given. Under Windows, the DEFAULT parameter can be used to set the icon for the widget and any descendents that don't have an icon set explicitly. DEFAULT can be the relative path to a .ico file (example: root.iconbitmap(default='myicon.ico') ). See Tk documentation for more information.""" if default: return self.tk.call('wm', 'iconbitmap', self._w, '-default', default) else: return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
[ "def", "wm_iconbitmap", "(", "self", ",", "bitmap", "=", "None", ",", "default", "=", "None", ")", ":", "if", "default", ":", "return", "self", ".", "tk", ".", "call", "(", "'wm'", ",", "'iconbitmap'", ",", "self", ".", "_w", ",", "'-default'", ",", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L1859-L1871
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/stata.py
python
StataWriter._write_expansion_fields
(self)
Write 5 zeros for expansion fields
Write 5 zeros for expansion fields
[ "Write", "5", "zeros", "for", "expansion", "fields" ]
def _write_expansion_fields(self): """Write 5 zeros for expansion fields""" self._write(_pad_bytes("", 5))
[ "def", "_write_expansion_fields", "(", "self", ")", ":", "self", ".", "_write", "(", "_pad_bytes", "(", "\"\"", ",", "5", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/stata.py#L2422-L2424
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/smtplib.py
python
SMTP.rset
(self)
return self.docmd("rset")
SMTP 'rset' command -- resets session.
SMTP 'rset' command -- resets session.
[ "SMTP", "rset", "command", "--", "resets", "session", "." ]
def rset(self): """SMTP 'rset' command -- resets session.""" self.command_encoding = 'ascii' return self.docmd("rset")
[ "def", "rset", "(", "self", ")", ":", "self", ".", "command_encoding", "=", "'ascii'", "return", "self", ".", "docmd", "(", "\"rset\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/smtplib.py#L495-L498
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py
python
Message.__getitem__
(self, name)
return self.get(name)
Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name.
Get a header value.
[ "Get", "a", "header", "value", "." ]
def __getitem__(self, name): """Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name. """ return self.get(name)
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "return", "self", ".", "get", "(", "name", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py#L285-L294
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py
python
DefaultCookiePolicy.set_blocked_domains
(self, blocked_domains)
Set the sequence of blocked domains.
Set the sequence of blocked domains.
[ "Set", "the", "sequence", "of", "blocked", "domains", "." ]
def set_blocked_domains(self, blocked_domains): """Set the sequence of blocked domains.""" self._blocked_domains = tuple(blocked_domains)
[ "def", "set_blocked_domains", "(", "self", ",", "blocked_domains", ")", ":", "self", ".", "_blocked_domains", "=", "tuple", "(", "blocked_domains", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py#L884-L886
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py
python
WhiteKernel.diag
(self, X)
return self.noise_level * np.ones(X.shape[0])
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X)
Returns the diagonal of the kernel k(X, X).
[ "Returns", "the", "diagonal", "of", "the", "kernel", "k", "(", "X", "X", ")", "." ]
def diag(self, X): """Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters ---------- X : array, shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y) Returns ------- K_diag : array, shape (n_samples_X,) Diagonal of kernel k(X, X) """ return self.noise_level * np.ones(X.shape[0])
[ "def", "diag", "(", "self", ",", "X", ")", ":", "return", "self", ".", "noise_level", "*", "np", ".", "ones", "(", "X", ".", "shape", "[", "0", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py#L1107-L1124
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
MouseState.SetX
(*args, **kwargs)
return _core_.MouseState_SetX(*args, **kwargs)
SetX(self, int x)
SetX(self, int x)
[ "SetX", "(", "self", "int", "x", ")" ]
def SetX(*args, **kwargs): """SetX(self, int x)""" return _core_.MouseState_SetX(*args, **kwargs)
[ "def", "SetX", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MouseState_SetX", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L4482-L4484
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/mturk/connection.py
python
MTurkConnection.extend_hit
(self, hit_id, assignments_increment=None, expiration_increment=None)
return self._process_request('ExtendHIT', params)
Increase the maximum number of assignments, or extend the expiration date, of an existing HIT. NOTE: If a HIT has a status of Reviewable and the HIT is extended to make it Available, the HIT will not be returned by GetReviewableHITs, and its submitted assignments will not be returned by GetAssignmentsForHIT, until the HIT is Reviewable again. Assignment auto-approval will still happen on its original schedule, even if the HIT has been extended. Be sure to retrieve and approve (or reject) submitted assignments before extending the HIT, if so desired.
Increase the maximum number of assignments, or extend the expiration date, of an existing HIT.
[ "Increase", "the", "maximum", "number", "of", "assignments", "or", "extend", "the", "expiration", "date", "of", "an", "existing", "HIT", "." ]
def extend_hit(self, hit_id, assignments_increment=None, expiration_increment=None): """ Increase the maximum number of assignments, or extend the expiration date, of an existing HIT. NOTE: If a HIT has a status of Reviewable and the HIT is extended to make it Available, the HIT will not be returned by GetReviewableHITs, and its submitted assignments will not be returned by GetAssignmentsForHIT, until the HIT is Reviewable again. Assignment auto-approval will still happen on its original schedule, even if the HIT has been extended. Be sure to retrieve and approve (or reject) submitted assignments before extending the HIT, if so desired. """ # must provide assignment *or* expiration increment if (assignments_increment is None and expiration_increment is None) or \ (assignments_increment is not None and expiration_increment is not None): raise ValueError("Must specify either assignments_increment or expiration_increment, but not both") params = {'HITId': hit_id} if assignments_increment: params['MaxAssignmentsIncrement'] = assignments_increment if expiration_increment: params['ExpirationIncrementInSeconds'] = expiration_increment return self._process_request('ExtendHIT', params)
[ "def", "extend_hit", "(", "self", ",", "hit_id", ",", "assignments_increment", "=", "None", ",", "expiration_increment", "=", "None", ")", ":", "# must provide assignment *or* expiration increment", "if", "(", "assignments_increment", "is", "None", "and", "expiration_in...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/mturk/connection.py#L536-L562
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/common/extensions/docs/examples/apps/hello-python/httplib2/__init__.py
python
HTTPResponse__getheaders
(self)
return self.msg.items()
Return list of (header, value) tuples.
Return list of (header, value) tuples.
[ "Return", "list", "of", "(", "header", "value", ")", "tuples", "." ]
def HTTPResponse__getheaders(self): """Return list of (header, value) tuples.""" if self.msg is None: raise httplib.ResponseNotReady() return self.msg.items()
[ "def", "HTTPResponse__getheaders", "(", "self", ")", ":", "if", "self", ".", "msg", "is", "None", ":", "raise", "httplib", ".", "ResponseNotReady", "(", ")", "return", "self", ".", "msg", ".", "items", "(", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/examples/apps/hello-python/httplib2/__init__.py#L99-L103
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/debug/cli/tensor_format.py
python
numeric_summary
(tensor)
Get a text summmary of a numeric tensor. This summary is only available for numeric (int*, float*, complex*) and Boolean tensors. Args: tensor: (`numpy.ndarray`) the tensor value object to be summarized. Returns: The summary text as a `RichTextLines` object. If the type of `tensor` is not numeric or Boolean, a single-line `RichTextLines` object containing a warning message will reflect that.
Get a text summmary of a numeric tensor.
[ "Get", "a", "text", "summmary", "of", "a", "numeric", "tensor", "." ]
def numeric_summary(tensor): """Get a text summmary of a numeric tensor. This summary is only available for numeric (int*, float*, complex*) and Boolean tensors. Args: tensor: (`numpy.ndarray`) the tensor value object to be summarized. Returns: The summary text as a `RichTextLines` object. If the type of `tensor` is not numeric or Boolean, a single-line `RichTextLines` object containing a warning message will reflect that. """ def _counts_summary(counts, skip_zeros=True, total_count=None): """Format values as a two-row table.""" if skip_zeros: counts = [(count_key, count_val) for count_key, count_val in counts if count_val] max_common_len = 0 for count_key, count_val in counts: count_val_str = str(count_val) common_len = max(len(count_key) + 1, len(count_val_str) + 1) max_common_len = max(common_len, max_common_len) key_line = debugger_cli_common.RichLine("|") val_line = debugger_cli_common.RichLine("|") for count_key, count_val in counts: count_val_str = str(count_val) key_line += _pad_string_to_length(count_key, max_common_len) val_line += _pad_string_to_length(count_val_str, max_common_len) key_line += " |" val_line += " |" if total_count is not None: total_key_str = "total" total_val_str = str(total_count) max_common_len = max(len(total_key_str) + 1, len(total_val_str)) total_key_str = _pad_string_to_length(total_key_str, max_common_len) total_val_str = _pad_string_to_length(total_val_str, max_common_len) key_line += total_key_str + " |" val_line += total_val_str + " |" return debugger_cli_common.rich_text_lines_from_rich_line_list( [key_line, val_line]) if not isinstance(tensor, np.ndarray) or not np.size(tensor): return debugger_cli_common.RichTextLines([ "No numeric summary available due to empty tensor."]) elif (np.issubdtype(tensor.dtype, np.float) or np.issubdtype(tensor.dtype, np.complex) or np.issubdtype(tensor.dtype, np.integer)): counts = [ ("nan", np.sum(np.isnan(tensor))), ("-inf", np.sum(np.isneginf(tensor))), ("-", np.sum(np.logical_and( tensor < 0.0, np.logical_not(np.isneginf(tensor))))), ("0", np.sum(tensor == 0.0)), ("+", np.sum(np.logical_and( tensor > 0.0, np.logical_not(np.isposinf(tensor))))), ("+inf", np.sum(np.isposinf(tensor)))] output = _counts_summary(counts, total_count=np.size(tensor)) valid_array = tensor[ np.logical_not(np.logical_or(np.isinf(tensor), np.isnan(tensor)))] if np.size(valid_array): stats = [ ("min", np.min(valid_array)), ("max", np.max(valid_array)), ("mean", np.mean(valid_array)), ("std", np.std(valid_array))] output.extend(_counts_summary(stats, skip_zeros=False)) return output elif tensor.dtype == np.bool: counts = [ ("False", np.sum(tensor == 0)), ("True", np.sum(tensor > 0)),] return _counts_summary(counts, total_count=np.size(tensor)) else: return debugger_cli_common.RichTextLines([ "No numeric summary available due to tensor dtype: %s." % tensor.dtype])
[ "def", "numeric_summary", "(", "tensor", ")", ":", "def", "_counts_summary", "(", "counts", ",", "skip_zeros", "=", "True", ",", "total_count", "=", "None", ")", ":", "\"\"\"Format values as a two-row table.\"\"\"", "if", "skip_zeros", ":", "counts", "=", "[", "...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/tensor_format.py#L482-L563
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/BASIC/basparse.py
python
p_varlist
(p)
varlist : varlist COMMA variable | variable
varlist : varlist COMMA variable | variable
[ "varlist", ":", "varlist", "COMMA", "variable", "|", "variable" ]
def p_varlist(p): '''varlist : varlist COMMA variable | variable''' if len(p) > 2: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]]
[ "def", "p_varlist", "(", "p", ")", ":", "if", "len", "(", "p", ")", ">", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "p", "[", "0", "]", ".", "append", "(", "p", "[", "3", "]", ")", "else", ":", "p", "[", "0", "]", "=", "...
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/BASIC/basparse.py#L334-L341
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/api.py
python
union_indexes
(indexes, sort: bool = True)
Return the union of indexes. The behavior of sort and names is not consistent. Parameters ---------- indexes : list of Index or list objects sort : bool, default True Whether the result index should come out sorted or not. Returns ------- Index
Return the union of indexes.
[ "Return", "the", "union", "of", "indexes", "." ]
def union_indexes(indexes, sort: bool = True) -> Index: """ Return the union of indexes. The behavior of sort and names is not consistent. Parameters ---------- indexes : list of Index or list objects sort : bool, default True Whether the result index should come out sorted or not. Returns ------- Index """ if len(indexes) == 0: raise AssertionError("Must have at least 1 Index to union") if len(indexes) == 1: result = indexes[0] if isinstance(result, list): result = Index(sorted(result)) return result indexes, kind = _sanitize_and_check(indexes) def _unique_indices(inds) -> Index: """ Convert indexes to lists and concatenate them, removing duplicates. The final dtype is inferred. Parameters ---------- inds : list of Index or list objects Returns ------- Index """ def conv(i): if isinstance(i, Index): i = i.tolist() return i return Index(lib.fast_unique_multiple_list([conv(i) for i in inds], sort=sort)) if kind == "special": result = indexes[0] if hasattr(result, "union_many"): # DatetimeIndex return result.union_many(indexes[1:]) else: for other in indexes[1:]: result = result.union(other) return result elif kind == "array": index = indexes[0] if not all(index.equals(other) for other in indexes[1:]): index = _unique_indices(indexes) name = get_unanimous_names(*indexes)[0] if name != index.name: index = index.rename(name) return index else: # kind='list' return _unique_indices(indexes)
[ "def", "union_indexes", "(", "indexes", ",", "sort", ":", "bool", "=", "True", ")", "->", "Index", ":", "if", "len", "(", "indexes", ")", "==", "0", ":", "raise", "AssertionError", "(", "\"Must have at least 1 Index to union\"", ")", "if", "len", "(", "ind...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/api.py#L165-L233
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/generator/msvs.py
python
_CreateProjectObjects
(target_list, target_dicts, options, msvs_version)
return projects
Create a MSVSProject object for the targets found in target list. Arguments: target_list: the list of targets to generate project objects for. target_dicts: the dictionary of specifications. options: global generator options. msvs_version: the MSVSVersion object. Returns: A set of created projects, keyed by target.
Create a MSVSProject object for the targets found in target list.
[ "Create", "a", "MSVSProject", "object", "for", "the", "targets", "found", "in", "target", "list", "." ]
def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): """Create a MSVSProject object for the targets found in target list. Arguments: target_list: the list of targets to generate project objects for. target_dicts: the dictionary of specifications. options: global generator options. msvs_version: the MSVSVersion object. Returns: A set of created projects, keyed by target. """ global fixpath_prefix # Generate each project. projects = {} for qualified_target in target_list: spec = target_dicts[qualified_target] if spec['toolset'] != 'target': raise Exception( 'Multiple toolsets not supported in msvs build (target %s)' % qualified_target) proj_path, fixpath_prefix = _GetPathOfProject(qualified_target, spec, options, msvs_version) guid = _GetGuidOfProject(proj_path, spec) overrides = _GetPlatformOverridesOfProject(spec) build_file = gyp.common.BuildFile(qualified_target) # Create object for this project. obj = MSVSNew.MSVSProject( _FixPath(proj_path), name=spec['target_name'], guid=guid, spec=spec, build_file=build_file, config_platform_overrides=overrides, fixpath_prefix=fixpath_prefix) # Set project toolset if any (MS build only) if msvs_version.UsesVcxproj(): obj.set_msbuild_toolset( _GetMsbuildToolsetOfProject(proj_path, spec, msvs_version)) projects[qualified_target] = obj # Set all the dependencies for project in projects.values(): deps = project.spec.get('dependencies', []) deps = [projects[d] for d in deps] project.set_dependencies(deps) return projects
[ "def", "_CreateProjectObjects", "(", "target_list", ",", "target_dicts", ",", "options", ",", "msvs_version", ")", ":", "global", "fixpath_prefix", "# Generate each project.", "projects", "=", "{", "}", "for", "qualified_target", "in", "target_list", ":", "spec", "=...
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/generator/msvs.py#L1642-L1686
mamedev/mame
02cd26d37ee11191f3e311e19e805d872cb1e3a4
3rdparty/benchmark/mingw.py
python
unpack
(archive, location, log = EmptyLogger())
Unpacks a mingw-builds archive
Unpacks a mingw-builds archive
[ "Unpacks", "a", "mingw", "-", "builds", "archive" ]
def unpack(archive, location, log = EmptyLogger()): ''' Unpacks a mingw-builds archive ''' sevenzip = find_7zip(log) log.info('unpacking %s', os.path.basename(archive)) cmd = [sevenzip, 'x', archive, '-o' + location, '-y'] log.debug(' - %r', cmd) with open(os.devnull, 'w') as devnull: subprocess.check_call(cmd, stdout = devnull)
[ "def", "unpack", "(", "archive", ",", "location", ",", "log", "=", "EmptyLogger", "(", ")", ")", ":", "sevenzip", "=", "find_7zip", "(", "log", ")", "log", ".", "info", "(", "'unpacking %s'", ",", "os", ".", "path", ".", "basename", "(", "archive", "...
https://github.com/mamedev/mame/blob/02cd26d37ee11191f3e311e19e805d872cb1e3a4/3rdparty/benchmark/mingw.py#L114-L123
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/moosetree/Node.py
python
Node.attributes
(self)
return self.__attributes
Return the a 'attributes' (key, value pairs supplied in construction) for this node.
Return the a 'attributes' (key, value pairs supplied in construction) for this node.
[ "Return", "the", "a", "attributes", "(", "key", "value", "pairs", "supplied", "in", "construction", ")", "for", "this", "node", "." ]
def attributes(self): """Return the a 'attributes' (key, value pairs supplied in construction) for this node.""" return self.__attributes
[ "def", "attributes", "(", "self", ")", ":", "return", "self", ".", "__attributes" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/moosetree/Node.py#L143-L145
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/optimizer.py
python
_deduplicate_indexed_slices
(values, indices)
return (summed_values, unique_indices)
Sums `values` associated with any non-unique `indices`. Args: values: A `Tensor` with rank >= 1. indices: A one-dimensional integer `Tensor`, indexing into the first dimension of `values` (as in an IndexedSlices object). Returns: A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a de-duplicated version of `indices` and `summed_values` contains the sum of `values` slices associated with each unique index.
Sums `values` associated with any non-unique `indices`.
[ "Sums", "values", "associated", "with", "any", "non", "-", "unique", "indices", "." ]
def _deduplicate_indexed_slices(values, indices): """Sums `values` associated with any non-unique `indices`. Args: values: A `Tensor` with rank >= 1. indices: A one-dimensional integer `Tensor`, indexing into the first dimension of `values` (as in an IndexedSlices object). Returns: A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a de-duplicated version of `indices` and `summed_values` contains the sum of `values` slices associated with each unique index. """ unique_indices, new_index_positions = array_ops.unique(indices) summed_values = math_ops.unsorted_segment_sum( values, new_index_positions, array_ops.shape(unique_indices)[0]) return (summed_values, unique_indices)
[ "def", "_deduplicate_indexed_slices", "(", "values", ",", "indices", ")", ":", "unique_indices", ",", "new_index_positions", "=", "array_ops", ".", "unique", "(", "indices", ")", "summed_values", "=", "math_ops", ".", "unsorted_segment_sum", "(", "values", ",", "n...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/optimizer.py#L64-L80
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/ndimage/interpolation.py
python
geometric_transform
(input, mapping, output_shape=None, output=None, order=3, mode='constant', cval=0.0, prefilter=True, extra_arguments=(), extra_keywords={})
return output
Apply an arbitrary geometric transform. The given mapping function is used to find, for each point in the output, the corresponding coordinates in the input. The value of the input at those coordinates is determined by spline interpolation of the requested order. Parameters ---------- %(input)s mapping : {callable, scipy.LowLevelCallable} A callable object that accepts a tuple of length equal to the output array rank, and returns the corresponding input coordinates as a tuple of length equal to the input array rank. output_shape : tuple of ints, optional Shape tuple. %(output)s order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5. %(mode)s %(cval)s %(prefilter)s extra_arguments : tuple, optional Extra arguments passed to `mapping`. extra_keywords : dict, optional Extra keywords passed to `mapping`. Returns ------- output : ndarray The filtered input. See Also -------- map_coordinates, affine_transform, spline_filter1d Notes ----- This function also accepts low-level callback functions with one the following signatures and wrapped in `scipy.LowLevelCallable`: .. code:: c int mapping(npy_intp *output_coordinates, double *input_coordinates, int output_rank, int input_rank, void *user_data) int mapping(intptr_t *output_coordinates, double *input_coordinates, int output_rank, int input_rank, void *user_data) The calling function iterates over the elements of the output array, calling the callback function at each element. The coordinates of the current output element are passed through ``output_coordinates``. The callback function must return the coordinates at which the input must be interpolated in ``input_coordinates``. The rank of the input and output arrays are given by ``input_rank`` and ``output_rank`` respectively. ``user_data`` is the data pointer provided to `scipy.LowLevelCallable` as-is. The callback function must return an integer error status that is zero if something went wrong and one otherwise. If an error occurs, you should normally set the python error status with an informative message before returning, otherwise a default error message is set by the calling function. In addition, some other low-level function pointer specifications are accepted, but these are for backward compatibility only and should not be used in new code. Examples -------- >>> import numpy as np >>> from scipy.ndimage import geometric_transform >>> a = np.arange(12.).reshape((4, 3)) >>> def shift_func(output_coords): ... return (output_coords[0] - 0.5, output_coords[1] - 0.5) ... >>> geometric_transform(a, shift_func) array([[ 0. , 0. , 0. ], [ 0. , 1.362, 2.738], [ 0. , 4.812, 6.187], [ 0. , 8.263, 9.637]]) >>> b = [1, 2, 3, 4, 5] >>> def shift_func(output_coords): ... return (output_coords[0] - 3,) ... >>> geometric_transform(b, shift_func, mode='constant') array([0, 0, 0, 1, 2]) >>> geometric_transform(b, shift_func, mode='nearest') array([1, 1, 1, 1, 2]) >>> geometric_transform(b, shift_func, mode='reflect') array([3, 2, 1, 1, 2]) >>> geometric_transform(b, shift_func, mode='wrap') array([2, 3, 4, 1, 2])
Apply an arbitrary geometric transform.
[ "Apply", "an", "arbitrary", "geometric", "transform", "." ]
def geometric_transform(input, mapping, output_shape=None, output=None, order=3, mode='constant', cval=0.0, prefilter=True, extra_arguments=(), extra_keywords={}): """ Apply an arbitrary geometric transform. The given mapping function is used to find, for each point in the output, the corresponding coordinates in the input. The value of the input at those coordinates is determined by spline interpolation of the requested order. Parameters ---------- %(input)s mapping : {callable, scipy.LowLevelCallable} A callable object that accepts a tuple of length equal to the output array rank, and returns the corresponding input coordinates as a tuple of length equal to the input array rank. output_shape : tuple of ints, optional Shape tuple. %(output)s order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5. %(mode)s %(cval)s %(prefilter)s extra_arguments : tuple, optional Extra arguments passed to `mapping`. extra_keywords : dict, optional Extra keywords passed to `mapping`. Returns ------- output : ndarray The filtered input. See Also -------- map_coordinates, affine_transform, spline_filter1d Notes ----- This function also accepts low-level callback functions with one the following signatures and wrapped in `scipy.LowLevelCallable`: .. code:: c int mapping(npy_intp *output_coordinates, double *input_coordinates, int output_rank, int input_rank, void *user_data) int mapping(intptr_t *output_coordinates, double *input_coordinates, int output_rank, int input_rank, void *user_data) The calling function iterates over the elements of the output array, calling the callback function at each element. The coordinates of the current output element are passed through ``output_coordinates``. The callback function must return the coordinates at which the input must be interpolated in ``input_coordinates``. The rank of the input and output arrays are given by ``input_rank`` and ``output_rank`` respectively. ``user_data`` is the data pointer provided to `scipy.LowLevelCallable` as-is. The callback function must return an integer error status that is zero if something went wrong and one otherwise. If an error occurs, you should normally set the python error status with an informative message before returning, otherwise a default error message is set by the calling function. In addition, some other low-level function pointer specifications are accepted, but these are for backward compatibility only and should not be used in new code. Examples -------- >>> import numpy as np >>> from scipy.ndimage import geometric_transform >>> a = np.arange(12.).reshape((4, 3)) >>> def shift_func(output_coords): ... return (output_coords[0] - 0.5, output_coords[1] - 0.5) ... >>> geometric_transform(a, shift_func) array([[ 0. , 0. , 0. ], [ 0. , 1.362, 2.738], [ 0. , 4.812, 6.187], [ 0. , 8.263, 9.637]]) >>> b = [1, 2, 3, 4, 5] >>> def shift_func(output_coords): ... return (output_coords[0] - 3,) ... >>> geometric_transform(b, shift_func, mode='constant') array([0, 0, 0, 1, 2]) >>> geometric_transform(b, shift_func, mode='nearest') array([1, 1, 1, 1, 2]) >>> geometric_transform(b, shift_func, mode='reflect') array([3, 2, 1, 1, 2]) >>> geometric_transform(b, shift_func, mode='wrap') array([2, 3, 4, 1, 2]) """ if order < 0 or order > 5: raise RuntimeError('spline order not supported') input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') if output_shape is None: output_shape = input.shape if input.ndim < 1 or len(output_shape) < 1: raise RuntimeError('input and output rank must be > 0') mode = _ni_support._extend_mode_to_code(mode) if prefilter and order > 1: filtered = spline_filter(input, order, output=numpy.float64) else: filtered = input output = _ni_support._get_output(output, input, shape=output_shape) _nd_image.geometric_transform(filtered, mapping, None, None, None, output, order, mode, cval, extra_arguments, extra_keywords) return output
[ "def", "geometric_transform", "(", "input", ",", "mapping", ",", "output_shape", "=", "None", ",", "output", "=", "None", ",", "order", "=", "3", ",", "mode", "=", "'constant'", ",", "cval", "=", "0.0", ",", "prefilter", "=", "True", ",", "extra_argument...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/ndimage/interpolation.py#L143-L263
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
src/bindings/python/src/compatibility/ngraph/opset1/ops.py
python
deformable_psroi_pooling
( feature_maps: NodeInput, coords: NodeInput, output_dim: int, spatial_scale: float, group_size: int = 1, mode: str = "bilinear_deformable", spatial_bins_x: int = 1, spatial_bins_y: int = 1, trans_std: float = 1.0, part_size: int = 1, offsets: Optional[NodeInput] = None, name: Optional[str] = None, )
return _get_node_factory_opset1().create( "DeformablePSROIPooling", node_inputs, { "output_dim": output_dim, "spatial_scale": spatial_scale, "group_size": group_size, "mode": mode, "spatial_bins_x": spatial_bins_x, "spatial_bins_y": spatial_bins_y, "trans_std": trans_std, "part_size": part_size, }, )
Return node performing DeformablePSROIPooling operation. DeformablePSROIPooling computes position-sensitive pooling on regions of interest specified by input. :param feature_maps: 4D tensor with feature maps. :param coords: 2D tensor describing box consisting of tuples: [batch_id, x_1, y_1, x_2, y_2]. :param output_dim: A pooled output channel number. :param spatial_scale: A multiplicative spatial scale factor to translate ROI. :param group_size: The number of groups to encode position-sensitive score. :param mode: Specifies mode for pooling. Range of values: ['bilinear_deformable']. :param spatial_bins_x: Specifies numbers of bins to divide the input feature maps over width. :param spatial_bins_y: Specifies numbers of bins to divide the input feature maps over height. :param trans_std: The value that all transformation (offset) values are multiplied with. :param part_size: The number of parts the output tensor spatial dimensions are divided into. :param offsets: Optional node. 4D input blob with transformation values (offsets). :param name: The optional new name for output node. :return: New node performing DeformablePSROIPooling operation.
Return node performing DeformablePSROIPooling operation.
[ "Return", "node", "performing", "DeformablePSROIPooling", "operation", "." ]
def deformable_psroi_pooling( feature_maps: NodeInput, coords: NodeInput, output_dim: int, spatial_scale: float, group_size: int = 1, mode: str = "bilinear_deformable", spatial_bins_x: int = 1, spatial_bins_y: int = 1, trans_std: float = 1.0, part_size: int = 1, offsets: Optional[NodeInput] = None, name: Optional[str] = None, ) -> Node: """Return node performing DeformablePSROIPooling operation. DeformablePSROIPooling computes position-sensitive pooling on regions of interest specified by input. :param feature_maps: 4D tensor with feature maps. :param coords: 2D tensor describing box consisting of tuples: [batch_id, x_1, y_1, x_2, y_2]. :param output_dim: A pooled output channel number. :param spatial_scale: A multiplicative spatial scale factor to translate ROI. :param group_size: The number of groups to encode position-sensitive score. :param mode: Specifies mode for pooling. Range of values: ['bilinear_deformable']. :param spatial_bins_x: Specifies numbers of bins to divide the input feature maps over width. :param spatial_bins_y: Specifies numbers of bins to divide the input feature maps over height. :param trans_std: The value that all transformation (offset) values are multiplied with. :param part_size: The number of parts the output tensor spatial dimensions are divided into. :param offsets: Optional node. 4D input blob with transformation values (offsets). :param name: The optional new name for output node. :return: New node performing DeformablePSROIPooling operation. """ node_inputs = as_nodes(feature_maps, coords) if offsets is not None: node_inputs.append(as_node(offsets)) return _get_node_factory_opset1().create( "DeformablePSROIPooling", node_inputs, { "output_dim": output_dim, "spatial_scale": spatial_scale, "group_size": group_size, "mode": mode, "spatial_bins_x": spatial_bins_x, "spatial_bins_y": spatial_bins_y, "trans_std": trans_std, "part_size": part_size, }, )
[ "def", "deformable_psroi_pooling", "(", "feature_maps", ":", "NodeInput", ",", "coords", ":", "NodeInput", ",", "output_dim", ":", "int", ",", "spatial_scale", ":", "float", ",", "group_size", ":", "int", "=", "1", ",", "mode", ":", "str", "=", "\"bilinear_d...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset1/ops.py#L524-L574
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/platform/profiler/android_profiling_helper.py
python
_FileMetadataMatches
(filea, fileb)
return True
Check if the metadata of two files matches.
Check if the metadata of two files matches.
[ "Check", "if", "the", "metadata", "of", "two", "files", "matches", "." ]
def _FileMetadataMatches(filea, fileb): """Check if the metadata of two files matches.""" assert os.path.exists(filea) if not os.path.exists(fileb): return False fields_to_compare = [ 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_size', 'st_uid'] filea_stat = os.stat(filea) fileb_stat = os.stat(fileb) for field in fields_to_compare: # shutil.copy2 doesn't get ctime/mtime identical when the file system # provides sub-second accuracy. if int(getattr(filea_stat, field)) != int(getattr(fileb_stat, field)): return False return True
[ "def", "_FileMetadataMatches", "(", "filea", ",", "fileb", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "filea", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fileb", ")", ":", "return", "False", "fields_to_compare", "=", "[",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/platform/profiler/android_profiling_helper.py#L171-L187
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/autograph/pyct/static_analysis/activity.py
python
Scope.finalize
(self)
Freezes this scope.
Freezes this scope.
[ "Freezes", "this", "scope", "." ]
def finalize(self): """Freezes this scope.""" assert not self.is_final # TODO(mdan): freeze read, modified, bound. if self.parent is not None: assert not self.parent.is_final if not self.isolated: self.parent.read.update(self.read - self.isolated_names) self.parent.modified.update(self.modified - self.isolated_names) self.parent.bound.update(self.bound - self.isolated_names) self.parent.globals.update(self.globals) self.parent.nonlocals.update(self.nonlocals) self.parent.annotations.update(self.annotations) else: # TODO(mdan): This is not accurate. self.parent.read.update(self.read - self.bound) self.parent.annotations.update(self.annotations - self.bound) self.is_final = True
[ "def", "finalize", "(", "self", ")", ":", "assert", "not", "self", ".", "is_final", "# TODO(mdan): freeze read, modified, bound.", "if", "self", ".", "parent", "is", "not", "None", ":", "assert", "not", "self", ".", "parent", ".", "is_final", "if", "not", "s...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/pyct/static_analysis/activity.py#L181-L198
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/rnn_cell.py
python
_state_size_with_prefix
(state_size, prefix=None)
return result_state_size
Helper function that enables int or TensorShape shape specification. This function takes a size specification, which can be an integer or a TensorShape, and converts it into a list of integers. One may specify any additional dimensions that precede the final state size specification. Args: state_size: TensorShape or int that specifies the size of a tensor. prefix: optional additional list of dimensions to prepend. Returns: result_state_size: list of dimensions the resulting tensor size.
Helper function that enables int or TensorShape shape specification.
[ "Helper", "function", "that", "enables", "int", "or", "TensorShape", "shape", "specification", "." ]
def _state_size_with_prefix(state_size, prefix=None): """Helper function that enables int or TensorShape shape specification. This function takes a size specification, which can be an integer or a TensorShape, and converts it into a list of integers. One may specify any additional dimensions that precede the final state size specification. Args: state_size: TensorShape or int that specifies the size of a tensor. prefix: optional additional list of dimensions to prepend. Returns: result_state_size: list of dimensions the resulting tensor size. """ result_state_size = tensor_shape.as_shape(state_size).as_list() if prefix is not None: if not isinstance(prefix, list): raise TypeError("prefix of _state_size_with_prefix should be a list.") result_state_size = prefix + result_state_size return result_state_size
[ "def", "_state_size_with_prefix", "(", "state_size", ",", "prefix", "=", "None", ")", ":", "result_state_size", "=", "tensor_shape", ".", "as_shape", "(", "state_size", ")", ".", "as_list", "(", ")", "if", "prefix", "is", "not", "None", ":", "if", "not", "...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/rnn_cell.py#L65-L84
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/stats/_distn_infrastructure.py
python
rv_continuous.logsf
(self, x, *args, **kwds)
return output
Log of the survival function of the given RV. Returns the log of the "survival function," defined as (1 - `cdf`), evaluated at `x`. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- logsf : ndarray Log of the survival function evaluated at `x`.
Log of the survival function of the given RV.
[ "Log", "of", "the", "survival", "function", "of", "the", "given", "RV", "." ]
def logsf(self, x, *args, **kwds): """ Log of the survival function of the given RV. Returns the log of the "survival function," defined as (1 - `cdf`), evaluated at `x`. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- logsf : ndarray Log of the survival function evaluated at `x`. """ args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x) & (scale > 0) cond2 = cond0 & (x <= self.a) cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 0.0) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._logsf(*goodargs)) if output.ndim == 0: return output[()] return output
[ "def", "logsf", "(", "self", ",", "x", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "args", ",", "loc", ",", "scale", "=", "self", ".", "_parse_args", "(", "*", "args", ",", "*", "*", "kwds", ")", "x", ",", "loc", ",", "scale", "=", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/_distn_infrastructure.py#L1825-L1868
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/tools/build/src/build/project.py
python
ProjectRegistry.load_standalone
(self, jamfile_module, file)
Loads 'file' as standalone project that has no location associated with it. This is mostly useful for user-config.jam, which should be able to define targets, but although it has some location in filesystem, we do not want any build to happen in user's HOME, for example. The caller is required to never call this method twice on the same file.
Loads 'file' as standalone project that has no location associated with it. This is mostly useful for user-config.jam, which should be able to define targets, but although it has some location in filesystem, we do not want any build to happen in user's HOME, for example.
[ "Loads", "file", "as", "standalone", "project", "that", "has", "no", "location", "associated", "with", "it", ".", "This", "is", "mostly", "useful", "for", "user", "-", "config", ".", "jam", "which", "should", "be", "able", "to", "define", "targets", "but",...
def load_standalone(self, jamfile_module, file): """Loads 'file' as standalone project that has no location associated with it. This is mostly useful for user-config.jam, which should be able to define targets, but although it has some location in filesystem, we do not want any build to happen in user's HOME, for example. The caller is required to never call this method twice on the same file. """ assert isinstance(jamfile_module, basestring) assert isinstance(file, basestring) self.used_projects[jamfile_module] = [] bjam.call("load", jamfile_module, file) self.load_used_projects(jamfile_module)
[ "def", "load_standalone", "(", "self", ",", "jamfile_module", ",", "file", ")", ":", "assert", "isinstance", "(", "jamfile_module", ",", "basestring", ")", "assert", "isinstance", "(", "file", ",", "basestring", ")", "self", ".", "used_projects", "[", "jamfile...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/project.py#L387-L402
ARM-software/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
examples/gemm_tuner/GemmTuner.py
python
extract_benchmark_results
( json_results: Dict, measurement_method="avg" )
Parse the benchmark result and extract relevant information, namely: GEMM param, Strategy, GEMM config, Measurements
Parse the benchmark result and extract relevant information, namely: GEMM param, Strategy, GEMM config, Measurements
[ "Parse", "the", "benchmark", "result", "and", "extract", "relevant", "information", "namely", ":", "GEMM", "param", "Strategy", "GEMM", "config", "Measurements" ]
def extract_benchmark_results( json_results: Dict, measurement_method="avg" ) -> Generator[BenchmarkResult, None, None]: """ Parse the benchmark result and extract relevant information, namely: GEMM param, Strategy, GEMM config, Measurements """ for json_res in json_results: # Get example test and test data. # There should only be 1 test per run example_tests = list(json_res["tests"].items()) assert len(example_tests) == 1 example_fn, example_test_data = example_tests[0] # Process example file name example_fn = example_fn.split(os.path.sep)[-1] # Get strategy strategy = EXAMPLE_FILE_2_STRATEGY[example_fn] # Get gemm params + gemm configs from example args benchmark_args = parse_benchmark_commandline(json_res["CommandLine"]) Gemm_Example_Args_T = GEMM_EXAMPLE_ARGS_FACTORY[strategy] example_args = Gemm_Example_Args_T( *(benchmark_args["example_args"].split(","))) # Gemm_Example_Arg consists of GEMMParam first and then GEMMConfig (in that order) # However data type option is parsed separately from end of options, hence -1 is applied to fields length gemm_param_fields_len = len(GEMMParam._fields) - 1 gemm_param = GEMMParam.parse_from_strs( *example_args[:gemm_param_fields_len], data_type = benchmark_args["type"]) GEMMConfig = GEMM_CONFIG_FACTORY[strategy] gemm_config = GEMMConfig.parse_from_strs( *example_args[gemm_param_fields_len:]) # Get OpenCL_Time_Ms stats measurements = list(example_test_data["measurements"].items()) # For reshaped RHS only we have two measurements (one also for the reshape kernel) # Hence we must parse and sum them measurement_ms_reshape = 0 measurement_ms_kernel = 0 for single_measurement in measurements: measurement_instrument, data = single_measurement # Get instrument name and assert that it is the one we expect measurement_instrument_name = measurement_instrument.split("/")[0] assert measurement_instrument_name == "OpenCLTimer" # Take either the minimum or the average of the raw data as the measurement value if measurement_method == "min": measurement_val = min(data["raw"]) elif measurement_method == "avg": measurement_val = sum(data["raw"]) / len(data["raw"]) else: raise ValueError( "Invalid measurement method: {}".format(measurement_method) ) measurement_type = measurement_instrument.split("/")[1] if "reshape" in measurement_type.split("_"): measurement_ms_reshape = measurement_val else: measurement_ms_kernel = measurement_val measurement = Measurement( measurement_ms_reshape, measurement_ms_kernel) yield BenchmarkResult(gemm_param, strategy, gemm_config, measurement)
[ "def", "extract_benchmark_results", "(", "json_results", ":", "Dict", ",", "measurement_method", "=", "\"avg\"", ")", "->", "Generator", "[", "BenchmarkResult", ",", "None", ",", "None", "]", ":", "for", "json_res", "in", "json_results", ":", "# Get example test a...
https://github.com/ARM-software/ComputeLibrary/blob/91ee4d0a9ef128b16936921470a0e3ffef347536/examples/gemm_tuner/GemmTuner.py#L488-L555
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/ceph-volume/ceph_volume/devices/lvm/batch.py
python
Batch._check_slot_args
(self)
checking if -slots args are consistent with other arguments
checking if -slots args are consistent with other arguments
[ "checking", "if", "-", "slots", "args", "are", "consistent", "with", "other", "arguments" ]
def _check_slot_args(self): ''' checking if -slots args are consistent with other arguments ''' if self.args.data_slots and self.args.osds_per_device: if self.args.data_slots < self.args.osds_per_device: raise ValueError('data_slots is smaller then osds_per_device')
[ "def", "_check_slot_args", "(", "self", ")", ":", "if", "self", ".", "args", ".", "data_slots", "and", "self", ".", "args", ".", "osds_per_device", ":", "if", "self", ".", "args", ".", "data_slots", "<", "self", ".", "args", ".", "osds_per_device", ":", ...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/devices/lvm/batch.py#L380-L386
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/io/netcdf.py
python
netcdf_file.flush
(self)
Perform a sync-to-disk flush if the `netcdf_file` object is in write mode. See Also -------- sync : Identical function
Perform a sync-to-disk flush if the `netcdf_file` object is in write mode.
[ "Perform", "a", "sync", "-", "to", "-", "disk", "flush", "if", "the", "netcdf_file", "object", "is", "in", "write", "mode", "." ]
def flush(self): """ Perform a sync-to-disk flush if the `netcdf_file` object is in write mode. See Also -------- sync : Identical function """ if hasattr(self, 'mode') and self.mode in 'wa': self._write()
[ "def", "flush", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'mode'", ")", "and", "self", ".", "mode", "in", "'wa'", ":", "self", ".", "_write", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/netcdf.py#L399-L409
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/xcode_emulation.py
python
GetXcodeArchsDefault
()
return XCODE_ARCHS_DEFAULT_CACHE
Returns the |XcodeArchsDefault| object to use to expand ARCHS for the installed version of Xcode. The default values used by Xcode for ARCHS and the expansion of the variables depends on the version of Xcode used. For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses $(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0 and deprecated with Xcode 5.1. For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit architecture as part of $(ARCHS_STANDARD) and default to only building it. For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they are also part of $(ARCHS_STANDARD). All thoses rules are coded in the construction of the |XcodeArchsDefault| object to use depending on the version of Xcode detected. The object is for performance reason.
Returns the |XcodeArchsDefault| object to use to expand ARCHS for the installed version of Xcode. The default values used by Xcode for ARCHS and the expansion of the variables depends on the version of Xcode used.
[ "Returns", "the", "|XcodeArchsDefault|", "object", "to", "use", "to", "expand", "ARCHS", "for", "the", "installed", "version", "of", "Xcode", ".", "The", "default", "values", "used", "by", "Xcode", "for", "ARCHS", "and", "the", "expansion", "of", "the", "var...
def GetXcodeArchsDefault(): """Returns the |XcodeArchsDefault| object to use to expand ARCHS for the installed version of Xcode. The default values used by Xcode for ARCHS and the expansion of the variables depends on the version of Xcode used. For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses $(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0 and deprecated with Xcode 5.1. For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit architecture as part of $(ARCHS_STANDARD) and default to only building it. For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they are also part of $(ARCHS_STANDARD). All thoses rules are coded in the construction of the |XcodeArchsDefault| object to use depending on the version of Xcode detected. The object is for performance reason.""" global XCODE_ARCHS_DEFAULT_CACHE if XCODE_ARCHS_DEFAULT_CACHE: return XCODE_ARCHS_DEFAULT_CACHE xcode_version, _ = XcodeVersion() if xcode_version < '0500': XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( '$(ARCHS_STANDARD)', XcodeArchsVariableMapping(['i386']), XcodeArchsVariableMapping(['i386']), XcodeArchsVariableMapping(['armv7'])) elif xcode_version < '0510': XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( '$(ARCHS_STANDARD_INCLUDING_64_BIT)', XcodeArchsVariableMapping(['x86_64'], ['x86_64']), XcodeArchsVariableMapping(['i386'], ['i386', 'x86_64']), XcodeArchsVariableMapping( ['armv7', 'armv7s'], ['armv7', 'armv7s', 'arm64'])) else: XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( '$(ARCHS_STANDARD)', XcodeArchsVariableMapping(['x86_64'], ['x86_64']), XcodeArchsVariableMapping(['i386', 'x86_64'], ['i386', 'x86_64']), XcodeArchsVariableMapping( ['armv7', 'armv7s', 'arm64'], ['armv7', 'armv7s', 'arm64'])) return XCODE_ARCHS_DEFAULT_CACHE
[ "def", "GetXcodeArchsDefault", "(", ")", ":", "global", "XCODE_ARCHS_DEFAULT_CACHE", "if", "XCODE_ARCHS_DEFAULT_CACHE", ":", "return", "XCODE_ARCHS_DEFAULT_CACHE", "xcode_version", ",", "_", "=", "XcodeVersion", "(", ")", "if", "xcode_version", "<", "'0500'", ":", "XC...
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/xcode_emulation.py#L95-L141
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/ffmpeg/ffmpeg_ops.py
python
encode_audio
(audio, file_format=None, samples_per_second=None)
return gen_encode_audio_op_py.encode_audio( audio, file_format=file_format, samples_per_second=samples_per_second)
Creates an op that encodes an audio file using sampled audio from a tensor. Args: audio: A rank 2 tensor that has time along dimension 0 and channels along dimension 1. Dimension 0 is `samples_per_second * length` long in seconds. file_format: The type of file to encode. "wav" is the only supported format. samples_per_second: The number of samples in the audio tensor per second of audio. Returns: A scalar tensor that contains the encoded audio in the specified file format.
Creates an op that encodes an audio file using sampled audio from a tensor.
[ "Creates", "an", "op", "that", "encodes", "an", "audio", "file", "using", "sampled", "audio", "from", "a", "tensor", "." ]
def encode_audio(audio, file_format=None, samples_per_second=None): """Creates an op that encodes an audio file using sampled audio from a tensor. Args: audio: A rank 2 tensor that has time along dimension 0 and channels along dimension 1. Dimension 0 is `samples_per_second * length` long in seconds. file_format: The type of file to encode. "wav" is the only supported format. samples_per_second: The number of samples in the audio tensor per second of audio. Returns: A scalar tensor that contains the encoded audio in the specified file format. """ return gen_encode_audio_op_py.encode_audio( audio, file_format=file_format, samples_per_second=samples_per_second)
[ "def", "encode_audio", "(", "audio", ",", "file_format", "=", "None", ",", "samples_per_second", "=", "None", ")", ":", "return", "gen_encode_audio_op_py", ".", "encode_audio", "(", "audio", ",", "file_format", "=", "file_format", ",", "samples_per_second", "=", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/ffmpeg/ffmpeg_ops.py#L92-L108
osrf/gazebo
f570338107862253229a0514ffea10deab4f4517
tools/cpplint.py
python
GetLineWidth
(line)
Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters.
Determines the width of the line in column positions.
[ "Determines", "the", "width", "of", "the", "line", "in", "column", "positions", "." ]
def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line)
[ "def", "GetLineWidth", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "unicode", ")", ":", "width", "=", "0", "for", "uc", "in", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "line", ")", ":", "if", "unicodedata", ".", "east_asian_w...
https://github.com/osrf/gazebo/blob/f570338107862253229a0514ffea10deab4f4517/tools/cpplint.py#L2114-L2133
PrincetonUniversity/athena-public-version
9c266692b9423743d8e23509b3ab266a232a92d2
tst/style/cpplint.py
python
_FilterExcludedFiles
(filenames)
return [f for f in filenames if os.path.abspath(f) not in exclude_paths]
Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory
Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory
[ "Filters", "out", "files", "listed", "in", "the", "--", "exclude", "command", "line", "switch", ".", "File", "paths", "in", "the", "switch", "are", "evaluated", "relative", "to", "the", "current", "working", "directory" ]
def _FilterExcludedFiles(filenames): """Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory """ exclude_paths = [os.path.abspath(f) for f in _excludes] return [f for f in filenames if os.path.abspath(f) not in exclude_paths]
[ "def", "_FilterExcludedFiles", "(", "filenames", ")", ":", "exclude_paths", "=", "[", "os", ".", "path", ".", "abspath", "(", "f", ")", "for", "f", "in", "_excludes", "]", "return", "[", "f", "for", "f", "in", "filenames", "if", "os", ".", "path", "....
https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L6587-L6592
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/longest-palindrome.py
python
Solution.longestPalindrome2
(self, s)
return len(s) - odd + int(odd > 0)
:type s: str :rtype: int
:type s: str :rtype: int
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "int" ]
def longestPalindrome2(self, s): """ :type s: str :rtype: int """ odd = sum(map(lambda x: x & 1, collections.Counter(s).values())) return len(s) - odd + int(odd > 0)
[ "def", "longestPalindrome2", "(", "self", ",", "s", ")", ":", "odd", "=", "sum", "(", "map", "(", "lambda", "x", ":", "x", "&", "1", ",", "collections", ".", "Counter", "(", "s", ")", ".", "values", "(", ")", ")", ")", "return", "len", "(", "s"...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/longest-palindrome.py#L18-L24
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/hshrink_grad.py
python
_hshrink_grad_tbe
()
return
HShrinkGrad TBE register
HShrinkGrad TBE register
[ "HShrinkGrad", "TBE", "register" ]
def _hshrink_grad_tbe(): """HShrinkGrad TBE register""" return
[ "def", "_hshrink_grad_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/hshrink_grad.py#L35-L37
google/fruit
49c47a7f45b6473254c8880d3862b2780c0f366a
extras/scripts/analyze_template_instantiations_clang_diagnostics.py
python
p_comma_separated_balanced_string_not_empty
(p)
comma_separated_balanced_string : COMMA balanced_string comma_separated_balanced_string
comma_separated_balanced_string : COMMA balanced_string comma_separated_balanced_string
[ "comma_separated_balanced_string", ":", "COMMA", "balanced_string", "comma_separated_balanced_string" ]
def p_comma_separated_balanced_string_not_empty(p): 'comma_separated_balanced_string : COMMA balanced_string comma_separated_balanced_string' p[0] = ( p[2], *(p[3]) )
[ "def", "p_comma_separated_balanced_string_not_empty", "(", "p", ")", ":", "p", "[", "0", "]", "=", "(", "p", "[", "2", "]", ",", "*", "(", "p", "[", "3", "]", ")", ")" ]
https://github.com/google/fruit/blob/49c47a7f45b6473254c8880d3862b2780c0f366a/extras/scripts/analyze_template_instantiations_clang_diagnostics.py#L148-L153
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/PyShell.py
python
ModifiedInterpreter.prepend_syspath
(self, filename)
Prepend sys.path with file's directory if not already included
Prepend sys.path with file's directory if not already included
[ "Prepend", "sys", ".", "path", "with", "file", "s", "directory", "if", "not", "already", "included" ]
def prepend_syspath(self, filename): "Prepend sys.path with file's directory if not already included" self.runcommand("""if 1: _filename = %r import sys as _sys from os.path import dirname as _dirname _dir = _dirname(_filename) if not _dir in _sys.path: _sys.path.insert(0, _dir) del _filename, _sys, _dirname, _dir \n""" % (filename,))
[ "def", "prepend_syspath", "(", "self", ",", "filename", ")", ":", "self", ".", "runcommand", "(", "\"\"\"if 1:\n _filename = %r\n import sys as _sys\n from os.path import dirname as _dirname\n _dir = _dirname(_filename)\n if not _dir in ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/PyShell.py#L667-L677
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/effects/color.py
python
gen_effects_color
(lottie, layer, idx)
Generates the dictionary corresponding to effects/color.json Args: lottie (dict) : Lottie format effects stored in this layer (common.Layer.Layer) : Synfig format layer idx (int) : Index/Count of effect Returns: (None)
Generates the dictionary corresponding to effects/color.json
[ "Generates", "the", "dictionary", "corresponding", "to", "effects", "/", "color", ".", "json" ]
def gen_effects_color(lottie, layer, idx): """ Generates the dictionary corresponding to effects/color.json Args: lottie (dict) : Lottie format effects stored in this layer (common.Layer.Layer) : Synfig format layer idx (int) : Index/Count of effect Returns: (None) """ lottie["ty"] = settings.EFFECTS_COLOR # Effect type lottie["nm"] = "Color" # Name lottie["ix"] = idx # Index lottie["v"] = {} # Value of color color = layer.get_param("color") color.animate("color") color.fill_path(lottie, "v")
[ "def", "gen_effects_color", "(", "lottie", ",", "layer", ",", "idx", ")", ":", "lottie", "[", "\"ty\"", "]", "=", "settings", ".", "EFFECTS_COLOR", "# Effect type", "lottie", "[", "\"nm\"", "]", "=", "\"Color\"", "# Name", "lottie", "[", "\"ix\"", "]", "="...
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/effects/color.py#L10-L30
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/util/md5_check.py
python
Changes.IterModifiedSubpaths
(self, path)
Generator for paths within a zip file whose contents have changed.
Generator for paths within a zip file whose contents have changed.
[ "Generator", "for", "paths", "within", "a", "zip", "file", "whose", "contents", "have", "changed", "." ]
def IterModifiedSubpaths(self, path): """Generator for paths within a zip file whose contents have changed.""" for subpath in self.new_metadata.IterSubpaths(path): old_tag = self._GetOldTag(path, subpath) new_tag = self.new_metadata.GetTag(path, subpath) if old_tag is not None and old_tag != new_tag: yield subpath
[ "def", "IterModifiedSubpaths", "(", "self", ",", "path", ")", ":", "for", "subpath", "in", "self", ".", "new_metadata", ".", "IterSubpaths", "(", "path", ")", ":", "old_tag", "=", "self", ".", "_GetOldTag", "(", "path", ",", "subpath", ")", "new_tag", "=...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/util/md5_check.py#L241-L247
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/learn/python/learn/preprocessing/categorical_vocabulary.py
python
CategoricalVocabulary.trim
(self, min_frequency, max_frequency=-1)
Trims vocabulary for minimum frequency. Remaps ids from 1..n in sort frequency order. where n - number of elements left. Args: min_frequency: minimum frequency to keep. max_frequency: optional, maximum frequency to keep. Useful to remove very frequent categories (like stop words).
Trims vocabulary for minimum frequency.
[ "Trims", "vocabulary", "for", "minimum", "frequency", "." ]
def trim(self, min_frequency, max_frequency=-1): """Trims vocabulary for minimum frequency. Remaps ids from 1..n in sort frequency order. where n - number of elements left. Args: min_frequency: minimum frequency to keep. max_frequency: optional, maximum frequency to keep. Useful to remove very frequent categories (like stop words). """ # Sort by alphabet then reversed frequency. self._freq = sorted( sorted( six.iteritems(self._freq), key=lambda x: (isinstance(x[0], str), x[0])), key=lambda x: x[1], reverse=True) self._mapping = {self._unknown_token: 0} if self._support_reverse: self._reverse_mapping = [self._unknown_token] idx = 1 for category, count in self._freq: if max_frequency > 0 and count >= max_frequency: continue if count <= min_frequency: break self._mapping[category] = idx idx += 1 if self._support_reverse: self._reverse_mapping.append(category) self._freq = dict(self._freq[:idx - 1])
[ "def", "trim", "(", "self", ",", "min_frequency", ",", "max_frequency", "=", "-", "1", ")", ":", "# Sort by alphabet then reversed frequency.", "self", ".", "_freq", "=", "sorted", "(", "sorted", "(", "six", ".", "iteritems", "(", "self", ".", "_freq", ")", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/preprocessing/categorical_vocabulary.py#L88-L119
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
IconBundleFromIcon
(*args, **kwargs)
return val
IconBundleFromIcon(Icon icon) -> IconBundle
IconBundleFromIcon(Icon icon) -> IconBundle
[ "IconBundleFromIcon", "(", "Icon", "icon", ")", "-", ">", "IconBundle" ]
def IconBundleFromIcon(*args, **kwargs): """IconBundleFromIcon(Icon icon) -> IconBundle""" val = _gdi_.new_IconBundleFromIcon(*args, **kwargs) return val
[ "def", "IconBundleFromIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_gdi_", ".", "new_IconBundleFromIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1515-L1518
ideawu/ssdb-rocks
a3cbb322cafb2f493252829c608e2239df98c9ac
deps/cpy/antlr3/tree.py
python
BaseTreeAdaptor.becomeRoot
(self, newRoot, oldRoot)
return newRoot
If oldRoot is a nil root, just copy or move the children to newRoot. If not a nil root, make oldRoot a child of newRoot. old=^(nil a b c), new=r yields ^(r a b c) old=^(a b c), new=r yields ^(r ^(a b c)) If newRoot is a nil-rooted single child tree, use the single child as the new root node. old=^(nil a b c), new=^(nil r) yields ^(r a b c) old=^(a b c), new=^(nil r) yields ^(r ^(a b c)) If oldRoot was null, it's ok, just return newRoot (even if isNil). old=null, new=r yields r old=null, new=^(nil r) yields ^(nil r) Return newRoot. Throw an exception if newRoot is not a simple node or nil root with a single child node--it must be a root node. If newRoot is ^(nil x) return x as newRoot. Be advised that it's ok for newRoot to point at oldRoot's children; i.e., you don't have to copy the list. We are constructing these nodes so we should have this control for efficiency.
If oldRoot is a nil root, just copy or move the children to newRoot. If not a nil root, make oldRoot a child of newRoot.
[ "If", "oldRoot", "is", "a", "nil", "root", "just", "copy", "or", "move", "the", "children", "to", "newRoot", ".", "If", "not", "a", "nil", "root", "make", "oldRoot", "a", "child", "of", "newRoot", "." ]
def becomeRoot(self, newRoot, oldRoot): """ If oldRoot is a nil root, just copy or move the children to newRoot. If not a nil root, make oldRoot a child of newRoot. old=^(nil a b c), new=r yields ^(r a b c) old=^(a b c), new=r yields ^(r ^(a b c)) If newRoot is a nil-rooted single child tree, use the single child as the new root node. old=^(nil a b c), new=^(nil r) yields ^(r a b c) old=^(a b c), new=^(nil r) yields ^(r ^(a b c)) If oldRoot was null, it's ok, just return newRoot (even if isNil). old=null, new=r yields r old=null, new=^(nil r) yields ^(nil r) Return newRoot. Throw an exception if newRoot is not a simple node or nil root with a single child node--it must be a root node. If newRoot is ^(nil x) return x as newRoot. Be advised that it's ok for newRoot to point at oldRoot's children; i.e., you don't have to copy the list. We are constructing these nodes so we should have this control for efficiency. """ if isinstance(newRoot, Token): newRoot = self.create(newRoot) if oldRoot is None: return newRoot if not isinstance(newRoot, CommonTree): newRoot = self.createWithPayload(newRoot) # handle ^(nil real-node) if newRoot.isNil(): nc = newRoot.getChildCount() if nc == 1: newRoot = newRoot.getChild(0) elif nc > 1: # TODO: make tree run time exceptions hierarchy raise RuntimeError("more than one node as root") # add oldRoot to newRoot; addChild takes care of case where oldRoot # is a flat list (i.e., nil-rooted tree). All children of oldRoot # are added to newRoot. newRoot.addChild(oldRoot) return newRoot
[ "def", "becomeRoot", "(", "self", ",", "newRoot", ",", "oldRoot", ")", ":", "if", "isinstance", "(", "newRoot", ",", "Token", ")", ":", "newRoot", "=", "self", ".", "create", "(", "newRoot", ")", "if", "oldRoot", "is", "None", ":", "return", "newRoot",...
https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/tree.py#L980-L1032
BitcoinUnlimited/BitcoinUnlimited
05de381c02eb4bfca94957733acadfa217527f25
contrib/linearize/linearize-data.py
python
BlockDataCopier.fetchBlock
(self, extent)
Fetch block contents from disk given extents
Fetch block contents from disk given extents
[ "Fetch", "block", "contents", "from", "disk", "given", "extents" ]
def fetchBlock(self, extent): '''Fetch block contents from disk given extents''' with open(self.inFileName(extent.fn), "rb") as f: f.seek(extent.offset) return f.read(extent.size)
[ "def", "fetchBlock", "(", "self", ",", "extent", ")", ":", "with", "open", "(", "self", ".", "inFileName", "(", "extent", ".", "fn", ")", ",", "\"rb\"", ")", "as", "f", ":", "f", ".", "seek", "(", "extent", ".", "offset", ")", "return", "f", ".",...
https://github.com/BitcoinUnlimited/BitcoinUnlimited/blob/05de381c02eb4bfca94957733acadfa217527f25/contrib/linearize/linearize-data.py#L173-L177
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/training/queue_runner.py
python
QueueRunner.__init__
(self, queue=None, enqueue_ops=None, close_op=None, cancel_op=None, queue_runner_def=None)
Create a QueueRunner. On construction the `QueueRunner` adds an op to close the queue. That op will be run if the enqueue ops raise exceptions. When you later call the `create_threads()` method, the `QueueRunner` will create one thread for each op in `enqueue_ops`. Each thread will run its enqueue op in parallel with the other threads. The enqueue ops do not have to all be the same op, but it is expected that they all enqueue tensors in `queue`. Args: queue: A `Queue`. enqueue_ops: List of enqueue ops to run in threads later. close_op: Op to close the queue. Pending enqueue ops are preserved. cancel_op: Op to close the queue and cancel pending enqueue ops. queue_runner_def: Optional `QueueRunnerDef` protocol buffer. If specified, recreates the QueueRunner from its contents. `queue_runner_def` and the other arguments are mutually exclusive. Raises: ValueError: If both `queue_runner_def` and `queue` are both specified. ValueError: If `queue` or `enqueue_ops` are not provided when not restoring from `queue_runner_def`.
Create a QueueRunner.
[ "Create", "a", "QueueRunner", "." ]
def __init__(self, queue=None, enqueue_ops=None, close_op=None, cancel_op=None, queue_runner_def=None): """Create a QueueRunner. On construction the `QueueRunner` adds an op to close the queue. That op will be run if the enqueue ops raise exceptions. When you later call the `create_threads()` method, the `QueueRunner` will create one thread for each op in `enqueue_ops`. Each thread will run its enqueue op in parallel with the other threads. The enqueue ops do not have to all be the same op, but it is expected that they all enqueue tensors in `queue`. Args: queue: A `Queue`. enqueue_ops: List of enqueue ops to run in threads later. close_op: Op to close the queue. Pending enqueue ops are preserved. cancel_op: Op to close the queue and cancel pending enqueue ops. queue_runner_def: Optional `QueueRunnerDef` protocol buffer. If specified, recreates the QueueRunner from its contents. `queue_runner_def` and the other arguments are mutually exclusive. Raises: ValueError: If both `queue_runner_def` and `queue` are both specified. ValueError: If `queue` or `enqueue_ops` are not provided when not restoring from `queue_runner_def`. """ if queue_runner_def: if queue or enqueue_ops: raise ValueError("queue_runner_def and queue are mutually exclusive.") self._init_from_proto(queue_runner_def) else: self._init_from_args(queue=queue, enqueue_ops=enqueue_ops, close_op=close_op, cancel_op=cancel_op) # Protect the count of runs to wait for. self._lock = threading.Lock() self._runs = 0 # List of exceptions raised by the running threads. self._exceptions_raised = []
[ "def", "__init__", "(", "self", ",", "queue", "=", "None", ",", "enqueue_ops", "=", "None", ",", "close_op", "=", "None", ",", "cancel_op", "=", "None", ",", "queue_runner_def", "=", "None", ")", ":", "if", "queue_runner_def", ":", "if", "queue", "or", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/queue_runner.py#L46-L84
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/parse/standard_method.py
python
argmax
(x, axis=None)
return P.Argmax(axis)(x)
Returns the indices of the maximum values along an axis. Args: axis (int, optional): By default, the index is into the flattened array, otherwise along the specified axis. Defaults to None. Returns: Tensor, array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. Raises: ValueError: if axis is out of range. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> import numpy as np >>> from mindspore import Tensor >>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32")) >>> print(a.argmax()) 5
Returns the indices of the maximum values along an axis.
[ "Returns", "the", "indices", "of", "the", "maximum", "values", "along", "an", "axis", "." ]
def argmax(x, axis=None): """ Returns the indices of the maximum values along an axis. Args: axis (int, optional): By default, the index is into the flattened array, otherwise along the specified axis. Defaults to None. Returns: Tensor, array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. Raises: ValueError: if axis is out of range. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> import numpy as np >>> from mindspore import Tensor >>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32")) >>> print(a.argmax()) 5 """ # P.Argmax only supports float x = x.astype(mstype.float32) if axis is None: x = ravel(x) axis = 0 else: axis = check_axis_in_range_const(axis, F.rank(x)) return P.Argmax(axis)(x)
[ "def", "argmax", "(", "x", ",", "axis", "=", "None", ")", ":", "# P.Argmax only supports float", "x", "=", "x", ".", "astype", "(", "mstype", ".", "float32", ")", "if", "axis", "is", "None", ":", "x", "=", "ravel", "(", "x", ")", "axis", "=", "0", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parse/standard_method.py#L434-L467
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/config/expandlibs.py
python
ExpandArgs.__init__
(self, args)
Creates a clone of the |args| list and performs file expansion on each item it contains
Creates a clone of the |args| list and performs file expansion on each item it contains
[ "Creates", "a", "clone", "of", "the", "|args|", "list", "and", "performs", "file", "expansion", "on", "each", "item", "it", "contains" ]
def __init__(self, args): '''Creates a clone of the |args| list and performs file expansion on each item it contains''' super(ExpandArgs, self).__init__() self._descs = set() for arg in args: self += self._expand(arg)
[ "def", "__init__", "(", "self", ",", "args", ")", ":", "super", "(", "ExpandArgs", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_descs", "=", "set", "(", ")", "for", "arg", "in", "args", ":", "self", "+=", "self", ".", "_expand", "(...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/config/expandlibs.py#L103-L109
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
configure.py
python
set_build_var
(environ_cp, var_name, query_item, option_name, enabled_by_default, bazel_config_name=None)
Set if query_item will be enabled for the build. Ask user if query_item will be enabled. Default is used if no input is given. Set subprocess environment variable and write to .bazelrc if enabled. Args: environ_cp: copy of the os.environ. var_name: string for name of environment variable, e.g. "TF_NEED_HDFS". query_item: string for feature related to the variable, e.g. "Hadoop File System". option_name: string for option to define in .bazelrc. enabled_by_default: boolean for default behavior. bazel_config_name: Name for Bazel --config argument to enable build feature.
Set if query_item will be enabled for the build.
[ "Set", "if", "query_item", "will", "be", "enabled", "for", "the", "build", "." ]
def set_build_var(environ_cp, var_name, query_item, option_name, enabled_by_default, bazel_config_name=None): """Set if query_item will be enabled for the build. Ask user if query_item will be enabled. Default is used if no input is given. Set subprocess environment variable and write to .bazelrc if enabled. Args: environ_cp: copy of the os.environ. var_name: string for name of environment variable, e.g. "TF_NEED_HDFS". query_item: string for feature related to the variable, e.g. "Hadoop File System". option_name: string for option to define in .bazelrc. enabled_by_default: boolean for default behavior. bazel_config_name: Name for Bazel --config argument to enable build feature. """ var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default))) environ_cp[var_name] = var if var == '1': write_to_bazelrc('build --define %s=true' % option_name) elif bazel_config_name is not None: # TODO(mikecase): Migrate all users of configure.py to use --config Bazel # options and not to set build configs through environment variables. write_to_bazelrc('build:%s --define %s=true' % (bazel_config_name, option_name))
[ "def", "set_build_var", "(", "environ_cp", ",", "var_name", ",", "query_item", ",", "option_name", ",", "enabled_by_default", ",", "bazel_config_name", "=", "None", ")", ":", "var", "=", "str", "(", "int", "(", "get_var", "(", "environ_cp", ",", "var_name", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/configure.py#L352-L377
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py
python
PrintTensor.__init__
(self, tensor_names, every_n=100, first_n=1)
Initializes a PrintTensor monitor. Args: tensor_names: `dict` of tag to tensor names or `iterable` of tensor names (strings). every_n: `int`, print every N steps. See `PrintN.` first_n: `int`, also print the first N steps. See `PrintN.`
Initializes a PrintTensor monitor.
[ "Initializes", "a", "PrintTensor", "monitor", "." ]
def __init__(self, tensor_names, every_n=100, first_n=1): """Initializes a PrintTensor monitor. Args: tensor_names: `dict` of tag to tensor names or `iterable` of tensor names (strings). every_n: `int`, print every N steps. See `PrintN.` first_n: `int`, also print the first N steps. See `PrintN.` """ super(PrintTensor, self).__init__(every_n, first_n) if not isinstance(tensor_names, dict): tensor_names = {item: item for item in tensor_names} self._tensor_names = tensor_names
[ "def", "__init__", "(", "self", ",", "tensor_names", ",", "every_n", "=", "100", ",", "first_n", "=", "1", ")", ":", "super", "(", "PrintTensor", ",", "self", ")", ".", "__init__", "(", "every_n", ",", "first_n", ")", "if", "not", "isinstance", "(", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py#L467-L479
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Build.py
python
BuildContext.symlink_as
(self, dest, src, **kw)
return tg
Creates a task generator to install a symlink:: def build(bld): bld.symlink_as('${PREFIX}/lib/libfoo.so', 'libfoo.so.1.2.3') :param dest: absolute path of the symlink :type dest: :py:class:`waflib.Node.Node` or string (absolute path) :param src: link contents, which is a relative or absolute path which may exist or not :type src: string :param env: configuration set for performing substitutions in dest :type env: :py:class:`waflib.ConfigSet.ConfigSet` :param add: add the task created to a build group - set ``False`` only if the installation task is created after the build has started :type add: bool :param postpone: execute the task immediately to perform the installation :type postpone: bool :param relative_trick: make the symlink relative (default: ``False``) :type relative_trick: bool
Creates a task generator to install a symlink::
[ "Creates", "a", "task", "generator", "to", "install", "a", "symlink", "::" ]
def symlink_as(self, dest, src, **kw): """ Creates a task generator to install a symlink:: def build(bld): bld.symlink_as('${PREFIX}/lib/libfoo.so', 'libfoo.so.1.2.3') :param dest: absolute path of the symlink :type dest: :py:class:`waflib.Node.Node` or string (absolute path) :param src: link contents, which is a relative or absolute path which may exist or not :type src: string :param env: configuration set for performing substitutions in dest :type env: :py:class:`waflib.ConfigSet.ConfigSet` :param add: add the task created to a build group - set ``False`` only if the installation task is created after the build has started :type add: bool :param postpone: execute the task immediately to perform the installation :type postpone: bool :param relative_trick: make the symlink relative (default: ``False``) :type relative_trick: bool """ assert(dest) tg = self(features='install_task', install_to=dest, install_from=src, **kw) tg.dest = tg.install_to tg.type = 'symlink_as' tg.link = src # TODO if add: self.add_to_group(tsk) if not kw.get('postpone', True): tg.post() return tg
[ "def", "symlink_as", "(", "self", ",", "dest", ",", "src", ",", "*", "*", "kw", ")", ":", "assert", "(", "dest", ")", "tg", "=", "self", "(", "features", "=", "'install_task'", ",", "install_to", "=", "dest", ",", "install_from", "=", "src", ",", "...
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Build.py#L895-L923
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/polynomial/hermite_e.py
python
hermeval2d
(x, y, c)
return c
Evaluate a 2-D HermiteE series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * He_i(x) * He_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points formed with pairs of corresponding values from `x` and `y`. See Also -------- hermeval, hermegrid2d, hermeval3d, hermegrid3d Notes ----- .. versionadded:: 1.7.0
Evaluate a 2-D HermiteE series at points (x, y).
[ "Evaluate", "a", "2", "-", "D", "HermiteE", "series", "at", "points", "(", "x", "y", ")", "." ]
def hermeval2d(x, y, c): """ Evaluate a 2-D HermiteE series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * He_i(x) * He_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points formed with pairs of corresponding values from `x` and `y`. See Also -------- hermeval, hermegrid2d, hermeval3d, hermegrid3d Notes ----- .. versionadded:: 1.7.0 """ try: x, y = np.array((x, y), copy=0) except Exception: raise ValueError('x, y are incompatible') c = hermeval(x, c) c = hermeval(y, c, tensor=False) return c
[ "def", "hermeval2d", "(", "x", ",", "y", ",", "c", ")", ":", "try", ":", "x", ",", "y", "=", "np", ".", "array", "(", "(", "x", ",", "y", ")", ",", "copy", "=", "0", ")", "except", "Exception", ":", "raise", "ValueError", "(", "'x, y are incomp...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/hermite_e.py#L946-L999
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/six.py
python
remove_move
(name)
Remove item from six.moves.
Remove item from six.moves.
[ "Remove", "item", "from", "six", ".", "moves", "." ]
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
[ "def", "remove_move", "(", "name", ")", ":", "try", ":", "delattr", "(", "_MovedItems", ",", "name", ")", "except", "AttributeError", ":", "try", ":", "del", "moves", ".", "__dict__", "[", "name", "]", "except", "KeyError", ":", "raise", "AttributeError", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/six.py#L1041-L1057
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
catalogResolvePublic
(pubID)
return ret
Try to lookup the catalog reference associated to a public ID
Try to lookup the catalog reference associated to a public ID
[ "Try", "to", "lookup", "the", "catalog", "reference", "associated", "to", "a", "public", "ID" ]
def catalogResolvePublic(pubID): """Try to lookup the catalog reference associated to a public ID """ ret = libxml2mod.xmlCatalogResolvePublic(pubID) return ret
[ "def", "catalogResolvePublic", "(", "pubID", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCatalogResolvePublic", "(", "pubID", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L161-L165