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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py
python
Output.erase_end_of_line
(self)
Erases from the current cursor position to the end of the current line.
Erases from the current cursor position to the end of the current line.
[ "Erases", "from", "the", "current", "cursor", "position", "to", "the", "end", "of", "the", "current", "line", "." ]
def erase_end_of_line(self): """ Erases from the current cursor position to the end of the current line. """
[ "def", "erase_end_of_line", "(", "self", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py#L80-L83
gwaldron/osgearth
4c521857d59a69743e4a9cedba00afe570f984e8
src/third_party/tinygltf/deps/cpplint.py
python
CheckAccess
(filename, clean_lines, linenum, nesting_state, error)
Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks for improper use of DISALLOW* macros.
[ "Checks", "for", "improper", "use", "of", "DISALLOW", "*", "macros", "." ]
def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass
[ "def", "CheckAccess", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "matched", "=", "Match", "(", "(", "r'...
https://github.com/gwaldron/osgearth/blob/4c521857d59a69743e4a9cedba00afe570f984e8/src/third_party/tinygltf/deps/cpplint.py#L2969-L2996
ablab/quast
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
quast_libs/site_packages/jsontemplate/jsontemplate.py
python
_ProgramBuilder._GetFormatter
(self, format_str)
The user's formatters are consulted first, then the default formatters.
The user's formatters are consulted first, then the default formatters.
[ "The", "user", "s", "formatters", "are", "consulted", "first", "then", "the", "default", "formatters", "." ]
def _GetFormatter(self, format_str): """ The user's formatters are consulted first, then the default formatters. """ formatter, args, func_type = self.formatters.LookupWithType(format_str) if formatter: return formatter, args, func_type else: raise BadFormatter('%r is not a valid formatter' % format_str)
[ "def", "_GetFormatter", "(", "self", ",", "format_str", ")", ":", "formatter", ",", "args", ",", "func_type", "=", "self", ".", "formatters", ".", "LookupWithType", "(", "format_str", ")", "if", "formatter", ":", "return", "formatter", ",", "args", ",", "f...
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/jsontemplate/jsontemplate.py#L281-L289
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/python-common/ceph/deployment/drive_group.py
python
DeviceSelection.__init__
(self, paths=None, # type: Optional[List[str]] model=None, # type: Optional[str] size=None, # type: Optional[str] rotational=None, # type: Optional[bool] limit=None, # type: Optional[int] vendor=None, # type: Optional[str] all=False, # type: bool )
ephemeral drive group device specification
ephemeral drive group device specification
[ "ephemeral", "drive", "group", "device", "specification" ]
def __init__(self, paths=None, # type: Optional[List[str]] model=None, # type: Optional[str] size=None, # type: Optional[str] rotational=None, # type: Optional[bool] limit=None, # type: Optional[int] vendor=None, # type: Optional[str] all=False, # type: bool ): """ ephemeral drive group device specification """ #: List of Device objects for devices paths. self.paths = [] if paths is None else [Device(path) for path in paths] # type: List[Device] #: A wildcard string. e.g: "SDD*" or "SanDisk SD8SN8U5" self.model = model #: Match on the VENDOR property of the drive self.vendor = vendor #: Size specification of format LOW:HIGH. #: Can also take the the form :HIGH, LOW: #: or an exact value (as ceph-volume inventory reports) self.size: Optional[str] = size #: is the drive rotating or not self.rotational = rotational #: Limit the number of devices added to this Drive Group. Devices #: are used from top to bottom in the output of ``ceph-volume inventory`` self.limit = limit #: Matches all devices. Can only be used for data devices self.all = all
[ "def", "__init__", "(", "self", ",", "paths", "=", "None", ",", "# type: Optional[List[str]]", "model", "=", "None", ",", "# type: Optional[str]", "size", "=", "None", ",", "# type: Optional[str]", "rotational", "=", "None", ",", "# type: Optional[bool]", "limit", ...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/python-common/ceph/deployment/drive_group.py#L32-L66
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/libdeps/libdeps/analyzer.py
python
DirectDependents.run
(self)
return sorted([ depender for depender in self._dependents_graph[self._node] if self._dependents_graph[self._node][depender].get(EdgeProps.direct.name) ])
For given nodes, report what nodes depend directly on that node.
For given nodes, report what nodes depend directly on that node.
[ "For", "given", "nodes", "report", "what", "nodes", "depend", "directly", "on", "that", "node", "." ]
def run(self): """For given nodes, report what nodes depend directly on that node.""" return sorted([ depender for depender in self._dependents_graph[self._node] if self._dependents_graph[self._node][depender].get(EdgeProps.direct.name) ])
[ "def", "run", "(", "self", ")", ":", "return", "sorted", "(", "[", "depender", "for", "depender", "in", "self", ".", "_dependents_graph", "[", "self", ".", "_node", "]", "if", "self", ".", "_dependents_graph", "[", "self", ".", "_node", "]", "[", "depe...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/libdeps/libdeps/analyzer.py#L416-L422
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_reactor.py
python
Transaction.abort
(self)
Abort or roll back this transaction. Closes the transaction as a failure, and reverses, or rolls back all actions (sent and received messages) performed under this transaction.
Abort or roll back this transaction. Closes the transaction as a failure, and reverses, or rolls back all actions (sent and received messages) performed under this transaction.
[ "Abort", "or", "roll", "back", "this", "transaction", ".", "Closes", "the", "transaction", "as", "a", "failure", "and", "reverses", "or", "rolls", "back", "all", "actions", "(", "sent", "and", "received", "messages", ")", "performed", "under", "this", "trans...
def abort(self) -> None: """ Abort or roll back this transaction. Closes the transaction as a failure, and reverses, or rolls back all actions (sent and received messages) performed under this transaction. """ self.discharge(True)
[ "def", "abort", "(", "self", ")", "->", "None", ":", "self", ".", "discharge", "(", "True", ")" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_reactor.py#L561-L567
TimoSaemann/caffe-segnet-cudnn5
abcf30dca449245e101bf4ced519f716177f0885
scripts/cpp_lint.py
python
FindNextMultiLineCommentStart
(lines, lineix)
return len(lines)
Find the beginning marker for a multiline comment.
Find the beginning marker for a multiline comment.
[ "Find", "the", "beginning", "marker", "for", "a", "multiline", "comment", "." ]
def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "startswith", "(", "'/*'", ")", ":", "# Only return this...
https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L1123-L1131
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/compiler.py
python
_make_subtarget
(targetctx, flags)
return targetctx.subtarget(**subtargetoptions)
Make a new target context from the given target context and flags.
Make a new target context from the given target context and flags.
[ "Make", "a", "new", "target", "context", "from", "the", "given", "target", "context", "and", "flags", "." ]
def _make_subtarget(targetctx, flags): """ Make a new target context from the given target context and flags. """ subtargetoptions = {} if flags.debuginfo: subtargetoptions['enable_debuginfo'] = True if flags.boundscheck: subtargetoptions['enable_boundscheck'] = True if flags.nrt: subtargetoptions['enable_nrt'] = True if flags.auto_parallel: subtargetoptions['auto_parallel'] = flags.auto_parallel if flags.fastmath: subtargetoptions['fastmath'] = flags.fastmath error_model = callconv.create_error_model(flags.error_model, targetctx) subtargetoptions['error_model'] = error_model return targetctx.subtarget(**subtargetoptions)
[ "def", "_make_subtarget", "(", "targetctx", ",", "flags", ")", ":", "subtargetoptions", "=", "{", "}", "if", "flags", ".", "debuginfo", ":", "subtargetoptions", "[", "'enable_debuginfo'", "]", "=", "True", "if", "flags", ".", "boundscheck", ":", "subtargetopti...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/compiler.py#L250-L268
pisa-engine/pisa
0efb7926d4928c8aae672ba4d7a1419891f2676d
script/ext/baker.py
python
format_paras
(paras, width, indent=0, lstripline=None)
return output
Takes a list of paragraph strings and formats them into a word-wrapped, optionally indented string.
Takes a list of paragraph strings and formats them into a word-wrapped, optionally indented string.
[ "Takes", "a", "list", "of", "paragraph", "strings", "and", "formats", "them", "into", "a", "word", "-", "wrapped", "optionally", "indented", "string", "." ]
def format_paras(paras, width, indent=0, lstripline=None): """ Takes a list of paragraph strings and formats them into a word-wrapped, optionally indented string. """ output = [] for para in paras: lines = wrap(para, width - indent) if lines: for line in lines: output.append((" " * indent) + line) for i in (lstripline or []): output[i] = output[i].lstrip() return output
[ "def", "format_paras", "(", "paras", ",", "width", ",", "indent", "=", "0", ",", "lstripline", "=", "None", ")", ":", "output", "=", "[", "]", "for", "para", "in", "paras", ":", "lines", "=", "wrap", "(", "para", ",", "width", "-", "indent", ")", ...
https://github.com/pisa-engine/pisa/blob/0efb7926d4928c8aae672ba4d7a1419891f2676d/script/ext/baker.py#L96-L109
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/dbgen/decay.py
python
make_decay_half_life_table
(nuc_data, build_dir="")
Makes a decay table in the nuc_data library. Parameters ---------- nuc_data : str Path to nuclide data file. build_dir : str Directory to place ensdf files in.
Makes a decay table in the nuc_data library.
[ "Makes", "a", "decay", "table", "in", "the", "nuc_data", "library", "." ]
def make_decay_half_life_table(nuc_data, build_dir=""): """Makes a decay table in the nuc_data library. Parameters ---------- nuc_data : str Path to nuclide data file. build_dir : str Directory to place ensdf files in. """ # Grab raw level data level_list = parse_level_data(build_dir) # Open the HDF5 File db = tb.open_file(nuc_data, 'a', filters=BASIC_FILTERS) # Make a new the table if not hasattr(db.root, 'decay'): db.create_group('/', 'decay', 'ENSDF Decay data') ll_table = db.create_table('/decay/', 'level_list', level_list, 'nuclide [nuc_id], level [keV], half life [s],' 'metastable [int]', expectedrows=len(level_list)) ll_table.flush() # now that the level data is in nuc_data we can build the decay data fast decay, gammas, alphas, betas, ecbp = parse_decay_data(build_dir) decay_table = db.create_table('/decay/', 'decays', decay, 'parent nuclide [nuc_id], daughter nuclide ' '[nuc_id], decay [string], half life [s],' 'half life error [s], branch ratio [frac],' 'branch ratio error [frac],' 'photon branch ratio [ratio],' 'photon branch ratio error [ratio],' 'beta branch ratio [ratio],' 'beta branch ratio error [ratio]', expectedrows=len(decay)) decay_table.flush() gamma_table = db.create_table('/decay/', 'gammas', gammas, 'from_nuc [int], to_nuc [int], primary parent' 'nuc_id [int], child nuc_id [int]' 'Energy [keV], Energy error [keV], ' 'photon intensity [ratio], ' 'photon intensity error [ratio],' 'conversion e intensity [ratio],' 'conversion e intensity error [ratio],' 'total intensity [ratio],' 'total intensity error [ratio], ' 'K conversion electron' 'intensity [ratio], L conversion electron' 'intensity [ratio], M conversion electron' 'intensity [ratio]', expectedrows=len(gammas)) gamma_table.flush() alphas_table = db.create_table('/decay/', 'alphas', alphas, 'from_nuc [int], to_nuc [int]' 'Energy [keV], Intensity [ratio],', expectedrows=len(alphas)) alphas_table.flush() betas_table = db.create_table('/decay/', 'betas', betas, 'from_nuc [int], to_nuc [int],' 'Endpoint Energy [keV], Average Energy [keV],' 'Intensity [ratio]', expectedrows=len(betas)) betas_table.flush() ecbp_table = db.create_table('/decay/', 'ecbp', ecbp, 'from_nuc [int], to_nuc [int],' 'Endpoint Energy [keV], Average Energy [keV],' 'B+ Intensity [ratio], ' 'Electron Capture Intensity [ratio],' 'K conversion' 'electron intensity [ratio], L conversion' 'electron intensity [ratio], M conversion' 'electron intensity [ratio]', expectedrows=len(ecbp)) ecbp_table.flush() # Close the hdf5 file db.close()
[ "def", "make_decay_half_life_table", "(", "nuc_data", ",", "build_dir", "=", "\"\"", ")", ":", "# Grab raw level data", "level_list", "=", "parse_level_data", "(", "build_dir", ")", "# Open the HDF5 File", "db", "=", "tb", ".", "open_file", "(", "nuc_data", ",", "...
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/dbgen/decay.py#L387-L472
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
EventLoopBase_GetActive
(*args)
return _core_.EventLoopBase_GetActive(*args)
EventLoopBase_GetActive() -> EventLoopBase
EventLoopBase_GetActive() -> EventLoopBase
[ "EventLoopBase_GetActive", "()", "-", ">", "EventLoopBase" ]
def EventLoopBase_GetActive(*args): """EventLoopBase_GetActive() -> EventLoopBase""" return _core_.EventLoopBase_GetActive(*args)
[ "def", "EventLoopBase_GetActive", "(", "*", "args", ")", ":", "return", "_core_", ".", "EventLoopBase_GetActive", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L8844-L8846
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/sparse/weighted_softmax_ce.py
python
WeightedSoftmaxCrossEntropyLoss.backward
(self, req, out_grad, in_data, out_data, in_grad, aux)
Implements backward computation req : list of {'null', 'write', 'inplace', 'add'}, how to assign to in_grad out_grad : list of NDArray, gradient w.r.t. output data. in_grad : list of NDArray, gradient w.r.t. input data. This is the output buffer.
Implements backward computation
[ "Implements", "backward", "computation" ]
def backward(self, req, out_grad, in_data, out_data, in_grad, aux): """Implements backward computation req : list of {'null', 'write', 'inplace', 'add'}, how to assign to in_grad out_grad : list of NDArray, gradient w.r.t. output data. in_grad : list of NDArray, gradient w.r.t. input data. This is the output buffer. """ label = in_data[1] pred = out_data[0] dx = pred - mx.nd.one_hot(label, 2) pos_cls_weight = self.positive_cls_weight scale_factor = ((1 + label * pos_cls_weight) / pos_cls_weight).reshape((pred.shape[0],1)) rescaled_dx = scale_factor * dx self.assign(in_grad[0], req[0], rescaled_dx)
[ "def", "backward", "(", "self", ",", "req", ",", "out_grad", ",", "in_data", ",", "out_data", ",", "in_grad", ",", "aux", ")", ":", "label", "=", "in_data", "[", "1", "]", "pred", "=", "out_data", "[", "0", "]", "dx", "=", "pred", "-", "mx", ".",...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/sparse/weighted_softmax_ce.py#L44-L57
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
official-ws/python/bitmex_websocket.py
python
BitMEXWebsocket.__send_command
(self, command, args=None)
Send a raw command.
Send a raw command.
[ "Send", "a", "raw", "command", "." ]
def __send_command(self, command, args=None): '''Send a raw command.''' if args is None: args = [] self.ws.send(json.dumps({"op": command, "args": args}))
[ "def", "__send_command", "(", "self", ",", "command", ",", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "self", ".", "ws", ".", "send", "(", "json", ".", "dumps", "(", "{", "\"op\"", ":", "command", ",", ...
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/official-ws/python/bitmex_websocket.py#L180-L184
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/cpplint.py
python
CheckAltTokens
(filename, clean_lines, linenum, error)
Check alternative keywords being used in boolean expressions. 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.
Check alternative keywords being used in boolean expressions.
[ "Check", "alternative", "keywords", "being", "used", "in", "boolean", "expressions", "." ]
def CheckAltTokens(filename, clean_lines, linenum, error): """Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # current line, but it catches most of the false positives. At least, # it provides a way to workaround this warning for people who use # multi-line comments in preprocessor macros. # # TODO(unknown): remove this once cpplint has better support for # multi-line comments. if line.find('/*') >= 0 or line.find('*/') >= 0: return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, 'Use operator %s instead of %s' % ( _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
[ "def", "CheckAltTokens", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Avoid preprocessor lines", "if", "Match", "(", "r'^\\s*#'", ",", "line", ")", ":", "retur...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/cpplint.py#L4214-L4243
CMU-Perceptual-Computing-Lab/caffe_rtpose
a4778bb1c3eb74d7250402016047216f77b4dba6
scripts/cpp_lint.py
python
CheckBraces
(filename, clean_lines, linenum, error)
Looks for misplaced braces (e.g. at the end of line). 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.
Looks for misplaced braces (e.g. at the end of line).
[ "Looks", "for", "misplaced", "braces", "(", "e", ".", "g", ".", "at", "the", "end", "of", "line", ")", "." ]
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\s*', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) if endline[endpos:].find('{') == -1: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') else: # common case: else not followed by a multi-line if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on compound # literals. closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_]+)\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or Search(r'\s+=\s*$', line_prefix)): match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }")
[ "def", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "if", "Match", "(", "r'\\s*{\\s*$'", ",", "line", ")", ":", ...
https://github.com/CMU-Perceptual-Computing-Lab/caffe_rtpose/blob/a4778bb1c3eb74d7250402016047216f77b4dba6/scripts/cpp_lint.py#L3069-L3240
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/module/qat/module.py
python
QATModule.get_weight_dtype
(self)
return self._get_method_result( "get_quantized_dtype", self.weight_fake_quant, self.weight_observer )
r"""Get weight's quantization dtype as the method from ``qconfig``.
r"""Get weight's quantization dtype as the method from ``qconfig``.
[ "r", "Get", "weight", "s", "quantization", "dtype", "as", "the", "method", "from", "qconfig", "." ]
def get_weight_dtype(self): r"""Get weight's quantization dtype as the method from ``qconfig``.""" return self._get_method_result( "get_quantized_dtype", self.weight_fake_quant, self.weight_observer )
[ "def", "get_weight_dtype", "(", "self", ")", ":", "return", "self", ".", "_get_method_result", "(", "\"get_quantized_dtype\"", ",", "self", ".", "weight_fake_quant", ",", "self", ".", "weight_observer", ")" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/module/qat/module.py#L134-L138
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/multiprocessing/forkserver.py
python
ForkServer.connect_to_new_process
(self, fds)
Request forkserver to create a child process. Returns a pair of fds (status_r, data_w). The calling process can read the child process's pid and (eventually) its returncode from status_r. The calling process should write to data_w the pickled preparation and process data.
Request forkserver to create a child process.
[ "Request", "forkserver", "to", "create", "a", "child", "process", "." ]
def connect_to_new_process(self, fds): '''Request forkserver to create a child process. Returns a pair of fds (status_r, data_w). The calling process can read the child process's pid and (eventually) its returncode from status_r. The calling process should write to data_w the pickled preparation and process data. ''' self.ensure_running() if len(fds) + 4 >= MAXFDS_TO_SEND: raise ValueError('too many fds') with socket.socket(socket.AF_UNIX) as client: client.connect(self._forkserver_address) parent_r, child_w = os.pipe() child_r, parent_w = os.pipe() allfds = [child_r, child_w, self._forkserver_alive_fd, resource_tracker.getfd()] allfds += fds try: reduction.sendfds(client, allfds) return parent_r, parent_w except: os.close(parent_r) os.close(parent_w) raise finally: os.close(child_r) os.close(child_w)
[ "def", "connect_to_new_process", "(", "self", ",", "fds", ")", ":", "self", ".", "ensure_running", "(", ")", "if", "len", "(", "fds", ")", "+", "4", ">=", "MAXFDS_TO_SEND", ":", "raise", "ValueError", "(", "'too many fds'", ")", "with", "socket", ".", "s...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/forkserver.py#L76-L103
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/xml/etree/ElementTree.py
python
TreeBuilder.pi
(self, target, text=None)
return self._handle_single( self._pi_factory, self.insert_pis, target, text)
Create a processing instruction using the pi_factory. *target* is the target name of the processing instruction. *text* is the data of the processing instruction, or ''.
Create a processing instruction using the pi_factory.
[ "Create", "a", "processing", "instruction", "using", "the", "pi_factory", "." ]
def pi(self, target, text=None): """Create a processing instruction using the pi_factory. *target* is the target name of the processing instruction. *text* is the data of the processing instruction, or ''. """ return self._handle_single( self._pi_factory, self.insert_pis, target, text)
[ "def", "pi", "(", "self", ",", "target", ",", "text", "=", "None", ")", ":", "return", "self", ".", "_handle_single", "(", "self", ".", "_pi_factory", ",", "self", ".", "insert_pis", ",", "target", ",", "text", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/etree/ElementTree.py#L1494-L1501
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/jinja2/utils.py
python
LRUCache.copy
(self)
return rv
Return a shallow copy of the instance.
Return a shallow copy of the instance.
[ "Return", "a", "shallow", "copy", "of", "the", "instance", "." ]
def copy(self): """Return a shallow copy of the instance.""" rv = self.__class__(self.capacity) rv._mapping.update(self._mapping) rv._queue = deque(self._queue) return rv
[ "def", "copy", "(", "self", ")", ":", "rv", "=", "self", ".", "__class__", "(", "self", ".", "capacity", ")", "rv", ".", "_mapping", ".", "update", "(", "self", ".", "_mapping", ")", "rv", ".", "_queue", "=", "deque", "(", "self", ".", "_queue", ...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/utils.py#L329-L334
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/column/string.py
python
StringMethods.isdigit
(self)
return self._return_or_inplace(libstrings.is_digit(self._column))
Check whether all characters in each string are digits. This is equivalent to running the Python string method `str.isdigit() <https://docs.python.org/3/library/stdtypes.html#str.isdigit>`_ for each element of the Series/Index. If a string has zero characters, False is returned for that check. Returns ------- Series or Index of bool Series or Index of boolean values with the same length as the original Series/Index. See also -------- isalnum Check whether all characters are alphanumeric. isalpha Check whether all characters are alphabetic. isdecimal Check whether all characters are decimal. isinteger Check whether all characters are integer. isnumeric Check whether all characters are numeric. isfloat Check whether all characters are float. islower Check whether all characters are lowercase. isspace Check whether all characters are whitespace. isupper Check whether all characters are uppercase. Examples -------- >>> import cudf >>> s = cudf.Series(['23', '³', '⅕', '']) The ``s.str.isdigit`` method is the same as ``s.str.isdecimal`` but also includes special digits, like superscripted and subscripted digits in unicode. >>> s.str.isdigit() 0 True 1 True 2 False 3 False dtype: bool
Check whether all characters in each string are digits.
[ "Check", "whether", "all", "characters", "in", "each", "string", "are", "digits", "." ]
def isdigit(self) -> SeriesOrIndex: """ Check whether all characters in each string are digits. This is equivalent to running the Python string method `str.isdigit() <https://docs.python.org/3/library/stdtypes.html#str.isdigit>`_ for each element of the Series/Index. If a string has zero characters, False is returned for that check. Returns ------- Series or Index of bool Series or Index of boolean values with the same length as the original Series/Index. See also -------- isalnum Check whether all characters are alphanumeric. isalpha Check whether all characters are alphabetic. isdecimal Check whether all characters are decimal. isinteger Check whether all characters are integer. isnumeric Check whether all characters are numeric. isfloat Check whether all characters are float. islower Check whether all characters are lowercase. isspace Check whether all characters are whitespace. isupper Check whether all characters are uppercase. Examples -------- >>> import cudf >>> s = cudf.Series(['23', '³', '⅕', '']) The ``s.str.isdigit`` method is the same as ``s.str.isdecimal`` but also includes special digits, like superscripted and subscripted digits in unicode. >>> s.str.isdigit() 0 True 1 True 2 False 3 False dtype: bool """ return self._return_or_inplace(libstrings.is_digit(self._column))
[ "def", "isdigit", "(", "self", ")", "->", "SeriesOrIndex", ":", "return", "self", ".", "_return_or_inplace", "(", "libstrings", ".", "is_digit", "(", "self", ".", "_column", ")", ")" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/string.py#L1441-L1503
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/eventstream.py
python
DecodeUtils.unpack_int16
(data)
return value, 2
Parse a signed 16-bit integer from the bytes. :type data: bytes :param data: The bytes to parse from. :rtype: tuple :rtype: (int, int) :returns: A tuple containing the (parsed integer value, bytes consumed)
Parse a signed 16-bit integer from the bytes.
[ "Parse", "a", "signed", "16", "-", "bit", "integer", "from", "the", "bytes", "." ]
def unpack_int16(data): """Parse a signed 16-bit integer from the bytes. :type data: bytes :param data: The bytes to parse from. :rtype: tuple :rtype: (int, int) :returns: A tuple containing the (parsed integer value, bytes consumed) """ value = unpack(DecodeUtils.INT16_BYTE_FORMAT, data[:2])[0] return value, 2
[ "def", "unpack_int16", "(", "data", ")", ":", "value", "=", "unpack", "(", "DecodeUtils", ".", "INT16_BYTE_FORMAT", ",", "data", "[", ":", "2", "]", ")", "[", "0", "]", "return", "value", ",", "2" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/eventstream.py#L151-L162
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/arch/isa_parser/isa_parser.py
python
ISAParser.p_specification
(self, t)
specification : opt_defs_and_outputs top_level_decode_block
specification : opt_defs_and_outputs top_level_decode_block
[ "specification", ":", "opt_defs_and_outputs", "top_level_decode_block" ]
def p_specification(self, t): 'specification : opt_defs_and_outputs top_level_decode_block' for f in self.splits.keys(): f.write('\n#endif\n') for f in self.files.values(): # close ALL the files; f.close() # not doing so can cause compilation to fail self.write_top_level_files() t[0] = True
[ "def", "p_specification", "(", "self", ",", "t", ")", ":", "for", "f", "in", "self", ".", "splits", ".", "keys", "(", ")", ":", "f", ".", "write", "(", "'\\n#endif\\n'", ")", "for", "f", "in", "self", ".", "files", ".", "values", "(", ")", ":", ...
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/arch/isa_parser/isa_parser.py#L863-L874
alexgkendall/caffe-posenet
62aafbd7c45df91acdba14f5d1406d8295c2bc6f
scripts/cpp_lint.py
python
RemoveMultiLineCommentsFromRange
(lines, begin, end)
Clears a range of lines for multi-line comments.
Clears a range of lines for multi-line comments.
[ "Clears", "a", "range", "of", "lines", "for", "multi", "-", "line", "comments", "." ]
def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '// dummy'
[ "def", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "begin", ",", "end", ")", ":", "# Having // dummy comments makes the lines non-empty, so we will not get", "# unnecessary blank line warnings later in the code.", "for", "i", "in", "range", "(", "begin", ",", "end", ...
https://github.com/alexgkendall/caffe-posenet/blob/62aafbd7c45df91acdba14f5d1406d8295c2bc6f/scripts/cpp_lint.py#L1143-L1148
clementine-player/Clementine
111379dfd027802b59125829fcf87e3e1d0ad73b
dist/cpplint.py
python
_VerboseLevel
()
return _cpplint_state.verbose_level
Returns the module's verbosity setting.
Returns the module's verbosity setting.
[ "Returns", "the", "module", "s", "verbosity", "setting", "." ]
def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level
[ "def", "_VerboseLevel", "(", ")", ":", "return", "_cpplint_state", ".", "verbose_level" ]
https://github.com/clementine-player/Clementine/blob/111379dfd027802b59125829fcf87e3e1d0ad73b/dist/cpplint.py#L855-L857
Illumina/manta
75b5c38d4fcd2f6961197b28a41eb61856f2d976
src/python/libexec/updateSampleFTFilter.py
python
processVariantRecordLine
(outfp, line)
Process each VCF variant record and write results to outfp stream after potentially modifying the record's FILTER value
Process each VCF variant record and write results to outfp stream after potentially modifying the record's FILTER value
[ "Process", "each", "VCF", "variant", "record", "and", "write", "results", "to", "outfp", "stream", "after", "potentially", "modifying", "the", "record", "s", "FILTER", "value" ]
def processVariantRecordLine(outfp, line) : """ Process each VCF variant record and write results to outfp stream after potentially modifying the record's FILTER value """ w=line.strip().split('\t') filters=w[VCFID.FILTER].split(';') assert(len(filters)) if filters[0] == "." or filters[0] == "PASS" : filters = [] formatTags=w[VCFID.FORMAT].split(':') assert(len(formatTags)) if formatTags[0] == "." : formatTags = [] def getFilterField() : if len(filters) == 0 : return "PASS" else : return ";".join(filters) def outputModifiedRecord() : w[VCFID.FILTER] = getFilterField() outfp.write("\t".join(w) + "\n") def addFilterAndOutput() : if Constants.filterLabel in filters : outfp.write(line) else : filters.append(Constants.filterLabel) outputModifiedRecord() def removeFilterAndOutput() : if Constants.filterLabel not in filters : outfp.write(line) else : filters.remove(Constants.filterLabel) outputModifiedRecord() try : ftIndex = formatTags.index("FT") except ValueError: addFilterAndOutput() return isPassed=False for sampleIndex in range(VCFID.FORMAT+1, len(w)) : sampleVals=w[sampleIndex].split(':') ft=sampleVals[ftIndex] if (ft == "PASS") : isPassed=True break if isPassed : removeFilterAndOutput() else : addFilterAndOutput()
[ "def", "processVariantRecordLine", "(", "outfp", ",", "line", ")", ":", "w", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "'\\t'", ")", "filters", "=", "w", "[", "VCFID", ".", "FILTER", "]", ".", "split", "(", "';'", ")", "assert", "(", ...
https://github.com/Illumina/manta/blob/75b5c38d4fcd2f6961197b28a41eb61856f2d976/src/python/libexec/updateSampleFTFilter.py#L67-L124
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/MSVSSettings.py
python
ValidateMSVSSettings
(settings, stderr=sys.stderr)
Validates that the names of the settings are valid for MSVS. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages.
Validates that the names of the settings are valid for MSVS.
[ "Validates", "that", "the", "names", "of", "the", "settings", "are", "valid", "for", "MSVS", "." ]
def ValidateMSVSSettings(settings, stderr=sys.stderr): """Validates that the names of the settings are valid for MSVS. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. """ _ValidateSettings(_msvs_validators, settings, stderr)
[ "def", "ValidateMSVSSettings", "(", "settings", ",", "stderr", "=", "sys", ".", "stderr", ")", ":", "_ValidateSettings", "(", "_msvs_validators", ",", "settings", ",", "stderr", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/MSVSSettings.py#L480-L488
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/mymod.py
python
mymod.OnNotify
(self,state,id,events)
Notify: should only be from the activator
Notify: should only be from the activator
[ "Notify", ":", "should", "only", "be", "from", "the", "activator" ]
def OnNotify(self,state,id,events): "Notify: should only be from the activator" global activator global openb global door global theobject PtDebugPrint("mymod: Notify event state=%f,id=%d,events=" % (state,id),events) # is this our activator notifying us? if state and id == activator.id: # first have the player do a little dance doDance.run(PtFindAvatar(events)) # yes, then run the responder if openb.value: door.run(self.key,state='open') theobject = object.value self.svMyNumber += 1 openb.value = False else: door.run(self.key,state='close') openb.value = True # get the avatar to create a myHelper class # find avatar for event in events: if event[0] == kCollisionEvent: self.helperslist.append(myHelper(event[2])) # save the last hitter if event[0] == kPickedEvent: self.helperslist.append(myHelper(event[2])) # save the last hitter # test the Save function savefile = open('pfile.txt','w') self.Save(savefile) savefile.close()
[ "def", "OnNotify", "(", "self", ",", "state", ",", "id", ",", "events", ")", ":", "global", "activator", "global", "openb", "global", "door", "global", "theobject", "PtDebugPrint", "(", "\"mymod: Notify event state=%f,id=%d,events=\"", "%", "(", "state", ",", "i...
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/mymod.py#L104-L135
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/signature_def_utils_impl.py
python
_supervised_signature_def
( method_name, inputs, loss=None, predictions=None, metrics=None)
return signature_def
Creates a signature for training and eval data. This function produces signatures that describe the inputs and outputs of a supervised process, such as training or evaluation, that results in loss, metrics, and the like. Note that this function only requires inputs to be not None. Args: method_name: Method name of the SignatureDef as a string. inputs: dict of string to `Tensor`. loss: dict of string to `Tensor` representing computed loss. predictions: dict of string to `Tensor` representing the output predictions. metrics: dict of string to `Tensor` representing metric ops. Returns: A train- or eval-flavored signature_def. Raises: ValueError: If inputs or outputs is `None`.
Creates a signature for training and eval data.
[ "Creates", "a", "signature", "for", "training", "and", "eval", "data", "." ]
def _supervised_signature_def( method_name, inputs, loss=None, predictions=None, metrics=None): """Creates a signature for training and eval data. This function produces signatures that describe the inputs and outputs of a supervised process, such as training or evaluation, that results in loss, metrics, and the like. Note that this function only requires inputs to be not None. Args: method_name: Method name of the SignatureDef as a string. inputs: dict of string to `Tensor`. loss: dict of string to `Tensor` representing computed loss. predictions: dict of string to `Tensor` representing the output predictions. metrics: dict of string to `Tensor` representing metric ops. Returns: A train- or eval-flavored signature_def. Raises: ValueError: If inputs or outputs is `None`. """ if inputs is None or not inputs: raise ValueError('{} inputs cannot be None or empty.'.format(method_name)) signature_inputs = {key: utils.build_tensor_info(tensor) for key, tensor in inputs.items()} signature_outputs = {} for output_set in (loss, predictions, metrics): if output_set is not None: sig_out = {key: utils.build_tensor_info(tensor) for key, tensor in output_set.items()} signature_outputs.update(sig_out) signature_def = build_signature_def( signature_inputs, signature_outputs, method_name) return signature_def
[ "def", "_supervised_signature_def", "(", "method_name", ",", "inputs", ",", "loss", "=", "None", ",", "predictions", "=", "None", ",", "metrics", "=", "None", ")", ":", "if", "inputs", "is", "None", "or", "not", "inputs", ":", "raise", "ValueError", "(", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/signature_def_utils_impl.py#L226-L265
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/mox.py
python
MockObject.__getitem__
(self, key)
return self._CreateMockMethod('__getitem__')(key)
Provide custom logic for mocking classes that are subscriptable. Args: key: Key to return the value for. Returns: Expected return value in replay mode. A MockMethod object for the __getitem__ method that has already been called if not in replay mode. Raises: TypeError if the underlying class is not subscriptable. UnexpectedMethodCallError if the object does not expect the call to __setitem__.
Provide custom logic for mocking classes that are subscriptable.
[ "Provide", "custom", "logic", "for", "mocking", "classes", "that", "are", "subscriptable", "." ]
def __getitem__(self, key): """Provide custom logic for mocking classes that are subscriptable. Args: key: Key to return the value for. Returns: Expected return value in replay mode. A MockMethod object for the __getitem__ method that has already been called if not in replay mode. Raises: TypeError if the underlying class is not subscriptable. UnexpectedMethodCallError if the object does not expect the call to __setitem__. """ getitem = self._class_to_mock.__dict__.get('__getitem__', None) # Verify the class supports item assignment. if getitem is None: raise TypeError('unsubscriptable object') # If we are in replay mode then simply call the mock __getitem__ method. if self._replay_mode: return MockMethod('__getitem__', self._expected_calls_queue, self._replay_mode)(key) # Otherwise, create a mock method __getitem__. return self._CreateMockMethod('__getitem__')(key)
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "getitem", "=", "self", ".", "_class_to_mock", ".", "__dict__", ".", "get", "(", "'__getitem__'", ",", "None", ")", "# Verify the class supports item assignment.", "if", "getitem", "is", "None", ":", "ra...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/mox.py#L459-L488
faasm/faasm
b3bc196d887adbd0bb9802bcb93323543bad59cb
faasmcli/faasmcli/tasks/dev.py
python
tools
(ctx, clean=False, build="Debug", parallel=0, sanitiser="None")
Builds all the targets commonly used for development
Builds all the targets commonly used for development
[ "Builds", "all", "the", "targets", "commonly", "used", "for", "development" ]
def tools(ctx, clean=False, build="Debug", parallel=0, sanitiser="None"): """ Builds all the targets commonly used for development """ cmake(ctx, clean=clean, build=build, sanitiser=sanitiser) targets = " ".join(DEV_TARGETS) cmake_cmd = "cmake --build . --target {}".format(targets) if parallel > 0: cmake_cmd += " --parallel {}".format(parallel) print(cmake_cmd) run( cmake_cmd, cwd=FAASM_BUILD_DIR, shell=True, check=True, )
[ "def", "tools", "(", "ctx", ",", "clean", "=", "False", ",", "build", "=", "\"Debug\"", ",", "parallel", "=", "0", ",", "sanitiser", "=", "\"None\"", ")", ":", "cmake", "(", "ctx", ",", "clean", "=", "clean", ",", "build", "=", "build", ",", "sanit...
https://github.com/faasm/faasm/blob/b3bc196d887adbd0bb9802bcb93323543bad59cb/faasmcli/faasmcli/tasks/dev.py#L64-L81
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.DocumentStart
(*args, **kwargs)
return _stc.StyledTextCtrl_DocumentStart(*args, **kwargs)
DocumentStart(self) Move caret to first position in document.
DocumentStart(self)
[ "DocumentStart", "(", "self", ")" ]
def DocumentStart(*args, **kwargs): """ DocumentStart(self) Move caret to first position in document. """ return _stc.StyledTextCtrl_DocumentStart(*args, **kwargs)
[ "def", "DocumentStart", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_DocumentStart", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L4456-L4462
iam-abbas/cs-algorithms
d04aa8fd9a1fa290266dde96afe9b90ee23c5a92
Python/cosine_similarity.py
python
cos_sim
(a, b)
return dot_product / (norm_a * norm_b)
Takes 2 vectors a, b and returns the cosine similarity according to the definition of the dot product
Takes 2 vectors a, b and returns the cosine similarity according to the definition of the dot product
[ "Takes", "2", "vectors", "a", "b", "and", "returns", "the", "cosine", "similarity", "according", "to", "the", "definition", "of", "the", "dot", "product" ]
def cos_sim(a, b): """Takes 2 vectors a, b and returns the cosine similarity according to the definition of the dot product """ dot_product = np.dot(a, b) norm_a = np.linalg.norm(a) norm_b = np.linalg.norm(b) return dot_product / (norm_a * norm_b)
[ "def", "cos_sim", "(", "a", ",", "b", ")", ":", "dot_product", "=", "np", ".", "dot", "(", "a", ",", "b", ")", "norm_a", "=", "np", ".", "linalg", ".", "norm", "(", "a", ")", "norm_b", "=", "np", ".", "linalg", ".", "norm", "(", "b", ")", "...
https://github.com/iam-abbas/cs-algorithms/blob/d04aa8fd9a1fa290266dde96afe9b90ee23c5a92/Python/cosine_similarity.py#L4-L11
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/insert-delete-getrandom-o1-duplicates-allowed.py
python
RandomizedCollection.insert
(self, val)
return not has
Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool
Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool
[ "Inserts", "a", "value", "to", "the", "collection", ".", "Returns", "true", "if", "the", "collection", "did", "not", "already", "contain", "the", "specified", "element", ".", ":", "type", "val", ":", "int", ":", "rtype", ":", "bool" ]
def insert(self, val): """ Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool """ has = val in self.__used self.__list += (val, len(self.__used[val])), self.__used[val] += len(self.__list)-1, return not has
[ "def", "insert", "(", "self", ",", "val", ")", ":", "has", "=", "val", "in", "self", ".", "__used", "self", ".", "__list", "+=", "(", "val", ",", "len", "(", "self", ".", "__used", "[", "val", "]", ")", ")", ",", "self", ".", "__used", "[", "...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/insert-delete-getrandom-o1-duplicates-allowed.py#L17-L28
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/dispatch.py
python
_create_path_to_resource_converter
(base_dir)
return converter
Returns a function that converts the path of a WebSocket handler source file to a resource string by removing the path to the base directory from its head, removing _SOURCE_SUFFIX from its tail, and replacing path separators in it with '/'. Args: base_dir: the path to the base directory.
Returns a function that converts the path of a WebSocket handler source file to a resource string by removing the path to the base directory from its head, removing _SOURCE_SUFFIX from its tail, and replacing path separators in it with '/'.
[ "Returns", "a", "function", "that", "converts", "the", "path", "of", "a", "WebSocket", "handler", "source", "file", "to", "a", "resource", "string", "by", "removing", "the", "path", "to", "the", "base", "directory", "from", "its", "head", "removing", "_SOURC...
def _create_path_to_resource_converter(base_dir): """Returns a function that converts the path of a WebSocket handler source file to a resource string by removing the path to the base directory from its head, removing _SOURCE_SUFFIX from its tail, and replacing path separators in it with '/'. Args: base_dir: the path to the base directory. """ base_dir = _normalize_path(base_dir) base_len = len(base_dir) suffix_len = len(_SOURCE_SUFFIX) def converter(path): if not path.endswith(_SOURCE_SUFFIX): return None # _normalize_path must not be used because resolving symlink breaks # following path check. path = path.replace('\\', '/') if not path.startswith(base_dir): return None return path[base_len:-suffix_len] return converter
[ "def", "_create_path_to_resource_converter", "(", "base_dir", ")", ":", "base_dir", "=", "_normalize_path", "(", "base_dir", ")", "base_len", "=", "len", "(", "base_dir", ")", "suffix_len", "=", "len", "(", "_SOURCE_SUFFIX", ")", "def", "converter", "(", "path",...
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/dispatch.py#L86-L111
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/auto_bisect.py
python
StartNewBisectForBug
(bug_id)
return bisect_result
Tries to trigger a bisect job for the alerts associated with a bug. Args: bug_id: A bug ID number. Returns: If successful, a dict containing "issue_id" and "issue_url" for the bisect job. Otherwise, a dict containing "error", with some description of the reason why a job wasn't started.
Tries to trigger a bisect job for the alerts associated with a bug.
[ "Tries", "to", "trigger", "a", "bisect", "job", "for", "the", "alerts", "associated", "with", "a", "bug", "." ]
def StartNewBisectForBug(bug_id): """Tries to trigger a bisect job for the alerts associated with a bug. Args: bug_id: A bug ID number. Returns: If successful, a dict containing "issue_id" and "issue_url" for the bisect job. Otherwise, a dict containing "error", with some description of the reason why a job wasn't started. """ try: bisect_job = _MakeBisectTryJob(bug_id) except NotBisectableError as e: return {'error': e.message} bisect_job_key = bisect_job.put() try: bisect_result = start_try_job.PerformBisect(bisect_job) except request_handler.InvalidInputError as e: bisect_result = {'error': e.message} if 'error' in bisect_result: bisect_job_key.delete() return bisect_result
[ "def", "StartNewBisectForBug", "(", "bug_id", ")", ":", "try", ":", "bisect_job", "=", "_MakeBisectTryJob", "(", "bug_id", ")", "except", "NotBisectableError", "as", "e", ":", "return", "{", "'error'", ":", "e", ".", "message", "}", "bisect_job_key", "=", "b...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/auto_bisect.py#L108-L131
omnisci/omniscidb
b9c95f1bd602b4ffc8b0edf18bfad61031e08d86
python/omnisci/thrift/OmniSci.py
python
Iface.get_db_objects_for_grantee
(self, session, roleName)
Parameters: - session - roleName
Parameters: - session - roleName
[ "Parameters", ":", "-", "session", "-", "roleName" ]
def get_db_objects_for_grantee(self, session, roleName): """ Parameters: - session - roleName """ pass
[ "def", "get_db_objects_for_grantee", "(", "self", ",", "session", ",", "roleName", ")", ":", "pass" ]
https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/python/omnisci/thrift/OmniSci.py#L853-L860
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/gluon/dc_gan/dcgan.py
python
get_configurations
(netG, netD)
return loss, trainerG, trainerD
Get configurations for net
Get configurations for net
[ "Get", "configurations", "for", "net" ]
def get_configurations(netG, netD): """Get configurations for net""" # loss loss = gluon.loss.SoftmaxCrossEntropyLoss() # initialize the generator and the discriminator netG.initialize(mx.init.Normal(0.02), ctx=ctx) netD.initialize(mx.init.Normal(0.02), ctx=ctx) # trainer for the generator and the discriminator trainerG = gluon.Trainer(netG.collect_params(), 'adam', {'learning_rate': opt.lr, 'beta1': opt.beta1}) trainerD = gluon.Trainer(netD.collect_params(), 'adam', {'learning_rate': opt.lr, 'beta1': opt.beta1}) return loss, trainerG, trainerD
[ "def", "get_configurations", "(", "netG", ",", "netD", ")", ":", "# loss", "loss", "=", "gluon", ".", "loss", ".", "SoftmaxCrossEntropyLoss", "(", ")", "# initialize the generator and the discriminator", "netG", ".", "initialize", "(", "mx", ".", "init", ".", "N...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/gluon/dc_gan/dcgan.py#L221-L234
POV-Ray/povray
76a804d18a30a1dbb0afbc0070b62526715571eb
tools/meta-make/bluenoise/BlueNoise.py
python
Generate3DBlueNoiseTexture
(Width,Height,Depth,nChannel,StandardDeviation=1.5)
This function generates a single 3D blue noise texture with the specified dimensions and number of channels. It then outputs it to a sequence of Depth output files in LDR and HDR in a well-organized tree of directories. It also outputs raw binary files. \sa StoreNDTextureHDR()
This function generates a single 3D blue noise texture with the specified dimensions and number of channels. It then outputs it to a sequence of Depth output files in LDR and HDR in a well-organized tree of directories. It also outputs raw binary files. \sa StoreNDTextureHDR()
[ "This", "function", "generates", "a", "single", "3D", "blue", "noise", "texture", "with", "the", "specified", "dimensions", "and", "number", "of", "channels", ".", "It", "then", "outputs", "it", "to", "a", "sequence", "of", "Depth", "output", "files", "in", ...
def Generate3DBlueNoiseTexture(Width,Height,Depth,nChannel,StandardDeviation=1.5): """This function generates a single 3D blue noise texture with the specified dimensions and number of channels. It then outputs it to a sequence of Depth output files in LDR and HDR in a well-organized tree of directories. It also outputs raw binary files. \sa StoreNDTextureHDR() """ OutputDirectory="../Data/%d_%d_%d"%(Width,Height,Depth); if(not path.exists(OutputDirectory)): makedirs(OutputDirectory); # Generate the blue noise for the various channels using multi-threading ChannelTextureList=[None]*nChannel; ChannelThreadList=[None]*nChannel; def GenerateAndStoreTexture(Index): ChannelTextureList[Index]=GetVoidAndClusterBlueNoise((Height,Width,Depth),StandardDeviation); for i in range(nChannel): ChannelThreadList[i]=threading.Thread(target=GenerateAndStoreTexture,args=(i,)); ChannelThreadList[i].start(); for Thread in ChannelThreadList: Thread.join(); Texture=np.concatenate([ChannelTextureList[i][:,:,:,np.newaxis] for i in range(nChannel)],3); LDRFormat=["LLL1","RG01","RGB1","RGBA"][nChannel-1]; HDRFormat=["L","LA","RGB","RGBA"][nChannel-1]; StoreNDTextureHDR(Texture,path.join(OutputDirectory,"HDR_"+HDRFormat+".raw")); for i in range(Depth): StoreNoiseTextureLDR(Texture[:,:,i,:],path.join(OutputDirectory,"LDR_%s_%d.png"%(LDRFormat,i)),Height*Width*Depth); StoreNoiseTextureHDR(Texture[:,:,i,:],path.join(OutputDirectory,"HDR_%s_%d.png"%(HDRFormat,i)),Height*Width*Depth);
[ "def", "Generate3DBlueNoiseTexture", "(", "Width", ",", "Height", ",", "Depth", ",", "nChannel", ",", "StandardDeviation", "=", "1.5", ")", ":", "OutputDirectory", "=", "\"../Data/%d_%d_%d\"", "%", "(", "Width", ",", "Height", ",", "Depth", ")", "if", "(", "...
https://github.com/POV-Ray/povray/blob/76a804d18a30a1dbb0afbc0070b62526715571eb/tools/meta-make/bluenoise/BlueNoise.py#L338-L363
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/SocketServer.py
python
TCPServer.fileno
(self)
return self.socket.fileno()
Return socket file number. Interface required by select().
Return socket file number.
[ "Return", "socket", "file", "number", "." ]
def fileno(self): """Return socket file number. Interface required by select(). """ return self.socket.fileno()
[ "def", "fileno", "(", "self", ")", ":", "return", "self", ".", "socket", ".", "fileno", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/SocketServer.py#L449-L455
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/inspect_utils.py
python
getqualifiedname
(namespace, object_, max_depth=5, visited=None)
return None
Returns the name by which a value can be referred to in a given namespace. If the object defines a parent module, the function attempts to use it to locate the object. This function will recurse inside modules, but it will not search objects for attributes. The recursion depth is controlled by max_depth. Args: namespace: Dict[str, Any], the namespace to search into. object_: Any, the value to search. max_depth: Optional[int], a limit to the recursion depth when searching inside modules. visited: Optional[Set[int]], ID of modules to avoid visiting. Returns: Union[str, None], the fully-qualified name that resolves to the value o, or None if it couldn't be found.
Returns the name by which a value can be referred to in a given namespace.
[ "Returns", "the", "name", "by", "which", "a", "value", "can", "be", "referred", "to", "in", "a", "given", "namespace", "." ]
def getqualifiedname(namespace, object_, max_depth=5, visited=None): """Returns the name by which a value can be referred to in a given namespace. If the object defines a parent module, the function attempts to use it to locate the object. This function will recurse inside modules, but it will not search objects for attributes. The recursion depth is controlled by max_depth. Args: namespace: Dict[str, Any], the namespace to search into. object_: Any, the value to search. max_depth: Optional[int], a limit to the recursion depth when searching inside modules. visited: Optional[Set[int]], ID of modules to avoid visiting. Returns: Union[str, None], the fully-qualified name that resolves to the value o, or None if it couldn't be found. """ if visited is None: visited = set() # Copy the dict to avoid "changed size error" during concurrent invocations. # TODO(mdan): This is on the hot path. Can we avoid the copy? namespace = dict(namespace) for name in namespace: # The value may be referenced by more than one symbol, case in which # any symbol will be fine. If the program contains symbol aliases that # change over time, this may capture a symbol that will later point to # something else. # TODO(mdan): Prefer the symbol that matches the value type name. if object_ is namespace[name]: return name # If an object is not found, try to search its parent modules. parent = tf_inspect.getmodule(object_) if (parent is not None and parent is not object_ and parent is not namespace): # No limit to recursion depth because of the guard above. parent_name = getqualifiedname( namespace, parent, max_depth=0, visited=visited) if parent_name is not None: name_in_parent = getqualifiedname( parent.__dict__, object_, max_depth=0, visited=visited) assert name_in_parent is not None, ( 'An object should always be found in its owner module') return '{}.{}'.format(parent_name, name_in_parent) if max_depth: # Iterating over a copy prevents "changed size due to iteration" errors. # It's unclear why those occur - suspecting new modules may load during # iteration. for name in namespace.keys(): value = namespace[name] if tf_inspect.ismodule(value) and id(value) not in visited: visited.add(id(value)) name_in_module = getqualifiedname(value.__dict__, object_, max_depth - 1, visited) if name_in_module is not None: return '{}.{}'.format(name, name_in_module) return None
[ "def", "getqualifiedname", "(", "namespace", ",", "object_", ",", "max_depth", "=", "5", ",", "visited", "=", "None", ")", ":", "if", "visited", "is", "None", ":", "visited", "=", "set", "(", ")", "# Copy the dict to avoid \"changed size error\" during concurrent ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/inspect_utils.py#L153-L213
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/financial.py
python
_rbl
(rate, per, pmt, pv, when)
return fv(rate, (per - 1), pmt, pv, when)
This function is here to simply have a different name for the 'fv' function to not interfere with the 'fv' keyword argument within the 'ipmt' function. It is the 'remaining balance on loan' which might be useful as it's own function, but is easily calculated with the 'fv' function.
This function is here to simply have a different name for the 'fv' function to not interfere with the 'fv' keyword argument within the 'ipmt' function. It is the 'remaining balance on loan' which might be useful as it's own function, but is easily calculated with the 'fv' function.
[ "This", "function", "is", "here", "to", "simply", "have", "a", "different", "name", "for", "the", "fv", "function", "to", "not", "interfere", "with", "the", "fv", "keyword", "argument", "within", "the", "ipmt", "function", ".", "It", "is", "the", "remainin...
def _rbl(rate, per, pmt, pv, when): """ This function is here to simply have a different name for the 'fv' function to not interfere with the 'fv' keyword argument within the 'ipmt' function. It is the 'remaining balance on loan' which might be useful as it's own function, but is easily calculated with the 'fv' function. """ return fv(rate, (per - 1), pmt, pv, when)
[ "def", "_rbl", "(", "rate", ",", "per", ",", "pmt", ",", "pv", ",", "when", ")", ":", "return", "fv", "(", "rate", ",", "(", "per", "-", "1", ")", ",", "pmt", ",", "pv", ",", "when", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/financial.py#L466-L473
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/enum.py
python
Enum.__dir__
(self)
return (['__class__', '__doc__', '__module__'] + added_behavior)
Returns all members and all public methods
Returns all members and all public methods
[ "Returns", "all", "members", "and", "all", "public", "methods" ]
def __dir__(self): """ Returns all members and all public methods """ added_behavior = [ m for cls in self.__class__.mro() for m in cls.__dict__ if m[0] != '_' and m not in self._member_map_ ] + [m for m in self.__dict__ if m[0] != '_'] return (['__class__', '__doc__', '__module__'] + added_behavior)
[ "def", "__dir__", "(", "self", ")", ":", "added_behavior", "=", "[", "m", "for", "cls", "in", "self", ".", "__class__", ".", "mro", "(", ")", "for", "m", "in", "cls", ".", "__dict__", "if", "m", "[", "0", "]", "!=", "'_'", "and", "m", "not", "i...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/enum.py#L743-L753
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/google/protobuf/service_reflection.py
python
_ServiceStubBuilder._StubMethod
(self, stub, method_descriptor, rpc_controller, request, callback)
return stub.rpc_channel.CallMethod( method_descriptor, rpc_controller, request, method_descriptor.output_type._concrete_class, callback)
The body of all service methods in the generated stub class. Args: stub: Stub instance. method_descriptor: Descriptor of the invoked method. rpc_controller: Rpc controller to execute the method. request: Request protocol message. callback: A callback to execute when the method finishes. Returns: Response message (in case of blocking call).
The body of all service methods in the generated stub class.
[ "The", "body", "of", "all", "service", "methods", "in", "the", "generated", "stub", "class", "." ]
def _StubMethod(self, stub, method_descriptor, rpc_controller, request, callback): """The body of all service methods in the generated stub class. Args: stub: Stub instance. method_descriptor: Descriptor of the invoked method. rpc_controller: Rpc controller to execute the method. request: Request protocol message. callback: A callback to execute when the method finishes. Returns: Response message (in case of blocking call). """ return stub.rpc_channel.CallMethod( method_descriptor, rpc_controller, request, method_descriptor.output_type._concrete_class, callback)
[ "def", "_StubMethod", "(", "self", ",", "stub", ",", "method_descriptor", ",", "rpc_controller", ",", "request", ",", "callback", ")", ":", "return", "stub", ".", "rpc_channel", ".", "CallMethod", "(", "method_descriptor", ",", "rpc_controller", ",", "request", ...
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/service_reflection.py#L269-L284
sigmaai/self-driving-golf-cart
8d891600af3d851add27a10ae45cf3c2108bb87c
ros/src/ros_carla_bridge/rqt_carla_control/src/rqt_carla_control/rqt_carla_control.py
python
CarlaControlPlugin.shutdown_plugin
(self)
shutdown plugin
shutdown plugin
[ "shutdown", "plugin" ]
def shutdown_plugin(self): """ shutdown plugin """ self.carla_control_publisher.unregister()
[ "def", "shutdown_plugin", "(", "self", ")", ":", "self", ".", "carla_control_publisher", ".", "unregister", "(", ")" ]
https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/rqt_carla_control/src/rqt_carla_control/rqt_carla_control.py#L101-L105
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
FileType.ExpandCommand
(*args, **kwargs)
return _misc_.FileType_ExpandCommand(*args, **kwargs)
ExpandCommand(String command, String filename, String mimetype=EmptyString) -> String
ExpandCommand(String command, String filename, String mimetype=EmptyString) -> String
[ "ExpandCommand", "(", "String", "command", "String", "filename", "String", "mimetype", "=", "EmptyString", ")", "-", ">", "String" ]
def ExpandCommand(*args, **kwargs): """ExpandCommand(String command, String filename, String mimetype=EmptyString) -> String""" return _misc_.FileType_ExpandCommand(*args, **kwargs)
[ "def", "ExpandCommand", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "FileType_ExpandCommand", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L2629-L2631
ROCmSoftwarePlatform/rocBLAS
3738f8b098cdc1db1bdfc164ceb689d073116c98
rmake.py
python
parse_args
()
return parser.parse_args()
Parse command-line arguments
Parse command-line arguments
[ "Parse", "command", "-", "line", "arguments" ]
def parse_args(): """Parse command-line arguments""" global OS_info parser = argparse.ArgumentParser(description="""Checks build arguments""") parser.add_argument('-a', '--architecture', dest='gpu_architecture', required=False, default="gfx906", #:sramecc+:xnack-" ) #gfx1030" ) #gfx906" ) # gfx1030" ) help='Set GPU architectures, e.g. all, gfx000, gfx803, gfx906:xnack-;gfx1030 (optional, default: all)') parser.add_argument('-b', '--branch', dest='tensile_tag', type=str, required=False, default="", help='Specify the Tensile repository branch or tag to use.(eg. develop, mybranch or <commit hash> )') parser.add_argument( '--build_dir', type=str, required=False, default = "build", help='Specify path to configure & build process output directory.(optional, default: ./build)') parser.add_argument('-c', '--clients', required=False, default = False, dest='build_clients', action='store_true', help='Build the library clients benchmark and gtest (optional, default: False,Generated binaries will be located at builddir/clients/staging)') parser.add_argument( '--clients-only', dest='clients_only', required=False, default = False, action='store_true', help='Skip building the library and only build the clients with a pre-built library.') parser.add_argument( '--cpu_ref_lib', type=str, required=False, default = "blis", help='Specify library to use for CPU reference code in testing (blis or lapack)') parser.add_argument( '--cmake-darg', required=False, dest='cmake_dargs', action='append', default=[], help='List of additional cmake defines for builds (optional, e.g. CMAKE)') parser.add_argument('-f', '--fork', dest='tensile_fork', type=str, required=False, default="", help='Specify the username to fork the Tensile GitHub repository (e.g., ROCmSoftwarePlatform or MyUserName)') parser.add_argument('-g', '--debug', required=False, default = False, action='store_true', help='Build in Debug mode (optional, default: False)') parser.add_argument('-i', '--install', required=False, default = False, dest='install', action='store_true', help='Generate and install library package after build. (optional, default: False)') parser.add_argument('-j', '--jobs', type=int, required=False, default = OS_info["NUM_PROC"], help='Specify number of parallel jobs to launch, increases memory usage (Default logical core count) ') parser.add_argument('-l', '--logic', dest='tensile_logic', type=str, required=False, default="asm_full", help='Specify the Tensile logic target, e.g., asm_full, asm_lite, etc. (optional, default: asm_full)') parser.add_argument( '--library-path', dest='library_dir_installed', type=str, required=False, default = "", help='Specify path to a pre-built rocBLAS library, when building clients only using --clients-only flag. (optional, default: /opt/rocm/rocblas)') parser.add_argument('-n', '--no_tensile', dest='build_tensile', required=False, default=True, action='store_false', help='Build a subset of rocBLAS library which does not require Tensile.') parser.add_argument( '--no-merge-files', dest='merge_files', required=False, default=True, action='store_false', help='Disable Tensile_MERGE_FILES (optional)') parser.add_argument( '--no-msgpack', dest='tensile_msgpack_backend', required=False, default=True, action='store_false', help='Build Tensile backend not to use MessagePack and so use YAML (optional)') parser.add_argument( '--rocm_dev', type=str, required=False, default = "", help='Specify specific rocm-dev version (e.g. 4.5.0).') parser.add_argument( '--skip_ld_conf_entry', required=False, default = False, help='Skip ld.so.conf entry.') parser.add_argument( '--static', required=False, default = False, dest='static_lib', action='store_true', help='Build rocblas as a static library. (optional, default: False)') parser.add_argument('-t', '--test_local_path', dest='tensile_test_local_path', type=str, required=False, default="", help='Use a local path for Tensile instead of remote GIT repo (optional)') parser.add_argument('-u', '--use-custom-version', dest='tensile_version', type=str, required=False, default="", help='Ignore Tensile version and just use the Tensile tag (optional)') parser.add_argument('-v', '--verbose', required=False, default = False, action='store_true', help='Verbose build (optional, default: False)') return parser.parse_args()
[ "def", "parse_args", "(", ")", ":", "global", "OS_info", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"\"\"Checks build arguments\"\"\"", ")", "parser", ".", "add_argument", "(", "'-a'", ",", "'--architecture'", ",", "dest", "=", ...
https://github.com/ROCmSoftwarePlatform/rocBLAS/blob/3738f8b098cdc1db1bdfc164ceb689d073116c98/rmake.py#L18-L90
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/multiarray.py
python
diagflat
(v, k=0)
return _mx_nd_np.diagflat(v, k=k)
Create a two-dimensional array with the flattened input as a diagonal. Parameters ---------- v : array_like Input data, which is flattened and set as the `k`-th diagonal of the output. k : int, optional Diagonal to set; 0, the default, corresponds to the "main" diagonal, a positive (negative) `k` giving the number of the diagonal above (below) the main. Returns ------- out : ndarray The 2-D output array. See Also -------- diag : MATLAB work-alike for 1-D and 2-D arrays. diagonal : Return specified diagonals. trace : Sum along diagonals. Examples -------- >>> np.diagflat([[1,2], [3,4]]) array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) >>> np.diagflat([1,2], 1) array([[0, 1, 0], [0, 0, 2], [0, 0, 0]])
Create a two-dimensional array with the flattened input as a diagonal.
[ "Create", "a", "two", "-", "dimensional", "array", "with", "the", "flattened", "input", "as", "a", "diagonal", "." ]
def diagflat(v, k=0): """ Create a two-dimensional array with the flattened input as a diagonal. Parameters ---------- v : array_like Input data, which is flattened and set as the `k`-th diagonal of the output. k : int, optional Diagonal to set; 0, the default, corresponds to the "main" diagonal, a positive (negative) `k` giving the number of the diagonal above (below) the main. Returns ------- out : ndarray The 2-D output array. See Also -------- diag : MATLAB work-alike for 1-D and 2-D arrays. diagonal : Return specified diagonals. trace : Sum along diagonals. Examples -------- >>> np.diagflat([[1,2], [3,4]]) array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) >>> np.diagflat([1,2], 1) array([[0, 1, 0], [0, 0, 2], [0, 0, 0]]) """ return _mx_nd_np.diagflat(v, k=k)
[ "def", "diagflat", "(", "v", ",", "k", "=", "0", ")", ":", "return", "_mx_nd_np", ".", "diagflat", "(", "v", ",", "k", "=", "k", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L13040-L13077
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py
python
MainWindow.menu_sort_survey_2theta
(self)
sort survey table by 2theta :return:
sort survey table by 2theta :return:
[ "sort", "survey", "table", "by", "2theta", ":", "return", ":" ]
def menu_sort_survey_2theta(self): """ sort survey table by 2theta :return: """ self.ui.tableWidget_surveyTable.filter_and_sort(start_scan=0, end_scan=100000, min_counts=0., max_counts=10000000000., sort_by_column='2theta', sort_order=0)
[ "def", "menu_sort_survey_2theta", "(", "self", ")", ":", "self", ".", "ui", ".", "tableWidget_surveyTable", ".", "filter_and_sort", "(", "start_scan", "=", "0", ",", "end_scan", "=", "100000", ",", "min_counts", "=", "0.", ",", "max_counts", "=", "10000000000....
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py#L3705-L3712
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
FileConfig.GetLocalFileName
(*args, **kwargs)
return _misc_.FileConfig_GetLocalFileName(*args, **kwargs)
GetLocalFileName(String szFile, int style=0) -> String
GetLocalFileName(String szFile, int style=0) -> String
[ "GetLocalFileName", "(", "String", "szFile", "int", "style", "=", "0", ")", "-", ">", "String" ]
def GetLocalFileName(*args, **kwargs): """GetLocalFileName(String szFile, int style=0) -> String""" return _misc_.FileConfig_GetLocalFileName(*args, **kwargs)
[ "def", "GetLocalFileName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "FileConfig_GetLocalFileName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L3522-L3524
Kronuz/Xapiand
a71570859dcfc9f48090d845053f359b07f4f78c
contrib/python/xapiand-py/xapiand/connection_pool.py
python
DummyConnectionPool.close
(self)
Explicitly closes connections
Explicitly closes connections
[ "Explicitly", "closes", "connections" ]
def close(self): """ Explicitly closes connections """ self.connection.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "connection", ".", "close", "(", ")" ]
https://github.com/Kronuz/Xapiand/blob/a71570859dcfc9f48090d845053f359b07f4f78c/contrib/python/xapiand-py/xapiand/connection_pool.py#L280-L284
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/terminal/shortcuts.py
python
next_history_or_next_completion
(event)
Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit. If completer is open this still select next completion.
Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
[ "Control", "-", "N", "in", "vi", "edit", "mode", "on", "readline", "is", "history", "previous", "unlike", "default", "prompt", "toolkit", "." ]
def next_history_or_next_completion(event): """ Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit. If completer is open this still select next completion. """ event.current_buffer.auto_down()
[ "def", "next_history_or_next_completion", "(", "event", ")", ":", "event", ".", "current_buffer", ".", "auto_down", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/terminal/shortcuts.py#L167-L173
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/batch_norm_benchmark.py
python
print_difference
(mode, t1, t2)
Print the difference in timing between two runs.
Print the difference in timing between two runs.
[ "Print", "the", "difference", "in", "timing", "between", "two", "runs", "." ]
def print_difference(mode, t1, t2): """Print the difference in timing between two runs.""" difference = (t2 - t1) / t1 * 100.0 print("=== %s: %.1f%% ===" % (mode, difference))
[ "def", "print_difference", "(", "mode", ",", "t1", ",", "t2", ")", ":", "difference", "=", "(", "t2", "-", "t1", ")", "/", "t1", "*", "100.0", "print", "(", "\"=== %s: %.1f%% ===\"", "%", "(", "mode", ",", "difference", ")", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/batch_norm_benchmark.py#L103-L106
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/process/servers.py
python
ServerAdapter.wait
(self)
Wait until the HTTP server is ready to receive requests.
Wait until the HTTP server is ready to receive requests.
[ "Wait", "until", "the", "HTTP", "server", "is", "ready", "to", "receive", "requests", "." ]
def wait(self): """Wait until the HTTP server is ready to receive requests.""" while not getattr(self.httpserver, "ready", False): if self.interrupt: raise self.interrupt time.sleep(.1) # Wait for port to be occupied if isinstance(self.bind_addr, tuple): host, port = self.bind_addr wait_for_occupied_port(host, port)
[ "def", "wait", "(", "self", ")", ":", "while", "not", "getattr", "(", "self", ".", "httpserver", ",", "\"ready\"", ",", "False", ")", ":", "if", "self", ".", "interrupt", ":", "raise", "self", ".", "interrupt", "time", ".", "sleep", "(", ".1", ")", ...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/process/servers.py#L204-L214
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/combo.py
python
ComboCtrl.SetCustomPaintWidth
(*args, **kwargs)
return _combo.ComboCtrl_SetCustomPaintWidth(*args, **kwargs)
SetCustomPaintWidth(self, int width) Set width, in pixels, of custom painted area in control without wx.CB_READONLY style. In read-only OwnerDrawnComboBox, this is used to indicate the area that is not covered by the focus rectangle.
SetCustomPaintWidth(self, int width)
[ "SetCustomPaintWidth", "(", "self", "int", "width", ")" ]
def SetCustomPaintWidth(*args, **kwargs): """ SetCustomPaintWidth(self, int width) Set width, in pixels, of custom painted area in control without wx.CB_READONLY style. In read-only OwnerDrawnComboBox, this is used to indicate the area that is not covered by the focus rectangle. """ return _combo.ComboCtrl_SetCustomPaintWidth(*args, **kwargs)
[ "def", "SetCustomPaintWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboCtrl_SetCustomPaintWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/combo.py#L302-L310
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/cli/base_ui.py
python
BaseUI._config_command_handler
(self, args, screen_info=None)
Command handler for the "config" command.
Command handler for the "config" command.
[ "Command", "handler", "for", "the", "config", "command", "." ]
def _config_command_handler(self, args, screen_info=None): """Command handler for the "config" command.""" del screen_info # Currently unused. parsed = self._config_argparser.parse_args(args) if hasattr(parsed, "property_name") and hasattr(parsed, "property_value"): # set. self._config.set(parsed.property_name, parsed.property_value) return self._config.summarize(highlight=parsed.property_name) else: # show. return self._config.summarize()
[ "def", "_config_command_handler", "(", "self", ",", "args", ",", "screen_info", "=", "None", ")", ":", "del", "screen_info", "# Currently unused.", "parsed", "=", "self", ".", "_config_argparser", ".", "parse_args", "(", "args", ")", "if", "hasattr", "(", "par...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/base_ui.py#L204-L215
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/mixture/_base.py
python
BaseMixture._estimate_log_weights
(self)
Estimate log-weights in EM algorithm, E[ log pi ] in VB algorithm. Returns ------- log_weight : array, shape (n_components, )
Estimate log-weights in EM algorithm, E[ log pi ] in VB algorithm.
[ "Estimate", "log", "-", "weights", "in", "EM", "algorithm", "E", "[", "log", "pi", "]", "in", "VB", "algorithm", "." ]
def _estimate_log_weights(self): """Estimate log-weights in EM algorithm, E[ log pi ] in VB algorithm. Returns ------- log_weight : array, shape (n_components, ) """ pass
[ "def", "_estimate_log_weights", "(", "self", ")", ":", "pass" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/mixture/_base.py#L457-L464
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/_ctypes/ndarray.py
python
_imperative_invoke
(handle, ndargs, keys, vals, out, is_np_op, output_is_list)
ctypes implementation of imperative invoke wrapper
ctypes implementation of imperative invoke wrapper
[ "ctypes", "implementation", "of", "imperative", "invoke", "wrapper" ]
def _imperative_invoke(handle, ndargs, keys, vals, out, is_np_op, output_is_list): """ctypes implementation of imperative invoke wrapper""" if out is not None: original_output = out if isinstance(out, NDArrayBase): out = (out,) num_output = ctypes.c_int(len(out)) output_vars = c_handle_array(out) output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle)) else: original_output = None output_vars = ctypes.POINTER(NDArrayHandle)() num_output = ctypes.c_int(0) # return output stypes to avoid the c_api call for checking # a handle's stype in _ndarray_cls out_stypes = ctypes.POINTER(ctypes.c_int)() check_call(_LIB.MXImperativeInvoke( ctypes.c_void_p(handle), ctypes.c_int(len(ndargs)), c_handle_array(ndargs), ctypes.byref(num_output), ctypes.byref(output_vars), ctypes.c_int(len(keys)), c_str_array(keys), c_str_array([str(s) for s in vals]), ctypes.byref(out_stypes))) create_ndarray_fn = _global_var._np_ndarray_cls if is_np_op else _global_var._ndarray_cls if original_output is not None: return original_output if num_output.value == 1 and not output_is_list: return create_ndarray_fn(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0]) else: return [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) for i in range(num_output.value)]
[ "def", "_imperative_invoke", "(", "handle", ",", "ndargs", ",", "keys", ",", "vals", ",", "out", ",", "is_np_op", ",", "output_is_list", ")", ":", "if", "out", "is", "not", "None", ":", "original_output", "=", "out", "if", "isinstance", "(", "out", ",", ...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/_ctypes/ndarray.py#L58-L95
wesnoth/wesnoth
6ccac5a5e8ff75303c9190c0da60580925cb32c0
data/tools/wesnoth/libgithub.py
python
Addon._copytree
(self, src, dst, ignore=None)
Recursively copy a directory tree using copy2(). Based on shutil.copytree
Recursively copy a directory tree using copy2().
[ "Recursively", "copy", "a", "directory", "tree", "using", "copy2", "()", "." ]
def _copytree(self, src, dst, ignore=None): """Recursively copy a directory tree using copy2(). Based on shutil.copytree """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() if not os.path.exists(dst): os.makedirs(dst) errors = [] for name in names: if name in ignored_names: continue srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if os.path.isdir(srcname): self._copytree(srcname, dstname, ignore) else: shutil.copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error) as why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files except Error as err: errors.extend(err.args[0]) try: shutil.copystat(src, dst) except OSError as why: if shutil.WindowsError is not None and isinstance(why, shutil.WindowsError): # Copying file access times may fail on Windows pass else: errors.extend((src, dst, str(why))) if errors: raise AddonError(self.name, "Errors attempting to sync:\n{0}".format("\n".join(errors)))
[ "def", "_copytree", "(", "self", ",", "src", ",", "dst", ",", "ignore", "=", "None", ")", ":", "names", "=", "os", ".", "listdir", "(", "src", ")", "if", "ignore", "is", "not", "None", ":", "ignored_names", "=", "ignore", "(", "src", ",", "names", ...
https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/libgithub.py#L237-L277
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.iterkeys
(self)
return iter(self)
od.iterkeys() -> an iterator over the keys in od
od.iterkeys() -> an iterator over the keys in od
[ "od", ".", "iterkeys", "()", "-", ">", "an", "iterator", "over", "the", "keys", "in", "od" ]
def iterkeys(self): 'od.iterkeys() -> an iterator over the keys in od' return iter(self)
[ "def", "iterkeys", "(", "self", ")", ":", "return", "iter", "(", "self", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/ordered_dict.py#L155-L157
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
utils/grid.py
python
TimelineEvent.__init__
(self, name = '')
! Get ranges bounds @param self this object @param name name
! Get ranges bounds
[ "!", "Get", "ranges", "bounds" ]
def __init__(self, name = ''): """! Get ranges bounds @param self this object @param name name """ self.name = name self.events = []
[ "def", "__init__", "(", "self", ",", "name", "=", "''", ")", ":", "self", ".", "name", "=", "name", "self", ".", "events", "=", "[", "]" ]
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/utils/grid.py#L188-L194
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
MenuItem.SetTextColour
(*args, **kwargs)
return _core_.MenuItem_SetTextColour(*args, **kwargs)
SetTextColour(self, Colour colText)
SetTextColour(self, Colour colText)
[ "SetTextColour", "(", "self", "Colour", "colText", ")" ]
def SetTextColour(*args, **kwargs): """SetTextColour(self, Colour colText)""" return _core_.MenuItem_SetTextColour(*args, **kwargs)
[ "def", "SetTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MenuItem_SetTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12561-L12563
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/tutorials/mnist_tflite.py
python
run_eval
(interpreter, input_image)
return output
Performs evaluation for input image over specified model. Args: interpreter: TFLite interpreter initialized with model to execute. input_image: Image input to the model. Returns: output: output tensor of model being executed.
Performs evaluation for input image over specified model.
[ "Performs", "evaluation", "for", "input", "image", "over", "specified", "model", "." ]
def run_eval(interpreter, input_image): """Performs evaluation for input image over specified model. Args: interpreter: TFLite interpreter initialized with model to execute. input_image: Image input to the model. Returns: output: output tensor of model being executed. """ # Get input and output tensors. input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # Test model on the input images. input_image = np.reshape(input_image, input_details[0]['shape']) interpreter.set_tensor(input_details[0]['index'], input_image) interpreter.invoke() output_data = interpreter.get_tensor(output_details[0]['index']) output = np.squeeze(output_data) return output
[ "def", "run_eval", "(", "interpreter", ",", "input_image", ")", ":", "# Get input and output tensors.", "input_details", "=", "interpreter", ".", "get_input_details", "(", ")", "output_details", "=", "interpreter", ".", "get_output_details", "(", ")", "# Test model on t...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/tutorials/mnist_tflite.py#L46-L68
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/agents/tools/wrappers.py
python
ConvertTo32Bit.step
(self, action)
return observ, reward, done, info
Forward action to the wrapped environment. Args: action: Action to apply to the environment. Raises: ValueError: Invalid action. Returns: Converted observation, converted reward, done flag, and info object.
Forward action to the wrapped environment.
[ "Forward", "action", "to", "the", "wrapped", "environment", "." ]
def step(self, action): """Forward action to the wrapped environment. Args: action: Action to apply to the environment. Raises: ValueError: Invalid action. Returns: Converted observation, converted reward, done flag, and info object. """ observ, reward, done, info = self._env.step(action) observ = self._convert_observ(observ) reward = self._convert_reward(reward) return observ, reward, done, info
[ "def", "step", "(", "self", ",", "action", ")", ":", "observ", ",", "reward", ",", "done", ",", "info", "=", "self", ".", "_env", ".", "step", "(", "action", ")", "observ", "=", "self", ".", "_convert_observ", "(", "observ", ")", "reward", "=", "se...
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/agents/tools/wrappers.py#L488-L503
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/EventHeader.py
python
EventHeader.addVisitor
(self, visitor)
Add a visitor to the list of visitors. @param visitor: the visitor to add, must be derived from AbstractVisitor.
Add a visitor to the list of visitors.
[ "Add", "a", "visitor", "to", "the", "list", "of", "visitors", "." ]
def addVisitor(self, visitor): """ Add a visitor to the list of visitors. @param visitor: the visitor to add, must be derived from AbstractVisitor. """ if issubclass(visitor.__class__, AbstractVisitor.AbstractVisitor): self.__visitor_list.append(visitor) else: DEBUG.error( "EventHeader.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!" ) raise Exception( "EventHeader.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!" )
[ "def", "addVisitor", "(", "self", ",", "visitor", ")", ":", "if", "issubclass", "(", "visitor", ".", "__class__", ",", "AbstractVisitor", ".", "AbstractVisitor", ")", ":", "self", ".", "__visitor_list", ".", "append", "(", "visitor", ")", "else", ":", "DEB...
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/EventHeader.py#L86-L99
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/__init__.py
python
escape2null
(text)
Return a string with escape-backslashes converted to nulls.
Return a string with escape-backslashes converted to nulls.
[ "Return", "a", "string", "with", "escape", "-", "backslashes", "converted", "to", "nulls", "." ]
def escape2null(text): """Return a string with escape-backslashes converted to nulls.""" parts = [] start = 0 while True: found = text.find('\\', start) if found == -1: parts.append(text[start:]) return ''.join(parts) parts.append(text[start:found]) parts.append('\x00' + text[found+1:found+2]) start = found + 2
[ "def", "escape2null", "(", "text", ")", ":", "parts", "=", "[", "]", "start", "=", "0", "while", "True", ":", "found", "=", "text", ".", "find", "(", "'\\\\'", ",", "start", ")", "if", "found", "==", "-", "1", ":", "parts", ".", "append", "(", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/__init__.py#L566-L577
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/html5lib/treebuilders/base.py
python
Node.removeChild
(self, node)
Remove node from the children of the current node :arg node: the child node to remove
Remove node from the children of the current node
[ "Remove", "node", "from", "the", "children", "of", "the", "current", "node" ]
def removeChild(self, node): """Remove node from the children of the current node :arg node: the child node to remove """ raise NotImplementedError
[ "def", "removeChild", "(", "self", ",", "node", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/html5lib/treebuilders/base.py#L177-L189
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/directives/html.py
python
MetaBody.field_marker
(self, match, context, next_state)
return [], next_state, []
Meta element.
Meta element.
[ "Meta", "element", "." ]
def field_marker(self, match, context, next_state): """Meta element.""" node, blank_finish = self.parsemeta(match) self.parent += node return [], next_state, []
[ "def", "field_marker", "(", "self", ",", "match", ",", "context", ",", "next_state", ")", ":", "node", ",", "blank_finish", "=", "self", ".", "parsemeta", "(", "match", ")", "self", ".", "parent", "+=", "node", "return", "[", "]", ",", "next_state", ",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/directives/html.py#L24-L28
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/fields.py
python
RequestField.from_tuples
(cls, fieldname, value, header_formatter=format_header_param_html5)
return request_param
A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', Field names and filenames must be unicode.
A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
[ "A", ":", "class", ":", "~urllib3", ".", "fields", ".", "RequestField", "factory", "from", "old", "-", "style", "tuple", "parameters", "." ]
def from_tuples(cls, fieldname, value, header_formatter=format_header_param_html5): """ A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', Field names and filenames must be unicode. """ if isinstance(value, tuple): if len(value) == 3: filename, data, content_type = value else: filename, data = value content_type = guess_content_type(filename) else: filename = None content_type = None data = value request_param = cls( fieldname, data, filename=filename, header_formatter=header_formatter ) request_param.make_multipart(content_type=content_type) return request_param
[ "def", "from_tuples", "(", "cls", ",", "fieldname", ",", "value", ",", "header_formatter", "=", "format_header_param_html5", ")", ":", "if", "isinstance", "(", "value", ",", "tuple", ")", ":", "if", "len", "(", "value", ")", "==", "3", ":", "filename", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/fields.py#L159-L192
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/dataview.py
python
DataViewCtrl.GetCurrentItem
(*args, **kwargs)
return _dataview.DataViewCtrl_GetCurrentItem(*args, **kwargs)
GetCurrentItem(self) -> DataViewItem
GetCurrentItem(self) -> DataViewItem
[ "GetCurrentItem", "(", "self", ")", "-", ">", "DataViewItem" ]
def GetCurrentItem(*args, **kwargs): """GetCurrentItem(self) -> DataViewItem""" return _dataview.DataViewCtrl_GetCurrentItem(*args, **kwargs)
[ "def", "GetCurrentItem", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewCtrl_GetCurrentItem", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L1743-L1745
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/control/robotinterface.py
python
RobotInterfaceBase.velocityFromKlampt
(self, klamptVelocity: Vector, part: Optional[str] = None, joint_idx: Optional[int] = None )
return [vdrivers[i] for i in self.indices(part,joint_idx)]
Extracts a RobotInterfaceBase velocity from a velocity of the Klampt model.
Extracts a RobotInterfaceBase velocity from a velocity of the Klampt model.
[ "Extracts", "a", "RobotInterfaceBase", "velocity", "from", "a", "velocity", "of", "the", "Klampt", "model", "." ]
def velocityFromKlampt(self, klamptVelocity: Vector, part: Optional[str] = None, joint_idx: Optional[int] = None ) -> Vector: """Extracts a RobotInterfaceBase velocity from a velocity of the Klampt model.""" model = self.klamptModel() if model is None: return klamptVelocity if len(klamptVelocity) != model.numLinks(): raise ValueError("Length of klamptVelocity is invalid for "+str(self)) vdrivers = model.velocityToDrivers(klamptVelocity) if part is None and joint_idx is None: return vdrivers return [vdrivers[i] for i in self.indices(part,joint_idx)]
[ "def", "velocityFromKlampt", "(", "self", ",", "klamptVelocity", ":", "Vector", ",", "part", ":", "Optional", "[", "str", "]", "=", "None", ",", "joint_idx", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Vector", ":", "model", "=", "self",...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterface.py#L897-L912
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/bintrees/bintrees/bintree.py
python
BinaryTree.__init__
(self, items=None)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
[ "x", ".", "__init__", "(", "...", ")", "initializes", "x", ";", "see", "x", ".", "__class__", ".", "__doc__", "for", "signature" ]
def __init__(self, items=None): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signature """ self._root = None self._count = 0 if items is not None: self.update(items)
[ "def", "__init__", "(", "self", ",", "items", "=", "None", ")", ":", "self", ".", "_root", "=", "None", "self", ".", "_count", "=", "0", "if", "items", "is", "not", "None", ":", "self", ".", "update", "(", "items", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/bintrees/bintrees/bintree.py#L61-L66
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/psutil/psutil/__init__.py
python
Process.username
(self)
The name of the user that owns the process. On UNIX this is calculated by using *real* process uid.
The name of the user that owns the process. On UNIX this is calculated by using *real* process uid.
[ "The", "name", "of", "the", "user", "that", "owns", "the", "process", ".", "On", "UNIX", "this", "is", "calculated", "by", "using", "*", "real", "*", "process", "uid", "." ]
def username(self): """The name of the user that owns the process. On UNIX this is calculated by using *real* process uid. """ if os.name == 'posix': if pwd is None: # might happen if python was installed from sources raise ImportError("requires pwd module shipped with standard python") return pwd.getpwuid(self.uids.real).pw_name else: return self._platform_impl.get_process_username()
[ "def", "username", "(", "self", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "if", "pwd", "is", "None", ":", "# might happen if python was installed from sources", "raise", "ImportError", "(", "\"requires pwd module shipped with standard python\"", ")", "r...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/__init__.py#L377-L387
yarny/gbdt
c99d90d7de57705c30b05d520a32e458985fd834
gbdt/_data_store.py
python
DataLoader.from_dict
(bucketized_float_cols={}, string_cols={}, raw_float_cols={})
return DataStore(d)
Loads data from dict of columns. bucketized_float_cols: Float columns that will be bucketized. All features will be bucketized. string_cols: String cols. raw_float_cols: Float columns that are loaded raw. Target columns are usually not bucketized.
Loads data from dict of columns. bucketized_float_cols: Float columns that will be bucketized. All features will be bucketized. string_cols: String cols. raw_float_cols: Float columns that are loaded raw. Target columns are usually not bucketized.
[ "Loads", "data", "from", "dict", "of", "columns", ".", "bucketized_float_cols", ":", "Float", "columns", "that", "will", "be", "bucketized", ".", "All", "features", "will", "be", "bucketized", ".", "string_cols", ":", "String", "cols", ".", "raw_float_cols", "...
def from_dict(bucketized_float_cols={}, string_cols={}, raw_float_cols={}): """Loads data from dict of columns. bucketized_float_cols: Float columns that will be bucketized. All features will be bucketized. string_cols: String cols. raw_float_cols: Float columns that are loaded raw. Target columns are usually not bucketized. """ d = libgbdt.DataStore() for key, value in bucketized_float_cols.items(): d.add_bucketized_float_col(key, value) for key, value in string_cols.items(): d.add_string_col(key, value) for key, value in raw_float_cols.items(): d.add_raw_float_col(key, value) return DataStore(d)
[ "def", "from_dict", "(", "bucketized_float_cols", "=", "{", "}", ",", "string_cols", "=", "{", "}", ",", "raw_float_cols", "=", "{", "}", ")", ":", "d", "=", "libgbdt", ".", "DataStore", "(", ")", "for", "key", ",", "value", "in", "bucketized_float_cols"...
https://github.com/yarny/gbdt/blob/c99d90d7de57705c30b05d520a32e458985fd834/gbdt/_data_store.py#L125-L139
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/xml/sax/_exceptions.py
python
SAXException.__getitem__
(self, ix)
Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.
Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.
[ "Avoids", "weird", "error", "messages", "if", "someone", "does", "exception", "[", "ix", "]", "by", "mistake", "since", "Exception", "has", "__getitem__", "defined", "." ]
def __getitem__(self, ix): """Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.""" raise AttributeError("__getitem__")
[ "def", "__getitem__", "(", "self", ",", "ix", ")", ":", "raise", "AttributeError", "(", "\"__getitem__\"", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/xml/sax/_exceptions.py#L38-L41
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/filters.py
python
do_first
(environment, seq)
Return the first item of a sequence.
Return the first item of a sequence.
[ "Return", "the", "first", "item", "of", "a", "sequence", "." ]
def do_first(environment, seq): """Return the first item of a sequence.""" try: return next(iter(seq)) except StopIteration: return environment.undefined('No first item, sequence was empty.')
[ "def", "do_first", "(", "environment", ",", "seq", ")", ":", "try", ":", "return", "next", "(", "iter", "(", "seq", ")", ")", "except", "StopIteration", ":", "return", "environment", ".", "undefined", "(", "'No first item, sequence was empty.'", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/filters.py#L433-L438
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/feature_column/sequence_feature_column.py
python
concatenate_context_input
(context_input, sequence_input)
return array_ops.concat([sequence_input, tiled_context_input], 2)
Replicates `context_input` across all timesteps of `sequence_input`. Expands dimension 1 of `context_input` then tiles it `sequence_length` times. This value is appended to `sequence_input` on dimension 2 and the result is returned. Args: context_input: A `Tensor` of dtype `float32` and shape `[batch_size, d1]`. sequence_input: A `Tensor` of dtype `float32` and shape `[batch_size, padded_length, d0]`. Returns: A `Tensor` of dtype `float32` and shape `[batch_size, padded_length, d0 + d1]`. Raises: ValueError: If `sequence_input` does not have rank 3 or `context_input` does not have rank 2.
Replicates `context_input` across all timesteps of `sequence_input`.
[ "Replicates", "context_input", "across", "all", "timesteps", "of", "sequence_input", "." ]
def concatenate_context_input(context_input, sequence_input): """Replicates `context_input` across all timesteps of `sequence_input`. Expands dimension 1 of `context_input` then tiles it `sequence_length` times. This value is appended to `sequence_input` on dimension 2 and the result is returned. Args: context_input: A `Tensor` of dtype `float32` and shape `[batch_size, d1]`. sequence_input: A `Tensor` of dtype `float32` and shape `[batch_size, padded_length, d0]`. Returns: A `Tensor` of dtype `float32` and shape `[batch_size, padded_length, d0 + d1]`. Raises: ValueError: If `sequence_input` does not have rank 3 or `context_input` does not have rank 2. """ seq_rank_check = check_ops.assert_rank( sequence_input, 3, message='sequence_input must have rank 3', data=[array_ops.shape(sequence_input)]) seq_type_check = check_ops.assert_type( sequence_input, dtypes.float32, message='sequence_input must have dtype float32; got {}.'.format( sequence_input.dtype)) ctx_rank_check = check_ops.assert_rank( context_input, 2, message='context_input must have rank 2', data=[array_ops.shape(context_input)]) ctx_type_check = check_ops.assert_type( context_input, dtypes.float32, message='context_input must have dtype float32; got {}.'.format( context_input.dtype)) with ops.control_dependencies( [seq_rank_check, seq_type_check, ctx_rank_check, ctx_type_check]): padded_length = array_ops.shape(sequence_input)[1] tiled_context_input = array_ops.tile( array_ops.expand_dims(context_input, 1), array_ops.concat([[1], [padded_length], [1]], 0)) return array_ops.concat([sequence_input, tiled_context_input], 2)
[ "def", "concatenate_context_input", "(", "context_input", ",", "sequence_input", ")", ":", "seq_rank_check", "=", "check_ops", ".", "assert_rank", "(", "sequence_input", ",", "3", ",", "message", "=", "'sequence_input must have rank 3'", ",", "data", "=", "[", "arra...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/sequence_feature_column.py#L37-L83
Ewenwan/MVision
97b394dfa48cb21c82cd003b1a952745e413a17f
CNN/yolo_v1_tf.py
python
Yolo.show_results
(self, image, results, imshow=True, deteted_boxes_file=None, detected_image_file=None)
Show the detection boxes
Show the detection boxes
[ "Show", "the", "detection", "boxes" ]
def show_results(self, image, results, imshow=True, deteted_boxes_file=None, detected_image_file=None): """Show the detection boxes""" img_cp = image.copy()#赋值原图像 因为要修改 画 矩形在上面 if deteted_boxes_file: f = open(deteted_boxes_file, "w")#写文件 # draw boxes for i in range(len(results)): x = int(results[i][1])#中心点坐标 y = int(results[i][2])# w = int(results[i][3]) // 2# 矩形框宽度 h = int(results[i][4]) // 2# 矩形框高度 if self.verbose:#打印调试信息 print(" class: %s, [x, y, w, h]=[%d, %d, %d, %d], confidence=%f" % (results[i][0], x, y, w, h, results[i][-1])) cv2.rectangle(img_cp, (x - w, y - h), (x + w, y + h), (0, 255, 0), 2) cv2.rectangle(img_cp, (x - w, y - h - 20), (x + w, y - h), (125, 125, 125), -1) cv2.putText(img_cp, results[i][0] + ' : %.2f' % results[i][5], (x - w + 5, y - h - 7), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1) if deteted_boxes_file: f.write(results[i][0] + ',' + str(x) + ',' + str(y) + ',' + str(w) + ',' + str(h)+',' + str(results[i][5]) + '\n') if imshow: cv2.imshow('YOLO_small detection', img_cp) cv2.waitKey(1) if detected_image_file: cv2.imwrite(detected_image_file, img_cp) if deteted_boxes_file: f.close()
[ "def", "show_results", "(", "self", ",", "image", ",", "results", ",", "imshow", "=", "True", ",", "deteted_boxes_file", "=", "None", ",", "detected_image_file", "=", "None", ")", ":", "img_cp", "=", "image", ".", "copy", "(", ")", "#赋值原图像 因为要修改 画 矩形在上面", ...
https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/CNN/yolo_v1_tf.py#L212-L241
Tencent/Pebble
68315f176d9e328a233ace29b7579a829f89879f
tools/blade/src/blade/blade_platform.py
python
SconsPlatform.get_gcc_version
(self)
return self.gcc_version
Returns gcc version.
Returns gcc version.
[ "Returns", "gcc", "version", "." ]
def get_gcc_version(self): """Returns gcc version. """ return self.gcc_version
[ "def", "get_gcc_version", "(", "self", ")", ":", "return", "self", ".", "gcc_version" ]
https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/blade_platform.py#L145-L147
libfive/libfive
ab5e354cf6fd992f80aaa9432c52683219515c8a
libfive/bind/python/libfive/shape.py
python
Shape.save_stl
(self, filename, xyz_min=(-10,-10,-10), xyz_max=(10,10,10), resolution=10)
Converts this Shape into a mesh and saves it as an STL file. xyz_min/max are three-element lists of corner positions resolution is the reciprocal of minimum feature size (larger values = higher resolution = slower)
Converts this Shape into a mesh and saves it as an STL file.
[ "Converts", "this", "Shape", "into", "a", "mesh", "and", "saves", "it", "as", "an", "STL", "file", "." ]
def save_stl(self, filename, xyz_min=(-10,-10,-10), xyz_max=(10,10,10), resolution=10): ''' Converts this Shape into a mesh and saves it as an STL file. xyz_min/max are three-element lists of corner positions resolution is the reciprocal of minimum feature size (larger values = higher resolution = slower) ''' region = libfive_region_t(*[libfive_interval_t(a, b) for a, b in zip(xyz_min, xyz_max)]) lib.libfive_tree_save_mesh(self.ptr, region, resolution, filename.encode('ascii'))
[ "def", "save_stl", "(", "self", ",", "filename", ",", "xyz_min", "=", "(", "-", "10", ",", "-", "10", ",", "-", "10", ")", ",", "xyz_max", "=", "(", "10", ",", "10", ",", "10", ")", ",", "resolution", "=", "10", ")", ":", "region", "=", "libf...
https://github.com/libfive/libfive/blob/ab5e354cf6fd992f80aaa9432c52683219515c8a/libfive/bind/python/libfive/shape.py#L232-L243
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
PythonAPI/examples/automatic_control.py
python
HUD.notification
(self, text, seconds=2.0)
Notification text
Notification text
[ "Notification", "text" ]
def notification(self, text, seconds=2.0): """Notification text""" self._notifications.set_text(text, seconds=seconds)
[ "def", "notification", "(", "self", ",", "text", ",", "seconds", "=", "2.0", ")", ":", "self", ".", "_notifications", ".", "set_text", "(", "text", ",", "seconds", "=", "seconds", ")" ]
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/examples/automatic_control.py#L334-L336
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/jinja2/ext.py
python
Extension.parse
(self, parser)
If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.
If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.
[ "If", "any", "of", "the", ":", "attr", ":", "tags", "matched", "this", "method", "is", "called", "with", "the", "parser", "as", "first", "argument", ".", "The", "token", "the", "parser", "stream", "is", "pointing", "at", "is", "the", "name", "token", "...
def parse(self, parser): """If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes. """ raise NotImplementedError()
[ "def", "parse", "(", "self", ",", "parser", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/ext.py#L96-L102
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.SetMouseDwellTime
(*args, **kwargs)
return _stc.StyledTextCtrl_SetMouseDwellTime(*args, **kwargs)
SetMouseDwellTime(self, int periodMilliseconds) Sets the time the mouse must sit still to generate a mouse dwell event.
SetMouseDwellTime(self, int periodMilliseconds)
[ "SetMouseDwellTime", "(", "self", "int", "periodMilliseconds", ")" ]
def SetMouseDwellTime(*args, **kwargs): """ SetMouseDwellTime(self, int periodMilliseconds) Sets the time the mouse must sit still to generate a mouse dwell event. """ return _stc.StyledTextCtrl_SetMouseDwellTime(*args, **kwargs)
[ "def", "SetMouseDwellTime", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetMouseDwellTime", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L4039-L4045
KhronosGroup/OpenCOLLADA
6031fa956e1da4bbdd910af3a8f9e924ef0fca7a
Externals/LibXML/python/libxml.py
python
SAXCallback.elementDecl
(self, name, type, content)
called when an ELEMENT definition has been found
called when an ELEMENT definition has been found
[ "called", "when", "an", "ELEMENT", "definition", "has", "been", "found" ]
def elementDecl(self, name, type, content): """called when an ELEMENT definition has been found""" pass
[ "def", "elementDecl", "(", "self", ",", "name", ",", "type", ",", "content", ")", ":", "pass" ]
https://github.com/KhronosGroup/OpenCOLLADA/blob/6031fa956e1da4bbdd910af3a8f9e924ef0fca7a/Externals/LibXML/python/libxml.py#L212-L214
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/clang/tools/scan-build-py/libscanbuild/intercept.py
python
setup_environment
(args, destination)
return environment
Sets up the environment for the build command. It sets the required environment variables and execute the given command. The exec calls will be logged by the 'libear' preloaded library or by the 'wrapper' programs.
Sets up the environment for the build command.
[ "Sets", "up", "the", "environment", "for", "the", "build", "command", "." ]
def setup_environment(args, destination): """ Sets up the environment for the build command. It sets the required environment variables and execute the given command. The exec calls will be logged by the 'libear' preloaded library or by the 'wrapper' programs. """ c_compiler = args.cc if 'cc' in args else 'cc' cxx_compiler = args.cxx if 'cxx' in args else 'c++' libear_path = None if args.override_compiler or is_preload_disabled( sys.platform) else build_libear(c_compiler, destination) environment = dict(os.environ) environment.update({'INTERCEPT_BUILD_TARGET_DIR': destination}) if not libear_path: logging.debug('intercept gonna use compiler wrappers') environment.update(wrapper_environment(args)) environment.update({ 'CC': COMPILER_WRAPPER_CC, 'CXX': COMPILER_WRAPPER_CXX }) elif sys.platform == 'darwin': logging.debug('intercept gonna preload libear on OSX') environment.update({ 'DYLD_INSERT_LIBRARIES': libear_path, 'DYLD_FORCE_FLAT_NAMESPACE': '1' }) else: logging.debug('intercept gonna preload libear on UNIX') environment.update({'LD_PRELOAD': libear_path}) return environment
[ "def", "setup_environment", "(", "args", ",", "destination", ")", ":", "c_compiler", "=", "args", ".", "cc", "if", "'cc'", "in", "args", "else", "'cc'", "cxx_compiler", "=", "args", ".", "cxx", "if", "'cxx'", "in", "args", "else", "'c++'", "libear_path", ...
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/tools/scan-build-py/libscanbuild/intercept.py#L103-L136
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/datasets/_base.py
python
clear_data_home
(data_home=None)
Delete all the content of the data home cache. Parameters ---------- data_home : str | None The path to scikit-learn data dir.
Delete all the content of the data home cache.
[ "Delete", "all", "the", "content", "of", "the", "data", "home", "cache", "." ]
def clear_data_home(data_home=None): """Delete all the content of the data home cache. Parameters ---------- data_home : str | None The path to scikit-learn data dir. """ data_home = get_data_home(data_home) shutil.rmtree(data_home)
[ "def", "clear_data_home", "(", "data_home", "=", "None", ")", ":", "data_home", "=", "get_data_home", "(", "data_home", ")", "shutil", ".", "rmtree", "(", "data_home", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/datasets/_base.py#L58-L67
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/math_ops.py
python
reduce_max
(input_tensor, reduction_indices=None, keep_dims=False, name=None)
return gen_math_ops._max(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
Computes the maximum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor.
Computes the maximum of elements across dimensions of a tensor.
[ "Computes", "the", "maximum", "of", "elements", "across", "dimensions", "of", "a", "tensor", "." ]
def reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the maximum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._max(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
[ "def", "reduce_max", "(", "input_tensor", ",", "reduction_indices", "=", "None", ",", "keep_dims", "=", "False", ",", "name", "=", "None", ")", ":", "return", "gen_math_ops", ".", "_max", "(", "input_tensor", ",", "_ReductionDims", "(", "input_tensor", ",", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L1152-L1176
bareos/bareos
56a10bb368b0a81e977bb51304033fe49d59efb0
python-bareos/bareos/bsock/lowlevel.py
python
LowLevel.get_tls_psk_identity
(self)
return bytes(bytearray(result, "utf-8"))
Bareos TLS-PSK excepts the identiy is a specific format.
Bareos TLS-PSK excepts the identiy is a specific format.
[ "Bareos", "TLS", "-", "PSK", "excepts", "the", "identiy", "is", "a", "specific", "format", "." ]
def get_tls_psk_identity(self): """Bareos TLS-PSK excepts the identiy is a specific format.""" name = str(self.name) if isinstance(self.name, bytes): name = self.name.decode("utf-8") result = u"{0}{1}{2}".format( self.identity_prefix, Constants.record_separator, name ) return bytes(bytearray(result, "utf-8"))
[ "def", "get_tls_psk_identity", "(", "self", ")", ":", "name", "=", "str", "(", "self", ".", "name", ")", "if", "isinstance", "(", "self", ".", "name", ",", "bytes", ")", ":", "name", "=", "self", ".", "name", ".", "decode", "(", "\"utf-8\"", ")", "...
https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/python-bareos/bareos/bsock/lowlevel.py#L273-L281
nektra/Deviare-InProc
e88b91afff32b773b10deeb82a928c6d4af1a9c2
NktHookLib/Src/libudis86/source/scripts/ud_opcode.py
python
UdOpcodeTables.walk
(self, tbl, opcodes)
return e
Walk down the opcode trie, starting at a given opcode table, given a string of opcodes. Return None if unable to walk, the object at the leaf otherwise.
Walk down the opcode trie, starting at a given opcode table, given a string of opcodes. Return None if unable to walk, the object at the leaf otherwise.
[ "Walk", "down", "the", "opcode", "trie", "starting", "at", "a", "given", "opcode", "table", "given", "a", "string", "of", "opcodes", ".", "Return", "None", "if", "unable", "to", "walk", "the", "object", "at", "the", "leaf", "otherwise", "." ]
def walk(self, tbl, opcodes): """Walk down the opcode trie, starting at a given opcode table, given a string of opcodes. Return None if unable to walk, the object at the leaf otherwise. """ opc = opcodes[0] e = tbl.lookup(opc) if e is None: return None elif isinstance(e, UdOpcodeTable) and len(opcodes[1:]): return self.walk(e, opcodes[1:]) return e
[ "def", "walk", "(", "self", ",", "tbl", ",", "opcodes", ")", ":", "opc", "=", "opcodes", "[", "0", "]", "e", "=", "tbl", ".", "lookup", "(", "opc", ")", "if", "e", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "e", ",", "UdOpc...
https://github.com/nektra/Deviare-InProc/blob/e88b91afff32b773b10deeb82a928c6d4af1a9c2/NktHookLib/Src/libudis86/source/scripts/ud_opcode.py#L279-L290
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathUtils.py
python
depth_params.final_depth
(self)
return self.__final_depth
The height of the cutter during the last pass or finish pass if z_finish_pass is given.
The height of the cutter during the last pass or finish pass if z_finish_pass is given.
[ "The", "height", "of", "the", "cutter", "during", "the", "last", "pass", "or", "finish", "pass", "if", "z_finish_pass", "is", "given", "." ]
def final_depth(self): """ The height of the cutter during the last pass or finish pass if z_finish_pass is given. """ return self.__final_depth
[ "def", "final_depth", "(", "self", ")", ":", "return", "self", ".", "__final_depth" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathUtils.py#L665-L670
iam-abbas/cs-algorithms
d04aa8fd9a1fa290266dde96afe9b90ee23c5a92
Backtracking/KnightTour/py/KnightTour.py
python
solveKT
()
This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions.
This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions.
[ "This", "function", "solves", "the", "Knight", "Tour", "problem", "using", "Backtracking", ".", "This", "function", "mainly", "uses", "solveKTUtil", "()", "to", "solve", "the", "problem", ".", "It", "returns", "false", "if", "no", "complete", "tour", "is", "...
def solveKT(): ''' This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. ''' # Initialization of Board matrix board = [[-1 for i in range(n)]for i in range(n)] # move_x and move_y define next move of Knight. # move_x is for next value of x coordinate # move_y is for next value of y coordinate move_x = [2, 1, -1, -2, -2, -1, 1, 2] move_y = [1, 2, 2, 1, -1, -2, -2, -1] # Since the Knight is initially at the first block board[0][0] = 0 # Step counter for knight's position pos = 1 # Checking if solution exists or not if(not solveKTUtil(board, 0, 0, move_x, move_y, pos)): print("Solution does not exist") else: printSolution(board)
[ "def", "solveKT", "(", ")", ":", "# Initialization of Board matrix ", "board", "=", "[", "[", "-", "1", "for", "i", "in", "range", "(", "n", ")", "]", "for", "i", "in", "range", "(", "n", ")", "]", "# move_x and move_y define next move of Knight. ", "# move_...
https://github.com/iam-abbas/cs-algorithms/blob/d04aa8fd9a1fa290266dde96afe9b90ee23c5a92/Backtracking/KnightTour/py/KnightTour.py#L25-L55
Yelp/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
moe/optimal_learning/python/interfaces/covariance_interface.py
python
CovarianceInterface.num_hyperparameters
(self)
Return the number of hyperparameters of this covariance function.
Return the number of hyperparameters of this covariance function.
[ "Return", "the", "number", "of", "hyperparameters", "of", "this", "covariance", "function", "." ]
def num_hyperparameters(self): """Return the number of hyperparameters of this covariance function.""" pass
[ "def", "num_hyperparameters", "(", "self", ")", ":", "pass" ]
https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/interfaces/covariance_interface.py#L54-L56
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Window.Enable
(*args, **kwargs)
return _core_.Window_Enable(*args, **kwargs)
Enable(self, bool enable=True) -> bool Enable or disable the window for user input. Note that when a parent window is disabled, all of its children are disabled as well and they are reenabled again when the parent is. Returns true if the window has been enabled or disabled, false if nothing was done, i.e. if the window had already been in the specified state.
Enable(self, bool enable=True) -> bool
[ "Enable", "(", "self", "bool", "enable", "=", "True", ")", "-", ">", "bool" ]
def Enable(*args, **kwargs): """ Enable(self, bool enable=True) -> bool Enable or disable the window for user input. Note that when a parent window is disabled, all of its children are disabled as well and they are reenabled again when the parent is. Returns true if the window has been enabled or disabled, false if nothing was done, i.e. if the window had already been in the specified state. """ return _core_.Window_Enable(*args, **kwargs)
[ "def", "Enable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_Enable", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L9958-L9968
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/backends/cudnn/__init__.py
python
is_available
()
return torch._C.has_cudnn
r"""Returns a bool indicating if CUDNN is currently available.
r"""Returns a bool indicating if CUDNN is currently available.
[ "r", "Returns", "a", "bool", "indicating", "if", "CUDNN", "is", "currently", "available", "." ]
def is_available(): r"""Returns a bool indicating if CUDNN is currently available.""" return torch._C.has_cudnn
[ "def", "is_available", "(", ")", ":", "return", "torch", ".", "_C", ".", "has_cudnn" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/backends/cudnn/__init__.py#L62-L64
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/less.py
python
_less_tbe
()
return
Less TBE register
Less TBE register
[ "Less", "TBE", "register" ]
def _less_tbe(): """Less TBE register""" return
[ "def", "_less_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/less.py#L39-L41
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py
python
SubstitutionEnvironment.AddMethod
(self, function, name=None)
Adds the specified function as a method of this construction environment with the specified name. If the name is omitted, the default name is the name of the function itself.
Adds the specified function as a method of this construction environment with the specified name. If the name is omitted, the default name is the name of the function itself.
[ "Adds", "the", "specified", "function", "as", "a", "method", "of", "this", "construction", "environment", "with", "the", "specified", "name", ".", "If", "the", "name", "is", "omitted", "the", "default", "name", "is", "the", "name", "of", "the", "function", ...
def AddMethod(self, function, name=None): """ Adds the specified function as a method of this construction environment with the specified name. If the name is omitted, the default name is the name of the function itself. """ method = MethodWrapper(self, function, name) self.added_methods.append(method)
[ "def", "AddMethod", "(", "self", ",", "function", ",", "name", "=", "None", ")", ":", "method", "=", "MethodWrapper", "(", "self", ",", "function", ",", "name", ")", "self", ".", "added_methods", ".", "append", "(", "method", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py#L592-L599
koying/SPMC
beca52667112f2661204ebb42406115825512491
tools/EventClients/lib/python/xbmcclient.py
python
Packet.num_packets
(self)
return self.maxseq
Return the number of packets required for payload
Return the number of packets required for payload
[ "Return", "the", "number", "of", "packets", "required", "for", "payload" ]
def num_packets(self): """ Return the number of packets required for payload """ return self.maxseq
[ "def", "num_packets", "(", "self", ")", ":", "return", "self", ".", "maxseq" ]
https://github.com/koying/SPMC/blob/beca52667112f2661204ebb42406115825512491/tools/EventClients/lib/python/xbmcclient.py#L174-L176
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/context.py
python
Context.scope_name
(self)
return self._thread_local_data.scope_name
Returns scope name for the current thread.
Returns scope name for the current thread.
[ "Returns", "scope", "name", "for", "the", "current", "thread", "." ]
def scope_name(self): """Returns scope name for the current thread.""" return self._thread_local_data.scope_name
[ "def", "scope_name", "(", "self", ")", ":", "return", "self", ".", "_thread_local_data", ".", "scope_name" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L972-L974
lballabio/quantlib-old
136336947ed4fea9ecc1da6edad188700e821739
gensrc/gensrc/addins/doxygen.py
python
Doxygen.generateDocs
(self)
Generate doxygen documentation files.
Generate doxygen documentation files.
[ "Generate", "doxygen", "documentation", "files", "." ]
def generateDocs(self): """Generate doxygen documentation files.""" allFuncs = [] for cat in self.categoryList_.categories( '*', self.coreCategories_, self.addinCategories_): bufLink = '' bufDoc = '' for func in cat.functions('*'): if not func.visible(): continue bufLink += '\\ref %s ()\\n\n' % func.name() bufDoc += self.generateFunctionDoc(func) allFuncs.append(func.name()) self.bufferFile_.set({ 'categoryDescription' : cat.description(), 'categoryDisplayName' : cat.displayName(), 'categoryName' : cat.name(), 'documentation' : bufDoc, 'links' : bufLink }) fileName = self.rootPath_ + cat.name() + '.docs' outputfile.OutputFile(self, fileName, cat.copyright(), self.bufferFile_) self.generateFunctionList(allFuncs)
[ "def", "generateDocs", "(", "self", ")", ":", "allFuncs", "=", "[", "]", "for", "cat", "in", "self", ".", "categoryList_", ".", "categories", "(", "'*'", ",", "self", ".", "coreCategories_", ",", "self", ".", "addinCategories_", ")", ":", "bufLink", "=",...
https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/addins/doxygen.py#L158-L178
pybox2d/pybox2d
09643321fd363f0850087d1bde8af3f4afd82163
library/Box2D/examples/backends/pyglet_framework.py
python
PygletDraw.DrawSolidCircle
(self, center, radius, axis, color)
Draw an filled circle given center, radius, axis (of orientation) and color.
Draw an filled circle given center, radius, axis (of orientation) and color.
[ "Draw", "an", "filled", "circle", "given", "center", "radius", "axis", "(", "of", "orientation", ")", "and", "color", "." ]
def DrawSolidCircle(self, center, radius, axis, color): """ Draw an filled circle given center, radius, axis (of orientation) and color. """ tf_vertices, ll_vertices = self.getCircleVertices( center, radius, self.circle_segments) tf_count, ll_count = len(tf_vertices) // 2, len(ll_vertices) // 2 self.batch.add(tf_count, gl.GL_TRIANGLES, self.blended, ('v2f', tf_vertices), ('c4f', [0.5 * color.r, 0.5 * color.g, 0.5 * color.b, 0.5] * tf_count)) self.batch.add(ll_count, gl.GL_LINES, None, ('v2f', ll_vertices), ('c4f', [color.r, color.g, color.b, 1.0] * (ll_count))) p = b2Vec2(center) + radius * b2Vec2(axis) self.batch.add(2, gl.GL_LINES, None, ('v2f', (center[0], center[1], p[0], p[1])), ('c3f', [1.0, 0.0, 0.0] * 2))
[ "def", "DrawSolidCircle", "(", "self", ",", "center", ",", "radius", ",", "axis", ",", "color", ")", ":", "tf_vertices", ",", "ll_vertices", "=", "self", ".", "getCircleVertices", "(", "center", ",", "radius", ",", "self", ".", "circle_segments", ")", "tf_...
https://github.com/pybox2d/pybox2d/blob/09643321fd363f0850087d1bde8af3f4afd82163/library/Box2D/examples/backends/pyglet_framework.py#L251-L270
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mhlib.py
python
Folder.getcurrent
(self)
Return the current message. Raise Error when there is none.
Return the current message. Raise Error when there is none.
[ "Return", "the", "current", "message", ".", "Raise", "Error", "when", "there", "is", "none", "." ]
def getcurrent(self): """Return the current message. Raise Error when there is none.""" seqs = self.getsequences() try: return max(seqs['cur']) except (ValueError, KeyError): raise Error, "no cur message"
[ "def", "getcurrent", "(", "self", ")", ":", "seqs", "=", "self", ".", "getsequences", "(", ")", "try", ":", "return", "max", "(", "seqs", "[", "'cur'", "]", ")", "except", "(", "ValueError", ",", "KeyError", ")", ":", "raise", "Error", ",", "\"no cur...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mhlib.py#L334-L340