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
greenheartgames/greenworks
3ea4ab490b56676de3f0a237c74bcfdb17323e60
deps/cpplint/cpplint.py
python
FileInfo.BaseName
(self)
return self.Split()[1]
File base name - text after the final slash, before the final period.
File base name - text after the final slash, before the final period.
[ "File", "base", "name", "-", "text", "after", "the", "final", "slash", "before", "the", "final", "period", "." ]
def BaseName(self): """File base name - text after the final slash, before the final period.""" return self.Split()[1]
[ "def", "BaseName", "(", "self", ")", ":", "return", "self", ".", "Split", "(", ")", "[", "1", "]" ]
https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L1144-L1146
NERSC/timemory
431912b360ff50d1a160d7826e2eea04fbd1037f
scripts/gprof2dot.py
python
Theme.hsl_to_rgb
(self, h, s, l)
return (r, g, b)
Convert a color from HSL color-model to RGB. See also: - http://www.w3.org/TR/css3-color/#hsl-color
Convert a color from HSL color-model to RGB.
[ "Convert", "a", "color", "from", "HSL", "color", "-", "model", "to", "RGB", "." ]
def hsl_to_rgb(self, h, s, l): """Convert a color from HSL color-model to RGB. See also: - http://www.w3.org/TR/css3-color/#hsl-color """ h = h % 1.0 s = min(max(s, 0.0), 1.0) l = min(max(l, 0.0), 1.0) if l <= 0.5: m2 = l*(s + 1.0) else: m2 = l + s - l*s m1 = l*2.0 - m2 r = self._hue_to_rgb(m1, m2, h + 1.0/3.0) g = self._hue_to_rgb(m1, m2, h) b = self._hue_to_rgb(m1, m2, h - 1.0/3.0) # Apply gamma correction r **= self.gamma g **= self.gamma b **= self.gamma return (r, g, b)
[ "def", "hsl_to_rgb", "(", "self", ",", "h", ",", "s", ",", "l", ")", ":", "h", "=", "h", "%", "1.0", "s", "=", "min", "(", "max", "(", "s", ",", "0.0", ")", ",", "1.0", ")", "l", "=", "min", "(", "max", "(", "l", ",", "0.0", ")", ",", "1.0", ")", "if", "l", "<=", "0.5", ":", "m2", "=", "l", "*", "(", "s", "+", "1.0", ")", "else", ":", "m2", "=", "l", "+", "s", "-", "l", "*", "s", "m1", "=", "l", "*", "2.0", "-", "m2", "r", "=", "self", ".", "_hue_to_rgb", "(", "m1", ",", "m2", ",", "h", "+", "1.0", "/", "3.0", ")", "g", "=", "self", ".", "_hue_to_rgb", "(", "m1", ",", "m2", ",", "h", ")", "b", "=", "self", ".", "_hue_to_rgb", "(", "m1", ",", "m2", ",", "h", "-", "1.0", "/", "3.0", ")", "# Apply gamma correction", "r", "**=", "self", ".", "gamma", "g", "**=", "self", ".", "gamma", "b", "**=", "self", ".", "gamma", "return", "(", "r", ",", "g", ",", "b", ")" ]
https://github.com/NERSC/timemory/blob/431912b360ff50d1a160d7826e2eea04fbd1037f/scripts/gprof2dot.py#L2863-L2888
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py
python
Node.select_scanner
(self, scanner)
return scanner.select(self)
Selects a scanner for this Node. This is a separate method so it can be overridden by Node subclasses (specifically, Node.FS.Dir) that *must* use their own Scanner and don't select one the Scanner.Selector that's configured for the target.
Selects a scanner for this Node.
[ "Selects", "a", "scanner", "for", "this", "Node", "." ]
def select_scanner(self, scanner): """Selects a scanner for this Node. This is a separate method so it can be overridden by Node subclasses (specifically, Node.FS.Dir) that *must* use their own Scanner and don't select one the Scanner.Selector that's configured for the target. """ return scanner.select(self)
[ "def", "select_scanner", "(", "self", ",", "scanner", ")", ":", "return", "scanner", ".", "select", "(", "self", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py#L1062-L1070
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
RegionIterator.GetW
(*args, **kwargs)
return _gdi_.RegionIterator_GetW(*args, **kwargs)
GetW(self) -> int
GetW(self) -> int
[ "GetW", "(", "self", ")", "-", ">", "int" ]
def GetW(*args, **kwargs): """GetW(self) -> int""" return _gdi_.RegionIterator_GetW(*args, **kwargs)
[ "def", "GetW", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "RegionIterator_GetW", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1678-L1680
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/texture.py
python
Texture.dtype
(self)
return self._dtype
str: Data type.
str: Data type.
[ "str", ":", "Data", "type", "." ]
def dtype(self) -> str: ''' str: Data type. ''' return self._dtype
[ "def", "dtype", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_dtype" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/texture.py#L285-L290
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py
python
_StandaloneConnection.__init__
(self, request_handler)
Construct an instance. Args: request_handler: A WebSocketRequestHandler instance.
Construct an instance.
[ "Construct", "an", "instance", "." ]
def __init__(self, request_handler): """Construct an instance. Args: request_handler: A WebSocketRequestHandler instance. """ self._request_handler = request_handler
[ "def", "__init__", "(", "self", ",", "request_handler", ")", ":", "self", ".", "_request_handler", "=", "request_handler" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py#L201-L208
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py2/jinja2/runtime.py
python
Context.call
(__self, __obj, *args, **kwargs)
Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`.
Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`.
[ "Call", "the", "callable", "with", "the", "arguments", "and", "keyword", "arguments", "provided", "but", "inject", "the", "active", "context", "or", "environment", "as", "first", "argument", "if", "the", "callable", "is", "a", ":", "func", ":", "contextfunction", "or", ":", "func", ":", "environmentfunction", "." ]
def call(__self, __obj, *args, **kwargs): # noqa: B902 """Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`. """ if __debug__: __traceback_hide__ = True # noqa # Allow callable classes to take a context if hasattr(__obj, "__call__"): # noqa: B004 fn = __obj.__call__ for fn_type in ( "contextfunction", "evalcontextfunction", "environmentfunction", ): if hasattr(fn, fn_type): __obj = fn break if callable(__obj): if getattr(__obj, "contextfunction", False) is True: args = (__self,) + args elif getattr(__obj, "evalcontextfunction", False) is True: args = (__self.eval_ctx,) + args elif getattr(__obj, "environmentfunction", False) is True: args = (__self.environment,) + args try: return __obj(*args, **kwargs) except StopIteration: return __self.environment.undefined( "value was undefined because " "a callable raised a " "StopIteration exception" )
[ "def", "call", "(", "__self", ",", "__obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# noqa: B902", "if", "__debug__", ":", "__traceback_hide__", "=", "True", "# noqa", "# Allow callable classes to take a context", "if", "hasattr", "(", "__obj", ",", "\"__call__\"", ")", ":", "# noqa: B004", "fn", "=", "__obj", ".", "__call__", "for", "fn_type", "in", "(", "\"contextfunction\"", ",", "\"evalcontextfunction\"", ",", "\"environmentfunction\"", ",", ")", ":", "if", "hasattr", "(", "fn", ",", "fn_type", ")", ":", "__obj", "=", "fn", "break", "if", "callable", "(", "__obj", ")", ":", "if", "getattr", "(", "__obj", ",", "\"contextfunction\"", ",", "False", ")", "is", "True", ":", "args", "=", "(", "__self", ",", ")", "+", "args", "elif", "getattr", "(", "__obj", ",", "\"evalcontextfunction\"", ",", "False", ")", "is", "True", ":", "args", "=", "(", "__self", ".", "eval_ctx", ",", ")", "+", "args", "elif", "getattr", "(", "__obj", ",", "\"environmentfunction\"", ",", "False", ")", "is", "True", ":", "args", "=", "(", "__self", ".", "environment", ",", ")", "+", "args", "try", ":", "return", "__obj", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "StopIteration", ":", "return", "__self", ".", "environment", ".", "undefined", "(", "\"value was undefined because \"", "\"a callable raised a \"", "\"StopIteration exception\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/runtime.py#L261-L296
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/code_coverage/croc.py
python
Coverage.ParseConfig
(self, filename, **kwargs)
Parses a configuration file. Args: filename: Config filename. kwargs: Additional parameters to pass to AddConfig().
Parses a configuration file.
[ "Parses", "a", "configuration", "file", "." ]
def ParseConfig(self, filename, **kwargs): """Parses a configuration file. Args: filename: Config filename. kwargs: Additional parameters to pass to AddConfig(). """ # TODO: All manner of error checking f = None try: f = open(filename, 'rt') # Need to strip CR's from CRLF-terminated lines or posix systems can't # eval the data. config_data = f.read().replace('\r\n', '\n') # TODO: some sort of include syntax. # # Needs to be done at string-time rather than at eval()-time, so that # it's possible to include parts of dicts. Path from a file to its # include should be relative to the dir containing the file. # # Or perhaps it could be done after eval. In that case, there'd be an # 'include' section with a list of files to include. Those would be # eval()'d and recursively pre- or post-merged with the including file. # # Or maybe just don't worry about it, since multiple configs can be # specified on the command line. self.AddConfig(config_data, **kwargs) finally: if f: f.close()
[ "def", "ParseConfig", "(", "self", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "# TODO: All manner of error checking", "f", "=", "None", "try", ":", "f", "=", "open", "(", "filename", ",", "'rt'", ")", "# Need to strip CR's from CRLF-terminated lines or posix systems can't", "# eval the data.", "config_data", "=", "f", ".", "read", "(", ")", ".", "replace", "(", "'\\r\\n'", ",", "'\\n'", ")", "# TODO: some sort of include syntax.", "#", "# Needs to be done at string-time rather than at eval()-time, so that", "# it's possible to include parts of dicts. Path from a file to its", "# include should be relative to the dir containing the file.", "#", "# Or perhaps it could be done after eval. In that case, there'd be an", "# 'include' section with a list of files to include. Those would be", "# eval()'d and recursively pre- or post-merged with the including file.", "#", "# Or maybe just don't worry about it, since multiple configs can be", "# specified on the command line.", "self", ".", "AddConfig", "(", "config_data", ",", "*", "*", "kwargs", ")", "finally", ":", "if", "f", ":", "f", ".", "close", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/code_coverage/croc.py#L539-L568
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenu.SendOverItem
(self, itemIdx, over)
Sends the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` and ``EVT_FLAT_MENU_ITEM_MOUSE_OUT`` events. :param integer `itemIdx`: the menu item index for which we want to send an event; :param bool `over`: ``True`` to send a ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event, ``False`` to send a ``EVT_FLAT_MENU_ITEM_MOUSE_OUT`` event.
Sends the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` and ``EVT_FLAT_MENU_ITEM_MOUSE_OUT`` events.
[ "Sends", "the", "EVT_FLAT_MENU_ITEM_MOUSE_OVER", "and", "EVT_FLAT_MENU_ITEM_MOUSE_OUT", "events", "." ]
def SendOverItem(self, itemIdx, over): """ Sends the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` and ``EVT_FLAT_MENU_ITEM_MOUSE_OUT`` events. :param integer `itemIdx`: the menu item index for which we want to send an event; :param bool `over`: ``True`` to send a ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event, ``False`` to send a ``EVT_FLAT_MENU_ITEM_MOUSE_OUT`` event. """ item = self._itemsArr[itemIdx] # Create the event event = FlatMenuEvent((over and [wxEVT_FLAT_MENU_ITEM_MOUSE_OVER] or [wxEVT_FLAT_MENU_ITEM_MOUSE_OUT])[0], item.GetId()) # For checkable item, set the IsChecked() value if item.IsCheckable(): event.SetInt((item.IsChecked() and [1] or [0])[0]) event.SetEventObject(self) if self._owner: self._owner.GetEventHandler().ProcessEvent(event) else: self.GetEventHandler().ProcessEvent(event)
[ "def", "SendOverItem", "(", "self", ",", "itemIdx", ",", "over", ")", ":", "item", "=", "self", ".", "_itemsArr", "[", "itemIdx", "]", "# Create the event", "event", "=", "FlatMenuEvent", "(", "(", "over", "and", "[", "wxEVT_FLAT_MENU_ITEM_MOUSE_OVER", "]", "or", "[", "wxEVT_FLAT_MENU_ITEM_MOUSE_OUT", "]", ")", "[", "0", "]", ",", "item", ".", "GetId", "(", ")", ")", "# For checkable item, set the IsChecked() value", "if", "item", ".", "IsCheckable", "(", ")", ":", "event", ".", "SetInt", "(", "(", "item", ".", "IsChecked", "(", ")", "and", "[", "1", "]", "or", "[", "0", "]", ")", "[", "0", "]", ")", "event", ".", "SetEventObject", "(", "self", ")", "if", "self", ".", "_owner", ":", "self", ".", "_owner", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "event", ")", "else", ":", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "event", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L6992-L7016
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Optimizer/vai_p_pytorch/cifar10/analyse.py
python
accuracy
(output, target, topk=(1,))
Computes the accuracy over the k top predictions for the specified values of k
Computes the accuracy over the k top predictions for the specified values of k
[ "Computes", "the", "accuracy", "over", "the", "k", "top", "predictions", "for", "the", "specified", "values", "of", "k" ]
def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].flatten().float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res
[ "def", "accuracy", "(", "output", ",", "target", ",", "topk", "=", "(", "1", ",", ")", ")", ":", "with", "torch", ".", "no_grad", "(", ")", ":", "maxk", "=", "max", "(", "topk", ")", "batch_size", "=", "target", ".", "size", "(", "0", ")", "_", ",", "pred", "=", "output", ".", "topk", "(", "maxk", ",", "1", ",", "True", ",", "True", ")", "pred", "=", "pred", ".", "t", "(", ")", "correct", "=", "pred", ".", "eq", "(", "target", ".", "view", "(", "1", ",", "-", "1", ")", ".", "expand_as", "(", "pred", ")", ")", "res", "=", "[", "]", "for", "k", "in", "topk", ":", "correct_k", "=", "correct", "[", ":", "k", "]", ".", "flatten", "(", ")", ".", "float", "(", ")", ".", "sum", "(", "0", ",", "keepdim", "=", "True", ")", "res", ".", "append", "(", "correct_k", ".", "mul_", "(", "100.0", "/", "batch_size", ")", ")", "return", "res" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Optimizer/vai_p_pytorch/cifar10/analyse.py#L60-L75
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/multiprocessing/__init__.py
python
set_sharing_strategy
(new_strategy)
Sets the strategy for sharing CPU tensors. Args: new_strategy (str): Name of the selected strategy. Should be one of the values returned by :func:`get_all_sharing_strategies()`.
Sets the strategy for sharing CPU tensors.
[ "Sets", "the", "strategy", "for", "sharing", "CPU", "tensors", "." ]
def set_sharing_strategy(new_strategy): """Sets the strategy for sharing CPU tensors. Args: new_strategy (str): Name of the selected strategy. Should be one of the values returned by :func:`get_all_sharing_strategies()`. """ global _sharing_strategy assert new_strategy in _all_sharing_strategies _sharing_strategy = new_strategy
[ "def", "set_sharing_strategy", "(", "new_strategy", ")", ":", "global", "_sharing_strategy", "assert", "new_strategy", "in", "_all_sharing_strategies", "_sharing_strategy", "=", "new_strategy" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/multiprocessing/__init__.py#L50-L59
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
armoryengine/ArmoryUtils.py
python
SettingsFile.extend
(self, name, value)
Adds/converts setting to list, appends value to the end of it
Adds/converts setting to list, appends value to the end of it
[ "Adds", "/", "converts", "setting", "to", "list", "appends", "value", "to", "the", "end", "of", "it" ]
def extend(self, name, value): """ Adds/converts setting to list, appends value to the end of it """ if not self.settingsMap.has_key(name): if isinstance(value, list): self.set(name, value) else: self.set(name, [value]) else: origVal = self.get(name, expectList=True) if isinstance(value, list): origVal.extend(value) else: origVal.append(value) self.settingsMap[name] = origVal self.writeSettingsFile()
[ "def", "extend", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "self", ".", "settingsMap", ".", "has_key", "(", "name", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "self", ".", "set", "(", "name", ",", "value", ")", "else", ":", "self", ".", "set", "(", "name", ",", "[", "value", "]", ")", "else", ":", "origVal", "=", "self", ".", "get", "(", "name", ",", "expectList", "=", "True", ")", "if", "isinstance", "(", "value", ",", "list", ")", ":", "origVal", ".", "extend", "(", "value", ")", "else", ":", "origVal", ".", "append", "(", "value", ")", "self", ".", "settingsMap", "[", "name", "]", "=", "origVal", "self", ".", "writeSettingsFile", "(", ")" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/ArmoryUtils.py#L3558-L3572
TimoSaemann/caffe-segnet-cudnn5
abcf30dca449245e101bf4ced519f716177f0885
scripts/cpp_lint.py
python
CheckForHeaderGuard
(filename, lines, error)
Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Checks that the file contains a header guard.
[ "Checks", "that", "the", "file", "contains", "a", "header", "guard", "." ]
def CheckForHeaderGuard(filename, lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ cppvar = GetHeaderGuardCPPVariable(filename) ifndef = None ifndef_linenum = 0 define = None endif = None endif_linenum = 0 for linenum, line in enumerate(lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return if not define: error(filename, 0, 'build/header_guard', 5, 'No #define header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) if define != ifndef: error(filename, 0, 'build/header_guard', 5, '#ifndef and #define don\'t match, suggested CPP variable is: %s' % cppvar) return if endif != ('#endif // %s' % cppvar): error_level = 0 if endif != ('#endif // %s' % (cppvar + '_')): error_level = 5 ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum, error) error(filename, endif_linenum, 'build/header_guard', error_level, '#endif line should be "#endif // %s"' % cppvar)
[ "def", "CheckForHeaderGuard", "(", "filename", ",", "lines", ",", "error", ")", ":", "cppvar", "=", "GetHeaderGuardCPPVariable", "(", "filename", ")", "ifndef", "=", "None", "ifndef_linenum", "=", "0", "define", "=", "None", "endif", "=", "None", "endif_linenum", "=", "0", "for", "linenum", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "linesplit", "=", "line", ".", "split", "(", ")", "if", "len", "(", "linesplit", ")", ">=", "2", ":", "# find the first occurrence of #ifndef and #define, save arg", "if", "not", "ifndef", "and", "linesplit", "[", "0", "]", "==", "'#ifndef'", ":", "# set ifndef to the header guard presented on the #ifndef line.", "ifndef", "=", "linesplit", "[", "1", "]", "ifndef_linenum", "=", "linenum", "if", "not", "define", "and", "linesplit", "[", "0", "]", "==", "'#define'", ":", "define", "=", "linesplit", "[", "1", "]", "# find the last occurrence of #endif, save entire line", "if", "line", ".", "startswith", "(", "'#endif'", ")", ":", "endif", "=", "line", "endif_linenum", "=", "linenum", "if", "not", "ifndef", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #ifndef header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "if", "not", "define", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #define header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__", "# for backward compatibility.", "if", "ifndef", "!=", "cppvar", ":", "error_level", "=", "0", "if", "ifndef", "!=", "cppvar", "+", "'_'", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "lines", "[", "ifndef_linenum", "]", ",", "ifndef_linenum", ",", "error", ")", "error", "(", "filename", ",", "ifndef_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#ifndef header guard has wrong style, please use: %s'", "%", "cppvar", ")", "if", "define", "!=", "ifndef", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'#ifndef and #define don\\'t match, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "if", "endif", "!=", "(", "'#endif // %s'", "%", "cppvar", ")", ":", "error_level", "=", "0", "if", "endif", "!=", "(", "'#endif // %s'", "%", "(", "cppvar", "+", "'_'", ")", ")", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "lines", "[", "endif_linenum", "]", ",", "endif_linenum", ",", "error", ")", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#endif line should be \"#endif // %s\"'", "%", "cppvar", ")" ]
https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L1408-L1480
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
util/py_lib/seqan/dox/proc_doc.py
python
EntryConverter.bodyToTextNode
(self, raw_body)
return res
Convert a RawBody to a TextNode.
Convert a RawBody to a TextNode.
[ "Convert", "a", "RawBody", "to", "a", "TextNode", "." ]
def bodyToTextNode(self, raw_body): """Convert a RawBody to a TextNode.""" res = TextNode(type='div') for p in raw_body.paragraphs: try: if p.getType() == 'paragraph': if not p.text.text.strip(): continue # Skip whitespace p = self.rawTextToTextNode(p.text) p.type = 'p' res.addChild(p) elif p.getType() == 'section': h = self.rawTextToTextNode(p.heading) h.type = 'h%d' % (p.level + 1) res.addChild(h) elif p.getType() == 'include': # Including a whole file. ftype = os.path.splitext(p.path.text)[1] code_text = self.doc_proc.include_mgr.loadFile(p.path.text) proc_include = TextNode(type='dox:code', attrs={'type': ftype, 'source': 'include', 'path': p.path.text}) proc_include.addChild(TextNode(text=code_text, verbatim=True)) res.addChild(proc_include) elif p.getType() == 'snippet': # Including a snippet file. ftype = os.path.splitext(p.path.text)[1] code_text = self.doc_proc.include_mgr.loadSnippet(p.path.text, p.name.text) proc_snippet = TextNode(type='dox:code', attrs={'type': ftype, 'source': 'snippet', 'path': p.path.text}) proc_snippet.addChild(TextNode(text=code_text, verbatim=True)) res.addChild(proc_snippet) elif p.getType() == 'code': code_text = p.text.text type = '.txt' m = re.match(r'^{[^}]+}', code_text) if m: type = m.group(0)[1:-1] code_text = code_text[len(type) + 2:].strip() #print [repr(t.val) for t in p.text.tokens] x = TextNode(type='dox:code', attrs={'type': type}) x.addChild(TextNode(text=code_text, verbatim=True)) res.addChild(x) elif p.getType() == 'htmlonly': res.addChild(TextNode(text=p.text.text, verbatim=True)) except inc_mgr.IncludeException, e: e2 = dox_parser.ParserError(msg=str(e), token=p.text.tokens[0]) self.doc_proc.msg_printer.printParserError(e2) n = TextNode(type='div', attrs={'class': 'note warning'}) n.children.append(TextNode(text=str(e))) res.addChild(n) return res
[ "def", "bodyToTextNode", "(", "self", ",", "raw_body", ")", ":", "res", "=", "TextNode", "(", "type", "=", "'div'", ")", "for", "p", "in", "raw_body", ".", "paragraphs", ":", "try", ":", "if", "p", ".", "getType", "(", ")", "==", "'paragraph'", ":", "if", "not", "p", ".", "text", ".", "text", ".", "strip", "(", ")", ":", "continue", "# Skip whitespace", "p", "=", "self", ".", "rawTextToTextNode", "(", "p", ".", "text", ")", "p", ".", "type", "=", "'p'", "res", ".", "addChild", "(", "p", ")", "elif", "p", ".", "getType", "(", ")", "==", "'section'", ":", "h", "=", "self", ".", "rawTextToTextNode", "(", "p", ".", "heading", ")", "h", ".", "type", "=", "'h%d'", "%", "(", "p", ".", "level", "+", "1", ")", "res", ".", "addChild", "(", "h", ")", "elif", "p", ".", "getType", "(", ")", "==", "'include'", ":", "# Including a whole file.", "ftype", "=", "os", ".", "path", ".", "splitext", "(", "p", ".", "path", ".", "text", ")", "[", "1", "]", "code_text", "=", "self", ".", "doc_proc", ".", "include_mgr", ".", "loadFile", "(", "p", ".", "path", ".", "text", ")", "proc_include", "=", "TextNode", "(", "type", "=", "'dox:code'", ",", "attrs", "=", "{", "'type'", ":", "ftype", ",", "'source'", ":", "'include'", ",", "'path'", ":", "p", ".", "path", ".", "text", "}", ")", "proc_include", ".", "addChild", "(", "TextNode", "(", "text", "=", "code_text", ",", "verbatim", "=", "True", ")", ")", "res", ".", "addChild", "(", "proc_include", ")", "elif", "p", ".", "getType", "(", ")", "==", "'snippet'", ":", "# Including a snippet file.", "ftype", "=", "os", ".", "path", ".", "splitext", "(", "p", ".", "path", ".", "text", ")", "[", "1", "]", "code_text", "=", "self", ".", "doc_proc", ".", "include_mgr", ".", "loadSnippet", "(", "p", ".", "path", ".", "text", ",", "p", ".", "name", ".", "text", ")", "proc_snippet", "=", "TextNode", "(", "type", "=", "'dox:code'", ",", "attrs", "=", "{", "'type'", ":", "ftype", ",", "'source'", ":", "'snippet'", ",", "'path'", ":", "p", ".", "path", ".", "text", "}", ")", "proc_snippet", ".", "addChild", "(", "TextNode", "(", "text", "=", "code_text", ",", "verbatim", "=", "True", ")", ")", "res", ".", "addChild", "(", "proc_snippet", ")", "elif", "p", ".", "getType", "(", ")", "==", "'code'", ":", "code_text", "=", "p", ".", "text", ".", "text", "type", "=", "'.txt'", "m", "=", "re", ".", "match", "(", "r'^{[^}]+}'", ",", "code_text", ")", "if", "m", ":", "type", "=", "m", ".", "group", "(", "0", ")", "[", "1", ":", "-", "1", "]", "code_text", "=", "code_text", "[", "len", "(", "type", ")", "+", "2", ":", "]", ".", "strip", "(", ")", "#print [repr(t.val) for t in p.text.tokens]", "x", "=", "TextNode", "(", "type", "=", "'dox:code'", ",", "attrs", "=", "{", "'type'", ":", "type", "}", ")", "x", ".", "addChild", "(", "TextNode", "(", "text", "=", "code_text", ",", "verbatim", "=", "True", ")", ")", "res", ".", "addChild", "(", "x", ")", "elif", "p", ".", "getType", "(", ")", "==", "'htmlonly'", ":", "res", ".", "addChild", "(", "TextNode", "(", "text", "=", "p", ".", "text", ".", "text", ",", "verbatim", "=", "True", ")", ")", "except", "inc_mgr", ".", "IncludeException", ",", "e", ":", "e2", "=", "dox_parser", ".", "ParserError", "(", "msg", "=", "str", "(", "e", ")", ",", "token", "=", "p", ".", "text", ".", "tokens", "[", "0", "]", ")", "self", ".", "doc_proc", ".", "msg_printer", ".", "printParserError", "(", "e2", ")", "n", "=", "TextNode", "(", "type", "=", "'div'", ",", "attrs", "=", "{", "'class'", ":", "'note warning'", "}", ")", "n", ".", "children", ".", "append", "(", "TextNode", "(", "text", "=", "str", "(", "e", ")", ")", ")", "res", ".", "addChild", "(", "n", ")", "return", "res" ]
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dox/proc_doc.py#L1155-L1203
yuxng/DA-RNN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
lib/datasets/rgbd_scene.py
python
rgbd_scene.depth_path_from_index
(self, index)
return depth_path
Construct an depth path from the image's "index" identifier.
Construct an depth path from the image's "index" identifier.
[ "Construct", "an", "depth", "path", "from", "the", "image", "s", "index", "identifier", "." ]
def depth_path_from_index(self, index): """ Construct an depth path from the image's "index" identifier. """ depth_path = os.path.join(self._data_path, index + '-depth' + self._image_ext) assert os.path.exists(depth_path), \ 'Path does not exist: {}'.format(depth_path) return depth_path
[ "def", "depth_path_from_index", "(", "self", ",", "index", ")", ":", "depth_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_path", ",", "index", "+", "'-depth'", "+", "self", ".", "_image_ext", ")", "assert", "os", ".", "path", ".", "exists", "(", "depth_path", ")", ",", "'Path does not exist: {}'", ".", "format", "(", "depth_path", ")", "return", "depth_path" ]
https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/rgbd_scene.py#L55-L62
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/dataset/wmt16.py
python
get_dict
(lang, dict_size, reverse=False)
return __load_dict(tar_file, dict_size, lang, reverse)
return the word dictionary for the specified language. Args: lang(string): A string indicating which language is the source language. Available options are: "en" for English and "de" for Germany. dict_size(int): Size of the specified language dictionary. reverse(bool): If reverse is set to False, the returned python dictionary will use word as key and use index as value. If reverse is set to True, the returned python dictionary will use index as key and word as value. Returns: dict: The word dictionary for the specific language.
return the word dictionary for the specified language.
[ "return", "the", "word", "dictionary", "for", "the", "specified", "language", "." ]
def get_dict(lang, dict_size, reverse=False): """ return the word dictionary for the specified language. Args: lang(string): A string indicating which language is the source language. Available options are: "en" for English and "de" for Germany. dict_size(int): Size of the specified language dictionary. reverse(bool): If reverse is set to False, the returned python dictionary will use word as key and use index as value. If reverse is set to True, the returned python dictionary will use index as key and word as value. Returns: dict: The word dictionary for the specific language. """ if lang == "en": dict_size = min(dict_size, TOTAL_EN_WORDS) else: dict_size = min(dict_size, TOTAL_DE_WORDS) dict_path = os.path.join(paddle.dataset.common.DATA_HOME, "wmt16/%s_%d.dict" % (lang, dict_size)) assert os.path.exists(dict_path), "Word dictionary does not exist. " "Please invoke paddle.dataset.wmt16.train/test/validation first " "to build the dictionary." tar_file = os.path.join(paddle.dataset.common.DATA_HOME, "wmt16.tar.gz") return __load_dict(tar_file, dict_size, lang, reverse)
[ "def", "get_dict", "(", "lang", ",", "dict_size", ",", "reverse", "=", "False", ")", ":", "if", "lang", "==", "\"en\"", ":", "dict_size", "=", "min", "(", "dict_size", ",", "TOTAL_EN_WORDS", ")", "else", ":", "dict_size", "=", "min", "(", "dict_size", ",", "TOTAL_DE_WORDS", ")", "dict_path", "=", "os", ".", "path", ".", "join", "(", "paddle", ".", "dataset", ".", "common", ".", "DATA_HOME", ",", "\"wmt16/%s_%d.dict\"", "%", "(", "lang", ",", "dict_size", ")", ")", "assert", "os", ".", "path", ".", "exists", "(", "dict_path", ")", ",", "\"Word dictionary does not exist. \"", "\"Please invoke paddle.dataset.wmt16.train/test/validation first \"", "\"to build the dictionary.\"", "tar_file", "=", "os", ".", "path", ".", "join", "(", "paddle", ".", "dataset", ".", "common", ".", "DATA_HOME", ",", "\"wmt16.tar.gz\"", ")", "return", "__load_dict", "(", "tar_file", ",", "dict_size", ",", "lang", ",", "reverse", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/dataset/wmt16.py#L307-L334
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/joblib/joblib/externals/cloudpickle/cloudpickle.py
python
_make_skeleton_enum
(bases, name, qualname, members, module, class_tracker_id, extra)
return _lookup_class_or_track(class_tracker_id, enum_class)
Build dynamic enum with an empty __dict__ to be filled once memoized The creation of the enum class is inspired by the code of EnumMeta._create_. If class_tracker_id is not None, try to lookup an existing enum definition matching that id. If none is found, track a newly reconstructed enum definition under that id so that other instances stemming from the same class id will also reuse this enum definition. The "extra" variable is meant to be a dict (or None) that can be used for forward compatibility shall the need arise.
Build dynamic enum with an empty __dict__ to be filled once memoized
[ "Build", "dynamic", "enum", "with", "an", "empty", "__dict__", "to", "be", "filled", "once", "memoized" ]
def _make_skeleton_enum(bases, name, qualname, members, module, class_tracker_id, extra): """Build dynamic enum with an empty __dict__ to be filled once memoized The creation of the enum class is inspired by the code of EnumMeta._create_. If class_tracker_id is not None, try to lookup an existing enum definition matching that id. If none is found, track a newly reconstructed enum definition under that id so that other instances stemming from the same class id will also reuse this enum definition. The "extra" variable is meant to be a dict (or None) that can be used for forward compatibility shall the need arise. """ # enums always inherit from their base Enum class at the last position in # the list of base classes: enum_base = bases[-1] metacls = enum_base.__class__ classdict = metacls.__prepare__(name, bases) for member_name, member_value in members.items(): classdict[member_name] = member_value enum_class = metacls.__new__(metacls, name, bases, classdict) enum_class.__module__ = module enum_class.__qualname__ = qualname return _lookup_class_or_track(class_tracker_id, enum_class)
[ "def", "_make_skeleton_enum", "(", "bases", ",", "name", ",", "qualname", ",", "members", ",", "module", ",", "class_tracker_id", ",", "extra", ")", ":", "# enums always inherit from their base Enum class at the last position in", "# the list of base classes:", "enum_base", "=", "bases", "[", "-", "1", "]", "metacls", "=", "enum_base", ".", "__class__", "classdict", "=", "metacls", ".", "__prepare__", "(", "name", ",", "bases", ")", "for", "member_name", ",", "member_value", "in", "members", ".", "items", "(", ")", ":", "classdict", "[", "member_name", "]", "=", "member_value", "enum_class", "=", "metacls", ".", "__new__", "(", "metacls", ",", "name", ",", "bases", ",", "classdict", ")", "enum_class", ".", "__module__", "=", "module", "enum_class", ".", "__qualname__", "=", "qualname", "return", "_lookup_class_or_track", "(", "class_tracker_id", ",", "enum_class", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/externals/cloudpickle/cloudpickle.py#L876-L903
CNevd/Difacto_DMLC
f16862e35062707b1cf7e37d04d9b6ae34bbfd28
dmlc-core/tracker/dmlc_sge.py
python
sge_submit
(nworker, nserver, pass_envs)
customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nworker number of slave process to start up nserver number of server nodes to start up pass_envs enviroment variables to be added to the starting programs
customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nworker number of slave process to start up nserver number of server nodes to start up pass_envs enviroment variables to be added to the starting programs
[ "customized", "submit", "script", "that", "submit", "nslave", "jobs", "each", "must", "contain", "args", "as", "parameter", "note", "this", "can", "be", "a", "lambda", "function", "containing", "additional", "parameters", "in", "input", "Parameters", "nworker", "number", "of", "slave", "process", "to", "start", "up", "nserver", "number", "of", "server", "nodes", "to", "start", "up", "pass_envs", "enviroment", "variables", "to", "be", "added", "to", "the", "starting", "programs" ]
def sge_submit(nworker, nserver, pass_envs): """ customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nworker number of slave process to start up nserver number of server nodes to start up pass_envs enviroment variables to be added to the starting programs """ env_arg = ','.join(['%s=\"%s\"' % (k, str(v)) for k, v in pass_envs.items()]) cmd = 'qsub -cwd -t 1-%d -S /bin/bash' % (nworker + nserver) if args.queue != 'default': cmd += '-q %s' % args.queue cmd += ' -N %s ' % args.jobname cmd += ' -e %s -o %s' % (args.logdir, args.logdir) cmd += ' -pe orte %d' % (args.vcores) cmd += ' -v %s,PATH=${PATH}:.' % env_arg cmd += ' %s %s' % (runscript, ' '.join(args.command) + ' ' + ' '.join(unknown)) print cmd subprocess.check_call(cmd, shell = True) print 'Waiting for the jobs to get up...'
[ "def", "sge_submit", "(", "nworker", ",", "nserver", ",", "pass_envs", ")", ":", "env_arg", "=", "','", ".", "join", "(", "[", "'%s=\\\"%s\\\"'", "%", "(", "k", ",", "str", "(", "v", ")", ")", "for", "k", ",", "v", "in", "pass_envs", ".", "items", "(", ")", "]", ")", "cmd", "=", "'qsub -cwd -t 1-%d -S /bin/bash'", "%", "(", "nworker", "+", "nserver", ")", "if", "args", ".", "queue", "!=", "'default'", ":", "cmd", "+=", "'-q %s'", "%", "args", ".", "queue", "cmd", "+=", "' -N %s '", "%", "args", ".", "jobname", "cmd", "+=", "' -e %s -o %s'", "%", "(", "args", ".", "logdir", ",", "args", ".", "logdir", ")", "cmd", "+=", "' -pe orte %d'", "%", "(", "args", ".", "vcores", ")", "cmd", "+=", "' -v %s,PATH=${PATH}:.'", "%", "env_arg", "cmd", "+=", "' %s %s'", "%", "(", "runscript", ",", "' '", ".", "join", "(", "args", ".", "command", ")", "+", "' '", "+", "' '", ".", "join", "(", "unknown", ")", ")", "print", "cmd", "subprocess", ".", "check_call", "(", "cmd", ",", "shell", "=", "True", ")", "print", "'Waiting for the jobs to get up...'" ]
https://github.com/CNevd/Difacto_DMLC/blob/f16862e35062707b1cf7e37d04d9b6ae34bbfd28/dmlc-core/tracker/dmlc_sge.py#L51-L71
Illumina/strelka
d7377443b62319f7c7bd70c241c4b2df3459e29a
src/python/lib/workflowUtil.py
python
cleanId
(input_id)
return re.sub(r'([^a-zA-Z0-9_\-])', "_", input_id)
filter id so that it's safe to use as a pyflow indentifier
filter id so that it's safe to use as a pyflow indentifier
[ "filter", "id", "so", "that", "it", "s", "safe", "to", "use", "as", "a", "pyflow", "indentifier" ]
def cleanId(input_id) : """ filter id so that it's safe to use as a pyflow indentifier """ import re return re.sub(r'([^a-zA-Z0-9_\-])', "_", input_id)
[ "def", "cleanId", "(", "input_id", ")", ":", "import", "re", "return", "re", ".", "sub", "(", "r'([^a-zA-Z0-9_\\-])'", ",", "\"_\"", ",", "input_id", ")" ]
https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/src/python/lib/workflowUtil.py#L265-L270
emsesp/EMS-ESP
65c4a381bf8df61d1e18ba00223b1a55933fc547
scripts/esptool.py
python
timeout_per_mb
(seconds_per_mb, size_bytes)
return result
Scales timeouts which are size-specific
Scales timeouts which are size-specific
[ "Scales", "timeouts", "which", "are", "size", "-", "specific" ]
def timeout_per_mb(seconds_per_mb, size_bytes): """ Scales timeouts which are size-specific """ result = seconds_per_mb * (size_bytes / 1e6) if result < DEFAULT_TIMEOUT: return DEFAULT_TIMEOUT return result
[ "def", "timeout_per_mb", "(", "seconds_per_mb", ",", "size_bytes", ")", ":", "result", "=", "seconds_per_mb", "*", "(", "size_bytes", "/", "1e6", ")", "if", "result", "<", "DEFAULT_TIMEOUT", ":", "return", "DEFAULT_TIMEOUT", "return", "result" ]
https://github.com/emsesp/EMS-ESP/blob/65c4a381bf8df61d1e18ba00223b1a55933fc547/scripts/esptool.py#L79-L84
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftobjects/layer.py
python
Layer.addObject
(self, obj, child)
Add an object to this object if not in the Group property.
Add an object to this object if not in the Group property.
[ "Add", "an", "object", "to", "this", "object", "if", "not", "in", "the", "Group", "property", "." ]
def addObject(self, obj, child): """Add an object to this object if not in the Group property.""" group = obj.Group if child not in group: group.append(child) obj.Group = group
[ "def", "addObject", "(", "self", ",", "obj", ",", "child", ")", ":", "group", "=", "obj", ".", "Group", "if", "child", "not", "in", "group", ":", "group", ".", "append", "(", "child", ")", "obj", ".", "Group", "=", "group" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftobjects/layer.py#L77-L82
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/envs_v2/sensors/sensor.py
python
newer_obs_blender
(low_value: Any, unused_high_value: Any, unused_coeff: float)
return low_value
Always choosing low value, which is the newer value between low/high.
Always choosing low value, which is the newer value between low/high.
[ "Always", "choosing", "low", "value", "which", "is", "the", "newer", "value", "between", "low", "/", "high", "." ]
def newer_obs_blender(low_value: Any, unused_high_value: Any, unused_coeff: float): """Always choosing low value, which is the newer value between low/high.""" return low_value
[ "def", "newer_obs_blender", "(", "low_value", ":", "Any", ",", "unused_high_value", ":", "Any", ",", "unused_coeff", ":", "float", ")", ":", "return", "low_value" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs_v2/sensors/sensor.py#L49-L52
AcademySoftwareFoundation/OpenColorIO
73508eb5230374df8d96147a0627c015d359a641
share/docs/frozendoc.py
python
backup_frozen
(app)
Duplicate existing frozen RST files for comparison with newly frozen RST in ``compare_frozen()`` after docs are built.
Duplicate existing frozen RST files for comparison with newly frozen RST in ``compare_frozen()`` after docs are built.
[ "Duplicate", "existing", "frozen", "RST", "files", "for", "comparison", "with", "newly", "frozen", "RST", "in", "compare_frozen", "()", "after", "docs", "are", "built", "." ]
def backup_frozen(app): """ Duplicate existing frozen RST files for comparison with newly frozen RST in ``compare_frozen()`` after docs are built. """ if app.config.frozendoc_build or app.config.frozendoc_compare: # Apply monkeypatch, enabling frozen RST generation patch() if not app.config.frozendoc_compare: return logger.info("Backing up frozen RST: {src} -> {dst}".format( src=PYTHON_FROZEN_DIR, dst=PYTHON_BACKUP_DIR )) if os.path.exists(PYTHON_FROZEN_DIR) and os.listdir(PYTHON_FROZEN_DIR): if os.path.exists(PYTHON_BACKUP_DIR): shutil.rmtree(PYTHON_BACKUP_DIR) shutil.move(PYTHON_FROZEN_DIR, PYTHON_BACKUP_DIR) else: raise ExtensionError( "No frozen RST found! Build OpenColorIO with CMake option " "'-DOCIO_BUILD_FROZEN_DOCS=ON' to generate required frozen " "documentation source files in: {dir}".format(dir=PYTHON_FROZEN_DIR) ) logger.info("Backup complete.")
[ "def", "backup_frozen", "(", "app", ")", ":", "if", "app", ".", "config", ".", "frozendoc_build", "or", "app", ".", "config", ".", "frozendoc_compare", ":", "# Apply monkeypatch, enabling frozen RST generation", "patch", "(", ")", "if", "not", "app", ".", "config", ".", "frozendoc_compare", ":", "return", "logger", ".", "info", "(", "\"Backing up frozen RST: {src} -> {dst}\"", ".", "format", "(", "src", "=", "PYTHON_FROZEN_DIR", ",", "dst", "=", "PYTHON_BACKUP_DIR", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "PYTHON_FROZEN_DIR", ")", "and", "os", ".", "listdir", "(", "PYTHON_FROZEN_DIR", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "PYTHON_BACKUP_DIR", ")", ":", "shutil", ".", "rmtree", "(", "PYTHON_BACKUP_DIR", ")", "shutil", ".", "move", "(", "PYTHON_FROZEN_DIR", ",", "PYTHON_BACKUP_DIR", ")", "else", ":", "raise", "ExtensionError", "(", "\"No frozen RST found! Build OpenColorIO with CMake option \"", "\"'-DOCIO_BUILD_FROZEN_DOCS=ON' to generate required frozen \"", "\"documentation source files in: {dir}\"", ".", "format", "(", "dir", "=", "PYTHON_FROZEN_DIR", ")", ")", "logger", ".", "info", "(", "\"Backup complete.\"", ")" ]
https://github.com/AcademySoftwareFoundation/OpenColorIO/blob/73508eb5230374df8d96147a0627c015d359a641/share/docs/frozendoc.py#L174-L202
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/cookies.py
python
remove_cookie_by_name
(cookiejar, name, domain=None, path=None)
Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n).
Unsets a cookie by name, by default over all domains and paths.
[ "Unsets", "a", "cookie", "by", "name", "by", "default", "over", "all", "domains", "and", "paths", "." ]
def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name)
[ "def", "remove_cookie_by_name", "(", "cookiejar", ",", "name", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "clearables", "=", "[", "]", "for", "cookie", "in", "cookiejar", ":", "if", "cookie", ".", "name", "!=", "name", ":", "continue", "if", "domain", "is", "not", "None", "and", "domain", "!=", "cookie", ".", "domain", ":", "continue", "if", "path", "is", "not", "None", "and", "path", "!=", "cookie", ".", "path", ":", "continue", "clearables", ".", "append", "(", "(", "cookie", ".", "domain", ",", "cookie", ".", "path", ",", "cookie", ".", "name", ")", ")", "for", "domain", ",", "path", ",", "name", "in", "clearables", ":", "cookiejar", ".", "clear", "(", "domain", ",", "path", ",", "name", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/cookies.py#L146-L162
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/internals/blocks.py
python
Block.putmask
(self, mask, new)
putmask the data to the block; it is possible that we may create a new dtype of block Return the resulting block(s). Parameters ---------- mask : np.ndarray[bool], SparseArray[bool], or BooleanArray new : a ndarray/object Returns ------- List[Block]
putmask the data to the block; it is possible that we may create a new dtype of block
[ "putmask", "the", "data", "to", "the", "block", ";", "it", "is", "possible", "that", "we", "may", "create", "a", "new", "dtype", "of", "block" ]
def putmask(self, mask, new) -> list[Block]: """ putmask the data to the block; it is possible that we may create a new dtype of block Return the resulting block(s). Parameters ---------- mask : np.ndarray[bool], SparseArray[bool], or BooleanArray new : a ndarray/object Returns ------- List[Block] """ orig_mask = mask mask, noop = validate_putmask(self.values.T, mask) assert not isinstance(new, (ABCIndex, ABCSeries, ABCDataFrame)) # if we are passed a scalar None, convert it here if not self.is_object and is_valid_na_for_dtype(new, self.dtype): new = self.fill_value if self._can_hold_element(new): # error: Argument 1 to "putmask_without_repeat" has incompatible type # "Union[ndarray, ExtensionArray]"; expected "ndarray" putmask_without_repeat(self.values.T, mask, new) # type: ignore[arg-type] return [self] elif noop: return [self] dtype, _ = infer_dtype_from(new) if dtype.kind in ["m", "M"]: # using putmask with object dtype will incorrectly cast to object # Having excluded self._can_hold_element, we know we cannot operate # in-place, so we are safe using `where` return self.where(new, ~mask) elif self.ndim == 1 or self.shape[0] == 1: # no need to split columns # error: Argument 1 to "putmask_smart" has incompatible type "Union[ndarray, # ExtensionArray]"; expected "ndarray" nv = putmask_smart(self.values.T, mask, new).T # type: ignore[arg-type] return [self.make_block(nv)] else: is_array = isinstance(new, np.ndarray) res_blocks = [] nbs = self._split() for i, nb in enumerate(nbs): n = new if is_array: # we have a different value per-column n = new[:, i : i + 1] submask = orig_mask[:, i : i + 1] rbs = nb.putmask(submask, n) res_blocks.extend(rbs) return res_blocks
[ "def", "putmask", "(", "self", ",", "mask", ",", "new", ")", "->", "list", "[", "Block", "]", ":", "orig_mask", "=", "mask", "mask", ",", "noop", "=", "validate_putmask", "(", "self", ".", "values", ".", "T", ",", "mask", ")", "assert", "not", "isinstance", "(", "new", ",", "(", "ABCIndex", ",", "ABCSeries", ",", "ABCDataFrame", ")", ")", "# if we are passed a scalar None, convert it here", "if", "not", "self", ".", "is_object", "and", "is_valid_na_for_dtype", "(", "new", ",", "self", ".", "dtype", ")", ":", "new", "=", "self", ".", "fill_value", "if", "self", ".", "_can_hold_element", "(", "new", ")", ":", "# error: Argument 1 to \"putmask_without_repeat\" has incompatible type", "# \"Union[ndarray, ExtensionArray]\"; expected \"ndarray\"", "putmask_without_repeat", "(", "self", ".", "values", ".", "T", ",", "mask", ",", "new", ")", "# type: ignore[arg-type]", "return", "[", "self", "]", "elif", "noop", ":", "return", "[", "self", "]", "dtype", ",", "_", "=", "infer_dtype_from", "(", "new", ")", "if", "dtype", ".", "kind", "in", "[", "\"m\"", ",", "\"M\"", "]", ":", "# using putmask with object dtype will incorrectly cast to object", "# Having excluded self._can_hold_element, we know we cannot operate", "# in-place, so we are safe using `where`", "return", "self", ".", "where", "(", "new", ",", "~", "mask", ")", "elif", "self", ".", "ndim", "==", "1", "or", "self", ".", "shape", "[", "0", "]", "==", "1", ":", "# no need to split columns", "# error: Argument 1 to \"putmask_smart\" has incompatible type \"Union[ndarray,", "# ExtensionArray]\"; expected \"ndarray\"", "nv", "=", "putmask_smart", "(", "self", ".", "values", ".", "T", ",", "mask", ",", "new", ")", ".", "T", "# type: ignore[arg-type]", "return", "[", "self", ".", "make_block", "(", "nv", ")", "]", "else", ":", "is_array", "=", "isinstance", "(", "new", ",", "np", ".", "ndarray", ")", "res_blocks", "=", "[", "]", "nbs", "=", "self", ".", "_split", "(", ")", "for", "i", ",", "nb", "in", "enumerate", "(", "nbs", ")", ":", "n", "=", "new", "if", "is_array", ":", "# we have a different value per-column", "n", "=", "new", "[", ":", ",", "i", ":", "i", "+", "1", "]", "submask", "=", "orig_mask", "[", ":", ",", "i", ":", "i", "+", "1", "]", "rbs", "=", "nb", ".", "putmask", "(", "submask", ",", "n", ")", "res_blocks", ".", "extend", "(", "rbs", ")", "return", "res_blocks" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/blocks.py#L990-L1053
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/urlgrabber/mirror.py
python
MirrorGroup.increment_mirror
(self, gr, action={})
Tell the mirror object increment the mirror index This increments the mirror index, which amounts to telling the mirror object to use a different mirror (for this and future downloads). This is a SEMI-public method. It will be called internally, and you may never need to call it. However, it is provided (and is made public) so that the calling program can increment the mirror choice for methods like urlopen. For example, with urlopen, there's no good way for the mirror group to know that an error occurs mid-download (it's already returned and given you the file object). remove --- can have several values 0 do not remove the mirror from the list 1 remove the mirror for this download only 2 remove the mirror permanently beware of remove=0 as it can lead to infinite loops
Tell the mirror object increment the mirror index
[ "Tell", "the", "mirror", "object", "increment", "the", "mirror", "index" ]
def increment_mirror(self, gr, action={}): """Tell the mirror object increment the mirror index This increments the mirror index, which amounts to telling the mirror object to use a different mirror (for this and future downloads). This is a SEMI-public method. It will be called internally, and you may never need to call it. However, it is provided (and is made public) so that the calling program can increment the mirror choice for methods like urlopen. For example, with urlopen, there's no good way for the mirror group to know that an error occurs mid-download (it's already returned and given you the file object). remove --- can have several values 0 do not remove the mirror from the list 1 remove the mirror for this download only 2 remove the mirror permanently beware of remove=0 as it can lead to infinite loops """ badmirror = gr.mirrors[gr._next] self._lock.acquire() try: ind = self.mirrors.index(badmirror) except ValueError: pass else: if action.get('remove_master', 0): del self.mirrors[ind] elif self._next == ind and action.get('increment_master', 1): self._next += 1 if self._next >= len(self.mirrors): self._next = 0 self._lock.release() if action.get('remove', 1): del gr.mirrors[gr._next] elif action.get('increment', 1): gr._next += 1 if gr._next >= len(gr.mirrors): gr._next = 0 if DEBUG: grm = [m['mirror'] for m in gr.mirrors] DEBUG.info('GR mirrors: [%s] %i', ' '.join(grm), gr._next) selfm = [m['mirror'] for m in self.mirrors] DEBUG.info('MAIN mirrors: [%s] %i', ' '.join(selfm), self._next)
[ "def", "increment_mirror", "(", "self", ",", "gr", ",", "action", "=", "{", "}", ")", ":", "badmirror", "=", "gr", ".", "mirrors", "[", "gr", ".", "_next", "]", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "ind", "=", "self", ".", "mirrors", ".", "index", "(", "badmirror", ")", "except", "ValueError", ":", "pass", "else", ":", "if", "action", ".", "get", "(", "'remove_master'", ",", "0", ")", ":", "del", "self", ".", "mirrors", "[", "ind", "]", "elif", "self", ".", "_next", "==", "ind", "and", "action", ".", "get", "(", "'increment_master'", ",", "1", ")", ":", "self", ".", "_next", "+=", "1", "if", "self", ".", "_next", ">=", "len", "(", "self", ".", "mirrors", ")", ":", "self", ".", "_next", "=", "0", "self", ".", "_lock", ".", "release", "(", ")", "if", "action", ".", "get", "(", "'remove'", ",", "1", ")", ":", "del", "gr", ".", "mirrors", "[", "gr", ".", "_next", "]", "elif", "action", ".", "get", "(", "'increment'", ",", "1", ")", ":", "gr", ".", "_next", "+=", "1", "if", "gr", ".", "_next", ">=", "len", "(", "gr", ".", "mirrors", ")", ":", "gr", ".", "_next", "=", "0", "if", "DEBUG", ":", "grm", "=", "[", "m", "[", "'mirror'", "]", "for", "m", "in", "gr", ".", "mirrors", "]", "DEBUG", ".", "info", "(", "'GR mirrors: [%s] %i'", ",", "' '", ".", "join", "(", "grm", ")", ",", "gr", ".", "_next", ")", "selfm", "=", "[", "m", "[", "'mirror'", "]", "for", "m", "in", "self", ".", "mirrors", "]", "DEBUG", ".", "info", "(", "'MAIN mirrors: [%s] %i'", ",", "' '", ".", "join", "(", "selfm", ")", ",", "self", ".", "_next", ")" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/urlgrabber/mirror.py#L315-L362
tangzhenyu/Scene-Text-Understanding
0f7ffc7aea5971a50cdc03d33d0a41075285948b
SynthText_Chinese/ransac.py
python
fit_plane_ransac
(pts, neighbors=None,z_pos=None, dist_inlier=0.05, min_inlier_frac=0.60, nsample=3, max_iter=100)
Fits a 3D plane model using RANSAC. pts : (nx3 array) of point coordinates
Fits a 3D plane model using RANSAC. pts : (nx3 array) of point coordinates
[ "Fits", "a", "3D", "plane", "model", "using", "RANSAC", ".", "pts", ":", "(", "nx3", "array", ")", "of", "point", "coordinates" ]
def fit_plane_ransac(pts, neighbors=None,z_pos=None, dist_inlier=0.05, min_inlier_frac=0.60, nsample=3, max_iter=100): """ Fits a 3D plane model using RANSAC. pts : (nx3 array) of point coordinates """ n,_ = pts.shape ninlier,models = [],[] for i in xrange(max_iter): if neighbors is None: p = pts[np.random.choice(pts.shape[0],nsample,replace=False),:] else: p = pts[neighbors[:,i],:] m = fit_plane(p,z_pos) ds = np.abs(pts.dot(m[:3])+m[3]) nin = np.sum(ds < dist_inlier) if nin/pts.shape[0] >= min_inlier_frac: ninlier.append(nin) models.append(m) if models == []: print "RANSAC plane fitting failed!" return #None else: #refit the model to inliers: ninlier = np.array(ninlier) best_model_idx = np.argsort(-ninlier) n_refit, m_refit, inliers = [],[],[] for idx in best_model_idx[:min(10,len(best_model_idx))]: # re-estimate the model based on inliers: dists = np.abs(pts.dot(models[idx][:3])+models[idx][3]) inlier = dists < dist_inlier m = fit_plane(pts[inlier,:],z_pos) # compute new inliers: d = np.abs(pts.dot(m[:3])+m[3]) inlier = d < dist_inlier/2 # heuristic n_refit.append(np.sum(inlier)) m_refit.append(m) inliers.append(inlier) best_plane = np.argmax(n_refit) return m_refit[best_plane],inliers[best_plane]
[ "def", "fit_plane_ransac", "(", "pts", ",", "neighbors", "=", "None", ",", "z_pos", "=", "None", ",", "dist_inlier", "=", "0.05", ",", "min_inlier_frac", "=", "0.60", ",", "nsample", "=", "3", ",", "max_iter", "=", "100", ")", ":", "n", ",", "_", "=", "pts", ".", "shape", "ninlier", ",", "models", "=", "[", "]", ",", "[", "]", "for", "i", "in", "xrange", "(", "max_iter", ")", ":", "if", "neighbors", "is", "None", ":", "p", "=", "pts", "[", "np", ".", "random", ".", "choice", "(", "pts", ".", "shape", "[", "0", "]", ",", "nsample", ",", "replace", "=", "False", ")", ",", ":", "]", "else", ":", "p", "=", "pts", "[", "neighbors", "[", ":", ",", "i", "]", ",", ":", "]", "m", "=", "fit_plane", "(", "p", ",", "z_pos", ")", "ds", "=", "np", ".", "abs", "(", "pts", ".", "dot", "(", "m", "[", ":", "3", "]", ")", "+", "m", "[", "3", "]", ")", "nin", "=", "np", ".", "sum", "(", "ds", "<", "dist_inlier", ")", "if", "nin", "/", "pts", ".", "shape", "[", "0", "]", ">=", "min_inlier_frac", ":", "ninlier", ".", "append", "(", "nin", ")", "models", ".", "append", "(", "m", ")", "if", "models", "==", "[", "]", ":", "print", "\"RANSAC plane fitting failed!\"", "return", "#None", "else", ":", "#refit the model to inliers:", "ninlier", "=", "np", ".", "array", "(", "ninlier", ")", "best_model_idx", "=", "np", ".", "argsort", "(", "-", "ninlier", ")", "n_refit", ",", "m_refit", ",", "inliers", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "idx", "in", "best_model_idx", "[", ":", "min", "(", "10", ",", "len", "(", "best_model_idx", ")", ")", "]", ":", "# re-estimate the model based on inliers:", "dists", "=", "np", ".", "abs", "(", "pts", ".", "dot", "(", "models", "[", "idx", "]", "[", ":", "3", "]", ")", "+", "models", "[", "idx", "]", "[", "3", "]", ")", "inlier", "=", "dists", "<", "dist_inlier", "m", "=", "fit_plane", "(", "pts", "[", "inlier", ",", ":", "]", ",", "z_pos", ")", "# compute new inliers:", "d", "=", "np", ".", "abs", "(", "pts", ".", "dot", "(", "m", "[", ":", "3", "]", ")", "+", "m", "[", "3", "]", ")", "inlier", "=", "d", "<", "dist_inlier", "/", "2", "# heuristic", "n_refit", ".", "append", "(", "np", ".", "sum", "(", "inlier", ")", ")", "m_refit", ".", "append", "(", "m", ")", "inliers", ".", "append", "(", "inlier", ")", "best_plane", "=", "np", ".", "argmax", "(", "n_refit", ")", "return", "m_refit", "[", "best_plane", "]", ",", "inliers", "[", "best_plane", "]" ]
https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/SynthText_Chinese/ransac.py#L25-L64
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/builtin_trap.py
python
BuiltinTrap.add_builtin
(self, key, value)
Add a builtin and save the original.
Add a builtin and save the original.
[ "Add", "a", "builtin", "and", "save", "the", "original", "." ]
def add_builtin(self, key, value): """Add a builtin and save the original.""" bdict = builtin_mod.__dict__ orig = bdict.get(key, BuiltinUndefined) if value is HideBuiltin: if orig is not BuiltinUndefined: #same as 'key in bdict' self._orig_builtins[key] = orig del bdict[key] else: self._orig_builtins[key] = orig bdict[key] = value
[ "def", "add_builtin", "(", "self", ",", "key", ",", "value", ")", ":", "bdict", "=", "builtin_mod", ".", "__dict__", "orig", "=", "bdict", ".", "get", "(", "key", ",", "BuiltinUndefined", ")", "if", "value", "is", "HideBuiltin", ":", "if", "orig", "is", "not", "BuiltinUndefined", ":", "#same as 'key in bdict'", "self", ".", "_orig_builtins", "[", "key", "]", "=", "orig", "del", "bdict", "[", "key", "]", "else", ":", "self", ".", "_orig_builtins", "[", "key", "]", "=", "orig", "bdict", "[", "key", "]", "=", "value" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/builtin_trap.py#L81-L91
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_utils/transformations.py
python
arcball_constrain_to_axis
(point, axis)
return unit_vector([-a[1], a[0], 0])
Return sphere point perpendicular to axis.
Return sphere point perpendicular to axis.
[ "Return", "sphere", "point", "perpendicular", "to", "axis", "." ]
def arcball_constrain_to_axis(point, axis): """Return sphere point perpendicular to axis.""" v = numpy.array(point, dtype=numpy.float64, copy=True) a = numpy.array(axis, dtype=numpy.float64, copy=True) v -= a * numpy.dot(a, v) # on plane n = vector_norm(v) if n > _EPS: if v[2] < 0.0: v *= -1.0 v /= n return v if a[2] == 1.0: return numpy.array([1, 0, 0], dtype=numpy.float64) return unit_vector([-a[1], a[0], 0])
[ "def", "arcball_constrain_to_axis", "(", "point", ",", "axis", ")", ":", "v", "=", "numpy", ".", "array", "(", "point", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "a", "=", "numpy", ".", "array", "(", "axis", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "v", "-=", "a", "*", "numpy", ".", "dot", "(", "a", ",", "v", ")", "# on plane", "n", "=", "vector_norm", "(", "v", ")", "if", "n", ">", "_EPS", ":", "if", "v", "[", "2", "]", "<", "0.0", ":", "v", "*=", "-", "1.0", "v", "/=", "n", "return", "v", "if", "a", "[", "2", "]", "==", "1.0", ":", "return", "numpy", ".", "array", "(", "[", "1", ",", "0", ",", "0", "]", ",", "dtype", "=", "numpy", ".", "float64", ")", "return", "unit_vector", "(", "[", "-", "a", "[", "1", "]", ",", "a", "[", "0", "]", ",", "0", "]", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_utils/transformations.py#L1485-L1498
DaFuCoding/MTCNN_Caffe
09c30c3ff391bd9cb6b249c1910afaf147767ab3
scripts/cpp_lint.py
python
CheckAccess
(filename, clean_lines, linenum, nesting_state, error)
Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks for improper use of DISALLOW* macros.
[ "Checks", "for", "improper", "use", "of", "DISALLOW", "*", "macros", "." ]
def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_EVIL_CONSTRUCTORS|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass
[ "def", "CheckAccess", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "matched", "=", "Match", "(", "(", "r'\\s*(DISALLOW_COPY_AND_ASSIGN|'", "r'DISALLOW_EVIL_CONSTRUCTORS|'", "r'DISALLOW_IMPLICIT_CONSTRUCTORS)'", ")", ",", "line", ")", "if", "not", "matched", ":", "return", "if", "nesting_state", ".", "stack", "and", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "1", "]", ",", "_ClassInfo", ")", ":", "if", "nesting_state", ".", "stack", "[", "-", "1", "]", ".", "access", "!=", "'private'", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/constructors'", ",", "3", ",", "'%s must be in the private: section'", "%", "matched", ".", "group", "(", "1", ")", ")", "else", ":", "# Found DISALLOW* macro outside a class declaration, or perhaps it", "# was used inside a function when it should have been part of the", "# class declaration. We could issue a warning here, but it", "# probably resulted in a compiler error already.", "pass" ]
https://github.com/DaFuCoding/MTCNN_Caffe/blob/09c30c3ff391bd9cb6b249c1910afaf147767ab3/scripts/cpp_lint.py#L2486-L2514
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py
python
ProgramMakefile.generate_target_default
(self, mfile)
Generate the default target. mfile is the file object.
Generate the default target.
[ "Generate", "the", "default", "target", "." ]
def generate_target_default(self, mfile): """Generate the default target. mfile is the file object. """ # Do these first so that it's safe for a sub-class to append additional # commands to the real target, but make sure the default is correct. mfile.write("\nall: $(TARGET)\n") mfile.write("\n$(OFILES): $(HFILES)\n") for mf in self._build["moc_headers"].split(): root, _ = os.path.splitext(mf) cpp = "moc_" + root + ".cpp" if self._src_dir != self.dir: mf = os.path.join(self._src_dir, mf) mfile.write("\n%s: %s\n" % (cpp, mf)) mfile.write("\t$(MOC) -o %s %s\n" % (cpp, mf)) mfile.write("\n$(TARGET): $(OFILES)\n") if self.generator in ("MSVC", "MSVC.NET", "MSBUILD"): mfile.write("\t$(LINK) $(LFLAGS) /OUT:$(TARGET) @<<\n") mfile.write("\t $(OFILES) $(LIBS)\n") mfile.write("<<\n") elif self.generator == "BMAKE": mfile.write("\t$(LINK) @&&|\n") mfile.write("\t$(LFLAGS) $(OFILES) ,$(TARGET),,$(LIBS),,\n") mfile.write("|\n") else: mfile.write("\t$(LINK) $(LFLAGS) -o $(TARGET) $(OFILES) $(LIBS)\n") if self._manifest: mfile.write("\tmt -nologo -manifest $(TARGET).manifest -outputresource:$(TARGET);1\n")
[ "def", "generate_target_default", "(", "self", ",", "mfile", ")", ":", "# Do these first so that it's safe for a sub-class to append additional", "# commands to the real target, but make sure the default is correct.", "mfile", ".", "write", "(", "\"\\nall: $(TARGET)\\n\"", ")", "mfile", ".", "write", "(", "\"\\n$(OFILES): $(HFILES)\\n\"", ")", "for", "mf", "in", "self", ".", "_build", "[", "\"moc_headers\"", "]", ".", "split", "(", ")", ":", "root", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "mf", ")", "cpp", "=", "\"moc_\"", "+", "root", "+", "\".cpp\"", "if", "self", ".", "_src_dir", "!=", "self", ".", "dir", ":", "mf", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_src_dir", ",", "mf", ")", "mfile", ".", "write", "(", "\"\\n%s: %s\\n\"", "%", "(", "cpp", ",", "mf", ")", ")", "mfile", ".", "write", "(", "\"\\t$(MOC) -o %s %s\\n\"", "%", "(", "cpp", ",", "mf", ")", ")", "mfile", ".", "write", "(", "\"\\n$(TARGET): $(OFILES)\\n\"", ")", "if", "self", ".", "generator", "in", "(", "\"MSVC\"", ",", "\"MSVC.NET\"", ",", "\"MSBUILD\"", ")", ":", "mfile", ".", "write", "(", "\"\\t$(LINK) $(LFLAGS) /OUT:$(TARGET) @<<\\n\"", ")", "mfile", ".", "write", "(", "\"\\t $(OFILES) $(LIBS)\\n\"", ")", "mfile", ".", "write", "(", "\"<<\\n\"", ")", "elif", "self", ".", "generator", "==", "\"BMAKE\"", ":", "mfile", ".", "write", "(", "\"\\t$(LINK) @&&|\\n\"", ")", "mfile", ".", "write", "(", "\"\\t$(LFLAGS) $(OFILES) ,$(TARGET),,$(LIBS),,\\n\"", ")", "mfile", ".", "write", "(", "\"|\\n\"", ")", "else", ":", "mfile", ".", "write", "(", "\"\\t$(LINK) $(LFLAGS) -o $(TARGET) $(OFILES) $(LIBS)\\n\"", ")", "if", "self", ".", "_manifest", ":", "mfile", ".", "write", "(", "\"\\tmt -nologo -manifest $(TARGET).manifest -outputresource:$(TARGET);1\\n\"", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py#L2023-L2057
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/tensor_forest/client/random_forest.py
python
_assert_float32
(tensors)
Assert all tensors are float32. Args: tensors: `Tensor` or `dict` of `Tensor` objects. Raises: TypeError: if any tensor is not float32.
Assert all tensors are float32.
[ "Assert", "all", "tensors", "are", "float32", "." ]
def _assert_float32(tensors): """Assert all tensors are float32. Args: tensors: `Tensor` or `dict` of `Tensor` objects. Raises: TypeError: if any tensor is not float32. """ if not isinstance(tensors, dict): tensors = [tensors] else: tensors = tensors.values() for tensor in tensors: if tensor.dtype.base_dtype != dtypes.float32: raise TypeError('Expected dtype=float32, %s.' % tensor)
[ "def", "_assert_float32", "(", "tensors", ")", ":", "if", "not", "isinstance", "(", "tensors", ",", "dict", ")", ":", "tensors", "=", "[", "tensors", "]", "else", ":", "tensors", "=", "tensors", ".", "values", "(", ")", "for", "tensor", "in", "tensors", ":", "if", "tensor", ".", "dtype", ".", "base_dtype", "!=", "dtypes", ".", "float32", ":", "raise", "TypeError", "(", "'Expected dtype=float32, %s.'", "%", "tensor", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/tensor_forest/client/random_forest.py#L51-L66
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/difflib.py
python
IS_LINE_JUNK
(line, pat=re.compile(r"\s*(?:#\s*)?$").match)
return pat(line) is not None
r""" Return True for ignorable line: iff `line` is blank or contains a single '#'. Examples: >>> IS_LINE_JUNK('\n') True >>> IS_LINE_JUNK(' # \n') True >>> IS_LINE_JUNK('hello\n') False
r""" Return True for ignorable line: iff `line` is blank or contains a single '#'.
[ "r", "Return", "True", "for", "ignorable", "line", ":", "iff", "line", "is", "blank", "or", "contains", "a", "single", "#", "." ]
def IS_LINE_JUNK(line, pat=re.compile(r"\s*(?:#\s*)?$").match): r""" Return True for ignorable line: iff `line` is blank or contains a single '#'. Examples: >>> IS_LINE_JUNK('\n') True >>> IS_LINE_JUNK(' # \n') True >>> IS_LINE_JUNK('hello\n') False """ return pat(line) is not None
[ "def", "IS_LINE_JUNK", "(", "line", ",", "pat", "=", "re", ".", "compile", "(", "r\"\\s*(?:#\\s*)?$\"", ")", ".", "match", ")", ":", "return", "pat", "(", "line", ")", "is", "not", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/difflib.py#L1045-L1059
milvus-io/milvus
3b1030de2b6c39e3512833e97f6044d63eb24237
internal/core/build-support/cpplint.py
python
FilesBelongToSameModule
(filename_cc, filename_h)
return files_belong_to_same_module, common_path
Check if these two filenames belong to the same module. The concept of a 'module' here is as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the source (e.g. .cc) file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file.
Check if these two filenames belong to the same module.
[ "Check", "if", "these", "two", "filenames", "belong", "to", "the", "same", "module", "." ]
def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the source (e.g. .cc) file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ fileinfo_cc = FileInfo(filename_cc) if not fileinfo_cc.Extension().lstrip('.') in GetNonHeaderExtensions(): return (False, '') fileinfo_h = FileInfo(filename_h) if not IsHeaderExtension(fileinfo_h.Extension().lstrip('.')): return (False, '') filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))] matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo_cc.BaseName()) if matched_test_suffix: filename_cc = filename_cc[:-len(matched_test_suffix.group(1))] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') filename_h = filename_h[:-(len(fileinfo_h.Extension()))] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path
[ "def", "FilesBelongToSameModule", "(", "filename_cc", ",", "filename_h", ")", ":", "fileinfo_cc", "=", "FileInfo", "(", "filename_cc", ")", "if", "not", "fileinfo_cc", ".", "Extension", "(", ")", ".", "lstrip", "(", "'.'", ")", "in", "GetNonHeaderExtensions", "(", ")", ":", "return", "(", "False", ",", "''", ")", "fileinfo_h", "=", "FileInfo", "(", "filename_h", ")", "if", "not", "IsHeaderExtension", "(", "fileinfo_h", ".", "Extension", "(", ")", ".", "lstrip", "(", "'.'", ")", ")", ":", "return", "(", "False", ",", "''", ")", "filename_cc", "=", "filename_cc", "[", ":", "-", "(", "len", "(", "fileinfo_cc", ".", "Extension", "(", ")", ")", ")", "]", "matched_test_suffix", "=", "Search", "(", "_TEST_FILE_SUFFIX", ",", "fileinfo_cc", ".", "BaseName", "(", ")", ")", "if", "matched_test_suffix", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "matched_test_suffix", ".", "group", "(", "1", ")", ")", "]", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "filename_h", "=", "filename_h", "[", ":", "-", "(", "len", "(", "fileinfo_h", ".", "Extension", "(", ")", ")", ")", "]", "if", "filename_h", ".", "endswith", "(", "'-inl'", ")", ":", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'-inl'", ")", "]", "filename_h", "=", "filename_h", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_h", "=", "filename_h", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "files_belong_to_same_module", "=", "filename_cc", ".", "endswith", "(", "filename_h", ")", "common_path", "=", "''", "if", "files_belong_to_same_module", ":", "common_path", "=", "filename_cc", "[", ":", "-", "len", "(", "filename_h", ")", "]", "return", "files_belong_to_same_module", ",", "common_path" ]
https://github.com/milvus-io/milvus/blob/3b1030de2b6c39e3512833e97f6044d63eb24237/internal/core/build-support/cpplint.py#L5967-L6022
wallix/redemption
fb4ceefb39e11e1ae250bce17e878e1dc7d195d2
tools/sesman/sesmanworker/challenge.py
python
md_to_challenge
(md)
return Challenge( challenge_type=auth_type, title=title, message=message, fields=[], echos=[], username=md.get("username"), challenge=md, token=None, recall=True, )
Convert new Challenge from bastion to internal Challenge param challenge: Challenge from bastion :rtype: Challenge :return: a converted Challenge
Convert new Challenge from bastion to internal Challenge
[ "Convert", "new", "Challenge", "from", "bastion", "to", "internal", "Challenge" ]
def md_to_challenge(md): """ Convert new Challenge from bastion to internal Challenge param challenge: Challenge from bastion :rtype: Challenge :return: a converted Challenge """ auth_type = md.get("auth_type") title = "= MOBILE DEVICE =" message = md.get("prompt", "") return Challenge( challenge_type=auth_type, title=title, message=message, fields=[], echos=[], username=md.get("username"), challenge=md, token=None, recall=True, )
[ "def", "md_to_challenge", "(", "md", ")", ":", "auth_type", "=", "md", ".", "get", "(", "\"auth_type\"", ")", "title", "=", "\"= MOBILE DEVICE =\"", "message", "=", "md", ".", "get", "(", "\"prompt\"", ",", "\"\"", ")", "return", "Challenge", "(", "challenge_type", "=", "auth_type", ",", "title", "=", "title", ",", "message", "=", "message", ",", "fields", "=", "[", "]", ",", "echos", "=", "[", "]", ",", "username", "=", "md", ".", "get", "(", "\"username\"", ")", ",", "challenge", "=", "md", ",", "token", "=", "None", ",", "recall", "=", "True", ",", ")" ]
https://github.com/wallix/redemption/blob/fb4ceefb39e11e1ae250bce17e878e1dc7d195d2/tools/sesman/sesmanworker/challenge.py#L97-L117
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py
python
Base.PrependENVPath
(self, name, newpath, envname = 'ENV', sep = os.pathsep, delete_existing=1)
Prepend path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the front (it will be left where it is).
Prepend path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string.
[ "Prepend", "path", "elements", "to", "the", "path", "name", "in", "the", "ENV", "dictionary", "for", "this", "environment", ".", "Will", "only", "add", "any", "particular", "path", "once", "and", "will", "normpath", "and", "normcase", "all", "paths", "to", "help", "assure", "this", ".", "This", "can", "also", "handle", "the", "case", "where", "the", "env", "variable", "is", "a", "list", "instead", "of", "a", "string", "." ]
def PrependENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep, delete_existing=1): """Prepend path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the front (it will be left where it is). """ orig = '' if envname in self._dict and name in self._dict[envname]: orig = self._dict[envname][name] nv = SCons.Util.PrependPath(orig, newpath, sep, delete_existing, canonicalize=self._canonicalize) if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv
[ "def", "PrependENVPath", "(", "self", ",", "name", ",", "newpath", ",", "envname", "=", "'ENV'", ",", "sep", "=", "os", ".", "pathsep", ",", "delete_existing", "=", "1", ")", ":", "orig", "=", "''", "if", "envname", "in", "self", ".", "_dict", "and", "name", "in", "self", ".", "_dict", "[", "envname", "]", ":", "orig", "=", "self", ".", "_dict", "[", "envname", "]", "[", "name", "]", "nv", "=", "SCons", ".", "Util", ".", "PrependPath", "(", "orig", ",", "newpath", ",", "sep", ",", "delete_existing", ",", "canonicalize", "=", "self", ".", "_canonicalize", ")", "if", "envname", "not", "in", "self", ".", "_dict", ":", "self", ".", "_dict", "[", "envname", "]", "=", "{", "}", "self", ".", "_dict", "[", "envname", "]", "[", "name", "]", "=", "nv" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py#L1668-L1690
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/FSIApplication/python_scripts/trilinos_partitioned_fsi_base_solver.py
python
TrilinosPartitionedFSIBaseSolver.GetDefaultParameters
(cls)
return this_defaults
This function returns the default-settings used by this class
This function returns the default-settings used by this class
[ "This", "function", "returns", "the", "default", "-", "settings", "used", "by", "this", "class" ]
def GetDefaultParameters(cls): """This function returns the default-settings used by this class """ this_defaults = KratosMultiphysics.Parameters("""{ "parallel_type": "MPI" }""") this_defaults.AddMissingParameters(super().GetDefaultParameters()) return this_defaults
[ "def", "GetDefaultParameters", "(", "cls", ")", ":", "this_defaults", "=", "KratosMultiphysics", ".", "Parameters", "(", "\"\"\"{\n \"parallel_type\": \"MPI\"\n }\"\"\"", ")", "this_defaults", ".", "AddMissingParameters", "(", "super", "(", ")", ".", "GetDefaultParameters", "(", ")", ")", "return", "this_defaults" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/FSIApplication/python_scripts/trilinos_partitioned_fsi_base_solver.py#L27-L34
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PGProperty.OnEvent
(*args, **kwargs)
return _propgrid.PGProperty_OnEvent(*args, **kwargs)
OnEvent(self, PropertyGrid propgrid, Window wnd_primary, Event event) -> bool
OnEvent(self, PropertyGrid propgrid, Window wnd_primary, Event event) -> bool
[ "OnEvent", "(", "self", "PropertyGrid", "propgrid", "Window", "wnd_primary", "Event", "event", ")", "-", ">", "bool" ]
def OnEvent(*args, **kwargs): """OnEvent(self, PropertyGrid propgrid, Window wnd_primary, Event event) -> bool""" return _propgrid.PGProperty_OnEvent(*args, **kwargs)
[ "def", "OnEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_OnEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L385-L387
SOUI2/soui
774e5566b2d3254a94f4b3efd55b982e7c665434
third-part/jsoncpp/makerelease.py
python
svn_export
(tag_url, export_dir)
Exports the tag_url revision to export_dir. Target directory, including its parent is created if it does not exist. If the directory export_dir exist, it is deleted before export proceed.
Exports the tag_url revision to export_dir. Target directory, including its parent is created if it does not exist. If the directory export_dir exist, it is deleted before export proceed.
[ "Exports", "the", "tag_url", "revision", "to", "export_dir", ".", "Target", "directory", "including", "its", "parent", "is", "created", "if", "it", "does", "not", "exist", ".", "If", "the", "directory", "export_dir", "exist", "it", "is", "deleted", "before", "export", "proceed", "." ]
def svn_export(tag_url, export_dir): """Exports the tag_url revision to export_dir. Target directory, including its parent is created if it does not exist. If the directory export_dir exist, it is deleted before export proceed. """ rmdir_if_exist(export_dir) svn_command('export', tag_url, export_dir)
[ "def", "svn_export", "(", "tag_url", ",", "export_dir", ")", ":", "rmdir_if_exist", "(", "export_dir", ")", "svn_command", "(", "'export'", ",", "tag_url", ",", "export_dir", ")" ]
https://github.com/SOUI2/soui/blob/774e5566b2d3254a94f4b3efd55b982e7c665434/third-part/jsoncpp/makerelease.py#L116-L122
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/python_message.py
python
_AddPropertiesForField
(field, cls)
Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're constructing.
Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field.
[ "Adds", "a", "public", "property", "for", "a", "protocol", "message", "field", ".", "Clients", "can", "use", "this", "property", "to", "get", "and", "(", "in", "the", "case", "of", "non", "-", "repeated", "scalar", "fields", ")", "directly", "set", "the", "value", "of", "a", "protocol", "message", "field", "." ]
def _AddPropertiesForField(field, cls): """Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're constructing. """ # Catch it if we add other types that we should # handle specially here. assert _FieldDescriptor.MAX_CPPTYPE == 10 constant_name = field.name.upper() + "_FIELD_NUMBER" setattr(cls, constant_name, field.number) if field.label == _FieldDescriptor.LABEL_REPEATED: _AddPropertiesForRepeatedField(field, cls) elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: _AddPropertiesForNonRepeatedCompositeField(field, cls) else: _AddPropertiesForNonRepeatedScalarField(field, cls)
[ "def", "_AddPropertiesForField", "(", "field", ",", "cls", ")", ":", "# Catch it if we add other types that we should", "# handle specially here.", "assert", "_FieldDescriptor", ".", "MAX_CPPTYPE", "==", "10", "constant_name", "=", "field", ".", "name", ".", "upper", "(", ")", "+", "\"_FIELD_NUMBER\"", "setattr", "(", "cls", ",", "constant_name", ",", "field", ".", "number", ")", "if", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "_AddPropertiesForRepeatedField", "(", "field", ",", "cls", ")", "elif", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "_AddPropertiesForNonRepeatedCompositeField", "(", "field", ",", "cls", ")", "else", ":", "_AddPropertiesForNonRepeatedScalarField", "(", "field", ",", "cls", ")" ]
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L361-L383
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/cli/req_command.py
python
with_cleanup
(func)
return wrapper
Decorator for common logic related to managing temporary directories.
Decorator for common logic related to managing temporary directories.
[ "Decorator", "for", "common", "logic", "related", "to", "managing", "temporary", "directories", "." ]
def with_cleanup(func): # type: (Any) -> Any """Decorator for common logic related to managing temporary directories. """ def configure_tempdir_registry(registry): # type: (TempDirectoryTypeRegistry) -> None for t in KEEPABLE_TEMPDIR_TYPES: registry.set_delete(t, False) def wrapper(self, options, args): # type: (RequirementCommand, Values, List[Any]) -> Optional[int] assert self.tempdir_registry is not None if options.no_clean: configure_tempdir_registry(self.tempdir_registry) try: return func(self, options, args) except PreviousBuildDirError: # This kind of conflict can occur when the user passes an explicit # build directory with a pre-existing folder. In that case we do # not want to accidentally remove it. configure_tempdir_registry(self.tempdir_registry) raise return wrapper
[ "def", "with_cleanup", "(", "func", ")", ":", "# type: (Any) -> Any", "def", "configure_tempdir_registry", "(", "registry", ")", ":", "# type: (TempDirectoryTypeRegistry) -> None", "for", "t", "in", "KEEPABLE_TEMPDIR_TYPES", ":", "registry", ".", "set_delete", "(", "t", ",", "False", ")", "def", "wrapper", "(", "self", ",", "options", ",", "args", ")", ":", "# type: (RequirementCommand, Values, List[Any]) -> Optional[int]", "assert", "self", ".", "tempdir_registry", "is", "not", "None", "if", "options", ".", "no_clean", ":", "configure_tempdir_registry", "(", "self", ".", "tempdir_registry", ")", "try", ":", "return", "func", "(", "self", ",", "options", ",", "args", ")", "except", "PreviousBuildDirError", ":", "# This kind of conflict can occur when the user passes an explicit", "# build directory with a pre-existing folder. In that case we do", "# not want to accidentally remove it.", "configure_tempdir_registry", "(", "self", ".", "tempdir_registry", ")", "raise", "return", "wrapper" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/cli/req_command.py#L161-L186
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/plugins/Launch/launch/handlers.py
python
_OpenToLine
(fname, line, mainw)
Open the given filename to the given line number @param fname: File name to open, relative paths will be converted to abs paths. @param line: Line number to set the cursor to after opening the file @param mainw: MainWindow instance to open the file in
Open the given filename to the given line number @param fname: File name to open, relative paths will be converted to abs paths. @param line: Line number to set the cursor to after opening the file @param mainw: MainWindow instance to open the file in
[ "Open", "the", "given", "filename", "to", "the", "given", "line", "number", "@param", "fname", ":", "File", "name", "to", "open", "relative", "paths", "will", "be", "converted", "to", "abs", "paths", ".", "@param", "line", ":", "Line", "number", "to", "set", "the", "cursor", "to", "after", "opening", "the", "file", "@param", "mainw", ":", "MainWindow", "instance", "to", "open", "the", "file", "in" ]
def _OpenToLine(fname, line, mainw): """Open the given filename to the given line number @param fname: File name to open, relative paths will be converted to abs paths. @param line: Line number to set the cursor to after opening the file @param mainw: MainWindow instance to open the file in """ fname = os.path.abspath(fname) # Normalize path nbook = mainw.GetNotebook() buffers = [ page.GetFileName() for page in nbook.GetTextControls() ] for page, name in enumerate(buffers): if ebmlib.ComparePaths(fname, name): nbook.ChangePage(page) nbook.GetPage(page).GotoLine(line) break else: nbook.OnDrop([fname]) nbook.GetPage(nbook.GetSelection()).GotoLine(line)
[ "def", "_OpenToLine", "(", "fname", ",", "line", ",", "mainw", ")", ":", "fname", "=", "os", ".", "path", ".", "abspath", "(", "fname", ")", "# Normalize path", "nbook", "=", "mainw", ".", "GetNotebook", "(", ")", "buffers", "=", "[", "page", ".", "GetFileName", "(", ")", "for", "page", "in", "nbook", ".", "GetTextControls", "(", ")", "]", "for", "page", ",", "name", "in", "enumerate", "(", "buffers", ")", ":", "if", "ebmlib", ".", "ComparePaths", "(", "fname", ",", "name", ")", ":", "nbook", ".", "ChangePage", "(", "page", ")", "nbook", ".", "GetPage", "(", "page", ")", ".", "GotoLine", "(", "line", ")", "break", "else", ":", "nbook", ".", "OnDrop", "(", "[", "fname", "]", ")", "nbook", ".", "GetPage", "(", "nbook", ".", "GetSelection", "(", ")", ")", ".", "GotoLine", "(", "line", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/Launch/launch/handlers.py#L899-L917
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/fx/passes/operator_support.py
python
create_op_support
(is_node_supported: IsNodeSupported)
return FunctionalOperatorSupport()
Wraps a `IsNodeSupported` function into an `OperatorSupportBase` instance `IsNodeSupported` has the same call signature as `OperatorSupportBase.is_node_supported`
Wraps a `IsNodeSupported` function into an `OperatorSupportBase` instance
[ "Wraps", "a", "IsNodeSupported", "function", "into", "an", "OperatorSupportBase", "instance" ]
def create_op_support(is_node_supported: IsNodeSupported) -> OperatorSupportBase: """Wraps a `IsNodeSupported` function into an `OperatorSupportBase` instance `IsNodeSupported` has the same call signature as `OperatorSupportBase.is_node_supported` """ class FunctionalOperatorSupport(OperatorSupportBase): def is_node_supported( self, submodules: t.Mapping[str, torch.nn.Module], node: torch.fx.Node ) -> bool: return is_node_supported(submodules, node) return FunctionalOperatorSupport()
[ "def", "create_op_support", "(", "is_node_supported", ":", "IsNodeSupported", ")", "->", "OperatorSupportBase", ":", "class", "FunctionalOperatorSupport", "(", "OperatorSupportBase", ")", ":", "def", "is_node_supported", "(", "self", ",", "submodules", ":", "t", ".", "Mapping", "[", "str", ",", "torch", ".", "nn", ".", "Module", "]", ",", "node", ":", "torch", ".", "fx", ".", "Node", ")", "->", "bool", ":", "return", "is_node_supported", "(", "submodules", ",", "node", ")", "return", "FunctionalOperatorSupport", "(", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/passes/operator_support.py#L133-L144
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/base/android/jni_generator/jni_registration_generator.py
python
CreateFromDict
(registration_dict, use_hash)
return template.substitute(registration_dict)
Returns the content of the header file.
Returns the content of the header file.
[ "Returns", "the", "content", "of", "the", "header", "file", "." ]
def CreateFromDict(registration_dict, use_hash): """Returns the content of the header file.""" template = string.Template("""\ // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is autogenerated by // base/android/jni_generator/jni_registration_generator.py // Please do not change its content. #ifndef ${HEADER_GUARD} #define ${HEADER_GUARD} #include <jni.h> #include "base/android/jni_generator/jni_generator_helper.h" #include "base/android/jni_int_wrapper.h" #include "base/cxx17_backports.h" // For base::size(). // Step 1: Forward declarations (classes). ${CLASS_PATH_DECLARATIONS} // Step 2: Forward declarations (methods). ${FORWARD_DECLARATIONS} // Step 3: Method declarations. ${JNI_NATIVE_METHOD_ARRAY}\ ${PROXY_NATIVE_METHOD_ARRAY}\ ${JNI_NATIVE_METHOD} // Step 4: Main dex and non-main dex registration functions. namespace ${NAMESPACE} { bool RegisterMainDexNatives(JNIEnv* env) {\ ${REGISTER_MAIN_DEX_PROXY_NATIVES} ${REGISTER_MAIN_DEX_NATIVES} return true; } bool RegisterNonMainDexNatives(JNIEnv* env) {\ ${REGISTER_PROXY_NATIVES} ${REGISTER_NON_MAIN_DEX_NATIVES} return true; } } // namespace ${NAMESPACE} #endif // ${HEADER_GUARD} """) _SetProxyRegistrationFields(registration_dict, use_hash) if len(registration_dict['FORWARD_DECLARATIONS']) == 0: return '' return template.substitute(registration_dict)
[ "def", "CreateFromDict", "(", "registration_dict", ",", "use_hash", ")", ":", "template", "=", "string", ".", "Template", "(", "\"\"\"\\\n// Copyright 2017 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n\n// This file is autogenerated by\n// base/android/jni_generator/jni_registration_generator.py\n// Please do not change its content.\n\n#ifndef ${HEADER_GUARD}\n#define ${HEADER_GUARD}\n\n#include <jni.h>\n\n#include \"base/android/jni_generator/jni_generator_helper.h\"\n#include \"base/android/jni_int_wrapper.h\"\n#include \"base/cxx17_backports.h\" // For base::size().\n\n\n// Step 1: Forward declarations (classes).\n${CLASS_PATH_DECLARATIONS}\n\n// Step 2: Forward declarations (methods).\n\n${FORWARD_DECLARATIONS}\n\n// Step 3: Method declarations.\n\n${JNI_NATIVE_METHOD_ARRAY}\\\n${PROXY_NATIVE_METHOD_ARRAY}\\\n\n${JNI_NATIVE_METHOD}\n// Step 4: Main dex and non-main dex registration functions.\n\nnamespace ${NAMESPACE} {\n\nbool RegisterMainDexNatives(JNIEnv* env) {\\\n${REGISTER_MAIN_DEX_PROXY_NATIVES}\n${REGISTER_MAIN_DEX_NATIVES}\n return true;\n}\n\nbool RegisterNonMainDexNatives(JNIEnv* env) {\\\n${REGISTER_PROXY_NATIVES}\n${REGISTER_NON_MAIN_DEX_NATIVES}\n return true;\n}\n\n} // namespace ${NAMESPACE}\n\n#endif // ${HEADER_GUARD}\n\"\"\"", ")", "_SetProxyRegistrationFields", "(", "registration_dict", ",", "use_hash", ")", "if", "len", "(", "registration_dict", "[", "'FORWARD_DECLARATIONS'", "]", ")", "==", "0", ":", "return", "''", "return", "template", ".", "substitute", "(", "registration_dict", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/base/android/jni_generator/jni_registration_generator.py#L250-L311
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/cpplint.py
python
_Filters
()
return _cpplint_state.filters
Returns the module's list of output filters, as a list.
Returns the module's list of output filters, as a list.
[ "Returns", "the", "module", "s", "list", "of", "output", "filters", "as", "a", "list", "." ]
def _Filters(): """Returns the module's list of output filters, as a list.""" return _cpplint_state.filters
[ "def", "_Filters", "(", ")", ":", "return", "_cpplint_state", ".", "filters" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/cpplint.py#L871-L873
vicaya/hypertable
e7386f799c238c109ae47973417c2a2c7f750825
src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py
python
Client.open_mutator
(self, name, flags, flush_interval)
return self.recv_open_mutator()
Open a table mutator @param name - table name @param flags - mutator flags @param flush_interval - auto-flush interval in milliseconds; 0 disables it. @return mutator id Parameters: - name - flags - flush_interval
Open a table mutator
[ "Open", "a", "table", "mutator" ]
def open_mutator(self, name, flags, flush_interval): """ Open a table mutator @param name - table name @param flags - mutator flags @param flush_interval - auto-flush interval in milliseconds; 0 disables it. @return mutator id Parameters: - name - flags - flush_interval """ self.send_open_mutator(name, flags, flush_interval) return self.recv_open_mutator()
[ "def", "open_mutator", "(", "self", ",", "name", ",", "flags", ",", "flush_interval", ")", ":", "self", ".", "send_open_mutator", "(", "name", ",", "flags", ",", "flush_interval", ")", "return", "self", ".", "recv_open_mutator", "(", ")" ]
https://github.com/vicaya/hypertable/blob/e7386f799c238c109ae47973417c2a2c7f750825/src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py#L783-L801
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
SimRobotController.getCommandedTorque
(self)
return _robotsim.SimRobotController_getCommandedTorque(self)
r""" Returns The current commanded (feedforward) torque (size model().numDrivers())
r""" Returns The current commanded (feedforward) torque (size model().numDrivers())
[ "r", "Returns", "The", "current", "commanded", "(", "feedforward", ")", "torque", "(", "size", "model", "()", ".", "numDrivers", "()", ")" ]
def getCommandedTorque(self) ->None: r""" Returns The current commanded (feedforward) torque (size model().numDrivers()) """ return _robotsim.SimRobotController_getCommandedTorque(self)
[ "def", "getCommandedTorque", "(", "self", ")", "->", "None", ":", "return", "_robotsim", ".", "SimRobotController_getCommandedTorque", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L7090-L7095
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/common/system/path.py
python
cygpath
(path)
return path
Converts an absolute cygwin path to an absolute Windows path.
Converts an absolute cygwin path to an absolute Windows path.
[ "Converts", "an", "absolute", "cygwin", "path", "to", "an", "absolute", "Windows", "path", "." ]
def cygpath(path): """Converts an absolute cygwin path to an absolute Windows path.""" if sys.platform == 'cygwin': return _CygPath.convert_using_singleton(path) return path
[ "def", "cygpath", "(", "path", ")", ":", "if", "sys", ".", "platform", "==", "'cygwin'", ":", "return", "_CygPath", ".", "convert_using_singleton", "(", "path", ")", "return", "path" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/common/system/path.py#L47-L51
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/graph_kernel/splitter.py
python
split_with_json
(json_str, flags_str)
Call cost model to split GraphKernel
Call cost model to split GraphKernel
[ "Call", "cost", "model", "to", "split", "GraphKernel" ]
def split_with_json(json_str, flags_str): """Call cost model to split GraphKernel""" try: graph_desc = json.loads(json_str) flags = json.loads(flags_str) target = graph_desc['process'] comp = model.load_composite(graph_desc) graph_split, graph_mode = model.split(comp.graph, target, flags) is_multi_graph = len(graph_split) > 1 graph_list = list(map(comp.dump, graph_split)) _reset_graphmode_for_inplaceassign(graph_list, graph_mode) result = {"multi_graph": is_multi_graph, "graph_desc": graph_list, "graph_mode": graph_mode} _dump_split_info(flags, json_str, comp.graph, graph_split, graph_mode) return json.dumps(result) except jd.JSONDecodeError: logger.error(traceback.format_exc()) return None
[ "def", "split_with_json", "(", "json_str", ",", "flags_str", ")", ":", "try", ":", "graph_desc", "=", "json", ".", "loads", "(", "json_str", ")", "flags", "=", "json", ".", "loads", "(", "flags_str", ")", "target", "=", "graph_desc", "[", "'process'", "]", "comp", "=", "model", ".", "load_composite", "(", "graph_desc", ")", "graph_split", ",", "graph_mode", "=", "model", ".", "split", "(", "comp", ".", "graph", ",", "target", ",", "flags", ")", "is_multi_graph", "=", "len", "(", "graph_split", ")", ">", "1", "graph_list", "=", "list", "(", "map", "(", "comp", ".", "dump", ",", "graph_split", ")", ")", "_reset_graphmode_for_inplaceassign", "(", "graph_list", ",", "graph_mode", ")", "result", "=", "{", "\"multi_graph\"", ":", "is_multi_graph", ",", "\"graph_desc\"", ":", "graph_list", ",", "\"graph_mode\"", ":", "graph_mode", "}", "_dump_split_info", "(", "flags", ",", "json_str", ",", "comp", ".", "graph", ",", "graph_split", ",", "graph_mode", ")", "return", "json", ".", "dumps", "(", "result", ")", "except", "jd", ".", "JSONDecodeError", ":", "logger", ".", "error", "(", "traceback", ".", "format_exc", "(", ")", ")", "return", "None" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/graph_kernel/splitter.py#L26-L44
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibook.py
python
AuiNotebook.OnRenameAccept
(self, page_index, value)
return not self.GetEventHandler().ProcessEvent(evt) or evt.IsAllowed()
Called by :class:`TabTextCtrl`, to accept the changes and to send the ``EVT_AUINOTEBOOK_END_LABEL_EDIT`` event. :param integer `page_index`: the page index in the notebook; :param string `value`: the new label for the tab.
Called by :class:`TabTextCtrl`, to accept the changes and to send the ``EVT_AUINOTEBOOK_END_LABEL_EDIT`` event.
[ "Called", "by", ":", "class", ":", "TabTextCtrl", "to", "accept", "the", "changes", "and", "to", "send", "the", "EVT_AUINOTEBOOK_END_LABEL_EDIT", "event", "." ]
def OnRenameAccept(self, page_index, value): """ Called by :class:`TabTextCtrl`, to accept the changes and to send the ``EVT_AUINOTEBOOK_END_LABEL_EDIT`` event. :param integer `page_index`: the page index in the notebook; :param string `value`: the new label for the tab. """ evt = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_END_LABEL_EDIT, self.GetId()) evt.SetSelection(page_index) evt.SetEventObject(self) evt.SetLabel(value) evt.SetEditCanceled(False) return not self.GetEventHandler().ProcessEvent(evt) or evt.IsAllowed()
[ "def", "OnRenameAccept", "(", "self", ",", "page_index", ",", "value", ")", ":", "evt", "=", "AuiNotebookEvent", "(", "wxEVT_COMMAND_AUINOTEBOOK_END_LABEL_EDIT", ",", "self", ".", "GetId", "(", ")", ")", "evt", ".", "SetSelection", "(", "page_index", ")", "evt", ".", "SetEventObject", "(", "self", ")", "evt", ".", "SetLabel", "(", "value", ")", "evt", ".", "SetEditCanceled", "(", "False", ")", "return", "not", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "evt", ")", "or", "evt", ".", "IsAllowed", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibook.py#L6014-L6029
facebook/fbthrift
fb9c8562aba04c4fd9b17716eb5d970cc88a75bb
thrift/lib/py/util/__init__.py
python
__list_to_dict
(alist, type_args, defaults: bool=False)
Given a python list-like collection, potentially containing Thrift Structs, convert it into a dict :param alist: a list or set :param defaults: return default values :return: List
Given a python list-like collection, potentially containing Thrift Structs, convert it into a dict :param alist: a list or set :param defaults: return default values :return: List
[ "Given", "a", "python", "list", "-", "like", "collection", "potentially", "containing", "Thrift", "Structs", "convert", "it", "into", "a", "dict", ":", "param", "alist", ":", "a", "list", "or", "set", ":", "param", "defaults", ":", "return", "default", "values", ":", "return", ":", "List" ]
def __list_to_dict(alist, type_args, defaults: bool=False): """ Given a python list-like collection, potentially containing Thrift Structs, convert it into a dict :param alist: a list or set :param defaults: return default values :return: List """ if not alist: return alist element_type = type_args[0] if element_type == TType.STRUCT: return [struct_to_dict(element, defaults=defaults) for element in alist] if element_type == TType.LIST: return [ __list_to_dict(element, type_args[1], defaults=defaults) for element in alist ] if element_type == TType.SET: return [ __set_to_dict(element, type_args[1], defaults=defaults) for element in alist ] else: return alist
[ "def", "__list_to_dict", "(", "alist", ",", "type_args", ",", "defaults", ":", "bool", "=", "False", ")", ":", "if", "not", "alist", ":", "return", "alist", "element_type", "=", "type_args", "[", "0", "]", "if", "element_type", "==", "TType", ".", "STRUCT", ":", "return", "[", "struct_to_dict", "(", "element", ",", "defaults", "=", "defaults", ")", "for", "element", "in", "alist", "]", "if", "element_type", "==", "TType", ".", "LIST", ":", "return", "[", "__list_to_dict", "(", "element", ",", "type_args", "[", "1", "]", ",", "defaults", "=", "defaults", ")", "for", "element", "in", "alist", "]", "if", "element_type", "==", "TType", ".", "SET", ":", "return", "[", "__set_to_dict", "(", "element", ",", "type_args", "[", "1", "]", ",", "defaults", "=", "defaults", ")", "for", "element", "in", "alist", "]", "else", ":", "return", "alist" ]
https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/thrift/lib/py/util/__init__.py#L123-L147
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBPlatformShellCommand.SetWorkingDirectory
(self, path)
return _lldb.SBPlatformShellCommand_SetWorkingDirectory(self, path)
SetWorkingDirectory(SBPlatformShellCommand self, char const * path)
SetWorkingDirectory(SBPlatformShellCommand self, char const * path)
[ "SetWorkingDirectory", "(", "SBPlatformShellCommand", "self", "char", "const", "*", "path", ")" ]
def SetWorkingDirectory(self, path): """SetWorkingDirectory(SBPlatformShellCommand self, char const * path)""" return _lldb.SBPlatformShellCommand_SetWorkingDirectory(self, path)
[ "def", "SetWorkingDirectory", "(", "self", ",", "path", ")", ":", "return", "_lldb", ".", "SBPlatformShellCommand_SetWorkingDirectory", "(", "self", ",", "path", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L8025-L8027
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/contrib/_appengine_environ.py
python
is_appengine_sandbox
()
return is_appengine() and os.environ["APPENGINE_RUNTIME"] == "python27"
Reports if the app is running in the first generation sandbox. The second generation runtimes are technically still in a sandbox, but it is much less restrictive, so generally you shouldn't need to check for it. see https://cloud.google.com/appengine/docs/standard/runtimes
Reports if the app is running in the first generation sandbox.
[ "Reports", "if", "the", "app", "is", "running", "in", "the", "first", "generation", "sandbox", "." ]
def is_appengine_sandbox(): """Reports if the app is running in the first generation sandbox. The second generation runtimes are technically still in a sandbox, but it is much less restrictive, so generally you shouldn't need to check for it. see https://cloud.google.com/appengine/docs/standard/runtimes """ return is_appengine() and os.environ["APPENGINE_RUNTIME"] == "python27"
[ "def", "is_appengine_sandbox", "(", ")", ":", "return", "is_appengine", "(", ")", "and", "os", ".", "environ", "[", "\"APPENGINE_RUNTIME\"", "]", "==", "\"python27\"" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/contrib/_appengine_environ.py#L12-L19
google/mediapipe
e6c19885c6d3c6f410c730952aeed2852790d306
mediapipe/python/solutions/face_detection.py
python
get_key_point
( detection: detection_pb2.Detection, key_point_enum: 'FaceKeyPoint' )
return detection.location_data.relative_keypoints[key_point_enum]
A convenience method to return a face key point by the FaceKeyPoint type. Args: detection: A detection proto message that contains face key points. key_point_enum: A FaceKeyPoint type. Returns: A RelativeKeypoint proto message.
A convenience method to return a face key point by the FaceKeyPoint type.
[ "A", "convenience", "method", "to", "return", "a", "face", "key", "point", "by", "the", "FaceKeyPoint", "type", "." ]
def get_key_point( detection: detection_pb2.Detection, key_point_enum: 'FaceKeyPoint' ) -> Union[None, location_data_pb2.LocationData.RelativeKeypoint]: """A convenience method to return a face key point by the FaceKeyPoint type. Args: detection: A detection proto message that contains face key points. key_point_enum: A FaceKeyPoint type. Returns: A RelativeKeypoint proto message. """ if not detection or not detection.location_data: return None return detection.location_data.relative_keypoints[key_point_enum]
[ "def", "get_key_point", "(", "detection", ":", "detection_pb2", ".", "Detection", ",", "key_point_enum", ":", "'FaceKeyPoint'", ")", "->", "Union", "[", "None", ",", "location_data_pb2", ".", "LocationData", ".", "RelativeKeypoint", "]", ":", "if", "not", "detection", "or", "not", "detection", ".", "location_data", ":", "return", "None", "return", "detection", ".", "location_data", ".", "relative_keypoints", "[", "key_point_enum", "]" ]
https://github.com/google/mediapipe/blob/e6c19885c6d3c6f410c730952aeed2852790d306/mediapipe/python/solutions/face_detection.py#L35-L49
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/importers/CNTK/lib/cntk_layers.py
python
DenseLayer.process
(self, ellLayers)
Appends the ELL equivalent of the current layer to ellLayers.
Appends the ELL equivalent of the current layer to ellLayers.
[ "Appends", "the", "ELL", "equivalent", "of", "the", "current", "layer", "to", "ellLayers", "." ]
def process(self, ellLayers): """Appends the ELL equivalent of the current layer to ellLayers.""" # Note that a single CNTK Dense function block is equivalent to the following 3 ELL layers: # - FullyConnectedLayer # - BiasLayer # - ActivationLayer. This layer is sometimes missing, depending on activation type. # # Therefore, make sure the output padding characteristics of the last layer reflect the next layer's # padding requirements. weightsParameter = utilities.find_parameter_by_name( self.layer.parameters, 'W', 0) biasParameter = utilities.find_parameter_by_name( self.layer.parameters, 'b', 1) weightsTensor = converters.get_tensor_from_cntk_dense_weight_parameter( weightsParameter) biasVector = converters.get_vector_from_cntk_trainable_parameter( biasParameter) # Create the ell.neural.LayerParameters for the various ELL layers firstLayerParameters = ell.neural.LayerParameters( self.layer.ell_inputShape, self.layer.ell_inputPaddingParameters, self.layer.ell_outputShapeMinusPadding, ell.neural.NoPadding(), ell.nodes.PortType.smallReal) middleLayerParameters = ell.neural.LayerParameters( self.layer.ell_outputShapeMinusPadding, ell.neural.NoPadding(), self.layer.ell_outputShapeMinusPadding, ell.neural.NoPadding(), ell.nodes.PortType.smallReal) lastLayerParameters = ell.neural.LayerParameters( self.layer.ell_outputShapeMinusPadding, ell.neural.NoPadding(), self.layer.ell_outputShape, self.layer.ell_outputPaddingParameters, ell.nodes.PortType.smallReal) layerParameters = firstLayerParameters internalNodes = utilities.get_model_layers(self.layer.block_root) activationType = utilities.get_ell_activation_type(internalNodes) # Create the ELL fully connected layer ellLayers.append(ell.neural.FullyConnectedLayer( layerParameters, weightsTensor)) # Create the ELL bias layer if (utilities.is_softmax_activation(internalNodes) or activationType is not None): layerParameters = middleLayerParameters else: layerParameters = lastLayerParameters ellLayers.append(ell.neural.BiasLayer(layerParameters, biasVector)) # Create the ELL activation layer if (utilities.is_softmax_activation(internalNodes) or activationType is not None): layerParameters = lastLayerParameters # Special case: if this is softmax activation, create an ELL Softmax layer. # Else, insert an ELL ActivationLayer if (utilities.is_softmax_activation(internalNodes)): ellLayers.append(ell.neural.SoftmaxLayer(layerParameters)) else: if (activationType is not None): ellLayers.append(ell.neural.ActivationLayer( layerParameters, activationType))
[ "def", "process", "(", "self", ",", "ellLayers", ")", ":", "# Note that a single CNTK Dense function block is equivalent to the following 3 ELL layers:", "# - FullyConnectedLayer", "# - BiasLayer", "# - ActivationLayer. This layer is sometimes missing, depending on activation type.", "#", "# Therefore, make sure the output padding characteristics of the last layer reflect the next layer's", "# padding requirements.", "weightsParameter", "=", "utilities", ".", "find_parameter_by_name", "(", "self", ".", "layer", ".", "parameters", ",", "'W'", ",", "0", ")", "biasParameter", "=", "utilities", ".", "find_parameter_by_name", "(", "self", ".", "layer", ".", "parameters", ",", "'b'", ",", "1", ")", "weightsTensor", "=", "converters", ".", "get_tensor_from_cntk_dense_weight_parameter", "(", "weightsParameter", ")", "biasVector", "=", "converters", ".", "get_vector_from_cntk_trainable_parameter", "(", "biasParameter", ")", "# Create the ell.neural.LayerParameters for the various ELL layers", "firstLayerParameters", "=", "ell", ".", "neural", ".", "LayerParameters", "(", "self", ".", "layer", ".", "ell_inputShape", ",", "self", ".", "layer", ".", "ell_inputPaddingParameters", ",", "self", ".", "layer", ".", "ell_outputShapeMinusPadding", ",", "ell", ".", "neural", ".", "NoPadding", "(", ")", ",", "ell", ".", "nodes", ".", "PortType", ".", "smallReal", ")", "middleLayerParameters", "=", "ell", ".", "neural", ".", "LayerParameters", "(", "self", ".", "layer", ".", "ell_outputShapeMinusPadding", ",", "ell", ".", "neural", ".", "NoPadding", "(", ")", ",", "self", ".", "layer", ".", "ell_outputShapeMinusPadding", ",", "ell", ".", "neural", ".", "NoPadding", "(", ")", ",", "ell", ".", "nodes", ".", "PortType", ".", "smallReal", ")", "lastLayerParameters", "=", "ell", ".", "neural", ".", "LayerParameters", "(", "self", ".", "layer", ".", "ell_outputShapeMinusPadding", ",", "ell", ".", "neural", ".", "NoPadding", "(", ")", ",", "self", ".", "layer", ".", "ell_outputShape", ",", "self", ".", "layer", ".", "ell_outputPaddingParameters", ",", "ell", ".", "nodes", ".", "PortType", ".", "smallReal", ")", "layerParameters", "=", "firstLayerParameters", "internalNodes", "=", "utilities", ".", "get_model_layers", "(", "self", ".", "layer", ".", "block_root", ")", "activationType", "=", "utilities", ".", "get_ell_activation_type", "(", "internalNodes", ")", "# Create the ELL fully connected layer", "ellLayers", ".", "append", "(", "ell", ".", "neural", ".", "FullyConnectedLayer", "(", "layerParameters", ",", "weightsTensor", ")", ")", "# Create the ELL bias layer", "if", "(", "utilities", ".", "is_softmax_activation", "(", "internalNodes", ")", "or", "activationType", "is", "not", "None", ")", ":", "layerParameters", "=", "middleLayerParameters", "else", ":", "layerParameters", "=", "lastLayerParameters", "ellLayers", ".", "append", "(", "ell", ".", "neural", ".", "BiasLayer", "(", "layerParameters", ",", "biasVector", ")", ")", "# Create the ELL activation layer", "if", "(", "utilities", ".", "is_softmax_activation", "(", "internalNodes", ")", "or", "activationType", "is", "not", "None", ")", ":", "layerParameters", "=", "lastLayerParameters", "# Special case: if this is softmax activation, create an ELL Softmax layer.", "# Else, insert an ELL ActivationLayer", "if", "(", "utilities", ".", "is_softmax_activation", "(", "internalNodes", ")", ")", ":", "ellLayers", ".", "append", "(", "ell", ".", "neural", ".", "SoftmaxLayer", "(", "layerParameters", ")", ")", "else", ":", "if", "(", "activationType", "is", "not", "None", ")", ":", "ellLayers", ".", "append", "(", "ell", ".", "neural", ".", "ActivationLayer", "(", "layerParameters", ",", "activationType", ")", ")" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/CNTK/lib/cntk_layers.py#L106-L164
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
tools/extra/summarize.py
python
print_table
(table, max_width)
Print a simple nicely-aligned table. table must be a list of (equal-length) lists. Columns are space-separated, and as narrow as possible, but no wider than max_width. Text may overflow columns; note that unlike string.format, this will not affect subsequent columns, if possible.
Print a simple nicely-aligned table.
[ "Print", "a", "simple", "nicely", "-", "aligned", "table", "." ]
def print_table(table, max_width): """Print a simple nicely-aligned table. table must be a list of (equal-length) lists. Columns are space-separated, and as narrow as possible, but no wider than max_width. Text may overflow columns; note that unlike string.format, this will not affect subsequent columns, if possible.""" max_widths = [max_width] * len(table[0]) column_widths = [max(printed_len(row[j]) + 1 for row in table) for j in range(len(table[0]))] column_widths = [min(w, max_w) for w, max_w in zip(column_widths, max_widths)] for row in table: row_str = '' right_col = 0 for cell, width in zip(row, column_widths): right_col += width row_str += cell + ' ' row_str += ' ' * max(right_col - printed_len(row_str), 0) print row_str
[ "def", "print_table", "(", "table", ",", "max_width", ")", ":", "max_widths", "=", "[", "max_width", "]", "*", "len", "(", "table", "[", "0", "]", ")", "column_widths", "=", "[", "max", "(", "printed_len", "(", "row", "[", "j", "]", ")", "+", "1", "for", "row", "in", "table", ")", "for", "j", "in", "range", "(", "len", "(", "table", "[", "0", "]", ")", ")", "]", "column_widths", "=", "[", "min", "(", "w", ",", "max_w", ")", "for", "w", ",", "max_w", "in", "zip", "(", "column_widths", ",", "max_widths", ")", "]", "for", "row", "in", "table", ":", "row_str", "=", "''", "right_col", "=", "0", "for", "cell", ",", "width", "in", "zip", "(", "row", ",", "column_widths", ")", ":", "right_col", "+=", "width", "row_str", "+=", "cell", "+", "' '", "row_str", "+=", "' '", "*", "max", "(", "right_col", "-", "printed_len", "(", "row_str", ")", ",", "0", ")", "print", "row_str" ]
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/tools/extra/summarize.py#L41-L61
nyuwireless-unipd/ns3-mmwave
4ff9e87e8079764e04cbeccd8e85bff15ae16fb3
waf-tools/cflags.py
python
CompilerTraits.get_debug_flags
(self, level)
get_debug_flags(level) -> (list of cflags, list of cppdefines)
get_debug_flags(level) -> (list of cflags, list of cppdefines)
[ "get_debug_flags", "(", "level", ")", "-", ">", "(", "list", "of", "cflags", "list", "of", "cppdefines", ")" ]
def get_debug_flags(self, level): """get_debug_flags(level) -> (list of cflags, list of cppdefines)""" raise NotImplementedError
[ "def", "get_debug_flags", "(", "self", ",", "level", ")", ":", "raise", "NotImplementedError" ]
https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/waf-tools/cflags.py#L13-L15
Atarity/Lightpack
4dee73a443cba4c4073291febe450e6c1941f3af
Software/apiexamples/liOSC/OSC.py
python
OSCServer.__ne__
(self, other)
return not self.__eq__(other)
Compare function.
Compare function.
[ "Compare", "function", "." ]
def __ne__(self, other): """Compare function. """ return not self.__eq__(other)
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "self", ".", "__eq__", "(", "other", ")" ]
https://github.com/Atarity/Lightpack/blob/4dee73a443cba4c4073291febe450e6c1941f3af/Software/apiexamples/liOSC/OSC.py#L1846-L1849
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/s3/inject.py
python
bucket_download_fileobj
(self, Key, Fileobj, ExtraArgs=None, Callback=None, Config=None)
return self.meta.client.download_fileobj( Bucket=self.name, Key=Key, Fileobj=Fileobj, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
Download an object from this bucket to a file-like-object. The file-like object must be in binary mode. This is a managed transfer which will perform a multipart download in multiple threads if necessary. Usage:: import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket('mybucket') with open('filename', 'wb') as data: bucket.download_fileobj('mykey', data) :type Fileobj: a file-like object :param Fileobj: A file-like object to download into. At a minimum, it must implement the `write` method and must accept bytes. :type Key: str :param Key: The name of the key to download from. :type ExtraArgs: dict :param ExtraArgs: Extra arguments that may be passed to the client operation. :type Callback: function :param Callback: A method which takes a number of bytes transferred to be periodically called during the download. :type Config: boto3.s3.transfer.TransferConfig :param Config: The transfer configuration to be used when performing the download.
Download an object from this bucket to a file-like-object.
[ "Download", "an", "object", "from", "this", "bucket", "to", "a", "file", "-", "like", "-", "object", "." ]
def bucket_download_fileobj(self, Key, Fileobj, ExtraArgs=None, Callback=None, Config=None): """Download an object from this bucket to a file-like-object. The file-like object must be in binary mode. This is a managed transfer which will perform a multipart download in multiple threads if necessary. Usage:: import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket('mybucket') with open('filename', 'wb') as data: bucket.download_fileobj('mykey', data) :type Fileobj: a file-like object :param Fileobj: A file-like object to download into. At a minimum, it must implement the `write` method and must accept bytes. :type Key: str :param Key: The name of the key to download from. :type ExtraArgs: dict :param ExtraArgs: Extra arguments that may be passed to the client operation. :type Callback: function :param Callback: A method which takes a number of bytes transferred to be periodically called during the download. :type Config: boto3.s3.transfer.TransferConfig :param Config: The transfer configuration to be used when performing the download. """ return self.meta.client.download_fileobj( Bucket=self.name, Key=Key, Fileobj=Fileobj, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
[ "def", "bucket_download_fileobj", "(", "self", ",", "Key", ",", "Fileobj", ",", "ExtraArgs", "=", "None", ",", "Callback", "=", "None", ",", "Config", "=", "None", ")", ":", "return", "self", ".", "meta", ".", "client", ".", "download_fileobj", "(", "Bucket", "=", "self", ".", "name", ",", "Key", "=", "Key", ",", "Fileobj", "=", "Fileobj", ",", "ExtraArgs", "=", "ExtraArgs", ",", "Callback", "=", "Callback", ",", "Config", "=", "Config", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/s3/inject.py#L681-L720
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
EvtHandler.ProcessEvent
(*args, **kwargs)
return _core_.EvtHandler_ProcessEvent(*args, **kwargs)
ProcessEvent(self, Event event) -> bool
ProcessEvent(self, Event event) -> bool
[ "ProcessEvent", "(", "self", "Event", "event", ")", "-", ">", "bool" ]
def ProcessEvent(*args, **kwargs): """ProcessEvent(self, Event event) -> bool""" return _core_.EvtHandler_ProcessEvent(*args, **kwargs)
[ "def", "ProcessEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "EvtHandler_ProcessEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L4152-L4154
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/javac_output_processor.py
python
JavacOutputProcessor._ElaborateLinesForUnknownSymbol
(self, lines)
Elaborates passed-in javac output for unresolved symbols. Looks for unresolved symbols in imports. Adds: - Line with GN target which cannot compile. - Mention of unresolved class if not present in error message. - Line with suggestion of GN dep to add. Args: lines: Generator with javac input. Returns: Generator with processed output.
Elaborates passed-in javac output for unresolved symbols.
[ "Elaborates", "passed", "-", "in", "javac", "output", "for", "unresolved", "symbols", "." ]
def _ElaborateLinesForUnknownSymbol(self, lines): """ Elaborates passed-in javac output for unresolved symbols. Looks for unresolved symbols in imports. Adds: - Line with GN target which cannot compile. - Mention of unresolved class if not present in error message. - Line with suggestion of GN dep to add. Args: lines: Generator with javac input. Returns: Generator with processed output. """ previous_line = next(lines, None) line = next(lines, None) while previous_line != None: elaborated_lines = self._ElaborateLineForUnknownSymbol( previous_line, line) for elaborated_line in elaborated_lines: yield elaborated_line previous_line = line line = next(lines, None)
[ "def", "_ElaborateLinesForUnknownSymbol", "(", "self", ",", "lines", ")", ":", "previous_line", "=", "next", "(", "lines", ",", "None", ")", "line", "=", "next", "(", "lines", ",", "None", ")", "while", "previous_line", "!=", "None", ":", "elaborated_lines", "=", "self", ".", "_ElaborateLineForUnknownSymbol", "(", "previous_line", ",", "line", ")", "for", "elaborated_line", "in", "elaborated_lines", ":", "yield", "elaborated_line", "previous_line", "=", "line", "line", "=", "next", "(", "lines", ",", "None", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/javac_output_processor.py#L85-L108
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBFrame.GetModule
(self)
return _lldb.SBFrame_GetModule(self)
GetModule(SBFrame self) -> SBModule
GetModule(SBFrame self) -> SBModule
[ "GetModule", "(", "SBFrame", "self", ")", "-", ">", "SBModule" ]
def GetModule(self): """GetModule(SBFrame self) -> SBModule""" return _lldb.SBFrame_GetModule(self)
[ "def", "GetModule", "(", "self", ")", ":", "return", "_lldb", ".", "SBFrame_GetModule", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L5507-L5509
JoseExposito/touchegg
1f3fda214358d071c05da4bf17c070c33d67b5eb
cmake/cpplint.py
python
CheckForNonConstReference
(filename, clean_lines, linenum, nesting_state, error)
Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Check for non-const references.
[ "Check", "for", "non", "-", "const", "references", "." ]
def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error): """Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Do nothing if there is no '&' on current line. line = clean_lines.elided[linenum] if '&' not in line: return # If a function is inherited, current function doesn't have much of # a choice, so any non-const references should not be blamed on # derived function. if IsDerivedFunction(clean_lines, linenum): return # Don't warn on out-of-line method definitions, as we would warn on the # in-line declaration, if it isn't marked with 'override'. if IsOutOfLineMethodDefinition(clean_lines, linenum): return # Long type names may be broken across multiple lines, usually in one # of these forms: # LongType # ::LongTypeContinued &identifier # LongType:: # LongTypeContinued &identifier # LongType< # ...>::LongTypeContinued &identifier # # If we detected a type split across two lines, join the previous # line to current line so that we can match const references # accordingly. # # Note that this only scans back one line, since scanning back # arbitrary number of lines would be expensive. If you have a type # that spans more than 2 lines, please use a typedef. if linenum > 1: previous = None if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): # previous_line\n + ::current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', clean_lines.elided[linenum - 1]) elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): # previous_line::\n + current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', clean_lines.elided[linenum - 1]) if previous: line = previous.group(1) + line.lstrip() else: # Check for templated parameter that is split across multiple lines endpos = line.rfind('>') if endpos > -1: (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, endpos) if startpos > -1 and startline < linenum: # Found the matching < on an earlier line, collect all # pieces up to current line. line = '' for i in xrange(startline, linenum + 1): line += clean_lines.elided[i].strip() # Check for non-const references in function parameters. A single '&' may # found in the following places: # inside expression: binary & for bitwise AND # inside expression: unary & for taking the address of something # inside declarators: reference parameter # We will exclude the first two cases by checking that we are not inside a # function body, including one that was just introduced by a trailing '{'. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. if (nesting_state.previous_stack_top and not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): # Not at toplevel, not within a class, and not within a namespace return # Avoid initializer lists. We only need to scan back from the # current line for something that starts with ':'. # # We don't need to check the current line, since the '&' would # appear inside the second set of parentheses on the current line as # opposed to the first set. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 10), -1): previous_line = clean_lines.elided[i] if not Search(r'[),]\s*$', previous_line): break if Match(r'^\s*:\s+\S', previous_line): return # Avoid preprocessors if Search(r'\\\s*$', line): return # Avoid constructor initializer lists if IsInitializerList(clean_lines, linenum): return # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". Do not check # those function parameters. # # We also accept & in static_assert, which looks like a function but # it's actually a declaration expression. allowed_functions = (r'(?:[sS]wap(?:<\w:+>)?|' r'operator\s*[<>][<>]|' r'static_assert|COMPILE_ASSERT' r')\s*\(') if Search(allowed_functions, line): return elif not Search(r'\S+\([^)]*$', line): # Don't see an allowed function on this line. Actually we # didn't see any function name on this line, so this is likely a # multi-line parameter list. Try a bit harder to catch this case. for i in xrange(2): if (linenum > i and Search(allowed_functions, clean_lines.elided[linenum - i - 1])): return decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer: ' + ReplaceAll(' *<', '<', parameter))
[ "def", "CheckForNonConstReference", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Do nothing if there is no '&' on current line.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "'&'", "not", "in", "line", ":", "return", "# If a function is inherited, current function doesn't have much of", "# a choice, so any non-const references should not be blamed on", "# derived function.", "if", "IsDerivedFunction", "(", "clean_lines", ",", "linenum", ")", ":", "return", "# Don't warn on out-of-line method definitions, as we would warn on the", "# in-line declaration, if it isn't marked with 'override'.", "if", "IsOutOfLineMethodDefinition", "(", "clean_lines", ",", "linenum", ")", ":", "return", "# Long type names may be broken across multiple lines, usually in one", "# of these forms:", "# LongType", "# ::LongTypeContinued &identifier", "# LongType::", "# LongTypeContinued &identifier", "# LongType<", "# ...>::LongTypeContinued &identifier", "#", "# If we detected a type split across two lines, join the previous", "# line to current line so that we can match const references", "# accordingly.", "#", "# Note that this only scans back one line, since scanning back", "# arbitrary number of lines would be expensive. If you have a type", "# that spans more than 2 lines, please use a typedef.", "if", "linenum", ">", "1", ":", "previous", "=", "None", "if", "Match", "(", "r'\\s*::(?:[\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line\\n + ::current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+[\\w<>])\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "elif", "Match", "(", "r'\\s*[a-zA-Z_]([\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line::\\n + current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+::)\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "if", "previous", ":", "line", "=", "previous", ".", "group", "(", "1", ")", "+", "line", ".", "lstrip", "(", ")", "else", ":", "# Check for templated parameter that is split across multiple lines", "endpos", "=", "line", ".", "rfind", "(", "'>'", ")", "if", "endpos", ">", "-", "1", ":", "(", "_", ",", "startline", ",", "startpos", ")", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "endpos", ")", "if", "startpos", ">", "-", "1", "and", "startline", "<", "linenum", ":", "# Found the matching < on an earlier line, collect all", "# pieces up to current line.", "line", "=", "''", "for", "i", "in", "xrange", "(", "startline", ",", "linenum", "+", "1", ")", ":", "line", "+=", "clean_lines", ".", "elided", "[", "i", "]", ".", "strip", "(", ")", "# Check for non-const references in function parameters. A single '&' may", "# found in the following places:", "# inside expression: binary & for bitwise AND", "# inside expression: unary & for taking the address of something", "# inside declarators: reference parameter", "# We will exclude the first two cases by checking that we are not inside a", "# function body, including one that was just introduced by a trailing '{'.", "# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].", "if", "(", "nesting_state", ".", "previous_stack_top", "and", "not", "(", "isinstance", "(", "nesting_state", ".", "previous_stack_top", ",", "_ClassInfo", ")", "or", "isinstance", "(", "nesting_state", ".", "previous_stack_top", ",", "_NamespaceInfo", ")", ")", ")", ":", "# Not at toplevel, not within a class, and not within a namespace", "return", "# Avoid initializer lists. We only need to scan back from the", "# current line for something that starts with ':'.", "#", "# We don't need to check the current line, since the '&' would", "# appear inside the second set of parentheses on the current line as", "# opposed to the first set.", "if", "linenum", ">", "0", ":", "for", "i", "in", "xrange", "(", "linenum", "-", "1", ",", "max", "(", "0", ",", "linenum", "-", "10", ")", ",", "-", "1", ")", ":", "previous_line", "=", "clean_lines", ".", "elided", "[", "i", "]", "if", "not", "Search", "(", "r'[),]\\s*$'", ",", "previous_line", ")", ":", "break", "if", "Match", "(", "r'^\\s*:\\s+\\S'", ",", "previous_line", ")", ":", "return", "# Avoid preprocessors", "if", "Search", "(", "r'\\\\\\s*$'", ",", "line", ")", ":", "return", "# Avoid constructor initializer lists", "if", "IsInitializerList", "(", "clean_lines", ",", "linenum", ")", ":", "return", "# We allow non-const references in a few standard places, like functions", "# called \"swap()\" or iostream operators like \"<<\" or \">>\". Do not check", "# those function parameters.", "#", "# We also accept & in static_assert, which looks like a function but", "# it's actually a declaration expression.", "allowed_functions", "=", "(", "r'(?:[sS]wap(?:<\\w:+>)?|'", "r'operator\\s*[<>][<>]|'", "r'static_assert|COMPILE_ASSERT'", "r')\\s*\\('", ")", "if", "Search", "(", "allowed_functions", ",", "line", ")", ":", "return", "elif", "not", "Search", "(", "r'\\S+\\([^)]*$'", ",", "line", ")", ":", "# Don't see an allowed function on this line. Actually we", "# didn't see any function name on this line, so this is likely a", "# multi-line parameter list. Try a bit harder to catch this case.", "for", "i", "in", "xrange", "(", "2", ")", ":", "if", "(", "linenum", ">", "i", "and", "Search", "(", "allowed_functions", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "i", "-", "1", "]", ")", ")", ":", "return", "decls", "=", "ReplaceAll", "(", "r'{[^}]*}'", ",", "' '", ",", "line", ")", "# exclude function body", "for", "parameter", "in", "re", ".", "findall", "(", "_RE_PATTERN_REF_PARAM", ",", "decls", ")", ":", "if", "(", "not", "Match", "(", "_RE_PATTERN_CONST_REF_PARAM", ",", "parameter", ")", "and", "not", "Match", "(", "_RE_PATTERN_REF_STREAM_PARAM", ",", "parameter", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/references'", ",", "2", ",", "'Is this a non-const reference? '", "'If so, make const or use a pointer: '", "+", "ReplaceAll", "(", "' *<'", ",", "'<'", ",", "parameter", ")", ")" ]
https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L5013-L5149
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/utils/pair_tab.py
python
PairTab.reinit
(self, filename : str )
Initialize the tabulated interaction Parameters ---------- filename File name for the short-range tabulated potential. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
Initialize the tabulated interaction
[ "Initialize", "the", "tabulated", "interaction" ]
def reinit(self, filename : str ) -> None: """ Initialize the tabulated interaction Parameters ---------- filename File name for the short-range tabulated potential. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly. """ self.vdata = np.loadtxt(filename) self.rmin = self.vdata[0][0] self.hh = self.vdata[1][0] - self.vdata[0][0] self.nspline = self.vdata.shape[0] - 1 ncol = self.vdata.shape[1] - 1 n0 = (-1 + np.sqrt(1 + 8 * ncol)) * 0.5 self.ntypes = int(n0 + 0.1) assert(self.ntypes * (self.ntypes+1) // 2 == ncol),\ "number of volumes provided in %s does not match guessed number of types %d" % (filename, self.ntypes) self.tab_info = np.array([self.rmin, self.hh, self.nspline, self.ntypes]) self.tab_data = self._make_data()
[ "def", "reinit", "(", "self", ",", "filename", ":", "str", ")", "->", "None", ":", "self", ".", "vdata", "=", "np", ".", "loadtxt", "(", "filename", ")", "self", ".", "rmin", "=", "self", ".", "vdata", "[", "0", "]", "[", "0", "]", "self", ".", "hh", "=", "self", ".", "vdata", "[", "1", "]", "[", "0", "]", "-", "self", ".", "vdata", "[", "0", "]", "[", "0", "]", "self", ".", "nspline", "=", "self", ".", "vdata", ".", "shape", "[", "0", "]", "-", "1", "ncol", "=", "self", ".", "vdata", ".", "shape", "[", "1", "]", "-", "1", "n0", "=", "(", "-", "1", "+", "np", ".", "sqrt", "(", "1", "+", "8", "*", "ncol", ")", ")", "*", "0.5", "self", ".", "ntypes", "=", "int", "(", "n0", "+", "0.1", ")", "assert", "(", "self", ".", "ntypes", "*", "(", "self", ".", "ntypes", "+", "1", ")", "//", "2", "==", "ncol", ")", ",", "\"number of volumes provided in %s does not match guessed number of types %d\"", "%", "(", "filename", ",", "self", ".", "ntypes", ")", "self", ".", "tab_info", "=", "np", ".", "array", "(", "[", "self", ".", "rmin", ",", "self", ".", "hh", ",", "self", ".", "nspline", ",", "self", ".", "ntypes", "]", ")", "self", ".", "tab_data", "=", "self", ".", "_make_data", "(", ")" ]
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/utils/pair_tab.py#L29-L55
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/command/build_py.py
python
build_py.exclude_data_files
(self, package, src_dir, files)
return [ f for f in files if f not in bad and f not in seen and seen.setdefault(f,1) # ditch dupes ]
Filter filenames for package's data files in 'src_dir
Filter filenames for package's data files in 'src_dir
[ "Filter", "filenames", "for", "package", "s", "data", "files", "in", "src_dir" ]
def exclude_data_files(self, package, src_dir, files): """Filter filenames for package's data files in 'src_dir'""" globs = (self.exclude_package_data.get('', []) + self.exclude_package_data.get(package, [])) bad = [] for pattern in globs: bad.extend( fnmatch.filter( files, os.path.join(src_dir, convert_path(pattern)) ) ) bad = dict.fromkeys(bad) seen = {} return [ f for f in files if f not in bad and f not in seen and seen.setdefault(f,1) # ditch dupes ]
[ "def", "exclude_data_files", "(", "self", ",", "package", ",", "src_dir", ",", "files", ")", ":", "globs", "=", "(", "self", ".", "exclude_package_data", ".", "get", "(", "''", ",", "[", "]", ")", "+", "self", ".", "exclude_package_data", ".", "get", "(", "package", ",", "[", "]", ")", ")", "bad", "=", "[", "]", "for", "pattern", "in", "globs", ":", "bad", ".", "extend", "(", "fnmatch", ".", "filter", "(", "files", ",", "os", ".", "path", ".", "join", "(", "src_dir", ",", "convert_path", "(", "pattern", ")", ")", ")", ")", "bad", "=", "dict", ".", "fromkeys", "(", "bad", ")", "seen", "=", "{", "}", "return", "[", "f", "for", "f", "in", "files", "if", "f", "not", "in", "bad", "and", "f", "not", "in", "seen", "and", "seen", ".", "setdefault", "(", "f", ",", "1", ")", "# ditch dupes", "]" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/command/build_py.py#L240-L256
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
DateTime.MakeTimezone
(*args, **kwargs)
return _misc_.DateTime_MakeTimezone(*args, **kwargs)
MakeTimezone(self, wxDateTime::TimeZone tz, bool noDST=False) -> DateTime
MakeTimezone(self, wxDateTime::TimeZone tz, bool noDST=False) -> DateTime
[ "MakeTimezone", "(", "self", "wxDateTime", "::", "TimeZone", "tz", "bool", "noDST", "=", "False", ")", "-", ">", "DateTime" ]
def MakeTimezone(*args, **kwargs): """MakeTimezone(self, wxDateTime::TimeZone tz, bool noDST=False) -> DateTime""" return _misc_.DateTime_MakeTimezone(*args, **kwargs)
[ "def", "MakeTimezone", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_MakeTimezone", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3926-L3928
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/pytables.py
python
HDFStore.select_as_multiple
(self, keys, where=None, selector=None, columns=None, start=None, stop=None, iterator=False, chunksize=None, auto_close=False, **kwargs)
return it.get_result(coordinates=True)
Retrieve pandas objects from multiple tables Parameters ---------- keys : a list of the tables selector : the table to apply the where criteria (defaults to keys[0] if not supplied) columns : the columns I want back start : integer (defaults to None), row number to start selection stop : integer (defaults to None), row number to stop selection iterator : boolean, return an iterator, default False chunksize : nrows to include in iteration, return an iterator Exceptions ---------- raises KeyError if keys or selector is not found or keys is empty raises TypeError if keys is not a list or tuple raises ValueError if the tables are not ALL THE SAME DIMENSIONS
Retrieve pandas objects from multiple tables
[ "Retrieve", "pandas", "objects", "from", "multiple", "tables" ]
def select_as_multiple(self, keys, where=None, selector=None, columns=None, start=None, stop=None, iterator=False, chunksize=None, auto_close=False, **kwargs): """ Retrieve pandas objects from multiple tables Parameters ---------- keys : a list of the tables selector : the table to apply the where criteria (defaults to keys[0] if not supplied) columns : the columns I want back start : integer (defaults to None), row number to start selection stop : integer (defaults to None), row number to stop selection iterator : boolean, return an iterator, default False chunksize : nrows to include in iteration, return an iterator Exceptions ---------- raises KeyError if keys or selector is not found or keys is empty raises TypeError if keys is not a list or tuple raises ValueError if the tables are not ALL THE SAME DIMENSIONS """ # default to single select where = _ensure_term(where, scope_level=1) if isinstance(keys, (list, tuple)) and len(keys) == 1: keys = keys[0] if isinstance(keys, string_types): return self.select(key=keys, where=where, columns=columns, start=start, stop=stop, iterator=iterator, chunksize=chunksize, **kwargs) if not isinstance(keys, (list, tuple)): raise TypeError("keys must be a list/tuple") if not len(keys): raise ValueError("keys must have a non-zero length") if selector is None: selector = keys[0] # collect the tables tbls = [self.get_storer(k) for k in keys] s = self.get_storer(selector) # validate rows nrows = None for t, k in itertools.chain([(s, selector)], zip(tbls, keys)): if t is None: raise KeyError("Invalid table [{key}]".format(key=k)) if not t.is_table: raise TypeError( "object [{obj}] is not a table, and cannot be used in all " "select as multiple".format(obj=t.pathname) ) if nrows is None: nrows = t.nrows elif t.nrows != nrows: raise ValueError( "all tables must have exactly the same nrows!") # axis is the concentation axes axis = list({t.non_index_axes[0][0] for t in tbls})[0] def func(_start, _stop, _where): # retrieve the objs, _where is always passed as a set of # coordinates here objs = [t.read(where=_where, columns=columns, start=_start, stop=_stop, **kwargs) for t in tbls] # concat and return return concat(objs, axis=axis, verify_integrity=False)._consolidate() # create the iterator it = TableIterator(self, s, func, where=where, nrows=nrows, start=start, stop=stop, iterator=iterator, chunksize=chunksize, auto_close=auto_close) return it.get_result(coordinates=True)
[ "def", "select_as_multiple", "(", "self", ",", "keys", ",", "where", "=", "None", ",", "selector", "=", "None", ",", "columns", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "iterator", "=", "False", ",", "chunksize", "=", "None", ",", "auto_close", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# default to single select", "where", "=", "_ensure_term", "(", "where", ",", "scope_level", "=", "1", ")", "if", "isinstance", "(", "keys", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "keys", ")", "==", "1", ":", "keys", "=", "keys", "[", "0", "]", "if", "isinstance", "(", "keys", ",", "string_types", ")", ":", "return", "self", ".", "select", "(", "key", "=", "keys", ",", "where", "=", "where", ",", "columns", "=", "columns", ",", "start", "=", "start", ",", "stop", "=", "stop", ",", "iterator", "=", "iterator", ",", "chunksize", "=", "chunksize", ",", "*", "*", "kwargs", ")", "if", "not", "isinstance", "(", "keys", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"keys must be a list/tuple\"", ")", "if", "not", "len", "(", "keys", ")", ":", "raise", "ValueError", "(", "\"keys must have a non-zero length\"", ")", "if", "selector", "is", "None", ":", "selector", "=", "keys", "[", "0", "]", "# collect the tables", "tbls", "=", "[", "self", ".", "get_storer", "(", "k", ")", "for", "k", "in", "keys", "]", "s", "=", "self", ".", "get_storer", "(", "selector", ")", "# validate rows", "nrows", "=", "None", "for", "t", ",", "k", "in", "itertools", ".", "chain", "(", "[", "(", "s", ",", "selector", ")", "]", ",", "zip", "(", "tbls", ",", "keys", ")", ")", ":", "if", "t", "is", "None", ":", "raise", "KeyError", "(", "\"Invalid table [{key}]\"", ".", "format", "(", "key", "=", "k", ")", ")", "if", "not", "t", ".", "is_table", ":", "raise", "TypeError", "(", "\"object [{obj}] is not a table, and cannot be used in all \"", "\"select as multiple\"", ".", "format", "(", "obj", "=", "t", ".", "pathname", ")", ")", "if", "nrows", "is", "None", ":", "nrows", "=", "t", ".", "nrows", "elif", "t", ".", "nrows", "!=", "nrows", ":", "raise", "ValueError", "(", "\"all tables must have exactly the same nrows!\"", ")", "# axis is the concentation axes", "axis", "=", "list", "(", "{", "t", ".", "non_index_axes", "[", "0", "]", "[", "0", "]", "for", "t", "in", "tbls", "}", ")", "[", "0", "]", "def", "func", "(", "_start", ",", "_stop", ",", "_where", ")", ":", "# retrieve the objs, _where is always passed as a set of", "# coordinates here", "objs", "=", "[", "t", ".", "read", "(", "where", "=", "_where", ",", "columns", "=", "columns", ",", "start", "=", "_start", ",", "stop", "=", "_stop", ",", "*", "*", "kwargs", ")", "for", "t", "in", "tbls", "]", "# concat and return", "return", "concat", "(", "objs", ",", "axis", "=", "axis", ",", "verify_integrity", "=", "False", ")", ".", "_consolidate", "(", ")", "# create the iterator", "it", "=", "TableIterator", "(", "self", ",", "s", ",", "func", ",", "where", "=", "where", ",", "nrows", "=", "nrows", ",", "start", "=", "start", ",", "stop", "=", "stop", ",", "iterator", "=", "iterator", ",", "chunksize", "=", "chunksize", ",", "auto_close", "=", "auto_close", ")", "return", "it", ".", "get_result", "(", "coordinates", "=", "True", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/pytables.py#L778-L859
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/progress_callback.py
python
FileProgressCallbackHandler.call
(self, # pylint: disable=invalid-name last_byte_processed, total_size)
Prints an overwriting line to stderr describing the operation progress. Args: last_byte_processed: The last byte processed in the file. For file components, this number should be in the range [start_byte:start_byte + override_total_size]. total_size: Total size of the ongoing operation.
Prints an overwriting line to stderr describing the operation progress.
[ "Prints", "an", "overwriting", "line", "to", "stderr", "describing", "the", "operation", "progress", "." ]
def call(self, # pylint: disable=invalid-name last_byte_processed, total_size): """Prints an overwriting line to stderr describing the operation progress. Args: last_byte_processed: The last byte processed in the file. For file components, this number should be in the range [start_byte:start_byte + override_total_size]. total_size: Total size of the ongoing operation. """ if not self._logger.isEnabledFor(logging.INFO) or self._last_byte_written: return if self._override_total_size: total_size = self._override_total_size if total_size: total_size_string = '/%s' % MakeHumanReadable(total_size) else: total_size_string = '' # Use sys.stderr.write instead of self.logger.info so progress messages # output on a single continuously overwriting line. # TODO: Make this work with logging.Logger. sys.stderr.write('%s%s%s \r' % ( self._announce_text, MakeHumanReadable(last_byte_processed - self._start_byte), total_size_string)) if total_size and last_byte_processed - self._start_byte == total_size: self._last_byte_written = True sys.stderr.write('\n')
[ "def", "call", "(", "self", ",", "# pylint: disable=invalid-name", "last_byte_processed", ",", "total_size", ")", ":", "if", "not", "self", ".", "_logger", ".", "isEnabledFor", "(", "logging", ".", "INFO", ")", "or", "self", ".", "_last_byte_written", ":", "return", "if", "self", ".", "_override_total_size", ":", "total_size", "=", "self", ".", "_override_total_size", "if", "total_size", ":", "total_size_string", "=", "'/%s'", "%", "MakeHumanReadable", "(", "total_size", ")", "else", ":", "total_size_string", "=", "''", "# Use sys.stderr.write instead of self.logger.info so progress messages", "# output on a single continuously overwriting line.", "# TODO: Make this work with logging.Logger.", "sys", ".", "stderr", ".", "write", "(", "'%s%s%s \\r'", "%", "(", "self", ".", "_announce_text", ",", "MakeHumanReadable", "(", "last_byte_processed", "-", "self", ".", "_start_byte", ")", ",", "total_size_string", ")", ")", "if", "total_size", "and", "last_byte_processed", "-", "self", ".", "_start_byte", "==", "total_size", ":", "self", ".", "_last_byte_written", "=", "True", "sys", ".", "stderr", ".", "write", "(", "'\\n'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/progress_callback.py#L141-L171
savoirfairelinux/jami-daemon
7634487e9f568ae727f2d4cffbb735d23fa0324c
tools/jamictrl/controller.py
python
DRingCtrl.Call
(self, dest, account=None)
return callid
Start a call and return a CallID Use the current account previously set using setAccount(). If no account specified, first registered one in account list is used. return callID Newly generated callidentifier for this call
Start a call and return a CallID
[ "Start", "a", "call", "and", "return", "a", "CallID" ]
def Call(self, dest, account=None): """Start a call and return a CallID Use the current account previously set using setAccount(). If no account specified, first registered one in account list is used. return callID Newly generated callidentifier for this call """ if dest is None or dest == "": raise DRingCtrlError("Invalid call destination") # Set the account to be used for this call if not self.account: self.setFirstRegisteredAccount() if self.account != "IP2IP" and not self.isAccountRegistered(): raise DRingCtrlAccountError("Can't place a call without a registered account") # Send the request to the CallManager callid = self.callmanager.placeCall(self.account, dest) if callid: # Add the call to the list of active calls and set status to SENT self.activeCalls[callid] = {'Account': self.account, 'To': dest, 'State': 'SENT' } return callid
[ "def", "Call", "(", "self", ",", "dest", ",", "account", "=", "None", ")", ":", "if", "dest", "is", "None", "or", "dest", "==", "\"\"", ":", "raise", "DRingCtrlError", "(", "\"Invalid call destination\"", ")", "# Set the account to be used for this call", "if", "not", "self", ".", "account", ":", "self", ".", "setFirstRegisteredAccount", "(", ")", "if", "self", ".", "account", "!=", "\"IP2IP\"", "and", "not", "self", ".", "isAccountRegistered", "(", ")", ":", "raise", "DRingCtrlAccountError", "(", "\"Can't place a call without a registered account\"", ")", "# Send the request to the CallManager", "callid", "=", "self", ".", "callmanager", ".", "placeCall", "(", "self", ".", "account", ",", "dest", ")", "if", "callid", ":", "# Add the call to the list of active calls and set status to SENT", "self", ".", "activeCalls", "[", "callid", "]", "=", "{", "'Account'", ":", "self", ".", "account", ",", "'To'", ":", "dest", ",", "'State'", ":", "'SENT'", "}", "return", "callid" ]
https://github.com/savoirfairelinux/jami-daemon/blob/7634487e9f568ae727f2d4cffbb735d23fa0324c/tools/jamictrl/controller.py#L554-L579
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Taskmaster.py
python
Task.get_target
(self)
return self.node
Fetch the target being built or updated by this task.
Fetch the target being built or updated by this task.
[ "Fetch", "the", "target", "being", "built", "or", "updated", "by", "this", "task", "." ]
def get_target(self): """Fetch the target being built or updated by this task. """ return self.node
[ "def", "get_target", "(", "self", ")", ":", "return", "self", ".", "node" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Taskmaster.py#L210-L213
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/mailbox.py
python
MH.lock
(self)
Lock the mailbox.
Lock the mailbox.
[ "Lock", "the", "mailbox", "." ]
def lock(self): """Lock the mailbox.""" if not self._locked: self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+') _lock_file(self._file) self._locked = True
[ "def", "lock", "(", "self", ")", ":", "if", "not", "self", ".", "_locked", ":", "self", ".", "_file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "'.mh_sequences'", ")", ",", "'rb+'", ")", "_lock_file", "(", "self", ".", "_file", ")", "self", ".", "_locked", "=", "True" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L1092-L1097
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/graphy/graphy/bar_chart.py
python
BarChart.GetMinMaxValues
(self)
return min_value, max_value
Get the largest & smallest bar values as (min_value, max_value).
Get the largest & smallest bar values as (min_value, max_value).
[ "Get", "the", "largest", "&", "smallest", "bar", "values", "as", "(", "min_value", "max_value", ")", "." ]
def GetMinMaxValues(self): """Get the largest & smallest bar values as (min_value, max_value).""" if not self.stacked: return super(BarChart, self).GetMinMaxValues() if not self.data: return None, None # No data, nothing to do. num_bars = max(len(series.data) for series in self.data) positives = [0 for i in xrange(0, num_bars)] negatives = list(positives) for series in self.data: for i, point in enumerate(series.data): if point: if point > 0: positives[i] += point else: negatives[i] += point min_value = min(min(positives), min(negatives)) max_value = max(max(positives), max(negatives)) return min_value, max_value
[ "def", "GetMinMaxValues", "(", "self", ")", ":", "if", "not", "self", ".", "stacked", ":", "return", "super", "(", "BarChart", ",", "self", ")", ".", "GetMinMaxValues", "(", ")", "if", "not", "self", ".", "data", ":", "return", "None", ",", "None", "# No data, nothing to do.", "num_bars", "=", "max", "(", "len", "(", "series", ".", "data", ")", "for", "series", "in", "self", ".", "data", ")", "positives", "=", "[", "0", "for", "i", "in", "xrange", "(", "0", ",", "num_bars", ")", "]", "negatives", "=", "list", "(", "positives", ")", "for", "series", "in", "self", ".", "data", ":", "for", "i", ",", "point", "in", "enumerate", "(", "series", ".", "data", ")", ":", "if", "point", ":", "if", "point", ">", "0", ":", "positives", "[", "i", "]", "+=", "point", "else", ":", "negatives", "[", "i", "]", "+=", "point", "min_value", "=", "min", "(", "min", "(", "positives", ")", ",", "min", "(", "negatives", ")", ")", "max_value", "=", "max", "(", "max", "(", "positives", ")", ",", "max", "(", "negatives", ")", ")", "return", "min_value", ",", "max_value" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/graphy/graphy/bar_chart.py#L152-L171
manutdzou/KITTI_SSD
5b620c2f291d36a0fe14489214f22a992f173f44
python/caffe/pycaffe.py
python
_Net_forward_backward_all
(self, blobs=None, diffs=None, **kwargs)
return all_outs, all_diffs
Run net forward + backward in batches. Parameters ---------- blobs: list of blobs to extract as in forward() diffs: list of diffs to extract as in backward() kwargs: Keys are input (for forward) and output (for backward) blob names and values are ndarrays. Refer to forward() and backward(). Prefilled variants are called for lack of input or output blobs. Returns ------- all_blobs: {blob name: blob ndarray} dict. all_diffs: {blob name: diff ndarray} dict.
Run net forward + backward in batches.
[ "Run", "net", "forward", "+", "backward", "in", "batches", "." ]
def _Net_forward_backward_all(self, blobs=None, diffs=None, **kwargs): """ Run net forward + backward in batches. Parameters ---------- blobs: list of blobs to extract as in forward() diffs: list of diffs to extract as in backward() kwargs: Keys are input (for forward) and output (for backward) blob names and values are ndarrays. Refer to forward() and backward(). Prefilled variants are called for lack of input or output blobs. Returns ------- all_blobs: {blob name: blob ndarray} dict. all_diffs: {blob name: diff ndarray} dict. """ # Batch blobs and diffs. all_outs = {out: [] for out in set(self.outputs + (blobs or []))} all_diffs = {diff: [] for diff in set(self.inputs + (diffs or []))} forward_batches = self._batch({in_: kwargs[in_] for in_ in self.inputs if in_ in kwargs}) backward_batches = self._batch({out: kwargs[out] for out in self.outputs if out in kwargs}) # Collect outputs from batches (and heed lack of forward/backward batches). for fb, bb in izip_longest(forward_batches, backward_batches, fillvalue={}): batch_blobs = self.forward(blobs=blobs, **fb) batch_diffs = self.backward(diffs=diffs, **bb) for out, out_blobs in six.iteritems(batch_blobs): all_outs[out].extend(out_blobs.copy()) for diff, out_diffs in six.iteritems(batch_diffs): all_diffs[diff].extend(out_diffs.copy()) # Package in ndarray. for out, diff in zip(all_outs, all_diffs): all_outs[out] = np.asarray(all_outs[out]) all_diffs[diff] = np.asarray(all_diffs[diff]) # Discard padding at the end and package in ndarray. pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs))) if pad: for out, diff in zip(all_outs, all_diffs): all_outs[out] = all_outs[out][:-pad] all_diffs[diff] = all_diffs[diff][:-pad] return all_outs, all_diffs
[ "def", "_Net_forward_backward_all", "(", "self", ",", "blobs", "=", "None", ",", "diffs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Batch blobs and diffs.", "all_outs", "=", "{", "out", ":", "[", "]", "for", "out", "in", "set", "(", "self", ".", "outputs", "+", "(", "blobs", "or", "[", "]", ")", ")", "}", "all_diffs", "=", "{", "diff", ":", "[", "]", "for", "diff", "in", "set", "(", "self", ".", "inputs", "+", "(", "diffs", "or", "[", "]", ")", ")", "}", "forward_batches", "=", "self", ".", "_batch", "(", "{", "in_", ":", "kwargs", "[", "in_", "]", "for", "in_", "in", "self", ".", "inputs", "if", "in_", "in", "kwargs", "}", ")", "backward_batches", "=", "self", ".", "_batch", "(", "{", "out", ":", "kwargs", "[", "out", "]", "for", "out", "in", "self", ".", "outputs", "if", "out", "in", "kwargs", "}", ")", "# Collect outputs from batches (and heed lack of forward/backward batches).", "for", "fb", ",", "bb", "in", "izip_longest", "(", "forward_batches", ",", "backward_batches", ",", "fillvalue", "=", "{", "}", ")", ":", "batch_blobs", "=", "self", ".", "forward", "(", "blobs", "=", "blobs", ",", "*", "*", "fb", ")", "batch_diffs", "=", "self", ".", "backward", "(", "diffs", "=", "diffs", ",", "*", "*", "bb", ")", "for", "out", ",", "out_blobs", "in", "six", ".", "iteritems", "(", "batch_blobs", ")", ":", "all_outs", "[", "out", "]", ".", "extend", "(", "out_blobs", ".", "copy", "(", ")", ")", "for", "diff", ",", "out_diffs", "in", "six", ".", "iteritems", "(", "batch_diffs", ")", ":", "all_diffs", "[", "diff", "]", ".", "extend", "(", "out_diffs", ".", "copy", "(", ")", ")", "# Package in ndarray.", "for", "out", ",", "diff", "in", "zip", "(", "all_outs", ",", "all_diffs", ")", ":", "all_outs", "[", "out", "]", "=", "np", ".", "asarray", "(", "all_outs", "[", "out", "]", ")", "all_diffs", "[", "diff", "]", "=", "np", ".", "asarray", "(", "all_diffs", "[", "diff", "]", ")", "# Discard padding at the end and package in ndarray.", "pad", "=", "len", "(", "six", ".", "next", "(", "six", ".", "itervalues", "(", "all_outs", ")", ")", ")", "-", "len", "(", "six", ".", "next", "(", "six", ".", "itervalues", "(", "kwargs", ")", ")", ")", "if", "pad", ":", "for", "out", ",", "diff", "in", "zip", "(", "all_outs", ",", "all_diffs", ")", ":", "all_outs", "[", "out", "]", "=", "all_outs", "[", "out", "]", "[", ":", "-", "pad", "]", "all_diffs", "[", "diff", "]", "=", "all_diffs", "[", "diff", "]", "[", ":", "-", "pad", "]", "return", "all_outs", ",", "all_diffs" ]
https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/python/caffe/pycaffe.py#L206-L248
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/rostime.py
python
Time.from_sec
(float_secs)
return Time(secs, nsecs)
Create new Time instance from a float seconds representation (e.g. time.time()). @param float_secs: time value in time.time() format @type float_secs: float @return: Time instance for specified time @rtype: L{Time}
Create new Time instance from a float seconds representation (e.g. time.time()).
[ "Create", "new", "Time", "instance", "from", "a", "float", "seconds", "representation", "(", "e", ".", "g", ".", "time", ".", "time", "()", ")", "." ]
def from_sec(float_secs): """ Create new Time instance from a float seconds representation (e.g. time.time()). @param float_secs: time value in time.time() format @type float_secs: float @return: Time instance for specified time @rtype: L{Time} """ secs = int(float_secs) nsecs = int((float_secs - secs) * 1000000000) return Time(secs, nsecs)
[ "def", "from_sec", "(", "float_secs", ")", ":", "secs", "=", "int", "(", "float_secs", ")", "nsecs", "=", "int", "(", "(", "float_secs", "-", "secs", ")", "*", "1000000000", ")", "return", "Time", "(", "secs", ",", "nsecs", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/rostime.py#L172-L184
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinema/paraview/tpl/cinema_python/images/compositor.py
python
Compositor_SpecB.ambient
(self, rgb)
return np.dstack((rgb[:, :, 0], rgb[:, :, 0], rgb[:, :, 0]))
Returns the ambient contribution in an RGB luminance image.
Returns the ambient contribution in an RGB luminance image.
[ "Returns", "the", "ambient", "contribution", "in", "an", "RGB", "luminance", "image", "." ]
def ambient(self, rgb): """ Returns the ambient contribution in an RGB luminance image. """ return np.dstack((rgb[:, :, 0], rgb[:, :, 0], rgb[:, :, 0]))
[ "def", "ambient", "(", "self", ",", "rgb", ")", ":", "return", "np", ".", "dstack", "(", "(", "rgb", "[", ":", ",", ":", ",", "0", "]", ",", "rgb", "[", ":", ",", ":", ",", "0", "]", ",", "rgb", "[", ":", ",", ":", ",", "0", "]", ")", ")" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/images/compositor.py#L67-L69
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/error_fixer.py
python
ErrorFixer.FinishFile
(self)
Called when the current file has finished style checking. Used to go back and fix any errors in the file. It currently supports both js and html files. For js files it does a simple dump of all tokens, but in order to support html file, we need to merge the original file with the new token set back together. This works because the tokenized html file is the original html file with all non js lines kept but blanked out with one blank line token per line of html.
Called when the current file has finished style checking.
[ "Called", "when", "the", "current", "file", "has", "finished", "style", "checking", "." ]
def FinishFile(self): """Called when the current file has finished style checking. Used to go back and fix any errors in the file. It currently supports both js and html files. For js files it does a simple dump of all tokens, but in order to support html file, we need to merge the original file with the new token set back together. This works because the tokenized html file is the original html file with all non js lines kept but blanked out with one blank line token per line of html. """ if self._file_fix_count: # Get the original file content for html. if self._file_is_html: f = open(self._file_name, 'r') original_lines = f.readlines() f.close() f = self._external_file if not f: error_noun = 'error' if self._file_fix_count == 1 else 'errors' print 'Fixed %d %s in %s' % ( self._file_fix_count, error_noun, self._file_name) f = open(self._file_name, 'w') token = self._file_token # Finding the first not deleted token. while token.is_deleted: token = token.next # If something got inserted before first token (e.g. due to sorting) # then move to start. Bug 8398202. while token.previous: token = token.previous char_count = 0 line = '' while token: line += token.string char_count += len(token.string) if token.IsLastInLine(): # We distinguish if a blank line in html was from stripped original # file or newly added error fix by looking at the "org_line_number" # field on the token. It is only set in the tokenizer, so for all # error fixes, the value should be None. if (line or not self._file_is_html or token.orig_line_number is None): f.write(line) f.write('\n') else: f.write(original_lines[token.orig_line_number - 1]) line = '' if char_count > 80 and token.line_number in self._file_changed_lines: print 'WARNING: Line %d of %s is now longer than 80 characters.' % ( token.line_number, self._file_name) char_count = 0 token = token.next if not self._external_file: # Close the file if we created it f.close()
[ "def", "FinishFile", "(", "self", ")", ":", "if", "self", ".", "_file_fix_count", ":", "# Get the original file content for html.", "if", "self", ".", "_file_is_html", ":", "f", "=", "open", "(", "self", ".", "_file_name", ",", "'r'", ")", "original_lines", "=", "f", ".", "readlines", "(", ")", "f", ".", "close", "(", ")", "f", "=", "self", ".", "_external_file", "if", "not", "f", ":", "error_noun", "=", "'error'", "if", "self", ".", "_file_fix_count", "==", "1", "else", "'errors'", "print", "'Fixed %d %s in %s'", "%", "(", "self", ".", "_file_fix_count", ",", "error_noun", ",", "self", ".", "_file_name", ")", "f", "=", "open", "(", "self", ".", "_file_name", ",", "'w'", ")", "token", "=", "self", ".", "_file_token", "# Finding the first not deleted token.", "while", "token", ".", "is_deleted", ":", "token", "=", "token", ".", "next", "# If something got inserted before first token (e.g. due to sorting)", "# then move to start. Bug 8398202.", "while", "token", ".", "previous", ":", "token", "=", "token", ".", "previous", "char_count", "=", "0", "line", "=", "''", "while", "token", ":", "line", "+=", "token", ".", "string", "char_count", "+=", "len", "(", "token", ".", "string", ")", "if", "token", ".", "IsLastInLine", "(", ")", ":", "# We distinguish if a blank line in html was from stripped original", "# file or newly added error fix by looking at the \"org_line_number\"", "# field on the token. It is only set in the tokenizer, so for all", "# error fixes, the value should be None.", "if", "(", "line", "or", "not", "self", ".", "_file_is_html", "or", "token", ".", "orig_line_number", "is", "None", ")", ":", "f", ".", "write", "(", "line", ")", "f", ".", "write", "(", "'\\n'", ")", "else", ":", "f", ".", "write", "(", "original_lines", "[", "token", ".", "orig_line_number", "-", "1", "]", ")", "line", "=", "''", "if", "char_count", ">", "80", "and", "token", ".", "line_number", "in", "self", ".", "_file_changed_lines", ":", "print", "'WARNING: Line %d of %s is now longer than 80 characters.'", "%", "(", "token", ".", "line_number", ",", "self", ".", "_file_name", ")", "char_count", "=", "0", "token", "=", "token", ".", "next", "if", "not", "self", ".", "_external_file", ":", "# Close the file if we created it", "f", ".", "close", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/error_fixer.py#L560-L620
NervanaSystems/ngraph
f677a119765ca30636cf407009dabd118664951f
python/src/ngraph/ops.py
python
max_pool
( data: NodeInput, strides: List[int], pads_begin: List[int], pads_end: List[int], kernel_shape: TensorShape, rounding_type: str = "floor", auto_pad: Optional[str] = None, name: Optional[str] = None, )
return _get_node_factory().create( "MaxPool", [as_node(data)], { "strides": strides, "pads_begin": pads_begin, "pads_end": pads_end, "kernel": kernel_shape, "rounding_type": rounding_type.upper(), "auto_pad": auto_pad.upper(), }, )
Perform max pooling operation with given parameters on provided data. :param data: The node providing input data. :param strides: The distance (in pixels) to slide the filter on the feature map over the axes. :param pads_begin: The number of pixels to add at the beginning along each axis. :param pads_end: The number of pixels to add at the end along each axis. :param kernel_shape: The pooling operation kernel shape. :param rounding_type: Determines used rounding schema when computing output shape. Acceptable values are: ['floor', 'ceil'] :param auto_pad: Determines how the padding is calculated. Acceptable values: [None, 'same_upper', 'same_lower', 'valid'] :param name: The optional name for the created output node. :returns: The new node performing max pooling operation.
Perform max pooling operation with given parameters on provided data.
[ "Perform", "max", "pooling", "operation", "with", "given", "parameters", "on", "provided", "data", "." ]
def max_pool( data: NodeInput, strides: List[int], pads_begin: List[int], pads_end: List[int], kernel_shape: TensorShape, rounding_type: str = "floor", auto_pad: Optional[str] = None, name: Optional[str] = None, ) -> Node: """Perform max pooling operation with given parameters on provided data. :param data: The node providing input data. :param strides: The distance (in pixels) to slide the filter on the feature map over the axes. :param pads_begin: The number of pixels to add at the beginning along each axis. :param pads_end: The number of pixels to add at the end along each axis. :param kernel_shape: The pooling operation kernel shape. :param rounding_type: Determines used rounding schema when computing output shape. Acceptable values are: ['floor', 'ceil'] :param auto_pad: Determines how the padding is calculated. Acceptable values: [None, 'same_upper', 'same_lower', 'valid'] :param name: The optional name for the created output node. :returns: The new node performing max pooling operation. """ if auto_pad is None: auto_pad = "explicit" return _get_node_factory().create( "MaxPool", [as_node(data)], { "strides": strides, "pads_begin": pads_begin, "pads_end": pads_end, "kernel": kernel_shape, "rounding_type": rounding_type.upper(), "auto_pad": auto_pad.upper(), }, )
[ "def", "max_pool", "(", "data", ":", "NodeInput", ",", "strides", ":", "List", "[", "int", "]", ",", "pads_begin", ":", "List", "[", "int", "]", ",", "pads_end", ":", "List", "[", "int", "]", ",", "kernel_shape", ":", "TensorShape", ",", "rounding_type", ":", "str", "=", "\"floor\"", ",", "auto_pad", ":", "Optional", "[", "str", "]", "=", "None", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "Node", ":", "if", "auto_pad", "is", "None", ":", "auto_pad", "=", "\"explicit\"", "return", "_get_node_factory", "(", ")", ".", "create", "(", "\"MaxPool\"", ",", "[", "as_node", "(", "data", ")", "]", ",", "{", "\"strides\"", ":", "strides", ",", "\"pads_begin\"", ":", "pads_begin", ",", "\"pads_end\"", ":", "pads_end", ",", "\"kernel\"", ":", "kernel_shape", ",", "\"rounding_type\"", ":", "rounding_type", ".", "upper", "(", ")", ",", "\"auto_pad\"", ":", "auto_pad", ".", "upper", "(", ")", ",", "}", ",", ")" ]
https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/ops.py#L1887-L1926
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlTextReader.NodeType
(self)
return ret
Get the node type of the current node Reference: http://www.gnu.org/software/dotgnu/pnetlib-doc/System/Xml/Xm lNodeType.html
Get the node type of the current node Reference: http://www.gnu.org/software/dotgnu/pnetlib-doc/System/Xml/Xm lNodeType.html
[ "Get", "the", "node", "type", "of", "the", "current", "node", "Reference", ":", "http", ":", "//", "www", ".", "gnu", ".", "org", "/", "software", "/", "dotgnu", "/", "pnetlib", "-", "doc", "/", "System", "/", "Xml", "/", "Xm", "lNodeType", ".", "html" ]
def NodeType(self): """Get the node type of the current node Reference: http://www.gnu.org/software/dotgnu/pnetlib-doc/System/Xml/Xm lNodeType.html """ ret = libxml2mod.xmlTextReaderNodeType(self._o) return ret
[ "def", "NodeType", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlTextReaderNodeType", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L6000-L6005
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/metrics/python/ops/metric_ops.py
python
streaming_false_positives
(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None)
return metrics.false_positives( predictions=predictions, labels=labels, weights=weights, metrics_collections=metrics_collections, updates_collections=updates_collections, name=name)
Sum the weights of false positives. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. labels: The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: value_tensor: A `Tensor` representing the current value of the metric. update_op: An operation that accumulates the error from a batch of data. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple.
Sum the weights of false positives.
[ "Sum", "the", "weights", "of", "false", "positives", "." ]
def streaming_false_positives(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Sum the weights of false positives. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. labels: The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: value_tensor: A `Tensor` representing the current value of the metric. update_op: An operation that accumulates the error from a batch of data. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ return metrics.false_positives( predictions=predictions, labels=labels, weights=weights, metrics_collections=metrics_collections, updates_collections=updates_collections, name=name)
[ "def", "streaming_false_positives", "(", "predictions", ",", "labels", ",", "weights", "=", "None", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")", ":", "return", "metrics", ".", "false_positives", "(", "predictions", "=", "predictions", ",", "labels", "=", "labels", ",", "weights", "=", "weights", ",", "metrics_collections", "=", "metrics_collections", ",", "updates_collections", "=", "updates_collections", ",", "name", "=", "name", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/metrics/python/ops/metric_ops.py#L140-L180
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/gdb/mongo.py
python
get_session_kv_pairs
()
return list(absl_get_nodes(session_catalog["_sessions"]))
Return the SessionRuntimeInfoMap stored in the global SessionCatalog object. Returns a list of (LogicalSessionId, std::unique_ptr<SessionRuntimeInfo>) key-value pairs. For key-value pair 'session_kv', access the key with 'session_kv["first"]' and access the value with 'session_kv["second"]'.
Return the SessionRuntimeInfoMap stored in the global SessionCatalog object.
[ "Return", "the", "SessionRuntimeInfoMap", "stored", "in", "the", "global", "SessionCatalog", "object", "." ]
def get_session_kv_pairs(): """Return the SessionRuntimeInfoMap stored in the global SessionCatalog object. Returns a list of (LogicalSessionId, std::unique_ptr<SessionRuntimeInfo>) key-value pairs. For key-value pair 'session_kv', access the key with 'session_kv["first"]' and access the value with 'session_kv["second"]'. """ session_catalog = get_session_catalog() if session_catalog is None: return list() return list(absl_get_nodes(session_catalog["_sessions"]))
[ "def", "get_session_kv_pairs", "(", ")", ":", "session_catalog", "=", "get_session_catalog", "(", ")", "if", "session_catalog", "is", "None", ":", "return", "list", "(", ")", "return", "list", "(", "absl_get_nodes", "(", "session_catalog", "[", "\"_sessions\"", "]", ")", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/gdb/mongo.py#L97-L107
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
ConstBitStream._setbytepos
(self, bytepos)
Move to absolute byte-aligned position in stream.
Move to absolute byte-aligned position in stream.
[ "Move", "to", "absolute", "byte", "-", "aligned", "position", "in", "stream", "." ]
def _setbytepos(self, bytepos): """Move to absolute byte-aligned position in stream.""" self._setbitpos(bytepos * 8)
[ "def", "_setbytepos", "(", "self", ",", "bytepos", ")", ":", "self", ".", "_setbitpos", "(", "bytepos", "*", "8", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L3788-L3790
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/runtime.py
python
LoopContext.cycle
(self, *args)
return args[self.index0 % len(args)]
Cycles among the arguments with the current loop index.
Cycles among the arguments with the current loop index.
[ "Cycles", "among", "the", "arguments", "with", "the", "current", "loop", "index", "." ]
def cycle(self, *args): """Cycles among the arguments with the current loop index.""" if not args: raise TypeError('no items for cycling given') return args[self.index0 % len(args)]
[ "def", "cycle", "(", "self", ",", "*", "args", ")", ":", "if", "not", "args", ":", "raise", "TypeError", "(", "'no items for cycling given'", ")", "return", "args", "[", "self", ".", "index0", "%", "len", "(", "args", ")", "]" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/runtime.py#L302-L306
networkit/networkit
695b7a786a894a303fa8587597d5ef916e797729
networkit/algebraic.py
python
symmetricEigenvectors
(matrix, cutoff=-1, reverse=False)
return (orderedW, orderedV)
symmetricEigenvectors(matrix, cutoff=-1, reverse=False) Computes eigenvectors and -values of symmetric matrices. Parameters ---------- matrix : sparse matrix The matrix to compute the eigenvectors of cutoff : int, optional The maximum (or minimum) magnitude of the eigenvectors needed reverse : boolean, optional If set to true, the smaller eigenvalues will be computed before the larger ones Returns ------- ( [ float ], [ ndarray ] ) A tuple of ordered lists, the first containing the eigenvalues in descending (ascending) magnitude, the second one holding the corresponding eigenvectors.
symmetricEigenvectors(matrix, cutoff=-1, reverse=False)
[ "symmetricEigenvectors", "(", "matrix", "cutoff", "=", "-", "1", "reverse", "=", "False", ")" ]
def symmetricEigenvectors(matrix, cutoff=-1, reverse=False): """ symmetricEigenvectors(matrix, cutoff=-1, reverse=False) Computes eigenvectors and -values of symmetric matrices. Parameters ---------- matrix : sparse matrix The matrix to compute the eigenvectors of cutoff : int, optional The maximum (or minimum) magnitude of the eigenvectors needed reverse : boolean, optional If set to true, the smaller eigenvalues will be computed before the larger ones Returns ------- ( [ float ], [ ndarray ] ) A tuple of ordered lists, the first containing the eigenvalues in descending (ascending) magnitude, the second one holding the corresponding eigenvectors. """ if cutoff == -1: cutoff = matrix.shape[0] - 3 if reverse: mode = "SA" else: mode = "LA" w, v = scipy.sparse.linalg.eigsh(matrix, cutoff + 1, which=mode) orderlist = zip(w, range(0, len(w))) orderlist = sorted(orderlist) orderedW = column(orderlist, 0) orderedV = [v[:,i] for i in column(orderlist, 1)] return (orderedW, orderedV)
[ "def", "symmetricEigenvectors", "(", "matrix", ",", "cutoff", "=", "-", "1", ",", "reverse", "=", "False", ")", ":", "if", "cutoff", "==", "-", "1", ":", "cutoff", "=", "matrix", ".", "shape", "[", "0", "]", "-", "3", "if", "reverse", ":", "mode", "=", "\"SA\"", "else", ":", "mode", "=", "\"LA\"", "w", ",", "v", "=", "scipy", ".", "sparse", ".", "linalg", ".", "eigsh", "(", "matrix", ",", "cutoff", "+", "1", ",", "which", "=", "mode", ")", "orderlist", "=", "zip", "(", "w", ",", "range", "(", "0", ",", "len", "(", "w", ")", ")", ")", "orderlist", "=", "sorted", "(", "orderlist", ")", "orderedW", "=", "column", "(", "orderlist", ",", "0", ")", "orderedV", "=", "[", "v", "[", ":", ",", "i", "]", "for", "i", "in", "column", "(", "orderlist", ",", "1", ")", "]", "return", "(", "orderedW", ",", "orderedV", ")" ]
https://github.com/networkit/networkit/blob/695b7a786a894a303fa8587597d5ef916e797729/networkit/algebraic.py#L143-L181
PlatformLab/Arachne
e67391471007174dd4002dc2c160628e19c284e8
scripts/cpplint.py
python
CheckCStyleCast
(filename, clean_lines, linenum, cast_type, pattern, error)
return True
Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise.
Checks for a C-style cast by looking for the pattern.
[ "Checks", "for", "a", "C", "-", "style", "cast", "by", "looking", "for", "the", "pattern", "." ]
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ line = clean_lines.elided[linenum] match = Search(pattern, line) if not match: return False # Exclude lines with keywords that tend to look like casts context = line[0:match.start(1) - 1] if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): return False # Try expanding current context to see if we one level of # parentheses inside a macro. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 5), -1): context = clean_lines.elided[i] + context if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): return False # operator++(int) and operator--(int) if context.endswith(' operator++') or context.endswith(' operator--'): return False # A single unnamed argument for a function tends to look like old style cast. # If we see those, don't issue warnings for deprecated casts. remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', remainder): return False # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True
[ "def", "CheckCStyleCast", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "cast_type", ",", "pattern", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "not", "match", ":", "return", "False", "# Exclude lines with keywords that tend to look like casts", "context", "=", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", "if", "Match", "(", "r'.*\\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\\s*$'", ",", "context", ")", ":", "return", "False", "# Try expanding current context to see if we one level of", "# parentheses inside a macro.", "if", "linenum", ">", "0", ":", "for", "i", "in", "xrange", "(", "linenum", "-", "1", ",", "max", "(", "0", ",", "linenum", "-", "5", ")", ",", "-", "1", ")", ":", "context", "=", "clean_lines", ".", "elided", "[", "i", "]", "+", "context", "if", "Match", "(", "r'.*\\b[_A-Z][_A-Z0-9]*\\s*\\((?:\\([^()]*\\)|[^()])*$'", ",", "context", ")", ":", "return", "False", "# operator++(int) and operator--(int)", "if", "context", ".", "endswith", "(", "' operator++'", ")", "or", "context", ".", "endswith", "(", "' operator--'", ")", ":", "return", "False", "# A single unnamed argument for a function tends to look like old style cast.", "# If we see those, don't issue warnings for deprecated casts.", "remainder", "=", "line", "[", "match", ".", "end", "(", "0", ")", ":", "]", "if", "Match", "(", "r'^\\s*(?:;|const\\b|throw\\b|final\\b|override\\b|[=>{),]|->)'", ",", "remainder", ")", ":", "return", "False", "# At this point, all that should be left is actual casts.", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "'Using C-style cast. Use %s<%s>(...) instead'", "%", "(", "cast_type", ",", "match", ".", "group", "(", "1", ")", ")", ")", "return", "True" ]
https://github.com/PlatformLab/Arachne/blob/e67391471007174dd4002dc2c160628e19c284e8/scripts/cpplint.py#L4992-L5042
kevinlin311tw/caffe-cvprw15
45c2a1bf0368569c54e0be4edf8d34285cf79e70
scripts/cpp_lint.py
python
CheckCStyleCast
(filename, linenum, line, raw_line, cast_type, pattern, error)
return True
Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise.
Checks for a C-style cast by looking for the pattern.
[ "Checks", "for", "a", "C", "-", "style", "cast", "by", "looking", "for", "the", "pattern", "." ]
def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ match = Search(pattern, line) if not match: return False # Exclude lines with sizeof, since sizeof looks like a cast. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) if sizeof_match: return False # operator++(int) and operator--(int) if (line[0:match.start(1) - 1].endswith(' operator++') or line[0:match.start(1) - 1].endswith(' operator--')): return False # A single unnamed argument for a function tends to look like old # style cast. If we see those, don't issue warnings for deprecated # casts, instead issue warnings for unnamed arguments where # appropriate. # # These are things that we want warnings for, since the style guide # explicitly require all parameters to be named: # Function(int); # Function(int) { # ConstMember(int) const; # ConstMember(int) const { # ExceptionMember(int) throw (...); # ExceptionMember(int) throw (...) { # PureVirtual(int) = 0; # # These are functions of some sort, where the compiler would be fine # if they had named parameters, but people often omit those # identifiers to reduce clutter: # (FunctionPointer)(int); # (FunctionPointer)(int) = value; # Function((function_pointer_arg)(int)) # <TemplateArgument(int)>; # <(FunctionPointerTemplateArgument)(int)>; remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder): # Looks like an unnamed parameter. # Don't warn on any kind of template arguments. if Match(r'^\s*>', remainder): return False # Don't warn on assignments to function pointers, but keep warnings for # unnamed parameters to pure virtual functions. Note that this pattern # will also pass on assignments of "0" to function pointers, but the # preferred values for those would be "nullptr" or "NULL". matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) if matched_zero and matched_zero.group(1) != '0': return False # Don't warn on function pointer declarations. For this we need # to check what came before the "(type)" string. if Match(r'.*\)\s*$', line[0:match.start(0)]): return False # Don't warn if the parameter is named with block comments, e.g.: # Function(int /*unused_param*/); if '/*' in raw_line: return False # Passed all filters, issue warning here. error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True
[ "def", "CheckCStyleCast", "(", "filename", ",", "linenum", ",", "line", ",", "raw_line", ",", "cast_type", ",", "pattern", ",", "error", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "not", "match", ":", "return", "False", "# Exclude lines with sizeof, since sizeof looks like a cast.", "sizeof_match", "=", "Match", "(", "r'.*sizeof\\s*$'", ",", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", ")", "if", "sizeof_match", ":", "return", "False", "# operator++(int) and operator--(int)", "if", "(", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", ".", "endswith", "(", "' operator++'", ")", "or", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", ".", "endswith", "(", "' operator--'", ")", ")", ":", "return", "False", "# A single unnamed argument for a function tends to look like old", "# style cast. If we see those, don't issue warnings for deprecated", "# casts, instead issue warnings for unnamed arguments where", "# appropriate.", "#", "# These are things that we want warnings for, since the style guide", "# explicitly require all parameters to be named:", "# Function(int);", "# Function(int) {", "# ConstMember(int) const;", "# ConstMember(int) const {", "# ExceptionMember(int) throw (...);", "# ExceptionMember(int) throw (...) {", "# PureVirtual(int) = 0;", "#", "# These are functions of some sort, where the compiler would be fine", "# if they had named parameters, but people often omit those", "# identifiers to reduce clutter:", "# (FunctionPointer)(int);", "# (FunctionPointer)(int) = value;", "# Function((function_pointer_arg)(int))", "# <TemplateArgument(int)>;", "# <(FunctionPointerTemplateArgument)(int)>;", "remainder", "=", "line", "[", "match", ".", "end", "(", "0", ")", ":", "]", "if", "Match", "(", "r'^\\s*(?:;|const\\b|throw\\b|=|>|\\{|\\))'", ",", "remainder", ")", ":", "# Looks like an unnamed parameter.", "# Don't warn on any kind of template arguments.", "if", "Match", "(", "r'^\\s*>'", ",", "remainder", ")", ":", "return", "False", "# Don't warn on assignments to function pointers, but keep warnings for", "# unnamed parameters to pure virtual functions. Note that this pattern", "# will also pass on assignments of \"0\" to function pointers, but the", "# preferred values for those would be \"nullptr\" or \"NULL\".", "matched_zero", "=", "Match", "(", "r'^\\s=\\s*(\\S+)\\s*;'", ",", "remainder", ")", "if", "matched_zero", "and", "matched_zero", ".", "group", "(", "1", ")", "!=", "'0'", ":", "return", "False", "# Don't warn on function pointer declarations. For this we need", "# to check what came before the \"(type)\" string.", "if", "Match", "(", "r'.*\\)\\s*$'", ",", "line", "[", "0", ":", "match", ".", "start", "(", "0", ")", "]", ")", ":", "return", "False", "# Don't warn if the parameter is named with block comments, e.g.:", "# Function(int /*unused_param*/);", "if", "'/*'", "in", "raw_line", ":", "return", "False", "# Passed all filters, issue warning here.", "error", "(", "filename", ",", "linenum", ",", "'readability/function'", ",", "3", ",", "'All parameters should be named in a function'", ")", "return", "True", "# At this point, all that should be left is actual casts.", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "'Using C-style cast. Use %s<%s>(...) instead'", "%", "(", "cast_type", ",", "match", ".", "group", "(", "1", ")", ")", ")", "return", "True" ]
https://github.com/kevinlin311tw/caffe-cvprw15/blob/45c2a1bf0368569c54e0be4edf8d34285cf79e70/scripts/cpp_lint.py#L4247-L4338
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/formats/style.py
python
_get_level_lengths
(index, hidden_elements=None)
return non_zero_lengths
Given an index, find the level length for each element. Optional argument is a list of index positions which should not be visible. Result is a dictionary of (level, initial_position): span
Given an index, find the level length for each element.
[ "Given", "an", "index", "find", "the", "level", "length", "for", "each", "element", "." ]
def _get_level_lengths(index, hidden_elements=None): """ Given an index, find the level length for each element. Optional argument is a list of index positions which should not be visible. Result is a dictionary of (level, initial_position): span """ levels = index.format(sparsify=lib.no_default, adjoin=False, names=False) if hidden_elements is None: hidden_elements = [] lengths = {} if index.nlevels == 1: for i, value in enumerate(levels): if i not in hidden_elements: lengths[(0, i)] = 1 return lengths for i, lvl in enumerate(levels): for j, row in enumerate(lvl): if not get_option("display.multi_sparse"): lengths[(i, j)] = 1 elif (row is not lib.no_default) and (j not in hidden_elements): last_label = j lengths[(i, last_label)] = 1 elif row is not lib.no_default: # even if its hidden, keep track of it in case # length >1 and later elements are visible last_label = j lengths[(i, last_label)] = 0 elif j not in hidden_elements: lengths[(i, last_label)] += 1 non_zero_lengths = { element: length for element, length in lengths.items() if length >= 1 } return non_zero_lengths
[ "def", "_get_level_lengths", "(", "index", ",", "hidden_elements", "=", "None", ")", ":", "levels", "=", "index", ".", "format", "(", "sparsify", "=", "lib", ".", "no_default", ",", "adjoin", "=", "False", ",", "names", "=", "False", ")", "if", "hidden_elements", "is", "None", ":", "hidden_elements", "=", "[", "]", "lengths", "=", "{", "}", "if", "index", ".", "nlevels", "==", "1", ":", "for", "i", ",", "value", "in", "enumerate", "(", "levels", ")", ":", "if", "i", "not", "in", "hidden_elements", ":", "lengths", "[", "(", "0", ",", "i", ")", "]", "=", "1", "return", "lengths", "for", "i", ",", "lvl", "in", "enumerate", "(", "levels", ")", ":", "for", "j", ",", "row", "in", "enumerate", "(", "lvl", ")", ":", "if", "not", "get_option", "(", "\"display.multi_sparse\"", ")", ":", "lengths", "[", "(", "i", ",", "j", ")", "]", "=", "1", "elif", "(", "row", "is", "not", "lib", ".", "no_default", ")", "and", "(", "j", "not", "in", "hidden_elements", ")", ":", "last_label", "=", "j", "lengths", "[", "(", "i", ",", "last_label", ")", "]", "=", "1", "elif", "row", "is", "not", "lib", ".", "no_default", ":", "# even if its hidden, keep track of it in case", "# length >1 and later elements are visible", "last_label", "=", "j", "lengths", "[", "(", "i", ",", "last_label", ")", "]", "=", "0", "elif", "j", "not", "in", "hidden_elements", ":", "lengths", "[", "(", "i", ",", "last_label", ")", "]", "+=", "1", "non_zero_lengths", "=", "{", "element", ":", "length", "for", "element", ",", "length", "in", "lengths", ".", "items", "(", ")", "if", "length", ">=", "1", "}", "return", "non_zero_lengths" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/formats/style.py#L1470-L1510
bakwc/JamSpell
ab5ade201df3e52d99c3a1d38ec422cf4ded1795
evaluate/context_spell_prototype.py
python
edits1
(word)
return set(deletes + transposes + replaces + inserts)
All edits that are one edit away from `word`.
All edits that are one edit away from `word`.
[ "All", "edits", "that", "are", "one", "edit", "away", "from", "word", "." ]
def edits1(word): "All edits that are one edit away from `word`." letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1] replaces = [L + c + R[1:] for L, R in splits if R for c in letters] inserts = [L + c + R for L, R in splits for c in letters] return set(deletes + transposes + replaces + inserts)
[ "def", "edits1", "(", "word", ")", ":", "letters", "=", "'abcdefghijklmnopqrstuvwxyz'", "splits", "=", "[", "(", "word", "[", ":", "i", "]", ",", "word", "[", "i", ":", "]", ")", "for", "i", "in", "range", "(", "len", "(", "word", ")", "+", "1", ")", "]", "deletes", "=", "[", "L", "+", "R", "[", "1", ":", "]", "for", "L", ",", "R", "in", "splits", "if", "R", "]", "transposes", "=", "[", "L", "+", "R", "[", "1", "]", "+", "R", "[", "0", "]", "+", "R", "[", "2", ":", "]", "for", "L", ",", "R", "in", "splits", "if", "len", "(", "R", ")", ">", "1", "]", "replaces", "=", "[", "L", "+", "c", "+", "R", "[", "1", ":", "]", "for", "L", ",", "R", "in", "splits", "if", "R", "for", "c", "in", "letters", "]", "inserts", "=", "[", "L", "+", "c", "+", "R", "for", "L", ",", "R", "in", "splits", "for", "c", "in", "letters", "]", "return", "set", "(", "deletes", "+", "transposes", "+", "replaces", "+", "inserts", ")" ]
https://github.com/bakwc/JamSpell/blob/ab5ade201df3e52d99c3a1d38ec422cf4ded1795/evaluate/context_spell_prototype.py#L54-L62
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/mtv/mtv_api.py
python
Videos.makeURL
(self, URL)
Form a URL to search for videos return a URL
Form a URL to search for videos return a URL
[ "Form", "a", "URL", "to", "search", "for", "videos", "return", "a", "URL" ]
def makeURL(self, URL): '''Form a URL to search for videos return a URL ''' additions = dict(self.tree_customize[self.tree_key]['__default__']) # Set defaults # Add customizations if self.feed in list(self.tree_customize[self.tree_key].keys()): for element in list(self.tree_customize[self.tree_key][self.feed].keys()): additions[element] = self.tree_customize[self.tree_key][self.feed][element] # Make the search extension string that is added to the URL addition = '' for ky in list(additions.keys()): if ky.startswith('add_'): addition+='/%s' % additions[ky] else: addition+='&%s=%s' % (ky, additions[ky]) index = URL.find('%') if index == -1: return (URL+addition) else: return (URL+addition) % self.feed
[ "def", "makeURL", "(", "self", ",", "URL", ")", ":", "additions", "=", "dict", "(", "self", ".", "tree_customize", "[", "self", ".", "tree_key", "]", "[", "'__default__'", "]", ")", "# Set defaults", "# Add customizations", "if", "self", ".", "feed", "in", "list", "(", "self", ".", "tree_customize", "[", "self", ".", "tree_key", "]", ".", "keys", "(", ")", ")", ":", "for", "element", "in", "list", "(", "self", ".", "tree_customize", "[", "self", ".", "tree_key", "]", "[", "self", ".", "feed", "]", ".", "keys", "(", ")", ")", ":", "additions", "[", "element", "]", "=", "self", ".", "tree_customize", "[", "self", ".", "tree_key", "]", "[", "self", ".", "feed", "]", "[", "element", "]", "# Make the search extension string that is added to the URL", "addition", "=", "''", "for", "ky", "in", "list", "(", "additions", ".", "keys", "(", ")", ")", ":", "if", "ky", ".", "startswith", "(", "'add_'", ")", ":", "addition", "+=", "'/%s'", "%", "additions", "[", "ky", "]", "else", ":", "addition", "+=", "'&%s=%s'", "%", "(", "ky", ",", "additions", "[", "ky", "]", ")", "index", "=", "URL", ".", "find", "(", "'%'", ")", "if", "index", "==", "-", "1", ":", "return", "(", "URL", "+", "addition", ")", "else", ":", "return", "(", "URL", "+", "addition", ")", "%", "self", ".", "feed" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/mtv/mtv_api.py#L596-L618
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros/rosunit/src/rosunit/xmlrunner.py
python
XMLTestRunnerTest._try_test_run
(self, test_class, expected)
Run the test suite against the supplied test class and compare the XML result against the expected XML string. Fail if the expected string doesn't match the actual string. All time attribute in the expected string should have the value "0.000". All error and failure messages are reduced to "Foobar".
Run the test suite against the supplied test class and compare the XML result against the expected XML string. Fail if the expected string doesn't match the actual string. All time attribute in the expected string should have the value "0.000". All error and failure messages are reduced to "Foobar".
[ "Run", "the", "test", "suite", "against", "the", "supplied", "test", "class", "and", "compare", "the", "XML", "result", "against", "the", "expected", "XML", "string", ".", "Fail", "if", "the", "expected", "string", "doesn", "t", "match", "the", "actual", "string", ".", "All", "time", "attribute", "in", "the", "expected", "string", "should", "have", "the", "value", "0", ".", "000", ".", "All", "error", "and", "failure", "messages", "are", "reduced", "to", "Foobar", "." ]
def _try_test_run(self, test_class, expected): """Run the test suite against the supplied test class and compare the XML result against the expected XML string. Fail if the expected string doesn't match the actual string. All time attribute in the expected string should have the value "0.000". All error and failure messages are reduced to "Foobar". """ runner = XMLTestRunner(self._stream) runner.run(unittest.makeSuite(test_class)) got = self._stream.getvalue() # Replace all time="X.YYY" attributes by time="0.000" to enable a # simple string comparison. got = re.sub(r'time="\d+\.\d+"', 'time="0.000"', got) # Likewise, replace all failure and error messages by a simple "Foobar" # string. got = re.sub(r'(?s)<failure (.*?)>.*?</failure>', r'<failure \1>Foobar</failure>', got) got = re.sub(r'(?s)<error (.*?)>.*?</error>', r'<error \1>Foobar</error>', got) self.assertEqual(expected, got)
[ "def", "_try_test_run", "(", "self", ",", "test_class", ",", "expected", ")", ":", "runner", "=", "XMLTestRunner", "(", "self", ".", "_stream", ")", "runner", ".", "run", "(", "unittest", ".", "makeSuite", "(", "test_class", ")", ")", "got", "=", "self", ".", "_stream", ".", "getvalue", "(", ")", "# Replace all time=\"X.YYY\" attributes by time=\"0.000\" to enable a", "# simple string comparison.", "got", "=", "re", ".", "sub", "(", "r'time=\"\\d+\\.\\d+\"'", ",", "'time=\"0.000\"'", ",", "got", ")", "# Likewise, replace all failure and error messages by a simple \"Foobar\"", "# string.", "got", "=", "re", ".", "sub", "(", "r'(?s)<failure (.*?)>.*?</failure>'", ",", "r'<failure \\1>Foobar</failure>'", ",", "got", ")", "got", "=", "re", ".", "sub", "(", "r'(?s)<error (.*?)>.*?</error>'", ",", "r'<error \\1>Foobar</error>'", ",", "got", ")", "self", ".", "assertEqual", "(", "expected", ",", "got", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/rosunit/src/rosunit/xmlrunner.py#L270-L292
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/lib/sessions.py
python
PostgresqlSession.setup
(cls, **kwargs)
Set up the storage system for Postgres-based sessions. This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).
Set up the storage system for Postgres-based sessions. This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).
[ "Set", "up", "the", "storage", "system", "for", "Postgres", "-", "based", "sessions", ".", "This", "should", "only", "be", "called", "once", "per", "process", ";", "this", "will", "be", "done", "automatically", "when", "using", "sessions", ".", "init", "(", "as", "the", "built", "-", "in", "Tool", "does", ")", "." ]
def setup(cls, **kwargs): """Set up the storage system for Postgres-based sessions. This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does). """ for k, v in kwargs.items(): setattr(cls, k, v) self.db = self.get_db()
[ "def", "setup", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "cls", ",", "k", ",", "v", ")", "self", ".", "db", "=", "self", ".", "get_db", "(", ")" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/sessions.py#L530-L539
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py
python
pyparsing_common.stripHTMLTags
(s, l, tokens)
return pyparsing_common._html_stripper.transformString(tokens[0])
Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) Prints:: More info at the pyparsing wiki page
Parse action to remove HTML tags from web page HTML source
[ "Parse", "action", "to", "remove", "HTML", "tags", "from", "web", "page", "HTML", "source" ]
def stripHTMLTags(s, l, tokens): """Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) Prints:: More info at the pyparsing wiki page """ return pyparsing_common._html_stripper.transformString(tokens[0])
[ "def", "stripHTMLTags", "(", "s", ",", "l", ",", "tokens", ")", ":", "return", "pyparsing_common", ".", "_html_stripper", ".", "transformString", "(", "tokens", "[", "0", "]", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py#L6196-L6211
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/GettextCommon.py
python
_POFileBuilder._execute
(self, env, target, source, *args, **kw)
return SCons.Node.NodeList(result)
Execute builder's actions. Here we append to `target` the languages read from `$LINGUAS_FILE` and apply `SCons.Builder.BuilderBase._execute()` separatelly to each target. The arguments and return value are same as for `SCons.Builder.BuilderBase._execute()`.
Execute builder's actions. Here we append to `target` the languages read from `$LINGUAS_FILE` and apply `SCons.Builder.BuilderBase._execute()` separatelly to each target. The arguments and return value are same as for `SCons.Builder.BuilderBase._execute()`.
[ "Execute", "builder", "s", "actions", ".", "Here", "we", "append", "to", "target", "the", "languages", "read", "from", "$LINGUAS_FILE", "and", "apply", "SCons", ".", "Builder", ".", "BuilderBase", ".", "_execute", "()", "separatelly", "to", "each", "target", ".", "The", "arguments", "and", "return", "value", "are", "same", "as", "for", "SCons", ".", "Builder", ".", "BuilderBase", ".", "_execute", "()", "." ]
def _execute(self, env, target, source, *args, **kw): """ Execute builder's actions. Here we append to `target` the languages read from `$LINGUAS_FILE` and apply `SCons.Builder.BuilderBase._execute()` separatelly to each target. The arguments and return value are same as for `SCons.Builder.BuilderBase._execute()`. """ import SCons.Util import SCons.Node linguas_files = None if env.has_key('LINGUAS_FILE') and env['LINGUAS_FILE']: linguas_files = env['LINGUAS_FILE'] # This prevents endless recursion loop (we'll be invoked once for # each target appended here, we must not extend the list again). env['LINGUAS_FILE'] = None linguas = _read_linguas_from_files(env,linguas_files) if SCons.Util.is_List(target): target.extend(linguas) elif target is not None: target = [target] + linguas else: target = linguas if not target: # Let the SCons.BuilderBase to handle this patologic situation return BuilderBase._execute( self, env, target, source, *args, **kw) # The rest is ours if not SCons.Util.is_List(target): target = [ target ] result = [] for tgt in target: r = BuilderBase._execute( self, env, [tgt], source, *args, **kw) result.extend(r) if linguas_files is not None: env['LINGUAS_FILE'] = linguas_files return SCons.Node.NodeList(result)
[ "def", "_execute", "(", "self", ",", "env", ",", "target", ",", "source", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "import", "SCons", ".", "Util", "import", "SCons", ".", "Node", "linguas_files", "=", "None", "if", "env", ".", "has_key", "(", "'LINGUAS_FILE'", ")", "and", "env", "[", "'LINGUAS_FILE'", "]", ":", "linguas_files", "=", "env", "[", "'LINGUAS_FILE'", "]", "# This prevents endless recursion loop (we'll be invoked once for ", "# each target appended here, we must not extend the list again).", "env", "[", "'LINGUAS_FILE'", "]", "=", "None", "linguas", "=", "_read_linguas_from_files", "(", "env", ",", "linguas_files", ")", "if", "SCons", ".", "Util", ".", "is_List", "(", "target", ")", ":", "target", ".", "extend", "(", "linguas", ")", "elif", "target", "is", "not", "None", ":", "target", "=", "[", "target", "]", "+", "linguas", "else", ":", "target", "=", "linguas", "if", "not", "target", ":", "# Let the SCons.BuilderBase to handle this patologic situation", "return", "BuilderBase", ".", "_execute", "(", "self", ",", "env", ",", "target", ",", "source", ",", "*", "args", ",", "*", "*", "kw", ")", "# The rest is ours", "if", "not", "SCons", ".", "Util", ".", "is_List", "(", "target", ")", ":", "target", "=", "[", "target", "]", "result", "=", "[", "]", "for", "tgt", "in", "target", ":", "r", "=", "BuilderBase", ".", "_execute", "(", "self", ",", "env", ",", "[", "tgt", "]", ",", "source", ",", "*", "args", ",", "*", "*", "kw", ")", "result", ".", "extend", "(", "r", ")", "if", "linguas_files", "is", "not", "None", ":", "env", "[", "'LINGUAS_FILE'", "]", "=", "linguas_files", "return", "SCons", ".", "Node", ".", "NodeList", "(", "result", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/GettextCommon.py#L188-L223
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/tabart.py
python
FF2TabArt.DrawTabBackground
(self, dc, rect, focus, upperTabs)
Draws the tab background for the Firefox 2 style. This is more consistent with :class:`~lib.agw.flatnotebook.FlatNotebook` than before. :param `dc`: a :class:`DC` device context; :param Rect `rect`: rectangle the tab should be confined to; :param bool `focus`: whether the tab has focus or not; :param bool `upperTabs`: whether the style is ``AUI_NB_TOP`` or ``AUI_NB_BOTTOM``.
Draws the tab background for the Firefox 2 style. This is more consistent with :class:`~lib.agw.flatnotebook.FlatNotebook` than before.
[ "Draws", "the", "tab", "background", "for", "the", "Firefox", "2", "style", ".", "This", "is", "more", "consistent", "with", ":", "class", ":", "~lib", ".", "agw", ".", "flatnotebook", ".", "FlatNotebook", "than", "before", "." ]
def DrawTabBackground(self, dc, rect, focus, upperTabs): """ Draws the tab background for the Firefox 2 style. This is more consistent with :class:`~lib.agw.flatnotebook.FlatNotebook` than before. :param `dc`: a :class:`DC` device context; :param Rect `rect`: rectangle the tab should be confined to; :param bool `focus`: whether the tab has focus or not; :param bool `upperTabs`: whether the style is ``AUI_NB_TOP`` or ``AUI_NB_BOTTOM``. """ # Define the rounded rectangle base on the given rect # we need an array of 9 points for it regPts = [wx.Point() for indx in xrange(9)] if focus: if upperTabs: leftPt = wx.Point(rect.x, rect.y + (rect.height / 10)*8) rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 10)*8) else: leftPt = wx.Point(rect.x, rect.y + (rect.height / 10)*5) rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 10)*5) else: leftPt = wx.Point(rect.x, rect.y + (rect.height / 2)) rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 2)) # Define the top region top = wx.RectPP(rect.GetTopLeft(), rightPt) bottom = wx.RectPP(leftPt, rect.GetBottomRight()) topStartColour = wx.WHITE if not focus: topStartColour = LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 50) topEndColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE) bottomStartColour = topEndColour bottomEndColour = topEndColour # Incase we use bottom tabs, switch the colours if upperTabs: if focus: dc.GradientFillLinear(top, topStartColour, topEndColour, wx.SOUTH) dc.GradientFillLinear(bottom, bottomStartColour, bottomEndColour, wx.SOUTH) else: dc.GradientFillLinear(top, topEndColour , topStartColour, wx.SOUTH) dc.GradientFillLinear(bottom, bottomStartColour, bottomEndColour, wx.SOUTH) else: if focus: dc.GradientFillLinear(bottom, topEndColour, bottomEndColour, wx.SOUTH) dc.GradientFillLinear(top, topStartColour, topStartColour, wx.SOUTH) else: dc.GradientFillLinear(bottom, bottomStartColour, bottomEndColour, wx.SOUTH) dc.GradientFillLinear(top, topEndColour, topStartColour, wx.SOUTH) dc.SetBrush(wx.TRANSPARENT_BRUSH)
[ "def", "DrawTabBackground", "(", "self", ",", "dc", ",", "rect", ",", "focus", ",", "upperTabs", ")", ":", "# Define the rounded rectangle base on the given rect", "# we need an array of 9 points for it", "regPts", "=", "[", "wx", ".", "Point", "(", ")", "for", "indx", "in", "xrange", "(", "9", ")", "]", "if", "focus", ":", "if", "upperTabs", ":", "leftPt", "=", "wx", ".", "Point", "(", "rect", ".", "x", ",", "rect", ".", "y", "+", "(", "rect", ".", "height", "/", "10", ")", "*", "8", ")", "rightPt", "=", "wx", ".", "Point", "(", "rect", ".", "x", "+", "rect", ".", "width", "-", "2", ",", "rect", ".", "y", "+", "(", "rect", ".", "height", "/", "10", ")", "*", "8", ")", "else", ":", "leftPt", "=", "wx", ".", "Point", "(", "rect", ".", "x", ",", "rect", ".", "y", "+", "(", "rect", ".", "height", "/", "10", ")", "*", "5", ")", "rightPt", "=", "wx", ".", "Point", "(", "rect", ".", "x", "+", "rect", ".", "width", "-", "2", ",", "rect", ".", "y", "+", "(", "rect", ".", "height", "/", "10", ")", "*", "5", ")", "else", ":", "leftPt", "=", "wx", ".", "Point", "(", "rect", ".", "x", ",", "rect", ".", "y", "+", "(", "rect", ".", "height", "/", "2", ")", ")", "rightPt", "=", "wx", ".", "Point", "(", "rect", ".", "x", "+", "rect", ".", "width", "-", "2", ",", "rect", ".", "y", "+", "(", "rect", ".", "height", "/", "2", ")", ")", "# Define the top region", "top", "=", "wx", ".", "RectPP", "(", "rect", ".", "GetTopLeft", "(", ")", ",", "rightPt", ")", "bottom", "=", "wx", ".", "RectPP", "(", "leftPt", ",", "rect", ".", "GetBottomRight", "(", ")", ")", "topStartColour", "=", "wx", ".", "WHITE", "if", "not", "focus", ":", "topStartColour", "=", "LightColour", "(", "wx", ".", "SystemSettings_GetColour", "(", "wx", ".", "SYS_COLOUR_3DFACE", ")", ",", "50", ")", "topEndColour", "=", "wx", ".", "SystemSettings_GetColour", "(", "wx", ".", "SYS_COLOUR_3DFACE", ")", "bottomStartColour", "=", "topEndColour", "bottomEndColour", "=", "topEndColour", "# Incase we use bottom tabs, switch the colours", "if", "upperTabs", ":", "if", "focus", ":", "dc", ".", "GradientFillLinear", "(", "top", ",", "topStartColour", ",", "topEndColour", ",", "wx", ".", "SOUTH", ")", "dc", ".", "GradientFillLinear", "(", "bottom", ",", "bottomStartColour", ",", "bottomEndColour", ",", "wx", ".", "SOUTH", ")", "else", ":", "dc", ".", "GradientFillLinear", "(", "top", ",", "topEndColour", ",", "topStartColour", ",", "wx", ".", "SOUTH", ")", "dc", ".", "GradientFillLinear", "(", "bottom", ",", "bottomStartColour", ",", "bottomEndColour", ",", "wx", ".", "SOUTH", ")", "else", ":", "if", "focus", ":", "dc", ".", "GradientFillLinear", "(", "bottom", ",", "topEndColour", ",", "bottomEndColour", ",", "wx", ".", "SOUTH", ")", "dc", ".", "GradientFillLinear", "(", "top", ",", "topStartColour", ",", "topStartColour", ",", "wx", ".", "SOUTH", ")", "else", ":", "dc", ".", "GradientFillLinear", "(", "bottom", ",", "bottomStartColour", ",", "bottomEndColour", ",", "wx", ".", "SOUTH", ")", "dc", ".", "GradientFillLinear", "(", "top", ",", "topEndColour", ",", "topStartColour", ",", "wx", ".", "SOUTH", ")", "dc", ".", "SetBrush", "(", "wx", ".", "TRANSPARENT_BRUSH", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/tabart.py#L2092-L2148
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/database.py
python
Distribution.__eq__
(self, other)
return result
See if this distribution is the same as another. :param other: The distribution to compare with. To be equal to one another. distributions must have the same type, name, version and source_url. :return: True if it is the same, else False.
See if this distribution is the same as another. :param other: The distribution to compare with. To be equal to one another. distributions must have the same type, name, version and source_url. :return: True if it is the same, else False.
[ "See", "if", "this", "distribution", "is", "the", "same", "as", "another", ".", ":", "param", "other", ":", "The", "distribution", "to", "compare", "with", ".", "To", "be", "equal", "to", "one", "another", ".", "distributions", "must", "have", "the", "same", "type", "name", "version", "and", "source_url", ".", ":", "return", ":", "True", "if", "it", "is", "the", "same", "else", "False", "." ]
def __eq__(self, other): """ See if this distribution is the same as another. :param other: The distribution to compare with. To be equal to one another. distributions must have the same type, name, version and source_url. :return: True if it is the same, else False. """ if type(other) is not type(self): result = False else: result = (self.name == other.name and self.version == other.version and self.source_url == other.source_url) return result
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "not", "type", "(", "self", ")", ":", "result", "=", "False", "else", ":", "result", "=", "(", "self", ".", "name", "==", "other", ".", "name", "and", "self", ".", "version", "==", "other", ".", "version", "and", "self", ".", "source_url", "==", "other", ".", "source_url", ")", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/database.py#L451-L465
Smorodov/Multitarget-tracker
bee300e8bfd660c86cbeb6892c65a5b7195c9381
thirdparty/pybind11/tools/clang/cindex.py
python
Cursor.is_static_method
(self)
return conf.lib.clang_CXXMethod_isStatic(self)
Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'.
Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "member", "function", "or", "member", "function", "template", "that", "is", "declared", "static", "." ]
def is_static_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'. """ return conf.lib.clang_CXXMethod_isStatic(self)
[ "def", "is_static_method", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXMethod_isStatic", "(", "self", ")" ]
https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L1359-L1363
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/kokkos-kernels/scripts/analysis/batched/pd.py
python
kkt_parse_exespace_re
(ln)
return hits[0]
Parse an ExecSpace line.
Parse an ExecSpace line.
[ "Parse", "an", "ExecSpace", "line", "." ]
def kkt_parse_exespace_re(ln): 'Parse an ExecSpace line.' hits = re.findall('topology\[(?P<one>.*) x (?P<two>.*) x (?P<three>.*) \]', ln + ' ') if len(hits) == 0: return () return hits[0]
[ "def", "kkt_parse_exespace_re", "(", "ln", ")", ":", "hits", "=", "re", ".", "findall", "(", "'topology\\[(?P<one>.*) x (?P<two>.*) x (?P<three>.*) \\]'", ",", "ln", "+", "' '", ")", "if", "len", "(", "hits", ")", "==", "0", ":", "return", "(", ")", "return", "hits", "[", "0", "]" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/kokkos-kernels/scripts/analysis/batched/pd.py#L168-L173
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py
python
Scale.configure
(self, cnf=None, **kw)
Modify or query scale options. Setting a value for any of the "from", "from_" or "to" options generates a <<RangeChanged>> event.
Modify or query scale options.
[ "Modify", "or", "query", "scale", "options", "." ]
def configure(self, cnf=None, **kw): """Modify or query scale options. Setting a value for any of the "from", "from_" or "to" options generates a <<RangeChanged>> event.""" if cnf: kw.update(cnf) Widget.configure(self, **kw) if any(['from' in kw, 'from_' in kw, 'to' in kw]): self.event_generate('<<RangeChanged>>')
[ "def", "configure", "(", "self", ",", "cnf", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "cnf", ":", "kw", ".", "update", "(", "cnf", ")", "Widget", ".", "configure", "(", "self", ",", "*", "*", "kw", ")", "if", "any", "(", "[", "'from'", "in", "kw", ",", "'from_'", "in", "kw", ",", "'to'", "in", "kw", "]", ")", ":", "self", ".", "event_generate", "(", "'<<RangeChanged>>'", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py#L1077-L1086
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py
python
BaseMonitor.begin
(self, max_steps=None)
Called at the beginning of training. When called, the default graph is the one we are executing. Args: max_steps: `int`, the maximum global step this training will run until. Raises: ValueError: if we've already begun a run.
Called at the beginning of training.
[ "Called", "at", "the", "beginning", "of", "training", "." ]
def begin(self, max_steps=None): """Called at the beginning of training. When called, the default graph is the one we are executing. Args: max_steps: `int`, the maximum global step this training will run until. Raises: ValueError: if we've already begun a run. """ if self._begun: raise ValueError("begin called twice without end.") self._max_steps = max_steps self._begun = True
[ "def", "begin", "(", "self", ",", "max_steps", "=", "None", ")", ":", "if", "self", ".", "_begun", ":", "raise", "ValueError", "(", "\"begin called twice without end.\"", ")", "self", ".", "_max_steps", "=", "max_steps", "self", ".", "_begun", "=", "True" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py#L137-L151
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/core/mpi.py
python
AllowParallel
()
return -1, []
Whether this node was set for data parallelism. Returns ------- boolean
Whether this node was set for data parallelism.
[ "Whether", "this", "node", "was", "set", "for", "data", "parallelism", "." ]
def AllowParallel(): """Whether this node was set for data parallelism. Returns ------- boolean """ global _parallel_groups world_rank = Rank() for idx, g in enumerate(_parallel_groups): if world_rank in g: return idx, g return -1, []
[ "def", "AllowParallel", "(", ")", ":", "global", "_parallel_groups", "world_rank", "=", "Rank", "(", ")", "for", "idx", ",", "g", "in", "enumerate", "(", "_parallel_groups", ")", ":", "if", "world_rank", "in", "g", ":", "return", "idx", ",", "g", "return", "-", "1", ",", "[", "]" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/core/mpi.py#L194-L206
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/regression/_regression.py
python
create
(dataset, target, features=None, validation_set="auto", verbose=True)
return _sl.wrap_model_proxy(model_proxy)
Automatically create a suitable regression model based on the provided training data. To use specific options of a desired model, use the ``create`` function of the corresponding model. Parameters ---------- dataset : SFrame Dataset for training the model. target : str The name of the column in ``dataset`` that is the prediction target. This column must have a numeric type (int/float). features : list[string], optional Names of the columns containing features. 'None' (the default) indicates that all columns except the target variable should be used as features. The features are columns in the input SFrame that can be of the following types: - *Numeric*: values of numeric type integer or float. - *Categorical*: values of type string. - *Array*: list of numeric (integer or float) values. Each list element is treated as a separate feature in the model. - *Dictionary*: key-value pairs with numeric (integer or float) values Each key of a dictionary is treated as a separate feature and the value in the dictionary corresponds to the value of the feature. Dictionaries are ideal for representing sparse data. Columns of type *list* are not supported. Convert such feature columns to type array if all entries in the list are of numeric types. If the lists contain data of mixed types, separate them out into different columns. validation_set : SFrame, optional A dataset for monitoring the model's generalization performance. For each row of the progress table, the chosen metrics are computed for both the provided training dataset and the validation_set. The format of this SFrame must be the same as the training set. By default this argument is set to 'auto' and a validation set is automatically sampled and used for progress printing. If validation_set is set to None, then no additional metrics are computed. The default value is 'auto'. verbose : boolean, optional If True, print progress information during training. Returns ------- out : A trained regression model. See Also -------- turicreate.linear_regression.LinearRegression, turicreate.boosted_trees_regression.BoostedTreesRegression Examples -------- .. sourcecode:: python # Setup the data >>> import turicreate as tc >>> data = tc.SFrame('https://static.turi.com/datasets/regression/houses.csv') # Selects the best model based on your data. >>> model = tc.regression.create(data, target='price', ... features=['bath', 'bedroom', 'size']) # Make predictions and evaluate results. >>> predictions = model.predict(data) >>> results = model.evaluate(data) # Setup the data >>> import turicreate as tc >>> data = tc.SFrame('https://static.turi.com/datasets/regression/houses.csv') # Selects the best model based on your data. >>> model = tc.regression.create(data, target='price', ... features=['bath', 'bedroom', 'size']) # Make predictions and evaluate results. >>> predictions = model.predict(data) >>> results = model.evaluate(data)
Automatically create a suitable regression model based on the provided training data.
[ "Automatically", "create", "a", "suitable", "regression", "model", "based", "on", "the", "provided", "training", "data", "." ]
def create(dataset, target, features=None, validation_set="auto", verbose=True): """ Automatically create a suitable regression model based on the provided training data. To use specific options of a desired model, use the ``create`` function of the corresponding model. Parameters ---------- dataset : SFrame Dataset for training the model. target : str The name of the column in ``dataset`` that is the prediction target. This column must have a numeric type (int/float). features : list[string], optional Names of the columns containing features. 'None' (the default) indicates that all columns except the target variable should be used as features. The features are columns in the input SFrame that can be of the following types: - *Numeric*: values of numeric type integer or float. - *Categorical*: values of type string. - *Array*: list of numeric (integer or float) values. Each list element is treated as a separate feature in the model. - *Dictionary*: key-value pairs with numeric (integer or float) values Each key of a dictionary is treated as a separate feature and the value in the dictionary corresponds to the value of the feature. Dictionaries are ideal for representing sparse data. Columns of type *list* are not supported. Convert such feature columns to type array if all entries in the list are of numeric types. If the lists contain data of mixed types, separate them out into different columns. validation_set : SFrame, optional A dataset for monitoring the model's generalization performance. For each row of the progress table, the chosen metrics are computed for both the provided training dataset and the validation_set. The format of this SFrame must be the same as the training set. By default this argument is set to 'auto' and a validation set is automatically sampled and used for progress printing. If validation_set is set to None, then no additional metrics are computed. The default value is 'auto'. verbose : boolean, optional If True, print progress information during training. Returns ------- out : A trained regression model. See Also -------- turicreate.linear_regression.LinearRegression, turicreate.boosted_trees_regression.BoostedTreesRegression Examples -------- .. sourcecode:: python # Setup the data >>> import turicreate as tc >>> data = tc.SFrame('https://static.turi.com/datasets/regression/houses.csv') # Selects the best model based on your data. >>> model = tc.regression.create(data, target='price', ... features=['bath', 'bedroom', 'size']) # Make predictions and evaluate results. >>> predictions = model.predict(data) >>> results = model.evaluate(data) # Setup the data >>> import turicreate as tc >>> data = tc.SFrame('https://static.turi.com/datasets/regression/houses.csv') # Selects the best model based on your data. >>> model = tc.regression.create(data, target='price', ... features=['bath', 'bedroom', 'size']) # Make predictions and evaluate results. >>> predictions = model.predict(data) >>> results = model.evaluate(data) """ dataset, validation_set = _validate_data(dataset, target, features, validation_set) if validation_set is None: validation_set = _turicreate.SFrame() model_proxy = _turicreate.extensions.create_automatic_regression_model( dataset, target, validation_set, {} ) return _sl.wrap_model_proxy(model_proxy)
[ "def", "create", "(", "dataset", ",", "target", ",", "features", "=", "None", ",", "validation_set", "=", "\"auto\"", ",", "verbose", "=", "True", ")", ":", "dataset", ",", "validation_set", "=", "_validate_data", "(", "dataset", ",", "target", ",", "features", ",", "validation_set", ")", "if", "validation_set", "is", "None", ":", "validation_set", "=", "_turicreate", ".", "SFrame", "(", ")", "model_proxy", "=", "_turicreate", ".", "extensions", ".", "create_automatic_regression_model", "(", "dataset", ",", "target", ",", "validation_set", ",", "{", "}", ")", "return", "_sl", ".", "wrap_model_proxy", "(", "model_proxy", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/regression/_regression.py#L15-L116