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
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
namePush
(ctxt, value)
return ret
Pushes a new element name on top of the name stack
Pushes a new element name on top of the name stack
[ "Pushes", "a", "new", "element", "name", "on", "top", "of", "the", "name", "stack" ]
def namePush(ctxt, value): """Pushes a new element name on top of the name stack """ if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o ret = libxml2mod.namePush(ctxt__o, value) return ret
[ "def", "namePush", "(", "ctxt", ",", "value", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "ret", "=", "libxml2mod", ".", "namePush", "(", "ctxt__o", ",", "value", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L1524-L1529
sonyxperiadev/WebGL
0299b38196f78c6d5f74bcf6fa312a3daee6de60
Tools/Scripts/webkitpy/style/checkers/cpp.py
python
_convert_to_lower_with_underscores
(text)
return text.lower()
Converts all text strings in camelCase or PascalCase to lowers with underscores.
Converts all text strings in camelCase or PascalCase to lowers with underscores.
[ "Converts", "all", "text", "strings", "in", "camelCase", "or", "PascalCase", "to", "lowers", "with", "underscores", "." ]
def _convert_to_lower_with_underscores(text): """Converts all text strings in camelCase or PascalCase to lowers with underscores.""" # First add underscores before any capital letter followed by a lower case letter # as long as it is in a word. # (This put an underscore before Password but not P and A in WPAPassword). text = sub(r'(?<=[A-Za-z0-9])([A-Z])(?=[a-z])', r'_\1', text) # Next add underscores before capitals at the end of words if it was # preceeded by lower case letter or number. # (This puts an underscore before A in isA but not A in CBA). text = sub(r'(?<=[a-z0-9])([A-Z])(?=\b)', r'_\1', text) # Next add underscores when you have a captial letter which is followed by a capital letter # but is not proceeded by one. (This puts an underscore before A in 'WordADay'). text = sub(r'(?<=[a-z0-9])([A-Z][A-Z_])', r'_\1', text) return text.lower()
[ "def", "_convert_to_lower_with_underscores", "(", "text", ")", ":", "# First add underscores before any capital letter followed by a lower case letter", "# as long as it is in a word.", "# (This put an underscore before Password but not P and A in WPAPassword).", "text", "=", "sub", "(", "r'(?<=[A-Za-z0-9])([A-Z])(?=[a-z])'", ",", "r'_\\1'", ",", "text", ")", "# Next add underscores before capitals at the end of words if it was", "# preceeded by lower case letter or number.", "# (This puts an underscore before A in isA but not A in CBA).", "text", "=", "sub", "(", "r'(?<=[a-z0-9])([A-Z])(?=\\b)'", ",", "r'_\\1'", ",", "text", ")", "# Next add underscores when you have a captial letter which is followed by a capital letter", "# but is not proceeded by one. (This puts an underscore before A in 'WordADay').", "text", "=", "sub", "(", "r'(?<=[a-z0-9])([A-Z][A-Z_])'", ",", "r'_\\1'", ",", "text", ")", "return", "text", ".", "lower", "(", ")" ]
https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/style/checkers/cpp.py#L222-L239
Harick1/caffe-yolo
eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3
scripts/cpp_lint.py
python
GetPreviousNonBlankLine
(clean_lines, linenum)
return ('', -1)
Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line.
Return the most recent non-blank line and its line number.
[ "Return", "the", "most", "recent", "non", "-", "blank", "line", "and", "its", "line", "number", "." ]
def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1)
[ "def", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", ":", "prevlinenum", "=", "linenum", "-", "1", "while", "prevlinenum", ">=", "0", ":", "prevline", "=", "clean_lines", ".", "elided", "[", "prevlinenum", "]", "if", "not", "IsBlankLine", "(", "prevline", ")", ":", "# if not a blank line...", "return", "(", "prevline", ",", "prevlinenum", ")", "prevlinenum", "-=", "1", "return", "(", "''", ",", "-", "1", ")" ]
https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/scripts/cpp_lint.py#L3046-L3066
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/random_ops.py
python
random_shuffle
(value, seed=None, name=None)
return gen_random_ops._random_shuffle( value, seed=seed1, seed2=seed2, name=name)
Randomly shuffles a tensor along its first dimension. The tensor is shuffled along dimension 0, such that each `value[j]` is mapped to one and only one `output[i]`. For example, a mapping that might occur for a 3x2 tensor is: ```python [[1, 2], [[5, 6], [3, 4], ==> [1, 2], [5, 6]] [3, 4]] ``` Args: value: A Tensor to be shuffled. seed: A Python integer. Used to create a random seed for the distribution. See @{tf.set_random_seed} for behavior. name: A name for the operation (optional). Returns: A tensor of same shape and type as `value`, shuffled along its first dimension.
Randomly shuffles a tensor along its first dimension.
[ "Randomly", "shuffles", "a", "tensor", "along", "its", "first", "dimension", "." ]
def random_shuffle(value, seed=None, name=None): """Randomly shuffles a tensor along its first dimension. The tensor is shuffled along dimension 0, such that each `value[j]` is mapped to one and only one `output[i]`. For example, a mapping that might occur for a 3x2 tensor is: ```python [[1, 2], [[5, 6], [3, 4], ==> [1, 2], [5, 6]] [3, 4]] ``` Args: value: A Tensor to be shuffled. seed: A Python integer. Used to create a random seed for the distribution. See @{tf.set_random_seed} for behavior. name: A name for the operation (optional). Returns: A tensor of same shape and type as `value`, shuffled along its first dimension. """ seed1, seed2 = random_seed.get_seed(seed) return gen_random_ops._random_shuffle( value, seed=seed1, seed2=seed2, name=name)
[ "def", "random_shuffle", "(", "value", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "seed1", ",", "seed2", "=", "random_seed", ".", "get_seed", "(", "seed", ")", "return", "gen_random_ops", ".", "_random_shuffle", "(", "value", ",", "seed", "=", "seed1", ",", "seed2", "=", "seed2", ",", "name", "=", "name", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/random_ops.py#L247-L274
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/debug.py
python
_init_ugly_crap
()
return tb_set_next
This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. Do not attempt to use this on non cpython interpreters
This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. Do not attempt to use this on non cpython interpreters
[ "This", "function", "implements", "a", "few", "ugly", "things", "so", "that", "we", "can", "patch", "the", "traceback", "objects", ".", "The", "function", "returned", "allows", "resetting", "tb_next", "on", "any", "python", "traceback", "object", ".", "Do", "not", "attempt", "to", "use", "this", "on", "non", "cpython", "interpreters" ]
def _init_ugly_crap(): """This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. Do not attempt to use this on non cpython interpreters """ import ctypes from types import TracebackType if PY2: # figure out size of _Py_ssize_t for Python 2: if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'): _Py_ssize_t = ctypes.c_int64 else: _Py_ssize_t = ctypes.c_int else: # platform ssize_t on Python 3 _Py_ssize_t = ctypes.c_ssize_t # regular python class _PyObject(ctypes.Structure): pass _PyObject._fields_ = [ ('ob_refcnt', _Py_ssize_t), ('ob_type', ctypes.POINTER(_PyObject)) ] # python with trace if hasattr(sys, 'getobjects'): class _PyObject(ctypes.Structure): pass _PyObject._fields_ = [ ('_ob_next', ctypes.POINTER(_PyObject)), ('_ob_prev', ctypes.POINTER(_PyObject)), ('ob_refcnt', _Py_ssize_t), ('ob_type', ctypes.POINTER(_PyObject)) ] class _Traceback(_PyObject): pass _Traceback._fields_ = [ ('tb_next', ctypes.POINTER(_Traceback)), ('tb_frame', ctypes.POINTER(_PyObject)), ('tb_lasti', ctypes.c_int), ('tb_lineno', ctypes.c_int) ] def tb_set_next(tb, next): """Set the tb_next attribute of a traceback object.""" if not (isinstance(tb, TracebackType) and (next is None or isinstance(next, TracebackType))): raise TypeError('tb_set_next arguments must be traceback objects') obj = _Traceback.from_address(id(tb)) if tb.tb_next is not None: old = _Traceback.from_address(id(tb.tb_next)) old.ob_refcnt -= 1 if next is None: obj.tb_next = ctypes.POINTER(_Traceback)() else: next = _Traceback.from_address(id(next)) next.ob_refcnt += 1 obj.tb_next = ctypes.pointer(next) return tb_set_next
[ "def", "_init_ugly_crap", "(", ")", ":", "import", "ctypes", "from", "types", "import", "TracebackType", "if", "PY2", ":", "# figure out size of _Py_ssize_t for Python 2:", "if", "hasattr", "(", "ctypes", ".", "pythonapi", ",", "'Py_InitModule4_64'", ")", ":", "_Py_ssize_t", "=", "ctypes", ".", "c_int64", "else", ":", "_Py_ssize_t", "=", "ctypes", ".", "c_int", "else", ":", "# platform ssize_t on Python 3", "_Py_ssize_t", "=", "ctypes", ".", "c_ssize_t", "# regular python", "class", "_PyObject", "(", "ctypes", ".", "Structure", ")", ":", "pass", "_PyObject", ".", "_fields_", "=", "[", "(", "'ob_refcnt'", ",", "_Py_ssize_t", ")", ",", "(", "'ob_type'", ",", "ctypes", ".", "POINTER", "(", "_PyObject", ")", ")", "]", "# python with trace", "if", "hasattr", "(", "sys", ",", "'getobjects'", ")", ":", "class", "_PyObject", "(", "ctypes", ".", "Structure", ")", ":", "pass", "_PyObject", ".", "_fields_", "=", "[", "(", "'_ob_next'", ",", "ctypes", ".", "POINTER", "(", "_PyObject", ")", ")", ",", "(", "'_ob_prev'", ",", "ctypes", ".", "POINTER", "(", "_PyObject", ")", ")", ",", "(", "'ob_refcnt'", ",", "_Py_ssize_t", ")", ",", "(", "'ob_type'", ",", "ctypes", ".", "POINTER", "(", "_PyObject", ")", ")", "]", "class", "_Traceback", "(", "_PyObject", ")", ":", "pass", "_Traceback", ".", "_fields_", "=", "[", "(", "'tb_next'", ",", "ctypes", ".", "POINTER", "(", "_Traceback", ")", ")", ",", "(", "'tb_frame'", ",", "ctypes", ".", "POINTER", "(", "_PyObject", ")", ")", ",", "(", "'tb_lasti'", ",", "ctypes", ".", "c_int", ")", ",", "(", "'tb_lineno'", ",", "ctypes", ".", "c_int", ")", "]", "def", "tb_set_next", "(", "tb", ",", "next", ")", ":", "\"\"\"Set the tb_next attribute of a traceback object.\"\"\"", "if", "not", "(", "isinstance", "(", "tb", ",", "TracebackType", ")", "and", "(", "next", "is", "None", "or", "isinstance", "(", "next", ",", "TracebackType", ")", ")", ")", ":", "raise", "TypeError", "(", "'tb_set_next arguments must be traceback objects'", ")", "obj", "=", "_Traceback", ".", "from_address", "(", "id", "(", "tb", ")", ")", "if", "tb", ".", "tb_next", "is", "not", "None", ":", "old", "=", "_Traceback", ".", "from_address", "(", "id", "(", "tb", ".", "tb_next", ")", ")", "old", ".", "ob_refcnt", "-=", "1", "if", "next", "is", "None", ":", "obj", ".", "tb_next", "=", "ctypes", ".", "POINTER", "(", "_Traceback", ")", "(", ")", "else", ":", "next", "=", "_Traceback", ".", "from_address", "(", "id", "(", "next", ")", ")", "next", ".", "ob_refcnt", "+=", "1", "obj", ".", "tb_next", "=", "ctypes", ".", "pointer", "(", "next", ")", "return", "tb_set_next" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/debug.py#L298-L361
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PyFileDialogAdapter.__init__
(self, *args, **kwargs)
__init__(self) -> PyFileDialogAdapter
__init__(self) -> PyFileDialogAdapter
[ "__init__", "(", "self", ")", "-", ">", "PyFileDialogAdapter" ]
def __init__(self, *args, **kwargs): """__init__(self) -> PyFileDialogAdapter""" _propgrid.PyFileDialogAdapter_swiginit(self,_propgrid.new_PyFileDialogAdapter(*args, **kwargs)) self._SetSelf(self); self._RegisterMethods()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_propgrid", ".", "PyFileDialogAdapter_swiginit", "(", "self", ",", "_propgrid", ".", "new_PyFileDialogAdapter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_SetSelf", "(", "self", ")", "self", ".", "_RegisterMethods", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3987-L3990
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TextCtrl.__init__
(self, *args, **kwargs)
__init__(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=TextCtrlNameStr) -> TextCtrl
__init__(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=TextCtrlNameStr) -> TextCtrl
[ "__init__", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "String", "value", "=", "EmptyString", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", "Validator", "validator", "=", "DefaultValidator", "String", "name", "=", "TextCtrlNameStr", ")", "-", ">", "TextCtrl" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=TextCtrlNameStr) -> TextCtrl """ _controls_.TextCtrl_swiginit(self,_controls_.new_TextCtrl(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_controls_", ".", "TextCtrl_swiginit", "(", "self", ",", "_controls_", ".", "new_TextCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L2012-L2020
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/AttentionDecoder.py
python
AttentionDecoder.hidden_layer_size
(self, hidden_layer_size)
Sets the size of the hidden layer.
Sets the size of the hidden layer.
[ "Sets", "the", "size", "of", "the", "hidden", "layer", "." ]
def hidden_layer_size(self, hidden_layer_size): """Sets the size of the hidden layer. """ self._internal.set_hidden_layer_size(int(hidden_layer_size))
[ "def", "hidden_layer_size", "(", "self", ",", "hidden_layer_size", ")", ":", "self", ".", "_internal", ".", "set_hidden_layer_size", "(", "int", "(", "hidden_layer_size", ")", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/AttentionDecoder.py#L131-L134
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/generic.py
python
NDFrame.__delitem__
(self, key)
Delete item
Delete item
[ "Delete", "item" ]
def __delitem__(self, key): """ Delete item """ deleted = False maybe_shortcut = False if hasattr(self, 'columns') and isinstance(self.columns, MultiIndex): try: maybe_shortcut = key not in self.columns._engine except TypeError: pass if maybe_shortcut: # Allow shorthand to delete all columns whose first len(key) # elements match key: if not isinstance(key, tuple): key = (key, ) for col in self.columns: if isinstance(col, tuple) and col[:len(key)] == key: del self[col] deleted = True if not deleted: # If the above loop ran and didn't delete anything because # there was no match, this call should raise the appropriate # exception: self._data.delete(key) # delete from the caches try: del self._item_cache[key] except KeyError: pass
[ "def", "__delitem__", "(", "self", ",", "key", ")", ":", "deleted", "=", "False", "maybe_shortcut", "=", "False", "if", "hasattr", "(", "self", ",", "'columns'", ")", "and", "isinstance", "(", "self", ".", "columns", ",", "MultiIndex", ")", ":", "try", ":", "maybe_shortcut", "=", "key", "not", "in", "self", ".", "columns", ".", "_engine", "except", "TypeError", ":", "pass", "if", "maybe_shortcut", ":", "# Allow shorthand to delete all columns whose first len(key)", "# elements match key:", "if", "not", "isinstance", "(", "key", ",", "tuple", ")", ":", "key", "=", "(", "key", ",", ")", "for", "col", "in", "self", ".", "columns", ":", "if", "isinstance", "(", "col", ",", "tuple", ")", "and", "col", "[", ":", "len", "(", "key", ")", "]", "==", "key", ":", "del", "self", "[", "col", "]", "deleted", "=", "True", "if", "not", "deleted", ":", "# If the above loop ran and didn't delete anything because", "# there was no match, this call should raise the appropriate", "# exception:", "self", ".", "_data", ".", "delete", "(", "key", ")", "# delete from the caches", "try", ":", "del", "self", ".", "_item_cache", "[", "key", "]", "except", "KeyError", ":", "pass" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/generic.py#L3289-L3321
tkn-tub/ns3-gym
19bfe0a583e641142609939a090a09dfc63a095f
src/visualizer/visualizer/ipython_view.py
python
ConsoleView.showReturned
(self, text)
! Show returned text from last command and print new prompt. @param text: Text to show. @return none
! Show returned text from last command and print new prompt.
[ "!", "Show", "returned", "text", "from", "last", "command", "and", "print", "new", "prompt", "." ]
def showReturned(self, text): """! Show returned text from last command and print new prompt. @param text: Text to show. @return none """ GObject.idle_add(self._showReturned, text)
[ "def", "showReturned", "(", "self", ",", "text", ")", ":", "GObject", ".", "idle_add", "(", "self", ".", "_showReturned", ",", "text", ")" ]
https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/src/visualizer/visualizer/ipython_view.py#L480-L487
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/lldb/lldbCheckExpect.py
python
unwrap
(s)
return s
Strip non-essential character sequences from a string. >>> unwrap('(String) value = "42\\\\n"') '42' >>> unwrap('(Int) $R0 = 42') '42' >>> unwrap('\\\\"foo\\"') 'foo' >>> unwrap('foo\\nbar') 'foo\\nbar' >>> unwrap(' foo ') 'foo'
Strip non-essential character sequences from a string.
[ "Strip", "non", "-", "essential", "character", "sequences", "from", "a", "string", "." ]
def unwrap(s): ''' Strip non-essential character sequences from a string. >>> unwrap('(String) value = "42\\\\n"') '42' >>> unwrap('(Int) $R0 = 42') '42' >>> unwrap('\\\\"foo\\"') 'foo' >>> unwrap('foo\\nbar') 'foo\\nbar' >>> unwrap(' foo ') 'foo' ''' s = s[s.find('=') + 1:] s = s.lstrip(' "') s = s.rstrip('"') if s.endswith('\\n'): s = s[:-2] if s.endswith('\\"'): s = s[:-2] if s.startswith('\\"'): s = s[2:] s = s.replace('\\n', '\n') s = s.strip() return s
[ "def", "unwrap", "(", "s", ")", ":", "s", "=", "s", "[", "s", ".", "find", "(", "'='", ")", "+", "1", ":", "]", "s", "=", "s", ".", "lstrip", "(", "' \"'", ")", "s", "=", "s", ".", "rstrip", "(", "'\"'", ")", "if", "s", ".", "endswith", "(", "'\\\\n'", ")", ":", "s", "=", "s", "[", ":", "-", "2", "]", "if", "s", ".", "endswith", "(", "'\\\\\"'", ")", ":", "s", "=", "s", "[", ":", "-", "2", "]", "if", "s", ".", "startswith", "(", "'\\\\\"'", ")", ":", "s", "=", "s", "[", "2", ":", "]", "s", "=", "s", ".", "replace", "(", "'\\\\n'", ",", "'\\n'", ")", "s", "=", "s", ".", "strip", "(", ")", "return", "s" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/lldb/lldbCheckExpect.py#L27-L53
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py
python
Image.tell
(self)
return 0
Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. :returns: Frame number, starting with 0.
Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
[ "Returns", "the", "current", "frame", "number", ".", "See", ":", "py", ":", "meth", ":", "~PIL", ".", "Image", ".", "Image", ".", "seek", "." ]
def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. :returns: Frame number, starting with 0. """ return 0
[ "def", "tell", "(", "self", ")", ":", "return", "0" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py#L2222-L2228
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/driver.py
python
Stream._add_signal
(self, signal)
Add a signal that corresponds to an async task.
Add a signal that corresponds to an async task.
[ "Add", "a", "signal", "that", "corresponds", "to", "an", "async", "task", "." ]
def _add_signal(self, signal): """ Add a signal that corresponds to an async task. """ # XXX: too many pending signals seem to cause async copy to hang if len(self._signals) > 100: self._sync(50) self._signals.append(signal)
[ "def", "_add_signal", "(", "self", ",", "signal", ")", ":", "# XXX: too many pending signals seem to cause async copy to hang", "if", "len", "(", "self", ".", "_signals", ")", ">", "100", ":", "self", ".", "_sync", "(", "50", ")", "self", ".", "_signals", ".", "append", "(", "signal", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/driver.py#L1352-L1359
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
vendor/pybind11/tools/clang/cindex.py
python
Cursor.is_virtual_method
(self)
return conf.lib.clang_CXXMethod_isVirtual(self)
Returns True if the cursor refers to a C++ member function or member function template that is declared 'virtual'.
Returns True if the cursor refers to a C++ member function or member function template that is declared 'virtual'.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "member", "function", "or", "member", "function", "template", "that", "is", "declared", "virtual", "." ]
def is_virtual_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared 'virtual'. """ return conf.lib.clang_CXXMethod_isVirtual(self)
[ "def", "is_virtual_method", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXMethod_isVirtual", "(", "self", ")" ]
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L1365-L1369
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/util/response.py
python
is_fp_closed
(obj)
Checks whether a given file-like object is closed. :param obj: The file-like object to check.
[]
def is_fp_closed(obj): """ Checks whether a given file-like object is closed. :param obj: The file-like object to check. """ try: # Check `isclosed()` first, in case Python3 doesn't set `closed`. # GH Issue #928 return obj.isclosed() except AttributeError: pass try: # Check via the official file-like-object way. return obj.closed except AttributeError: pass try: # Check if the object is a container for another file-like object that # gets released on exhaustion (e.g. HTTPResponse). return obj.fp is None except AttributeError: pass raise ValueError("Unable to determine whether fp is closed.")
[ "def", "is_fp_closed", "(", "obj", ")", ":", "try", ":", "# Check `isclosed()` first, in case Python3 doesn't set `closed`.", "# GH Issue #928", "return", "obj", ".", "isclosed", "(", ")", "except", "AttributeError", ":", "pass", "try", ":", "# Check via the official file-like-object way.", "return", "obj", ".", "closed", "except", "AttributeError", ":", "pass", "try", ":", "# Check if the object is a container for another file-like object that", "# gets released on exhaustion (e.g. HTTPResponse).", "return", "obj", ".", "fp", "is", "None", "except", "AttributeError", ":", "pass", "raise", "ValueError", "(", "\"Unable to determine whether fp is closed.\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/util/response.py#L17-L73
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Wrapping/Python/paraview/simple.py
python
AssignLookupTable
(arrayInfo, lutName, rangeOveride=[])
return True
Assign a lookup table to an array by lookup table name. `arrayInfo` is the information object for the array. The array name and its range is determined using the info object provided. `lutName` is the name for the transfer function preset. `rangeOveride` is provided as the range to use instead of the range of the array determined using the `arrayInfo`. Example usage:: track = GetAnimationTrack("Center", 0, sphere) or arrayInfo = source.PointData["Temperature"] AssignLookupTable(arrayInfo, "Cool to Warm")
Assign a lookup table to an array by lookup table name.
[ "Assign", "a", "lookup", "table", "to", "an", "array", "by", "lookup", "table", "name", "." ]
def AssignLookupTable(arrayInfo, lutName, rangeOveride=[]): """Assign a lookup table to an array by lookup table name. `arrayInfo` is the information object for the array. The array name and its range is determined using the info object provided. `lutName` is the name for the transfer function preset. `rangeOveride` is provided as the range to use instead of the range of the array determined using the `arrayInfo`. Example usage:: track = GetAnimationTrack("Center", 0, sphere) or arrayInfo = source.PointData["Temperature"] AssignLookupTable(arrayInfo, "Cool to Warm") """ # If the named LUT is not in the presets, see if it was one that was removed and # substitute it with the backwards compatibility helper presets = servermanager.vtkSMTransferFunctionPresets.GetInstance() reverse = False if not presets.HasPreset(lutName): (lutName, reverse) = paraview._backwardscompatibilityhelper.lookupTableUpdate(lutName) # If no alternate LUT exists, raise an exception if not presets.HasPreset(lutName): raise RuntimeError("no preset with name `%s` present", lutName) # Preset found. Apply it. lut = GetColorTransferFunction(arrayInfo.Name) if not lut.ApplyPreset(lutName): return False if rangeOveride: lut.RescaleTransferFunction(rangeOveride) # Reverse if necessary for backwards compatibility if reverse: lut.InvertTransferFunction() return True
[ "def", "AssignLookupTable", "(", "arrayInfo", ",", "lutName", ",", "rangeOveride", "=", "[", "]", ")", ":", "# If the named LUT is not in the presets, see if it was one that was removed and", "# substitute it with the backwards compatibility helper", "presets", "=", "servermanager", ".", "vtkSMTransferFunctionPresets", ".", "GetInstance", "(", ")", "reverse", "=", "False", "if", "not", "presets", ".", "HasPreset", "(", "lutName", ")", ":", "(", "lutName", ",", "reverse", ")", "=", "paraview", ".", "_backwardscompatibilityhelper", ".", "lookupTableUpdate", "(", "lutName", ")", "# If no alternate LUT exists, raise an exception", "if", "not", "presets", ".", "HasPreset", "(", "lutName", ")", ":", "raise", "RuntimeError", "(", "\"no preset with name `%s` present\"", ",", "lutName", ")", "# Preset found. Apply it.", "lut", "=", "GetColorTransferFunction", "(", "arrayInfo", ".", "Name", ")", "if", "not", "lut", ".", "ApplyPreset", "(", "lutName", ")", ":", "return", "False", "if", "rangeOveride", ":", "lut", ".", "RescaleTransferFunction", "(", "rangeOveride", ")", "# Reverse if necessary for backwards compatibility", "if", "reverse", ":", "lut", ".", "InvertTransferFunction", "(", ")", "return", "True" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/simple.py#L1904-L1946
kungfu-origin/kungfu
90c84b2b590855654cb9a6395ed050e0f7763512
core/deps/SQLiteCpp-2.3.0/cpplint.py
python
_FunctionState.End
(self)
Stop analyzing function body.
Stop analyzing function body.
[ "Stop", "analyzing", "function", "body", "." ]
def End(self): """Stop analyzing function body.""" self.in_a_function = False
[ "def", "End", "(", "self", ")", ":", "self", ".", "in_a_function", "=", "False" ]
https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L852-L854
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/generator/analyzer.py
python
TargetCalculator._supplied_target_names_no_all
(self)
return result
Returns the supplied test targets without 'all'.
Returns the supplied test targets without 'all'.
[ "Returns", "the", "supplied", "test", "targets", "without", "all", "." ]
def _supplied_target_names_no_all(self): """Returns the supplied test targets without 'all'.""" result = self._supplied_target_names() result.discard('all') return result
[ "def", "_supplied_target_names_no_all", "(", "self", ")", ":", "result", "=", "self", ".", "_supplied_target_names", "(", ")", "result", ".", "discard", "(", "'all'", ")", "return", "result" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/generator/analyzer.py#L616-L620
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
docs/sphinxext/mantiddoc/directives/interface.py
python
InterfaceDirective._insert_screenshot_link
(self, picture, align=None, width=None)
Outputs an image link with a custom :class: style. The filename is extracted from the path given and then a relative link to the directory specified by the SCREENSHOTS_DIR environment variable from the root source directory is formed. Args: picture (Screenshot): A Screenshot object align: The alignment to use, None for block, "left" or "right" for flowing width: The width to use (in pixels, defaults to width of screenshot)
Outputs an image link with a custom :class: style. The filename is extracted from the path given and then a relative link to the directory specified by the SCREENSHOTS_DIR environment variable from the root source directory is formed.
[ "Outputs", "an", "image", "link", "with", "a", "custom", ":", "class", ":", "style", ".", "The", "filename", "is", "extracted", "from", "the", "path", "given", "and", "then", "a", "relative", "link", "to", "the", "directory", "specified", "by", "the", "SCREENSHOTS_DIR", "environment", "variable", "from", "the", "root", "source", "directory", "is", "formed", "." ]
def _insert_screenshot_link(self, picture, align=None, width=None): """ Outputs an image link with a custom :class: style. The filename is extracted from the path given and then a relative link to the directory specified by the SCREENSHOTS_DIR environment variable from the root source directory is formed. Args: picture (Screenshot): A Screenshot object align: The alignment to use, None for block, "left" or "right" for flowing width: The width to use (in pixels, defaults to width of screenshot) """ env = self.state.document.settings.env # Sphinx assumes that an absolute path is actually relative to the directory containing the # conf.py file and a relative path is relative to the directory where the current rst file # is located. if picture: screenshots_dir, filename = os.path.split(picture.imgpath) if width is None: # No width provided, use screenshot width width = picture.width # relative path to image rel_path = os.path.relpath(screenshots_dir, env.srcdir) # This is a href link so is expected to be in unix style rel_path = rel_path.replace("\\", "/") # stick a "/" as the first character so Sphinx computes relative location from source directory path = "/" + rel_path + "/" + filename caption = "" else: # use stock not found image path = "/images/ImageNotFound.png" width = 200 caption = "Enable screenshots using DOCS_SCREENSHOTS in CMake" if align is not None: self.add_rst(f".. figure:: {path}\n" f" :class: screenshot\n" f" :width: {width}px\n" f" :align: {align}\n\n" f" {caption}\n\n") else: self.add_rst(f".. figure:: {path}\n" f" :class: screenshot\n" f" :width: {width}px\n\n" f" {caption}\n\n")
[ "def", "_insert_screenshot_link", "(", "self", ",", "picture", ",", "align", "=", "None", ",", "width", "=", "None", ")", ":", "env", "=", "self", ".", "state", ".", "document", ".", "settings", ".", "env", "# Sphinx assumes that an absolute path is actually relative to the directory containing the", "# conf.py file and a relative path is relative to the directory where the current rst file", "# is located.", "if", "picture", ":", "screenshots_dir", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "picture", ".", "imgpath", ")", "if", "width", "is", "None", ":", "# No width provided, use screenshot width", "width", "=", "picture", ".", "width", "# relative path to image", "rel_path", "=", "os", ".", "path", ".", "relpath", "(", "screenshots_dir", ",", "env", ".", "srcdir", ")", "# This is a href link so is expected to be in unix style", "rel_path", "=", "rel_path", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "# stick a \"/\" as the first character so Sphinx computes relative location from source directory", "path", "=", "\"/\"", "+", "rel_path", "+", "\"/\"", "+", "filename", "caption", "=", "\"\"", "else", ":", "# use stock not found image", "path", "=", "\"/images/ImageNotFound.png\"", "width", "=", "200", "caption", "=", "\"Enable screenshots using DOCS_SCREENSHOTS in CMake\"", "if", "align", "is", "not", "None", ":", "self", ".", "add_rst", "(", "f\".. figure:: {path}\\n\"", "f\" :class: screenshot\\n\"", "f\" :width: {width}px\\n\"", "f\" :align: {align}\\n\\n\"", "f\" {caption}\\n\\n\"", ")", "else", ":", "self", ".", "add_rst", "(", "f\".. figure:: {path}\\n\"", "f\" :class: screenshot\\n\"", "f\" :width: {width}px\\n\\n\"", "f\" {caption}\\n\\n\"", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/docs/sphinxext/mantiddoc/directives/interface.py#L71-L118
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/py/py/_path/local.py
python
LocalPath.mtime
(self)
return self.stat().mtime
return last modification time of the path.
return last modification time of the path.
[ "return", "last", "modification", "time", "of", "the", "path", "." ]
def mtime(self): """ return last modification time of the path. """ return self.stat().mtime
[ "def", "mtime", "(", "self", ")", ":", "return", "self", ".", "stat", "(", ")", ".", "mtime" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/py/py/_path/local.py#L417-L419
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/google/protobuf/internal/python_message.py
python
_IsPresent
(item)
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
[ "Given", "a", "(", "FieldDescriptor", "value", ")", "tuple", "from", "_fields", "return", "true", "if", "the", "value", "should", "be", "included", "in", "the", "list", "returned", "by", "ListFields", "()", "." ]
def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return item[1]._is_present_in_parent else: return True
[ "def", "_IsPresent", "(", "item", ")", ":", "if", "item", "[", "0", "]", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "return", "bool", "(", "item", "[", "1", "]", ")", "elif", "item", "[", "0", "]", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "return", "item", "[", "1", "]", ".", "_is_present_in_parent", "else", ":", "return", "True" ]
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/internal/python_message.py#L806-L815
HKUST-Aerial-Robotics/Fast-Planner
2ddd7793eecd573dbb5b47e2c985aa06606df3cf
uav_simulator/Utils/pose_utils/build/devel/_setup_util.py
python
_rollback_env_variable
(environ, name, subfolder)
return new_value if value_modified else None
For each catkin workspace in CMAKE_PREFIX_PATH remove the first entry from env[NAME] matching workspace + subfolder. :param subfolder: str '' or subfoldername that may start with '/' :returns: the updated value of the environment variable.
For each catkin workspace in CMAKE_PREFIX_PATH remove the first entry from env[NAME] matching workspace + subfolder.
[ "For", "each", "catkin", "workspace", "in", "CMAKE_PREFIX_PATH", "remove", "the", "first", "entry", "from", "env", "[", "NAME", "]", "matching", "workspace", "+", "subfolder", "." ]
def _rollback_env_variable(environ, name, subfolder): ''' For each catkin workspace in CMAKE_PREFIX_PATH remove the first entry from env[NAME] matching workspace + subfolder. :param subfolder: str '' or subfoldername that may start with '/' :returns: the updated value of the environment variable. ''' value = environ[name] if name in environ else '' env_paths = [path for path in value.split(os.pathsep) if path] value_modified = False if subfolder: if subfolder.startswith(os.path.sep) or (os.path.altsep and subfolder.startswith(os.path.altsep)): subfolder = subfolder[1:] if subfolder.endswith(os.path.sep) or (os.path.altsep and subfolder.endswith(os.path.altsep)): subfolder = subfolder[:-1] for ws_path in _get_workspaces(environ, include_fuerte=True, include_non_existing=True): path_to_find = os.path.join(ws_path, subfolder) if subfolder else ws_path path_to_remove = None for env_path in env_paths: env_path_clean = env_path[:-1] if env_path and env_path[-1] in [os.path.sep, os.path.altsep] else env_path if env_path_clean == path_to_find: path_to_remove = env_path break if path_to_remove: env_paths.remove(path_to_remove) value_modified = True new_value = os.pathsep.join(env_paths) return new_value if value_modified else None
[ "def", "_rollback_env_variable", "(", "environ", ",", "name", ",", "subfolder", ")", ":", "value", "=", "environ", "[", "name", "]", "if", "name", "in", "environ", "else", "''", "env_paths", "=", "[", "path", "for", "path", "in", "value", ".", "split", "(", "os", ".", "pathsep", ")", "if", "path", "]", "value_modified", "=", "False", "if", "subfolder", ":", "if", "subfolder", ".", "startswith", "(", "os", ".", "path", ".", "sep", ")", "or", "(", "os", ".", "path", ".", "altsep", "and", "subfolder", ".", "startswith", "(", "os", ".", "path", ".", "altsep", ")", ")", ":", "subfolder", "=", "subfolder", "[", "1", ":", "]", "if", "subfolder", ".", "endswith", "(", "os", ".", "path", ".", "sep", ")", "or", "(", "os", ".", "path", ".", "altsep", "and", "subfolder", ".", "endswith", "(", "os", ".", "path", ".", "altsep", ")", ")", ":", "subfolder", "=", "subfolder", "[", ":", "-", "1", "]", "for", "ws_path", "in", "_get_workspaces", "(", "environ", ",", "include_fuerte", "=", "True", ",", "include_non_existing", "=", "True", ")", ":", "path_to_find", "=", "os", ".", "path", ".", "join", "(", "ws_path", ",", "subfolder", ")", "if", "subfolder", "else", "ws_path", "path_to_remove", "=", "None", "for", "env_path", "in", "env_paths", ":", "env_path_clean", "=", "env_path", "[", ":", "-", "1", "]", "if", "env_path", "and", "env_path", "[", "-", "1", "]", "in", "[", "os", ".", "path", ".", "sep", ",", "os", ".", "path", ".", "altsep", "]", "else", "env_path", "if", "env_path_clean", "==", "path_to_find", ":", "path_to_remove", "=", "env_path", "break", "if", "path_to_remove", ":", "env_paths", ".", "remove", "(", "path_to_remove", ")", "value_modified", "=", "True", "new_value", "=", "os", ".", "pathsep", ".", "join", "(", "env_paths", ")", "return", "new_value", "if", "value_modified", "else", "None" ]
https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/pose_utils/build/devel/_setup_util.py#L84-L111
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBSourceManager.DisplaySourceLinesWithLineNumbersAndColumn
(self, file, line, column, context_before, context_after, current_line_cstr, s)
return _lldb.SBSourceManager_DisplaySourceLinesWithLineNumbersAndColumn(self, file, line, column, context_before, context_after, current_line_cstr, s)
DisplaySourceLinesWithLineNumbersAndColumn(SBSourceManager self, SBFileSpec file, uint32_t line, uint32_t column, uint32_t context_before, uint32_t context_after, char const * current_line_cstr, SBStream s) -> size_t
DisplaySourceLinesWithLineNumbersAndColumn(SBSourceManager self, SBFileSpec file, uint32_t line, uint32_t column, uint32_t context_before, uint32_t context_after, char const * current_line_cstr, SBStream s) -> size_t
[ "DisplaySourceLinesWithLineNumbersAndColumn", "(", "SBSourceManager", "self", "SBFileSpec", "file", "uint32_t", "line", "uint32_t", "column", "uint32_t", "context_before", "uint32_t", "context_after", "char", "const", "*", "current_line_cstr", "SBStream", "s", ")", "-", ">", "size_t" ]
def DisplaySourceLinesWithLineNumbersAndColumn(self, file, line, column, context_before, context_after, current_line_cstr, s): """DisplaySourceLinesWithLineNumbersAndColumn(SBSourceManager self, SBFileSpec file, uint32_t line, uint32_t column, uint32_t context_before, uint32_t context_after, char const * current_line_cstr, SBStream s) -> size_t""" return _lldb.SBSourceManager_DisplaySourceLinesWithLineNumbersAndColumn(self, file, line, column, context_before, context_after, current_line_cstr, s)
[ "def", "DisplaySourceLinesWithLineNumbersAndColumn", "(", "self", ",", "file", ",", "line", ",", "column", ",", "context_before", ",", "context_after", ",", "current_line_cstr", ",", "s", ")", ":", "return", "_lldb", ".", "SBSourceManager_DisplaySourceLinesWithLineNumbersAndColumn", "(", "self", ",", "file", ",", "line", ",", "column", ",", "context_before", ",", "context_after", ",", "current_line_cstr", ",", "s", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L9452-L9454
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/inv_grad_ds.py
python
_inv_grad_ds_tbe
()
return
InvGrad TBE register
InvGrad TBE register
[ "InvGrad", "TBE", "register" ]
def _inv_grad_ds_tbe(): """InvGrad TBE register""" return
[ "def", "_inv_grad_ds_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/inv_grad_ds.py#L39-L41
robotology/yarp
3d6e3f258db7755a3c44dd1e62c303cc36c49a8f
extern/thrift/thrift/lib/py/src/transport/TZlibTransport.py
python
TZlibTransport.flush
(self)
Flush any queued up data in the write buffer and ensure the compression buffer is flushed out to the underlying transport
Flush any queued up data in the write buffer and ensure the compression buffer is flushed out to the underlying transport
[ "Flush", "any", "queued", "up", "data", "in", "the", "write", "buffer", "and", "ensure", "the", "compression", "buffer", "is", "flushed", "out", "to", "the", "underlying", "transport" ]
def flush(self): """Flush any queued up data in the write buffer and ensure the compression buffer is flushed out to the underlying transport """ wout = self.__wbuf.getvalue() if len(wout) > 0: zbuf = self._zcomp_write.compress(wout) self.bytes_out += len(wout) self.bytes_out_comp += len(zbuf) else: zbuf = '' ztail = self._zcomp_write.flush(zlib.Z_SYNC_FLUSH) self.bytes_out_comp += len(ztail) if (len(zbuf) + len(ztail)) > 0: self.__wbuf = BufferIO() self.__trans.write(zbuf + ztail) self.__trans.flush()
[ "def", "flush", "(", "self", ")", ":", "wout", "=", "self", ".", "__wbuf", ".", "getvalue", "(", ")", "if", "len", "(", "wout", ")", ">", "0", ":", "zbuf", "=", "self", ".", "_zcomp_write", ".", "compress", "(", "wout", ")", "self", ".", "bytes_out", "+=", "len", "(", "wout", ")", "self", ".", "bytes_out_comp", "+=", "len", "(", "zbuf", ")", "else", ":", "zbuf", "=", "''", "ztail", "=", "self", ".", "_zcomp_write", ".", "flush", "(", "zlib", ".", "Z_SYNC_FLUSH", ")", "self", ".", "bytes_out_comp", "+=", "len", "(", "ztail", ")", "if", "(", "len", "(", "zbuf", ")", "+", "len", "(", "ztail", ")", ")", ">", "0", ":", "self", ".", "__wbuf", "=", "BufferIO", "(", ")", "self", ".", "__trans", ".", "write", "(", "zbuf", "+", "ztail", ")", "self", ".", "__trans", ".", "flush", "(", ")" ]
https://github.com/robotology/yarp/blob/3d6e3f258db7755a3c44dd1e62c303cc36c49a8f/extern/thrift/thrift/lib/py/src/transport/TZlibTransport.py#L217-L233
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/docview.py
python
DocManager.CreateView
(self, doc, flags=0)
Creates a new view for the given document. If more than one view is allowed for the document (by virtue of multiple templates mentioning the same document type), a choice of view is presented to the user.
Creates a new view for the given document. If more than one view is allowed for the document (by virtue of multiple templates mentioning the same document type), a choice of view is presented to the user.
[ "Creates", "a", "new", "view", "for", "the", "given", "document", ".", "If", "more", "than", "one", "view", "is", "allowed", "for", "the", "document", "(", "by", "virtue", "of", "multiple", "templates", "mentioning", "the", "same", "document", "type", ")", "a", "choice", "of", "view", "is", "presented", "to", "the", "user", "." ]
def CreateView(self, doc, flags=0): """ Creates a new view for the given document. If more than one view is allowed for the document (by virtue of multiple templates mentioning the same document type), a choice of view is presented to the user. """ templates = [] for temp in self._templates: if temp.IsVisible(): if temp.GetDocumentName() == doc.GetDocumentName(): templates.append(temp) if len(templates) == 0: return None if len(templates) == 1: temp = templates[0] view = temp.CreateView(doc, flags) if view: view.SetViewName(temp.GetViewName()) return view temp = SelectViewType(templates) if temp: view = temp.CreateView(doc, flags) if view: view.SetViewName(temp.GetViewName()) return view else: return None
[ "def", "CreateView", "(", "self", ",", "doc", ",", "flags", "=", "0", ")", ":", "templates", "=", "[", "]", "for", "temp", "in", "self", ".", "_templates", ":", "if", "temp", ".", "IsVisible", "(", ")", ":", "if", "temp", ".", "GetDocumentName", "(", ")", "==", "doc", ".", "GetDocumentName", "(", ")", ":", "templates", ".", "append", "(", "temp", ")", "if", "len", "(", "templates", ")", "==", "0", ":", "return", "None", "if", "len", "(", "templates", ")", "==", "1", ":", "temp", "=", "templates", "[", "0", "]", "view", "=", "temp", ".", "CreateView", "(", "doc", ",", "flags", ")", "if", "view", ":", "view", ".", "SetViewName", "(", "temp", ".", "GetViewName", "(", ")", ")", "return", "view", "temp", "=", "SelectViewType", "(", "templates", ")", "if", "temp", ":", "view", "=", "temp", ".", "CreateView", "(", "doc", ",", "flags", ")", "if", "view", ":", "view", ".", "SetViewName", "(", "temp", ".", "GetViewName", "(", ")", ")", "return", "view", "else", ":", "return", "None" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L1934-L1962
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/filters.py
python
make_attrgetter
(environment, attribute, postprocess=None)
return attrgetter
Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers.
Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers.
[ "Returns", "a", "callable", "that", "looks", "up", "the", "given", "attribute", "from", "a", "passed", "object", "with", "the", "rules", "of", "the", "environment", ".", "Dots", "are", "allowed", "to", "access", "attributes", "of", "attributes", ".", "Integer", "parts", "in", "paths", "are", "looked", "up", "as", "integers", "." ]
def make_attrgetter(environment, attribute, postprocess=None): """Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers. """ if attribute is None: attribute = [] elif isinstance(attribute, string_types): attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')] else: attribute = [attribute] def attrgetter(item): for part in attribute: item = environment.getitem(item, part) if postprocess is not None: item = postprocess(item) return item return attrgetter
[ "def", "make_attrgetter", "(", "environment", ",", "attribute", ",", "postprocess", "=", "None", ")", ":", "if", "attribute", "is", "None", ":", "attribute", "=", "[", "]", "elif", "isinstance", "(", "attribute", ",", "string_types", ")", ":", "attribute", "=", "[", "int", "(", "x", ")", "if", "x", ".", "isdigit", "(", ")", "else", "x", "for", "x", "in", "attribute", ".", "split", "(", "'.'", ")", "]", "else", ":", "attribute", "=", "[", "attribute", "]", "def", "attrgetter", "(", "item", ")", ":", "for", "part", "in", "attribute", ":", "item", "=", "environment", ".", "getitem", "(", "item", ",", "part", ")", "if", "postprocess", "is", "not", "None", ":", "item", "=", "postprocess", "(", "item", ")", "return", "item", "return", "attrgetter" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/filters.py#L62-L84
etternagame/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
extern/crashpad/crashpad/build/ios/setup_ios_gn.py
python
FindGn
()
return None
Returns absolute path to gn binary looking at the PATH env variable.
Returns absolute path to gn binary looking at the PATH env variable.
[ "Returns", "absolute", "path", "to", "gn", "binary", "looking", "at", "the", "PATH", "env", "variable", "." ]
def FindGn(): '''Returns absolute path to gn binary looking at the PATH env variable.''' for path in os.environ['PATH'].split(os.path.pathsep): gn_path = os.path.join(path, 'gn') if os.path.isfile(gn_path) and os.access(gn_path, os.X_OK): return gn_path return None
[ "def", "FindGn", "(", ")", ":", "for", "path", "in", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "os", ".", "path", ".", "pathsep", ")", ":", "gn_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'gn'", ")", "if", "os", ".", "path", ".", "isfile", "(", "gn_path", ")", "and", "os", ".", "access", "(", "gn_path", ",", "os", ".", "X_OK", ")", ":", "return", "gn_path", "return", "None" ]
https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/crashpad/crashpad/build/ios/setup_ios_gn.py#L248-L254
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Menu.InsertItem
(*args, **kwargs)
return _core_.Menu_InsertItem(*args, **kwargs)
InsertItem(self, size_t pos, MenuItem item) -> MenuItem
InsertItem(self, size_t pos, MenuItem item) -> MenuItem
[ "InsertItem", "(", "self", "size_t", "pos", "MenuItem", "item", ")", "-", ">", "MenuItem" ]
def InsertItem(*args, **kwargs): """InsertItem(self, size_t pos, MenuItem item) -> MenuItem""" return _core_.Menu_InsertItem(*args, **kwargs)
[ "def", "InsertItem", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_InsertItem", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12037-L12039
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CorelliPowderCalibrationCreate.py
python
insert_bank_numbers
(input_workspace: Union[str, Workspace2D], grouping_workspace: Union[str, WorkspaceGroup])
r""" Label each spectra according to each bank number @param input_workspace : workpace with spectra to be labelled @param grouping_workspace : group workspace has the group ID (bank number) for each pixel
r""" Label each spectra according to each bank number
[ "r", "Label", "each", "spectra", "according", "to", "each", "bank", "number" ]
def insert_bank_numbers(input_workspace: Union[str, Workspace2D], grouping_workspace: Union[str, WorkspaceGroup]): r""" Label each spectra according to each bank number @param input_workspace : workpace with spectra to be labelled @param grouping_workspace : group workspace has the group ID (bank number) for each pixel """ input_handle, grouping_handle = mtd[str(input_workspace)], mtd[str(grouping_workspace)] group_ids = sorted(list(set(grouping_handle.extractY().flatten()))) assert input_handle.getNumberHistograms() == len(group_ids) axis = TextAxis.create(len(group_ids)) [axis.setLabel(index, f'bank{group_id}') for index, group_id in enumerate(group_ids)] input_handle.replaceAxis(1, axis)
[ "def", "insert_bank_numbers", "(", "input_workspace", ":", "Union", "[", "str", ",", "Workspace2D", "]", ",", "grouping_workspace", ":", "Union", "[", "str", ",", "WorkspaceGroup", "]", ")", ":", "input_handle", ",", "grouping_handle", "=", "mtd", "[", "str", "(", "input_workspace", ")", "]", ",", "mtd", "[", "str", "(", "grouping_workspace", ")", "]", "group_ids", "=", "sorted", "(", "list", "(", "set", "(", "grouping_handle", ".", "extractY", "(", ")", ".", "flatten", "(", ")", ")", ")", ")", "assert", "input_handle", ".", "getNumberHistograms", "(", ")", "==", "len", "(", "group_ids", ")", "axis", "=", "TextAxis", ".", "create", "(", "len", "(", "group_ids", ")", ")", "[", "axis", ".", "setLabel", "(", "index", ",", "f'bank{group_id}'", ")", "for", "index", ",", "group_id", "in", "enumerate", "(", "group_ids", ")", "]", "input_handle", ".", "replaceAxis", "(", "1", ",", "axis", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CorelliPowderCalibrationCreate.py#L60-L73
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Text.image_create
(self, index, cnf={}, **kw)
return self.tk.call( self._w, "image", "create", index, *self._options(cnf, kw))
Create an embedded image at INDEX.
Create an embedded image at INDEX.
[ "Create", "an", "embedded", "image", "at", "INDEX", "." ]
def image_create(self, index, cnf={}, **kw): """Create an embedded image at INDEX.""" return self.tk.call( self._w, "image", "create", index, *self._options(cnf, kw))
[ "def", "image_create", "(", "self", ",", "index", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"image\"", ",", "\"create\"", ",", "index", ",", "*", "self", ".", "_options", "(", "cnf", ",", "kw", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3258-L3262
xenia-project/xenia
9b1fdac98665ac091b9660a5d0fbb259ed79e578
third_party/google-styleguide/cpplint/cpplint.py
python
ExpectingFunctionArgs
(clean_lines, linenum)
return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or (linenum >= 2 and (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', clean_lines.elided[linenum - 1]) or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', clean_lines.elided[linenum - 2]) or Search(r'\bstd::m?function\s*\<\s*$', clean_lines.elided[linenum - 1]))))
Checks whether where function type arguments are expected. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if the line at 'linenum' is inside something that expects arguments of function types.
Checks whether where function type arguments are expected.
[ "Checks", "whether", "where", "function", "type", "arguments", "are", "expected", "." ]
def ExpectingFunctionArgs(clean_lines, linenum): """Checks whether where function type arguments are expected. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if the line at 'linenum' is inside something that expects arguments of function types. """ line = clean_lines.elided[linenum] return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or (linenum >= 2 and (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', clean_lines.elided[linenum - 1]) or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', clean_lines.elided[linenum - 2]) or Search(r'\bstd::m?function\s*\<\s*$', clean_lines.elided[linenum - 1]))))
[ "def", "ExpectingFunctionArgs", "(", "clean_lines", ",", "linenum", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "return", "(", "Match", "(", "r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('", ",", "line", ")", "or", "(", "linenum", ">=", "2", "and", "(", "Match", "(", "r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\((?:\\S+,)?\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "or", "Match", "(", "r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\(\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "2", "]", ")", "or", "Search", "(", "r'\\bstd::m?function\\s*\\<\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", ")", ")", ")" ]
https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L4985-L5004
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
examples/python/dict_utils.py
python
LookupDictionary.get_value
(self, key, fail_value=None)
return fail_value
find the value given a key
find the value given a key
[ "find", "the", "value", "given", "a", "key" ]
def get_value(self, key, fail_value=None): """find the value given a key""" if key in self: return self[key] return fail_value
[ "def", "get_value", "(", "self", ",", "key", ",", "fail_value", "=", "None", ")", ":", "if", "key", "in", "self", ":", "return", "self", "[", "key", "]", "return", "fail_value" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/examples/python/dict_utils.py#L25-L29
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/pypack/altgraph/Graph.py
python
Graph.inc_degree
(self, node)
return len(self.inc_edges(node))
Returns the number of incoming edges
Returns the number of incoming edges
[ "Returns", "the", "number", "of", "incoming", "edges" ]
def inc_degree(self, node): """ Returns the number of incoming edges """ return len(self.inc_edges(node))
[ "def", "inc_degree", "(", "self", ",", "node", ")", ":", "return", "len", "(", "self", ".", "inc_edges", "(", "node", ")", ")" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/altgraph/Graph.py#L347-L351
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/json_schema_compiler/h_generator.py
python
_Generator._GenerateFunctionResults
(self, callback)
return c
Generates namespace for passing a function's result back.
Generates namespace for passing a function's result back.
[ "Generates", "namespace", "for", "passing", "a", "function", "s", "result", "back", "." ]
def _GenerateFunctionResults(self, callback): """Generates namespace for passing a function's result back. """ c = Code() (c.Append('namespace Results {') .Append() .Concat(self._GenerateCreateCallbackArguments(callback)) .Append('} // namespace Results') ) return c
[ "def", "_GenerateFunctionResults", "(", "self", ",", "callback", ")", ":", "c", "=", "Code", "(", ")", "(", "c", ".", "Append", "(", "'namespace Results {'", ")", ".", "Append", "(", ")", ".", "Concat", "(", "self", ".", "_GenerateCreateCallbackArguments", "(", "callback", ")", ")", ".", "Append", "(", "'} // namespace Results'", ")", ")", "return", "c" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/h_generator.py#L384-L393
plumonito/dtslam
5994bb9cf7a11981b830370db206bceb654c085d
3rdparty/opencv-git/3rdparty/jinja2/ext.py
python
babel_extract
(fileobj, keywords, comment_tags, options)
Babel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best preceeding comment that begins with one of the keywords. For best results, make sure to not have more than one gettext call in one line of code and the matching comment in the same line or the line before. .. versionchanged:: 2.5.1 The `newstyle_gettext` flag can be set to `True` to enable newstyle gettext calls. .. versionchanged:: 2.7 A `silent` option can now be provided. If set to `False` template syntax errors are propagated instead of being ignored. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results. :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples. (comments will be empty currently)
Babel extraction method for Jinja templates.
[ "Babel", "extraction", "method", "for", "Jinja", "templates", "." ]
def babel_extract(fileobj, keywords, comment_tags, options): """Babel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best preceeding comment that begins with one of the keywords. For best results, make sure to not have more than one gettext call in one line of code and the matching comment in the same line or the line before. .. versionchanged:: 2.5.1 The `newstyle_gettext` flag can be set to `True` to enable newstyle gettext calls. .. versionchanged:: 2.7 A `silent` option can now be provided. If set to `False` template syntax errors are propagated instead of being ignored. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results. :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples. (comments will be empty currently) """ extensions = set() for extension in options.get('extensions', '').split(','): extension = extension.strip() if not extension: continue extensions.add(import_string(extension)) if InternationalizationExtension not in extensions: extensions.add(InternationalizationExtension) def getbool(options, key, default=False): return options.get(key, str(default)).lower() in \ ('1', 'on', 'yes', 'true') silent = getbool(options, 'silent', True) environment = Environment( options.get('block_start_string', BLOCK_START_STRING), options.get('block_end_string', BLOCK_END_STRING), options.get('variable_start_string', VARIABLE_START_STRING), options.get('variable_end_string', VARIABLE_END_STRING), options.get('comment_start_string', COMMENT_START_STRING), options.get('comment_end_string', COMMENT_END_STRING), options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX, options.get('line_comment_prefix') or LINE_COMMENT_PREFIX, getbool(options, 'trim_blocks', TRIM_BLOCKS), getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS), NEWLINE_SEQUENCE, getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE), frozenset(extensions), cache_size=0, auto_reload=False ) if getbool(options, 'newstyle_gettext'): environment.newstyle_gettext = True source = fileobj.read().decode(options.get('encoding', 'utf-8')) try: node = environment.parse(source) tokens = list(environment.lex(environment.preprocess(source))) except TemplateSyntaxError as e: if not silent: raise # skip templates with syntax errors return finder = _CommentFinder(tokens, comment_tags) for lineno, func, message in extract_from_ast(node, keywords): yield lineno, func, message, finder.find_comments(lineno)
[ "def", "babel_extract", "(", "fileobj", ",", "keywords", ",", "comment_tags", ",", "options", ")", ":", "extensions", "=", "set", "(", ")", "for", "extension", "in", "options", ".", "get", "(", "'extensions'", ",", "''", ")", ".", "split", "(", "','", ")", ":", "extension", "=", "extension", ".", "strip", "(", ")", "if", "not", "extension", ":", "continue", "extensions", ".", "add", "(", "import_string", "(", "extension", ")", ")", "if", "InternationalizationExtension", "not", "in", "extensions", ":", "extensions", ".", "add", "(", "InternationalizationExtension", ")", "def", "getbool", "(", "options", ",", "key", ",", "default", "=", "False", ")", ":", "return", "options", ".", "get", "(", "key", ",", "str", "(", "default", ")", ")", ".", "lower", "(", ")", "in", "(", "'1'", ",", "'on'", ",", "'yes'", ",", "'true'", ")", "silent", "=", "getbool", "(", "options", ",", "'silent'", ",", "True", ")", "environment", "=", "Environment", "(", "options", ".", "get", "(", "'block_start_string'", ",", "BLOCK_START_STRING", ")", ",", "options", ".", "get", "(", "'block_end_string'", ",", "BLOCK_END_STRING", ")", ",", "options", ".", "get", "(", "'variable_start_string'", ",", "VARIABLE_START_STRING", ")", ",", "options", ".", "get", "(", "'variable_end_string'", ",", "VARIABLE_END_STRING", ")", ",", "options", ".", "get", "(", "'comment_start_string'", ",", "COMMENT_START_STRING", ")", ",", "options", ".", "get", "(", "'comment_end_string'", ",", "COMMENT_END_STRING", ")", ",", "options", ".", "get", "(", "'line_statement_prefix'", ")", "or", "LINE_STATEMENT_PREFIX", ",", "options", ".", "get", "(", "'line_comment_prefix'", ")", "or", "LINE_COMMENT_PREFIX", ",", "getbool", "(", "options", ",", "'trim_blocks'", ",", "TRIM_BLOCKS", ")", ",", "getbool", "(", "options", ",", "'lstrip_blocks'", ",", "LSTRIP_BLOCKS", ")", ",", "NEWLINE_SEQUENCE", ",", "getbool", "(", "options", ",", "'keep_trailing_newline'", ",", "KEEP_TRAILING_NEWLINE", ")", ",", "frozenset", "(", "extensions", ")", ",", "cache_size", "=", "0", ",", "auto_reload", "=", "False", ")", "if", "getbool", "(", "options", ",", "'newstyle_gettext'", ")", ":", "environment", ".", "newstyle_gettext", "=", "True", "source", "=", "fileobj", ".", "read", "(", ")", ".", "decode", "(", "options", ".", "get", "(", "'encoding'", ",", "'utf-8'", ")", ")", "try", ":", "node", "=", "environment", ".", "parse", "(", "source", ")", "tokens", "=", "list", "(", "environment", ".", "lex", "(", "environment", ".", "preprocess", "(", "source", ")", ")", ")", "except", "TemplateSyntaxError", "as", "e", ":", "if", "not", "silent", ":", "raise", "# skip templates with syntax errors", "return", "finder", "=", "_CommentFinder", "(", "tokens", ",", "comment_tags", ")", "for", "lineno", ",", "func", ",", "message", "in", "extract_from_ast", "(", "node", ",", "keywords", ")", ":", "yield", "lineno", ",", "func", ",", "message", ",", "finder", ".", "find_comments", "(", "lineno", ")" ]
https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/ext.py#L553-L628
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
resources/web/server/simulation_server.py
python
ClientWebSocketHandler.next_available_port
(self)
Return a port number available for a new Webots WebSocket server.
Return a port number available for a new Webots WebSocket server.
[ "Return", "a", "port", "number", "available", "for", "a", "new", "Webots", "WebSocket", "server", "." ]
def next_available_port(self): """Return a port number available for a new Webots WebSocket server.""" port = config['port'] + 1 while True: if port > config['port'] + config['maxConnections']: logging.error("Too many open connections (>" + str(config['maxConnections']) + ")") return 0 found = False for client in self.clients: if port == client.streaming_server_port: found = True break if found: port += 1 continue # try to create a server to make sure that port is available testSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: testSocket.bind(('0.0.0.0', port)) found = True except socket.error as e: found = False if e.errno == errno.EADDRINUSE: logging.info('Port ' + str(port) + ' is already in use.') else: # something else raised the socket.error exception logging.info('Port ' + str(port) + ': ' + e) finally: testSocket.close() if found: return port port += 1
[ "def", "next_available_port", "(", "self", ")", ":", "port", "=", "config", "[", "'port'", "]", "+", "1", "while", "True", ":", "if", "port", ">", "config", "[", "'port'", "]", "+", "config", "[", "'maxConnections'", "]", ":", "logging", ".", "error", "(", "\"Too many open connections (>\"", "+", "str", "(", "config", "[", "'maxConnections'", "]", ")", "+", "\")\"", ")", "return", "0", "found", "=", "False", "for", "client", "in", "self", ".", "clients", ":", "if", "port", "==", "client", ".", "streaming_server_port", ":", "found", "=", "True", "break", "if", "found", ":", "port", "+=", "1", "continue", "# try to create a server to make sure that port is available", "testSocket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "try", ":", "testSocket", ".", "bind", "(", "(", "'0.0.0.0'", ",", "port", ")", ")", "found", "=", "True", "except", "socket", ".", "error", "as", "e", ":", "found", "=", "False", "if", "e", ".", "errno", "==", "errno", ".", "EADDRINUSE", ":", "logging", ".", "info", "(", "'Port '", "+", "str", "(", "port", ")", "+", "' is already in use.'", ")", "else", ":", "# something else raised the socket.error exception", "logging", ".", "info", "(", "'Port '", "+", "str", "(", "port", ")", "+", "': '", "+", "e", ")", "finally", ":", "testSocket", ".", "close", "(", ")", "if", "found", ":", "return", "port", "port", "+=", "1" ]
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/resources/web/server/simulation_server.py#L369-L399
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
benchmarks/operator_benchmark/benchmark_utils.py
python
cross_product
(*inputs)
return (list(itertools.product(*inputs)))
Return a list of cartesian product of input iterables. For example, cross_product(A, B) returns ((x,y) for x in A for y in B).
Return a list of cartesian product of input iterables. For example, cross_product(A, B) returns ((x,y) for x in A for y in B).
[ "Return", "a", "list", "of", "cartesian", "product", "of", "input", "iterables", ".", "For", "example", "cross_product", "(", "A", "B", ")", "returns", "((", "x", "y", ")", "for", "x", "in", "A", "for", "y", "in", "B", ")", "." ]
def cross_product(*inputs): """ Return a list of cartesian product of input iterables. For example, cross_product(A, B) returns ((x,y) for x in A for y in B). """ return (list(itertools.product(*inputs)))
[ "def", "cross_product", "(", "*", "inputs", ")", ":", "return", "(", "list", "(", "itertools", ".", "product", "(", "*", "inputs", ")", ")", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/operator_benchmark/benchmark_utils.py#L60-L65
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/ElementalAnalysis/PeriodicTable/periodic_table.py
python
_ElementButton.leaveEvent
(self, e)
Emit a :attr:`sigElementLeave` signal and send a :class:`PeriodicTableItem` object
Emit a :attr:`sigElementLeave` signal and send a :class:`PeriodicTableItem` object
[ "Emit", "a", ":", "attr", ":", "sigElementLeave", "signal", "and", "send", "a", ":", "class", ":", "PeriodicTableItem", "object" ]
def leaveEvent(self, e): """Emit a :attr:`sigElementLeave` signal and send a :class:`PeriodicTableItem` object""" self.sigElementLeave.emit(self.item)
[ "def", "leaveEvent", "(", "self", ",", "e", ")", ":", "self", ".", "sigElementLeave", ".", "emit", "(", "self", ".", "item", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/ElementalAnalysis/PeriodicTable/periodic_table.py#L399-L402
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/ExodusViewer/plugins/OutputPlugin.py
python
OutputPlugin._callbackExportPython
(self)
Open dialog and write script.
Open dialog and write script.
[ "Open", "dialog", "and", "write", "script", "." ]
def _callbackExportPython(self): """ Open dialog and write script. """ dialog = QtWidgets.QFileDialog() dialog.setWindowTitle('Write Python Script') dialog.setNameFilter('Python Files (*.py)') dialog.setFileMode(QtWidgets.QFileDialog.AnyFile) dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog) if dialog.exec_() == QtWidgets.QDialog.Accepted: filename = str(dialog.selectedFiles()[0]) self.write.emit(filename)
[ "def", "_callbackExportPython", "(", "self", ")", ":", "dialog", "=", "QtWidgets", ".", "QFileDialog", "(", ")", "dialog", ".", "setWindowTitle", "(", "'Write Python Script'", ")", "dialog", ".", "setNameFilter", "(", "'Python Files (*.py)'", ")", "dialog", ".", "setFileMode", "(", "QtWidgets", ".", "QFileDialog", ".", "AnyFile", ")", "dialog", ".", "setAcceptMode", "(", "QtWidgets", ".", "QFileDialog", ".", "AcceptSave", ")", "dialog", ".", "setOption", "(", "QtWidgets", ".", "QFileDialog", ".", "DontUseNativeDialog", ")", "if", "dialog", ".", "exec_", "(", ")", "==", "QtWidgets", ".", "QDialog", ".", "Accepted", ":", "filename", "=", "str", "(", "dialog", ".", "selectedFiles", "(", ")", "[", "0", "]", ")", "self", ".", "write", ".", "emit", "(", "filename", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/OutputPlugin.py#L119-L132
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/backend.py
python
_scratch_graph
(graph=None)
Retrieve a shared and temporary func graph. The eager execution path lifts a subgraph from the keras global graph into a scratch graph in order to create a function. DistributionStrategies, in turn, constructs multiple functions as well as a final combined function. In order for that logic to work correctly, all of the functions need to be created on the same scratch FuncGraph. Args: graph: A graph to be used as the current scratch graph. If not set then a scratch graph will either be retrieved or created: Yields: The current scratch graph.
Retrieve a shared and temporary func graph.
[ "Retrieve", "a", "shared", "and", "temporary", "func", "graph", "." ]
def _scratch_graph(graph=None): """Retrieve a shared and temporary func graph. The eager execution path lifts a subgraph from the keras global graph into a scratch graph in order to create a function. DistributionStrategies, in turn, constructs multiple functions as well as a final combined function. In order for that logic to work correctly, all of the functions need to be created on the same scratch FuncGraph. Args: graph: A graph to be used as the current scratch graph. If not set then a scratch graph will either be retrieved or created: Yields: The current scratch graph. """ global _CURRENT_SCRATCH_GRAPH scratch_graph = getattr(_CURRENT_SCRATCH_GRAPH, 'graph', None) # If scratch graph and `graph` are both configured, they must match. if (scratch_graph is not None and graph is not None and scratch_graph is not graph): raise ValueError('Multiple scratch graphs specified.') if scratch_graph: yield scratch_graph return graph = graph or func_graph.FuncGraph('keras_scratch_graph') try: _CURRENT_SCRATCH_GRAPH.graph = graph yield graph finally: _CURRENT_SCRATCH_GRAPH.graph = None
[ "def", "_scratch_graph", "(", "graph", "=", "None", ")", ":", "global", "_CURRENT_SCRATCH_GRAPH", "scratch_graph", "=", "getattr", "(", "_CURRENT_SCRATCH_GRAPH", ",", "'graph'", ",", "None", ")", "# If scratch graph and `graph` are both configured, they must match.", "if", "(", "scratch_graph", "is", "not", "None", "and", "graph", "is", "not", "None", "and", "scratch_graph", "is", "not", "graph", ")", ":", "raise", "ValueError", "(", "'Multiple scratch graphs specified.'", ")", "if", "scratch_graph", ":", "yield", "scratch_graph", "return", "graph", "=", "graph", "or", "func_graph", ".", "FuncGraph", "(", "'keras_scratch_graph'", ")", "try", ":", "_CURRENT_SCRATCH_GRAPH", ".", "graph", "=", "graph", "yield", "graph", "finally", ":", "_CURRENT_SCRATCH_GRAPH", ".", "graph", "=", "None" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L770-L802
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/html.py
python
HtmlContainerCell.SetAlignHor
(*args, **kwargs)
return _html.HtmlContainerCell_SetAlignHor(*args, **kwargs)
SetAlignHor(self, int al)
SetAlignHor(self, int al)
[ "SetAlignHor", "(", "self", "int", "al", ")" ]
def SetAlignHor(*args, **kwargs): """SetAlignHor(self, int al)""" return _html.HtmlContainerCell_SetAlignHor(*args, **kwargs)
[ "def", "SetAlignHor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlContainerCell_SetAlignHor", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L805-L807
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
libcxx/utils/gdb/libcxx/printers.py
python
StdStringPrinter._get_short_size
(self, short_field, short_size)
Short size depends on both endianness and a compile-time define.
Short size depends on both endianness and a compile-time define.
[ "Short", "size", "depends", "on", "both", "endianness", "and", "a", "compile", "-", "time", "define", "." ]
def _get_short_size(self, short_field, short_size): """Short size depends on both endianness and a compile-time define.""" # If the padding field is present after all this indirection, then string # was compiled with _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT defined. field = short_field.type.fields()[1].type.fields()[0] libcpp_abi_alternate_string_layout = field.name and "__padding" in field.name # This logical structure closely follows the original code (which is clearer # in C++). Keep them parallel to make them easier to compare. if libcpp_abi_alternate_string_layout: if _libcpp_big_endian: return short_size >> 1 else: return short_size elif _libcpp_big_endian: return short_size else: return short_size >> 1
[ "def", "_get_short_size", "(", "self", ",", "short_field", ",", "short_size", ")", ":", "# If the padding field is present after all this indirection, then string", "# was compiled with _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT defined.", "field", "=", "short_field", ".", "type", ".", "fields", "(", ")", "[", "1", "]", ".", "type", ".", "fields", "(", ")", "[", "0", "]", "libcpp_abi_alternate_string_layout", "=", "field", ".", "name", "and", "\"__padding\"", "in", "field", ".", "name", "# This logical structure closely follows the original code (which is clearer", "# in C++). Keep them parallel to make them easier to compare.", "if", "libcpp_abi_alternate_string_layout", ":", "if", "_libcpp_big_endian", ":", "return", "short_size", ">>", "1", "else", ":", "return", "short_size", "elif", "_libcpp_big_endian", ":", "return", "short_size", "else", ":", "return", "short_size", ">>", "1" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/libcxx/utils/gdb/libcxx/printers.py#L197-L215
SeisSol/SeisSol
955fbeb8c5d40d3363a2da0edc611259aebe1653
preprocessing/science/kinematic_models/Yoffe.py
python
C1
(t, ts, tr)
return ( (0.5 * t + 0.25 * tr) * sqrt(t * (tr - t)) + (t * tr - tr * tr) * asin(sqrt(t / tr)) - 0.75 * tr * tr * atan(sqrt((tr - t) / t)) )
C1 to C6 are analytical functions used for building the regularized Yoffe function
C1 to C6 are analytical functions used for building the regularized Yoffe function
[ "C1", "to", "C6", "are", "analytical", "functions", "used", "for", "building", "the", "regularized", "Yoffe", "function" ]
def C1(t, ts, tr): """ C1 to C6 are analytical functions used for building the regularized Yoffe function """ return ( (0.5 * t + 0.25 * tr) * sqrt(t * (tr - t)) + (t * tr - tr * tr) * asin(sqrt(t / tr)) - 0.75 * tr * tr * atan(sqrt((tr - t) / t)) )
[ "def", "C1", "(", "t", ",", "ts", ",", "tr", ")", ":", "return", "(", "(", "0.5", "*", "t", "+", "0.25", "*", "tr", ")", "*", "sqrt", "(", "t", "*", "(", "tr", "-", "t", ")", ")", "+", "(", "t", "*", "tr", "-", "tr", "*", "tr", ")", "*", "asin", "(", "sqrt", "(", "t", "/", "tr", ")", ")", "-", "0.75", "*", "tr", "*", "tr", "*", "atan", "(", "sqrt", "(", "(", "tr", "-", "t", ")", "/", "t", ")", ")", ")" ]
https://github.com/SeisSol/SeisSol/blob/955fbeb8c5d40d3363a2da0edc611259aebe1653/preprocessing/science/kinematic_models/Yoffe.py#L4-L12
balint256/gr-baz
937834ce3520b730277328d8e0cdebb3f2b1aafc
python/doa_compass_plotter.py
python
compass_plotter._draw_profile
(self)
Draw the profiles into the compass rose as polygons.
Draw the profiles into the compass rose as polygons.
[ "Draw", "the", "profiles", "into", "the", "compass", "rose", "as", "polygons", "." ]
def _draw_profile(self): """ Draw the profiles into the compass rose as polygons. """ self._setup_antialiasing() GL.glLineWidth(PROFILE_LINE_WIDTH) #scale with matrix transform GL.glPushMatrix() GL.glScalef(self.width, self.height, 1) GL.glTranslatef(0.5, 0.5, 0) GL.glScalef(CIRCLE_RAD, CIRCLE_RAD, 1) GL.glRotatef(-90, 0, 0, 1) #draw the profile for key in sorted(self._profiles.keys()): color_spec, fill, profile = self._profiles[key] if not profile: continue points = polar2rect(*profile) GL.glColor3f(*color_spec) GL.glVertexPointerf(points) GL.glDrawArrays(fill and GL.GL_POLYGON or GL.GL_LINE_LOOP, 0, len(points)) GL.glPopMatrix()
[ "def", "_draw_profile", "(", "self", ")", ":", "self", ".", "_setup_antialiasing", "(", ")", "GL", ".", "glLineWidth", "(", "PROFILE_LINE_WIDTH", ")", "#scale with matrix transform", "GL", ".", "glPushMatrix", "(", ")", "GL", ".", "glScalef", "(", "self", ".", "width", ",", "self", ".", "height", ",", "1", ")", "GL", ".", "glTranslatef", "(", "0.5", ",", "0.5", ",", "0", ")", "GL", ".", "glScalef", "(", "CIRCLE_RAD", ",", "CIRCLE_RAD", ",", "1", ")", "GL", ".", "glRotatef", "(", "-", "90", ",", "0", ",", "0", ",", "1", ")", "#draw the profile", "for", "key", "in", "sorted", "(", "self", ".", "_profiles", ".", "keys", "(", ")", ")", ":", "color_spec", ",", "fill", ",", "profile", "=", "self", ".", "_profiles", "[", "key", "]", "if", "not", "profile", ":", "continue", "points", "=", "polar2rect", "(", "*", "profile", ")", "GL", ".", "glColor3f", "(", "*", "color_spec", ")", "GL", ".", "glVertexPointerf", "(", "points", ")", "GL", ".", "glDrawArrays", "(", "fill", "and", "GL", ".", "GL_POLYGON", "or", "GL", ".", "GL_LINE_LOOP", ",", "0", ",", "len", "(", "points", ")", ")", "GL", ".", "glPopMatrix", "(", ")" ]
https://github.com/balint256/gr-baz/blob/937834ce3520b730277328d8e0cdebb3f2b1aafc/python/doa_compass_plotter.py#L119-L139
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_parser.py
python
p_targs_lparen_tsyms_rparen
(p)
targs : LPAREN tsyms RPAREN
targs : LPAREN tsyms RPAREN
[ "targs", ":", "LPAREN", "tsyms", "RPAREN" ]
def p_targs_lparen_tsyms_rparen(p): 'targs : LPAREN tsyms RPAREN' p[0] = p[2]
[ "def", "p_targs_lparen_tsyms_rparen", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "2", "]" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L1353-L1355
jiaxiang-wu/quantized-cnn
4d020e17026df90e40111d219e3eb74e0afb1588
cpplint.py
python
CheckForFunctionLengths
(filename, clean_lines, linenum, function_state, error)
Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found.
Reports for long function bodies.
[ "Reports", "for", "long", "function", "bodies", "." ]
def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count()
[ "def", "CheckForFunctionLengths", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "function_state", ",", "error", ")", ":", "lines", "=", "clean_lines", ".", "lines", "line", "=", "lines", "[", "linenum", "]", "joined_line", "=", "''", "starting_func", "=", "False", "regexp", "=", "r'(\\w(\\w|::|\\*|\\&|\\s)*)\\('", "# decls * & space::name( ...", "match_result", "=", "Match", "(", "regexp", ",", "line", ")", "if", "match_result", ":", "# If the name is all caps and underscores, figure it's a macro and", "# ignore it, unless it's TEST or TEST_F.", "function_name", "=", "match_result", ".", "group", "(", "1", ")", ".", "split", "(", ")", "[", "-", "1", "]", "if", "function_name", "==", "'TEST'", "or", "function_name", "==", "'TEST_F'", "or", "(", "not", "Match", "(", "r'[A-Z_]+$'", ",", "function_name", ")", ")", ":", "starting_func", "=", "True", "if", "starting_func", ":", "body_found", "=", "False", "for", "start_linenum", "in", "xrange", "(", "linenum", ",", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "start_line", "=", "lines", "[", "start_linenum", "]", "joined_line", "+=", "' '", "+", "start_line", ".", "lstrip", "(", ")", "if", "Search", "(", "r'(;|})'", ",", "start_line", ")", ":", "# Declarations and trivial functions", "body_found", "=", "True", "break", "# ... ignore", "elif", "Search", "(", "r'{'", ",", "start_line", ")", ":", "body_found", "=", "True", "function", "=", "Search", "(", "r'((\\w|:)*)\\('", ",", "line", ")", ".", "group", "(", "1", ")", "if", "Match", "(", "r'TEST'", ",", "function", ")", ":", "# Handle TEST... macros", "parameter_regexp", "=", "Search", "(", "r'(\\(.*\\))'", ",", "joined_line", ")", "if", "parameter_regexp", ":", "# Ignore bad syntax", "function", "+=", "parameter_regexp", ".", "group", "(", "1", ")", "else", ":", "function", "+=", "'()'", "function_state", ".", "Begin", "(", "function", ")", "break", "if", "not", "body_found", ":", "# No body for the function (or evidence of a non-function) was found.", "error", "(", "filename", ",", "linenum", ",", "'readability/fn_size'", ",", "5", ",", "'Lint failed to find start of function body.'", ")", "elif", "Match", "(", "r'^\\}\\s*$'", ",", "line", ")", ":", "# function end", "function_state", ".", "Check", "(", "error", ",", "filename", ",", "linenum", ")", "function_state", ".", "End", "(", ")", "elif", "not", "Match", "(", "r'^\\s*$'", ",", "line", ")", ":", "function_state", ".", "Count", "(", ")" ]
https://github.com/jiaxiang-wu/quantized-cnn/blob/4d020e17026df90e40111d219e3eb74e0afb1588/cpplint.py#L2842-L2907
numworks/epsilon
8952d2f8b1de1c3f064eec8ffcea804c5594ba4c
build/device/usb/util.py
python
get_string
(dev, index, langid = None)
r"""Retrieve a string descriptor from the device. dev is the Device object which the string will be read from. index is the string descriptor index and langid is the Language ID of the descriptor. If langid is omitted, the string descriptor of the first Language ID will be returned. Zero is never the index of a real string. The USB spec allows a device to use zero in a string index field to indicate that no string is provided. So the caller does not have to treat that case specially, this function returns None if passed an index of zero, and generates no traffic to the device. The return value is the unicode string present in the descriptor, or None if the requested index was zero.
r"""Retrieve a string descriptor from the device.
[ "r", "Retrieve", "a", "string", "descriptor", "from", "the", "device", "." ]
def get_string(dev, index, langid = None): r"""Retrieve a string descriptor from the device. dev is the Device object which the string will be read from. index is the string descriptor index and langid is the Language ID of the descriptor. If langid is omitted, the string descriptor of the first Language ID will be returned. Zero is never the index of a real string. The USB spec allows a device to use zero in a string index field to indicate that no string is provided. So the caller does not have to treat that case specially, this function returns None if passed an index of zero, and generates no traffic to the device. The return value is the unicode string present in the descriptor, or None if the requested index was zero. """ if 0 == index: return None from usb.control import get_descriptor if langid is None: langids = dev.langids if 0 == len(langids): raise ValueError("The device has no langid" " (permission issue, no string descriptors supported or device error)") langid = langids[0] buf = get_descriptor( dev, 254, # maximum even length DESC_TYPE_STRING, index, langid ) blen = buf[0] & 0xfe # should be even, ignore any trailing byte (see #154) if hexversion >= 0x03020000: return buf[2:blen].tobytes().decode('utf-16-le') else: return buf[2:blen].tostring().decode('utf-16-le')
[ "def", "get_string", "(", "dev", ",", "index", ",", "langid", "=", "None", ")", ":", "if", "0", "==", "index", ":", "return", "None", "from", "usb", ".", "control", "import", "get_descriptor", "if", "langid", "is", "None", ":", "langids", "=", "dev", ".", "langids", "if", "0", "==", "len", "(", "langids", ")", ":", "raise", "ValueError", "(", "\"The device has no langid\"", "\" (permission issue, no string descriptors supported or device error)\"", ")", "langid", "=", "langids", "[", "0", "]", "buf", "=", "get_descriptor", "(", "dev", ",", "254", ",", "# maximum even length", "DESC_TYPE_STRING", ",", "index", ",", "langid", ")", "blen", "=", "buf", "[", "0", "]", "&", "0xfe", "# should be even, ignore any trailing byte (see #154)", "if", "hexversion", ">=", "0x03020000", ":", "return", "buf", "[", "2", ":", "blen", "]", ".", "tobytes", "(", ")", ".", "decode", "(", "'utf-16-le'", ")", "else", ":", "return", "buf", "[", "2", ":", "blen", "]", ".", "tostring", "(", ")", ".", "decode", "(", "'utf-16-le'", ")" ]
https://github.com/numworks/epsilon/blob/8952d2f8b1de1c3f064eec8ffcea804c5594ba4c/build/device/usb/util.py#L287-L328
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/linalg/matfuncs.py
python
sinm
(A)
Compute the matrix sine. This routine uses expm to compute the matrix exponentials. Parameters ---------- A : (N, N) array_like Input array. Returns ------- sinm : (N, N) ndarray Matrix cosine of `A` Examples -------- >>> from scipy.linalg import expm, sinm, cosm Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta)) applied to a matrix: >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]]) >>> expm(1j*a) array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) >>> cosm(a) + 1j*sinm(a) array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
Compute the matrix sine.
[ "Compute", "the", "matrix", "sine", "." ]
def sinm(A): """ Compute the matrix sine. This routine uses expm to compute the matrix exponentials. Parameters ---------- A : (N, N) array_like Input array. Returns ------- sinm : (N, N) ndarray Matrix cosine of `A` Examples -------- >>> from scipy.linalg import expm, sinm, cosm Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta)) applied to a matrix: >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]]) >>> expm(1j*a) array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) >>> cosm(a) + 1j*sinm(a) array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) """ A = _asarray_square(A) if np.iscomplexobj(A): return -0.5j*(expm(1j*A) - expm(-1j*A)) else: return expm(1j*A).imag
[ "def", "sinm", "(", "A", ")", ":", "A", "=", "_asarray_square", "(", "A", ")", "if", "np", ".", "iscomplexobj", "(", "A", ")", ":", "return", "-", "0.5j", "*", "(", "expm", "(", "1j", "*", "A", ")", "-", "expm", "(", "-", "1j", "*", "A", ")", ")", "else", ":", "return", "expm", "(", "1j", "*", "A", ")", ".", "imag" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/linalg/matfuncs.py#L368-L404
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fastparquet/api.py
python
filter_out_cats
(rg, filters)
return False
According to the filters, should this row-group be excluded Considers the partitioning category applicable to this row-group Parameters ---------- rg: thrift RowGroup structure filters: list of 3-tuples Structure of each tuple: (column, op, value) where op is one of ['==', '!=', '<', '<=', '>', '>=', 'in', 'not in'] and value is appropriate for the column in question Returns ------- True or False
According to the filters, should this row-group be excluded
[ "According", "to", "the", "filters", "should", "this", "row", "-", "group", "be", "excluded" ]
def filter_out_cats(rg, filters): """ According to the filters, should this row-group be excluded Considers the partitioning category applicable to this row-group Parameters ---------- rg: thrift RowGroup structure filters: list of 3-tuples Structure of each tuple: (column, op, value) where op is one of ['==', '!=', '<', '<=', '>', '>=', 'in', 'not in'] and value is appropriate for the column in question Returns ------- True or False """ # TODO: fix for Drill if len(filters) == 0 or rg.columns[0].file_path is None: return False s = ex_from_sep('/') partitions = s.findall(rg.columns[0].file_path) pairs = [(p[0], p[1]) for p in partitions] for cat, v in pairs: app_filters = [f[1:] for f in filters if f[0] == cat] for op, val in app_filters: tstr = six.string_types + (six.text_type, ) if isinstance(val, tstr) or (isinstance(val, (tuple, list)) and all(isinstance(x, tstr) for x in val)): v0 = v else: v0 = val_to_num(v) if filter_val(op, val, v0, v0): return True return False
[ "def", "filter_out_cats", "(", "rg", ",", "filters", ")", ":", "# TODO: fix for Drill", "if", "len", "(", "filters", ")", "==", "0", "or", "rg", ".", "columns", "[", "0", "]", ".", "file_path", "is", "None", ":", "return", "False", "s", "=", "ex_from_sep", "(", "'/'", ")", "partitions", "=", "s", ".", "findall", "(", "rg", ".", "columns", "[", "0", "]", ".", "file_path", ")", "pairs", "=", "[", "(", "p", "[", "0", "]", ",", "p", "[", "1", "]", ")", "for", "p", "in", "partitions", "]", "for", "cat", ",", "v", "in", "pairs", ":", "app_filters", "=", "[", "f", "[", "1", ":", "]", "for", "f", "in", "filters", "if", "f", "[", "0", "]", "==", "cat", "]", "for", "op", ",", "val", "in", "app_filters", ":", "tstr", "=", "six", ".", "string_types", "+", "(", "six", ".", "text_type", ",", ")", "if", "isinstance", "(", "val", ",", "tstr", ")", "or", "(", "isinstance", "(", "val", ",", "(", "tuple", ",", "list", ")", ")", "and", "all", "(", "isinstance", "(", "x", ",", "tstr", ")", "for", "x", "in", "val", ")", ")", ":", "v0", "=", "v", "else", ":", "v0", "=", "val_to_num", "(", "v", ")", "if", "filter_val", "(", "op", ",", "val", ",", "v0", ",", "v0", ")", ":", "return", "True", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fastparquet/api.py#L803-L839
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/handlers.py
python
NTEventLogHandler.close
(self)
Clean up this handler. You can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the DLL name.
Clean up this handler.
[ "Clean", "up", "this", "handler", "." ]
def close(self): """ Clean up this handler. You can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the DLL name. """ #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype) logging.Handler.close(self)
[ "def", "close", "(", "self", ")", ":", "#self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)", "logging", ".", "Handler", ".", "close", "(", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/handlers.py#L1035-L1046
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/archive_util.py
python
_get_uid
(name)
return None
Returns an uid, given a user name.
Returns an uid, given a user name.
[ "Returns", "an", "uid", "given", "a", "user", "name", "." ]
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "def", "_get_uid", "(", "name", ")", ":", "if", "getpwnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getpwnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "is", "not", "None", ":", "return", "result", "[", "2", "]", "return", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/archive_util.py#L43-L53
floooh/oryol
eb08cffe1b1cb6b05ed14ec692bca9372cef064e
tools/texexport.py
python
toCubePVR
(srcDir, srcExt, dstFilename, format)
Generate a cube map and convert to PVR
Generate a cube map and convert to PVR
[ "Generate", "a", "cube", "map", "and", "convert", "to", "PVR" ]
def toCubePVR(srcDir, srcExt, dstFilename, format) : ''' Generate a cube map and convert to PVR ''' if format not in PVRFormats : error('invalid PVR texture format {}!'.format(format)) ensureDstDirectory() pvrTool = getToolsBinPath() + 'PVRTexToolCLI' srcFiles = ['posx', 'negx', 'posy', 'negy', 'posz', 'negz'] dstPath = TexDstDirectory + '/' + dstFilename print('=== toCubePVR: {}/{}/[posx,negx,posy,negy,posz,negz].{} => {}'.format(TexSrcDirectory, srcDir, srcExt, dstPath)) cmdLine = [pvrTool, '-i'] inputFiles = '' dirty = False for src in srcFiles : srcPath = TexSrcDirectory + '/' + srcDir + '/' + src + '.' + srcExt dirty |= needsExport(srcPath, dstPath) inputFiles += srcPath + ',' if not dirty: return inputFiles = inputFiles[:-1] cmdLine.append(inputFiles) cmdLine.append('-o') cmdLine.append(dstPath) cmdLine.append('-cube') cmdLine.append('-m') cmdLine.append('-mfilter') cmdLine.append('cubic') cmdLine.append('-f') cmdLine.append(format) subprocess.call(args=cmdLine)
[ "def", "toCubePVR", "(", "srcDir", ",", "srcExt", ",", "dstFilename", ",", "format", ")", ":", "if", "format", "not", "in", "PVRFormats", ":", "error", "(", "'invalid PVR texture format {}!'", ".", "format", "(", "format", ")", ")", "ensureDstDirectory", "(", ")", "pvrTool", "=", "getToolsBinPath", "(", ")", "+", "'PVRTexToolCLI'", "srcFiles", "=", "[", "'posx'", ",", "'negx'", ",", "'posy'", ",", "'negy'", ",", "'posz'", ",", "'negz'", "]", "dstPath", "=", "TexDstDirectory", "+", "'/'", "+", "dstFilename", "print", "(", "'=== toCubePVR: {}/{}/[posx,negx,posy,negy,posz,negz].{} => {}'", ".", "format", "(", "TexSrcDirectory", ",", "srcDir", ",", "srcExt", ",", "dstPath", ")", ")", "cmdLine", "=", "[", "pvrTool", ",", "'-i'", "]", "inputFiles", "=", "''", "dirty", "=", "False", "for", "src", "in", "srcFiles", ":", "srcPath", "=", "TexSrcDirectory", "+", "'/'", "+", "srcDir", "+", "'/'", "+", "src", "+", "'.'", "+", "srcExt", "dirty", "|=", "needsExport", "(", "srcPath", ",", "dstPath", ")", "inputFiles", "+=", "srcPath", "+", "','", "if", "not", "dirty", ":", "return", "inputFiles", "=", "inputFiles", "[", ":", "-", "1", "]", "cmdLine", ".", "append", "(", "inputFiles", ")", "cmdLine", ".", "append", "(", "'-o'", ")", "cmdLine", ".", "append", "(", "dstPath", ")", "cmdLine", ".", "append", "(", "'-cube'", ")", "cmdLine", ".", "append", "(", "'-m'", ")", "cmdLine", ".", "append", "(", "'-mfilter'", ")", "cmdLine", ".", "append", "(", "'cubic'", ")", "cmdLine", ".", "append", "(", "'-f'", ")", "cmdLine", ".", "append", "(", "format", ")", "subprocess", ".", "call", "(", "args", "=", "cmdLine", ")" ]
https://github.com/floooh/oryol/blob/eb08cffe1b1cb6b05ed14ec692bca9372cef064e/tools/texexport.py#L140-L173
nasa/astrobee
9241e67e6692810d6e275abb3165b6d02f4ca5ef
scripts/git/cpplint.py
python
_DropCommonSuffixes
(filename)
return os.path.splitext(filename)[0]
Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed.
Drops common suffixes like _test.cc or -inl.h from filename.
[ "Drops", "common", "suffixes", "like", "_test", ".", "cc", "or", "-", "inl", ".", "h", "from", "filename", "." ]
def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in ( "test.cc", "regtest.cc", "unittest.cc", "inl.h", "impl.h", "internal.h", ): if ( filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ("-", "_") ): return filename[: -len(suffix) - 1] return os.path.splitext(filename)[0]
[ "def", "_DropCommonSuffixes", "(", "filename", ")", ":", "for", "suffix", "in", "(", "\"test.cc\"", ",", "\"regtest.cc\"", ",", "\"unittest.cc\"", ",", "\"inl.h\"", ",", "\"impl.h\"", ",", "\"internal.h\"", ",", ")", ":", "if", "(", "filename", ".", "endswith", "(", "suffix", ")", "and", "len", "(", "filename", ")", ">", "len", "(", "suffix", ")", "and", "filename", "[", "-", "len", "(", "suffix", ")", "-", "1", "]", "in", "(", "\"-\"", ",", "\"_\"", ")", ")", ":", "return", "filename", "[", ":", "-", "len", "(", "suffix", ")", "-", "1", "]", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]" ]
https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/scripts/git/cpplint.py#L4911-L4944
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/GardenSnake/GardenSnake.py
python
t_LPAR
(t)
return t
r'\(
r'\(
[ "r", "\\", "(" ]
def t_LPAR(t): r'\(' t.lexer.paren_count += 1 return t
[ "def", "t_LPAR", "(", "t", ")", ":", "t", ".", "lexer", ".", "paren_count", "+=", "1", "return", "t" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/GardenSnake/GardenSnake.py#L135-L138
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
tools/pytorch-quantization/pytorch_quantization/calib/calibrator.py
python
_Calibrator.compute_amax
(self, *args, **kwargs)
Abstract method: compute the amax from the collected data Returns: amax: a tensor
Abstract method: compute the amax from the collected data
[ "Abstract", "method", ":", "compute", "the", "amax", "from", "the", "collected", "data" ]
def compute_amax(self, *args, **kwargs): """Abstract method: compute the amax from the collected data Returns: amax: a tensor """ raise NotImplementedError
[ "def", "compute_amax", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/pytorch-quantization/pytorch_quantization/calib/calibrator.py#L48-L54
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/metrics/actions/extract_actions.py
python
AddHistoryPageActions
(actions)
Add actions that are used in History page. Arguments actions: set of actions to add to.
Add actions that are used in History page.
[ "Add", "actions", "that", "are", "used", "in", "History", "page", "." ]
def AddHistoryPageActions(actions): """Add actions that are used in History page. Arguments actions: set of actions to add to. """ actions.add('HistoryPage_BookmarkStarClicked') actions.add('HistoryPage_EntryMenuRemoveFromHistory') actions.add('HistoryPage_EntryLinkClick') actions.add('HistoryPage_EntryLinkRightClick') actions.add('HistoryPage_SearchResultClick') actions.add('HistoryPage_EntryMenuShowMoreFromSite') actions.add('HistoryPage_NewestHistoryClick') actions.add('HistoryPage_NewerHistoryClick') actions.add('HistoryPage_OlderHistoryClick') actions.add('HistoryPage_Search') actions.add('HistoryPage_InitClearBrowsingData') actions.add('HistoryPage_RemoveSelected') actions.add('HistoryPage_SearchResultRemove') actions.add('HistoryPage_ConfirmRemoveSelected') actions.add('HistoryPage_CancelRemoveSelected')
[ "def", "AddHistoryPageActions", "(", "actions", ")", ":", "actions", ".", "add", "(", "'HistoryPage_BookmarkStarClicked'", ")", "actions", ".", "add", "(", "'HistoryPage_EntryMenuRemoveFromHistory'", ")", "actions", ".", "add", "(", "'HistoryPage_EntryLinkClick'", ")", "actions", ".", "add", "(", "'HistoryPage_EntryLinkRightClick'", ")", "actions", ".", "add", "(", "'HistoryPage_SearchResultClick'", ")", "actions", ".", "add", "(", "'HistoryPage_EntryMenuShowMoreFromSite'", ")", "actions", ".", "add", "(", "'HistoryPage_NewestHistoryClick'", ")", "actions", ".", "add", "(", "'HistoryPage_NewerHistoryClick'", ")", "actions", ".", "add", "(", "'HistoryPage_OlderHistoryClick'", ")", "actions", ".", "add", "(", "'HistoryPage_Search'", ")", "actions", ".", "add", "(", "'HistoryPage_InitClearBrowsingData'", ")", "actions", ".", "add", "(", "'HistoryPage_RemoveSelected'", ")", "actions", ".", "add", "(", "'HistoryPage_SearchResultRemove'", ")", "actions", ".", "add", "(", "'HistoryPage_ConfirmRemoveSelected'", ")", "actions", ".", "add", "(", "'HistoryPage_CancelRemoveSelected'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/metrics/actions/extract_actions.py#L528-L548
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/stencil.py
python
StencilFunc.add_indices_to_kernel
(self, kernel, index_names, ndim, neighborhood, standard_indexed, typemap, calltypes)
return (neighborhood, relatively_indexed)
Transforms the stencil kernel as specified by the user into one that includes each dimension's index variable as part of the getitem calls. So, in effect array[-1] becomes array[index0-1].
Transforms the stencil kernel as specified by the user into one that includes each dimension's index variable as part of the getitem calls. So, in effect array[-1] becomes array[index0-1].
[ "Transforms", "the", "stencil", "kernel", "as", "specified", "by", "the", "user", "into", "one", "that", "includes", "each", "dimension", "s", "index", "variable", "as", "part", "of", "the", "getitem", "calls", ".", "So", "in", "effect", "array", "[", "-", "1", "]", "becomes", "array", "[", "index0", "-", "1", "]", "." ]
def add_indices_to_kernel(self, kernel, index_names, ndim, neighborhood, standard_indexed, typemap, calltypes): """ Transforms the stencil kernel as specified by the user into one that includes each dimension's index variable as part of the getitem calls. So, in effect array[-1] becomes array[index0-1]. """ const_dict = {} kernel_consts = [] if config.DEBUG_ARRAY_OPT >= 1: print("add_indices_to_kernel", ndim, neighborhood) ir_utils.dump_blocks(kernel.blocks) if neighborhood is None: need_to_calc_kernel = True else: need_to_calc_kernel = False if len(neighborhood) != ndim: raise ValueError("%d dimensional neighborhood specified for %d " \ "dimensional input array" % (len(neighborhood), ndim)) tuple_table = ir_utils.get_tuple_table(kernel.blocks) relatively_indexed = set() for block in kernel.blocks.values(): scope = block.scope loc = block.loc new_body = [] for stmt in block.body: if (isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Const)): if config.DEBUG_ARRAY_OPT >= 1: print("remembering in const_dict", stmt.target.name, stmt.value.value) # Remember consts for use later. const_dict[stmt.target.name] = stmt.value.value if ((isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr) and stmt.value.op in ['setitem', 'static_setitem'] and stmt.value.value.name in kernel.arg_names) or (isinstance(stmt, ir.SetItem) and stmt.target.name in kernel.arg_names)): raise ValueError("Assignments to arrays passed to stencil " \ "kernels is not allowed.") if (isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr) and stmt.value.op in ['getitem', 'static_getitem'] and stmt.value.value.name in kernel.arg_names and stmt.value.value.name not in standard_indexed): # We found a getitem from the input array. if stmt.value.op == 'getitem': stmt_index_var = stmt.value.index else: stmt_index_var = stmt.value.index_var # allow static_getitem since rewrite passes are applied #raise ValueError("Unexpected static_getitem in add_indices_to_kernel.") relatively_indexed.add(stmt.value.value.name) # Store the index used after looking up the variable in # the const dictionary. if need_to_calc_kernel: assert hasattr(stmt_index_var, 'name') if stmt_index_var.name in tuple_table: kernel_consts += [tuple_table[stmt_index_var.name]] elif stmt_index_var.name in const_dict: kernel_consts += [const_dict[stmt_index_var.name]] else: raise ValueError("stencil kernel index is not " "constant, 'neighborhood' option required") if ndim == 1: # Single dimension always has index variable 'index0'. # tmpvar will hold the real index and is computed by # adding the relative offset in stmt.value.index to # the current absolute location in index0. index_var = ir.Var(scope, index_names[0], loc) tmpname = ir_utils.mk_unique_var("stencil_index") tmpvar = ir.Var(scope, tmpname, loc) stmt_index_var_typ = typemap[stmt_index_var.name] # If the array is indexed with a slice then we # have to add the index value with a call to # slice_addition. if isinstance(stmt_index_var_typ, types.misc.SliceType): sa_var = ir.Var(scope, ir_utils.mk_unique_var("slice_addition"), loc) sa_func = numba.njit(slice_addition) sa_func_typ = types.functions.Dispatcher(sa_func) typemap[sa_var.name] = sa_func_typ g_sa = ir.Global("slice_addition", sa_func, loc) new_body.append(ir.Assign(g_sa, sa_var, loc)) slice_addition_call = ir.Expr.call(sa_var, [stmt_index_var, index_var], (), loc) calltypes[slice_addition_call] = sa_func_typ.get_call_type(self._typingctx, [stmt_index_var_typ, types.intp], {}) new_body.append(ir.Assign(slice_addition_call, tmpvar, loc)) new_body.append(ir.Assign( ir.Expr.getitem(stmt.value.value, tmpvar, loc), stmt.target, loc)) else: acc_call = ir.Expr.binop(operator.add, stmt_index_var, index_var, loc) new_body.append(ir.Assign(acc_call, tmpvar, loc)) new_body.append(ir.Assign( ir.Expr.getitem(stmt.value.value, tmpvar, loc), stmt.target, loc)) else: index_vars = [] sum_results = [] s_index_name = ir_utils.mk_unique_var("stencil_index") s_index_var = ir.Var(scope, s_index_name, loc) const_index_vars = [] ind_stencils = [] stmt_index_var_typ = typemap[stmt_index_var.name] # Same idea as above but you have to extract # individual elements out of the tuple indexing # expression and add the corresponding index variable # to them and then reconstitute as a tuple that can # index the array. for dim in range(ndim): tmpname = ir_utils.mk_unique_var("const_index") tmpvar = ir.Var(scope, tmpname, loc) new_body.append(ir.Assign(ir.Const(dim, loc), tmpvar, loc)) const_index_vars += [tmpvar] index_var = ir.Var(scope, index_names[dim], loc) index_vars += [index_var] tmpname = ir_utils.mk_unique_var("ind_stencil_index") tmpvar = ir.Var(scope, tmpname, loc) ind_stencils += [tmpvar] getitemname = ir_utils.mk_unique_var("getitem") getitemvar = ir.Var(scope, getitemname, loc) getitemcall = ir.Expr.getitem(stmt_index_var, const_index_vars[dim], loc) new_body.append(ir.Assign(getitemcall, getitemvar, loc)) # Get the type of this particular part of the index tuple. one_index_typ = stmt_index_var_typ[dim] # If the array is indexed with a slice then we # have to add the index value with a call to # slice_addition. if isinstance(one_index_typ, types.misc.SliceType): sa_var = ir.Var(scope, ir_utils.mk_unique_var("slice_addition"), loc) sa_func = numba.njit(slice_addition) sa_func_typ = types.functions.Dispatcher(sa_func) typemap[sa_var.name] = sa_func_typ g_sa = ir.Global("slice_addition", sa_func, loc) new_body.append(ir.Assign(g_sa, sa_var, loc)) slice_addition_call = ir.Expr.call(sa_var, [getitemvar, index_vars[dim]], (), loc) calltypes[slice_addition_call] = sa_func_typ.get_call_type(self._typingctx, [one_index_typ, types.intp], {}) new_body.append(ir.Assign(slice_addition_call, tmpvar, loc)) else: acc_call = ir.Expr.binop(operator.add, getitemvar, index_vars[dim], loc) new_body.append(ir.Assign(acc_call, tmpvar, loc)) tuple_call = ir.Expr.build_tuple(ind_stencils, loc) new_body.append(ir.Assign(tuple_call, s_index_var, loc)) new_body.append(ir.Assign( ir.Expr.getitem(stmt.value.value,s_index_var,loc), stmt.target,loc)) else: new_body.append(stmt) block.body = new_body if need_to_calc_kernel: # Find the size of the kernel by finding the maximum absolute value # index used in the kernel specification. neighborhood = [[0,0] for _ in range(ndim)] if len(kernel_consts) == 0: raise ValueError("Stencil kernel with no accesses to " "relatively indexed arrays.") for index in kernel_consts: if isinstance(index, tuple) or isinstance(index, list): for i in range(len(index)): te = index[i] if isinstance(te, ir.Var) and te.name in const_dict: te = const_dict[te.name] if isinstance(te, int): neighborhood[i][0] = min(neighborhood[i][0], te) neighborhood[i][1] = max(neighborhood[i][1], te) else: raise ValueError( "stencil kernel index is not constant," "'neighborhood' option required") index_len = len(index) elif isinstance(index, int): neighborhood[0][0] = min(neighborhood[0][0], index) neighborhood[0][1] = max(neighborhood[0][1], index) index_len = 1 else: raise ValueError( "Non-tuple or non-integer used as stencil index.") if index_len != ndim: raise ValueError( "Stencil index does not match array dimensionality.") return (neighborhood, relatively_indexed)
[ "def", "add_indices_to_kernel", "(", "self", ",", "kernel", ",", "index_names", ",", "ndim", ",", "neighborhood", ",", "standard_indexed", ",", "typemap", ",", "calltypes", ")", ":", "const_dict", "=", "{", "}", "kernel_consts", "=", "[", "]", "if", "config", ".", "DEBUG_ARRAY_OPT", ">=", "1", ":", "print", "(", "\"add_indices_to_kernel\"", ",", "ndim", ",", "neighborhood", ")", "ir_utils", ".", "dump_blocks", "(", "kernel", ".", "blocks", ")", "if", "neighborhood", "is", "None", ":", "need_to_calc_kernel", "=", "True", "else", ":", "need_to_calc_kernel", "=", "False", "if", "len", "(", "neighborhood", ")", "!=", "ndim", ":", "raise", "ValueError", "(", "\"%d dimensional neighborhood specified for %d \"", "\"dimensional input array\"", "%", "(", "len", "(", "neighborhood", ")", ",", "ndim", ")", ")", "tuple_table", "=", "ir_utils", ".", "get_tuple_table", "(", "kernel", ".", "blocks", ")", "relatively_indexed", "=", "set", "(", ")", "for", "block", "in", "kernel", ".", "blocks", ".", "values", "(", ")", ":", "scope", "=", "block", ".", "scope", "loc", "=", "block", ".", "loc", "new_body", "=", "[", "]", "for", "stmt", "in", "block", ".", "body", ":", "if", "(", "isinstance", "(", "stmt", ",", "ir", ".", "Assign", ")", "and", "isinstance", "(", "stmt", ".", "value", ",", "ir", ".", "Const", ")", ")", ":", "if", "config", ".", "DEBUG_ARRAY_OPT", ">=", "1", ":", "print", "(", "\"remembering in const_dict\"", ",", "stmt", ".", "target", ".", "name", ",", "stmt", ".", "value", ".", "value", ")", "# Remember consts for use later.", "const_dict", "[", "stmt", ".", "target", ".", "name", "]", "=", "stmt", ".", "value", ".", "value", "if", "(", "(", "isinstance", "(", "stmt", ",", "ir", ".", "Assign", ")", "and", "isinstance", "(", "stmt", ".", "value", ",", "ir", ".", "Expr", ")", "and", "stmt", ".", "value", ".", "op", "in", "[", "'setitem'", ",", "'static_setitem'", "]", "and", "stmt", ".", "value", ".", "value", ".", "name", "in", "kernel", ".", "arg_names", ")", "or", "(", "isinstance", "(", "stmt", ",", "ir", ".", "SetItem", ")", "and", "stmt", ".", "target", ".", "name", "in", "kernel", ".", "arg_names", ")", ")", ":", "raise", "ValueError", "(", "\"Assignments to arrays passed to stencil \"", "\"kernels is not allowed.\"", ")", "if", "(", "isinstance", "(", "stmt", ",", "ir", ".", "Assign", ")", "and", "isinstance", "(", "stmt", ".", "value", ",", "ir", ".", "Expr", ")", "and", "stmt", ".", "value", ".", "op", "in", "[", "'getitem'", ",", "'static_getitem'", "]", "and", "stmt", ".", "value", ".", "value", ".", "name", "in", "kernel", ".", "arg_names", "and", "stmt", ".", "value", ".", "value", ".", "name", "not", "in", "standard_indexed", ")", ":", "# We found a getitem from the input array.", "if", "stmt", ".", "value", ".", "op", "==", "'getitem'", ":", "stmt_index_var", "=", "stmt", ".", "value", ".", "index", "else", ":", "stmt_index_var", "=", "stmt", ".", "value", ".", "index_var", "# allow static_getitem since rewrite passes are applied", "#raise ValueError(\"Unexpected static_getitem in add_indices_to_kernel.\")", "relatively_indexed", ".", "add", "(", "stmt", ".", "value", ".", "value", ".", "name", ")", "# Store the index used after looking up the variable in", "# the const dictionary.", "if", "need_to_calc_kernel", ":", "assert", "hasattr", "(", "stmt_index_var", ",", "'name'", ")", "if", "stmt_index_var", ".", "name", "in", "tuple_table", ":", "kernel_consts", "+=", "[", "tuple_table", "[", "stmt_index_var", ".", "name", "]", "]", "elif", "stmt_index_var", ".", "name", "in", "const_dict", ":", "kernel_consts", "+=", "[", "const_dict", "[", "stmt_index_var", ".", "name", "]", "]", "else", ":", "raise", "ValueError", "(", "\"stencil kernel index is not \"", "\"constant, 'neighborhood' option required\"", ")", "if", "ndim", "==", "1", ":", "# Single dimension always has index variable 'index0'.", "# tmpvar will hold the real index and is computed by", "# adding the relative offset in stmt.value.index to", "# the current absolute location in index0.", "index_var", "=", "ir", ".", "Var", "(", "scope", ",", "index_names", "[", "0", "]", ",", "loc", ")", "tmpname", "=", "ir_utils", ".", "mk_unique_var", "(", "\"stencil_index\"", ")", "tmpvar", "=", "ir", ".", "Var", "(", "scope", ",", "tmpname", ",", "loc", ")", "stmt_index_var_typ", "=", "typemap", "[", "stmt_index_var", ".", "name", "]", "# If the array is indexed with a slice then we", "# have to add the index value with a call to", "# slice_addition.", "if", "isinstance", "(", "stmt_index_var_typ", ",", "types", ".", "misc", ".", "SliceType", ")", ":", "sa_var", "=", "ir", ".", "Var", "(", "scope", ",", "ir_utils", ".", "mk_unique_var", "(", "\"slice_addition\"", ")", ",", "loc", ")", "sa_func", "=", "numba", ".", "njit", "(", "slice_addition", ")", "sa_func_typ", "=", "types", ".", "functions", ".", "Dispatcher", "(", "sa_func", ")", "typemap", "[", "sa_var", ".", "name", "]", "=", "sa_func_typ", "g_sa", "=", "ir", ".", "Global", "(", "\"slice_addition\"", ",", "sa_func", ",", "loc", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "g_sa", ",", "sa_var", ",", "loc", ")", ")", "slice_addition_call", "=", "ir", ".", "Expr", ".", "call", "(", "sa_var", ",", "[", "stmt_index_var", ",", "index_var", "]", ",", "(", ")", ",", "loc", ")", "calltypes", "[", "slice_addition_call", "]", "=", "sa_func_typ", ".", "get_call_type", "(", "self", ".", "_typingctx", ",", "[", "stmt_index_var_typ", ",", "types", ".", "intp", "]", ",", "{", "}", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "slice_addition_call", ",", "tmpvar", ",", "loc", ")", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "ir", ".", "Expr", ".", "getitem", "(", "stmt", ".", "value", ".", "value", ",", "tmpvar", ",", "loc", ")", ",", "stmt", ".", "target", ",", "loc", ")", ")", "else", ":", "acc_call", "=", "ir", ".", "Expr", ".", "binop", "(", "operator", ".", "add", ",", "stmt_index_var", ",", "index_var", ",", "loc", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "acc_call", ",", "tmpvar", ",", "loc", ")", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "ir", ".", "Expr", ".", "getitem", "(", "stmt", ".", "value", ".", "value", ",", "tmpvar", ",", "loc", ")", ",", "stmt", ".", "target", ",", "loc", ")", ")", "else", ":", "index_vars", "=", "[", "]", "sum_results", "=", "[", "]", "s_index_name", "=", "ir_utils", ".", "mk_unique_var", "(", "\"stencil_index\"", ")", "s_index_var", "=", "ir", ".", "Var", "(", "scope", ",", "s_index_name", ",", "loc", ")", "const_index_vars", "=", "[", "]", "ind_stencils", "=", "[", "]", "stmt_index_var_typ", "=", "typemap", "[", "stmt_index_var", ".", "name", "]", "# Same idea as above but you have to extract", "# individual elements out of the tuple indexing", "# expression and add the corresponding index variable", "# to them and then reconstitute as a tuple that can", "# index the array.", "for", "dim", "in", "range", "(", "ndim", ")", ":", "tmpname", "=", "ir_utils", ".", "mk_unique_var", "(", "\"const_index\"", ")", "tmpvar", "=", "ir", ".", "Var", "(", "scope", ",", "tmpname", ",", "loc", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "ir", ".", "Const", "(", "dim", ",", "loc", ")", ",", "tmpvar", ",", "loc", ")", ")", "const_index_vars", "+=", "[", "tmpvar", "]", "index_var", "=", "ir", ".", "Var", "(", "scope", ",", "index_names", "[", "dim", "]", ",", "loc", ")", "index_vars", "+=", "[", "index_var", "]", "tmpname", "=", "ir_utils", ".", "mk_unique_var", "(", "\"ind_stencil_index\"", ")", "tmpvar", "=", "ir", ".", "Var", "(", "scope", ",", "tmpname", ",", "loc", ")", "ind_stencils", "+=", "[", "tmpvar", "]", "getitemname", "=", "ir_utils", ".", "mk_unique_var", "(", "\"getitem\"", ")", "getitemvar", "=", "ir", ".", "Var", "(", "scope", ",", "getitemname", ",", "loc", ")", "getitemcall", "=", "ir", ".", "Expr", ".", "getitem", "(", "stmt_index_var", ",", "const_index_vars", "[", "dim", "]", ",", "loc", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "getitemcall", ",", "getitemvar", ",", "loc", ")", ")", "# Get the type of this particular part of the index tuple.", "one_index_typ", "=", "stmt_index_var_typ", "[", "dim", "]", "# If the array is indexed with a slice then we", "# have to add the index value with a call to", "# slice_addition.", "if", "isinstance", "(", "one_index_typ", ",", "types", ".", "misc", ".", "SliceType", ")", ":", "sa_var", "=", "ir", ".", "Var", "(", "scope", ",", "ir_utils", ".", "mk_unique_var", "(", "\"slice_addition\"", ")", ",", "loc", ")", "sa_func", "=", "numba", ".", "njit", "(", "slice_addition", ")", "sa_func_typ", "=", "types", ".", "functions", ".", "Dispatcher", "(", "sa_func", ")", "typemap", "[", "sa_var", ".", "name", "]", "=", "sa_func_typ", "g_sa", "=", "ir", ".", "Global", "(", "\"slice_addition\"", ",", "sa_func", ",", "loc", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "g_sa", ",", "sa_var", ",", "loc", ")", ")", "slice_addition_call", "=", "ir", ".", "Expr", ".", "call", "(", "sa_var", ",", "[", "getitemvar", ",", "index_vars", "[", "dim", "]", "]", ",", "(", ")", ",", "loc", ")", "calltypes", "[", "slice_addition_call", "]", "=", "sa_func_typ", ".", "get_call_type", "(", "self", ".", "_typingctx", ",", "[", "one_index_typ", ",", "types", ".", "intp", "]", ",", "{", "}", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "slice_addition_call", ",", "tmpvar", ",", "loc", ")", ")", "else", ":", "acc_call", "=", "ir", ".", "Expr", ".", "binop", "(", "operator", ".", "add", ",", "getitemvar", ",", "index_vars", "[", "dim", "]", ",", "loc", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "acc_call", ",", "tmpvar", ",", "loc", ")", ")", "tuple_call", "=", "ir", ".", "Expr", ".", "build_tuple", "(", "ind_stencils", ",", "loc", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "tuple_call", ",", "s_index_var", ",", "loc", ")", ")", "new_body", ".", "append", "(", "ir", ".", "Assign", "(", "ir", ".", "Expr", ".", "getitem", "(", "stmt", ".", "value", ".", "value", ",", "s_index_var", ",", "loc", ")", ",", "stmt", ".", "target", ",", "loc", ")", ")", "else", ":", "new_body", ".", "append", "(", "stmt", ")", "block", ".", "body", "=", "new_body", "if", "need_to_calc_kernel", ":", "# Find the size of the kernel by finding the maximum absolute value", "# index used in the kernel specification.", "neighborhood", "=", "[", "[", "0", ",", "0", "]", "for", "_", "in", "range", "(", "ndim", ")", "]", "if", "len", "(", "kernel_consts", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Stencil kernel with no accesses to \"", "\"relatively indexed arrays.\"", ")", "for", "index", "in", "kernel_consts", ":", "if", "isinstance", "(", "index", ",", "tuple", ")", "or", "isinstance", "(", "index", ",", "list", ")", ":", "for", "i", "in", "range", "(", "len", "(", "index", ")", ")", ":", "te", "=", "index", "[", "i", "]", "if", "isinstance", "(", "te", ",", "ir", ".", "Var", ")", "and", "te", ".", "name", "in", "const_dict", ":", "te", "=", "const_dict", "[", "te", ".", "name", "]", "if", "isinstance", "(", "te", ",", "int", ")", ":", "neighborhood", "[", "i", "]", "[", "0", "]", "=", "min", "(", "neighborhood", "[", "i", "]", "[", "0", "]", ",", "te", ")", "neighborhood", "[", "i", "]", "[", "1", "]", "=", "max", "(", "neighborhood", "[", "i", "]", "[", "1", "]", ",", "te", ")", "else", ":", "raise", "ValueError", "(", "\"stencil kernel index is not constant,\"", "\"'neighborhood' option required\"", ")", "index_len", "=", "len", "(", "index", ")", "elif", "isinstance", "(", "index", ",", "int", ")", ":", "neighborhood", "[", "0", "]", "[", "0", "]", "=", "min", "(", "neighborhood", "[", "0", "]", "[", "0", "]", ",", "index", ")", "neighborhood", "[", "0", "]", "[", "1", "]", "=", "max", "(", "neighborhood", "[", "0", "]", "[", "1", "]", ",", "index", ")", "index_len", "=", "1", "else", ":", "raise", "ValueError", "(", "\"Non-tuple or non-integer used as stencil index.\"", ")", "if", "index_len", "!=", "ndim", ":", "raise", "ValueError", "(", "\"Stencil index does not match array dimensionality.\"", ")", "return", "(", "neighborhood", ",", "relatively_indexed", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/stencil.py#L125-L324
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/aui.py
python
AuiToolBar.GetToolLabel
(*args, **kwargs)
return _aui.AuiToolBar_GetToolLabel(*args, **kwargs)
GetToolLabel(self, int toolId) -> String
GetToolLabel(self, int toolId) -> String
[ "GetToolLabel", "(", "self", "int", "toolId", ")", "-", ">", "String" ]
def GetToolLabel(*args, **kwargs): """GetToolLabel(self, int toolId) -> String""" return _aui.AuiToolBar_GetToolLabel(*args, **kwargs)
[ "def", "GetToolLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiToolBar_GetToolLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L2218-L2220
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Window.DissociateHandle
(*args, **kwargs)
return _core_.Window_DissociateHandle(*args, **kwargs)
DissociateHandle(self) Dissociate the current native handle from the window
DissociateHandle(self)
[ "DissociateHandle", "(", "self", ")" ]
def DissociateHandle(*args, **kwargs): """ DissociateHandle(self) Dissociate the current native handle from the window """ return _core_.Window_DissociateHandle(*args, **kwargs)
[ "def", "DissociateHandle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_DissociateHandle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L11186-L11192
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/audio/validators.py
python
check_band_biquad
(method)
return new_method
Wrapper method to check the parameters of BandBiquad.
Wrapper method to check the parameters of BandBiquad.
[ "Wrapper", "method", "to", "check", "the", "parameters", "of", "BandBiquad", "." ]
def check_band_biquad(method): """Wrapper method to check the parameters of BandBiquad.""" @wraps(method) def new_method(self, *args, **kwargs): [sample_rate, central_freq, q, noise], _ = parse_user_args( method, *args, **kwargs) check_biquad_sample_rate(sample_rate) check_biquad_central_freq(central_freq) check_biquad_q(q) check_biquad_noise(noise) return method(self, *args, **kwargs) return new_method
[ "def", "check_band_biquad", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "new_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "[", "sample_rate", ",", "central_freq", ",", "q", ",", "noise", "]", ",", "_", "=", "parse_user_args", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", "check_biquad_sample_rate", "(", "sample_rate", ")", "check_biquad_central_freq", "(", "central_freq", ")", "check_biquad_q", "(", "q", ")", "check_biquad_noise", "(", "noise", ")", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_method" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/audio/validators.py#L87-L100
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/messages.py
python
Field.__init__
(self, number, required=False, repeated=False, variant=None, default=None)
Constructor. The required and repeated parameters are mutually exclusive. Setting both to True will raise a FieldDefinitionError. Sub-class Attributes: Each sub-class of Field must define the following: VARIANTS: Set of variant types accepted by that field. DEFAULT_VARIANT: Default variant type if not specified in constructor. Args: number: Number of field. Must be unique per message class. required: Whether or not field is required. Mutually exclusive with 'repeated'. repeated: Whether or not field is repeated. Mutually exclusive with 'required'. variant: Wire-format variant hint. default: Default value for field if not found in stream. Raises: InvalidVariantError when invalid variant for field is provided. InvalidDefaultError when invalid default for field is provided. FieldDefinitionError when invalid number provided or mutually exclusive fields are used. InvalidNumberError when the field number is out of range or reserved.
Constructor.
[ "Constructor", "." ]
def __init__(self, number, required=False, repeated=False, variant=None, default=None): """Constructor. The required and repeated parameters are mutually exclusive. Setting both to True will raise a FieldDefinitionError. Sub-class Attributes: Each sub-class of Field must define the following: VARIANTS: Set of variant types accepted by that field. DEFAULT_VARIANT: Default variant type if not specified in constructor. Args: number: Number of field. Must be unique per message class. required: Whether or not field is required. Mutually exclusive with 'repeated'. repeated: Whether or not field is repeated. Mutually exclusive with 'required'. variant: Wire-format variant hint. default: Default value for field if not found in stream. Raises: InvalidVariantError when invalid variant for field is provided. InvalidDefaultError when invalid default for field is provided. FieldDefinitionError when invalid number provided or mutually exclusive fields are used. InvalidNumberError when the field number is out of range or reserved. """ if not isinstance(number, int) or not 1 <= number <= MAX_FIELD_NUMBER: raise InvalidNumberError('Invalid number for field: %s\n' 'Number must be 1 or greater and %d or less' % (number, MAX_FIELD_NUMBER)) if FIRST_RESERVED_FIELD_NUMBER <= number <= LAST_RESERVED_FIELD_NUMBER: raise InvalidNumberError('Tag number %d is a reserved number.\n' 'Numbers %d to %d are reserved' % (number, FIRST_RESERVED_FIELD_NUMBER, LAST_RESERVED_FIELD_NUMBER)) if repeated and required: raise FieldDefinitionError('Cannot set both repeated and required') if variant is None: variant = self.DEFAULT_VARIANT if repeated and default is not None: raise FieldDefinitionError('Repeated fields may not have defaults') if variant not in self.VARIANTS: raise InvalidVariantError( 'Invalid variant: %s\nValid variants for %s are %r' % (variant, type(self).__name__, sorted(self.VARIANTS))) self.number = number self.required = required self.repeated = repeated self.variant = variant if default is not None: try: self.validate_default(default) except ValidationError as err: try: name = self.name except AttributeError: # For when raising error before name initialization. raise InvalidDefaultError('Invalid default value for %s: %r: %s' % (self.__class__.__name__, default, err)) else: raise InvalidDefaultError('Invalid default value for field %s: ' '%r: %s' % (name, default, err)) self.__default = default self.__initialized = True
[ "def", "__init__", "(", "self", ",", "number", ",", "required", "=", "False", ",", "repeated", "=", "False", ",", "variant", "=", "None", ",", "default", "=", "None", ")", ":", "if", "not", "isinstance", "(", "number", ",", "int", ")", "or", "not", "1", "<=", "number", "<=", "MAX_FIELD_NUMBER", ":", "raise", "InvalidNumberError", "(", "'Invalid number for field: %s\\n'", "'Number must be 1 or greater and %d or less'", "%", "(", "number", ",", "MAX_FIELD_NUMBER", ")", ")", "if", "FIRST_RESERVED_FIELD_NUMBER", "<=", "number", "<=", "LAST_RESERVED_FIELD_NUMBER", ":", "raise", "InvalidNumberError", "(", "'Tag number %d is a reserved number.\\n'", "'Numbers %d to %d are reserved'", "%", "(", "number", ",", "FIRST_RESERVED_FIELD_NUMBER", ",", "LAST_RESERVED_FIELD_NUMBER", ")", ")", "if", "repeated", "and", "required", ":", "raise", "FieldDefinitionError", "(", "'Cannot set both repeated and required'", ")", "if", "variant", "is", "None", ":", "variant", "=", "self", ".", "DEFAULT_VARIANT", "if", "repeated", "and", "default", "is", "not", "None", ":", "raise", "FieldDefinitionError", "(", "'Repeated fields may not have defaults'", ")", "if", "variant", "not", "in", "self", ".", "VARIANTS", ":", "raise", "InvalidVariantError", "(", "'Invalid variant: %s\\nValid variants for %s are %r'", "%", "(", "variant", ",", "type", "(", "self", ")", ".", "__name__", ",", "sorted", "(", "self", ".", "VARIANTS", ")", ")", ")", "self", ".", "number", "=", "number", "self", ".", "required", "=", "required", "self", ".", "repeated", "=", "repeated", "self", ".", "variant", "=", "variant", "if", "default", "is", "not", "None", ":", "try", ":", "self", ".", "validate_default", "(", "default", ")", "except", "ValidationError", "as", "err", ":", "try", ":", "name", "=", "self", ".", "name", "except", "AttributeError", ":", "# For when raising error before name initialization.", "raise", "InvalidDefaultError", "(", "'Invalid default value for %s: %r: %s'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "default", ",", "err", ")", ")", "else", ":", "raise", "InvalidDefaultError", "(", "'Invalid default value for field %s: '", "'%r: %s'", "%", "(", "name", ",", "default", ",", "err", ")", ")", "self", ".", "__default", "=", "default", "self", ".", "__initialized", "=", "True" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/messages.py#L1152-L1229
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/clang/bindings/python/clang/cindex.py
python
Cursor.get_arguments
(self)
Return an iterator for accessing the arguments of this cursor.
Return an iterator for accessing the arguments of this cursor.
[ "Return", "an", "iterator", "for", "accessing", "the", "arguments", "of", "this", "cursor", "." ]
def get_arguments(self): """Return an iterator for accessing the arguments of this cursor.""" num_args = conf.lib.clang_Cursor_getNumArguments(self) for i in range(0, num_args): yield conf.lib.clang_Cursor_getArgument(self, i)
[ "def", "get_arguments", "(", "self", ")", ":", "num_args", "=", "conf", ".", "lib", ".", "clang_Cursor_getNumArguments", "(", "self", ")", "for", "i", "in", "range", "(", "0", ",", "num_args", ")", ":", "yield", "conf", ".", "lib", ".", "clang_Cursor_getArgument", "(", "self", ",", "i", ")" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/bindings/python/clang/cindex.py#L1800-L1804
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
PowerEvent.__init__
(self, *args, **kwargs)
__init__(self, EventType evtType) -> PowerEvent wx.PowerEvent is generated when the system online status changes. Currently this is only implemented for Windows.
__init__(self, EventType evtType) -> PowerEvent
[ "__init__", "(", "self", "EventType", "evtType", ")", "-", ">", "PowerEvent" ]
def __init__(self, *args, **kwargs): """ __init__(self, EventType evtType) -> PowerEvent wx.PowerEvent is generated when the system online status changes. Currently this is only implemented for Windows. """ _misc_.PowerEvent_swiginit(self,_misc_.new_PowerEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_misc_", ".", "PowerEvent_swiginit", "(", "self", ",", "_misc_", ".", "new_PowerEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L6489-L6496
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/framework/ops.py
python
Graph.gradient_override_map
(self, op_type_map)
EXPERIMENTAL: A context manager for overriding gradient functions. This context manager can be used to override the gradient function that will be used for ops within the scope of the context. For example: ```python @tf.RegisterGradient("CustomSquare") def _custom_square_grad(op, grad): # ... with tf.Graph().as_default() as g: c = tf.constant(5.0) s_1 = tf.square(c) # Uses the default gradient for tf.square. with g.gradient_override_map({"Square": "CustomSquare"}): s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the # gradient of s_2. ``` Args: op_type_map: A dictionary mapping op type strings to alternative op type strings. Returns: A context manager that sets the alternative op type to be used for one or more ops created in that context. Raises: TypeError: If `op_type_map` is not a dictionary mapping strings to strings.
EXPERIMENTAL: A context manager for overriding gradient functions.
[ "EXPERIMENTAL", ":", "A", "context", "manager", "for", "overriding", "gradient", "functions", "." ]
def gradient_override_map(self, op_type_map): """EXPERIMENTAL: A context manager for overriding gradient functions. This context manager can be used to override the gradient function that will be used for ops within the scope of the context. For example: ```python @tf.RegisterGradient("CustomSquare") def _custom_square_grad(op, grad): # ... with tf.Graph().as_default() as g: c = tf.constant(5.0) s_1 = tf.square(c) # Uses the default gradient for tf.square. with g.gradient_override_map({"Square": "CustomSquare"}): s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the # gradient of s_2. ``` Args: op_type_map: A dictionary mapping op type strings to alternative op type strings. Returns: A context manager that sets the alternative op type to be used for one or more ops created in that context. Raises: TypeError: If `op_type_map` is not a dictionary mapping strings to strings. """ if not isinstance(op_type_map, dict): raise TypeError("op_type_map must be a dictionary mapping " "strings to strings") # The saved_mappings dictionary stores any currently-set mappings that # will be overridden by this context manager. saved_mappings = {} # Install the given label for op_type, mapped_op_type in op_type_map.items(): if not (isinstance(op_type, six.string_types) and isinstance(mapped_op_type, six.string_types)): raise TypeError("op_type_map must be a dictionary mapping " "strings to strings") try: saved_mappings[op_type] = self._gradient_override_map[op_type] except KeyError: pass self._gradient_override_map[op_type] = mapped_op_type try: yield # The code within the context runs here. finally: # Remove the labels set for this context, and restore any saved labels. for op_type, mapped_op_type in op_type_map.items(): try: self._gradient_override_map[op_type] = saved_mappings[op_type] except KeyError: del self._gradient_override_map[op_type]
[ "def", "gradient_override_map", "(", "self", ",", "op_type_map", ")", ":", "if", "not", "isinstance", "(", "op_type_map", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"op_type_map must be a dictionary mapping \"", "\"strings to strings\"", ")", "# The saved_mappings dictionary stores any currently-set mappings that", "# will be overridden by this context manager.", "saved_mappings", "=", "{", "}", "# Install the given label", "for", "op_type", ",", "mapped_op_type", "in", "op_type_map", ".", "items", "(", ")", ":", "if", "not", "(", "isinstance", "(", "op_type", ",", "six", ".", "string_types", ")", "and", "isinstance", "(", "mapped_op_type", ",", "six", ".", "string_types", ")", ")", ":", "raise", "TypeError", "(", "\"op_type_map must be a dictionary mapping \"", "\"strings to strings\"", ")", "try", ":", "saved_mappings", "[", "op_type", "]", "=", "self", ".", "_gradient_override_map", "[", "op_type", "]", "except", "KeyError", ":", "pass", "self", ".", "_gradient_override_map", "[", "op_type", "]", "=", "mapped_op_type", "try", ":", "yield", "# The code within the context runs here.", "finally", ":", "# Remove the labels set for this context, and restore any saved labels.", "for", "op_type", ",", "mapped_op_type", "in", "op_type_map", ".", "items", "(", ")", ":", "try", ":", "self", ".", "_gradient_override_map", "[", "op_type", "]", "=", "saved_mappings", "[", "op_type", "]", "except", "KeyError", ":", "del", "self", ".", "_gradient_override_map", "[", "op_type", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L4207-L4265
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_pyio.py
python
TextIOBase.truncate
(self, pos=None)
Truncate size to pos.
Truncate size to pos.
[ "Truncate", "size", "to", "pos", "." ]
def truncate(self, pos=None): """Truncate size to pos.""" self._unsupported("truncate")
[ "def", "truncate", "(", "self", ",", "pos", "=", "None", ")", ":", "self", ".", "_unsupported", "(", "\"truncate\"", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_pyio.py#L1317-L1319
CMU-Perceptual-Computing-Lab/caffe_rtpose
a4778bb1c3eb74d7250402016047216f77b4dba6
python/caffe/io.py
python
Transformer.set_channel_swap
(self, in_, order)
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose. Parameters ---------- in_ : which input to assign this channel order order : the order to take the channels. (2,1,0) maps RGB to BGR for example.
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose.
[ "Set", "the", "input", "channel", "order", "for", "e", ".", "g", ".", "RGB", "to", "BGR", "conversion", "as", "needed", "for", "the", "reference", "ImageNet", "model", ".", "N", ".", "B", ".", "this", "assumes", "the", "channels", "are", "the", "first", "dimension", "AFTER", "transpose", "." ]
def set_channel_swap(self, in_, order): """ Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose. Parameters ---------- in_ : which input to assign this channel order order : the order to take the channels. (2,1,0) maps RGB to BGR for example. """ self.__check_input(in_) if len(order) != self.inputs[in_][1]: raise Exception('Channel swap needs to have the same number of ' 'dimensions as the input channels.') self.channel_swap[in_] = order
[ "def", "set_channel_swap", "(", "self", ",", "in_", ",", "order", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "if", "len", "(", "order", ")", "!=", "self", ".", "inputs", "[", "in_", "]", "[", "1", "]", ":", "raise", "Exception", "(", "'Channel swap needs to have the same number of '", "'dimensions as the input channels.'", ")", "self", ".", "channel_swap", "[", "in_", "]", "=", "order" ]
https://github.com/CMU-Perceptual-Computing-Lab/caffe_rtpose/blob/a4778bb1c3eb74d7250402016047216f77b4dba6/python/caffe/io.py#L203-L219
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py
python
Logger.error
(self, msg, *args, **kwargs)
Log 'msg % args' with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we have a %s", "major problem", exc_info=1)
Log 'msg % args' with severity 'ERROR'.
[ "Log", "msg", "%", "args", "with", "severity", "ERROR", "." ]
def error(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we have a %s", "major problem", exc_info=1) """ if self.isEnabledFor(ERROR): self._log(ERROR, msg, args, **kwargs)
[ "def", "error", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "isEnabledFor", "(", "ERROR", ")", ":", "self", ".", "_log", "(", "ERROR", ",", "msg", ",", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py#L1165-L1175
microsoft/LightGBM
904b2d5158703c4900b68008617951dd2f9ff21b
python-package/lightgbm/dask.py
python
DaskLGBMRanker.fit
( self, X: _DaskMatrixLike, y: _DaskCollection, sample_weight: Optional[_DaskVectorLike] = None, init_score: Optional[_DaskVectorLike] = None, group: Optional[_DaskVectorLike] = None, eval_set: Optional[List[Tuple[_DaskMatrixLike, _DaskCollection]]] = None, eval_names: Optional[List[str]] = None, eval_sample_weight: Optional[List[_DaskVectorLike]] = None, eval_init_score: Optional[List[_DaskVectorLike]] = None, eval_group: Optional[List[_DaskVectorLike]] = None, eval_metric: Optional[Union[_LGBM_ScikitCustomEvalFunction, str, List[Union[_LGBM_ScikitCustomEvalFunction, str]]]] = None, eval_at: Iterable[int] = (1, 2, 3, 4, 5), **kwargs: Any )
return self._lgb_dask_fit( model_factory=LGBMRanker, X=X, y=y, sample_weight=sample_weight, init_score=init_score, group=group, eval_set=eval_set, eval_names=eval_names, eval_sample_weight=eval_sample_weight, eval_init_score=eval_init_score, eval_group=eval_group, eval_metric=eval_metric, eval_at=eval_at, **kwargs )
Docstring is inherited from the lightgbm.LGBMRanker.fit.
Docstring is inherited from the lightgbm.LGBMRanker.fit.
[ "Docstring", "is", "inherited", "from", "the", "lightgbm", ".", "LGBMRanker", ".", "fit", "." ]
def fit( self, X: _DaskMatrixLike, y: _DaskCollection, sample_weight: Optional[_DaskVectorLike] = None, init_score: Optional[_DaskVectorLike] = None, group: Optional[_DaskVectorLike] = None, eval_set: Optional[List[Tuple[_DaskMatrixLike, _DaskCollection]]] = None, eval_names: Optional[List[str]] = None, eval_sample_weight: Optional[List[_DaskVectorLike]] = None, eval_init_score: Optional[List[_DaskVectorLike]] = None, eval_group: Optional[List[_DaskVectorLike]] = None, eval_metric: Optional[Union[_LGBM_ScikitCustomEvalFunction, str, List[Union[_LGBM_ScikitCustomEvalFunction, str]]]] = None, eval_at: Iterable[int] = (1, 2, 3, 4, 5), **kwargs: Any ) -> "DaskLGBMRanker": """Docstring is inherited from the lightgbm.LGBMRanker.fit.""" return self._lgb_dask_fit( model_factory=LGBMRanker, X=X, y=y, sample_weight=sample_weight, init_score=init_score, group=group, eval_set=eval_set, eval_names=eval_names, eval_sample_weight=eval_sample_weight, eval_init_score=eval_init_score, eval_group=eval_group, eval_metric=eval_metric, eval_at=eval_at, **kwargs )
[ "def", "fit", "(", "self", ",", "X", ":", "_DaskMatrixLike", ",", "y", ":", "_DaskCollection", ",", "sample_weight", ":", "Optional", "[", "_DaskVectorLike", "]", "=", "None", ",", "init_score", ":", "Optional", "[", "_DaskVectorLike", "]", "=", "None", ",", "group", ":", "Optional", "[", "_DaskVectorLike", "]", "=", "None", ",", "eval_set", ":", "Optional", "[", "List", "[", "Tuple", "[", "_DaskMatrixLike", ",", "_DaskCollection", "]", "]", "]", "=", "None", ",", "eval_names", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "eval_sample_weight", ":", "Optional", "[", "List", "[", "_DaskVectorLike", "]", "]", "=", "None", ",", "eval_init_score", ":", "Optional", "[", "List", "[", "_DaskVectorLike", "]", "]", "=", "None", ",", "eval_group", ":", "Optional", "[", "List", "[", "_DaskVectorLike", "]", "]", "=", "None", ",", "eval_metric", ":", "Optional", "[", "Union", "[", "_LGBM_ScikitCustomEvalFunction", ",", "str", ",", "List", "[", "Union", "[", "_LGBM_ScikitCustomEvalFunction", ",", "str", "]", "]", "]", "]", "=", "None", ",", "eval_at", ":", "Iterable", "[", "int", "]", "=", "(", "1", ",", "2", ",", "3", ",", "4", ",", "5", ")", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "\"DaskLGBMRanker\"", ":", "return", "self", ".", "_lgb_dask_fit", "(", "model_factory", "=", "LGBMRanker", ",", "X", "=", "X", ",", "y", "=", "y", ",", "sample_weight", "=", "sample_weight", ",", "init_score", "=", "init_score", ",", "group", "=", "group", ",", "eval_set", "=", "eval_set", ",", "eval_names", "=", "eval_names", ",", "eval_sample_weight", "=", "eval_sample_weight", ",", "eval_init_score", "=", "eval_init_score", ",", "eval_group", "=", "eval_group", ",", "eval_metric", "=", "eval_metric", ",", "eval_at", "=", "eval_at", ",", "*", "*", "kwargs", ")" ]
https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/python-package/lightgbm/dask.py#L1480-L1512
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/decimal.py
python
_Log10Memoize.getdigits
(self, p)
return int(self.digits[:p+1])
Given an integer p >= 0, return floor(10**p)*log(10). For example, self.getdigits(3) returns 2302.
Given an integer p >= 0, return floor(10**p)*log(10).
[ "Given", "an", "integer", "p", ">", "=", "0", "return", "floor", "(", "10", "**", "p", ")", "*", "log", "(", "10", ")", "." ]
def getdigits(self, p): """Given an integer p >= 0, return floor(10**p)*log(10). For example, self.getdigits(3) returns 2302. """ # digits are stored as a string, for quick conversion to # integer in the case that we've already computed enough # digits; the stored digits should always be correct # (truncated, not rounded to nearest). if p < 0: raise ValueError("p should be nonnegative") if p >= len(self.digits): # compute p+3, p+6, p+9, ... digits; continue until at # least one of the extra digits is nonzero extra = 3 while True: # compute p+extra digits, correct to within 1ulp M = 10**(p+extra+2) digits = str(_div_nearest(_ilog(10*M, M), 100)) if digits[-extra:] != '0'*extra: break extra += 3 # keep all reliable digits so far; remove trailing zeros # and next nonzero digit self.digits = digits.rstrip('0')[:-1] return int(self.digits[:p+1])
[ "def", "getdigits", "(", "self", ",", "p", ")", ":", "# digits are stored as a string, for quick conversion to", "# integer in the case that we've already computed enough", "# digits; the stored digits should always be correct", "# (truncated, not rounded to nearest).", "if", "p", "<", "0", ":", "raise", "ValueError", "(", "\"p should be nonnegative\"", ")", "if", "p", ">=", "len", "(", "self", ".", "digits", ")", ":", "# compute p+3, p+6, p+9, ... digits; continue until at", "# least one of the extra digits is nonzero", "extra", "=", "3", "while", "True", ":", "# compute p+extra digits, correct to within 1ulp", "M", "=", "10", "**", "(", "p", "+", "extra", "+", "2", ")", "digits", "=", "str", "(", "_div_nearest", "(", "_ilog", "(", "10", "*", "M", ",", "M", ")", ",", "100", ")", ")", "if", "digits", "[", "-", "extra", ":", "]", "!=", "'0'", "*", "extra", ":", "break", "extra", "+=", "3", "# keep all reliable digits so far; remove trailing zeros", "# and next nonzero digit", "self", ".", "digits", "=", "digits", ".", "rstrip", "(", "'0'", ")", "[", ":", "-", "1", "]", "return", "int", "(", "self", ".", "digits", "[", ":", "p", "+", "1", "]", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L5165-L5191
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
PNEANet.__deref__
(self)
return _snap.PNEANet___deref__(self)
__deref__(PNEANet self) -> TNEANet Parameters: self: TPt< TNEANet > const *
__deref__(PNEANet self) -> TNEANet
[ "__deref__", "(", "PNEANet", "self", ")", "-", ">", "TNEANet" ]
def __deref__(self): """ __deref__(PNEANet self) -> TNEANet Parameters: self: TPt< TNEANet > const * """ return _snap.PNEANet___deref__(self)
[ "def", "__deref__", "(", "self", ")", ":", "return", "_snap", ".", "PNEANet___deref__", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L23040-L23048
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/framework/common_shapes.py
python
scalar_shape
(unused_op)
return [tensor_shape.scalar()]
Shape function for ops that output a scalar value.
Shape function for ops that output a scalar value.
[ "Shape", "function", "for", "ops", "that", "output", "a", "scalar", "value", "." ]
def scalar_shape(unused_op): """Shape function for ops that output a scalar value.""" return [tensor_shape.scalar()]
[ "def", "scalar_shape", "(", "unused_op", ")", ":", "return", "[", "tensor_shape", ".", "scalar", "(", ")", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/common_shapes.py#L23-L25
lmb-freiburg/ogn
974f72ef4bf840d6f6693d22d1843a79223e77ce
scripts/cpp_lint.py
python
ReverseCloseExpression
(clean_lines, linenum, pos)
return (line, 0, -1)
If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ) or } or ] or >, finds the position that opens it.
[ "If", "input", "points", "to", ")", "or", "}", "or", "]", "or", ">", "finds", "the", "position", "that", "opens", "it", "." ]
def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] endchar = line[pos] if endchar not in ')}]>': return (line, 0, -1) if endchar == ')': startchar = '(' if endchar == ']': startchar = '[' if endchar == '}': startchar = '{' if endchar == '>': startchar = '<' # Check last line (start_pos, num_open) = FindStartOfExpressionInLine( line, pos, 0, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, num_open) = FindStartOfExpressionInLine( line, len(line) - 1, num_open, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Did not find startchar before beginning of file, give up return (line, 0, -1)
[ "def", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "endchar", "=", "line", "[", "pos", "]", "if", "endchar", "not", "in", "')}]>'", ":", "return", "(", "line", ",", "0", ",", "-", "1", ")", "if", "endchar", "==", "')'", ":", "startchar", "=", "'('", "if", "endchar", "==", "']'", ":", "startchar", "=", "'['", "if", "endchar", "==", "'}'", ":", "startchar", "=", "'{'", "if", "endchar", "==", "'>'", ":", "startchar", "=", "'<'", "# Check last line", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "pos", ",", "0", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Continue scanning backward", "while", "linenum", ">", "0", ":", "linenum", "-=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "len", "(", "line", ")", "-", "1", ",", "num_open", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Did not find startchar before beginning of file, give up", "return", "(", "line", ",", "0", ",", "-", "1", ")" ]
https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/scripts/cpp_lint.py#L1327-L1369
turesnake/tprPix
6b5471a072a1a8b423834ab04ff03e64df215d5e
deps/fmt-6.1.2/support/docopt.py
python
parse_seq
(tokens, options)
return result
seq ::= ( atom [ '...' ] )* ;
seq ::= ( atom [ '...' ] )* ;
[ "seq", "::", "=", "(", "atom", "[", "...", "]", ")", "*", ";" ]
def parse_seq(tokens, options): """seq ::= ( atom [ '...' ] )* ;""" result = [] while tokens.current() not in [None, ']', ')', '|']: atom = parse_atom(tokens, options) if tokens.current() == '...': atom = [OneOrMore(*atom)] tokens.move() result += atom return result
[ "def", "parse_seq", "(", "tokens", ",", "options", ")", ":", "result", "=", "[", "]", "while", "tokens", ".", "current", "(", ")", "not", "in", "[", "None", ",", "']'", ",", "')'", ",", "'|'", "]", ":", "atom", "=", "parse_atom", "(", "tokens", ",", "options", ")", "if", "tokens", ".", "current", "(", ")", "==", "'...'", ":", "atom", "=", "[", "OneOrMore", "(", "*", "atom", ")", "]", "tokens", ".", "move", "(", ")", "result", "+=", "atom", "return", "result" ]
https://github.com/turesnake/tprPix/blob/6b5471a072a1a8b423834ab04ff03e64df215d5e/deps/fmt-6.1.2/support/docopt.py#L390-L399
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/mrecords.py
python
MaskedRecords.__setitem__
(self, indx, value)
Sets the given record to value.
Sets the given record to value.
[ "Sets", "the", "given", "record", "to", "value", "." ]
def __setitem__(self, indx, value): """ Sets the given record to value. """ MaskedArray.__setitem__(self, indx, value) if isinstance(indx, basestring): self._mask[indx] = ma.getmaskarray(value)
[ "def", "__setitem__", "(", "self", ",", "indx", ",", "value", ")", ":", "MaskedArray", ".", "__setitem__", "(", "self", ",", "indx", ",", "value", ")", "if", "isinstance", "(", "indx", ",", "basestring", ")", ":", "self", ".", "_mask", "[", "indx", "]", "=", "ma", ".", "getmaskarray", "(", "value", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/mrecords.py#L332-L339
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/xrc.py
python
XmlNode.GetAttribute
(*args, **kwargs)
return _xrc.XmlNode_GetAttribute(*args, **kwargs)
GetAttribute(self, String attrName, String defaultVal) -> String
GetAttribute(self, String attrName, String defaultVal) -> String
[ "GetAttribute", "(", "self", "String", "attrName", "String", "defaultVal", ")", "-", ">", "String" ]
def GetAttribute(*args, **kwargs): """GetAttribute(self, String attrName, String defaultVal) -> String""" return _xrc.XmlNode_GetAttribute(*args, **kwargs)
[ "def", "GetAttribute", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlNode_GetAttribute", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/xrc.py#L481-L483
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/ops/loop.py
python
Loop.normalize_input_output_ports
(loop_node: Node)
Remove inputs, outputs, back edges from the port map which are not used in the body and were removed by a graph clean up, for example, in case of not used current_iteration body Parameter. Then renumber input/output ports. :param loop_node: the Loop node to normalize :return: None
Remove inputs, outputs, back edges from the port map which are not used in the body and were removed by a graph clean up, for example, in case of not used current_iteration body Parameter. Then renumber input/output ports.
[ "Remove", "inputs", "outputs", "back", "edges", "from", "the", "port", "map", "which", "are", "not", "used", "in", "the", "body", "and", "were", "removed", "by", "a", "graph", "clean", "up", "for", "example", "in", "case", "of", "not", "used", "current_iteration", "body", "Parameter", ".", "Then", "renumber", "input", "/", "output", "ports", "." ]
def normalize_input_output_ports(loop_node: Node): """ Remove inputs, outputs, back edges from the port map which are not used in the body and were removed by a graph clean up, for example, in case of not used current_iteration body Parameter. Then renumber input/output ports. :param loop_node: the Loop node to normalize :return: None """ Loop.remove_unused_ops_from_port_map(loop_node, loop_node.input_port_map, 'internal_layer_id', 'in') Loop.remove_unused_ops_from_port_map(loop_node, loop_node.output_port_map, 'internal_layer_id', 'out') Loop.remove_unused_ops_from_port_map(loop_node, loop_node.back_edges, 'to_layer') # remove not connected input/output ports Loop.re_numerate_input_ports(loop_node) Loop.re_numerate_output_ports(loop_node)
[ "def", "normalize_input_output_ports", "(", "loop_node", ":", "Node", ")", ":", "Loop", ".", "remove_unused_ops_from_port_map", "(", "loop_node", ",", "loop_node", ".", "input_port_map", ",", "'internal_layer_id'", ",", "'in'", ")", "Loop", ".", "remove_unused_ops_from_port_map", "(", "loop_node", ",", "loop_node", ".", "output_port_map", ",", "'internal_layer_id'", ",", "'out'", ")", "Loop", ".", "remove_unused_ops_from_port_map", "(", "loop_node", ",", "loop_node", ".", "back_edges", ",", "'to_layer'", ")", "# remove not connected input/output ports", "Loop", ".", "re_numerate_input_ports", "(", "loop_node", ")", "Loop", ".", "re_numerate_output_ports", "(", "loop_node", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/ops/loop.py#L520-L535
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Listbox.index
(self, index)
return getint(i)
Return index of item identified with INDEX.
Return index of item identified with INDEX.
[ "Return", "index", "of", "item", "identified", "with", "INDEX", "." ]
def index(self, index): """Return index of item identified with INDEX.""" i = self.tk.call(self._w, 'index', index) if i == 'none': return None return getint(i)
[ "def", "index", "(", "self", ",", "index", ")", ":", "i", "=", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'index'", ",", "index", ")", "if", "i", "==", "'none'", ":", "return", "None", "return", "getint", "(", "i", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L2573-L2577
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
armorycolors.py
python
htmlColor
(name)
These are not official HTML colors: this is simply a method for taking one of the above colors and converting to a hex string
These are not official HTML colors: this is simply a method for taking one of the above colors and converting to a hex string
[ "These", "are", "not", "official", "HTML", "colors", ":", "this", "is", "simply", "a", "method", "for", "taking", "one", "of", "the", "above", "colors", "and", "converting", "to", "a", "hex", "string" ]
def htmlColor(name): """ These are not official HTML colors: this is simply a method for taking one of the above colors and converting to a hex string """ try: qcolor = Colors.__dict__[name] r,g,b = qcolor.red(), qcolor.green(), qcolor.blue() rstr = hex(r)[2:].rjust(2, '0') gstr = hex(g)[2:].rjust(2, '0') bstr = hex(b)[2:].rjust(2, '0') return '#%s%s%s' % (rstr, gstr, bstr) except: raise InvalidColor, 'Invalid color: ' + name
[ "def", "htmlColor", "(", "name", ")", ":", "try", ":", "qcolor", "=", "Colors", ".", "__dict__", "[", "name", "]", "r", ",", "g", ",", "b", "=", "qcolor", ".", "red", "(", ")", ",", "qcolor", ".", "green", "(", ")", ",", "qcolor", ".", "blue", "(", ")", "rstr", "=", "hex", "(", "r", ")", "[", "2", ":", "]", ".", "rjust", "(", "2", ",", "'0'", ")", "gstr", "=", "hex", "(", "g", ")", "[", "2", ":", "]", ".", "rjust", "(", "2", ",", "'0'", ")", "bstr", "=", "hex", "(", "b", ")", "[", "2", ":", "]", ".", "rjust", "(", "2", ",", "'0'", ")", "return", "'#%s%s%s'", "%", "(", "rstr", ",", "gstr", ",", "bstr", ")", "except", ":", "raise", "InvalidColor", ",", "'Invalid color: '", "+", "name" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armorycolors.py#L144-L157
apache/kudu
90895ce76590f10730ad7aac3613b69d89ff5422
build-support/mini-cluster/relocate_binaries_for_mini_cluster.py
python
check_for_command
(command)
Ensure that the specified command is available on the PATH.
Ensure that the specified command is available on the PATH.
[ "Ensure", "that", "the", "specified", "command", "is", "available", "on", "the", "PATH", "." ]
def check_for_command(command): """ Ensure that the specified command is available on the PATH. """ try: _ = check_output(['which', command]) except subprocess.CalledProcessError as err: logging.error("Unable to find %s command", command) raise err
[ "def", "check_for_command", "(", "command", ")", ":", "try", ":", "_", "=", "check_output", "(", "[", "'which'", ",", "command", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "err", ":", "logging", ".", "error", "(", "\"Unable to find %s command\"", ",", "command", ")", "raise", "err" ]
https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/mini-cluster/relocate_binaries_for_mini_cluster.py#L117-L125
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/core/numeric.py
python
convolve
(a, v, mode='full')
return multiarray.correlate(a, v[::-1], mode)
Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [1]_. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. If `v` is longer than `a`, the arrays are swapped before computation. Parameters ---------- a : (N,) array_like First one-dimensional input array. v : (M,) array_like Second one-dimensional input array. mode : {'full', 'valid', 'same'}, optional 'full': By default, mode is 'full'. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen. 'same': Mode 'same' returns output of length ``max(M, N)``. Boundary effects are still visible. 'valid': Mode 'valid' returns output of length ``max(M, N) - min(M, N) + 1``. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect. Returns ------- out : ndarray Discrete, linear convolution of `a` and `v`. See Also -------- scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier Transform. scipy.linalg.toeplitz : Used to construct the convolution operator. polymul : Polynomial multiplication. Same output as convolve, but also accepts poly1d objects as input. Notes ----- The discrete convolution operation is defined as .. math:: (a * v)[n] = \\sum_{m = -\\infty}^{\\infty} a[m] v[n - m] It can be shown that a convolution :math:`x(t) * y(t)` in time/space is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier domain, after appropriate padding (padding is necessary to prevent circular convolution). Since multiplication is more efficient (faster) than convolution, the function `scipy.signal.fftconvolve` exploits the FFT to calculate the convolution of large data-sets. References ---------- .. [1] Wikipedia, "Convolution", https://en.wikipedia.org/wiki/Convolution Examples -------- Note how the convolution operator flips the second array before "sliding" the two across one another: >>> np.convolve([1, 2, 3], [0, 1, 0.5]) array([0. , 1. , 2.5, 4. , 1.5]) Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account: >>> np.convolve([1,2,3],[0,1,0.5], 'same') array([1. , 2.5, 4. ]) The two arrays are of the same length, so there is only one position where they completely overlap: >>> np.convolve([1,2,3],[0,1,0.5], 'valid') array([2.5])
Returns the discrete, linear convolution of two one-dimensional sequences.
[ "Returns", "the", "discrete", "linear", "convolution", "of", "two", "one", "-", "dimensional", "sequences", "." ]
def convolve(a, v, mode='full'): """ Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [1]_. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. If `v` is longer than `a`, the arrays are swapped before computation. Parameters ---------- a : (N,) array_like First one-dimensional input array. v : (M,) array_like Second one-dimensional input array. mode : {'full', 'valid', 'same'}, optional 'full': By default, mode is 'full'. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen. 'same': Mode 'same' returns output of length ``max(M, N)``. Boundary effects are still visible. 'valid': Mode 'valid' returns output of length ``max(M, N) - min(M, N) + 1``. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect. Returns ------- out : ndarray Discrete, linear convolution of `a` and `v`. See Also -------- scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier Transform. scipy.linalg.toeplitz : Used to construct the convolution operator. polymul : Polynomial multiplication. Same output as convolve, but also accepts poly1d objects as input. Notes ----- The discrete convolution operation is defined as .. math:: (a * v)[n] = \\sum_{m = -\\infty}^{\\infty} a[m] v[n - m] It can be shown that a convolution :math:`x(t) * y(t)` in time/space is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier domain, after appropriate padding (padding is necessary to prevent circular convolution). Since multiplication is more efficient (faster) than convolution, the function `scipy.signal.fftconvolve` exploits the FFT to calculate the convolution of large data-sets. References ---------- .. [1] Wikipedia, "Convolution", https://en.wikipedia.org/wiki/Convolution Examples -------- Note how the convolution operator flips the second array before "sliding" the two across one another: >>> np.convolve([1, 2, 3], [0, 1, 0.5]) array([0. , 1. , 2.5, 4. , 1.5]) Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account: >>> np.convolve([1,2,3],[0,1,0.5], 'same') array([1. , 2.5, 4. ]) The two arrays are of the same length, so there is only one position where they completely overlap: >>> np.convolve([1,2,3],[0,1,0.5], 'valid') array([2.5]) """ a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1) if (len(v) > len(a)): a, v = v, a if len(a) == 0: raise ValueError('a cannot be empty') if len(v) == 0: raise ValueError('v cannot be empty') return multiarray.correlate(a, v[::-1], mode)
[ "def", "convolve", "(", "a", ",", "v", ",", "mode", "=", "'full'", ")", ":", "a", ",", "v", "=", "array", "(", "a", ",", "copy", "=", "False", ",", "ndmin", "=", "1", ")", ",", "array", "(", "v", ",", "copy", "=", "False", ",", "ndmin", "=", "1", ")", "if", "(", "len", "(", "v", ")", ">", "len", "(", "a", ")", ")", ":", "a", ",", "v", "=", "v", ",", "a", "if", "len", "(", "a", ")", "==", "0", ":", "raise", "ValueError", "(", "'a cannot be empty'", ")", "if", "len", "(", "v", ")", "==", "0", ":", "raise", "ValueError", "(", "'v cannot be empty'", ")", "return", "multiarray", ".", "correlate", "(", "a", ",", "v", "[", ":", ":", "-", "1", "]", ",", "mode", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/numeric.py#L749-L844
taskflow/taskflow
f423a100a70b275f6e7331bc96537a3fe172e8d7
3rd-party/tbb/python/tbb/pool.py
python
Pool.terminate
(self)
Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected terminate() will be called immediately.
Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected terminate() will be called immediately.
[ "Stops", "the", "worker", "processes", "immediately", "without", "completing", "outstanding", "work", ".", "When", "the", "pool", "object", "is", "garbage", "collected", "terminate", "()", "will", "be", "called", "immediately", "." ]
def terminate(self): """Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected terminate() will be called immediately.""" self.close() self._tasks.cancel()
[ "def", "terminate", "(", "self", ")", ":", "self", ".", "close", "(", ")", "self", ".", "_tasks", ".", "cancel", "(", ")" ]
https://github.com/taskflow/taskflow/blob/f423a100a70b275f6e7331bc96537a3fe172e8d7/3rd-party/tbb/python/tbb/pool.py#L213-L218
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/decoder.py
python
_FloatDecoder
()
return _SimpleDecoder(wire_format.WIRETYPE_FIXED32, InnerDecode)
Returns a decoder for a float field. This code works around a bug in struct.unpack for non-finite 32-bit floating-point values.
Returns a decoder for a float field.
[ "Returns", "a", "decoder", "for", "a", "float", "field", "." ]
def _FloatDecoder(): """Returns a decoder for a float field. This code works around a bug in struct.unpack for non-finite 32-bit floating-point values. """ local_unpack = struct.unpack def InnerDecode(buffer, pos): # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand. new_pos = pos + 4 float_bytes = buffer[pos:new_pos] # If this value has all its exponent bits set, then it's non-finite. # In Python 2.4, struct.unpack will convert it to a finite 64-bit value. # To avoid that, we parse it specially. if ((float_bytes[3] in '\x7F\xFF') and (float_bytes[2] >= '\x80')): # If at least one significand bit is set... if float_bytes[0:3] != '\x00\x00\x80': return (_NAN, new_pos) # If sign bit is set... if float_bytes[3] == '\xFF': return (_NEG_INF, new_pos) return (_POS_INF, new_pos) # Note that we expect someone up-stack to catch struct.error and convert # it to _DecodeError -- this way we don't have to set up exception- # handling blocks every time we parse one value. result = local_unpack('<f', float_bytes)[0] return (result, new_pos) return _SimpleDecoder(wire_format.WIRETYPE_FIXED32, InnerDecode)
[ "def", "_FloatDecoder", "(", ")", ":", "local_unpack", "=", "struct", ".", "unpack", "def", "InnerDecode", "(", "buffer", ",", "pos", ")", ":", "# We expect a 32-bit value in little-endian byte order. Bit 1 is the sign", "# bit, bits 2-9 represent the exponent, and bits 10-32 are the significand.", "new_pos", "=", "pos", "+", "4", "float_bytes", "=", "buffer", "[", "pos", ":", "new_pos", "]", "# If this value has all its exponent bits set, then it's non-finite.", "# In Python 2.4, struct.unpack will convert it to a finite 64-bit value.", "# To avoid that, we parse it specially.", "if", "(", "(", "float_bytes", "[", "3", "]", "in", "'\\x7F\\xFF'", ")", "and", "(", "float_bytes", "[", "2", "]", ">=", "'\\x80'", ")", ")", ":", "# If at least one significand bit is set...", "if", "float_bytes", "[", "0", ":", "3", "]", "!=", "'\\x00\\x00\\x80'", ":", "return", "(", "_NAN", ",", "new_pos", ")", "# If sign bit is set...", "if", "float_bytes", "[", "3", "]", "==", "'\\xFF'", ":", "return", "(", "_NEG_INF", ",", "new_pos", ")", "return", "(", "_POS_INF", ",", "new_pos", ")", "# Note that we expect someone up-stack to catch struct.error and convert", "# it to _DecodeError -- this way we don't have to set up exception-", "# handling blocks every time we parse one value.", "result", "=", "local_unpack", "(", "'<f'", ",", "float_bytes", ")", "[", "0", "]", "return", "(", "result", ",", "new_pos", ")", "return", "_SimpleDecoder", "(", "wire_format", ".", "WIRETYPE_FIXED32", ",", "InnerDecode", ")" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/decoder.py#L279-L312
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/framemanager.py
python
AuiManager.RestoreMinimizedPane
(self, paneInfo)
Restores a previously minimized pane. :param `paneInfo`: a :class:`AuiPaneInfo` instance for the pane to be restored.
Restores a previously minimized pane.
[ "Restores", "a", "previously", "minimized", "pane", "." ]
def RestoreMinimizedPane(self, paneInfo): """ Restores a previously minimized pane. :param `paneInfo`: a :class:`AuiPaneInfo` instance for the pane to be restored. """ panename = paneInfo.name if paneInfo.minimize_mode & AUI_MINIMIZE_POS_TOOLBAR: pane = self.GetPane(panename) hasTarget = True else: panename = panename[0:-4] hasTarget = False pane = self.GetPane(panename) pane.SetFlag(pane.needsRestore, True) if not pane.IsOk(): panename = paneInfo.name pane = self.GetPane(panename) paneInfo = self.GetPane(panename + "_min") if not paneInfo.IsOk(): # Already minimized return if pane.IsOk(): if not pane.IsMinimized(): return if pane.HasFlag(pane.wasMaximized): self.SavePreviousDockSizes(pane) self.ShowPane(pane.window, True) pane.Show(True) self._has_minimized = False pane.SetFlag(pane.optionMinimized, False) if hasTarget: targetName = pane.minimize_target toolbarPane = self.GetPane(targetName) toolbar = toolbarPane.window item = toolbar.FindToolByLabel(pane.caption) toolbar.DeleteTool(item.id) else: paneInfo.window.Show(False) self.DetachPane(paneInfo.window) paneInfo.Show(False) paneInfo.Hide() self.Update()
[ "def", "RestoreMinimizedPane", "(", "self", ",", "paneInfo", ")", ":", "panename", "=", "paneInfo", ".", "name", "if", "paneInfo", ".", "minimize_mode", "&", "AUI_MINIMIZE_POS_TOOLBAR", ":", "pane", "=", "self", ".", "GetPane", "(", "panename", ")", "hasTarget", "=", "True", "else", ":", "panename", "=", "panename", "[", "0", ":", "-", "4", "]", "hasTarget", "=", "False", "pane", "=", "self", ".", "GetPane", "(", "panename", ")", "pane", ".", "SetFlag", "(", "pane", ".", "needsRestore", ",", "True", ")", "if", "not", "pane", ".", "IsOk", "(", ")", ":", "panename", "=", "paneInfo", ".", "name", "pane", "=", "self", ".", "GetPane", "(", "panename", ")", "paneInfo", "=", "self", ".", "GetPane", "(", "panename", "+", "\"_min\"", ")", "if", "not", "paneInfo", ".", "IsOk", "(", ")", ":", "# Already minimized", "return", "if", "pane", ".", "IsOk", "(", ")", ":", "if", "not", "pane", ".", "IsMinimized", "(", ")", ":", "return", "if", "pane", ".", "HasFlag", "(", "pane", ".", "wasMaximized", ")", ":", "self", ".", "SavePreviousDockSizes", "(", "pane", ")", "self", ".", "ShowPane", "(", "pane", ".", "window", ",", "True", ")", "pane", ".", "Show", "(", "True", ")", "self", ".", "_has_minimized", "=", "False", "pane", ".", "SetFlag", "(", "pane", ".", "optionMinimized", ",", "False", ")", "if", "hasTarget", ":", "targetName", "=", "pane", ".", "minimize_target", "toolbarPane", "=", "self", ".", "GetPane", "(", "targetName", ")", "toolbar", "=", "toolbarPane", ".", "window", "item", "=", "toolbar", ".", "FindToolByLabel", "(", "pane", ".", "caption", ")", "toolbar", ".", "DeleteTool", "(", "item", ".", "id", ")", "else", ":", "paneInfo", ".", "window", ".", "Show", "(", "False", ")", "self", ".", "DetachPane", "(", "paneInfo", ".", "window", ")", "paneInfo", ".", "Show", "(", "False", ")", "paneInfo", ".", "Hide", "(", ")", "self", ".", "Update", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L10253-L10305
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/estimator.py
python
_get_input_fn
(x, y, input_fn, feed_fn, batch_size, shuffle=False, epochs=1)
return input_fn, feed_fn
Make inputs into input and feed functions.
Make inputs into input and feed functions.
[ "Make", "inputs", "into", "input", "and", "feed", "functions", "." ]
def _get_input_fn(x, y, input_fn, feed_fn, batch_size, shuffle=False, epochs=1): """Make inputs into input and feed functions.""" if input_fn is None: if x is None: raise ValueError('Either x or input_fn must be provided.') if contrib_framework.is_tensor(x) or (y is not None and contrib_framework.is_tensor(y)): raise ValueError('Inputs cannot be tensors. Please provide input_fn.') if feed_fn is not None: raise ValueError('Can not provide both feed_fn and x or y.') df = data_feeder.setup_train_data_feeder(x, y, n_classes=None, batch_size=batch_size, shuffle=shuffle, epochs=epochs) return df.input_builder, df.get_feed_dict_fn() if (x is not None) or (y is not None): raise ValueError('Can not provide both input_fn and x or y.') if batch_size is not None: raise ValueError('Can not provide both input_fn and batch_size.') return input_fn, feed_fn
[ "def", "_get_input_fn", "(", "x", ",", "y", ",", "input_fn", ",", "feed_fn", ",", "batch_size", ",", "shuffle", "=", "False", ",", "epochs", "=", "1", ")", ":", "if", "input_fn", "is", "None", ":", "if", "x", "is", "None", ":", "raise", "ValueError", "(", "'Either x or input_fn must be provided.'", ")", "if", "contrib_framework", ".", "is_tensor", "(", "x", ")", "or", "(", "y", "is", "not", "None", "and", "contrib_framework", ".", "is_tensor", "(", "y", ")", ")", ":", "raise", "ValueError", "(", "'Inputs cannot be tensors. Please provide input_fn.'", ")", "if", "feed_fn", "is", "not", "None", ":", "raise", "ValueError", "(", "'Can not provide both feed_fn and x or y.'", ")", "df", "=", "data_feeder", ".", "setup_train_data_feeder", "(", "x", ",", "y", ",", "n_classes", "=", "None", ",", "batch_size", "=", "batch_size", ",", "shuffle", "=", "shuffle", ",", "epochs", "=", "epochs", ")", "return", "df", ".", "input_builder", ",", "df", ".", "get_feed_dict_fn", "(", ")", "if", "(", "x", "is", "not", "None", ")", "or", "(", "y", "is", "not", "None", ")", ":", "raise", "ValueError", "(", "'Can not provide both input_fn and x or y.'", ")", "if", "batch_size", "is", "not", "None", ":", "raise", "ValueError", "(", "'Can not provide both input_fn and batch_size.'", ")", "return", "input_fn", ",", "feed_fn" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L68-L92
microsoft/clang
86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5
tools/scan-build-py/libscanbuild/arguments.py
python
create_analyze_parser
(from_build_command)
return parser
Creates a parser for command-line arguments to 'analyze'.
Creates a parser for command-line arguments to 'analyze'.
[ "Creates", "a", "parser", "for", "command", "-", "line", "arguments", "to", "analyze", "." ]
def create_analyze_parser(from_build_command): """ Creates a parser for command-line arguments to 'analyze'. """ parser = create_default_parser() if from_build_command: parser_add_prefer_wrapper(parser) parser_add_compilers(parser) parser.add_argument( '--intercept-first', action='store_true', help="""Run the build commands first, intercept compiler calls and then run the static analyzer afterwards. Generally speaking it has better coverage on build commands. With '--override-compiler' it use compiler wrapper, but does not run the analyzer till the build is finished.""") else: parser_add_cdb(parser) parser.add_argument( '--status-bugs', action='store_true', help="""The exit status of '%(prog)s' is the same as the executed build command. This option ignores the build exit status and sets to be non zero if it found potential bugs or zero otherwise.""") parser.add_argument( '--exclude', metavar='<directory>', dest='excludes', action='append', default=[], help="""Do not run static analyzer against files found in this directory. (You can specify this option multiple times.) Could be useful when project contains 3rd party libraries.""") output = parser.add_argument_group('output control options') output.add_argument( '--output', '-o', metavar='<path>', default=tempfile.gettempdir(), help="""Specifies the output directory for analyzer reports. Subdirectory will be created if default directory is targeted.""") output.add_argument( '--keep-empty', action='store_true', help="""Don't remove the build results directory even if no issues were reported.""") output.add_argument( '--html-title', metavar='<title>', help="""Specify the title used on generated HTML pages. If not specified, a default title will be used.""") format_group = output.add_mutually_exclusive_group() format_group.add_argument( '--plist', '-plist', dest='output_format', const='plist', default='html', action='store_const', help="""Cause the results as a set of .plist files.""") format_group.add_argument( '--plist-html', '-plist-html', dest='output_format', const='plist-html', default='html', action='store_const', help="""Cause the results as a set of .html and .plist files.""") format_group.add_argument( '--plist-multi-file', '-plist-multi-file', dest='output_format', const='plist-multi-file', default='html', action='store_const', help="""Cause the results as a set of .plist files with extra information on related files.""") advanced = parser.add_argument_group('advanced options') advanced.add_argument( '--use-analyzer', metavar='<path>', dest='clang', default='clang', help="""'%(prog)s' uses the 'clang' executable relative to itself for static analysis. One can override this behavior with this option by using the 'clang' packaged with Xcode (on OS X) or from the PATH.""") advanced.add_argument( '--no-failure-reports', '-no-failure-reports', dest='output_failures', action='store_false', help="""Do not create a 'failures' subdirectory that includes analyzer crash reports and preprocessed source files.""") parser.add_argument( '--analyze-headers', action='store_true', help="""Also analyze functions in #included files. By default, such functions are skipped unless they are called by functions within the main source file.""") advanced.add_argument( '--stats', '-stats', action='store_true', help="""Generates visitation statistics for the project.""") advanced.add_argument( '--internal-stats', action='store_true', help="""Generate internal analyzer statistics.""") advanced.add_argument( '--maxloop', '-maxloop', metavar='<loop count>', type=int, help="""Specify the number of times a block can be visited before giving up. Increase for more comprehensive coverage at a cost of speed.""") advanced.add_argument( '--store', '-store', metavar='<model>', dest='store_model', choices=['region', 'basic'], help="""Specify the store model used by the analyzer. 'region' specifies a field- sensitive store model. 'basic' which is far less precise but can more quickly analyze code. 'basic' was the default store model for checker-0.221 and earlier.""") advanced.add_argument( '--constraints', '-constraints', metavar='<model>', dest='constraints_model', choices=['range', 'basic'], help="""Specify the constraint engine used by the analyzer. Specifying 'basic' uses a simpler, less powerful constraint model used by checker-0.160 and earlier.""") advanced.add_argument( '--analyzer-config', '-analyzer-config', metavar='<options>', help="""Provide options to pass through to the analyzer's -analyzer-config flag. Several options are separated with comma: 'key1=val1,key2=val2' Available options: stable-report-filename=true or false (default) Switch the page naming to: report-<filename>-<function/method name>-<id>.html instead of report-XXXXXX.html""") advanced.add_argument( '--force-analyze-debug-code', dest='force_debug', action='store_true', help="""Tells analyzer to enable assertions in code even if they were disabled during compilation, enabling more precise results.""") plugins = parser.add_argument_group('checker options') plugins.add_argument( '--load-plugin', '-load-plugin', metavar='<plugin library>', dest='plugins', action='append', help="""Loading external checkers using the clang plugin interface.""") plugins.add_argument( '--enable-checker', '-enable-checker', metavar='<checker name>', action=AppendCommaSeparated, help="""Enable specific checker.""") plugins.add_argument( '--disable-checker', '-disable-checker', metavar='<checker name>', action=AppendCommaSeparated, help="""Disable specific checker.""") plugins.add_argument( '--help-checkers', action='store_true', help="""A default group of checkers is run unless explicitly disabled. Exactly which checkers constitute the default group is a function of the operating system in use. These can be printed with this flag.""") plugins.add_argument( '--help-checkers-verbose', action='store_true', help="""Print all available checkers and mark the enabled ones.""") if from_build_command: parser.add_argument( dest='build', nargs=argparse.REMAINDER, help="""Command to run.""") else: ctu = parser.add_argument_group('cross translation unit analysis') ctu_mutex_group = ctu.add_mutually_exclusive_group() ctu_mutex_group.add_argument( '--ctu', action='store_const', const=CtuConfig(collect=True, analyze=True, dir='', func_map_cmd=''), dest='ctu_phases', help="""Perform cross translation unit (ctu) analysis (both collect and analyze phases) using default <ctu-dir> for temporary output. At the end of the analysis, the temporary directory is removed.""") ctu.add_argument( '--ctu-dir', metavar='<ctu-dir>', dest='ctu_dir', default='ctu-dir', help="""Defines the temporary directory used between ctu phases.""") ctu_mutex_group.add_argument( '--ctu-collect-only', action='store_const', const=CtuConfig(collect=True, analyze=False, dir='', func_map_cmd=''), dest='ctu_phases', help="""Perform only the collect phase of ctu. Keep <ctu-dir> for further use.""") ctu_mutex_group.add_argument( '--ctu-analyze-only', action='store_const', const=CtuConfig(collect=False, analyze=True, dir='', func_map_cmd=''), dest='ctu_phases', help="""Perform only the analyze phase of ctu. <ctu-dir> should be present and will not be removed after analysis.""") ctu.add_argument( '--use-func-map-cmd', metavar='<path>', dest='func_map_cmd', default='clang-func-mapping', help="""'%(prog)s' uses the 'clang-func-mapping' executable relative to itself for generating function maps for static analysis. One can override this behavior with this option by using the 'clang-func-mapping' packaged with Xcode (on OS X) or from the PATH.""") return parser
[ "def", "create_analyze_parser", "(", "from_build_command", ")", ":", "parser", "=", "create_default_parser", "(", ")", "if", "from_build_command", ":", "parser_add_prefer_wrapper", "(", "parser", ")", "parser_add_compilers", "(", "parser", ")", "parser", ".", "add_argument", "(", "'--intercept-first'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"Run the build commands first, intercept compiler\n calls and then run the static analyzer afterwards.\n Generally speaking it has better coverage on build commands.\n With '--override-compiler' it use compiler wrapper, but does\n not run the analyzer till the build is finished.\"\"\"", ")", "else", ":", "parser_add_cdb", "(", "parser", ")", "parser", ".", "add_argument", "(", "'--status-bugs'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"The exit status of '%(prog)s' is the same as the executed\n build command. This option ignores the build exit status and sets to\n be non zero if it found potential bugs or zero otherwise.\"\"\"", ")", "parser", ".", "add_argument", "(", "'--exclude'", ",", "metavar", "=", "'<directory>'", ",", "dest", "=", "'excludes'", ",", "action", "=", "'append'", ",", "default", "=", "[", "]", ",", "help", "=", "\"\"\"Do not run static analyzer against files found in this\n directory. (You can specify this option multiple times.)\n Could be useful when project contains 3rd party libraries.\"\"\"", ")", "output", "=", "parser", ".", "add_argument_group", "(", "'output control options'", ")", "output", ".", "add_argument", "(", "'--output'", ",", "'-o'", ",", "metavar", "=", "'<path>'", ",", "default", "=", "tempfile", ".", "gettempdir", "(", ")", ",", "help", "=", "\"\"\"Specifies the output directory for analyzer reports.\n Subdirectory will be created if default directory is targeted.\"\"\"", ")", "output", ".", "add_argument", "(", "'--keep-empty'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"Don't remove the build results directory even if no issues\n were reported.\"\"\"", ")", "output", ".", "add_argument", "(", "'--html-title'", ",", "metavar", "=", "'<title>'", ",", "help", "=", "\"\"\"Specify the title used on generated HTML pages.\n If not specified, a default title will be used.\"\"\"", ")", "format_group", "=", "output", ".", "add_mutually_exclusive_group", "(", ")", "format_group", ".", "add_argument", "(", "'--plist'", ",", "'-plist'", ",", "dest", "=", "'output_format'", ",", "const", "=", "'plist'", ",", "default", "=", "'html'", ",", "action", "=", "'store_const'", ",", "help", "=", "\"\"\"Cause the results as a set of .plist files.\"\"\"", ")", "format_group", ".", "add_argument", "(", "'--plist-html'", ",", "'-plist-html'", ",", "dest", "=", "'output_format'", ",", "const", "=", "'plist-html'", ",", "default", "=", "'html'", ",", "action", "=", "'store_const'", ",", "help", "=", "\"\"\"Cause the results as a set of .html and .plist files.\"\"\"", ")", "format_group", ".", "add_argument", "(", "'--plist-multi-file'", ",", "'-plist-multi-file'", ",", "dest", "=", "'output_format'", ",", "const", "=", "'plist-multi-file'", ",", "default", "=", "'html'", ",", "action", "=", "'store_const'", ",", "help", "=", "\"\"\"Cause the results as a set of .plist files with extra\n information on related files.\"\"\"", ")", "advanced", "=", "parser", ".", "add_argument_group", "(", "'advanced options'", ")", "advanced", ".", "add_argument", "(", "'--use-analyzer'", ",", "metavar", "=", "'<path>'", ",", "dest", "=", "'clang'", ",", "default", "=", "'clang'", ",", "help", "=", "\"\"\"'%(prog)s' uses the 'clang' executable relative to itself for\n static analysis. One can override this behavior with this option by\n using the 'clang' packaged with Xcode (on OS X) or from the PATH.\"\"\"", ")", "advanced", ".", "add_argument", "(", "'--no-failure-reports'", ",", "'-no-failure-reports'", ",", "dest", "=", "'output_failures'", ",", "action", "=", "'store_false'", ",", "help", "=", "\"\"\"Do not create a 'failures' subdirectory that includes analyzer\n crash reports and preprocessed source files.\"\"\"", ")", "parser", ".", "add_argument", "(", "'--analyze-headers'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"Also analyze functions in #included files. By default, such\n functions are skipped unless they are called by functions within the\n main source file.\"\"\"", ")", "advanced", ".", "add_argument", "(", "'--stats'", ",", "'-stats'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"Generates visitation statistics for the project.\"\"\"", ")", "advanced", ".", "add_argument", "(", "'--internal-stats'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"Generate internal analyzer statistics.\"\"\"", ")", "advanced", ".", "add_argument", "(", "'--maxloop'", ",", "'-maxloop'", ",", "metavar", "=", "'<loop count>'", ",", "type", "=", "int", ",", "help", "=", "\"\"\"Specify the number of times a block can be visited before\n giving up. Increase for more comprehensive coverage at a cost of\n speed.\"\"\"", ")", "advanced", ".", "add_argument", "(", "'--store'", ",", "'-store'", ",", "metavar", "=", "'<model>'", ",", "dest", "=", "'store_model'", ",", "choices", "=", "[", "'region'", ",", "'basic'", "]", ",", "help", "=", "\"\"\"Specify the store model used by the analyzer. 'region'\n specifies a field- sensitive store model. 'basic' which is far less\n precise but can more quickly analyze code. 'basic' was the default\n store model for checker-0.221 and earlier.\"\"\"", ")", "advanced", ".", "add_argument", "(", "'--constraints'", ",", "'-constraints'", ",", "metavar", "=", "'<model>'", ",", "dest", "=", "'constraints_model'", ",", "choices", "=", "[", "'range'", ",", "'basic'", "]", ",", "help", "=", "\"\"\"Specify the constraint engine used by the analyzer. Specifying\n 'basic' uses a simpler, less powerful constraint model used by\n checker-0.160 and earlier.\"\"\"", ")", "advanced", ".", "add_argument", "(", "'--analyzer-config'", ",", "'-analyzer-config'", ",", "metavar", "=", "'<options>'", ",", "help", "=", "\"\"\"Provide options to pass through to the analyzer's\n -analyzer-config flag. Several options are separated with comma:\n 'key1=val1,key2=val2'\n\n Available options:\n stable-report-filename=true or false (default)\n\n Switch the page naming to:\n report-<filename>-<function/method name>-<id>.html\n instead of report-XXXXXX.html\"\"\"", ")", "advanced", ".", "add_argument", "(", "'--force-analyze-debug-code'", ",", "dest", "=", "'force_debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"Tells analyzer to enable assertions in code even if they were\n disabled during compilation, enabling more precise results.\"\"\"", ")", "plugins", "=", "parser", ".", "add_argument_group", "(", "'checker options'", ")", "plugins", ".", "add_argument", "(", "'--load-plugin'", ",", "'-load-plugin'", ",", "metavar", "=", "'<plugin library>'", ",", "dest", "=", "'plugins'", ",", "action", "=", "'append'", ",", "help", "=", "\"\"\"Loading external checkers using the clang plugin interface.\"\"\"", ")", "plugins", ".", "add_argument", "(", "'--enable-checker'", ",", "'-enable-checker'", ",", "metavar", "=", "'<checker name>'", ",", "action", "=", "AppendCommaSeparated", ",", "help", "=", "\"\"\"Enable specific checker.\"\"\"", ")", "plugins", ".", "add_argument", "(", "'--disable-checker'", ",", "'-disable-checker'", ",", "metavar", "=", "'<checker name>'", ",", "action", "=", "AppendCommaSeparated", ",", "help", "=", "\"\"\"Disable specific checker.\"\"\"", ")", "plugins", ".", "add_argument", "(", "'--help-checkers'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"A default group of checkers is run unless explicitly disabled.\n Exactly which checkers constitute the default group is a function of\n the operating system in use. These can be printed with this flag.\"\"\"", ")", "plugins", ".", "add_argument", "(", "'--help-checkers-verbose'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"Print all available checkers and mark the enabled ones.\"\"\"", ")", "if", "from_build_command", ":", "parser", ".", "add_argument", "(", "dest", "=", "'build'", ",", "nargs", "=", "argparse", ".", "REMAINDER", ",", "help", "=", "\"\"\"Command to run.\"\"\"", ")", "else", ":", "ctu", "=", "parser", ".", "add_argument_group", "(", "'cross translation unit analysis'", ")", "ctu_mutex_group", "=", "ctu", ".", "add_mutually_exclusive_group", "(", ")", "ctu_mutex_group", ".", "add_argument", "(", "'--ctu'", ",", "action", "=", "'store_const'", ",", "const", "=", "CtuConfig", "(", "collect", "=", "True", ",", "analyze", "=", "True", ",", "dir", "=", "''", ",", "func_map_cmd", "=", "''", ")", ",", "dest", "=", "'ctu_phases'", ",", "help", "=", "\"\"\"Perform cross translation unit (ctu) analysis (both collect\n and analyze phases) using default <ctu-dir> for temporary output.\n At the end of the analysis, the temporary directory is removed.\"\"\"", ")", "ctu", ".", "add_argument", "(", "'--ctu-dir'", ",", "metavar", "=", "'<ctu-dir>'", ",", "dest", "=", "'ctu_dir'", ",", "default", "=", "'ctu-dir'", ",", "help", "=", "\"\"\"Defines the temporary directory used between ctu\n phases.\"\"\"", ")", "ctu_mutex_group", ".", "add_argument", "(", "'--ctu-collect-only'", ",", "action", "=", "'store_const'", ",", "const", "=", "CtuConfig", "(", "collect", "=", "True", ",", "analyze", "=", "False", ",", "dir", "=", "''", ",", "func_map_cmd", "=", "''", ")", ",", "dest", "=", "'ctu_phases'", ",", "help", "=", "\"\"\"Perform only the collect phase of ctu.\n Keep <ctu-dir> for further use.\"\"\"", ")", "ctu_mutex_group", ".", "add_argument", "(", "'--ctu-analyze-only'", ",", "action", "=", "'store_const'", ",", "const", "=", "CtuConfig", "(", "collect", "=", "False", ",", "analyze", "=", "True", ",", "dir", "=", "''", ",", "func_map_cmd", "=", "''", ")", ",", "dest", "=", "'ctu_phases'", ",", "help", "=", "\"\"\"Perform only the analyze phase of ctu. <ctu-dir> should be\n present and will not be removed after analysis.\"\"\"", ")", "ctu", ".", "add_argument", "(", "'--use-func-map-cmd'", ",", "metavar", "=", "'<path>'", ",", "dest", "=", "'func_map_cmd'", ",", "default", "=", "'clang-func-mapping'", ",", "help", "=", "\"\"\"'%(prog)s' uses the 'clang-func-mapping' executable\n relative to itself for generating function maps for static\n analysis. One can override this behavior with this option by using\n the 'clang-func-mapping' packaged with Xcode (on OS X) or from the\n PATH.\"\"\"", ")", "return", "parser" ]
https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/tools/scan-build-py/libscanbuild/arguments.py#L167-L406
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/modify-python-lldb.py
python
NewContent.finish
(self)
Call this when you're finished with populating content.
Call this when you're finished with populating content.
[ "Call", "this", "when", "you", "re", "finished", "with", "populating", "content", "." ]
def finish(self): """Call this when you're finished with populating content.""" if self.prev_line is not None: self.write(self.prev_line + "\n") self.prev_line = None
[ "def", "finish", "(", "self", ")", ":", "if", "self", ".", "prev_line", "is", "not", "None", ":", "self", ".", "write", "(", "self", ".", "prev_line", "+", "\"\\n\"", ")", "self", ".", "prev_line", "=", "None" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/modify-python-lldb.py#L315-L319
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/stcprint.py
python
STCPrintout._drawPageHeader
(self, dc, page)
Draw the page header into the DC for printing @param dc: the device context representing the page @param page: page number
Draw the page header into the DC for printing
[ "Draw", "the", "page", "header", "into", "the", "DC", "for", "printing" ]
def _drawPageHeader(self, dc, page): """Draw the page header into the DC for printing @param dc: the device context representing the page @param page: page number """ # Set font for title/page number rendering dc.SetFont(self.getHeaderFont()) dc.SetTextForeground ("black") dum, yoffset = dc.GetTextExtent(".") yoffset /= 2 if self.title: title_w, title_h = dc.GetTextExtent(self.title) dc.DrawText(self.title, self.x1, self.y1 - title_h - yoffset) # Page Number page_lbl = _("Page: %d") % page pg_lbl_w, pg_lbl_h = dc.GetTextExtent(page_lbl) dc.DrawText(page_lbl, self.x2 - pg_lbl_w, self.y1 - pg_lbl_h - yoffset)
[ "def", "_drawPageHeader", "(", "self", ",", "dc", ",", "page", ")", ":", "# Set font for title/page number rendering", "dc", ".", "SetFont", "(", "self", ".", "getHeaderFont", "(", ")", ")", "dc", ".", "SetTextForeground", "(", "\"black\"", ")", "dum", ",", "yoffset", "=", "dc", ".", "GetTextExtent", "(", "\".\"", ")", "yoffset", "/=", "2", "if", "self", ".", "title", ":", "title_w", ",", "title_h", "=", "dc", ".", "GetTextExtent", "(", "self", ".", "title", ")", "dc", ".", "DrawText", "(", "self", ".", "title", ",", "self", ".", "x1", ",", "self", ".", "y1", "-", "title_h", "-", "yoffset", ")", "# Page Number", "page_lbl", "=", "_", "(", "\"Page: %d\"", ")", "%", "page", "pg_lbl_w", ",", "pg_lbl_h", "=", "dc", ".", "GetTextExtent", "(", "page_lbl", ")", "dc", ".", "DrawText", "(", "page_lbl", ",", "self", ".", "x2", "-", "pg_lbl_w", ",", "self", ".", "y1", "-", "pg_lbl_h", "-", "yoffset", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/stcprint.py#L388-L407
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/control_flow_ops.py
python
_GetWhileContext
(op)
return ctxt
Get the WhileContext to which this op belongs.
Get the WhileContext to which this op belongs.
[ "Get", "the", "WhileContext", "to", "which", "this", "op", "belongs", "." ]
def _GetWhileContext(op): """Get the WhileContext to which this op belongs.""" ctxt = op._get_control_flow_context() if ctxt: ctxt = ctxt.GetWhileContext() return ctxt
[ "def", "_GetWhileContext", "(", "op", ")", ":", "ctxt", "=", "op", ".", "_get_control_flow_context", "(", ")", "if", "ctxt", ":", "ctxt", "=", "ctxt", ".", "GetWhileContext", "(", ")", "return", "ctxt" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L1004-L1009
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchComponent.py
python
ViewProviderComponent.setEdit
(self,vobj,mode)
return False
Method called when the document requests the object to enter edit mode. Edit mode is entered when a user double clicks on an object in the tree view, or when they use the menu option [Edit -> Toggle Edit Mode]. Parameters ---------- vobj: <Gui.ViewProviderDocumentObject> The component's view provider object. mode: int or str The edit mode the document has requested. Set to 0 when requested via a double click or [Edit -> Toggle Edit Mode]. Returns ------- bool If edit mode was entered.
Method called when the document requests the object to enter edit mode.
[ "Method", "called", "when", "the", "document", "requests", "the", "object", "to", "enter", "edit", "mode", "." ]
def setEdit(self,vobj,mode): """Method called when the document requests the object to enter edit mode. Edit mode is entered when a user double clicks on an object in the tree view, or when they use the menu option [Edit -> Toggle Edit Mode]. Parameters ---------- vobj: <Gui.ViewProviderDocumentObject> The component's view provider object. mode: int or str The edit mode the document has requested. Set to 0 when requested via a double click or [Edit -> Toggle Edit Mode]. Returns ------- bool If edit mode was entered. """ if mode == 0: taskd = ComponentTaskPanel() taskd.obj = self.Object taskd.update() FreeCADGui.Control.showDialog(taskd) return True return False
[ "def", "setEdit", "(", "self", ",", "vobj", ",", "mode", ")", ":", "if", "mode", "==", "0", ":", "taskd", "=", "ComponentTaskPanel", "(", ")", "taskd", ".", "obj", "=", "self", ".", "Object", "taskd", ".", "update", "(", ")", "FreeCADGui", ".", "Control", ".", "showDialog", "(", "taskd", ")", "return", "True", "return", "False" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchComponent.py#L1447-L1473
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
_exit
(code=0)
Internal function. Calling it will raise the exception SystemExit.
Internal function. Calling it will raise the exception SystemExit.
[ "Internal", "function", ".", "Calling", "it", "will", "raise", "the", "exception", "SystemExit", "." ]
def _exit(code=0): """Internal function. Calling it will raise the exception SystemExit.""" try: code = int(code) except ValueError: pass raise SystemExit, code
[ "def", "_exit", "(", "code", "=", "0", ")", ":", "try", ":", "code", "=", "int", "(", "code", ")", "except", "ValueError", ":", "pass", "raise", "SystemExit", ",", "code" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L189-L195
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Rect2D.MoveRightTo
(*args, **kwargs)
return _core_.Rect2D_MoveRightTo(*args, **kwargs)
MoveRightTo(self, Double n)
MoveRightTo(self, Double n)
[ "MoveRightTo", "(", "self", "Double", "n", ")" ]
def MoveRightTo(*args, **kwargs): """MoveRightTo(self, Double n)""" return _core_.Rect2D_MoveRightTo(*args, **kwargs)
[ "def", "MoveRightTo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Rect2D_MoveRightTo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1899-L1901
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
python
PBXProject.AddOrGetProjectReference
(self, other_pbxproject)
return [product_group, project_ref]
Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary.
Add a reference to another project file (via PBXProject object) to this one.
[ "Add", "a", "reference", "to", "another", "project", "file", "(", "via", "PBXProject", "object", ")", "to", "this", "one", "." ]
def AddOrGetProjectReference(self, other_pbxproject): """Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary. """ if not 'projectReferences' in self._properties: self._properties['projectReferences'] = [] product_group = None project_ref = None if not other_pbxproject in self._other_pbxprojects: # This project file isn't yet linked to the other one. Establish the # link. product_group = PBXGroup({'name': 'Products'}) # ProductGroup is strong. product_group.parent = self # There's nothing unique about this PBXGroup, and if left alone, it will # wind up with the same set of hashables as all other PBXGroup objects # owned by the projectReferences list. Add the hashables of the # remote PBXProject that it's related to. product_group._hashables.extend(other_pbxproject.Hashables()) # The other project reports its path as relative to the same directory # that this project's path is relative to. The other project's path # is not necessarily already relative to this project. Figure out the # pathname that this project needs to use to refer to the other one. this_path = posixpath.dirname(self.Path()) projectDirPath = self.GetProperty('projectDirPath') if projectDirPath: if posixpath.isabs(projectDirPath[0]): this_path = projectDirPath else: this_path = posixpath.join(this_path, projectDirPath) other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path) # ProjectRef is weak (it's owned by the mainGroup hierarchy). project_ref = PBXFileReference({ 'lastKnownFileType': 'wrapper.pb-project', 'path': other_path, 'sourceTree': 'SOURCE_ROOT', }) self.ProjectsGroup().AppendChild(project_ref) ref_dict = {'ProductGroup': product_group, 'ProjectRef': project_ref} self._other_pbxprojects[other_pbxproject] = ref_dict self.AppendProperty('projectReferences', ref_dict) # Xcode seems to sort this list case-insensitively self._properties['projectReferences'] = \ sorted(self._properties['projectReferences'], cmp=lambda x,y: cmp(x['ProjectRef'].Name().lower(), y['ProjectRef'].Name().lower())) else: # The link already exists. Pull out the relevnt data. project_ref_dict = self._other_pbxprojects[other_pbxproject] product_group = project_ref_dict['ProductGroup'] project_ref = project_ref_dict['ProjectRef'] self._SetUpProductReferences(other_pbxproject, product_group, project_ref) inherit_unique_symroot = self._AllSymrootsUnique(other_pbxproject, False) targets = other_pbxproject.GetProperty('targets') if all(self._AllSymrootsUnique(t, inherit_unique_symroot) for t in targets): dir_path = project_ref._properties['path'] product_group._hashables.extend(dir_path) return [product_group, project_ref]
[ "def", "AddOrGetProjectReference", "(", "self", ",", "other_pbxproject", ")", ":", "if", "not", "'projectReferences'", "in", "self", ".", "_properties", ":", "self", ".", "_properties", "[", "'projectReferences'", "]", "=", "[", "]", "product_group", "=", "None", "project_ref", "=", "None", "if", "not", "other_pbxproject", "in", "self", ".", "_other_pbxprojects", ":", "# This project file isn't yet linked to the other one. Establish the", "# link.", "product_group", "=", "PBXGroup", "(", "{", "'name'", ":", "'Products'", "}", ")", "# ProductGroup is strong.", "product_group", ".", "parent", "=", "self", "# There's nothing unique about this PBXGroup, and if left alone, it will", "# wind up with the same set of hashables as all other PBXGroup objects", "# owned by the projectReferences list. Add the hashables of the", "# remote PBXProject that it's related to.", "product_group", ".", "_hashables", ".", "extend", "(", "other_pbxproject", ".", "Hashables", "(", ")", ")", "# The other project reports its path as relative to the same directory", "# that this project's path is relative to. The other project's path", "# is not necessarily already relative to this project. Figure out the", "# pathname that this project needs to use to refer to the other one.", "this_path", "=", "posixpath", ".", "dirname", "(", "self", ".", "Path", "(", ")", ")", "projectDirPath", "=", "self", ".", "GetProperty", "(", "'projectDirPath'", ")", "if", "projectDirPath", ":", "if", "posixpath", ".", "isabs", "(", "projectDirPath", "[", "0", "]", ")", ":", "this_path", "=", "projectDirPath", "else", ":", "this_path", "=", "posixpath", ".", "join", "(", "this_path", ",", "projectDirPath", ")", "other_path", "=", "gyp", ".", "common", ".", "RelativePath", "(", "other_pbxproject", ".", "Path", "(", ")", ",", "this_path", ")", "# ProjectRef is weak (it's owned by the mainGroup hierarchy).", "project_ref", "=", "PBXFileReference", "(", "{", "'lastKnownFileType'", ":", "'wrapper.pb-project'", ",", "'path'", ":", "other_path", ",", "'sourceTree'", ":", "'SOURCE_ROOT'", ",", "}", ")", "self", ".", "ProjectsGroup", "(", ")", ".", "AppendChild", "(", "project_ref", ")", "ref_dict", "=", "{", "'ProductGroup'", ":", "product_group", ",", "'ProjectRef'", ":", "project_ref", "}", "self", ".", "_other_pbxprojects", "[", "other_pbxproject", "]", "=", "ref_dict", "self", ".", "AppendProperty", "(", "'projectReferences'", ",", "ref_dict", ")", "# Xcode seems to sort this list case-insensitively", "self", ".", "_properties", "[", "'projectReferences'", "]", "=", "sorted", "(", "self", ".", "_properties", "[", "'projectReferences'", "]", ",", "cmp", "=", "lambda", "x", ",", "y", ":", "cmp", "(", "x", "[", "'ProjectRef'", "]", ".", "Name", "(", ")", ".", "lower", "(", ")", ",", "y", "[", "'ProjectRef'", "]", ".", "Name", "(", ")", ".", "lower", "(", ")", ")", ")", "else", ":", "# The link already exists. Pull out the relevnt data.", "project_ref_dict", "=", "self", ".", "_other_pbxprojects", "[", "other_pbxproject", "]", "product_group", "=", "project_ref_dict", "[", "'ProductGroup'", "]", "project_ref", "=", "project_ref_dict", "[", "'ProjectRef'", "]", "self", ".", "_SetUpProductReferences", "(", "other_pbxproject", ",", "product_group", ",", "project_ref", ")", "inherit_unique_symroot", "=", "self", ".", "_AllSymrootsUnique", "(", "other_pbxproject", ",", "False", ")", "targets", "=", "other_pbxproject", ".", "GetProperty", "(", "'targets'", ")", "if", "all", "(", "self", ".", "_AllSymrootsUnique", "(", "t", ",", "inherit_unique_symroot", ")", "for", "t", "in", "targets", ")", ":", "dir_path", "=", "project_ref", ".", "_properties", "[", "'path'", "]", "product_group", ".", "_hashables", ".", "extend", "(", "dir_path", ")", "return", "[", "product_group", ",", "project_ref", "]" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L2669-L2747
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py
python
NextQueuedSequenceBatch.sequence_count
(self)
return self._state_saver._received_sequence_count
An int32 vector, length `batch_size`: the sequence count of each entry. When an input is split up, the number of splits is equal to: `padded_length / num_unroll`. This is the sequence_count. Returns: An int32 vector `Tensor`.
An int32 vector, length `batch_size`: the sequence count of each entry.
[ "An", "int32", "vector", "length", "batch_size", ":", "the", "sequence", "count", "of", "each", "entry", "." ]
def sequence_count(self): """An int32 vector, length `batch_size`: the sequence count of each entry. When an input is split up, the number of splits is equal to: `padded_length / num_unroll`. This is the sequence_count. Returns: An int32 vector `Tensor`. """ return self._state_saver._received_sequence_count
[ "def", "sequence_count", "(", "self", ")", ":", "return", "self", ".", "_state_saver", ".", "_received_sequence_count" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L469-L478
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/pyserial/serial/serialwin32.py
python
Win32Serial.read
(self, size=1)
return bytes(read)
Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.
Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.
[ "Read", "size", "bytes", "from", "the", "serial", "port", ".", "If", "a", "timeout", "is", "set", "it", "may", "return", "less", "characters", "as", "requested", ".", "With", "no", "timeout", "it", "will", "block", "until", "the", "requested", "number", "of", "bytes", "is", "read", "." ]
def read(self, size=1): """Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.""" if not self.hComPort: raise portNotOpenError if size > 0: win32.ResetEvent(self._overlappedRead.hEvent) flags = win32.DWORD() comstat = win32.COMSTAT() if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)): raise SerialException('call to ClearCommError failed') if self.timeout == 0: n = min(comstat.cbInQue, size) if n > 0: buf = ctypes.create_string_buffer(n) rc = win32.DWORD() err = win32.ReadFile(self.hComPort, buf, n, ctypes.byref(rc), ctypes.byref(self._overlappedRead)) if not err and win32.GetLastError() != win32.ERROR_IO_PENDING: raise SerialException("ReadFile failed (%r)" % ctypes.WinError()) err = win32.WaitForSingleObject(self._overlappedRead.hEvent, win32.INFINITE) read = buf.raw[:rc.value] else: read = bytes() else: buf = ctypes.create_string_buffer(size) rc = win32.DWORD() err = win32.ReadFile(self.hComPort, buf, size, ctypes.byref(rc), ctypes.byref(self._overlappedRead)) if not err and win32.GetLastError() != win32.ERROR_IO_PENDING: raise SerialException("ReadFile failed (%r)" % ctypes.WinError()) err = win32.GetOverlappedResult(self.hComPort, ctypes.byref(self._overlappedRead), ctypes.byref(rc), True) read = buf.raw[:rc.value] else: read = bytes() return bytes(read)
[ "def", "read", "(", "self", ",", "size", "=", "1", ")", ":", "if", "not", "self", ".", "hComPort", ":", "raise", "portNotOpenError", "if", "size", ">", "0", ":", "win32", ".", "ResetEvent", "(", "self", ".", "_overlappedRead", ".", "hEvent", ")", "flags", "=", "win32", ".", "DWORD", "(", ")", "comstat", "=", "win32", ".", "COMSTAT", "(", ")", "if", "not", "win32", ".", "ClearCommError", "(", "self", ".", "hComPort", ",", "ctypes", ".", "byref", "(", "flags", ")", ",", "ctypes", ".", "byref", "(", "comstat", ")", ")", ":", "raise", "SerialException", "(", "'call to ClearCommError failed'", ")", "if", "self", ".", "timeout", "==", "0", ":", "n", "=", "min", "(", "comstat", ".", "cbInQue", ",", "size", ")", "if", "n", ">", "0", ":", "buf", "=", "ctypes", ".", "create_string_buffer", "(", "n", ")", "rc", "=", "win32", ".", "DWORD", "(", ")", "err", "=", "win32", ".", "ReadFile", "(", "self", ".", "hComPort", ",", "buf", ",", "n", ",", "ctypes", ".", "byref", "(", "rc", ")", ",", "ctypes", ".", "byref", "(", "self", ".", "_overlappedRead", ")", ")", "if", "not", "err", "and", "win32", ".", "GetLastError", "(", ")", "!=", "win32", ".", "ERROR_IO_PENDING", ":", "raise", "SerialException", "(", "\"ReadFile failed (%r)\"", "%", "ctypes", ".", "WinError", "(", ")", ")", "err", "=", "win32", ".", "WaitForSingleObject", "(", "self", ".", "_overlappedRead", ".", "hEvent", ",", "win32", ".", "INFINITE", ")", "read", "=", "buf", ".", "raw", "[", ":", "rc", ".", "value", "]", "else", ":", "read", "=", "bytes", "(", ")", "else", ":", "buf", "=", "ctypes", ".", "create_string_buffer", "(", "size", ")", "rc", "=", "win32", ".", "DWORD", "(", ")", "err", "=", "win32", ".", "ReadFile", "(", "self", ".", "hComPort", ",", "buf", ",", "size", ",", "ctypes", ".", "byref", "(", "rc", ")", ",", "ctypes", ".", "byref", "(", "self", ".", "_overlappedRead", ")", ")", "if", "not", "err", "and", "win32", ".", "GetLastError", "(", ")", "!=", "win32", ".", "ERROR_IO_PENDING", ":", "raise", "SerialException", "(", "\"ReadFile failed (%r)\"", "%", "ctypes", ".", "WinError", "(", ")", ")", "err", "=", "win32", ".", "GetOverlappedResult", "(", "self", ".", "hComPort", ",", "ctypes", ".", "byref", "(", "self", ".", "_overlappedRead", ")", ",", "ctypes", ".", "byref", "(", "rc", ")", ",", "True", ")", "read", "=", "buf", ".", "raw", "[", ":", "rc", ".", "value", "]", "else", ":", "read", "=", "bytes", "(", ")", "return", "bytes", "(", "read", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/serialwin32.py#L242-L275
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/threading.py
python
_RLock.release
(self)
Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value.
Release a lock, decrementing the recursion level.
[ "Release", "a", "lock", "decrementing", "the", "recursion", "level", "." ]
def release(self): """Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value. """ if self.__owner != _get_ident(): raise RuntimeError("cannot release un-acquired lock") self.__count = count = self.__count - 1 if not count: self.__owner = None self.__block.release() if __debug__: self._note("%s.release(): final release", self) else: if __debug__: self._note("%s.release(): non-final release", self)
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "__owner", "!=", "_get_ident", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot release un-acquired lock\"", ")", "self", ".", "__count", "=", "count", "=", "self", ".", "__count", "-", "1", "if", "not", "count", ":", "self", ".", "__owner", "=", "None", "self", ".", "__block", ".", "release", "(", ")", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.release(): final release\"", ",", "self", ")", "else", ":", "if", "__debug__", ":", "self", ".", "_note", "(", "\"%s.release(): non-final release\"", ",", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/threading.py#L186-L212
sigmaai/self-driving-golf-cart
8d891600af3d851add27a10ae45cf3c2108bb87c
ros/src/detection/object_detection/scripts/yolo3/model.py
python
DarknetConv2D
(*args, **kwargs)
return Conv2D(*args, **darknet_conv_kwargs)
Wrapper to set Darknet parameters for Convolution2D.
Wrapper to set Darknet parameters for Convolution2D.
[ "Wrapper", "to", "set", "Darknet", "parameters", "for", "Convolution2D", "." ]
def DarknetConv2D(*args, **kwargs): """Wrapper to set Darknet parameters for Convolution2D.""" darknet_conv_kwargs = {'kernel_regularizer': l2(5e-4)} darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides')==(2,2) else 'same' darknet_conv_kwargs.update(kwargs) return Conv2D(*args, **darknet_conv_kwargs)
[ "def", "DarknetConv2D", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "darknet_conv_kwargs", "=", "{", "'kernel_regularizer'", ":", "l2", "(", "5e-4", ")", "}", "darknet_conv_kwargs", "[", "'padding'", "]", "=", "'valid'", "if", "kwargs", ".", "get", "(", "'strides'", ")", "==", "(", "2", ",", "2", ")", "else", "'same'", "darknet_conv_kwargs", ".", "update", "(", "kwargs", ")", "return", "Conv2D", "(", "*", "args", ",", "*", "*", "darknet_conv_kwargs", ")" ]
https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/detection/object_detection/scripts/yolo3/model.py#L23-L29
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/request.py
python
RequestMethods.request_encode_body
( self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw )
return self.urlopen(method, url, **extra_kw)
Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :func:`urllib3.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :func:`urllib.parse.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter.
Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc.
[ "Make", "a", "request", "using", ":", "meth", ":", "urlopen", "with", "the", "fields", "encoded", "in", "the", "body", ".", "This", "is", "useful", "for", "request", "methods", "like", "POST", "PUT", "PATCH", "etc", "." ]
def request_encode_body( self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw ): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :func:`urllib3.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :func:`urllib.parse.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter. """ if headers is None: headers = self.headers extra_kw = {"headers": {}} if fields: if "body" in urlopen_kw: raise TypeError( "request got values for both 'fields' and 'body', can only specify one." ) if encode_multipart: body, content_type = encode_multipart_formdata( fields, boundary=multipart_boundary ) else: body, content_type = ( urlencode(fields), "application/x-www-form-urlencoded", ) extra_kw["body"] = body extra_kw["headers"] = {"Content-Type": content_type} extra_kw["headers"].update(headers) extra_kw.update(urlopen_kw) return self.urlopen(method, url, **extra_kw)
[ "def", "request_encode_body", "(", "self", ",", "method", ",", "url", ",", "fields", "=", "None", ",", "headers", "=", "None", ",", "encode_multipart", "=", "True", ",", "multipart_boundary", "=", "None", ",", "*", "*", "urlopen_kw", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "self", ".", "headers", "extra_kw", "=", "{", "\"headers\"", ":", "{", "}", "}", "if", "fields", ":", "if", "\"body\"", "in", "urlopen_kw", ":", "raise", "TypeError", "(", "\"request got values for both 'fields' and 'body', can only specify one.\"", ")", "if", "encode_multipart", ":", "body", ",", "content_type", "=", "encode_multipart_formdata", "(", "fields", ",", "boundary", "=", "multipart_boundary", ")", "else", ":", "body", ",", "content_type", "=", "(", "urlencode", "(", "fields", ")", ",", "\"application/x-www-form-urlencoded\"", ",", ")", "extra_kw", "[", "\"body\"", "]", "=", "body", "extra_kw", "[", "\"headers\"", "]", "=", "{", "\"Content-Type\"", ":", "content_type", "}", "extra_kw", "[", "\"headers\"", "]", ".", "update", "(", "headers", ")", "extra_kw", ".", "update", "(", "urlopen_kw", ")", "return", "self", ".", "urlopen", "(", "method", ",", "url", ",", "*", "*", "extra_kw", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/request.py#L98-L170
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/google/protobuf/text_format.py
python
ParseInteger
(text, is_signed=False, is_long=False)
return result
Parses an integer. Args: text: The text to parse. is_signed: True if a signed integer must be parsed. is_long: True if a long integer must be parsed. Returns: The integer value. Raises: ValueError: Thrown Iff the text is not a valid integer.
Parses an integer.
[ "Parses", "an", "integer", "." ]
def ParseInteger(text, is_signed=False, is_long=False): """Parses an integer. Args: text: The text to parse. is_signed: True if a signed integer must be parsed. is_long: True if a long integer must be parsed. Returns: The integer value. Raises: ValueError: Thrown Iff the text is not a valid integer. """ # Do the actual parsing. Exception handling is propagated to caller. try: # We force 32-bit values to int and 64-bit values to long to make # alternate implementations where the distinction is more significant # (e.g. the C++ implementation) simpler. if is_long: result = long(text, 0) else: result = int(text, 0) except ValueError: raise ValueError('Couldn\'t parse integer: %s' % text) # Check if the integer is sane. Exceptions handled by callers. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)] checker.CheckValue(result) return result
[ "def", "ParseInteger", "(", "text", ",", "is_signed", "=", "False", ",", "is_long", "=", "False", ")", ":", "# Do the actual parsing. Exception handling is propagated to caller.", "try", ":", "# We force 32-bit values to int and 64-bit values to long to make", "# alternate implementations where the distinction is more significant", "# (e.g. the C++ implementation) simpler.", "if", "is_long", ":", "result", "=", "long", "(", "text", ",", "0", ")", "else", ":", "result", "=", "int", "(", "text", ",", "0", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Couldn\\'t parse integer: %s'", "%", "text", ")", "# Check if the integer is sane. Exceptions handled by callers.", "checker", "=", "_INTEGER_CHECKERS", "[", "2", "*", "int", "(", "is_long", ")", "+", "int", "(", "is_signed", ")", "]", "checker", ".", "CheckValue", "(", "result", ")", "return", "result" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/text_format.py#L1102-L1131
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/cpplint.py
python
CheckForMultilineCommentsAndStrings
(filename, clean_lines, linenum, error)
Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Logs an error if we see /* ... */ or "..." that extend past one line.
[ "Logs", "an", "error", "if", "we", "see", "/", "*", "...", "*", "/", "or", "...", "that", "extend", "past", "one", "line", "." ]
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.')
[ "def", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the", "# second (escaped) slash may trigger later \\\" detection erroneously.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "line", ".", "count", "(", "'/*'", ")", ">", "line", ".", "count", "(", "'*/'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_comment'", ",", "5", ",", "'Complex multi-line /*...*/-style comment found. '", "'Lint may give bogus warnings. '", "'Consider replacing these with //-style comments, '", "'with #if 0...#endif, '", "'or with more clearly structured multi-line comments.'", ")", "if", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ")", ")", "%", "2", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_string'", ",", "5", ",", "'Multi-line string (\"...\") found. This lint script doesn\\'t '", "'do well with such strings, and may give bogus warnings. '", "'Use C++11 raw strings or concatenation instead.'", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L2570-L2605