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
apache/mesos
97d9a4063332aae3825d78de71611657e05cf5e2
support/cpplint.py
python
CheckSectionSpacing
(filename, clean_lines, class_info, linenum, error)
Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for additional blank line issues related to sections.
[ "Checks", "for", "additional", "blank", "line", "issues", "related", "to", "sections", "." ]
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1))
[ "def", "CheckSectionSpacing", "(", "filename", ",", "clean_lines", ",", "class_info", ",", "linenum", ",", "error", ")", ":", "# Skip checks if the class is small, where small means 25 lines or less.", "# 25 lines seems like a good cutoff since that's the usual height of", "# termina...
https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L3658-L3710
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/sys_util.py
python
set_windows_dll_path
()
Sets the dll load path so that things are resolved correctly.
Sets the dll load path so that things are resolved correctly.
[ "Sets", "the", "dll", "load", "path", "so", "that", "things", "are", "resolved", "correctly", "." ]
def set_windows_dll_path(): """ Sets the dll load path so that things are resolved correctly. """ lib_path = os.path.dirname(os.path.abspath(_pylambda_worker.__file__)) lib_path = os.path.abspath(os.path.join(lib_path, os.pardir)) def errcheck_bool(result, func, args): if not result: last_error = ctypes.get_last_error() if last_error != 0: raise ctypes.WinError(last_error) else: raise OSError return args # Also need to set the dll loading directory to the main # folder so windows attempts to load all DLLs from this # directory. import ctypes.wintypes as wintypes try: kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) kernel32.SetDllDirectoryW.errcheck = errcheck_bool kernel32.SetDllDirectoryW.argtypes = (wintypes.LPCWSTR,) kernel32.SetDllDirectoryW(lib_path) except Exception as e: logging.getLogger(__name__).warning( "Error setting DLL load orders: %s (things should still work)." % str(e))
[ "def", "set_windows_dll_path", "(", ")", ":", "lib_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "_pylambda_worker", ".", "__file__", ")", ")", "lib_path", "=", "os", ".", "path", ".", "abspath", "(", "os",...
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/sys_util.py#L78-L107
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py
python
AppendableFrameTable.get_object
(cls, obj, transposed: bool)
return obj
these are written transposed
these are written transposed
[ "these", "are", "written", "transposed" ]
def get_object(cls, obj, transposed: bool): """ these are written transposed """ if transposed: obj = obj.T return obj
[ "def", "get_object", "(", "cls", ",", "obj", ",", "transposed", ":", "bool", ")", ":", "if", "transposed", ":", "obj", "=", "obj", ".", "T", "return", "obj" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py#L4357-L4361
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py2/shell.py
python
frompath
(executable)
return None
Find executable in PATH
Find executable in PATH
[ "Find", "executable", "in", "PATH" ]
def frompath(executable): """ Find executable in PATH """ # Based on distutils.spawn.find_executable. path = _os.environ.get('PATH', '') paths = [ _os.path.expanduser(item) for item in path.split(_os.pathsep) ] ext = _os.path.splitext(executable)[1] exts = [''] if _sys.platform == 'win32' or _os.name == 'os2': eext = ['.exe', '.bat', '.py'] if ext not in eext: exts.extend(eext) for ext in exts: if not _os.path.isfile(executable + ext): for path in paths: fname = _os.path.join(path, executable + ext) if _os.path.isfile(fname): # the file exists, we have a shot at spawn working return fname else: return executable + ext return None
[ "def", "frompath", "(", "executable", ")", ":", "# Based on distutils.spawn.find_executable.", "path", "=", "_os", ".", "environ", ".", "get", "(", "'PATH'", ",", "''", ")", "paths", "=", "[", "_os", ".", "path", ".", "expanduser", "(", "item", ")", "for",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py2/shell.py#L453-L478
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
WorldModel.terrain
(self, *args)
return _robotsim.WorldModel_terrain(self, *args)
terrain(WorldModel self, int index) -> TerrainModel terrain(WorldModel self, char const * name) -> TerrainModel Returns a TerrainModel in the world by index or name.
terrain(WorldModel self, int index) -> TerrainModel terrain(WorldModel self, char const * name) -> TerrainModel
[ "terrain", "(", "WorldModel", "self", "int", "index", ")", "-", ">", "TerrainModel", "terrain", "(", "WorldModel", "self", "char", "const", "*", "name", ")", "-", ">", "TerrainModel" ]
def terrain(self, *args): """ terrain(WorldModel self, int index) -> TerrainModel terrain(WorldModel self, char const * name) -> TerrainModel Returns a TerrainModel in the world by index or name. """ return _robotsim.WorldModel_terrain(self, *args)
[ "def", "terrain", "(", "self", ",", "*", "args", ")", ":", "return", "_robotsim", ".", "WorldModel_terrain", "(", "self", ",", "*", "args", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L5910-L5920
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiManager.CalculateHintRect
(*args, **kwargs)
return _aui.AuiManager_CalculateHintRect(*args, **kwargs)
CalculateHintRect(self, Window paneWindow, Point pt, Point offset) -> Rect
CalculateHintRect(self, Window paneWindow, Point pt, Point offset) -> Rect
[ "CalculateHintRect", "(", "self", "Window", "paneWindow", "Point", "pt", "Point", "offset", ")", "-", ">", "Rect" ]
def CalculateHintRect(*args, **kwargs): """CalculateHintRect(self, Window paneWindow, Point pt, Point offset) -> Rect""" return _aui.AuiManager_CalculateHintRect(*args, **kwargs)
[ "def", "CalculateHintRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiManager_CalculateHintRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L715-L717
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/xsltfunctions/tedtalksXSL_api.py
python
OutStreamEncoder.__getattr__
(self, attr)
return getattr(self.out, attr)
Delegate everything but write to the stream
Delegate everything but write to the stream
[ "Delegate", "everything", "but", "write", "to", "the", "stream" ]
def __getattr__(self, attr): """Delegate everything but write to the stream""" return getattr(self.out, attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "return", "getattr", "(", "self", ".", "out", ",", "attr", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/xsltfunctions/tedtalksXSL_api.py#L59-L61
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/xapian/xapian-maintainer-tools/buildbot/xapian_factories.py
python
gen_git_updated_valgrind_factory
(repourl, configure_opts=[])
return f
Factory for doing build from git master, without cleaning first, and using valgrind to check. This one is much more expensive, so should be run with a higher stable time.
Factory for doing build from git master, without cleaning first, and using valgrind to check. This one is much more expensive, so should be run with a higher stable time.
[ "Factory", "for", "doing", "build", "from", "git", "master", "without", "cleaning", "first", "and", "using", "valgrind", "to", "check", ".", "This", "one", "is", "much", "more", "expensive", "so", "should", "be", "run", "with", "a", "higher", "stable", "ti...
def gen_git_updated_valgrind_factory(repourl, configure_opts=[]): """ Factory for doing build from git master, without cleaning first, and using valgrind to check. This one is much more expensive, so should be run with a higher stable time. """ f = factory.BuildFactory() f.addStep(source.Git(repourl=repourl, mode="update")) f.addStep(Bootstrap()) f.addStep(shell.Configure(command = ["sh", "configure", "CXXFLAGS=-O0 -g"] + configure_opts)) f.addStep(shell.Compile()) f.addStep(shell.Test(name="check", command = ["make", "check", "XAPIAN_TESTSUITE_OUTPUT=plain"], workdir='build/xapian-core')) return f
[ "def", "gen_git_updated_valgrind_factory", "(", "repourl", ",", "configure_opts", "=", "[", "]", ")", ":", "f", "=", "factory", ".", "BuildFactory", "(", ")", "f", ".", "addStep", "(", "source", ".", "Git", "(", "repourl", "=", "repourl", ",", "mode", "=...
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/xapian/xapian-maintainer-tools/buildbot/xapian_factories.py#L175-L189
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/qt4.py
python
qxx.runnable_status
(self)
Compute the task signature to make sure the scanner was executed. Create the moc tasks by using :py:meth:`waflib.Tools.qt4.qxx.add_moc_tasks` (if necessary), then postpone the task execution (there is no need to recompute the task signature).
Compute the task signature to make sure the scanner was executed. Create the moc tasks by using :py:meth:`waflib.Tools.qt4.qxx.add_moc_tasks` (if necessary), then postpone the task execution (there is no need to recompute the task signature).
[ "Compute", "the", "task", "signature", "to", "make", "sure", "the", "scanner", "was", "executed", ".", "Create", "the", "moc", "tasks", "by", "using", ":", "py", ":", "meth", ":", "waflib", ".", "Tools", ".", "qt4", ".", "qxx", ".", "add_moc_tasks", "(...
def runnable_status(self): """ Compute the task signature to make sure the scanner was executed. Create the moc tasks by using :py:meth:`waflib.Tools.qt4.qxx.add_moc_tasks` (if necessary), then postpone the task execution (there is no need to recompute the task signature). """ if self.moc_done: return Task.Task.runnable_status(self) else: for t in self.run_after: if not t.hasrun: return Task.ASK_LATER self.add_moc_tasks() return Task.Task.runnable_status(self)
[ "def", "runnable_status", "(", "self", ")", ":", "if", "self", ".", "moc_done", ":", "return", "Task", ".", "Task", ".", "runnable_status", "(", "self", ")", "else", ":", "for", "t", "in", "self", ".", "run_after", ":", "if", "not", "t", ".", "hasrun...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/qt4.py#L117-L130
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBCommunication.Connect
(self, *args)
return _lldb.SBCommunication_Connect(self, *args)
Connect(self, str url) -> ConnectionStatus
Connect(self, str url) -> ConnectionStatus
[ "Connect", "(", "self", "str", "url", ")", "-", ">", "ConnectionStatus" ]
def Connect(self, *args): """Connect(self, str url) -> ConnectionStatus""" return _lldb.SBCommunication_Connect(self, *args)
[ "def", "Connect", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBCommunication_Connect", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L2443-L2445
blackberry/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
tools/build/v2/build/build_request.py
python
from_command_line
(command_line)
return [targets, properties]
Takes the command line tokens (such as taken from ARGV rule) and constructs build request from it. Returns a list of two lists. First is the set of targets specified in the command line, and second is the set of requested build properties.
Takes the command line tokens (such as taken from ARGV rule) and constructs build request from it. Returns a list of two lists. First is the set of targets specified in the command line, and second is the set of requested build properties.
[ "Takes", "the", "command", "line", "tokens", "(", "such", "as", "taken", "from", "ARGV", "rule", ")", "and", "constructs", "build", "request", "from", "it", ".", "Returns", "a", "list", "of", "two", "lists", ".", "First", "is", "the", "set", "of", "tar...
def from_command_line(command_line): """Takes the command line tokens (such as taken from ARGV rule) and constructs build request from it. Returns a list of two lists. First is the set of targets specified in the command line, and second is the set of requested build properties.""" targets = [] properties = [] for e in command_line: if e[0] != "-": # Build request spec either has "=" in it, or completely # consists of implicit feature values. if e.find("=") != -1 or looks_like_implicit_value(e.split("/")[0]): properties += convert_command_line_element(e) else: targets.append(e) return [targets, properties]
[ "def", "from_command_line", "(", "command_line", ")", ":", "targets", "=", "[", "]", "properties", "=", "[", "]", "for", "e", "in", "command_line", ":", "if", "e", "[", "0", "]", "!=", "\"-\"", ":", "# Build request spec either has \"=\" in it, or completely", ...
https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/build_request.py#L102-L120
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/range.py
python
RangeIndex._get_data_as_items
(self)
return [("start", rng.start), ("stop", rng.stop), ("step", rng.step)]
return a list of tuples of start, stop, step
return a list of tuples of start, stop, step
[ "return", "a", "list", "of", "tuples", "of", "start", "stop", "step" ]
def _get_data_as_items(self): """return a list of tuples of start, stop, step""" rng = self._range return [("start", rng.start), ("stop", rng.stop), ("step", rng.step)]
[ "def", "_get_data_as_items", "(", "self", ")", ":", "rng", "=", "self", ".", "_range", "return", "[", "(", "\"start\"", ",", "rng", ".", "start", ")", ",", "(", "\"stop\"", ",", "rng", ".", "stop", ")", ",", "(", "\"step\"", ",", "rng", ".", "step"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/range.py#L199-L202
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/client/timeline.py
python
_ChromeTraceFormatter._create_event
(self, ph, category, name, pid, tid, timestamp)
return event
Creates a new Chrome Trace event. For details of the file format, see: https://github.com/catapult-project/catapult/blob/master/tracing/README.md Args: ph: The type of event - usually a single character. category: The event category as a string. name: The event name as a string. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. timestamp: The timestamp of this event as a long integer. Returns: A JSON compatible event object.
Creates a new Chrome Trace event.
[ "Creates", "a", "new", "Chrome", "Trace", "event", "." ]
def _create_event(self, ph, category, name, pid, tid, timestamp): """Creates a new Chrome Trace event. For details of the file format, see: https://github.com/catapult-project/catapult/blob/master/tracing/README.md Args: ph: The type of event - usually a single character. category: The event category as a string. name: The event name as a string. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. timestamp: The timestamp of this event as a long integer. Returns: A JSON compatible event object. """ event = {} event['ph'] = ph event['cat'] = category event['name'] = name event['pid'] = pid event['tid'] = tid event['ts'] = timestamp return event
[ "def", "_create_event", "(", "self", ",", "ph", ",", "category", ",", "name", ",", "pid", ",", "tid", ",", "timestamp", ")", ":", "event", "=", "{", "}", "event", "[", "'ph'", "]", "=", "ph", "event", "[", "'cat'", "]", "=", "category", "event", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/client/timeline.py#L65-L89
nodejs/nan
8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62
cpplint.py
python
CheckCheck
(filename, clean_lines, linenum, error)
Checks the use of CHECK and EXPECT 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. error: The function to call with any errors found.
Checks the use of CHECK and EXPECT macros.
[ "Checks", "the", "use", "of", "CHECK", "and", "EXPECT", "macros", "." ]
def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT 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. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested lines = clean_lines.elided (check_macro, start_pos) = FindCheckMacro(lines[linenum]) if not check_macro: return # Find end of the boolean expression by matching parentheses (last_line, end_line, end_pos) = CloseExpression( clean_lines, linenum, start_pos) if end_pos < 0: return # If the check macro is followed by something other than a # semicolon, assume users will log their own custom error messages # and don't suggest any replacements. if not Match(r'\s*;', last_line[end_pos:]): return if linenum == end_line: expression = lines[linenum][start_pos + 1:end_pos - 1] else: expression = lines[linenum][start_pos + 1:] for i in xrange(linenum + 1, end_line): expression += lines[i] expression += last_line[0:end_pos - 1] # Parse expression so that we can take parentheses into account. # This avoids false positives for inputs like "CHECK((a < 4) == b)", # which is not replaceable by CHECK_LE. lhs = '' rhs = '' operator = None while expression: matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' r'==|!=|>=|>|<=|<|\()(.*)$', expression) if matched: token = matched.group(1) if token == '(': # Parenthesized operand expression = matched.group(2) (end, _) = FindEndOfExpressionInLine(expression, 0, ['(']) if end < 0: return # Unmatched parenthesis lhs += '(' + expression[0:end] expression = expression[end:] elif token in ('&&', '||'): # Logical and/or operators. This means the expression # contains more than one term, for example: # CHECK(42 < a && a < b); # # These are not replaceable with CHECK_LE, so bail out early. return elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): # Non-relational operator lhs += token expression = matched.group(2) else: # Relational operator operator = token rhs = matched.group(2) break else: # Unparenthesized operand. Instead of appending to lhs one character # at a time, we do another regular expression match to consume several # characters at once if possible. Trivial benchmark shows that this # is more efficient when the operands are longer than a single # character, which is generally the case. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) if not matched: matched = Match(r'^(\s*\S)(.*)$', expression) if not matched: break lhs += matched.group(1) expression = matched.group(2) # Only apply checks if we got all parts of the boolean expression if not (lhs and operator and rhs): return # Check that rhs do not contain logical operators. We already know # that lhs is fine since the loop above parses out && and ||. if rhs.find('&&') > -1 or rhs.find('||') > -1: return # At least one of the operands must be a constant literal. This is # to avoid suggesting replacements for unprintable things like # CHECK(variable != iterator) # # The following pattern matches decimal, hex integers, strings, and # characters (in that order). lhs = lhs.strip() rhs = rhs.strip() match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' if Match(match_constant, lhs) or Match(match_constant, rhs): # Note: since we know both lhs and rhs, we can provide a more # descriptive error message like: # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) # Instead of: # Consider using CHECK_EQ instead of CHECK(a == b) # # We are still keeping the less descriptive message because if lhs # or rhs gets long, the error message might become unreadable. error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[check_macro][operator], check_macro, operator))
[ "def", "CheckCheck", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Decide the set of replacement macros that should be suggested", "lines", "=", "clean_lines", ".", "elided", "(", "check_macro", ",", "start_pos", ")", "=", "FindCheckM...
https://github.com/nodejs/nan/blob/8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62/cpplint.py#L4365-L4480
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/parse/standard_method.py
python
while_cond
(x)
return x
For while condition, if the condition is a tensor, the loop will not be unrolled
For while condition, if the condition is a tensor, the loop will not be unrolled
[ "For", "while", "condition", "if", "the", "condition", "is", "a", "tensor", "the", "loop", "will", "not", "be", "unrolled" ]
def while_cond(x): """For while condition, if the condition is a tensor, the loop will not be unrolled""" if F.issubclass_(F.typeof(x), F.typeof(mstype.tensor)): is_cond = check_is_tensor_bool_cond(F.shape(x)) if is_cond: return F.cast(x, mstype.bool_) return x
[ "def", "while_cond", "(", "x", ")", ":", "if", "F", ".", "issubclass_", "(", "F", ".", "typeof", "(", "x", ")", ",", "F", ".", "typeof", "(", "mstype", ".", "tensor", ")", ")", ":", "is_cond", "=", "check_is_tensor_bool_cond", "(", "F", ".", "shape...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parse/standard_method.py#L1516-L1522
Lavender105/DFF
152397cec4a3dac2aa86e92a65cc27e6c8016ab9
pytorch-encoding/encoding/utils/metrics.py
python
batch_intersection_union
(output, target, nclass)
return area_inter, area_union
Batch Intersection of Union Args: predict: input 4D tensor target: label 3D tensor nclass: number of categories (int)
Batch Intersection of Union Args: predict: input 4D tensor target: label 3D tensor nclass: number of categories (int)
[ "Batch", "Intersection", "of", "Union", "Args", ":", "predict", ":", "input", "4D", "tensor", "target", ":", "label", "3D", "tensor", "nclass", ":", "number", "of", "categories", "(", "int", ")" ]
def batch_intersection_union(output, target, nclass): """Batch Intersection of Union Args: predict: input 4D tensor target: label 3D tensor nclass: number of categories (int) """ _, predict = torch.max(output, 1) mini = 1 maxi = nclass nbins = nclass predict = predict.cpu().numpy().astype('int64') + 1 target = target.cpu().numpy().astype('int64') + 1 predict = predict * (target > 0).astype(predict.dtype) intersection = predict * (predict == target) # areas of intersection and union area_inter, _ = np.histogram(intersection, bins=nbins, range=(mini, maxi)) area_pred, _ = np.histogram(predict, bins=nbins, range=(mini, maxi)) area_lab, _ = np.histogram(target, bins=nbins, range=(mini, maxi)) area_union = area_pred + area_lab - area_inter assert (area_inter <= area_union).all(), \ "Intersection area should be smaller than Union area" return area_inter, area_union
[ "def", "batch_intersection_union", "(", "output", ",", "target", ",", "nclass", ")", ":", "_", ",", "predict", "=", "torch", ".", "max", "(", "output", ",", "1", ")", "mini", "=", "1", "maxi", "=", "nclass", "nbins", "=", "nclass", "predict", "=", "p...
https://github.com/Lavender105/DFF/blob/152397cec4a3dac2aa86e92a65cc27e6c8016ab9/pytorch-encoding/encoding/utils/metrics.py#L128-L151
kevinlin311tw/Caffe-DeepBinaryCode
9eaa7662be47d49f475ecbeea2bd51be105270d2
scripts/cpp_lint.py
python
Error
(filename, linenum, category, confidence, message)
Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message.
Logs the fact we've found a lint error.
[ "Logs", "the", "fact", "we", "ve", "found", "a", "lint", "error", "." ]
def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) else: sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence))
[ "def", "Error", "(", "filename", ",", "linenum", ",", "category", ",", "confidence", ",", "message", ")", ":", "if", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "_cpplint_state", ".", "IncrementErrorCount", "(", "category...
https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/scripts/cpp_lint.py#L988-L1020
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/vis/editors.py
python
RigidTransformEditor.disable_rotation
(self)
Turns off editing of rotation.
Turns off editing of rotation.
[ "Turns", "off", "editing", "of", "rotation", "." ]
def disable_rotation(self): """Turns off editing of rotation.""" self.rotationEnabled = False self.xformposer.enableRotation(False)
[ "def", "disable_rotation", "(", "self", ")", ":", "self", ".", "rotationEnabled", "=", "False", "self", ".", "xformposer", ".", "enableRotation", "(", "False", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/editors.py#L1009-L1012
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/benchmark.py
python
Benchmark.__init__
(self, max_failures=None)
Creates a new Benchmark. Args: max_failures: The number of story run's failures before bailing from executing subsequent page runs. If None, we never bail.
Creates a new Benchmark.
[ "Creates", "a", "new", "Benchmark", "." ]
def __init__(self, max_failures=None): """Creates a new Benchmark. Args: max_failures: The number of story run's failures before bailing from executing subsequent page runs. If None, we never bail. """ self._max_failures = max_failures self._has_original_tbm_options = ( self.CreateTimelineBasedMeasurementOptions.__func__ == Benchmark.CreateTimelineBasedMeasurementOptions.__func__) has_original_create_page_test = ( self.CreatePageTest.__func__ == Benchmark.CreatePageTest.__func__) assert self._has_original_tbm_options or has_original_create_page_test, ( 'Cannot override both CreatePageTest and ' 'CreateTimelineBasedMeasurementOptions.')
[ "def", "__init__", "(", "self", ",", "max_failures", "=", "None", ")", ":", "self", ".", "_max_failures", "=", "max_failures", "self", ".", "_has_original_tbm_options", "=", "(", "self", ".", "CreateTimelineBasedMeasurementOptions", ".", "__func__", "==", "Benchma...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/benchmark.py#L62-L77
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py
python
MH.remove
(self, key)
Remove the keyed message; raise KeyError if it doesn't exist.
Remove the keyed message; raise KeyError if it doesn't exist.
[ "Remove", "the", "keyed", "message", ";", "raise", "KeyError", "if", "it", "doesn", "t", "exist", "." ]
def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise else: f.close() os.remove(path)
[ "def", "remove", "(", "self", ",", "key", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "str", "(", "key", ")", ")", "try", ":", "f", "=", "open", "(", "path", ",", "'rb+'", ")", "except", "IOError", "...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py#L956-L968
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
util/run-clang-tidy.py
python
check_clang_apply_replacements_binary
(args)
Checks if invoking supplied clang-apply-replacements binary works.
Checks if invoking supplied clang-apply-replacements binary works.
[ "Checks", "if", "invoking", "supplied", "clang", "-", "apply", "-", "replacements", "binary", "works", "." ]
def check_clang_apply_replacements_binary(args): """Checks if invoking supplied clang-apply-replacements binary works.""" try: subprocess.check_call([args.clang_apply_replacements_binary, "--version"]) except: print( "Unable to run clang-apply-replacements. Is clang-apply-replacements " "binary correctly specified?", file=sys.stderr, ) traceback.print_exc() sys.exit(1)
[ "def", "check_clang_apply_replacements_binary", "(", "args", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "[", "args", ".", "clang_apply_replacements_binary", ",", "\"--version\"", "]", ")", "except", ":", "print", "(", "\"Unable to run clang-apply-repl...
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/util/run-clang-tidy.py#L149-L160
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/sentence-screen-fitting.py
python
Solution.wordsTyping
(self, sentence, rows, cols)
return words / len(sentence)
:type sentence: List[str] :type rows: int :type cols: int :rtype: int
:type sentence: List[str] :type rows: int :type cols: int :rtype: int
[ ":", "type", "sentence", ":", "List", "[", "str", "]", ":", "type", "rows", ":", "int", ":", "type", "cols", ":", "int", ":", "rtype", ":", "int" ]
def wordsTyping(self, sentence, rows, cols): """ :type sentence: List[str] :type rows: int :type cols: int :rtype: int """ def words_fit(sentence, start, cols): if len(sentence[start]) > cols: return 0 s, count = len(sentence[start]), 1 i = (start + 1) % len(sentence) while s + 1 + len(sentence[i]) <= cols: s += 1 + len(sentence[i]) count += 1 i = (i + 1) % len(sentence) return count wc = [0] * len(sentence) for i in xrange(len(sentence)): wc[i] = words_fit(sentence, i, cols) words, start = 0, 0 for i in xrange(rows): words += wc[start] start = (start + wc[start]) % len(sentence) return words / len(sentence)
[ "def", "wordsTyping", "(", "self", ",", "sentence", ",", "rows", ",", "cols", ")", ":", "def", "words_fit", "(", "sentence", ",", "start", ",", "cols", ")", ":", "if", "len", "(", "sentence", "[", "start", "]", ")", ">", "cols", ":", "return", "0",...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/sentence-screen-fitting.py#L5-L32
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/keypair.py
python
KeyPair.delete
(self, dry_run=False)
return self.connection.delete_key_pair(self.name, dry_run=dry_run)
Delete the KeyPair. :rtype: bool :return: True if successful, otherwise False.
Delete the KeyPair.
[ "Delete", "the", "KeyPair", "." ]
def delete(self, dry_run=False): """ Delete the KeyPair. :rtype: bool :return: True if successful, otherwise False. """ return self.connection.delete_key_pair(self.name, dry_run=dry_run)
[ "def", "delete", "(", "self", ",", "dry_run", "=", "False", ")", ":", "return", "self", ".", "connection", ".", "delete_key_pair", "(", "self", ".", "name", ",", "dry_run", "=", "dry_run", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/keypair.py#L52-L59
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/math_grad.py
python
_safe_shape_div
(x, y)
return x // math_ops.maximum(y, 1)
Divides `x / y` assuming `x, y >= 0`, treating `0 / 0 = 0`.
Divides `x / y` assuming `x, y >= 0`, treating `0 / 0 = 0`.
[ "Divides", "x", "/", "y", "assuming", "x", "y", ">", "=", "0", "treating", "0", "/", "0", "=", "0", "." ]
def _safe_shape_div(x, y): """Divides `x / y` assuming `x, y >= 0`, treating `0 / 0 = 0`.""" return x // math_ops.maximum(y, 1)
[ "def", "_safe_shape_div", "(", "x", ",", "y", ")", ":", "return", "x", "//", "math_ops", ".", "maximum", "(", "y", ",", "1", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/math_grad.py#L38-L40
KhronosGroup/SPIRV-LLVM
1eb85593f3fe2c39379b9a9b088d51eda4f42b8b
examples/Kaleidoscope/MCJIT/lazy/genk-timing.py
python
KScriptGenerator.updateCalledFunctionList
(self, callee)
Maintains a list of functions that will actually be called
Maintains a list of functions that will actually be called
[ "Maintains", "a", "list", "of", "functions", "that", "will", "actually", "be", "called" ]
def updateCalledFunctionList(self, callee): """Maintains a list of functions that will actually be called""" # Update the total call count self.updateTotalCallCount(callee) # If this function is already in the list, don't do anything else if callee in self.calledFunctions: return # Add this function to the list of those that will be called. self.calledFunctions.append(callee) # If this function calls other functions, add them too if callee in self.calledFunctionTable: for subCallee in self.calledFunctionTable[callee]: self.updateCalledFunctionList(subCallee)
[ "def", "updateCalledFunctionList", "(", "self", ",", "callee", ")", ":", "# Update the total call count", "self", ".", "updateTotalCallCount", "(", "callee", ")", "# If this function is already in the list, don't do anything else", "if", "callee", "in", "self", ".", "called...
https://github.com/KhronosGroup/SPIRV-LLVM/blob/1eb85593f3fe2c39379b9a9b088d51eda4f42b8b/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py#L66-L78
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py
python
_FieldMaskTree.AddLeafNodes
(self, prefix, node)
Adds leaf nodes begin with prefix to this tree.
Adds leaf nodes begin with prefix to this tree.
[ "Adds", "leaf", "nodes", "begin", "with", "prefix", "to", "this", "tree", "." ]
def AddLeafNodes(self, prefix, node): """Adds leaf nodes begin with prefix to this tree.""" if not node: self.AddPath(prefix) for name in node: child_path = prefix + '.' + name self.AddLeafNodes(child_path, node[name])
[ "def", "AddLeafNodes", "(", "self", ",", "prefix", ",", "node", ")", ":", "if", "not", "node", ":", "self", ".", "AddPath", "(", "prefix", ")", "for", "name", "in", "node", ":", "child_path", "=", "prefix", "+", "'.'", "+", "name", "self", ".", "Ad...
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py#L546-L552
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/optparse.py
python
HelpFormatter._format_text
(self, text)
return textwrap.fill(text, text_width, initial_indent=indent, subsequent_indent=indent)
Format a paragraph of free-form text for inclusion in the help output at the current indentation level.
Format a paragraph of free-form text for inclusion in the help output at the current indentation level.
[ "Format", "a", "paragraph", "of", "free", "-", "form", "text", "for", "inclusion", "in", "the", "help", "output", "at", "the", "current", "indentation", "level", "." ]
def _format_text(self, text): """ Format a paragraph of free-form text for inclusion in the help output at the current indentation level. """ text_width = self.width - self.current_indent indent = " "*self.current_indent return textwrap.fill(text, text_width, initial_indent=indent, subsequent_indent=indent)
[ "def", "_format_text", "(", "self", ",", "text", ")", ":", "text_width", "=", "self", ".", "width", "-", "self", ".", "current_indent", "indent", "=", "\" \"", "*", "self", ".", "current_indent", "return", "textwrap", ".", "fill", "(", "text", ",", "text...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/optparse.py#L254-L264
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_simulation.py
python
SimulationDomain.getArrivedIDList
(self)
return self._getUniversal(tc.VAR_ARRIVED_VEHICLES_IDS)
getArrivedIDList() -> list(string) Returns a list of ids of vehicles which arrived (have reached their destination and are removed from the road network) in this time step.
getArrivedIDList() -> list(string)
[ "getArrivedIDList", "()", "-", ">", "list", "(", "string", ")" ]
def getArrivedIDList(self): """getArrivedIDList() -> list(string) Returns a list of ids of vehicles which arrived (have reached their destination and are removed from the road network) in this time step. """ return self._getUniversal(tc.VAR_ARRIVED_VEHICLES_IDS)
[ "def", "getArrivedIDList", "(", "self", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_ARRIVED_VEHICLES_IDS", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_simulation.py#L321-L327
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/cygprofile/check_orderfile.py
python
_CountMisorderedSymbols
(symbols, symbol_infos)
return (misordered_count, len(matched_symbol_infos), missing_count)
Count the number of misordered symbols, and log them. Args: symbols: ordered sequence of symbols from the orderfile symbol_infos: ordered list of SymbolInfo from the binary Returns: (misordered_pairs_count, matched_symbols_count, unmatched_symbols_count)
Count the number of misordered symbols, and log them.
[ "Count", "the", "number", "of", "misordered", "symbols", "and", "log", "them", "." ]
def _CountMisorderedSymbols(symbols, symbol_infos): """Count the number of misordered symbols, and log them. Args: symbols: ordered sequence of symbols from the orderfile symbol_infos: ordered list of SymbolInfo from the binary Returns: (misordered_pairs_count, matched_symbols_count, unmatched_symbols_count) """ name_to_symbol_info = symbol_extractor.CreateNameToSymbolInfo(symbol_infos) matched_symbol_infos = [] missing_count = 0 misordered_count = 0 # Find the SymbolInfo matching the orderfile symbols in the binary. for symbol in symbols: if symbol in name_to_symbol_info: matched_symbol_infos.append(name_to_symbol_info[symbol]) else: missing_count += 1 if missing_count < _MAX_WARNINGS_TO_PRINT: logging.warning('Symbol "%s" is in the orderfile, not in the binary' % symbol) logging.info('%d matched symbols, %d un-matched (Only the first %d unmatched' ' symbols are shown)' % ( len(matched_symbol_infos), missing_count, _MAX_WARNINGS_TO_PRINT)) # In the order of the orderfile, find all the symbols that are at an offset # smaller than their immediate predecessor, and record the pair. previous_symbol_info = symbol_extractor.SymbolInfo( name='', offset=-1, size=0, section='') for symbol_info in matched_symbol_infos: if symbol_info.offset < previous_symbol_info.offset and not ( _IsSameMethod(symbol_info.name, previous_symbol_info.name)): logging.warning('Misordered pair: %s - %s' % ( str(previous_symbol_info), str(symbol_info))) misordered_count += 1 previous_symbol_info = symbol_info return (misordered_count, len(matched_symbol_infos), missing_count)
[ "def", "_CountMisorderedSymbols", "(", "symbols", ",", "symbol_infos", ")", ":", "name_to_symbol_info", "=", "symbol_extractor", ".", "CreateNameToSymbolInfo", "(", "symbol_infos", ")", "matched_symbol_infos", "=", "[", "]", "missing_count", "=", "0", "misordered_count"...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cygprofile/check_orderfile.py#L28-L68
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextBuffer.EndSymbolBullet
(*args, **kwargs)
return _richtext.RichTextBuffer_EndSymbolBullet(*args, **kwargs)
EndSymbolBullet(self) -> bool
EndSymbolBullet(self) -> bool
[ "EndSymbolBullet", "(", "self", ")", "-", ">", "bool" ]
def EndSymbolBullet(*args, **kwargs): """EndSymbolBullet(self) -> bool""" return _richtext.RichTextBuffer_EndSymbolBullet(*args, **kwargs)
[ "def", "EndSymbolBullet", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_EndSymbolBullet", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L2436-L2438
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/ansic/cparse.py
python
p_struct_declaration_list_1
(t)
struct_declaration_list : struct_declaration
struct_declaration_list : struct_declaration
[ "struct_declaration_list", ":", "struct_declaration" ]
def p_struct_declaration_list_1(t): 'struct_declaration_list : struct_declaration' pass
[ "def", "p_struct_declaration_list_1", "(", "t", ")", ":", "pass" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L153-L155
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozbuild/mozpack/files.py
python
FileFinder._find_glob
(self, base, pattern)
Actual implementation of FileFinder.find() when the given pattern contains globbing patterns ('*' or '**'). This is meant to be an equivalent of: for p, f in self: if mozpack.path.match(p, pattern): yield p, f but avoids scanning the entire tree.
Actual implementation of FileFinder.find() when the given pattern contains globbing patterns ('*' or '**'). This is meant to be an equivalent of: for p, f in self: if mozpack.path.match(p, pattern): yield p, f but avoids scanning the entire tree.
[ "Actual", "implementation", "of", "FileFinder", ".", "find", "()", "when", "the", "given", "pattern", "contains", "globbing", "patterns", "(", "*", "or", "**", ")", ".", "This", "is", "meant", "to", "be", "an", "equivalent", "of", ":", "for", "p", "f", ...
def _find_glob(self, base, pattern): ''' Actual implementation of FileFinder.find() when the given pattern contains globbing patterns ('*' or '**'). This is meant to be an equivalent of: for p, f in self: if mozpack.path.match(p, pattern): yield p, f but avoids scanning the entire tree. ''' if not pattern: for p, f in self._find(base): yield p, f elif pattern[0] == '**': for p, f in self._find(base): if mozpack.path.match(p, mozpack.path.join(*pattern)): yield p, f elif '*' in pattern[0]: if not os.path.exists(os.path.join(self.base, base)): return for p in self.ignore: if mozpack.path.match(base, p): return # See above comment w.r.t. sorted() and idempotent behavior. for p in sorted(os.listdir(os.path.join(self.base, base))): if p.startswith('.') and not pattern[0].startswith('.'): continue if mozpack.path.match(p, pattern[0]): for p_, f in self._find_glob(mozpack.path.join(base, p), pattern[1:]): yield p_, f else: for p, f in self._find_glob(mozpack.path.join(base, pattern[0]), pattern[1:]): yield p, f
[ "def", "_find_glob", "(", "self", ",", "base", ",", "pattern", ")", ":", "if", "not", "pattern", ":", "for", "p", ",", "f", "in", "self", ".", "_find", "(", "base", ")", ":", "yield", "p", ",", "f", "elif", "pattern", "[", "0", "]", "==", "'**'...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozpack/files.py#L799-L835
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cffi/api.py
python
FFI.sizeof
(self, cdecl)
Return the size in bytes of the argument. It can be a string naming a C type, or a 'cdata' instance.
Return the size in bytes of the argument. It can be a string naming a C type, or a 'cdata' instance.
[ "Return", "the", "size", "in", "bytes", "of", "the", "argument", ".", "It", "can", "be", "a", "string", "naming", "a", "C", "type", "or", "a", "cdata", "instance", "." ]
def sizeof(self, cdecl): """Return the size in bytes of the argument. It can be a string naming a C type, or a 'cdata' instance. """ if isinstance(cdecl, basestring): BType = self._typeof(cdecl) return self._backend.sizeof(BType) else: return self._backend.sizeof(cdecl)
[ "def", "sizeof", "(", "self", ",", "cdecl", ")", ":", "if", "isinstance", "(", "cdecl", ",", "basestring", ")", ":", "BType", "=", "self", ".", "_typeof", "(", "cdecl", ")", "return", "self", ".", "_backend", ".", "sizeof", "(", "BType", ")", "else",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cffi/api.py#L213-L221
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/core.py
python
CherryTree.switch_buffer_text_source
(self, text_buffer, tree_iter, new_syntax_highl, old_syntax_highl)
Switch TextBuffer -> SourceBuffer or SourceBuffer -> TextBuffer
Switch TextBuffer -> SourceBuffer or SourceBuffer -> TextBuffer
[ "Switch", "TextBuffer", "-", ">", "SourceBuffer", "or", "SourceBuffer", "-", ">", "TextBuffer" ]
def switch_buffer_text_source(self, text_buffer, tree_iter, new_syntax_highl, old_syntax_highl): """Switch TextBuffer -> SourceBuffer or SourceBuffer -> TextBuffer""" if self.user_active: self.user_active = False user_active_restore = True else: user_active_restore = False if old_syntax_highl == cons.RICH_TEXT_ID and new_syntax_highl != cons.RICH_TEXT_ID: rich_to_non_rich = True txt_handler = exports.Export2Txt(self) node_text = txt_handler.node_export_to_txt(text_buffer, "") else: rich_to_non_rich = False node_text = text_buffer.get_text(*text_buffer.get_bounds()) self.treestore[tree_iter][2] = self.buffer_create(new_syntax_highl) if rich_to_non_rich: self.treestore[tree_iter][2].begin_not_undoable_action() self.treestore[tree_iter][2].set_text(node_text) if rich_to_non_rich: self.treestore[tree_iter][2].end_not_undoable_action() self.sourceview.set_buffer(self.treestore[tree_iter][2]) self.treestore[tree_iter][2].connect('modified-changed', self.on_modified_changed) self.sourceview_set_properties(tree_iter, new_syntax_highl) if user_active_restore: self.user_active = True self.ctdb_handler.pending_edit_db_node_buff(self.treestore[tree_iter][3])
[ "def", "switch_buffer_text_source", "(", "self", ",", "text_buffer", ",", "tree_iter", ",", "new_syntax_highl", ",", "old_syntax_highl", ")", ":", "if", "self", ".", "user_active", ":", "self", ".", "user_active", "=", "False", "user_active_restore", "=", "True", ...
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L3101-L3122
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/examples/tutorials/mnist/mnist.py
python
training
(loss, learning_rate)
return train_op
Sets up the training Ops. Creates a summarizer to track the loss over time in TensorBoard. Creates an optimizer and applies the gradients to all trainable variables. The Op returned by this function is what must be passed to the `sess.run()` call to cause the model to train. Args: loss: Loss tensor, from loss(). learning_rate: The learning rate to use for gradient descent. Returns: train_op: The Op for training.
Sets up the training Ops.
[ "Sets", "up", "the", "training", "Ops", "." ]
def training(loss, learning_rate): """Sets up the training Ops. Creates a summarizer to track the loss over time in TensorBoard. Creates an optimizer and applies the gradients to all trainable variables. The Op returned by this function is what must be passed to the `sess.run()` call to cause the model to train. Args: loss: Loss tensor, from loss(). learning_rate: The learning rate to use for gradient descent. Returns: train_op: The Op for training. """ # Add a scalar summary for the snapshot loss. tf.compat.v1.summary.scalar('loss', loss) # Create the gradient descent optimizer with the given learning rate. optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate) # Create a variable to track the global step. global_step = tf.Variable(0, name='global_step', trainable=False) # Use the optimizer to apply the gradients that minimize the loss # (and also increment the global step counter) as a single training step. train_op = optimizer.minimize(loss, global_step=global_step) return train_op
[ "def", "training", "(", "loss", ",", "learning_rate", ")", ":", "# Add a scalar summary for the snapshot loss.", "tf", ".", "compat", ".", "v1", ".", "summary", ".", "scalar", "(", "'loss'", ",", "loss", ")", "# Create the gradient descent optimizer with the given learn...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/examples/tutorials/mnist/mnist.py#L101-L127
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
HandWrittenHandler.WriteImmediateServiceImplementation
(self, func, file)
Overrriden from TypeHandler.
Overrriden from TypeHandler.
[ "Overrriden", "from", "TypeHandler", "." ]
def WriteImmediateServiceImplementation(self, func, file): """Overrriden from TypeHandler.""" pass
[ "def", "WriteImmediateServiceImplementation", "(", "self", ",", "func", ",", "file", ")", ":", "pass" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L2457-L2459
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/html.py
python
HtmlHelpController.GetFrame
(*args, **kwargs)
return _html.HtmlHelpController_GetFrame(*args, **kwargs)
GetFrame(self) -> HtmlHelpFrame
GetFrame(self) -> HtmlHelpFrame
[ "GetFrame", "(", "self", ")", "-", ">", "HtmlHelpFrame" ]
def GetFrame(*args, **kwargs): """GetFrame(self) -> HtmlHelpFrame""" return _html.HtmlHelpController_GetFrame(*args, **kwargs)
[ "def", "GetFrame", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlHelpController_GetFrame", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L1950-L1952
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/datetime.py
python
datetime.time
(self)
return time(self.hour, self.minute, self.second, self.microsecond, fold=self.fold)
Return the time part, with tzinfo None.
Return the time part, with tzinfo None.
[ "Return", "the", "time", "part", "with", "tzinfo", "None", "." ]
def time(self): "Return the time part, with tzinfo None." return time(self.hour, self.minute, self.second, self.microsecond, fold=self.fold)
[ "def", "time", "(", "self", ")", ":", "return", "time", "(", "self", ".", "hour", ",", "self", ".", "minute", ",", "self", ".", "second", ",", "self", ".", "microsecond", ",", "fold", "=", "self", ".", "fold", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/datetime.py#L1760-L1762
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Tools/fc_config.py
python
fc_add_flags
(conf)
Adds FCFLAGS / LDFLAGS / LINKFLAGS from os.environ to conf.env
Adds FCFLAGS / LDFLAGS / LINKFLAGS from os.environ to conf.env
[ "Adds", "FCFLAGS", "/", "LDFLAGS", "/", "LINKFLAGS", "from", "os", ".", "environ", "to", "conf", ".", "env" ]
def fc_add_flags(conf): """ Adds FCFLAGS / LDFLAGS / LINKFLAGS from os.environ to conf.env """ conf.add_os_flags('FCPPFLAGS', dup=False) conf.add_os_flags('FCFLAGS', dup=False) conf.add_os_flags('LINKFLAGS', dup=False) conf.add_os_flags('LDFLAGS', dup=False)
[ "def", "fc_add_flags", "(", "conf", ")", ":", "conf", ".", "add_os_flags", "(", "'FCPPFLAGS'", ",", "dup", "=", "False", ")", "conf", ".", "add_os_flags", "(", "'FCFLAGS'", ",", "dup", "=", "False", ")", "conf", ".", "add_os_flags", "(", "'LINKFLAGS'", "...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/fc_config.py#L51-L58
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TInt_SaveFrugalIntV
(*args)
return _snap.TInt_SaveFrugalIntV(*args)
TInt_SaveFrugalIntV(TSOut SOut, TIntV IntV) Parameters: SOut: TSOut & IntV: TVec< TInt,int > const &
TInt_SaveFrugalIntV(TSOut SOut, TIntV IntV)
[ "TInt_SaveFrugalIntV", "(", "TSOut", "SOut", "TIntV", "IntV", ")" ]
def TInt_SaveFrugalIntV(*args): """ TInt_SaveFrugalIntV(TSOut SOut, TIntV IntV) Parameters: SOut: TSOut & IntV: TVec< TInt,int > const & """ return _snap.TInt_SaveFrugalIntV(*args)
[ "def", "TInt_SaveFrugalIntV", "(", "*", "args", ")", ":", "return", "_snap", ".", "TInt_SaveFrugalIntV", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L13528-L13537
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
CommandListEvent.__init__
(self, commandTypeOrEvent=None, winid=0)
Default class constructor. For internal use: do not call it in your code! :param `commandTypeOrEvent`: the event type or another instance of :class:`PyCommandEvent`; :param `winid`: the event identifier.
Default class constructor. For internal use: do not call it in your code!
[ "Default", "class", "constructor", ".", "For", "internal", "use", ":", "do", "not", "call", "it", "in", "your", "code!" ]
def __init__(self, commandTypeOrEvent=None, winid=0): """ Default class constructor. For internal use: do not call it in your code! :param `commandTypeOrEvent`: the event type or another instance of :class:`PyCommandEvent`; :param `winid`: the event identifier. """ if type(commandTypeOrEvent) == types.IntType: wx.PyCommandEvent.__init__(self, commandTypeOrEvent, winid) self.m_code = 0 self.m_oldItemIndex = 0 self.m_itemIndex = 0 self.m_col = 0 self.m_pointDrag = wx.Point() self.m_item = UltimateListItem() self.m_editCancelled = False else: wx.PyCommandEvent.__init__(self, commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId()) self.m_code = commandTypeOrEvent.m_code self.m_oldItemIndex = commandTypeOrEvent.m_oldItemIndex self.m_itemIndex = commandTypeOrEvent.m_itemIndex self.m_col = commandTypeOrEvent.m_col self.m_pointDrag = commandTypeOrEvent.m_pointDrag self.m_item = commandTypeOrEvent.m_item self.m_editCancelled = commandTypeOrEvent.m_editCancelled
[ "def", "__init__", "(", "self", ",", "commandTypeOrEvent", "=", "None", ",", "winid", "=", "0", ")", ":", "if", "type", "(", "commandTypeOrEvent", ")", "==", "types", ".", "IntType", ":", "wx", ".", "PyCommandEvent", ".", "__init__", "(", "self", ",", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L2279-L2310
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/service.py
python
RpcController.SetFailed
(self, reason)
Sets a failure reason. Causes Failed() to return true on the client side. "reason" will be incorporated into the message returned by ErrorText(). If you find you need to return machine-readable information about failures, you should incorporate it into your response protocol buffer and should NOT call SetFailed().
Sets a failure reason.
[ "Sets", "a", "failure", "reason", "." ]
def SetFailed(self, reason): """Sets a failure reason. Causes Failed() to return true on the client side. "reason" will be incorporated into the message returned by ErrorText(). If you find you need to return machine-readable information about failures, you should incorporate it into your response protocol buffer and should NOT call SetFailed(). """ raise NotImplementedError
[ "def", "SetFailed", "(", "self", ",", "reason", ")", ":", "raise", "NotImplementedError" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/service.py#L169-L178
google/nucleus
68d3947fafba1337f294c0668a6e1c7f3f1273e3
nucleus/util/ranges.py
python
make_range
(chrom, start, end)
return range_pb2.Range(reference_name=chrom, start=start, end=end)
Returns a nucleus.genomics.v1.Range. Args: chrom: str. The chromosome name. start: int. The start position (0-based, inclusive) of this range. end: int. The end position (0-based, exclusive) of this range. Returns: A nucleus.genomics.v1.Range.
Returns a nucleus.genomics.v1.Range.
[ "Returns", "a", "nucleus", ".", "genomics", ".", "v1", ".", "Range", "." ]
def make_range(chrom, start, end): """Returns a nucleus.genomics.v1.Range. Args: chrom: str. The chromosome name. start: int. The start position (0-based, inclusive) of this range. end: int. The end position (0-based, exclusive) of this range. Returns: A nucleus.genomics.v1.Range. """ return range_pb2.Range(reference_name=chrom, start=start, end=end)
[ "def", "make_range", "(", "chrom", ",", "start", ",", "end", ")", ":", "return", "range_pb2", ".", "Range", "(", "reference_name", "=", "chrom", ",", "start", "=", "start", ",", "end", "=", "end", ")" ]
https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/util/ranges.py#L365-L376
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
PyApp_SetMacExitMenuItemId
(*args, **kwargs)
return _core_.PyApp_SetMacExitMenuItemId(*args, **kwargs)
PyApp_SetMacExitMenuItemId(long val)
PyApp_SetMacExitMenuItemId(long val)
[ "PyApp_SetMacExitMenuItemId", "(", "long", "val", ")" ]
def PyApp_SetMacExitMenuItemId(*args, **kwargs): """PyApp_SetMacExitMenuItemId(long val)""" return _core_.PyApp_SetMacExitMenuItemId(*args, **kwargs)
[ "def", "PyApp_SetMacExitMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_SetMacExitMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L8306-L8308
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py
python
Buffer._open_file_in_editor
(self, filename)
return False
Call editor executable. Return True when we received a zero return code.
Call editor executable.
[ "Call", "editor", "executable", "." ]
def _open_file_in_editor(self, filename): """ Call editor executable. Return True when we received a zero return code. """ # If the 'VISUAL' or 'EDITOR' environment variable has been set, use that. # Otherwise, fall back to the first available editor that we can find. visual = os.environ.get('VISUAL') editor = os.environ.get('EDITOR') editors = [ visual, editor, # Order of preference. '/usr/bin/editor', '/usr/bin/nano', '/usr/bin/pico', '/usr/bin/vi', '/usr/bin/emacs', ] for e in editors: if e: try: # Use 'shlex.split()', because $VISUAL can contain spaces # and quotes. returncode = subprocess.call(shlex.split(e) + [filename]) return returncode == 0 except OSError: # Executable does not exist, try the next one. pass return False
[ "def", "_open_file_in_editor", "(", "self", ",", "filename", ")", ":", "# If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.", "# Otherwise, fall back to the first available editor that we can find.", "visual", "=", "os", ".", "environ", ".", "get", "(", "'V...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py#L1294-L1329
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/auto_bisect/bisect_perf_regression.py
python
BisectPerformanceMetrics.NudgeRevisionsIfDEPSChange
(self, bad_revision, good_revision, good_svn_revision=None)
return (bad_revision, good_revision)
Checks to see if changes to DEPS file occurred, and that the revision range also includes the change to .DEPS.git. If it doesn't, attempts to expand the revision range to include it. Args: bad_revision: First known bad git revision. good_revision: Last known good git revision. good_svn_revision: Last known good svn revision. Returns: A tuple with the new bad and good revisions.
Checks to see if changes to DEPS file occurred, and that the revision range also includes the change to .DEPS.git. If it doesn't, attempts to expand the revision range to include it.
[ "Checks", "to", "see", "if", "changes", "to", "DEPS", "file", "occurred", "and", "that", "the", "revision", "range", "also", "includes", "the", "change", "to", ".", "DEPS", ".", "git", ".", "If", "it", "doesn", "t", "attempts", "to", "expand", "the", "...
def NudgeRevisionsIfDEPSChange(self, bad_revision, good_revision, good_svn_revision=None): """Checks to see if changes to DEPS file occurred, and that the revision range also includes the change to .DEPS.git. If it doesn't, attempts to expand the revision range to include it. Args: bad_revision: First known bad git revision. good_revision: Last known good git revision. good_svn_revision: Last known good svn revision. Returns: A tuple with the new bad and good revisions. """ # DONOT perform nudge because at revision 291563 .DEPS.git was removed # and source contain only DEPS file for dependency changes. if good_svn_revision >= 291563: return (bad_revision, good_revision) if self.opts.target_platform == 'chromium': changes_to_deps = source_control.QueryFileRevisionHistory( bisect_utils.FILE_DEPS, good_revision, bad_revision) if changes_to_deps: # DEPS file was changed, search from the oldest change to DEPS file to # bad_revision to see if there are matching .DEPS.git changes. oldest_deps_change = changes_to_deps[-1] changes_to_gitdeps = source_control.QueryFileRevisionHistory( bisect_utils.FILE_DEPS_GIT, oldest_deps_change, bad_revision) if len(changes_to_deps) != len(changes_to_gitdeps): # Grab the timestamp of the last DEPS change cmd = ['log', '--format=%ct', '-1', changes_to_deps[0]] output = bisect_utils.CheckRunGit(cmd) commit_time = int(output) # Try looking for a commit that touches the .DEPS.git file in the # next 15 minutes after the DEPS file change. cmd = [ 'log', '--format=%H', '-1', '--before=%d' % (commit_time + 900), '--after=%d' % commit_time, 'origin/master', '--', bisect_utils.FILE_DEPS_GIT ] output = bisect_utils.CheckRunGit(cmd) output = output.strip() if output: self.warnings.append( 'Detected change to DEPS and modified ' 'revision range to include change to .DEPS.git') return (output, good_revision) else: self.warnings.append( 'Detected change to DEPS but couldn\'t find ' 'matching change to .DEPS.git') return (bad_revision, good_revision)
[ "def", "NudgeRevisionsIfDEPSChange", "(", "self", ",", "bad_revision", ",", "good_revision", ",", "good_svn_revision", "=", "None", ")", ":", "# DONOT perform nudge because at revision 291563 .DEPS.git was removed", "# and source contain only DEPS file for dependency changes.", "if",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/bisect_perf_regression.py#L1917-L1972
kismetwireless/kismet
a7c0dc270c960fb1f58bd9cec4601c201885fd4e
capture_proxy_adsb/KismetCaptureProxyAdsb/kismetexternal/__init__.py
python
ExternalInterface.write_ext_packet
(self, cmdtype, content)
Generate a Kismet external interface command, frame, and transmit it. :param cmdtype: Command type string :param content: Command content, must be a serializable protobuf object :return: None
Generate a Kismet external interface command, frame, and transmit it.
[ "Generate", "a", "Kismet", "external", "interface", "command", "frame", "and", "transmit", "it", "." ]
def write_ext_packet(self, cmdtype, content): """ Generate a Kismet external interface command, frame, and transmit it. :param cmdtype: Command type string :param content: Command content, must be a serializable protobuf object :return: None """ cp = kismet_pb2.Command() cp.command = cmdtype cp.seqno = self.cmdnum cp.content = content.SerializeToString() self.write_raw_packet(cp) self.cmdnum = self.cmdnum + 1
[ "def", "write_ext_packet", "(", "self", ",", "cmdtype", ",", "content", ")", ":", "cp", "=", "kismet_pb2", ".", "Command", "(", ")", "cp", ".", "command", "=", "cmdtype", "cp", ".", "seqno", "=", "self", ".", "cmdnum", "cp", ".", "content", "=", "con...
https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_proxy_adsb/KismetCaptureProxyAdsb/kismetexternal/__init__.py#L594-L611
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/DocXMLRPCServer.py
python
DocXMLRPCRequestHandler.do_GET
(self)
Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation.
Handles the HTTP GET request.
[ "Handles", "the", "HTTP", "GET", "request", "." ]
def do_GET(self): """Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. """ # Check that the path is legal if not self.is_rpc_path_valid(): self.report_404() return response = self.server.generate_html_documentation() self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response)
[ "def", "do_GET", "(", "self", ")", ":", "# Check that the path is legal", "if", "not", "self", ".", "is_rpc_path_valid", "(", ")", ":", "self", ".", "report_404", "(", ")", "return", "response", "=", "self", ".", "server", ".", "generate_html_documentation", "...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/DocXMLRPCServer.py#L225-L241
facebook/fbthrift
fb9c8562aba04c4fd9b17716eb5d970cc88a75bb
build/fbcode_builder/getdeps/load.py
python
ManifestLoader.manifests_in_dependency_order
(self, manifest=None)
return dep_order
Compute all dependencies of the specified project. Returns a list of the dependencies plus the project itself, in topologically sorted order. Each entry in the returned list only depends on projects that appear before it in the list. If the input manifest is None, the dependencies for all currently loaded projects will be computed. i.e., if you call load_all_manifests() followed by manifests_in_dependency_order() this will return a global dependency ordering of all projects.
Compute all dependencies of the specified project. Returns a list of the dependencies plus the project itself, in topologically sorted order.
[ "Compute", "all", "dependencies", "of", "the", "specified", "project", ".", "Returns", "a", "list", "of", "the", "dependencies", "plus", "the", "project", "itself", "in", "topologically", "sorted", "order", "." ]
def manifests_in_dependency_order(self, manifest=None): """Compute all dependencies of the specified project. Returns a list of the dependencies plus the project itself, in topologically sorted order. Each entry in the returned list only depends on projects that appear before it in the list. If the input manifest is None, the dependencies for all currently loaded projects will be computed. i.e., if you call load_all_manifests() followed by manifests_in_dependency_order() this will return a global dependency ordering of all projects.""" # The list of deps that have been fully processed seen = set() # The list of deps which have yet to be evaluated. This # can potentially contain duplicates. if manifest is None: deps = list(self.manifests_by_name.values()) else: assert manifest.name in self.manifests_by_name deps = [manifest] # The list of manifests in dependency order dep_order = [] while len(deps) > 0: m = deps.pop(0) if m.name in seen: continue # Consider its deps, if any. # We sort them for increased determinism; we'll produce # a correct order even if they aren't sorted, but we prefer # to produce the same order regardless of how they are listed # in the project manifest files. ctx = self.ctx_gen.get_context(m.name) dep_list = m.get_dependencies(ctx) dep_count = 0 for dep_name in dep_list: # If we're not sure whether it is done, queue it up if dep_name not in seen: dep = self.manifests_by_name.get(dep_name) if dep is None: dep = self._loader.load_project(self.build_opts, dep_name) self.manifests_by_name[dep.name] = dep deps.append(dep) dep_count += 1 if dep_count > 0: # If we queued anything, re-queue this item, as it depends # those new item(s) and their transitive deps. deps.append(m) continue # Its deps are done, so we can emit it seen.add(m.name) dep_order.append(m) return dep_order
[ "def", "manifests_in_dependency_order", "(", "self", ",", "manifest", "=", "None", ")", ":", "# The list of deps that have been fully processed", "seen", "=", "set", "(", ")", "# The list of deps which have yet to be evaluated. This", "# can potentially contain duplicates.", "if...
https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/build/fbcode_builder/getdeps/load.py#L159-L217
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/locators.py
python
AggregatingLocator.get_distribution_names
(self)
return result
Return all the distribution names known to this locator.
Return all the distribution names known to this locator.
[ "Return", "all", "the", "distribution", "names", "known", "to", "this", "locator", "." ]
def get_distribution_names(self): """ Return all the distribution names known to this locator. """ result = set() for locator in self.locators: try: result |= locator.get_distribution_names() except NotImplementedError: pass return result
[ "def", "get_distribution_names", "(", "self", ")", ":", "result", "=", "set", "(", ")", "for", "locator", "in", "self", ".", "locators", ":", "try", ":", "result", "|=", "locator", ".", "get_distribution_names", "(", ")", "except", "NotImplementedError", ":"...
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/distlib/locators.py#L1035-L1045
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
PythonAPI/examples/no_rendering_mode.py
python
HelpText.__init__
(self, font, width, height)
Renders the help text that shows the controls for using no rendering mode
Renders the help text that shows the controls for using no rendering mode
[ "Renders", "the", "help", "text", "that", "shows", "the", "controls", "for", "using", "no", "rendering", "mode" ]
def __init__(self, font, width, height): """Renders the help text that shows the controls for using no rendering mode""" lines = __doc__.split('\n') self.font = font self.dim = (680, len(lines) * 22 + 12) self.pos = (0.5 * width - 0.5 * self.dim[0], 0.5 * height - 0.5 * self.dim[1]) self.seconds_left = 0 self.surface = pygame.Surface(self.dim) self.surface.fill(COLOR_BLACK) for n, line in enumerate(lines): text_texture = self.font.render(line, True, COLOR_WHITE) self.surface.blit(text_texture, (22, n * 22)) self._render = False self.surface.set_alpha(220)
[ "def", "__init__", "(", "self", ",", "font", ",", "width", ",", "height", ")", ":", "lines", "=", "__doc__", ".", "split", "(", "'\\n'", ")", "self", ".", "font", "=", "font", "self", ".", "dim", "=", "(", "680", ",", "len", "(", "lines", ")", ...
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/examples/no_rendering_mode.py#L230-L243
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/multiprocessing/process.py
python
Process.daemon
(self, daemonic)
Set whether process is a daemon
Set whether process is a daemon
[ "Set", "whether", "process", "is", "a", "daemon" ]
def daemon(self, daemonic): ''' Set whether process is a daemon ''' assert self._popen is None, 'process has already started' self._daemonic = daemonic
[ "def", "daemon", "(", "self", ",", "daemonic", ")", ":", "assert", "self", ".", "_popen", "is", "None", ",", "'process has already started'", "self", ".", "_daemonic", "=", "daemonic" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/multiprocessing/process.py#L152-L157
eclipse/omr
056e7c9ce9d503649190bc5bd9931fac30b4e4bc
jitbuilder/apigen/genutils.py
python
APIClass.name
(self)
return self.description["name"]
Returns the (base) name of the API class.
Returns the (base) name of the API class.
[ "Returns", "the", "(", "base", ")", "name", "of", "the", "API", "class", "." ]
def name(self): """Returns the (base) name of the API class.""" return self.description["name"]
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "description", "[", "\"name\"", "]" ]
https://github.com/eclipse/omr/blob/056e7c9ce9d503649190bc5bd9931fac30b4e4bc/jitbuilder/apigen/genutils.py#L295-L297
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
substituteEntitiesDefault
(val)
return ret
Set and return the previous value for default entity support. Initially the parser always keep entity references instead of substituting entity values in the output. This function has to be used to change the default parser behavior SAX::substituteEntities() has to be used for changing that on a file by file basis.
Set and return the previous value for default entity support. Initially the parser always keep entity references instead of substituting entity values in the output. This function has to be used to change the default parser behavior SAX::substituteEntities() has to be used for changing that on a file by file basis.
[ "Set", "and", "return", "the", "previous", "value", "for", "default", "entity", "support", ".", "Initially", "the", "parser", "always", "keep", "entity", "references", "instead", "of", "substituting", "entity", "values", "in", "the", "output", ".", "This", "fu...
def substituteEntitiesDefault(val): """Set and return the previous value for default entity support. Initially the parser always keep entity references instead of substituting entity values in the output. This function has to be used to change the default parser behavior SAX::substituteEntities() has to be used for changing that on a file by file basis. """ ret = libxml2mod.xmlSubstituteEntitiesDefault(val) return ret
[ "def", "substituteEntitiesDefault", "(", "val", ")", ":", "ret", "=", "libxml2mod", ".", "xmlSubstituteEntitiesDefault", "(", "val", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L621-L629
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/internals/blocks.py
python
Block.copy
(self, deep: bool = True)
return self.make_block_same_class(values)
copy constructor
copy constructor
[ "copy", "constructor" ]
def copy(self, deep: bool = True): """copy constructor""" values = self.values if deep: values = values.copy() return self.make_block_same_class(values)
[ "def", "copy", "(", "self", ",", "deep", ":", "bool", "=", "True", ")", ":", "values", "=", "self", ".", "values", "if", "deep", ":", "values", "=", "values", ".", "copy", "(", ")", "return", "self", ".", "make_block_same_class", "(", "values", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/blocks.py#L646-L651
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/decimal.py
python
Decimal._cmp
(self, other)
Compare the two non-NaN decimal instances self and other. Returns -1 if self < other, 0 if self == other and 1 if self > other. This routine is for internal use only.
Compare the two non-NaN decimal instances self and other.
[ "Compare", "the", "two", "non", "-", "NaN", "decimal", "instances", "self", "and", "other", "." ]
def _cmp(self, other): """Compare the two non-NaN decimal instances self and other. Returns -1 if self < other, 0 if self == other and 1 if self > other. This routine is for internal use only.""" if self._is_special or other._is_special: self_inf = self._isinfinity() other_inf = other._isinfinity() if self_inf == other_inf: return 0 elif self_inf < other_inf: return -1 else: return 1 # check for zeros; Decimal('0') == Decimal('-0') if not self: if not other: return 0 else: return -((-1)**other._sign) if not other: return (-1)**self._sign # If different signs, neg one is less if other._sign < self._sign: return -1 if self._sign < other._sign: return 1 self_adjusted = self.adjusted() other_adjusted = other.adjusted() if self_adjusted == other_adjusted: self_padded = self._int + '0'*(self._exp - other._exp) other_padded = other._int + '0'*(other._exp - self._exp) if self_padded == other_padded: return 0 elif self_padded < other_padded: return -(-1)**self._sign else: return (-1)**self._sign elif self_adjusted > other_adjusted: return (-1)**self._sign else: # self_adjusted < other_adjusted return -((-1)**self._sign)
[ "def", "_cmp", "(", "self", ",", "other", ")", ":", "if", "self", ".", "_is_special", "or", "other", ".", "_is_special", ":", "self_inf", "=", "self", ".", "_isinfinity", "(", ")", "other_inf", "=", "other", ".", "_isinfinity", "(", ")", "if", "self_in...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L753-L798
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/retrying.py
python
Attempt.get
(self, wrap_exception=False)
Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised.
Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised.
[ "Return", "the", "return", "value", "of", "this", "Attempt", "instance", "or", "raise", "an", "Exception", ".", "If", "wrap_exception", "is", "true", "this", "Attempt", "is", "wrapped", "inside", "of", "a", "RetryError", "before", "being", "raised", "." ]
def get(self, wrap_exception=False): """ Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised. """ if self.has_exception: if wrap_exception: raise RetryError(self) else: six.reraise(self.value[0], self.value[1], self.value[2]) else: return self.value
[ "def", "get", "(", "self", ",", "wrap_exception", "=", "False", ")", ":", "if", "self", ".", "has_exception", ":", "if", "wrap_exception", ":", "raise", "RetryError", "(", "self", ")", "else", ":", "six", ".", "reraise", "(", "self", ".", "value", "[",...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/retrying.py#L237-L249
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
MicroSleep
(*args, **kwargs)
return _misc_.MicroSleep(*args, **kwargs)
MicroSleep(unsigned long microseconds)
MicroSleep(unsigned long microseconds)
[ "MicroSleep", "(", "unsigned", "long", "microseconds", ")" ]
def MicroSleep(*args, **kwargs): """MicroSleep(unsigned long microseconds)""" return _misc_.MicroSleep(*args, **kwargs)
[ "def", "MicroSleep", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "MicroSleep", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L372-L374
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ToolBarBase.SetToolLongHelp
(*args, **kwargs)
return _controls_.ToolBarBase_SetToolLongHelp(*args, **kwargs)
SetToolLongHelp(self, int id, String helpString)
SetToolLongHelp(self, int id, String helpString)
[ "SetToolLongHelp", "(", "self", "int", "id", "String", "helpString", ")" ]
def SetToolLongHelp(*args, **kwargs): """SetToolLongHelp(self, int id, String helpString)""" return _controls_.ToolBarBase_SetToolLongHelp(*args, **kwargs)
[ "def", "SetToolLongHelp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToolBarBase_SetToolLongHelp", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L3831-L3833
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/build/android/emulator.py
python
Emulator._DeleteAVD
(self)
Delete the AVD of this emulator.
Delete the AVD of this emulator.
[ "Delete", "the", "AVD", "of", "this", "emulator", "." ]
def _DeleteAVD(self): """Delete the AVD of this emulator.""" avd_command = [ self.android, '--silent', 'delete', 'avd', '--name', self.avd, ] avd_process = subprocess.Popen(args=avd_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) logging.info('Delete AVD command: %s', ' '.join(avd_command)) avd_process.wait()
[ "def", "_DeleteAVD", "(", "self", ")", ":", "avd_command", "=", "[", "self", ".", "android", ",", "'--silent'", ",", "'delete'", ",", "'avd'", ",", "'--name'", ",", "self", ".", "avd", ",", "]", "avd_process", "=", "subprocess", ".", "Popen", "(", "arg...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/android/emulator.py#L191-L204
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/encoding.py
python
_IncludeFields
(encoded_message, message, include_fields)
return json.dumps(result)
Add the requested fields to the encoded message.
Add the requested fields to the encoded message.
[ "Add", "the", "requested", "fields", "to", "the", "encoded", "message", "." ]
def _IncludeFields(encoded_message, message, include_fields): """Add the requested fields to the encoded message.""" if include_fields is None: return encoded_message result = json.loads(encoded_message) for field_name in include_fields: try: value = _GetField(message, field_name.split('.')) nullvalue = None if isinstance(value, list): nullvalue = [] except KeyError: raise exceptions.InvalidDataError( 'No field named %s in message of type %s' % ( field_name, type(message))) _SetField(result, field_name.split('.'), nullvalue) return json.dumps(result)
[ "def", "_IncludeFields", "(", "encoded_message", ",", "message", ",", "include_fields", ")", ":", "if", "include_fields", "is", "None", ":", "return", "encoded_message", "result", "=", "json", ".", "loads", "(", "encoded_message", ")", "for", "field_name", "in",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/encoding.py#L223-L239
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/commands/install.py
python
InstallCommand._build_package_finder
(self, options, index_urls)
return PackageFinder(find_links=options.find_links, index_urls=index_urls, use_mirrors=options.use_mirrors, mirrors=options.mirrors, use_wheel=options.use_wheel, allow_external=options.allow_external, allow_insecure=options.allow_insecure, allow_all_external=options.allow_all_external, allow_all_insecure=options.allow_all_insecure, allow_all_prereleases=options.pre, )
Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly.
Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly.
[ "Create", "a", "package", "finder", "appropriate", "to", "this", "install", "command", ".", "This", "method", "is", "meant", "to", "be", "overridden", "by", "subclasses", "not", "called", "directly", "." ]
def _build_package_finder(self, options, index_urls): """ Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly. """ return PackageFinder(find_links=options.find_links, index_urls=index_urls, use_mirrors=options.use_mirrors, mirrors=options.mirrors, use_wheel=options.use_wheel, allow_external=options.allow_external, allow_insecure=options.allow_insecure, allow_all_external=options.allow_all_external, allow_all_insecure=options.allow_all_insecure, allow_all_prereleases=options.pre, )
[ "def", "_build_package_finder", "(", "self", ",", "options", ",", "index_urls", ")", ":", "return", "PackageFinder", "(", "find_links", "=", "options", ".", "find_links", ",", "index_urls", "=", "index_urls", ",", "use_mirrors", "=", "options", ".", "use_mirrors...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/commands/install.py#L154-L170
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
Log_ClearTraceMasks
(*args)
return _misc_.Log_ClearTraceMasks(*args)
Log_ClearTraceMasks()
Log_ClearTraceMasks()
[ "Log_ClearTraceMasks", "()" ]
def Log_ClearTraceMasks(*args): """Log_ClearTraceMasks()""" return _misc_.Log_ClearTraceMasks(*args)
[ "def", "Log_ClearTraceMasks", "(", "*", "args", ")", ":", "return", "_misc_", ".", "Log_ClearTraceMasks", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1708-L1710
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/boost_1_66_0/tools/build/src/build/type.py
python
registered
(type)
return type in __types
Returns true iff type has been registered.
Returns true iff type has been registered.
[ "Returns", "true", "iff", "type", "has", "been", "registered", "." ]
def registered (type): """ Returns true iff type has been registered. """ assert isinstance(type, basestring) return type in __types
[ "def", "registered", "(", "type", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "return", "type", "in", "__types" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/type.py#L137-L141
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/base_pane/base_pane_view.py
python
BasePaneView.enable_tile_plotting_options
(self)
Enable tile plotting
Enable tile plotting
[ "Enable", "tile", "plotting" ]
def enable_tile_plotting_options(self): """ Enable tile plotting """ self.tiled_plot_checkbox.setEnabled(True) self.tiled_by_combo.setEnabled(True) self.plot_raw_checkbox.setEnabled(True)
[ "def", "enable_tile_plotting_options", "(", "self", ")", ":", "self", ".", "tiled_plot_checkbox", ".", "setEnabled", "(", "True", ")", "self", ".", "tiled_by_combo", ".", "setEnabled", "(", "True", ")", "self", ".", "plot_raw_checkbox", ".", "setEnabled", "(", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/base_pane/base_pane_view.py#L169-L175
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/telnetlib.py
python
Telnet.msg
(self, msg, *args)
Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator.
Print a debug message, when the debug level is > 0.
[ "Print", "a", "debug", "message", "when", "the", "debug", "level", "is", ">", "0", "." ]
def msg(self, msg, *args): """Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator. """ if self.debuglevel > 0: print 'Telnet(%s,%d):' % (self.host, self.port), if args: print msg % args else: print msg
[ "def", "msg", "(", "self", ",", "msg", ",", "*", "args", ")", ":", "if", "self", ".", "debuglevel", ">", "0", ":", "print", "'Telnet(%s,%d):'", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", ",", "if", "args", ":", "print", "msg", ...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/telnetlib.py#L231-L243
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
Pythonwin/pywin/framework/editor/editor.py
python
EditorDocument.SetLineColor
(self, lineNo, color)
Color a line of all views
Color a line of all views
[ "Color", "a", "line", "of", "all", "views" ]
def SetLineColor(self, lineNo, color): "Color a line of all views" for view in self.GetAllViews(): view.SetLineColor(lineNo, color)
[ "def", "SetLineColor", "(", "self", ",", "lineNo", ",", "color", ")", ":", "for", "view", "in", "self", ".", "GetAllViews", "(", ")", ":", "view", ".", "SetLineColor", "(", "lineNo", ",", "color", ")" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/Pythonwin/pywin/framework/editor/editor.py#L169-L172
genn-team/genn
75e1eb218cafa228bf36ae4613d1ce26e877b12c
generate_swig_interfaces.py
python
SwigModuleGenerator.addSwigRename
( self, identifier, newName, comment='' )
Adds a line instructing SWIG to rename the matching identifier
Adds a line instructing SWIG to rename the matching identifier
[ "Adds", "a", "line", "instructing", "SWIG", "to", "rename", "the", "matching", "identifier" ]
def addSwigRename( self, identifier, newName, comment='' ): '''Adds a line instructing SWIG to rename the matching identifier''' self.write( '%rename({}) {}; {}\n'.format( newName, identifier, comment ) )
[ "def", "addSwigRename", "(", "self", ",", "identifier", ",", "newName", ",", "comment", "=", "''", ")", ":", "self", ".", "write", "(", "'%rename({}) {}; {}\\n'", ".", "format", "(", "newName", ",", "identifier", ",", "comment", ")", ")" ]
https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/generate_swig_interfaces.py#L159-L161
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/optparse.py
python
OptionContainer.destroy
(self)
see OptionParser.destroy().
see OptionParser.destroy().
[ "see", "OptionParser", ".", "destroy", "()", "." ]
def destroy(self): """see OptionParser.destroy().""" del self._short_opt del self._long_opt del self.defaults
[ "def", "destroy", "(", "self", ")", ":", "del", "self", ".", "_short_opt", "del", "self", ".", "_long_opt", "del", "self", ".", "defaults" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/optparse.py#L971-L975
xiaolonw/caffe-video_triplet
c39ea1ad6e937ccf7deba4510b7e555165abf05f
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 batch_blobs.iteritems(): all_outs[out].extend(out_blobs) for diff, out_diffs in batch_diffs.iteritems(): all_diffs[diff].extend(out_diffs) # 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(all_outs.itervalues().next()) - len(kwargs.itervalues().next()) 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", "....
https://github.com/xiaolonw/caffe-video_triplet/blob/c39ea1ad6e937ccf7deba4510b7e555165abf05f/python/caffe/pycaffe.py#L192-L234
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
rj_gameplay/stp/utils/world_state_converter.py
python
ballstate_to_ball
(ball_msg: msg.BallState)
return ball
:return: ball class representing the state of the ball.
:return: ball class representing the state of the ball.
[ ":", "return", ":", "ball", "class", "representing", "the", "state", "of", "the", "ball", "." ]
def ballstate_to_ball(ball_msg: msg.BallState) -> rc.Ball: """ :return: ball class representing the state of the ball. """ x = ball_msg.position.x y = ball_msg.position.y pos = np.array([x, y]) dx = ball_msg.velocity.x dy = ball_msg.velocity.y vel = np.array([dx, dy]) visible = ball_msg.visible ball = rc.Ball(pos, vel, visible) return ball
[ "def", "ballstate_to_ball", "(", "ball_msg", ":", "msg", ".", "BallState", ")", "->", "rc", ".", "Ball", ":", "x", "=", "ball_msg", ".", "position", ".", "x", "y", "=", "ball_msg", ".", "position", ".", "y", "pos", "=", "np", ".", "array", "(", "["...
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/utils/world_state_converter.py#L138-L153
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/buildbot/bb_utils.py
python
SpawnCmd
(command, stdout=None, cwd=CHROME_SRC)
return subprocess.Popen(command, cwd=cwd, stdout=stdout)
Spawn a process without waiting for termination.
Spawn a process without waiting for termination.
[ "Spawn", "a", "process", "without", "waiting", "for", "termination", "." ]
def SpawnCmd(command, stdout=None, cwd=CHROME_SRC): """Spawn a process without waiting for termination.""" print '>', CommandToString(command) sys.stdout.flush() if TESTING: class MockPopen(object): @staticmethod def wait(): return 0 @staticmethod def communicate(): return '', '' return MockPopen() return subprocess.Popen(command, cwd=cwd, stdout=stdout)
[ "def", "SpawnCmd", "(", "command", ",", "stdout", "=", "None", ",", "cwd", "=", "CHROME_SRC", ")", ":", "print", "'>'", ",", "CommandToString", "(", "command", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "if", "TESTING", ":", "class", "MockPopen...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/buildbot/bb_utils.py#L39-L52
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/pylinters.py
python
_fix_files
(linters, config_dict, file_names)
Fix a list of files with linters if possible.
Fix a list of files with linters if possible.
[ "Fix", "a", "list", "of", "files", "with", "linters", "if", "possible", "." ]
def _fix_files(linters, config_dict, file_names): # type: (str, Dict[str, str], List[str]) -> None """Fix a list of files with linters if possible.""" linter_list = get_py_linter(linters) # Get a list of linters which return a valid command for get_fix_cmd() fix_list = [fixer for fixer in linter_list if fixer.get_fix_cmd_args("ignore")] if not fix_list: raise ValueError("Cannot find any linters '%s' that support fixing." % (linters)) lint_runner = runner.LintRunner() linter_instances = runner.find_linters(fix_list, config_dict) if not linter_instances: sys.exit(1) for linter in linter_instances: run_linter = lambda param1: lint_runner.run(linter.cmd_path + linter.linter. # pylint: disable=cell-var-from-loop get_fix_cmd_args(param1)) # pylint: disable=cell-var-from-loop lint_clean = parallel.parallel_process([os.path.abspath(f) for f in file_names], run_linter) if not lint_clean: print("ERROR: Code Style does not match coding style") sys.exit(1)
[ "def", "_fix_files", "(", "linters", ",", "config_dict", ",", "file_names", ")", ":", "# type: (str, Dict[str, str], List[str]) -> None", "linter_list", "=", "get_py_linter", "(", "linters", ")", "# Get a list of linters which return a valid command for get_fix_cmd()", "fix_list"...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/pylinters.py#L131-L156
CaoWGG/TensorRT-CenterNet
f949252e37b51e60f873808f46d3683f15735e79
onnx-tensorrt/third_party/onnx/third_party/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/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L1359-L1363
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/input.py
python
EvalCondition
(condition, conditions_key, phase, variables, build_file)
return result
Returns the dict that should be used or None if the result was that nothing should be used.
Returns the dict that should be used or None if the result was that nothing should be used.
[ "Returns", "the", "dict", "that", "should", "be", "used", "or", "None", "if", "the", "result", "was", "that", "nothing", "should", "be", "used", "." ]
def EvalCondition(condition, conditions_key, phase, variables, build_file): """Returns the dict that should be used or None if the result was that nothing should be used.""" if type(condition) is not list: raise GypError(conditions_key + ' must be a list') if len(condition) < 2: # It's possible that condition[0] won't work in which case this # attempt will raise its own IndexError. That's probably fine. raise GypError(conditions_key + ' ' + condition[0] + ' must be at least length 2, not ' + str(len(condition))) i = 0 result = None while i < len(condition): cond_expr = condition[i] true_dict = condition[i + 1] if type(true_dict) is not dict: raise GypError('{} {} must be followed by a dictionary, not {}'.format( conditions_key, cond_expr, type(true_dict))) if len(condition) > i + 2 and type(condition[i + 2]) is dict: false_dict = condition[i + 2] i = i + 3 if i != len(condition): raise GypError('{} {} has {} unexpected trailing items'.format( conditions_key, cond_expr, len(condition) - i)) else: false_dict = None i = i + 2 if result == None: result = EvalSingleCondition( cond_expr, true_dict, false_dict, phase, variables, build_file) return result
[ "def", "EvalCondition", "(", "condition", ",", "conditions_key", ",", "phase", ",", "variables", ",", "build_file", ")", ":", "if", "type", "(", "condition", ")", "is", "not", "list", ":", "raise", "GypError", "(", "conditions_key", "+", "' must be a list'", ...
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/input.py#L1033-L1065
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/index.py
python
PackageIndex.get_sign_command
(self, filename, signer, sign_password, keystore=None)
return cmd, sf
Return a suitable command for signing a file. :param filename: The pathname to the file to be signed. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :param keystore: The path to a directory which contains the keys used in verification. If not specified, the instance's ``gpg_home`` attribute is used instead. :return: The signing command as a list suitable to be passed to :class:`subprocess.Popen`.
Return a suitable command for signing a file.
[ "Return", "a", "suitable", "command", "for", "signing", "a", "file", "." ]
def get_sign_command(self, filename, signer, sign_password, keystore=None): """ Return a suitable command for signing a file. :param filename: The pathname to the file to be signed. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :param keystore: The path to a directory which contains the keys used in verification. If not specified, the instance's ``gpg_home`` attribute is used instead. :return: The signing command as a list suitable to be passed to :class:`subprocess.Popen`. """ cmd = [self.gpg, '--status-fd', '2', '--no-tty'] if keystore is None: keystore = self.gpg_home if keystore: cmd.extend(['--homedir', keystore]) if sign_password is not None: cmd.extend(['--batch', '--passphrase-fd', '0']) td = tempfile.mkdtemp() sf = os.path.join(td, os.path.basename(filename) + '.asc') cmd.extend(['--detach-sign', '--armor', '--local-user', signer, '--output', sf, filename]) logger.debug('invoking: %s', ' '.join(cmd)) return cmd, sf
[ "def", "get_sign_command", "(", "self", ",", "filename", ",", "signer", ",", "sign_password", ",", "keystore", "=", "None", ")", ":", "cmd", "=", "[", "self", ".", "gpg", ",", "'--status-fd'", ",", "'2'", ",", "'--no-tty'", "]", "if", "keystore", "is", ...
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/distlib/index.py#L152-L179
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/serial/urlhandler/protocol_loop.py
python
Serial.cts
(self)
return self._rts_state
Read terminal status line: Clear To Send
Read terminal status line: Clear To Send
[ "Read", "terminal", "status", "line", ":", "Clear", "To", "Send" ]
def cts(self): """Read terminal status line: Clear To Send""" if not self.is_open: raise portNotOpenError if self.logger: self.logger.info('CTS -> state of RTS ({!r})'.format(self._rts_state)) return self._rts_state
[ "def", "cts", "(", "self", ")", ":", "if", "not", "self", ".", "is_open", ":", "raise", "portNotOpenError", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'CTS -> state of RTS ({!r})'", ".", "format", "(", "self", ".", "_rts_...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/urlhandler/protocol_loop.py#L247-L253
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Tools/framer/framer/util.py
python
unindent
(s, skipfirst=True)
return "\n".join(L)
Return an unindented version of a docstring. Removes indentation on lines following the first one, using the leading whitespace of the first indented line that is not blank to determine the indentation.
Return an unindented version of a docstring.
[ "Return", "an", "unindented", "version", "of", "a", "docstring", "." ]
def unindent(s, skipfirst=True): """Return an unindented version of a docstring. Removes indentation on lines following the first one, using the leading whitespace of the first indented line that is not blank to determine the indentation. """ lines = s.split("\n") if skipfirst: first = lines.pop(0) L = [first] else: L = [] indent = None for l in lines: ls = l.strip() if ls: indent = len(l) - len(ls) break L += [l[indent:] for l in lines] return "\n".join(L)
[ "def", "unindent", "(", "s", ",", "skipfirst", "=", "True", ")", ":", "lines", "=", "s", ".", "split", "(", "\"\\n\"", ")", "if", "skipfirst", ":", "first", "=", "lines", ".", "pop", "(", "0", ")", "L", "=", "[", "first", "]", "else", ":", "L",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/framer/framer/util.py#L13-L35
eldar/deepcut-cnn
928bf2f224fce132f6e4404b4c95fb017297a5e0
python/caffe/detector.py
python
Detector.detect_selective_search
(self, image_fnames)
return self.detect_windows(zip(image_fnames, windows_list))
Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net. Parameters ---------- image_fnames: list Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts.
Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net.
[ "Do", "windowed", "detection", "over", "Selective", "Search", "proposals", "by", "extracting", "the", "crop", "and", "warping", "to", "the", "input", "dimensions", "of", "the", "net", "." ]
def detect_selective_search(self, image_fnames): """ Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net. Parameters ---------- image_fnames: list Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts. """ import selective_search_ijcv_with_python as selective_search # Make absolute paths so MATLAB can find the files. image_fnames = [os.path.abspath(f) for f in image_fnames] windows_list = selective_search.get_windows( image_fnames, cmd='selective_search_rcnn' ) # Run windowed detection on the selective search list. return self.detect_windows(zip(image_fnames, windows_list))
[ "def", "detect_selective_search", "(", "self", ",", "image_fnames", ")", ":", "import", "selective_search_ijcv_with_python", "as", "selective_search", "# Make absolute paths so MATLAB can find the files.", "image_fnames", "=", "[", "os", ".", "path", ".", "abspath", "(", ...
https://github.com/eldar/deepcut-cnn/blob/928bf2f224fce132f6e4404b4c95fb017297a5e0/python/caffe/detector.py#L101-L123
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/xrc.py
python
XmlResourceHandler.CreateResource
(*args, **kwargs)
return _xrc.XmlResourceHandler_CreateResource(*args, **kwargs)
CreateResource(self, XmlNode node, Object parent, Object instance) -> Object
CreateResource(self, XmlNode node, Object parent, Object instance) -> Object
[ "CreateResource", "(", "self", "XmlNode", "node", "Object", "parent", "Object", "instance", ")", "-", ">", "Object" ]
def CreateResource(*args, **kwargs): """CreateResource(self, XmlNode node, Object parent, Object instance) -> Object""" return _xrc.XmlResourceHandler_CreateResource(*args, **kwargs)
[ "def", "CreateResource", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlResourceHandler_CreateResource", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/xrc.py#L595-L597
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/distributed_c10d.py
python
broadcast_multigpu
(tensor_list, src, group=None, async_op=False, src_tensor=0)
Broadcasts the tensor to the whole group with multiple GPU tensors per node. ``tensor`` must have the same number of elements in all the GPUs from all processes participating in the collective. each tensor in the list must be on a different GPU Only nccl and gloo backend are currently supported tensors should only be GPU tensors Args: tensor_list (List[Tensor]): Tensors that participate in the collective operation. If ``src`` is the rank, then the specified ``src_tensor`` element of ``tensor_list`` (``tensor_list[src_tensor]``) will be broadcast to all other tensors (on different GPUs) in the src process and all tensors in ``tensor_list`` of other non-src processes. You also need to make sure that ``len(tensor_list)`` is the same for all the distributed processes calling this function. src (int): Source rank. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. async_op (bool, optional): Whether this op should be an async op src_tensor (int, optional): Source tensor rank within ``tensor_list`` Returns: Async work handle, if async_op is set to True. None, if not async_op or if not part of the group
Broadcasts the tensor to the whole group with multiple GPU tensors per node.
[ "Broadcasts", "the", "tensor", "to", "the", "whole", "group", "with", "multiple", "GPU", "tensors", "per", "node", "." ]
def broadcast_multigpu(tensor_list, src, group=None, async_op=False, src_tensor=0): """ Broadcasts the tensor to the whole group with multiple GPU tensors per node. ``tensor`` must have the same number of elements in all the GPUs from all processes participating in the collective. each tensor in the list must be on a different GPU Only nccl and gloo backend are currently supported tensors should only be GPU tensors Args: tensor_list (List[Tensor]): Tensors that participate in the collective operation. If ``src`` is the rank, then the specified ``src_tensor`` element of ``tensor_list`` (``tensor_list[src_tensor]``) will be broadcast to all other tensors (on different GPUs) in the src process and all tensors in ``tensor_list`` of other non-src processes. You also need to make sure that ``len(tensor_list)`` is the same for all the distributed processes calling this function. src (int): Source rank. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. async_op (bool, optional): Whether this op should be an async op src_tensor (int, optional): Source tensor rank within ``tensor_list`` Returns: Async work handle, if async_op is set to True. None, if not async_op or if not part of the group """ if _rank_not_in_group(group): _warn_not_in_group("broadcast_multigpu") return opts = BroadcastOptions() opts.rootRank = src opts.rootTensor = src_tensor if group is None or group is GroupMember.WORLD: default_pg = _get_default_group() work = default_pg.broadcast(tensor_list, opts) else: group_src_rank = _get_group_rank(group, src) opts.rootRank = group_src_rank work = group.broadcast(tensor_list, opts) if async_op: return work else: work.wait()
[ "def", "broadcast_multigpu", "(", "tensor_list", ",", "src", ",", "group", "=", "None", ",", "async_op", "=", "False", ",", "src_tensor", "=", "0", ")", ":", "if", "_rank_not_in_group", "(", "group", ")", ":", "_warn_not_in_group", "(", "\"broadcast_multigpu\"...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/distributed_c10d.py#L1103-L1153
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/cpp_lint.py
python
_ShouldPrintError
(category, confidence, linenum)
return True
If confidence >= verbose, category passes filter and is not suppressed.
If confidence >= verbose, category passes filter and is not suppressed.
[ "If", "confidence", ">", "=", "verbose", "category", "passes", "filter", "and", "is", "not", "suppressed", "." ]
def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True
[ "def", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "# There are three ways we might decide not to print an error message:", "# a \"NOLINT(category)\" comment appears in the source,", "# the verbosity level isn't high enough, or the filters filter it out...
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/cpp_lint.py#L961-L985
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
TreeItemId.__init__
(self, *args, **kwargs)
__init__(self) -> TreeItemId
__init__(self) -> TreeItemId
[ "__init__", "(", "self", ")", "-", ">", "TreeItemId" ]
def __init__(self, *args, **kwargs): """__init__(self) -> TreeItemId""" _controls_.TreeItemId_swiginit(self,_controls_.new_TreeItemId(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_controls_", ".", "TreeItemId_swiginit", "(", "self", ",", "_controls_", ".", "new_TreeItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4996-L4998
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.GetLength
(*args, **kwargs)
return _stc.StyledTextCtrl_GetLength(*args, **kwargs)
GetLength(self) -> int Returns the number of bytes in the document.
GetLength(self) -> int
[ "GetLength", "(", "self", ")", "-", ">", "int" ]
def GetLength(*args, **kwargs): """ GetLength(self) -> int Returns the number of bytes in the document. """ return _stc.StyledTextCtrl_GetLength(*args, **kwargs)
[ "def", "GetLength", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetLength", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2079-L2085
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/cachecontrol/serialize.py
python
Serializer.prepare_response
(self, request, cached)
return HTTPResponse(body=body, preload_content=False, **cached["response"])
Verify our vary headers match and construct a real urllib3 HTTPResponse object.
Verify our vary headers match and construct a real urllib3 HTTPResponse object.
[ "Verify", "our", "vary", "headers", "match", "and", "construct", "a", "real", "urllib3", "HTTPResponse", "object", "." ]
def prepare_response(self, request, cached): """Verify our vary headers match and construct a real urllib3 HTTPResponse object. """ # Special case the '*' Vary value as it means we cannot actually # determine if the cached response is suitable for this request. # This case is also handled in the controller code when creating # a cache entry, but is left here for backwards compatibility. if "*" in cached.get("vary", {}): return # Ensure that the Vary headers for the cached response match our # request for header, value in cached.get("vary", {}).items(): if request.headers.get(header, None) != value: return body_raw = cached["response"].pop("body") headers = CaseInsensitiveDict(data=cached["response"]["headers"]) if headers.get("transfer-encoding", "") == "chunked": headers.pop("transfer-encoding") cached["response"]["headers"] = headers try: body = io.BytesIO(body_raw) except TypeError: # This can happen if cachecontrol serialized to v1 format (pickle) # using Python 2. A Python 2 str(byte string) will be unpickled as # a Python 3 str (unicode string), which will cause the above to # fail with: # # TypeError: 'str' does not support the buffer interface body = io.BytesIO(body_raw.encode("utf8")) return HTTPResponse(body=body, preload_content=False, **cached["response"])
[ "def", "prepare_response", "(", "self", ",", "request", ",", "cached", ")", ":", "# Special case the '*' Vary value as it means we cannot actually", "# determine if the cached response is suitable for this request.", "# This case is also handled in the controller code when creating", "# a ...
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/_vendor/cachecontrol/serialize.py#L104-L140
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
BookCtrlBase.SetPageText
(*args, **kwargs)
return _core_.BookCtrlBase_SetPageText(*args, **kwargs)
SetPageText(self, size_t n, String strText) -> bool
SetPageText(self, size_t n, String strText) -> bool
[ "SetPageText", "(", "self", "size_t", "n", "String", "strText", ")", "-", ">", "bool" ]
def SetPageText(*args, **kwargs): """SetPageText(self, size_t n, String strText) -> bool""" return _core_.BookCtrlBase_SetPageText(*args, **kwargs)
[ "def", "SetPageText", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "BookCtrlBase_SetPageText", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13550-L13552
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Script/Interactive.py
python
SConsInteractiveCmd.do_clean
(self, argv)
return self.do_build(['build', '--clean'] + argv[1:])
\ clean [TARGETS] Clean (remove) the specified TARGETS and their dependencies. 'c' is a synonym.
\ clean [TARGETS] Clean (remove) the specified TARGETS and their dependencies. 'c' is a synonym.
[ "\\", "clean", "[", "TARGETS", "]", "Clean", "(", "remove", ")", "the", "specified", "TARGETS", "and", "their", "dependencies", ".", "c", "is", "a", "synonym", "." ]
def do_clean(self, argv): """\ clean [TARGETS] Clean (remove) the specified TARGETS and their dependencies. 'c' is a synonym. """ return self.do_build(['build', '--clean'] + argv[1:])
[ "def", "do_clean", "(", "self", ",", "argv", ")", ":", "return", "self", ".", "do_build", "(", "[", "'build'", ",", "'--clean'", "]", "+", "argv", "[", "1", ":", "]", ")" ]
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/Script/Interactive.py#L269-L274
CanalTP/navitia
cb84ce9859070187e708818b058e6a7e0b7f891b
source/tyr/tyr/tasks.py
python
import_autocomplete
(files, autocomplete_instance, asynchronous=True, backup_file=True)
Import the autocomplete'instance data files
Import the autocomplete'instance data files
[ "Import", "the", "autocomplete", "instance", "data", "files" ]
def import_autocomplete(files, autocomplete_instance, asynchronous=True, backup_file=True): """ Import the autocomplete'instance data files """ job = models.Job() job.state = 'running' actions = [] task = { 'bano': {2: bano2mimir, 7: bano2mimir}, 'oa': {2: openaddresses2mimir, 7: openaddresses2mimir}, 'osm': {2: osm2mimir, 7: osm2mimir}, 'cosmogony': {2: cosmogony2mimir, 7: cosmogony2mimir}, } autocomplete_dir = current_app.config['TYR_AUTOCOMPLETE_DIR'] # it's important for the admin to be loaded first, then addresses, then street, then poi import_order = ['cosmogony', 'bano', 'oa', 'osm'] files_and_types = [(f, type_of_autocomplete_data(f)) for f in files] files_and_types = sorted(files_and_types, key=lambda f_t: import_order.index(f_t[1])) for f, ftype in files_and_types: if ftype not in task: # unknown type, we skip it current_app.logger.debug("unknown file type: {} for file {}".format(ftype, f)) continue filename = f if backup_file: filename = move_to_backupdirectory( f, autocomplete_instance.backup_dir(autocomplete_dir), manage_sp_char=True ) for version, executable in task[ftype].items(): if not is_activate_autocomplete_version(version): current_app.logger.debug("Autocomplete version {} is disableed".format(version)) continue dataset = create_and_get_dataset( ds_type=ftype, family_type='autocomplete_{}'.format(ftype), filename=filename ) actions.append( executable.si( autocomplete_instance, filename=filename, job_id=job.id, dataset_uid=dataset.uid, autocomplete_version=version, ) ) models.db.session.add(dataset) job.data_sets.append(dataset) job.autocomplete_params_id = autocomplete_instance.id if not actions: return models.db.session.add(job) models.db.session.commit() for action in actions: action.kwargs['job_id'] = job.id actions.append(finish_job.si(job.id)) if asynchronous: return chain(*actions).delay(), job else: # all job are run in sequence and import_data will only return when all the jobs are finish return chain(*actions).apply(), job
[ "def", "import_autocomplete", "(", "files", ",", "autocomplete_instance", ",", "asynchronous", "=", "True", ",", "backup_file", "=", "True", ")", ":", "job", "=", "models", ".", "Job", "(", ")", "job", ".", "state", "=", "'running'", "actions", "=", "[", ...
https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/tyr/tyr/tasks.py#L330-L393
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
isXHTML
(systemID, publicID)
return ret
Try to find if the document correspond to an XHTML DTD
Try to find if the document correspond to an XHTML DTD
[ "Try", "to", "find", "if", "the", "document", "correspond", "to", "an", "XHTML", "DTD" ]
def isXHTML(systemID, publicID): """Try to find if the document correspond to an XHTML DTD """ ret = libxml2mod.xmlIsXHTML(systemID, publicID) return ret
[ "def", "isXHTML", "(", "systemID", ",", "publicID", ")", ":", "ret", "=", "libxml2mod", ".", "xmlIsXHTML", "(", "systemID", ",", "publicID", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L1672-L1675
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/ndarray/ndarray.py
python
NDArray.size_array
(self, *args, **kwargs)
return op.size_array(self, *args, **kwargs)
Convenience fluent method for :py:func:`size_array`. The arguments are the same as for :py:func:`size_array`, with this array as data.
Convenience fluent method for :py:func:`size_array`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "size_array", "." ]
def size_array(self, *args, **kwargs): """Convenience fluent method for :py:func:`size_array`. The arguments are the same as for :py:func:`size_array`, with this array as data. """ return op.size_array(self, *args, **kwargs)
[ "def", "size_array", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "size_array", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L1294-L1300
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/__init__.py
python
IndigoObject.iterateTGroups
(self)
return self.dispatcher.IndigoObject( self.dispatcher, self.dispatcher._checkResult( Indigo._lib.indigoIterateTGroups(self.id) ), )
Molecule method iterates t-groups Returns: IndigoObject: t-groups iterator
Molecule method iterates t-groups
[ "Molecule", "method", "iterates", "t", "-", "groups" ]
def iterateTGroups(self): """Molecule method iterates t-groups Returns: IndigoObject: t-groups iterator """ self.dispatcher._setSessionId() return self.dispatcher.IndigoObject( self.dispatcher, self.dispatcher._checkResult( Indigo._lib.indigoIterateTGroups(self.id) ), )
[ "def", "iterateTGroups", "(", "self", ")", ":", "self", ".", "dispatcher", ".", "_setSessionId", "(", ")", "return", "self", ".", "dispatcher", ".", "IndigoObject", "(", "self", ".", "dispatcher", ",", "self", ".", "dispatcher", ".", "_checkResult", "(", "...
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L1444-L1456
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Sizer.InsertF
(*args, **kwargs)
return _core_.Sizer_InsertF(*args, **kwargs)
InsertF(self, int before, item, wx.SizerFlags flags) -> wx.SizerItem Similar to `Insert`, but uses the `wx.SizerFlags` convenience class for setting the various flags, options and borders.
InsertF(self, int before, item, wx.SizerFlags flags) -> wx.SizerItem
[ "InsertF", "(", "self", "int", "before", "item", "wx", ".", "SizerFlags", "flags", ")", "-", ">", "wx", ".", "SizerItem" ]
def InsertF(*args, **kwargs): """ InsertF(self, int before, item, wx.SizerFlags flags) -> wx.SizerItem Similar to `Insert`, but uses the `wx.SizerFlags` convenience class for setting the various flags, options and borders. """ return _core_.Sizer_InsertF(*args, **kwargs)
[ "def", "InsertF", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Sizer_InsertF", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L14482-L14489
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/layer1.py
python
DynamoDBConnection.update_item
(self, table_name, key, attribute_updates=None, expected=None, conditional_operator=None, return_values=None, return_consumed_capacity=None, return_item_collection_metrics=None, update_expression=None, condition_expression=None, expression_attribute_names=None, expression_attribute_values=None)
return self.make_request(action='UpdateItem', body=json.dumps(params))
Edits an existing item's attributes, or adds a new item to the table if it does not already exist. You can put, delete, or add attribute values. You can also perform a conditional update (insert a new attribute name-value pair if it doesn't exist, or replace an existing name-value pair if it has certain expected attribute values). You can also return the item's attribute values in the same UpdateItem operation using the ReturnValues parameter. :type table_name: string :param table_name: The name of the table containing the item to update. :type key: map :param key: The primary key of the item to be updated. Each element consists of an attribute name and a value for that attribute. For the primary key, you must provide all of the attributes. For example, with a hash type primary key, you only need to specify the hash attribute. For a hash-and-range type primary key, you must specify both the hash attribute and the range attribute. :type attribute_updates: map :param attribute_updates: There is a newer parameter available. Use UpdateExpression instead. Note that if you use AttributeUpdates and UpdateExpression at the same time, DynamoDB will return a ValidationException exception. This parameter can be used for modifying top-level attributes; however, it does not support individual list or map elements. The names of attributes to be modified, the action to perform on each, and the new value for each. If you are updating an attribute that is an index key attribute for any indexes on that table, the attribute type must match the index key type defined in the AttributesDefinition of the table description. You can use UpdateItem to update any nonkey attributes. Attribute values cannot be null. String and Binary type attributes must have lengths greater than zero. Set type attributes must not be empty. Requests with empty values will be rejected with a ValidationException exception. Each AttributeUpdates element consists of an attribute name to modify, along with the following: + Value - The new value, if applicable, for this attribute. + Action - A value that specifies how to perform the update. This action is only valid for an existing attribute whose data type is Number or is a set; do not use `ADD` for other data types. If an item with the specified primary key is found in the table, the following values perform the following actions: + `PUT` - Adds the specified attribute to the item. If the attribute already exists, it is replaced by the new value. + `DELETE` - Removes the attribute and its value, if no value is specified for `DELETE`. The data type of the specified value must match the existing value's data type. If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set `[a,b,c]` and the `DELETE` action specifies `[a,c]`, then the final attribute value is `[b]`. Specifying an empty set is an error. + `ADD` - Adds the specified value to the item, if the attribute does not already exist. If the attribute does exist, then the behavior of `ADD` depends on the data type of the attribute: + If the existing attribute is a number, and if Value is also a number, then Value is mathematically added to the existing attribute. If Value is a negative number, then it is subtracted from the existing attribute. If you use `ADD` to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses 0 as the initial value. Similarly, if you use `ADD` for an existing item to increment or decrement an attribute value that doesn't exist before the update, DynamoDB uses `0` as the initial value. For example, suppose that the item you want to update doesn't have an attribute named itemcount , but you decide to `ADD` the number `3` to this attribute anyway. DynamoDB will create the itemcount attribute, set its initial value to `0`, and finally add `3` to it. The result will be a new itemcount attribute, with a value of `3`. + If the existing data type is a set, and if Value is also a set, then Value is appended to the existing set. For example, if the attribute value is the set `[1,2]`, and the `ADD` action specified `[3]`, then the final attribute value is `[1,2,3]`. An error occurs if an `ADD` action is specified for a set attribute and the attribute type specified does not match the existing set type. Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, Value must also be a set of strings. If no item with the specified key is found in the table, the following values perform the following actions: + `PUT` - Causes DynamoDB to create a new item with the specified primary key, and then adds the attribute. + `DELETE` - Nothing happens, because attributes cannot be deleted from a nonexistent item. The operation succeeds, but DynamoDB does not create a new item. + `ADD` - Causes DynamoDB to create an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types allowed are Number and Number Set. If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition. :type expected: map :param expected: There is a newer parameter available. Use ConditionExpression instead. Note that if you use Expected and ConditionExpression at the same time, DynamoDB will return a ValidationException exception. This parameter does not support lists or maps. A map of attribute/condition pairs. Expected provides a conditional block for the UpdateItem operation. Each element of Expected consists of an attribute name, a comparison operator, and one or more values. DynamoDB compares the attribute with the value(s) you supplied, using the comparison operator. For each Expected element, the result of the evaluation is either true or false. If you specify more than one element in the Expected map, then by default all of the conditions must evaluate to true. In other words, the conditions are ANDed together. (You can use the ConditionalOperator parameter to OR the conditions instead. If you do this, then at least one of the conditions must evaluate to true, rather than all of them.) If the Expected map evaluates to true, then the conditional operation succeeds; otherwise, it fails. Expected contains the following: + AttributeValueList - One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used. For type Number, value comparisons are numeric. String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, `a` is greater than `A`, and `a` is greater than `B`. For a list of code values, see `http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters`_. For type Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values, for example when evaluating query expressions. + ComparisonOperator - A comparator for evaluating attributes in the AttributeValueList . When performing the comparison, DynamoDB uses strongly consistent reads. The following comparison operators are available: `EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN` The following are descriptions of each comparison operator. + `EQ` : Equal. `EQ` is supported for all datatypes, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not equal `{"NS":["6", "2", "1"]}`. > <li> + `NE` : Not equal. `NE` is supported for all datatypes, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not equal `{"NS":["6", "2", "1"]}`. > <li> + `LE` : Less than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}`. > <li> + `LT` : Less than. AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}`. > <li> + `GE` : Greater than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}`. > <li> + `GT` : Greater than. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}`. > <li> + `NOT_NULL` : The attribute exists. `NOT_NULL` is supported for all datatypes, including lists and maps. This operator tests for the existence of an attribute, not its data type. If the data type of attribute " `a`" is null, and you evaluate it using `NOT_NULL`, the result is a Boolean true . This result is because the attribute " `a`" exists; its data type is not relevant to the `NOT_NULL` comparison operator. + `NULL` : The attribute does not exist. `NULL` is supported for all datatypes, including lists and maps. This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute " `a`" is null, and you evaluate it using `NULL`, the result is a Boolean false . This is because the attribute " `a`" exists; its data type is not relevant to the `NULL` comparison operator. + `CONTAINS` : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set (" `SS`", " `NS`", or " `BS`"), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating " `a CONTAINS b`", " `a`" can be a list; however, " `b`" cannot be a set, a map, or a list. + `NOT_CONTAINS` : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set (" `SS`", " `NS`", or " `BS`"), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating " `a NOT CONTAINS b`", " `a`" can be a list; however, " `b`" cannot be a set, a map, or a list. + `BEGINS_WITH` : Checks for a prefix. AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type). > <li> + `IN` : Checks for matching elements within two sets. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary (not a set type). These attributes are compared against an existing set type attribute of an item. If any elements of the input set are present in the item attribute, the expression evaluates to true. + `BETWEEN` : Greater than or equal to the first value, and less than or equal to the second value. AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not compare to `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}` For usage examples of AttributeValueList and ComparisonOperator , see `Legacy Conditional Parameters`_ in the Amazon DynamoDB Developer Guide . For backward compatibility with previous DynamoDB releases, the following parameters can be used instead of AttributeValueList and ComparisonOperator : + Value - A value for DynamoDB to compare with an attribute. + Exists - A Boolean value that causes DynamoDB to evaluate the value before attempting the conditional operation: + If Exists is `True`, DynamoDB will check to see if that attribute value already exists in the table. If it is found, then the condition evaluates to true; otherwise the condition evaluate to false. + If Exists is `False`, DynamoDB assumes that the attribute value does not exist in the table. If in fact the value does not exist, then the assumption is valid and the condition evaluates to true. If the value is found, despite the assumption that it does not exist, the condition evaluates to false. Note that the default value for Exists is `True`. The Value and Exists parameters are incompatible with AttributeValueList and ComparisonOperator . Note that if you use both sets of parameters at once, DynamoDB will return a ValidationException exception. :type conditional_operator: string :param conditional_operator: There is a newer parameter available. Use ConditionExpression instead. Note that if you use ConditionalOperator and ConditionExpression at the same time, DynamoDB will return a ValidationException exception. This parameter does not support lists or maps. A logical operator to apply to the conditions in the Expected map: + `AND` - If all of the conditions evaluate to true, then the entire map evaluates to true. + `OR` - If at least one of the conditions evaluate to true, then the entire map evaluates to true. If you omit ConditionalOperator , then `AND` is the default. The operation will succeed only if the entire map evaluates to true. :type return_values: string :param return_values: Use ReturnValues if you want to get the item attributes as they appeared either before or after they were updated. For UpdateItem , the valid values are: + `NONE` - If ReturnValues is not specified, or if its value is `NONE`, then nothing is returned. (This setting is the default for ReturnValues .) + `ALL_OLD` - If UpdateItem overwrote an attribute name-value pair, then the content of the old item is returned. + `UPDATED_OLD` - The old versions of only the updated attributes are returned. + `ALL_NEW` - All of the attributes of the new version of the item are returned. + `UPDATED_NEW` - The new versions of only the updated attributes are returned. :type return_consumed_capacity: string :param return_consumed_capacity: A value that if set to `TOTAL`, the response includes ConsumedCapacity data for tables and indexes. If set to `INDEXES`, the response includes ConsumedCapacity for indexes. If set to `NONE` (the default), ConsumedCapacity is not included in the response. :type return_item_collection_metrics: string :param return_item_collection_metrics: A value that if set to `SIZE`, the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to `NONE` (the default), no statistics are returned. :type update_expression: string :param update_expression: An expression that defines one or more attributes to be updated, the action to be performed on them, and new value(s) for them. The following action values are available for UpdateExpression . + `SET` - Adds one or more attributes and values to an item. If any of these attribute already exist, they are replaced by the new values. You can also use `SET` to add or subtract from an attribute that is of type Number. `SET` supports the following functions: + `if_not_exists (path, operand)` - if the item does not contain an attribute at the specified path, then `if_not_exists` evaluates to operand; otherwise, it evaluates to path. You can use this function to avoid overwriting an attribute that may already be present in the item. + `list_append (operand, operand)` - evaluates to a list with a new element added to it. You can append the new element to the start or the end of the list by reversing the order of the operands. These function names are case-sensitive. + `REMOVE` - Removes one or more attributes from an item. + `ADD` - Adds the specified value to the item, if the attribute does not already exist. If the attribute does exist, then the behavior of `ADD` depends on the data type of the attribute: + If the existing attribute is a number, and if Value is also a number, then Value is mathematically added to the existing attribute. If Value is a negative number, then it is subtracted from the existing attribute. If you use `ADD` to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses `0` as the initial value. Similarly, if you use `ADD` for an existing item to increment or decrement an attribute value that doesn't exist before the update, DynamoDB uses `0` as the initial value. For example, suppose that the item you want to update doesn't have an attribute named itemcount , but you decide to `ADD` the number `3` to this attribute anyway. DynamoDB will create the itemcount attribute, set its initial value to `0`, and finally add `3` to it. The result will be a new itemcount attribute in the item, with a value of `3`. + If the existing data type is a set and if Value is also a set, then Value is added to the existing set. For example, if the attribute value is the set `[1,2]`, and the `ADD` action specified `[3]`, then the final attribute value is `[1,2,3]`. An error occurs if an `ADD` action is specified for a set attribute and the attribute type specified does not match the existing set type. Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, the Value must also be a set of strings. The `ADD` action only supports Number and set data types. In addition, `ADD` can only be used on top-level attributes, not nested attributes. + `DELETE` - Deletes an element from a set. If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set `[a,b,c]` and the `DELETE` action specifies `[a,c]`, then the final attribute value is `[b]`. Specifying an empty set is an error. The `DELETE` action only supports Number and set data types. In addition, `DELETE` can only be used on top-level attributes, not nested attributes. You can have many actions in a single expression, such as the following: `SET a=:value1, b=:value2 DELETE :value3, :value4, :value5` For more information on update expressions, go to `Modifying Items and Attributes`_ in the Amazon DynamoDB Developer Guide . :type condition_expression: string :param condition_expression: A condition that must be satisfied in order for a conditional update to succeed. An expression can contain any of the following: + Boolean functions: `attribute_exists | attribute_not_exists | contains | begins_with` These function names are case-sensitive. + Comparison operators: ` = | <> | < | > | <= | >= | BETWEEN | IN` + Logical operators: `AND | OR | NOT` For more information on condition expressions, go to `Specifying Conditions`_ in the Amazon DynamoDB Developer Guide . :type expression_attribute_names: map :param expression_attribute_names: One or more substitution tokens for simplifying complex expressions. The following are some use cases for using ExpressionAttributeNames : + To shorten an attribute name that is very long or unwieldy in an expression. + To create a placeholder for repeating occurrences of an attribute name in an expression. + To prevent special characters in an attribute name from being misinterpreted in an expression. Use the **#** character in an expression to dereference an attribute name. For example, consider the following expression: + `order.customerInfo.LastName = "Smith" OR order.customerInfo.LastName = "Jones"` Now suppose that you specified the following for ExpressionAttributeNames : + `{"#name":"order.customerInfo.LastName"}` The expression can now be simplified as follows: + `#name = "Smith" OR #name = "Jones"` For more information on expression attribute names, go to `Accessing Item Attributes`_ in the Amazon DynamoDB Developer Guide . :type expression_attribute_values: map :param expression_attribute_values: One or more values that can be substituted in an expression. Use the **:** (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following: `Available | Backordered | Discontinued` You would first need to specify ExpressionAttributeValues as follows: `{ ":avail":{"S":"Available"}, ":back":{"S":"Backordered"}, ":disc":{"S":"Discontinued"} }` You could then use these values in an expression, such as this: `ProductStatus IN (:avail, :back, :disc)` For more information on expression attribute values, go to `Specifying Conditions`_ in the Amazon DynamoDB Developer Guide .
Edits an existing item's attributes, or adds a new item to the table if it does not already exist. You can put, delete, or add attribute values. You can also perform a conditional update (insert a new attribute name-value pair if it doesn't exist, or replace an existing name-value pair if it has certain expected attribute values).
[ "Edits", "an", "existing", "item", "s", "attributes", "or", "adds", "a", "new", "item", "to", "the", "table", "if", "it", "does", "not", "already", "exist", ".", "You", "can", "put", "delete", "or", "add", "attribute", "values", ".", "You", "can", "als...
def update_item(self, table_name, key, attribute_updates=None, expected=None, conditional_operator=None, return_values=None, return_consumed_capacity=None, return_item_collection_metrics=None, update_expression=None, condition_expression=None, expression_attribute_names=None, expression_attribute_values=None): """ Edits an existing item's attributes, or adds a new item to the table if it does not already exist. You can put, delete, or add attribute values. You can also perform a conditional update (insert a new attribute name-value pair if it doesn't exist, or replace an existing name-value pair if it has certain expected attribute values). You can also return the item's attribute values in the same UpdateItem operation using the ReturnValues parameter. :type table_name: string :param table_name: The name of the table containing the item to update. :type key: map :param key: The primary key of the item to be updated. Each element consists of an attribute name and a value for that attribute. For the primary key, you must provide all of the attributes. For example, with a hash type primary key, you only need to specify the hash attribute. For a hash-and-range type primary key, you must specify both the hash attribute and the range attribute. :type attribute_updates: map :param attribute_updates: There is a newer parameter available. Use UpdateExpression instead. Note that if you use AttributeUpdates and UpdateExpression at the same time, DynamoDB will return a ValidationException exception. This parameter can be used for modifying top-level attributes; however, it does not support individual list or map elements. The names of attributes to be modified, the action to perform on each, and the new value for each. If you are updating an attribute that is an index key attribute for any indexes on that table, the attribute type must match the index key type defined in the AttributesDefinition of the table description. You can use UpdateItem to update any nonkey attributes. Attribute values cannot be null. String and Binary type attributes must have lengths greater than zero. Set type attributes must not be empty. Requests with empty values will be rejected with a ValidationException exception. Each AttributeUpdates element consists of an attribute name to modify, along with the following: + Value - The new value, if applicable, for this attribute. + Action - A value that specifies how to perform the update. This action is only valid for an existing attribute whose data type is Number or is a set; do not use `ADD` for other data types. If an item with the specified primary key is found in the table, the following values perform the following actions: + `PUT` - Adds the specified attribute to the item. If the attribute already exists, it is replaced by the new value. + `DELETE` - Removes the attribute and its value, if no value is specified for `DELETE`. The data type of the specified value must match the existing value's data type. If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set `[a,b,c]` and the `DELETE` action specifies `[a,c]`, then the final attribute value is `[b]`. Specifying an empty set is an error. + `ADD` - Adds the specified value to the item, if the attribute does not already exist. If the attribute does exist, then the behavior of `ADD` depends on the data type of the attribute: + If the existing attribute is a number, and if Value is also a number, then Value is mathematically added to the existing attribute. If Value is a negative number, then it is subtracted from the existing attribute. If you use `ADD` to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses 0 as the initial value. Similarly, if you use `ADD` for an existing item to increment or decrement an attribute value that doesn't exist before the update, DynamoDB uses `0` as the initial value. For example, suppose that the item you want to update doesn't have an attribute named itemcount , but you decide to `ADD` the number `3` to this attribute anyway. DynamoDB will create the itemcount attribute, set its initial value to `0`, and finally add `3` to it. The result will be a new itemcount attribute, with a value of `3`. + If the existing data type is a set, and if Value is also a set, then Value is appended to the existing set. For example, if the attribute value is the set `[1,2]`, and the `ADD` action specified `[3]`, then the final attribute value is `[1,2,3]`. An error occurs if an `ADD` action is specified for a set attribute and the attribute type specified does not match the existing set type. Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, Value must also be a set of strings. If no item with the specified key is found in the table, the following values perform the following actions: + `PUT` - Causes DynamoDB to create a new item with the specified primary key, and then adds the attribute. + `DELETE` - Nothing happens, because attributes cannot be deleted from a nonexistent item. The operation succeeds, but DynamoDB does not create a new item. + `ADD` - Causes DynamoDB to create an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types allowed are Number and Number Set. If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition. :type expected: map :param expected: There is a newer parameter available. Use ConditionExpression instead. Note that if you use Expected and ConditionExpression at the same time, DynamoDB will return a ValidationException exception. This parameter does not support lists or maps. A map of attribute/condition pairs. Expected provides a conditional block for the UpdateItem operation. Each element of Expected consists of an attribute name, a comparison operator, and one or more values. DynamoDB compares the attribute with the value(s) you supplied, using the comparison operator. For each Expected element, the result of the evaluation is either true or false. If you specify more than one element in the Expected map, then by default all of the conditions must evaluate to true. In other words, the conditions are ANDed together. (You can use the ConditionalOperator parameter to OR the conditions instead. If you do this, then at least one of the conditions must evaluate to true, rather than all of them.) If the Expected map evaluates to true, then the conditional operation succeeds; otherwise, it fails. Expected contains the following: + AttributeValueList - One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used. For type Number, value comparisons are numeric. String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, `a` is greater than `A`, and `a` is greater than `B`. For a list of code values, see `http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters`_. For type Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values, for example when evaluating query expressions. + ComparisonOperator - A comparator for evaluating attributes in the AttributeValueList . When performing the comparison, DynamoDB uses strongly consistent reads. The following comparison operators are available: `EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN` The following are descriptions of each comparison operator. + `EQ` : Equal. `EQ` is supported for all datatypes, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not equal `{"NS":["6", "2", "1"]}`. > <li> + `NE` : Not equal. `NE` is supported for all datatypes, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not equal `{"NS":["6", "2", "1"]}`. > <li> + `LE` : Less than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}`. > <li> + `LT` : Less than. AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}`. > <li> + `GE` : Greater than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}`. > <li> + `GT` : Greater than. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}`. > <li> + `NOT_NULL` : The attribute exists. `NOT_NULL` is supported for all datatypes, including lists and maps. This operator tests for the existence of an attribute, not its data type. If the data type of attribute " `a`" is null, and you evaluate it using `NOT_NULL`, the result is a Boolean true . This result is because the attribute " `a`" exists; its data type is not relevant to the `NOT_NULL` comparison operator. + `NULL` : The attribute does not exist. `NULL` is supported for all datatypes, including lists and maps. This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute " `a`" is null, and you evaluate it using `NULL`, the result is a Boolean false . This is because the attribute " `a`" exists; its data type is not relevant to the `NULL` comparison operator. + `CONTAINS` : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set (" `SS`", " `NS`", or " `BS`"), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating " `a CONTAINS b`", " `a`" can be a list; however, " `b`" cannot be a set, a map, or a list. + `NOT_CONTAINS` : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set (" `SS`", " `NS`", or " `BS`"), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating " `a NOT CONTAINS b`", " `a`" can be a list; however, " `b`" cannot be a set, a map, or a list. + `BEGINS_WITH` : Checks for a prefix. AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type). > <li> + `IN` : Checks for matching elements within two sets. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary (not a set type). These attributes are compared against an existing set type attribute of an item. If any elements of the input set are present in the item attribute, the expression evaluates to true. + `BETWEEN` : Greater than or equal to the first value, and less than or equal to the second value. AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one specified in the request, the value does not match. For example, `{"S":"6"}` does not compare to `{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6", "2", "1"]}` For usage examples of AttributeValueList and ComparisonOperator , see `Legacy Conditional Parameters`_ in the Amazon DynamoDB Developer Guide . For backward compatibility with previous DynamoDB releases, the following parameters can be used instead of AttributeValueList and ComparisonOperator : + Value - A value for DynamoDB to compare with an attribute. + Exists - A Boolean value that causes DynamoDB to evaluate the value before attempting the conditional operation: + If Exists is `True`, DynamoDB will check to see if that attribute value already exists in the table. If it is found, then the condition evaluates to true; otherwise the condition evaluate to false. + If Exists is `False`, DynamoDB assumes that the attribute value does not exist in the table. If in fact the value does not exist, then the assumption is valid and the condition evaluates to true. If the value is found, despite the assumption that it does not exist, the condition evaluates to false. Note that the default value for Exists is `True`. The Value and Exists parameters are incompatible with AttributeValueList and ComparisonOperator . Note that if you use both sets of parameters at once, DynamoDB will return a ValidationException exception. :type conditional_operator: string :param conditional_operator: There is a newer parameter available. Use ConditionExpression instead. Note that if you use ConditionalOperator and ConditionExpression at the same time, DynamoDB will return a ValidationException exception. This parameter does not support lists or maps. A logical operator to apply to the conditions in the Expected map: + `AND` - If all of the conditions evaluate to true, then the entire map evaluates to true. + `OR` - If at least one of the conditions evaluate to true, then the entire map evaluates to true. If you omit ConditionalOperator , then `AND` is the default. The operation will succeed only if the entire map evaluates to true. :type return_values: string :param return_values: Use ReturnValues if you want to get the item attributes as they appeared either before or after they were updated. For UpdateItem , the valid values are: + `NONE` - If ReturnValues is not specified, or if its value is `NONE`, then nothing is returned. (This setting is the default for ReturnValues .) + `ALL_OLD` - If UpdateItem overwrote an attribute name-value pair, then the content of the old item is returned. + `UPDATED_OLD` - The old versions of only the updated attributes are returned. + `ALL_NEW` - All of the attributes of the new version of the item are returned. + `UPDATED_NEW` - The new versions of only the updated attributes are returned. :type return_consumed_capacity: string :param return_consumed_capacity: A value that if set to `TOTAL`, the response includes ConsumedCapacity data for tables and indexes. If set to `INDEXES`, the response includes ConsumedCapacity for indexes. If set to `NONE` (the default), ConsumedCapacity is not included in the response. :type return_item_collection_metrics: string :param return_item_collection_metrics: A value that if set to `SIZE`, the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to `NONE` (the default), no statistics are returned. :type update_expression: string :param update_expression: An expression that defines one or more attributes to be updated, the action to be performed on them, and new value(s) for them. The following action values are available for UpdateExpression . + `SET` - Adds one or more attributes and values to an item. If any of these attribute already exist, they are replaced by the new values. You can also use `SET` to add or subtract from an attribute that is of type Number. `SET` supports the following functions: + `if_not_exists (path, operand)` - if the item does not contain an attribute at the specified path, then `if_not_exists` evaluates to operand; otherwise, it evaluates to path. You can use this function to avoid overwriting an attribute that may already be present in the item. + `list_append (operand, operand)` - evaluates to a list with a new element added to it. You can append the new element to the start or the end of the list by reversing the order of the operands. These function names are case-sensitive. + `REMOVE` - Removes one or more attributes from an item. + `ADD` - Adds the specified value to the item, if the attribute does not already exist. If the attribute does exist, then the behavior of `ADD` depends on the data type of the attribute: + If the existing attribute is a number, and if Value is also a number, then Value is mathematically added to the existing attribute. If Value is a negative number, then it is subtracted from the existing attribute. If you use `ADD` to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses `0` as the initial value. Similarly, if you use `ADD` for an existing item to increment or decrement an attribute value that doesn't exist before the update, DynamoDB uses `0` as the initial value. For example, suppose that the item you want to update doesn't have an attribute named itemcount , but you decide to `ADD` the number `3` to this attribute anyway. DynamoDB will create the itemcount attribute, set its initial value to `0`, and finally add `3` to it. The result will be a new itemcount attribute in the item, with a value of `3`. + If the existing data type is a set and if Value is also a set, then Value is added to the existing set. For example, if the attribute value is the set `[1,2]`, and the `ADD` action specified `[3]`, then the final attribute value is `[1,2,3]`. An error occurs if an `ADD` action is specified for a set attribute and the attribute type specified does not match the existing set type. Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, the Value must also be a set of strings. The `ADD` action only supports Number and set data types. In addition, `ADD` can only be used on top-level attributes, not nested attributes. + `DELETE` - Deletes an element from a set. If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set `[a,b,c]` and the `DELETE` action specifies `[a,c]`, then the final attribute value is `[b]`. Specifying an empty set is an error. The `DELETE` action only supports Number and set data types. In addition, `DELETE` can only be used on top-level attributes, not nested attributes. You can have many actions in a single expression, such as the following: `SET a=:value1, b=:value2 DELETE :value3, :value4, :value5` For more information on update expressions, go to `Modifying Items and Attributes`_ in the Amazon DynamoDB Developer Guide . :type condition_expression: string :param condition_expression: A condition that must be satisfied in order for a conditional update to succeed. An expression can contain any of the following: + Boolean functions: `attribute_exists | attribute_not_exists | contains | begins_with` These function names are case-sensitive. + Comparison operators: ` = | <> | < | > | <= | >= | BETWEEN | IN` + Logical operators: `AND | OR | NOT` For more information on condition expressions, go to `Specifying Conditions`_ in the Amazon DynamoDB Developer Guide . :type expression_attribute_names: map :param expression_attribute_names: One or more substitution tokens for simplifying complex expressions. The following are some use cases for using ExpressionAttributeNames : + To shorten an attribute name that is very long or unwieldy in an expression. + To create a placeholder for repeating occurrences of an attribute name in an expression. + To prevent special characters in an attribute name from being misinterpreted in an expression. Use the **#** character in an expression to dereference an attribute name. For example, consider the following expression: + `order.customerInfo.LastName = "Smith" OR order.customerInfo.LastName = "Jones"` Now suppose that you specified the following for ExpressionAttributeNames : + `{"#name":"order.customerInfo.LastName"}` The expression can now be simplified as follows: + `#name = "Smith" OR #name = "Jones"` For more information on expression attribute names, go to `Accessing Item Attributes`_ in the Amazon DynamoDB Developer Guide . :type expression_attribute_values: map :param expression_attribute_values: One or more values that can be substituted in an expression. Use the **:** (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following: `Available | Backordered | Discontinued` You would first need to specify ExpressionAttributeValues as follows: `{ ":avail":{"S":"Available"}, ":back":{"S":"Backordered"}, ":disc":{"S":"Discontinued"} }` You could then use these values in an expression, such as this: `ProductStatus IN (:avail, :back, :disc)` For more information on expression attribute values, go to `Specifying Conditions`_ in the Amazon DynamoDB Developer Guide . """ params = {'TableName': table_name, 'Key': key, } if attribute_updates is not None: params['AttributeUpdates'] = attribute_updates if expected is not None: params['Expected'] = expected if conditional_operator is not None: params['ConditionalOperator'] = conditional_operator if return_values is not None: params['ReturnValues'] = return_values if return_consumed_capacity is not None: params['ReturnConsumedCapacity'] = return_consumed_capacity if return_item_collection_metrics is not None: params['ReturnItemCollectionMetrics'] = return_item_collection_metrics if update_expression is not None: params['UpdateExpression'] = update_expression if condition_expression is not None: params['ConditionExpression'] = condition_expression if expression_attribute_names is not None: params['ExpressionAttributeNames'] = expression_attribute_names if expression_attribute_values is not None: params['ExpressionAttributeValues'] = expression_attribute_values return self.make_request(action='UpdateItem', body=json.dumps(params))
[ "def", "update_item", "(", "self", ",", "table_name", ",", "key", ",", "attribute_updates", "=", "None", ",", "expected", "=", "None", ",", "conditional_operator", "=", "None", ",", "return_values", "=", "None", ",", "return_consumed_capacity", "=", "None", ",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/layer1.py#L2248-L2765
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/__future__.py
python
_Feature.getOptionalRelease
(self)
return self.optional
Return first release in which this feature was recognized. This is a 5-tuple, of the same form as sys.version_info.
Return first release in which this feature was recognized.
[ "Return", "first", "release", "in", "which", "this", "feature", "was", "recognized", "." ]
def getOptionalRelease(self): """Return first release in which this feature was recognized. This is a 5-tuple, of the same form as sys.version_info. """ return self.optional
[ "def", "getOptionalRelease", "(", "self", ")", ":", "return", "self", ".", "optional" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/__future__.py#L86-L92
ros-planning/moveit2
dd240ef6fd8b9932a7a53964140f2952786187a9
moveit_commander/src/moveit_commander/move_group.py
python
MoveGroupCommander.enforce_bounds
(self, robot_state_msg)
return s
Takes a moveit_msgs RobotState and enforces the state bounds, based on the C++ RobotState enforceBounds()
Takes a moveit_msgs RobotState and enforces the state bounds, based on the C++ RobotState enforceBounds()
[ "Takes", "a", "moveit_msgs", "RobotState", "and", "enforces", "the", "state", "bounds", "based", "on", "the", "C", "++", "RobotState", "enforceBounds", "()" ]
def enforce_bounds(self, robot_state_msg): """ Takes a moveit_msgs RobotState and enforces the state bounds, based on the C++ RobotState enforceBounds() """ s = RobotState() c_str = self._g.enforce_bounds(conversions.msg_to_string(robot_state_msg)) conversions.msg_from_string(s, c_str) return s
[ "def", "enforce_bounds", "(", "self", ",", "robot_state_msg", ")", ":", "s", "=", "RobotState", "(", ")", "c_str", "=", "self", ".", "_g", ".", "enforce_bounds", "(", "conversions", ".", "msg_to_string", "(", "robot_state_msg", ")", ")", "conversions", ".", ...
https://github.com/ros-planning/moveit2/blob/dd240ef6fd8b9932a7a53964140f2952786187a9/moveit_commander/src/moveit_commander/move_group.py#L784-L789
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/geographic_msgs/msg/_GeoPoint.py
python
GeoPoint.serialize_numpy
(self, buff, numpy)
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
[ "serialize", "message", "with", "numpy", "array", "types", "into", "buffer", ":", "param", "buff", ":", "buffer", "StringIO", ":", "param", "numpy", ":", "numpy", "python", "module" ]
def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self buff.write(_struct_3d.pack(_x.latitude, _x.longitude, _x.altitude)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x)))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
[ "def", "serialize_numpy", "(", "self", ",", "buff", ",", "numpy", ")", ":", "try", ":", "_x", "=", "self", "buff", ".", "write", "(", "_struct_3d", ".", "pack", "(", "_x", ".", "latitude", ",", "_x", ".", "longitude", ",", "_x", ".", "altitude", ")...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/geographic_msgs/msg/_GeoPoint.py#L92-L102
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
util/py_lib/seqan/dox/write_html.py
python
HtmlWriter.copyStaticFiles
(self)
Copy static files.
Copy static files.
[ "Copy", "static", "files", "." ]
def copyStaticFiles(self): """Copy static files.""" for kind in ['css', 'js', 'img', 'lib']: in_dir = os.path.join(self.path_manager.this_dir, 'tpl/%s' % kind) out_path = self.out_dirs[kind] self.log(' Copying %s => %s', in_dir, out_path) distutils.dir_util.copy_tree(in_dir, out_path, verbose=True)
[ "def", "copyStaticFiles", "(", "self", ")", ":", "for", "kind", "in", "[", "'css'", ",", "'js'", ",", "'img'", ",", "'lib'", "]", ":", "in_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path_manager", ".", "this_dir", ",", "'tpl/%s'", ...
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dox/write_html.py#L385-L391
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/fileinput.py
python
filelineno
()
return _state.filelineno()
Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file.
Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file.
[ "Return", "the", "line", "number", "in", "the", "current", "file", ".", "Before", "the", "first", "line", "has", "been", "read", "returns", "0", ".", "After", "the", "last", "line", "of", "the", "last", "file", "has", "been", "read", "returns", "the", ...
def filelineno(): """ Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file. """ if not _state: raise RuntimeError("no active input()") return _state.filelineno()
[ "def", "filelineno", "(", ")", ":", "if", "not", "_state", ":", "raise", "RuntimeError", "(", "\"no active input()\"", ")", "return", "_state", ".", "filelineno", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/fileinput.py#L138-L146
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLApplySelfShielding.py
python
DirectILLApplySelfShielding._applyCorrections
(self, mainWS)
return correctedWS, True
Applies self shielding corrections to a workspace, if corrections exist.
Applies self shielding corrections to a workspace, if corrections exist.
[ "Applies", "self", "shielding", "corrections", "to", "a", "workspace", "if", "corrections", "exist", "." ]
def _applyCorrections(self, mainWS): """Applies self shielding corrections to a workspace, if corrections exist.""" if self.getProperty(common.PROP_SELF_SHIELDING_CORRECTION_WS).isDefault: return mainWS, False correctionWS = self.getProperty(common.PROP_SELF_SHIELDING_CORRECTION_WS).value correctedWSName = self._names.withSuffix('self_shielding_corrected') correctedWS = Divide(LHSWorkspace=mainWS, RHSWorkspace=correctionWS, OutputWorkspace=correctedWSName, EnableLogging=self._subalgLogging) self._cleanup.cleanup(mainWS) return correctedWS, True
[ "def", "_applyCorrections", "(", "self", ",", "mainWS", ")", ":", "if", "self", ".", "getProperty", "(", "common", ".", "PROP_SELF_SHIELDING_CORRECTION_WS", ")", ".", "isDefault", ":", "return", "mainWS", ",", "False", "correctionWS", "=", "self", ".", "getPro...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLApplySelfShielding.py#L142-L153
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchSite.py
python
_ViewProviderSite.updateData
(self,obj,prop)
Method called when the host object has a property changed. If the Longitude or Latitude has changed, set the SolarDiagram to update. If Terrain or Placement has changed, move the compass to follow it. Parameters ---------- obj: <App::FeaturePython> The host object that has changed. prop: string The name of the property that has changed.
Method called when the host object has a property changed.
[ "Method", "called", "when", "the", "host", "object", "has", "a", "property", "changed", "." ]
def updateData(self,obj,prop): """Method called when the host object has a property changed. If the Longitude or Latitude has changed, set the SolarDiagram to update. If Terrain or Placement has changed, move the compass to follow it. Parameters ---------- obj: <App::FeaturePython> The host object that has changed. prop: string The name of the property that has changed. """ if prop in ["Longitude","Latitude","TimeZone"]: self.onChanged(obj.ViewObject,"SolarDiagram") elif prop == "Declination": self.onChanged(obj.ViewObject,"SolarDiagramPosition") self.updateTrueNorthRotation() elif prop == "Terrain": self.updateCompassLocation(obj.ViewObject) elif prop == "Placement": self.updateCompassLocation(obj.ViewObject) self.updateDeclination(obj.ViewObject) elif prop == "ProjectedArea": self.updateCompassScale(obj.ViewObject)
[ "def", "updateData", "(", "self", ",", "obj", ",", "prop", ")", ":", "if", "prop", "in", "[", "\"Longitude\"", ",", "\"Latitude\"", ",", "\"TimeZone\"", "]", ":", "self", ".", "onChanged", "(", "obj", ".", "ViewObject", ",", "\"SolarDiagram\"", ")", "eli...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchSite.py#L981-L1008