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
VladyslavUsenko/basalt-mirror
6d55fdab9ff2e6901dbcab634cf5025c58ad7371
python/basalt/experiments.py
python
Experiment.sequences
(self, filter_regex=None)
return list of sequence names found for this experiment :param filter_regex: if provided, return only they sequences that match the regex
return list of sequence names found for this experiment :param filter_regex: if provided, return only they sequences that match the regex
[ "return", "list", "of", "sequence", "names", "found", "for", "this", "experiment", ":", "param", "filter_regex", ":", "if", "provided", "return", "only", "they", "sequences", "that", "match", "the", "regex" ]
def sequences(self, filter_regex=None): """return list of sequence names found for this experiment :param filter_regex: if provided, return only they sequences that match the regex """ if filter_regex is None: return self.runs.keys() else: return [k for k in self.runs.keys() if re.search(filter_regex, k)]
[ "def", "sequences", "(", "self", ",", "filter_regex", "=", "None", ")", ":", "if", "filter_regex", "is", "None", ":", "return", "self", ".", "runs", ".", "keys", "(", ")", "else", ":", "return", "[", "k", "for", "k", "in", "self", ".", "runs", ".", "keys", "(", ")", "if", "re", ".", "search", "(", "filter_regex", ",", "k", ")", "]" ]
https://github.com/VladyslavUsenko/basalt-mirror/blob/6d55fdab9ff2e6901dbcab634cf5025c58ad7371/python/basalt/experiments.py#L121-L129
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
AutoBufferedPaintDC.__init__
(self, *args, **kwargs)
__init__(self, Window win) -> AutoBufferedPaintDC If the current platform double buffers by default then this DC is the same as a plain `wx.PaintDC`, otherwise it is a `wx.BufferedPaintDC`. :see: `wx.AutoBufferedPaintDCFactory`
__init__(self, Window win) -> AutoBufferedPaintDC
[ "__init__", "(", "self", "Window", "win", ")", "-", ">", "AutoBufferedPaintDC" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window win) -> AutoBufferedPaintDC If the current platform double buffers by default then this DC is the same as a plain `wx.PaintDC`, otherwise it is a `wx.BufferedPaintDC`. :see: `wx.AutoBufferedPaintDCFactory` """ _gdi_.AutoBufferedPaintDC_swiginit(self,_gdi_.new_AutoBufferedPaintDC(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gdi_", ".", "AutoBufferedPaintDC_swiginit", "(", "self", ",", "_gdi_", ".", "new_AutoBufferedPaintDC", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L5307-L5317
leanprover/lean
72a965986fa5aeae54062e98efb3140b2c4e79fd
src/cmake/Modules/cpplint.py
python
FindNextMatchingAngleBracket
(clean_lines, linenum, init_suffix)
return True
Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists.
Find the corresponding > to close a template.
[ "Find", "the", "corresponding", ">", "to", "close", "a", "template", "." ]
def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix): """Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists. """ line = init_suffix nesting_stack = ['<'] while True: # Find the next operator that can tell us whether < is used as an # opening bracket or as a less-than operator. We only want to # warn on the latter case. # # We could also check all other operators and terminate the search # early, e.g. if we got something like this "a<b+c", the "<" is # most likely a less-than operator, but then we will get false # positives for default arguments (e.g. http://go/prccd) and # other template expressions (e.g. http://go/oxcjq). match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line) if match: # Found an operator, update nesting stack operator = match.group(1) line = match.group(2) if nesting_stack[-1] == '<': # Expecting closing angle bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator == '>': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma after a bracket, this is most likely a template # argument. We have not seen a closing angle bracket yet, but # it's probably a few lines later if we look for it, so just # return early here. return True else: # Got some other operator. return False else: # Expecting closing parenthesis or closing bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator in (')', ']'): # We don't bother checking for matching () or []. If we got # something like (] or [), it would have been a syntax error. nesting_stack.pop() else: # Scan the next line linenum += 1 if linenum >= len(clean_lines.elided): break line = clean_lines.elided[linenum] # Exhausted all remaining lines and still no matching angle bracket. # Most likely the input was incomplete, otherwise we should have # seen a semicolon and returned early. return True
[ "def", "FindNextMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "init_suffix", ")", ":", "line", "=", "init_suffix", "nesting_stack", "=", "[", "'<'", "]", "while", "True", ":", "# Find the next operator that can tell us whether < is used as an", "# opening bracket or as a less-than operator. We only want to", "# warn on the latter case.", "#", "# We could also check all other operators and terminate the search", "# early, e.g. if we got something like this \"a<b+c\", the \"<\" is", "# most likely a less-than operator, but then we will get false", "# positives for default arguments (e.g. http://go/prccd) and", "# other template expressions (e.g. http://go/oxcjq).", "match", "=", "Search", "(", "r'^[^<>(),;\\[\\]]*([<>(),;\\[\\]])(.*)$'", ",", "line", ")", "if", "match", ":", "# Found an operator, update nesting stack", "operator", "=", "match", ".", "group", "(", "1", ")", "line", "=", "match", ".", "group", "(", "2", ")", "if", "nesting_stack", "[", "-", "1", "]", "==", "'<'", ":", "# Expecting closing angle bracket", "if", "operator", "in", "(", "'<'", ",", "'('", ",", "'['", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "==", "'>'", ":", "nesting_stack", ".", "pop", "(", ")", "if", "not", "nesting_stack", ":", "# Found matching angle bracket", "return", "True", "elif", "operator", "==", "','", ":", "# Got a comma after a bracket, this is most likely a template", "# argument. We have not seen a closing angle bracket yet, but", "# it's probably a few lines later if we look for it, so just", "# return early here.", "return", "True", "else", ":", "# Got some other operator.", "return", "False", "else", ":", "# Expecting closing parenthesis or closing bracket", "if", "operator", "in", "(", "'<'", ",", "'('", ",", "'['", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "in", "(", "')'", ",", "']'", ")", ":", "# We don't bother checking for matching () or []. If we got", "# something like (] or [), it would have been a syntax error.", "nesting_stack", ".", "pop", "(", ")", "else", ":", "# Scan the next line", "linenum", "+=", "1", "if", "linenum", ">=", "len", "(", "clean_lines", ".", "elided", ")", ":", "break", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Exhausted all remaining lines and still no matching angle bracket.", "# Most likely the input was incomplete, otherwise we should have", "# seen a semicolon and returned early.", "return", "True" ]
https://github.com/leanprover/lean/blob/72a965986fa5aeae54062e98efb3140b2c4e79fd/src/cmake/Modules/cpplint.py#L2149-L2216
shedskin/shedskin
ae88dbca7b1d9671cd8be448cb0b497122758936
examples/msp_ss.py
python
BootStrapLoader.actionChangeBaudrate
(self, baudrate=9600)
change baudrate. first the command is sent, then the comm port is reprogrammed. only possible with newer MSP430-BSL versions. (ROM >=1.6, downloadable >=1.5)
change baudrate. first the command is sent, then the comm port is reprogrammed. only possible with newer MSP430-BSL versions. (ROM >=1.6, downloadable >=1.5)
[ "change", "baudrate", ".", "first", "the", "command", "is", "sent", "then", "the", "comm", "port", "is", "reprogrammed", ".", "only", "possible", "with", "newer", "MSP430", "-", "BSL", "versions", ".", "(", "ROM", ">", "=", "1", ".", "6", "downloadable", ">", "=", "1", ".", "5", ")" ]
def actionChangeBaudrate(self, baudrate=9600): """change baudrate. first the command is sent, then the comm port is reprogrammed. only possible with newer MSP430-BSL versions. (ROM >=1.6, downloadable >=1.5)""" try: baudconfigs = bauratetable[self.cpu] except KeyError: raise ValueError("unknown CPU type %s, can't switch baudrate" % self.cpu) try: a,l = baudconfigs[baudrate] except KeyError: raise ValueError("baudrate not valid. valid values are %r" % baudconfigs.keys()) #a, l = 0x87e0, 0x0002 sys.stderr.write("Changing baudrate to %d ...\n" % baudrate) sys.stderr.flush() self.bslTxRx(BSL_CHANGEBAUD, #Command: change baudrate a, l) #args are coded in adr and len time.sleep(0.010) #recomended delay self.serialport.setBaudrate(baudrate)
[ "def", "actionChangeBaudrate", "(", "self", ",", "baudrate", "=", "9600", ")", ":", "try", ":", "baudconfigs", "=", "bauratetable", "[", "self", ".", "cpu", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"unknown CPU type %s, can't switch baudrate\"", "%", "self", ".", "cpu", ")", "try", ":", "a", ",", "l", "=", "baudconfigs", "[", "baudrate", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"baudrate not valid. valid values are %r\"", "%", "baudconfigs", ".", "keys", "(", ")", ")", "#a, l = 0x87e0, 0x0002", "sys", ".", "stderr", ".", "write", "(", "\"Changing baudrate to %d ...\\n\"", "%", "baudrate", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "self", ".", "bslTxRx", "(", "BSL_CHANGEBAUD", ",", "#Command: change baudrate", "a", ",", "l", ")", "#args are coded in adr and len", "time", ".", "sleep", "(", "0.010", ")", "#recomended delay", "self", ".", "serialport", ".", "setBaudrate", "(", "baudrate", ")" ]
https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/msp_ss.py#L1173-L1192
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/__init__.py
python
Node.build
(self, **kw)
Actually build the node. This is called by the Taskmaster after it's decided that the Node is out-of-date and must be rebuilt, and after the prepare() method has gotten everything, uh, prepared. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built().
Actually build the node.
[ "Actually", "build", "the", "node", "." ]
def build(self, **kw): """Actually build the node. This is called by the Taskmaster after it's decided that the Node is out-of-date and must be rebuilt, and after the prepare() method has gotten everything, uh, prepared. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). """ try: self.get_executor()(self, **kw) except SCons.Errors.BuildError as e: e.node = self raise
[ "def", "build", "(", "self", ",", "*", "*", "kw", ")", ":", "try", ":", "self", ".", "get_executor", "(", ")", "(", "self", ",", "*", "*", "kw", ")", "except", "SCons", ".", "Errors", ".", "BuildError", "as", "e", ":", "e", ".", "node", "=", "self", "raise" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/__init__.py#L753-L769
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetCflagsObjCC
(self, configname)
return cflags_objcc
Returns flags that need to be added to .mm compilations.
Returns flags that need to be added to .mm compilations.
[ "Returns", "flags", "that", "need", "to", "be", "added", "to", ".", "mm", "compilations", "." ]
def GetCflagsObjCC(self, configname): """Returns flags that need to be added to .mm compilations.""" self.configname = configname cflags_objcc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objcc) if self._Test('GCC_OBJC_CALL_CXX_CDTORS', 'YES', default='NO'): cflags_objcc.append('-fobjc-call-cxx-cdtors') self.configname = None return cflags_objcc
[ "def", "GetCflagsObjCC", "(", "self", ",", "configname", ")", ":", "self", ".", "configname", "=", "configname", "cflags_objcc", "=", "[", "]", "self", ".", "_AddObjectiveCGarbageCollectionFlags", "(", "cflags_objcc", ")", "if", "self", ".", "_Test", "(", "'GCC_OBJC_CALL_CXX_CDTORS'", ",", "'YES'", ",", "default", "=", "'NO'", ")", ":", "cflags_objcc", ".", "append", "(", "'-fobjc-call-cxx-cdtors'", ")", "self", ".", "configname", "=", "None", "return", "cflags_objcc" ]
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/xcode_emulation.py#L400-L408
apple/swift-clang
d7403439fc6641751840b723e7165fb02f52db95
bindings/python/clang/cindex.py
python
TranslationUnit.save
(self, filename)
Saves the TranslationUnit to a file. This is equivalent to passing -emit-ast to the clang frontend. The saved file can be loaded back into a TranslationUnit. Or, if it corresponds to a header, it can be used as a pre-compiled header file. If an error occurs while saving, a TranslationUnitSaveError is raised. If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means the constructed TranslationUnit was not valid at time of save. In this case, the reason(s) why should be available via TranslationUnit.diagnostics(). filename -- The path to save the translation unit to (str or PathLike).
Saves the TranslationUnit to a file.
[ "Saves", "the", "TranslationUnit", "to", "a", "file", "." ]
def save(self, filename): """Saves the TranslationUnit to a file. This is equivalent to passing -emit-ast to the clang frontend. The saved file can be loaded back into a TranslationUnit. Or, if it corresponds to a header, it can be used as a pre-compiled header file. If an error occurs while saving, a TranslationUnitSaveError is raised. If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means the constructed TranslationUnit was not valid at time of save. In this case, the reason(s) why should be available via TranslationUnit.diagnostics(). filename -- The path to save the translation unit to (str or PathLike). """ options = conf.lib.clang_defaultSaveOptions(self) result = int(conf.lib.clang_saveTranslationUnit(self, fspath(filename), options)) if result != 0: raise TranslationUnitSaveError(result, 'Error saving TranslationUnit.')
[ "def", "save", "(", "self", ",", "filename", ")", ":", "options", "=", "conf", ".", "lib", ".", "clang_defaultSaveOptions", "(", "self", ")", "result", "=", "int", "(", "conf", ".", "lib", ".", "clang_saveTranslationUnit", "(", "self", ",", "fspath", "(", "filename", ")", ",", "options", ")", ")", "if", "result", "!=", "0", ":", "raise", "TranslationUnitSaveError", "(", "result", ",", "'Error saving TranslationUnit.'", ")" ]
https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L3012-L3032
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
llvm/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py
python
generateKScript
(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript)
Generate a random Kaleidoscope script based on the given parameters
Generate a random Kaleidoscope script based on the given parameters
[ "Generate", "a", "random", "Kaleidoscope", "script", "based", "on", "the", "given", "parameters" ]
def generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript): """ Generate a random Kaleidoscope script based on the given parameters """ print("Generating " + filename) print(" %d functions, %d elements per function, %d functions between execution" % (numFuncs, elementsPerFunc, funcsBetweenExec)) print(" Call weighting = %f" % callWeighting) script = KScriptGenerator(filename) script.setCallWeighting(callWeighting) script.writeComment("===========================================================================") script.writeComment("Auto-generated script") script.writeComment(" %d functions, %d elements per function, %d functions between execution" % (numFuncs, elementsPerFunc, funcsBetweenExec)) script.writeComment(" call weighting = %f" % callWeighting) script.writeComment("===========================================================================") script.writeEmptyLine() script.writePredefinedFunctions() funcsSinceLastExec = 0 for i in range(numFuncs): script.writeFunction(elementsPerFunc) funcsSinceLastExec += 1 if funcsSinceLastExec == funcsBetweenExec: script.writeFunctionCall() funcsSinceLastExec = 0 # Always end with a function call if funcsSinceLastExec > 0: script.writeFunctionCall() script.writeEmptyLine() script.writeFinalFunctionCounts() funcsCalled = len(script.calledFunctions) print(" Called %d of %d functions, %d total" % (funcsCalled, numFuncs, script.totalCallsExecuted)) timingScript.writeTimingCall(filename, numFuncs, funcsCalled, script.totalCallsExecuted)
[ "def", "generateKScript", "(", "filename", ",", "numFuncs", ",", "elementsPerFunc", ",", "funcsBetweenExec", ",", "callWeighting", ",", "timingScript", ")", ":", "print", "(", "\"Generating \"", "+", "filename", ")", "print", "(", "\" %d functions, %d elements per function, %d functions between execution\"", "%", "(", "numFuncs", ",", "elementsPerFunc", ",", "funcsBetweenExec", ")", ")", "print", "(", "\" Call weighting = %f\"", "%", "callWeighting", ")", "script", "=", "KScriptGenerator", "(", "filename", ")", "script", ".", "setCallWeighting", "(", "callWeighting", ")", "script", ".", "writeComment", "(", "\"===========================================================================\"", ")", "script", ".", "writeComment", "(", "\"Auto-generated script\"", ")", "script", ".", "writeComment", "(", "\" %d functions, %d elements per function, %d functions between execution\"", "%", "(", "numFuncs", ",", "elementsPerFunc", ",", "funcsBetweenExec", ")", ")", "script", ".", "writeComment", "(", "\" call weighting = %f\"", "%", "callWeighting", ")", "script", ".", "writeComment", "(", "\"===========================================================================\"", ")", "script", ".", "writeEmptyLine", "(", ")", "script", ".", "writePredefinedFunctions", "(", ")", "funcsSinceLastExec", "=", "0", "for", "i", "in", "range", "(", "numFuncs", ")", ":", "script", ".", "writeFunction", "(", "elementsPerFunc", ")", "funcsSinceLastExec", "+=", "1", "if", "funcsSinceLastExec", "==", "funcsBetweenExec", ":", "script", ".", "writeFunctionCall", "(", ")", "funcsSinceLastExec", "=", "0", "# Always end with a function call", "if", "funcsSinceLastExec", ">", "0", ":", "script", ".", "writeFunctionCall", "(", ")", "script", ".", "writeEmptyLine", "(", ")", "script", ".", "writeFinalFunctionCounts", "(", ")", "funcsCalled", "=", "len", "(", "script", ".", "calledFunctions", ")", "print", "(", "\" Called %d of %d functions, %d total\"", "%", "(", "funcsCalled", ",", "numFuncs", ",", "script", ".", "totalCallsExecuted", ")", ")", "timingScript", ".", "writeTimingCall", "(", "filename", ",", "numFuncs", ",", "funcsCalled", ",", "script", ".", "totalCallsExecuted", ")" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py#L176-L206
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
onnxruntime/python/tools/transformers/gpt2_beamsearch_helper.py
python
Gpt2BeamSearchHelper.prepare_io_binding
(ort_session, input_ids, position_ids, attention_mask, past, output_buffers, output_shapes, beam_select_idx=None, input_log_probs=None, input_unfinished_sents=None, prev_step_results=None, prev_step_scores=None)
return io_binding
Returnas IO binding object for a session.
Returnas IO binding object for a session.
[ "Returnas", "IO", "binding", "object", "for", "a", "session", "." ]
def prepare_io_binding(ort_session, input_ids, position_ids, attention_mask, past, output_buffers, output_shapes, beam_select_idx=None, input_log_probs=None, input_unfinished_sents=None, prev_step_results=None, prev_step_scores=None): """Returnas IO binding object for a session.""" # Bind inputs and outputs to onnxruntime session io_binding = Gpt2Helper.prepare_io_binding(ort_session, input_ids, position_ids, attention_mask, past=past, output_buffers=output_buffers, output_shapes=output_shapes) # Bind inputs data_type = output_buffers[ort_session.get_outputs()[1].name].dtype float_type = numpy.float16 if data_type == torch.float16 else numpy.float32 if past is not None: for i, past_i in enumerate(past): assert past_i.is_contiguous() data_ptr = past_i.data_ptr() if data_ptr == 0: # When past_sequence_length is 0, its data_ptr will be zero. IO Binding asserts that data_ptr shall not be zero. # Here we workaround and pass data pointer of input_ids. Actual data is not used for past so it does not matter. data_ptr = input_ids.data_ptr() io_binding.bind_input(f'past_{i}', past_i.device.type, 0, float_type, list(past_i.size()), data_ptr) if attention_mask is not None: assert attention_mask.is_contiguous() io_binding.bind_input('attention_mask', attention_mask.device.type, 0, float_type, list(attention_mask.size()), attention_mask.data_ptr()) if beam_select_idx is not None: assert beam_select_idx.is_contiguous() io_binding.bind_input( "beam_select_idx", beam_select_idx.device.type, 0, numpy.longlong, list(beam_select_idx.size()), beam_select_idx.data_ptr(), ) if input_log_probs is not None: assert input_log_probs.is_contiguous() io_binding.bind_input( "input_log_probs", input_log_probs.device.type, 0, float_type, list(input_log_probs.size()), input_log_probs.data_ptr(), ) if input_unfinished_sents is not None: assert input_unfinished_sents.is_contiguous() io_binding.bind_input( "input_unfinished_sents", input_unfinished_sents.device.type, 0, numpy.bool, list(input_unfinished_sents.size()), input_unfinished_sents.data_ptr(), ) if prev_step_results is not None: assert prev_step_results.is_contiguous() io_binding.bind_input( "prev_step_results", prev_step_results.device.type, 0, numpy.longlong, list(prev_step_results.size()), prev_step_results.data_ptr(), ) if prev_step_scores is not None: assert prev_step_scores.is_contiguous() io_binding.bind_input( "prev_step_scores", prev_step_scores.device.type, 0, float_type, list(prev_step_scores.size()), prev_step_scores.data_ptr(), ) # Bind outputs for output in ort_session.get_outputs(): output_name = output.name output_buffer = output_buffers[output_name] logger.debug(f"{output_name} device type={output_buffer.device.type} shape={list(output_buffer.size())}") if (output_name == "output_selected_indices" or output_name == "last_state" or output_name == "current_step_results"): io_binding.bind_output( output_name, output_buffer.device.type, 0, numpy.longlong, output_shapes[output_name], output_buffer.data_ptr(), ) elif output_name == "output_unfinished_sents": io_binding.bind_output( output_name, output_buffer.device.type, 0, numpy.bool, output_shapes[output_name], output_buffer.data_ptr(), ) else: io_binding.bind_output( output_name, output_buffer.device.type, 0, float_type, output_shapes[output_name], output_buffer.data_ptr(), ) return io_binding
[ "def", "prepare_io_binding", "(", "ort_session", ",", "input_ids", ",", "position_ids", ",", "attention_mask", ",", "past", ",", "output_buffers", ",", "output_shapes", ",", "beam_select_idx", "=", "None", ",", "input_log_probs", "=", "None", ",", "input_unfinished_sents", "=", "None", ",", "prev_step_results", "=", "None", ",", "prev_step_scores", "=", "None", ")", ":", "# Bind inputs and outputs to onnxruntime session", "io_binding", "=", "Gpt2Helper", ".", "prepare_io_binding", "(", "ort_session", ",", "input_ids", ",", "position_ids", ",", "attention_mask", ",", "past", "=", "past", ",", "output_buffers", "=", "output_buffers", ",", "output_shapes", "=", "output_shapes", ")", "# Bind inputs", "data_type", "=", "output_buffers", "[", "ort_session", ".", "get_outputs", "(", ")", "[", "1", "]", ".", "name", "]", ".", "dtype", "float_type", "=", "numpy", ".", "float16", "if", "data_type", "==", "torch", ".", "float16", "else", "numpy", ".", "float32", "if", "past", "is", "not", "None", ":", "for", "i", ",", "past_i", "in", "enumerate", "(", "past", ")", ":", "assert", "past_i", ".", "is_contiguous", "(", ")", "data_ptr", "=", "past_i", ".", "data_ptr", "(", ")", "if", "data_ptr", "==", "0", ":", "# When past_sequence_length is 0, its data_ptr will be zero. IO Binding asserts that data_ptr shall not be zero.", "# Here we workaround and pass data pointer of input_ids. Actual data is not used for past so it does not matter.", "data_ptr", "=", "input_ids", ".", "data_ptr", "(", ")", "io_binding", ".", "bind_input", "(", "f'past_{i}'", ",", "past_i", ".", "device", ".", "type", ",", "0", ",", "float_type", ",", "list", "(", "past_i", ".", "size", "(", ")", ")", ",", "data_ptr", ")", "if", "attention_mask", "is", "not", "None", ":", "assert", "attention_mask", ".", "is_contiguous", "(", ")", "io_binding", ".", "bind_input", "(", "'attention_mask'", ",", "attention_mask", ".", "device", ".", "type", ",", "0", ",", "float_type", ",", "list", "(", "attention_mask", ".", "size", "(", ")", ")", ",", "attention_mask", ".", "data_ptr", "(", ")", ")", "if", "beam_select_idx", "is", "not", "None", ":", "assert", "beam_select_idx", ".", "is_contiguous", "(", ")", "io_binding", ".", "bind_input", "(", "\"beam_select_idx\"", ",", "beam_select_idx", ".", "device", ".", "type", ",", "0", ",", "numpy", ".", "longlong", ",", "list", "(", "beam_select_idx", ".", "size", "(", ")", ")", ",", "beam_select_idx", ".", "data_ptr", "(", ")", ",", ")", "if", "input_log_probs", "is", "not", "None", ":", "assert", "input_log_probs", ".", "is_contiguous", "(", ")", "io_binding", ".", "bind_input", "(", "\"input_log_probs\"", ",", "input_log_probs", ".", "device", ".", "type", ",", "0", ",", "float_type", ",", "list", "(", "input_log_probs", ".", "size", "(", ")", ")", ",", "input_log_probs", ".", "data_ptr", "(", ")", ",", ")", "if", "input_unfinished_sents", "is", "not", "None", ":", "assert", "input_unfinished_sents", ".", "is_contiguous", "(", ")", "io_binding", ".", "bind_input", "(", "\"input_unfinished_sents\"", ",", "input_unfinished_sents", ".", "device", ".", "type", ",", "0", ",", "numpy", ".", "bool", ",", "list", "(", "input_unfinished_sents", ".", "size", "(", ")", ")", ",", "input_unfinished_sents", ".", "data_ptr", "(", ")", ",", ")", "if", "prev_step_results", "is", "not", "None", ":", "assert", "prev_step_results", ".", "is_contiguous", "(", ")", "io_binding", ".", "bind_input", "(", "\"prev_step_results\"", ",", "prev_step_results", ".", "device", ".", "type", ",", "0", ",", "numpy", ".", "longlong", ",", "list", "(", "prev_step_results", ".", "size", "(", ")", ")", ",", "prev_step_results", ".", "data_ptr", "(", ")", ",", ")", "if", "prev_step_scores", "is", "not", "None", ":", "assert", "prev_step_scores", ".", "is_contiguous", "(", ")", "io_binding", ".", "bind_input", "(", "\"prev_step_scores\"", ",", "prev_step_scores", ".", "device", ".", "type", ",", "0", ",", "float_type", ",", "list", "(", "prev_step_scores", ".", "size", "(", ")", ")", ",", "prev_step_scores", ".", "data_ptr", "(", ")", ",", ")", "# Bind outputs", "for", "output", "in", "ort_session", ".", "get_outputs", "(", ")", ":", "output_name", "=", "output", ".", "name", "output_buffer", "=", "output_buffers", "[", "output_name", "]", "logger", ".", "debug", "(", "f\"{output_name} device type={output_buffer.device.type} shape={list(output_buffer.size())}\"", ")", "if", "(", "output_name", "==", "\"output_selected_indices\"", "or", "output_name", "==", "\"last_state\"", "or", "output_name", "==", "\"current_step_results\"", ")", ":", "io_binding", ".", "bind_output", "(", "output_name", ",", "output_buffer", ".", "device", ".", "type", ",", "0", ",", "numpy", ".", "longlong", ",", "output_shapes", "[", "output_name", "]", ",", "output_buffer", ".", "data_ptr", "(", ")", ",", ")", "elif", "output_name", "==", "\"output_unfinished_sents\"", ":", "io_binding", ".", "bind_output", "(", "output_name", ",", "output_buffer", ".", "device", ".", "type", ",", "0", ",", "numpy", ".", "bool", ",", "output_shapes", "[", "output_name", "]", ",", "output_buffer", ".", "data_ptr", "(", ")", ",", ")", "else", ":", "io_binding", ".", "bind_output", "(", "output_name", ",", "output_buffer", ".", "device", ".", "type", ",", "0", ",", "float_type", ",", "output_shapes", "[", "output_name", "]", ",", "output_buffer", ".", "data_ptr", "(", ")", ",", ")", "return", "io_binding" ]
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/transformers/gpt2_beamsearch_helper.py#L686-L819
xenia-project/xenia
9b1fdac98665ac091b9660a5d0fbb259ed79e578
third_party/google-styleguide/cpplint/cpplint.py
python
CloseExpression
(clean_lines, linenum, pos)
return (line, clean_lines.NumLines(), -1)
If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ( or { or [ or <, finds the position that closes it.
[ "If", "input", "points", "to", "(", "or", "{", "or", "[", "or", "<", "finds", "the", "position", "that", "closes", "it", "." ]
def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): return (line, clean_lines.NumLines(), -1) # Check first line (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while stack and linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) if end_pos > -1: return (line, linenum, end_pos) # Did not find end of expression before end of file, give up return (line, clean_lines.NumLines(), -1)
[ "def", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "(", "line", "[", "pos", "]", "not", "in", "'({[<'", ")", "or", "Match", "(", "r'<[<=]'", ",", "line", "[", "pos", ":", "]", ")", ":", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")", "# Check first line", "(", "end_pos", ",", "stack", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "pos", ",", "[", "]", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Continue scanning forward", "while", "stack", "and", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ":", "linenum", "+=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "end_pos", ",", "stack", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "0", ",", "stack", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Did not find end of expression before end of file, give up", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")" ]
https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L1348-L1389
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/util.py
python
execute
(func, args, msg=None, verbose=0, dry_run=0)
Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the "external action" being performed), and an optional message to print.
Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the "external action" being performed), and an optional message to print.
[ "Perform", "some", "action", "that", "affects", "the", "outside", "world", "(", "eg", ".", "by", "writing", "to", "the", "filesystem", ")", ".", "Such", "actions", "are", "special", "because", "they", "are", "disabled", "by", "the", "dry_run", "flag", ".", "This", "method", "takes", "care", "of", "all", "that", "bureaucracy", "for", "you", ";", "all", "you", "have", "to", "do", "is", "supply", "the", "function", "to", "call", "and", "an", "argument", "tuple", "for", "it", "(", "to", "embody", "the", "external", "action", "being", "performed", ")", "and", "an", "optional", "message", "to", "print", "." ]
def execute (func, args, msg=None, verbose=0, dry_run=0): """Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the "external action" being performed), and an optional message to print. """ if msg is None: msg = "%s%r" % (func.__name__, args) if msg[-2:] == ',)': # correct for singleton tuple msg = msg[0:-2] + ')' log.info(msg) if not dry_run: func(*args)
[ "def", "execute", "(", "func", ",", "args", ",", "msg", "=", "None", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ")", ":", "if", "msg", "is", "None", ":", "msg", "=", "\"%s%r\"", "%", "(", "func", ".", "__name__", ",", "args", ")", "if", "msg", "[", "-", "2", ":", "]", "==", "',)'", ":", "# correct for singleton tuple", "msg", "=", "msg", "[", "0", ":", "-", "2", "]", "+", "')'", "log", ".", "info", "(", "msg", ")", "if", "not", "dry_run", ":", "func", "(", "*", "args", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/util.py#L315-L331
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
python
DirpathWidgetContainer.define_widgetset
(self)
return [('name', self.create_namewidget(), wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL), ('value', self.create_valuewidget(), wx.EXPAND), ('unit', self.create_unitwidget(), wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL), ]
Generates the widgets representing this attribute.
Generates the widgets representing this attribute.
[ "Generates", "the", "widgets", "representing", "this", "attribute", "." ]
def define_widgetset(self): """ Generates the widgets representing this attribute. """ return [('name', self.create_namewidget(), wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL), ('value', self.create_valuewidget(), wx.EXPAND), ('unit', self.create_unitwidget(), wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL), ]
[ "def", "define_widgetset", "(", "self", ")", ":", "return", "[", "(", "'name'", ",", "self", ".", "create_namewidget", "(", ")", ",", "wx", ".", "ALIGN_RIGHT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ")", ",", "(", "'value'", ",", "self", ".", "create_valuewidget", "(", ")", ",", "wx", ".", "EXPAND", ")", ",", "(", "'unit'", ",", "self", ".", "create_unitwidget", "(", ")", ",", "wx", ".", "ALIGN_LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ")", ",", "]" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L1608-L1614
traveller59/spconv
647927ce6b64dc51fbec4eb50c7194f8ca5007e5
spconv/pytorch/core.py
python
SparseConvTensor.__init__
(self, features: torch.Tensor, indices: torch.Tensor, spatial_shape: Union[List[int], np.ndarray], batch_size: int, grid: Optional[torch.Tensor] = None, voxel_num: Optional[torch.Tensor] = None, indice_dict: Optional[dict] = None, benchmark: bool = False, permanent_thrust_allocator: bool = False, enable_timer: bool = False)
Args: features: [num_points, num_features] feature tensor indices: [num_points, ndim + 1] indice tensor. batch index saved in indices[:, 0] spatial_shape: spatial shape of your sparse data batch_size: batch size of your sparse data grid: pre-allocated grid tensor. should be used when the volume of spatial shape is very large. benchmark: whether to enable benchmark. if enabled, all sparse operators will be record to SparseConvTensor.
Args: features: [num_points, num_features] feature tensor indices: [num_points, ndim + 1] indice tensor. batch index saved in indices[:, 0] spatial_shape: spatial shape of your sparse data batch_size: batch size of your sparse data grid: pre-allocated grid tensor. should be used when the volume of spatial shape is very large. benchmark: whether to enable benchmark. if enabled, all sparse operators will be record to SparseConvTensor.
[ "Args", ":", "features", ":", "[", "num_points", "num_features", "]", "feature", "tensor", "indices", ":", "[", "num_points", "ndim", "+", "1", "]", "indice", "tensor", ".", "batch", "index", "saved", "in", "indices", "[", ":", "0", "]", "spatial_shape", ":", "spatial", "shape", "of", "your", "sparse", "data", "batch_size", ":", "batch", "size", "of", "your", "sparse", "data", "grid", ":", "pre", "-", "allocated", "grid", "tensor", ".", "should", "be", "used", "when", "the", "volume", "of", "spatial", "shape", "is", "very", "large", ".", "benchmark", ":", "whether", "to", "enable", "benchmark", ".", "if", "enabled", "all", "sparse", "operators", "will", "be", "record", "to", "SparseConvTensor", "." ]
def __init__(self, features: torch.Tensor, indices: torch.Tensor, spatial_shape: Union[List[int], np.ndarray], batch_size: int, grid: Optional[torch.Tensor] = None, voxel_num: Optional[torch.Tensor] = None, indice_dict: Optional[dict] = None, benchmark: bool = False, permanent_thrust_allocator: bool = False, enable_timer: bool = False): """ Args: features: [num_points, num_features] feature tensor indices: [num_points, ndim + 1] indice tensor. batch index saved in indices[:, 0] spatial_shape: spatial shape of your sparse data batch_size: batch size of your sparse data grid: pre-allocated grid tensor. should be used when the volume of spatial shape is very large. benchmark: whether to enable benchmark. if enabled, all sparse operators will be record to SparseConvTensor. """ ndim = indices.shape[1] - 1 assert features.ndim == 2 assert indices.ndim == 2 assert len(spatial_shape) == ndim, "spatial shape must equal to ndim" assert indices.dtype == torch.int32, "only support int32" assert batch_size > 0 self._features = features self.indices = indices self.spatial_shape = [int(v) for v in spatial_shape] self.batch_size = batch_size if indice_dict is None: indice_dict = {} self.indice_dict = indice_dict if grid is None: grid = torch.Tensor() # empty tensor self.grid = grid self.voxel_num = voxel_num # for tensorrt self.benchmark = benchmark self.benchmark_record = {} self.thrust_allocator: Optional[ThrustSortAllocator] = None if permanent_thrust_allocator: self.thrust_allocator = ThrustSortAllocator(features.device) self._timer = CUDAKernelTimer(enable_timer)
[ "def", "__init__", "(", "self", ",", "features", ":", "torch", ".", "Tensor", ",", "indices", ":", "torch", ".", "Tensor", ",", "spatial_shape", ":", "Union", "[", "List", "[", "int", "]", ",", "np", ".", "ndarray", "]", ",", "batch_size", ":", "int", ",", "grid", ":", "Optional", "[", "torch", ".", "Tensor", "]", "=", "None", ",", "voxel_num", ":", "Optional", "[", "torch", ".", "Tensor", "]", "=", "None", ",", "indice_dict", ":", "Optional", "[", "dict", "]", "=", "None", ",", "benchmark", ":", "bool", "=", "False", ",", "permanent_thrust_allocator", ":", "bool", "=", "False", ",", "enable_timer", ":", "bool", "=", "False", ")", ":", "ndim", "=", "indices", ".", "shape", "[", "1", "]", "-", "1", "assert", "features", ".", "ndim", "==", "2", "assert", "indices", ".", "ndim", "==", "2", "assert", "len", "(", "spatial_shape", ")", "==", "ndim", ",", "\"spatial shape must equal to ndim\"", "assert", "indices", ".", "dtype", "==", "torch", ".", "int32", ",", "\"only support int32\"", "assert", "batch_size", ">", "0", "self", ".", "_features", "=", "features", "self", ".", "indices", "=", "indices", "self", ".", "spatial_shape", "=", "[", "int", "(", "v", ")", "for", "v", "in", "spatial_shape", "]", "self", ".", "batch_size", "=", "batch_size", "if", "indice_dict", "is", "None", ":", "indice_dict", "=", "{", "}", "self", ".", "indice_dict", "=", "indice_dict", "if", "grid", "is", "None", ":", "grid", "=", "torch", ".", "Tensor", "(", ")", "# empty tensor", "self", ".", "grid", "=", "grid", "self", ".", "voxel_num", "=", "voxel_num", "# for tensorrt", "self", ".", "benchmark", "=", "benchmark", "self", ".", "benchmark_record", "=", "{", "}", "self", ".", "thrust_allocator", ":", "Optional", "[", "ThrustSortAllocator", "]", "=", "None", "if", "permanent_thrust_allocator", ":", "self", ".", "thrust_allocator", "=", "ThrustSortAllocator", "(", "features", ".", "device", ")", "self", ".", "_timer", "=", "CUDAKernelTimer", "(", "enable_timer", ")" ]
https://github.com/traveller59/spconv/blob/647927ce6b64dc51fbec4eb50c7194f8ca5007e5/spconv/pytorch/core.py#L124-L168
nasa/astrobee
9241e67e6692810d6e275abb3165b6d02f4ca5ef
scripts/git/cpplint.py
python
FileInfo.Extension
(self)
return self.Split()[2]
File extension - text following the final period.
File extension - text following the final period.
[ "File", "extension", "-", "text", "following", "the", "final", "period", "." ]
def Extension(self): """File extension - text following the final period.""" return self.Split()[2]
[ "def", "Extension", "(", "self", ")", ":", "return", "self", ".", "Split", "(", ")", "[", "2", "]" ]
https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/scripts/git/cpplint.py#L1096-L1098
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py
python
_format_elemcreate
(etype, script=False, *args, **kw)
return spec, opts
Formats args and kw according to the given element factory etype.
Formats args and kw according to the given element factory etype.
[ "Formats", "args", "and", "kw", "according", "to", "the", "given", "element", "factory", "etype", "." ]
def _format_elemcreate(etype, script=False, *args, **kw): """Formats args and kw according to the given element factory etype.""" spec = None opts = () if etype in ("image", "vsapi"): if etype == "image": # define an element based on an image # first arg should be the default image name iname = args[0] # next args, if any, are statespec/value pairs which is almost # a mapdict, but we just need the value imagespec = _join(_mapdict_values(args[1:])) spec = "%s %s" % (iname, imagespec) else: # define an element whose visual appearance is drawn using the # Microsoft Visual Styles API which is responsible for the # themed styles on Windows XP and Vista. # Availability: Tk 8.6, Windows XP and Vista. class_name, part_id = args[:2] statemap = _join(_mapdict_values(args[2:])) spec = "%s %s %s" % (class_name, part_id, statemap) opts = _format_optdict(kw, script) elif etype == "from": # clone an element # it expects a themename and optionally an element to clone from, # otherwise it will clone {} (empty element) spec = args[0] # theme name if len(args) > 1: # elementfrom specified opts = (_format_optvalue(args[1], script),) if script: spec = '{%s}' % spec opts = ' '.join(opts) return spec, opts
[ "def", "_format_elemcreate", "(", "etype", ",", "script", "=", "False", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "spec", "=", "None", "opts", "=", "(", ")", "if", "etype", "in", "(", "\"image\"", ",", "\"vsapi\"", ")", ":", "if", "etype", "==", "\"image\"", ":", "# define an element based on an image", "# first arg should be the default image name", "iname", "=", "args", "[", "0", "]", "# next args, if any, are statespec/value pairs which is almost", "# a mapdict, but we just need the value", "imagespec", "=", "_join", "(", "_mapdict_values", "(", "args", "[", "1", ":", "]", ")", ")", "spec", "=", "\"%s %s\"", "%", "(", "iname", ",", "imagespec", ")", "else", ":", "# define an element whose visual appearance is drawn using the", "# Microsoft Visual Styles API which is responsible for the", "# themed styles on Windows XP and Vista.", "# Availability: Tk 8.6, Windows XP and Vista.", "class_name", ",", "part_id", "=", "args", "[", ":", "2", "]", "statemap", "=", "_join", "(", "_mapdict_values", "(", "args", "[", "2", ":", "]", ")", ")", "spec", "=", "\"%s %s %s\"", "%", "(", "class_name", ",", "part_id", ",", "statemap", ")", "opts", "=", "_format_optdict", "(", "kw", ",", "script", ")", "elif", "etype", "==", "\"from\"", ":", "# clone an element", "# it expects a themename and optionally an element to clone from,", "# otherwise it will clone {} (empty element)", "spec", "=", "args", "[", "0", "]", "# theme name", "if", "len", "(", "args", ")", ">", "1", ":", "# elementfrom specified", "opts", "=", "(", "_format_optvalue", "(", "args", "[", "1", "]", ",", "script", ")", ",", ")", "if", "script", ":", "spec", "=", "'{%s}'", "%", "spec", "opts", "=", "' '", ".", "join", "(", "opts", ")", "return", "spec", ",", "opts" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py#L117-L152
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py
python
ParseResults.dump
(self, indent='', depth=0, full=True)
return "".join(out)
Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(result.dump()) prints:: ['12', '/', '31', '/', '1999'] - day: 1999 - month: 31 - year: 12
Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data.
[ "Diagnostic", "method", "for", "listing", "out", "the", "contents", "of", "a", "C", "{", "ParseResults", "}", ".", "Accepts", "an", "optional", "C", "{", "indent", "}", "argument", "so", "that", "this", "string", "can", "be", "embedded", "in", "a", "nested", "display", "of", "other", "data", "." ]
def dump(self, indent='', depth=0, full=True): """ Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(result.dump()) prints:: ['12', '/', '31', '/', '1999'] - day: 1999 - month: 31 - year: 12 """ out = [] NL = '\n' out.append( indent+_ustr(self.asList()) ) if full: if self.haskeys(): items = sorted((str(k), v) for k,v in self.items()) for k,v in items: if out: out.append(NL) out.append( "%s%s- %s: " % (indent,(' '*depth), k) ) if isinstance(v,ParseResults): if v: out.append( v.dump(indent,depth+1) ) else: out.append(_ustr(v)) else: out.append(repr(v)) elif any(isinstance(vv,ParseResults) for vv in self): v = self for i,vv in enumerate(v): if isinstance(vv,ParseResults): out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),vv.dump(indent,depth+1) )) else: out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),_ustr(vv))) return "".join(out)
[ "def", "dump", "(", "self", ",", "indent", "=", "''", ",", "depth", "=", "0", ",", "full", "=", "True", ")", ":", "out", "=", "[", "]", "NL", "=", "'\\n'", "out", ".", "append", "(", "indent", "+", "_ustr", "(", "self", ".", "asList", "(", ")", ")", ")", "if", "full", ":", "if", "self", ".", "haskeys", "(", ")", ":", "items", "=", "sorted", "(", "(", "str", "(", "k", ")", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ")", "for", "k", ",", "v", "in", "items", ":", "if", "out", ":", "out", ".", "append", "(", "NL", ")", "out", ".", "append", "(", "\"%s%s- %s: \"", "%", "(", "indent", ",", "(", "' '", "*", "depth", ")", ",", "k", ")", ")", "if", "isinstance", "(", "v", ",", "ParseResults", ")", ":", "if", "v", ":", "out", ".", "append", "(", "v", ".", "dump", "(", "indent", ",", "depth", "+", "1", ")", ")", "else", ":", "out", ".", "append", "(", "_ustr", "(", "v", ")", ")", "else", ":", "out", ".", "append", "(", "repr", "(", "v", ")", ")", "elif", "any", "(", "isinstance", "(", "vv", ",", "ParseResults", ")", "for", "vv", "in", "self", ")", ":", "v", "=", "self", "for", "i", ",", "vv", "in", "enumerate", "(", "v", ")", ":", "if", "isinstance", "(", "vv", ",", "ParseResults", ")", ":", "out", ".", "append", "(", "\"\\n%s%s[%d]:\\n%s%s%s\"", "%", "(", "indent", ",", "(", "' '", "*", "(", "depth", ")", ")", ",", "i", ",", "indent", ",", "(", "' '", "*", "(", "depth", "+", "1", ")", ")", ",", "vv", ".", "dump", "(", "indent", ",", "depth", "+", "1", ")", ")", ")", "else", ":", "out", ".", "append", "(", "\"\\n%s%s[%d]:\\n%s%s%s\"", "%", "(", "indent", ",", "(", "' '", "*", "(", "depth", ")", ")", ",", "i", ",", "indent", ",", "(", "' '", "*", "(", "depth", "+", "1", ")", ")", ",", "_ustr", "(", "vv", ")", ")", ")", "return", "\"\"", ".", "join", "(", "out", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py#L871-L914
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/meta/bytecodetools/pyc_file.py
python
extract
(binary)
return modtime, code
Extract a code object from a binary pyc file. :param binary: a sequence of bytes from a pyc file.
Extract a code object from a binary pyc file. :param binary: a sequence of bytes from a pyc file.
[ "Extract", "a", "code", "object", "from", "a", "binary", "pyc", "file", ".", ":", "param", "binary", ":", "a", "sequence", "of", "bytes", "from", "a", "pyc", "file", "." ]
def extract(binary): ''' Extract a code object from a binary pyc file. :param binary: a sequence of bytes from a pyc file. ''' if len(binary) <= 8: raise Exception("Binary pyc must be greater than 8 bytes (got %i)" % len(binary)) magic = binary[:4] MAGIC = get_magic() if magic != MAGIC: raise Exception("Python version mismatch (%r != %r) Is this a pyc file?" % (magic, MAGIC)) modtime = time.asctime(time.localtime(struct.unpack('i', binary[4:8])[0])) code = marshal.loads(binary[8:]) return modtime, code
[ "def", "extract", "(", "binary", ")", ":", "if", "len", "(", "binary", ")", "<=", "8", ":", "raise", "Exception", "(", "\"Binary pyc must be greater than 8 bytes (got %i)\"", "%", "len", "(", "binary", ")", ")", "magic", "=", "binary", "[", ":", "4", "]", "MAGIC", "=", "get_magic", "(", ")", "if", "magic", "!=", "MAGIC", ":", "raise", "Exception", "(", "\"Python version mismatch (%r != %r) Is this a pyc file?\"", "%", "(", "magic", ",", "MAGIC", ")", ")", "modtime", "=", "time", ".", "asctime", "(", "time", ".", "localtime", "(", "struct", ".", "unpack", "(", "'i'", ",", "binary", "[", "4", ":", "8", "]", ")", "[", "0", "]", ")", ")", "code", "=", "marshal", ".", "loads", "(", "binary", "[", "8", ":", "]", ")", "return", "modtime", ",", "code" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/meta/bytecodetools/pyc_file.py#L12-L31
dscharrer/innoextract
5519d364cc8898f906f6285d81a87ab8c5469cde
cmake/cpplint.py
python
CleansedLines._CollapseStrings
(elided)
return elided
Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings.
Collapses strings and chars on a line to simple "" or '' blocks.
[ "Collapses", "strings", "and", "chars", "on", "a", "line", "to", "simple", "or", "blocks", "." ]
def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if not _RE_PATTERN_INCLUDE.match(elided): # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided) elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided) return elided
[ "def", "_CollapseStrings", "(", "elided", ")", ":", "if", "not", "_RE_PATTERN_INCLUDE", ".", "match", "(", "elided", ")", ":", "# Remove escaped characters first to make quote/single quote collapsing", "# basic. Things that look like escaped characters shouldn't occur", "# outside of strings and chars.", "elided", "=", "_RE_PATTERN_CLEANSE_LINE_ESCAPES", ".", "sub", "(", "''", ",", "elided", ")", "elided", "=", "_RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES", ".", "sub", "(", "\"''\"", ",", "elided", ")", "elided", "=", "_RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES", ".", "sub", "(", "'\"\"'", ",", "elided", ")", "return", "elided" ]
https://github.com/dscharrer/innoextract/blob/5519d364cc8898f906f6285d81a87ab8c5469cde/cmake/cpplint.py#L1010-L1028
zerollzeng/tiny-tensorrt
e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2
third_party/pybind11/tools/clang/cindex.py
python
Config.set_compatibility_check
(check_status)
Perform compatibility check when loading libclang The python bindings are only tested and evaluated with the version of libclang they are provided with. To ensure correct behavior a (limited) compatibility check is performed when loading the bindings. This check will throw an exception, as soon as it fails. In case these bindings are used with an older version of libclang, parts that have been stable between releases may still work. Users of the python bindings can disable the compatibility check. This will cause the python bindings to load, even though they are written for a newer version of libclang. Failures now arise if unsupported or incompatible features are accessed. The user is required to test themselves if the features they are using are available and compatible between different libclang versions.
Perform compatibility check when loading libclang
[ "Perform", "compatibility", "check", "when", "loading", "libclang" ]
def set_compatibility_check(check_status): """ Perform compatibility check when loading libclang The python bindings are only tested and evaluated with the version of libclang they are provided with. To ensure correct behavior a (limited) compatibility check is performed when loading the bindings. This check will throw an exception, as soon as it fails. In case these bindings are used with an older version of libclang, parts that have been stable between releases may still work. Users of the python bindings can disable the compatibility check. This will cause the python bindings to load, even though they are written for a newer version of libclang. Failures now arise if unsupported or incompatible features are accessed. The user is required to test themselves if the features they are using are available and compatible between different libclang versions. """ if Config.loaded: raise Exception("compatibility_check must be set before before " \ "using any other functionalities in libclang.") Config.compatibility_check = check_status
[ "def", "set_compatibility_check", "(", "check_status", ")", ":", "if", "Config", ".", "loaded", ":", "raise", "Exception", "(", "\"compatibility_check must be set before before \"", "\"using any other functionalities in libclang.\"", ")", "Config", ".", "compatibility_check", "=", "check_status" ]
https://github.com/zerollzeng/tiny-tensorrt/blob/e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2/third_party/pybind11/tools/clang/cindex.py#L3789-L3810
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/nntplib.py
python
NNTP.getline
(self)
return line
Internal: return one line from the server, stripping CRLF. Raise EOFError if the connection is closed.
Internal: return one line from the server, stripping CRLF. Raise EOFError if the connection is closed.
[ "Internal", ":", "return", "one", "line", "from", "the", "server", "stripping", "CRLF", ".", "Raise", "EOFError", "if", "the", "connection", "is", "closed", "." ]
def getline(self): """Internal: return one line from the server, stripping CRLF. Raise EOFError if the connection is closed.""" line = self.file.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise NNTPDataError('line too long') if self.debugging > 1: print '*get*', repr(line) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] return line
[ "def", "getline", "(", "self", ")", ":", "line", "=", "self", ".", "file", ".", "readline", "(", "_MAXLINE", "+", "1", ")", "if", "len", "(", "line", ")", ">", "_MAXLINE", ":", "raise", "NNTPDataError", "(", "'line too long'", ")", "if", "self", ".", "debugging", ">", "1", ":", "print", "'*get*'", ",", "repr", "(", "line", ")", "if", "not", "line", ":", "raise", "EOFError", "if", "line", "[", "-", "2", ":", "]", "==", "CRLF", ":", "line", "=", "line", "[", ":", "-", "2", "]", "elif", "line", "[", "-", "1", ":", "]", "in", "CRLF", ":", "line", "=", "line", "[", ":", "-", "1", "]", "return", "line" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/nntplib.py#L207-L218
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/nest.py
python
flatten
(structure, expand_composites=False)
return _pywrap_tensorflow.Flatten(structure, expand_composites)
Returns a flat list from a given nested structure. If nest is not a sequence, tuple, or dict, then returns a single-element list: [nest]. In the case of dict instances, the sequence consists of the values, sorted by key to ensure deterministic behavior. This is true also for OrderedDict instances: their sequence order is ignored, the sorting order of keys is used instead. The same convention is followed in pack_sequence_as. This correctly repacks dicts and OrderedDicts after they have been flattened, and also allows flattening an OrderedDict and then repacking it back using a corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys cannot be flattened. Users must not modify any collections used in nest while this function is running. Args: structure: an arbitrarily nested structure or a scalar object. Note, numpy arrays are considered scalars. expand_composites: If true, then composite tensors such as tf.SparseTensor and tf.RaggedTensor are expanded into their component tensors. Returns: A Python list, the flattened version of the input. Raises: TypeError: The nest is or contains a dict with non-sortable keys.
Returns a flat list from a given nested structure.
[ "Returns", "a", "flat", "list", "from", "a", "given", "nested", "structure", "." ]
def flatten(structure, expand_composites=False): """Returns a flat list from a given nested structure. If nest is not a sequence, tuple, or dict, then returns a single-element list: [nest]. In the case of dict instances, the sequence consists of the values, sorted by key to ensure deterministic behavior. This is true also for OrderedDict instances: their sequence order is ignored, the sorting order of keys is used instead. The same convention is followed in pack_sequence_as. This correctly repacks dicts and OrderedDicts after they have been flattened, and also allows flattening an OrderedDict and then repacking it back using a corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys cannot be flattened. Users must not modify any collections used in nest while this function is running. Args: structure: an arbitrarily nested structure or a scalar object. Note, numpy arrays are considered scalars. expand_composites: If true, then composite tensors such as tf.SparseTensor and tf.RaggedTensor are expanded into their component tensors. Returns: A Python list, the flattened version of the input. Raises: TypeError: The nest is or contains a dict with non-sortable keys. """ return _pywrap_tensorflow.Flatten(structure, expand_composites)
[ "def", "flatten", "(", "structure", ",", "expand_composites", "=", "False", ")", ":", "return", "_pywrap_tensorflow", ".", "Flatten", "(", "structure", ",", "expand_composites", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/nest.py#L233-L263
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/modtool/core/rm.py
python
ModToolRemove._run_subdir
(self, path, globs, makefile_vars, cmakeedit_func=None)
return files_deleted
Delete all files that match a certain pattern in path. path - The directory in which this will take place globs - A tuple of standard UNIX globs of files to delete (e.g. *.yml) makefile_vars - A tuple with a list of CMakeLists.txt-variables which may contain references to the globbed files cmakeedit_func - If the CMakeLists.txt needs special editing, use this
Delete all files that match a certain pattern in path. path - The directory in which this will take place globs - A tuple of standard UNIX globs of files to delete (e.g. *.yml) makefile_vars - A tuple with a list of CMakeLists.txt-variables which may contain references to the globbed files cmakeedit_func - If the CMakeLists.txt needs special editing, use this
[ "Delete", "all", "files", "that", "match", "a", "certain", "pattern", "in", "path", ".", "path", "-", "The", "directory", "in", "which", "this", "will", "take", "place", "globs", "-", "A", "tuple", "of", "standard", "UNIX", "globs", "of", "files", "to", "delete", "(", "e", ".", "g", ".", "*", ".", "yml", ")", "makefile_vars", "-", "A", "tuple", "with", "a", "list", "of", "CMakeLists", ".", "txt", "-", "variables", "which", "may", "contain", "references", "to", "the", "globbed", "files", "cmakeedit_func", "-", "If", "the", "CMakeLists", ".", "txt", "needs", "special", "editing", "use", "this" ]
def _run_subdir(self, path, globs, makefile_vars, cmakeedit_func=None): """ Delete all files that match a certain pattern in path. path - The directory in which this will take place globs - A tuple of standard UNIX globs of files to delete (e.g. *.yml) makefile_vars - A tuple with a list of CMakeLists.txt-variables which may contain references to the globbed files cmakeedit_func - If the CMakeLists.txt needs special editing, use this """ if self.cli: from ..cli import cli_input # 1. Create a filtered list files = [] for g in globs: files = files + sorted(glob.glob(f"{path}/{g}")) files_filt = [] logger.info(f"Searching for matching files in {path}/:") if self.info['blockname']: # Ensure the blockname given is not confused with similarly named blocks blockname_pattern = '' if path == self.info['pydir']: blockname_pattern = f"^(qa_)?{self.info['blockname']}.py$" elif path == os.path.join(self.info['pydir'], 'bindings'): blockname_pattern = f"^{self.info['blockname']}_python.cc$" elif path == os.path.join(self.info['pydir'], 'bindings', 'docstrings'): blockname_pattern = f"^{self.info['blockname']}_pydoc_template.h$" elif path == 'lib': blockname_pattern = f"^{self.info['blockname']}_impl(\\.h|\\.cc)$" elif path == self.info['includedir']: blockname_pattern = f"^{self.info['blockname']}.h$" elif path == 'grc': blockname_pattern = f"^{self.info['modname']}_{self.info['blockname']}.block.yml$" for f in files: if re.search(blockname_pattern, os.path.basename(f)) is not None: files_filt.append(f) elif self.info['pattern']: # A regex resembling one or several blocks were given as stdin for f in files: if re.search(self.info['pattern'], os.path.basename(f)) is not None: files_filt.append(f) if len(files_filt) == 0: logger.info("None found.") return [] # 2. Delete files, Makefile entries and other occurrences files_deleted = [] yes = self.info['yes'] for f in files_filt: b = os.path.basename(f) if not yes and self.cli: ans = cli_input( f"Really delete {f}? [Y/n/a/q]: ").lower().strip() if ans == 'a': yes = True if ans == 'q': sys.exit(0) if ans == 'n': continue files_deleted.append(b) logger.info(f"Deleting {f}.") self.scm.remove_file(f) os.unlink(f) if (os.path.exists(f'{path}/CMakeLists.txt')): ed = CMakeFileEditor(f'{path}/CMakeLists.txt') logger.info( f"Deleting occurrences of {b} from {path}/CMakeLists.txt...") for var in makefile_vars: ed.remove_value(var, b) if cmakeedit_func is not None: cmakeedit_func(b, ed) ed.write() self.scm.mark_files_updated((f'{path}/CMakeLists.txt')) return files_deleted
[ "def", "_run_subdir", "(", "self", ",", "path", ",", "globs", ",", "makefile_vars", ",", "cmakeedit_func", "=", "None", ")", ":", "if", "self", ".", "cli", ":", "from", ".", ".", "cli", "import", "cli_input", "# 1. Create a filtered list", "files", "=", "[", "]", "for", "g", "in", "globs", ":", "files", "=", "files", "+", "sorted", "(", "glob", ".", "glob", "(", "f\"{path}/{g}\"", ")", ")", "files_filt", "=", "[", "]", "logger", ".", "info", "(", "f\"Searching for matching files in {path}/:\"", ")", "if", "self", ".", "info", "[", "'blockname'", "]", ":", "# Ensure the blockname given is not confused with similarly named blocks", "blockname_pattern", "=", "''", "if", "path", "==", "self", ".", "info", "[", "'pydir'", "]", ":", "blockname_pattern", "=", "f\"^(qa_)?{self.info['blockname']}.py$\"", "elif", "path", "==", "os", ".", "path", ".", "join", "(", "self", ".", "info", "[", "'pydir'", "]", ",", "'bindings'", ")", ":", "blockname_pattern", "=", "f\"^{self.info['blockname']}_python.cc$\"", "elif", "path", "==", "os", ".", "path", ".", "join", "(", "self", ".", "info", "[", "'pydir'", "]", ",", "'bindings'", ",", "'docstrings'", ")", ":", "blockname_pattern", "=", "f\"^{self.info['blockname']}_pydoc_template.h$\"", "elif", "path", "==", "'lib'", ":", "blockname_pattern", "=", "f\"^{self.info['blockname']}_impl(\\\\.h|\\\\.cc)$\"", "elif", "path", "==", "self", ".", "info", "[", "'includedir'", "]", ":", "blockname_pattern", "=", "f\"^{self.info['blockname']}.h$\"", "elif", "path", "==", "'grc'", ":", "blockname_pattern", "=", "f\"^{self.info['modname']}_{self.info['blockname']}.block.yml$\"", "for", "f", "in", "files", ":", "if", "re", ".", "search", "(", "blockname_pattern", ",", "os", ".", "path", ".", "basename", "(", "f", ")", ")", "is", "not", "None", ":", "files_filt", ".", "append", "(", "f", ")", "elif", "self", ".", "info", "[", "'pattern'", "]", ":", "# A regex resembling one or several blocks were given as stdin", "for", "f", "in", "files", ":", "if", "re", ".", "search", "(", "self", ".", "info", "[", "'pattern'", "]", ",", "os", ".", "path", ".", "basename", "(", "f", ")", ")", "is", "not", "None", ":", "files_filt", ".", "append", "(", "f", ")", "if", "len", "(", "files_filt", ")", "==", "0", ":", "logger", ".", "info", "(", "\"None found.\"", ")", "return", "[", "]", "# 2. Delete files, Makefile entries and other occurrences", "files_deleted", "=", "[", "]", "yes", "=", "self", ".", "info", "[", "'yes'", "]", "for", "f", "in", "files_filt", ":", "b", "=", "os", ".", "path", ".", "basename", "(", "f", ")", "if", "not", "yes", "and", "self", ".", "cli", ":", "ans", "=", "cli_input", "(", "f\"Really delete {f}? [Y/n/a/q]: \"", ")", ".", "lower", "(", ")", ".", "strip", "(", ")", "if", "ans", "==", "'a'", ":", "yes", "=", "True", "if", "ans", "==", "'q'", ":", "sys", ".", "exit", "(", "0", ")", "if", "ans", "==", "'n'", ":", "continue", "files_deleted", ".", "append", "(", "b", ")", "logger", ".", "info", "(", "f\"Deleting {f}.\"", ")", "self", ".", "scm", ".", "remove_file", "(", "f", ")", "os", ".", "unlink", "(", "f", ")", "if", "(", "os", ".", "path", ".", "exists", "(", "f'{path}/CMakeLists.txt'", ")", ")", ":", "ed", "=", "CMakeFileEditor", "(", "f'{path}/CMakeLists.txt'", ")", "logger", ".", "info", "(", "f\"Deleting occurrences of {b} from {path}/CMakeLists.txt...\"", ")", "for", "var", "in", "makefile_vars", ":", "ed", ".", "remove_value", "(", "var", ",", "b", ")", "if", "cmakeedit_func", "is", "not", "None", ":", "cmakeedit_func", "(", "b", ",", "ed", ")", "ed", ".", "write", "(", ")", "self", ".", "scm", ".", "mark_files_updated", "(", "(", "f'{path}/CMakeLists.txt'", ")", ")", "return", "files_deleted" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/core/rm.py#L135-L207
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/ultratb.py
python
VerboseTB.format_records
(self, records, last_unique, recursion_repeat)
return frames
Format the stack frames of the traceback
Format the stack frames of the traceback
[ "Format", "the", "stack", "frames", "of", "the", "traceback" ]
def format_records(self, records, last_unique, recursion_repeat): """Format the stack frames of the traceback""" frames = [] skipped = 0 lastrecord = len(records) - 1 for i, r in enumerate(records[: last_unique + recursion_repeat + 1]): if self.skip_hidden: if r[0].f_locals.get("__tracebackhide__", 0) and i != lastrecord: skipped += 1 continue if skipped: Colors = self.Colors # just a shorthand + quicker name lookup ColorsNormal = Colors.Normal # used a lot frames.append( " %s[... skipping hidden %s frame]%s\n" % (Colors.excName, skipped, ColorsNormal) ) skipped = 0 frames.append(self.format_record(*r)) if skipped: Colors = self.Colors # just a shorthand + quicker name lookup ColorsNormal = Colors.Normal # used a lot frames.append( " %s[... skipping hidden %s frame]%s\n" % (Colors.excName, skipped, ColorsNormal) ) if recursion_repeat: frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat) frames.append(self.format_record(*records[last_unique+recursion_repeat+1])) return frames
[ "def", "format_records", "(", "self", ",", "records", ",", "last_unique", ",", "recursion_repeat", ")", ":", "frames", "=", "[", "]", "skipped", "=", "0", "lastrecord", "=", "len", "(", "records", ")", "-", "1", "for", "i", ",", "r", "in", "enumerate", "(", "records", "[", ":", "last_unique", "+", "recursion_repeat", "+", "1", "]", ")", ":", "if", "self", ".", "skip_hidden", ":", "if", "r", "[", "0", "]", ".", "f_locals", ".", "get", "(", "\"__tracebackhide__\"", ",", "0", ")", "and", "i", "!=", "lastrecord", ":", "skipped", "+=", "1", "continue", "if", "skipped", ":", "Colors", "=", "self", ".", "Colors", "# just a shorthand + quicker name lookup", "ColorsNormal", "=", "Colors", ".", "Normal", "# used a lot", "frames", ".", "append", "(", "\" %s[... skipping hidden %s frame]%s\\n\"", "%", "(", "Colors", ".", "excName", ",", "skipped", ",", "ColorsNormal", ")", ")", "skipped", "=", "0", "frames", ".", "append", "(", "self", ".", "format_record", "(", "*", "r", ")", ")", "if", "skipped", ":", "Colors", "=", "self", ".", "Colors", "# just a shorthand + quicker name lookup", "ColorsNormal", "=", "Colors", ".", "Normal", "# used a lot", "frames", ".", "append", "(", "\" %s[... skipping hidden %s frame]%s\\n\"", "%", "(", "Colors", ".", "excName", ",", "skipped", ",", "ColorsNormal", ")", ")", "if", "recursion_repeat", ":", "frames", ".", "append", "(", "'... last %d frames repeated, from the frame below ...\\n'", "%", "recursion_repeat", ")", "frames", ".", "append", "(", "self", ".", "format_record", "(", "*", "records", "[", "last_unique", "+", "recursion_repeat", "+", "1", "]", ")", ")", "return", "frames" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/ultratb.py#L815-L849
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Base/Python/slicer/util.py
python
arrayFromMarkupsControlPoints
(markupsNode, world = False)
return narray
Return control point positions of a markups node as rows in a numpy array (of size Nx3). :param world: if set to True then the control points coordinates are returned in world coordinate system (effect of parent transform to the node is applied). The returned array is just a copy and so any modification in the array will not affect the markup node. To modify markup control points based on a numpy array, use :py:meth:`updateMarkupsControlPointsFromArray`.
Return control point positions of a markups node as rows in a numpy array (of size Nx3). :param world: if set to True then the control points coordinates are returned in world coordinate system (effect of parent transform to the node is applied). The returned array is just a copy and so any modification in the array will not affect the markup node. To modify markup control points based on a numpy array, use :py:meth:`updateMarkupsControlPointsFromArray`.
[ "Return", "control", "point", "positions", "of", "a", "markups", "node", "as", "rows", "in", "a", "numpy", "array", "(", "of", "size", "Nx3", ")", ".", ":", "param", "world", ":", "if", "set", "to", "True", "then", "the", "control", "points", "coordinates", "are", "returned", "in", "world", "coordinate", "system", "(", "effect", "of", "parent", "transform", "to", "the", "node", "is", "applied", ")", ".", "The", "returned", "array", "is", "just", "a", "copy", "and", "so", "any", "modification", "in", "the", "array", "will", "not", "affect", "the", "markup", "node", ".", "To", "modify", "markup", "control", "points", "based", "on", "a", "numpy", "array", "use", ":", "py", ":", "meth", ":", "updateMarkupsControlPointsFromArray", "." ]
def arrayFromMarkupsControlPoints(markupsNode, world = False): """Return control point positions of a markups node as rows in a numpy array (of size Nx3). :param world: if set to True then the control points coordinates are returned in world coordinate system (effect of parent transform to the node is applied). The returned array is just a copy and so any modification in the array will not affect the markup node. To modify markup control points based on a numpy array, use :py:meth:`updateMarkupsControlPointsFromArray`. """ numberOfControlPoints = markupsNode.GetNumberOfControlPoints() import numpy as np narray = np.zeros([numberOfControlPoints, 3]) for controlPointIndex in range(numberOfControlPoints): if world: markupsNode.GetNthControlPointPositionWorld(controlPointIndex, narray[controlPointIndex,:]) else: markupsNode.GetNthControlPointPosition(controlPointIndex, narray[controlPointIndex,:]) return narray
[ "def", "arrayFromMarkupsControlPoints", "(", "markupsNode", ",", "world", "=", "False", ")", ":", "numberOfControlPoints", "=", "markupsNode", ".", "GetNumberOfControlPoints", "(", ")", "import", "numpy", "as", "np", "narray", "=", "np", ".", "zeros", "(", "[", "numberOfControlPoints", ",", "3", "]", ")", "for", "controlPointIndex", "in", "range", "(", "numberOfControlPoints", ")", ":", "if", "world", ":", "markupsNode", ".", "GetNthControlPointPositionWorld", "(", "controlPointIndex", ",", "narray", "[", "controlPointIndex", ",", ":", "]", ")", "else", ":", "markupsNode", ".", "GetNthControlPointPosition", "(", "controlPointIndex", ",", "narray", "[", "controlPointIndex", ",", ":", "]", ")", "return", "narray" ]
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Base/Python/slicer/util.py#L1223-L1238
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/service_reflection.py
python
_ServiceStubBuilder.__init__
(self, service_descriptor)
Initializes an instance of the service stub class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the stub class.
Initializes an instance of the service stub class builder.
[ "Initializes", "an", "instance", "of", "the", "service", "stub", "class", "builder", "." ]
def __init__(self, service_descriptor): """Initializes an instance of the service stub class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the stub class. """ self.descriptor = service_descriptor
[ "def", "__init__", "(", "self", ",", "service_descriptor", ")", ":", "self", ".", "descriptor", "=", "service_descriptor" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/service_reflection.py#L242-L249
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/LoadEmptyVesuvio.py
python
LoadEmptyVesuvio._load_ip_file
(self, workspace, ip_file)
return update_inst.getProperty("Workspace").value
If provided, load the instrument parameter file into the result workspace. @param ip_file A string containing the full path to an IP file @return Updated workspace
If provided, load the instrument parameter file into the result workspace.
[ "If", "provided", "load", "the", "instrument", "parameter", "file", "into", "the", "result", "workspace", "." ]
def _load_ip_file(self, workspace, ip_file): """ If provided, load the instrument parameter file into the result workspace. @param ip_file A string containing the full path to an IP file @return Updated workspace """ ip_header = self._get_header_format(ip_file) # More verbose until the child algorithm stuff is sorted update_inst = self.createChildAlgorithm("UpdateInstrumentFromFile") update_inst.setLogging(_LOGGING_) update_inst.setProperty("Workspace", workspace) update_inst.setProperty("Filename", ip_file) update_inst.setProperty("MoveMonitors", False) update_inst.setProperty("IgnorePhi", True) update_inst.setProperty("AsciiHeader", ip_header) update_inst.execute() return update_inst.getProperty("Workspace").value
[ "def", "_load_ip_file", "(", "self", ",", "workspace", ",", "ip_file", ")", ":", "ip_header", "=", "self", ".", "_get_header_format", "(", "ip_file", ")", "# More verbose until the child algorithm stuff is sorted", "update_inst", "=", "self", ".", "createChildAlgorithm", "(", "\"UpdateInstrumentFromFile\"", ")", "update_inst", ".", "setLogging", "(", "_LOGGING_", ")", "update_inst", ".", "setProperty", "(", "\"Workspace\"", ",", "workspace", ")", "update_inst", ".", "setProperty", "(", "\"Filename\"", ",", "ip_file", ")", "update_inst", ".", "setProperty", "(", "\"MoveMonitors\"", ",", "False", ")", "update_inst", ".", "setProperty", "(", "\"IgnorePhi\"", ",", "True", ")", "update_inst", ".", "setProperty", "(", "\"AsciiHeader\"", ",", "ip_header", ")", "update_inst", ".", "execute", "(", ")", "return", "update_inst", ".", "getProperty", "(", "\"Workspace\"", ")", ".", "value" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/LoadEmptyVesuvio.py#L85-L103
numworks/epsilon
8952d2f8b1de1c3f064eec8ffcea804c5594ba4c
build/device/usb/_objfinalizer.py
python
_AutoFinalizedObjectBase._finalize_object
(self)
Actually finalizes the object (frees allocated resources etc.). Returns: None Derived classes should implement this.
Actually finalizes the object (frees allocated resources etc.).
[ "Actually", "finalizes", "the", "object", "(", "frees", "allocated", "resources", "etc", ".", ")", "." ]
def _finalize_object(self): """Actually finalizes the object (frees allocated resources etc.). Returns: None Derived classes should implement this. """ pass
[ "def", "_finalize_object", "(", "self", ")", ":", "pass" ]
https://github.com/numworks/epsilon/blob/8952d2f8b1de1c3f064eec8ffcea804c5594ba4c/build/device/usb/_objfinalizer.py#L44-L51
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_parkingarea.py
python
ParkingAreaDomain.getVehicleCount
(self, stopID)
return self._getUniversal(tc.VAR_STOP_STARTING_VEHICLES_NUMBER, stopID)
getParkingAreaWaiting() -> integer Get the total number of vehicles stopped at the named parking area.
getParkingAreaWaiting() -> integer Get the total number of vehicles stopped at the named parking area.
[ "getParkingAreaWaiting", "()", "-", ">", "integer", "Get", "the", "total", "number", "of", "vehicles", "stopped", "at", "the", "named", "parking", "area", "." ]
def getVehicleCount(self, stopID): """getParkingAreaWaiting() -> integer Get the total number of vehicles stopped at the named parking area. """ return self._getUniversal(tc.VAR_STOP_STARTING_VEHICLES_NUMBER, stopID)
[ "def", "getVehicleCount", "(", "self", ",", "stopID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_STOP_STARTING_VEHICLES_NUMBER", ",", "stopID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_parkingarea.py#L57-L61
potassco/clingo
e0c91d8f95cc28de1c480a871f9c97c30de83d40
libpyclingo/clingo/symbolic_atoms.py
python
SymbolicAtoms.signatures
(self)
return [ (_to_str(_lib.clingo_signature_name(c_sig)), _lib.clingo_signature_arity(c_sig), _lib.clingo_signature_is_positive(c_sig)) for c_sig in p_sigs ]
The list of predicate signatures occurring in the program. The Boolean indicates the sign of the signature.
The list of predicate signatures occurring in the program.
[ "The", "list", "of", "predicate", "signatures", "occurring", "in", "the", "program", "." ]
def signatures(self) -> List[Tuple[str,int,bool]]: ''' The list of predicate signatures occurring in the program. The Boolean indicates the sign of the signature. ''' size = _c_call('size_t', _lib.clingo_symbolic_atoms_signatures_size, self._rep) p_sigs = _ffi.new('clingo_signature_t[]', size) _handle_error(_lib.clingo_symbolic_atoms_signatures(self._rep, p_sigs, size)) return [ (_to_str(_lib.clingo_signature_name(c_sig)), _lib.clingo_signature_arity(c_sig), _lib.clingo_signature_is_positive(c_sig)) for c_sig in p_sigs ]
[ "def", "signatures", "(", "self", ")", "->", "List", "[", "Tuple", "[", "str", ",", "int", ",", "bool", "]", "]", ":", "size", "=", "_c_call", "(", "'size_t'", ",", "_lib", ".", "clingo_symbolic_atoms_signatures_size", ",", "self", ".", "_rep", ")", "p_sigs", "=", "_ffi", ".", "new", "(", "'clingo_signature_t[]'", ",", "size", ")", "_handle_error", "(", "_lib", ".", "clingo_symbolic_atoms_signatures", "(", "self", ".", "_rep", ",", "p_sigs", ",", "size", ")", ")", "return", "[", "(", "_to_str", "(", "_lib", ".", "clingo_signature_name", "(", "c_sig", ")", ")", ",", "_lib", ".", "clingo_signature_arity", "(", "c_sig", ")", ",", "_lib", ".", "clingo_signature_is_positive", "(", "c_sig", ")", ")", "for", "c_sig", "in", "p_sigs", "]" ]
https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/libpyclingo/clingo/symbolic_atoms.py#L154-L167
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/imaplib.py
python
ParseFlags
(resp)
return tuple(mo.group('flags').split())
Convert IMAP4 flags response to python tuple.
Convert IMAP4 flags response to python tuple.
[ "Convert", "IMAP4", "flags", "response", "to", "python", "tuple", "." ]
def ParseFlags(resp): """Convert IMAP4 flags response to python tuple.""" mo = Flags.match(resp) if not mo: return () return tuple(mo.group('flags').split())
[ "def", "ParseFlags", "(", "resp", ")", ":", "mo", "=", "Flags", ".", "match", "(", "resp", ")", "if", "not", "mo", ":", "return", "(", ")", "return", "tuple", "(", "mo", ".", "group", "(", "'flags'", ")", ".", "split", "(", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/imaplib.py#L1371-L1379
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlWordCell.SetPreviousWord
(*args, **kwargs)
return _html.HtmlWordCell_SetPreviousWord(*args, **kwargs)
SetPreviousWord(self, HtmlWordCell cell)
SetPreviousWord(self, HtmlWordCell cell)
[ "SetPreviousWord", "(", "self", "HtmlWordCell", "cell", ")" ]
def SetPreviousWord(*args, **kwargs): """SetPreviousWord(self, HtmlWordCell cell)""" return _html.HtmlWordCell_SetPreviousWord(*args, **kwargs)
[ "def", "SetPreviousWord", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlWordCell_SetPreviousWord", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L779-L781
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
MouseState.SetRightDown
(*args, **kwargs)
return _core_.MouseState_SetRightDown(*args, **kwargs)
SetRightDown(self, bool down)
SetRightDown(self, bool down)
[ "SetRightDown", "(", "self", "bool", "down", ")" ]
def SetRightDown(*args, **kwargs): """SetRightDown(self, bool down)""" return _core_.MouseState_SetRightDown(*args, **kwargs)
[ "def", "SetRightDown", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MouseState_SetRightDown", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L4502-L4504
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/logging_ops.py
python
Print
(input_, data, message=None, first_n=None, summarize=None, name=None)
return gen_logging_ops._print(input_, data, message, first_n, summarize, name)
Prints a list of tensors. This is an identity op with the side effect of printing `data` when evaluating. Args: input_: A tensor passed through this op. data: A list of tensors to print out when op is evaluated. message: A string, prefix of the error message. first_n: Only log `first_n` number of times. Negative numbers log always; this is the default. summarize: Only print this many entries of each tensor. If None, then a maximum of 3 elements are printed per input tensor. name: A name for the operation (optional). Returns: Same tensor as `input_`.
Prints a list of tensors.
[ "Prints", "a", "list", "of", "tensors", "." ]
def Print(input_, data, message=None, first_n=None, summarize=None, name=None): """Prints a list of tensors. This is an identity op with the side effect of printing `data` when evaluating. Args: input_: A tensor passed through this op. data: A list of tensors to print out when op is evaluated. message: A string, prefix of the error message. first_n: Only log `first_n` number of times. Negative numbers log always; this is the default. summarize: Only print this many entries of each tensor. If None, then a maximum of 3 elements are printed per input tensor. name: A name for the operation (optional). Returns: Same tensor as `input_`. """ return gen_logging_ops._print(input_, data, message, first_n, summarize, name)
[ "def", "Print", "(", "input_", ",", "data", ",", "message", "=", "None", ",", "first_n", "=", "None", ",", "summarize", "=", "None", ",", "name", "=", "None", ")", ":", "return", "gen_logging_ops", ".", "_print", "(", "input_", ",", "data", ",", "message", ",", "first_n", ",", "summarize", ",", "name", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/logging_ops.py#L64-L84
zeakey/DeepSkeleton
dc70170f8fd2ec8ca1157484ce66129981104486
python/caffe/io.py
python
Transformer.set_raw_scale
(self, in_, scale)
Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient
Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255.
[ "Set", "the", "scale", "of", "raw", "features", "s", ".", "t", ".", "the", "input", "blob", "=", "input", "*", "scale", ".", "While", "Python", "represents", "images", "in", "[", "0", "1", "]", "certain", "Caffe", "models", "like", "CaffeNet", "and", "AlexNet", "represent", "images", "in", "[", "0", "255", "]", "so", "the", "raw_scale", "of", "these", "models", "must", "be", "255", "." ]
def set_raw_scale(self, in_, scale): """ Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient """ self.__check_input(in_) self.raw_scale[in_] = scale
[ "def", "set_raw_scale", "(", "self", ",", "in_", ",", "scale", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "self", ".", "raw_scale", "[", "in_", "]", "=", "scale" ]
https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/python/caffe/io.py#L217-L230
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PyScrolledWindow.DoGetVirtualSize
(*args, **kwargs)
return _windows_.PyScrolledWindow_DoGetVirtualSize(*args, **kwargs)
DoGetVirtualSize(self) -> Size
DoGetVirtualSize(self) -> Size
[ "DoGetVirtualSize", "(", "self", ")", "-", ">", "Size" ]
def DoGetVirtualSize(*args, **kwargs): """DoGetVirtualSize(self) -> Size""" return _windows_.PyScrolledWindow_DoGetVirtualSize(*args, **kwargs)
[ "def", "DoGetVirtualSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PyScrolledWindow_DoGetVirtualSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L4540-L4542
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
DC.MinY
(*args, **kwargs)
return _gdi_.DC_MinY(*args, **kwargs)
MinY(self) -> int Gets the minimum vertical extent used in drawing commands so far.
MinY(self) -> int
[ "MinY", "(", "self", ")", "-", ">", "int" ]
def MinY(*args, **kwargs): """ MinY(self) -> int Gets the minimum vertical extent used in drawing commands so far. """ return _gdi_.DC_MinY(*args, **kwargs)
[ "def", "MinY", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_MinY", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L4587-L4593
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBCommandReturnObject.GetStatus
(self)
return _lldb.SBCommandReturnObject_GetStatus(self)
GetStatus(SBCommandReturnObject self) -> lldb::ReturnStatus
GetStatus(SBCommandReturnObject self) -> lldb::ReturnStatus
[ "GetStatus", "(", "SBCommandReturnObject", "self", ")", "-", ">", "lldb", "::", "ReturnStatus" ]
def GetStatus(self): """GetStatus(SBCommandReturnObject self) -> lldb::ReturnStatus""" return _lldb.SBCommandReturnObject_GetStatus(self)
[ "def", "GetStatus", "(", "self", ")", ":", "return", "_lldb", ".", "SBCommandReturnObject_GetStatus", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L2915-L2917
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/count-unhappy-friends.py
python
Solution.unhappyFriends
(self, n, preferences, pairs)
return sum(any(friends[i][j] < friends[i][pairing[i]] and friends[j][i] < friends[j][pairing[j]] for j in xrange(len(friends[i])) if j != i and j != pairing[i]) for i in xrange(len(friends)))
:type n: int :type preferences: List[List[int]] :type pairs: List[List[int]] :rtype: int
:type n: int :type preferences: List[List[int]] :type pairs: List[List[int]] :rtype: int
[ ":", "type", "n", ":", "int", ":", "type", "preferences", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "pairs", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "int" ]
def unhappyFriends(self, n, preferences, pairs): """ :type n: int :type preferences: List[List[int]] :type pairs: List[List[int]] :rtype: int """ friends = [[0]*n for _ in xrange(n)] for i in xrange(len(preferences)): for j in xrange(len(preferences[i])): friends[i][preferences[i][j]] = j pairing = [0]*n for i, j in pairs: pairing[i], pairing[j] = j, i return sum(any(friends[i][j] < friends[i][pairing[i]] and friends[j][i] < friends[j][pairing[j]] for j in xrange(len(friends[i])) if j != i and j != pairing[i]) for i in xrange(len(friends)))
[ "def", "unhappyFriends", "(", "self", ",", "n", ",", "preferences", ",", "pairs", ")", ":", "friends", "=", "[", "[", "0", "]", "*", "n", "for", "_", "in", "xrange", "(", "n", ")", "]", "for", "i", "in", "xrange", "(", "len", "(", "preferences", ")", ")", ":", "for", "j", "in", "xrange", "(", "len", "(", "preferences", "[", "i", "]", ")", ")", ":", "friends", "[", "i", "]", "[", "preferences", "[", "i", "]", "[", "j", "]", "]", "=", "j", "pairing", "=", "[", "0", "]", "*", "n", "for", "i", ",", "j", "in", "pairs", ":", "pairing", "[", "i", "]", ",", "pairing", "[", "j", "]", "=", "j", ",", "i", "return", "sum", "(", "any", "(", "friends", "[", "i", "]", "[", "j", "]", "<", "friends", "[", "i", "]", "[", "pairing", "[", "i", "]", "]", "and", "friends", "[", "j", "]", "[", "i", "]", "<", "friends", "[", "j", "]", "[", "pairing", "[", "j", "]", "]", "for", "j", "in", "xrange", "(", "len", "(", "friends", "[", "i", "]", ")", ")", "if", "j", "!=", "i", "and", "j", "!=", "pairing", "[", "i", "]", ")", "for", "i", "in", "xrange", "(", "len", "(", "friends", ")", ")", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/count-unhappy-friends.py#L5-L21
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/json/_json.py
python
JSONTableWriter.__init__
( self, obj, orient: Optional[str], date_format: str, double_precision: int, ensure_ascii: bool, date_unit: str, index: bool, default_handler: Optional[Callable[[Any], JSONSerializable]] = None, indent: int = 0, )
Adds a `schema` attribute with the Table Schema, resets the index (can't do in caller, because the schema inference needs to know what the index is, forces orient to records, and forces date_format to 'iso'.
Adds a `schema` attribute with the Table Schema, resets the index (can't do in caller, because the schema inference needs to know what the index is, forces orient to records, and forces date_format to 'iso'.
[ "Adds", "a", "schema", "attribute", "with", "the", "Table", "Schema", "resets", "the", "index", "(", "can", "t", "do", "in", "caller", "because", "the", "schema", "inference", "needs", "to", "know", "what", "the", "index", "is", "forces", "orient", "to", "records", "and", "forces", "date_format", "to", "iso", "." ]
def __init__( self, obj, orient: Optional[str], date_format: str, double_precision: int, ensure_ascii: bool, date_unit: str, index: bool, default_handler: Optional[Callable[[Any], JSONSerializable]] = None, indent: int = 0, ): """ Adds a `schema` attribute with the Table Schema, resets the index (can't do in caller, because the schema inference needs to know what the index is, forces orient to records, and forces date_format to 'iso'. """ super().__init__( obj, orient, date_format, double_precision, ensure_ascii, date_unit, index, default_handler=default_handler, indent=indent, ) if date_format != "iso": msg = ( "Trying to write with `orient='table'` and " f"`date_format='{date_format}'`. Table Schema requires dates " "to be formatted with `date_format='iso'`" ) raise ValueError(msg) self.schema = build_table_schema(obj, index=self.index) # NotImplemented on a column MultiIndex if obj.ndim == 2 and isinstance(obj.columns, MultiIndex): raise NotImplementedError("orient='table' is not supported for MultiIndex") # TODO: Do this timedelta properly in objToJSON.c See GH #15137 if ( (obj.ndim == 1) and (obj.name in set(obj.index.names)) or len(obj.columns & obj.index.names) ): msg = "Overlapping names between the index and columns" raise ValueError(msg) obj = obj.copy() timedeltas = obj.select_dtypes(include=["timedelta"]).columns if len(timedeltas): obj[timedeltas] = obj[timedeltas].applymap(lambda x: x.isoformat()) # Convert PeriodIndex to datetimes before serializing if is_period_dtype(obj.index): obj.index = obj.index.to_timestamp() # exclude index from obj if index=False if not self.index: self.obj = obj.reset_index(drop=True) else: self.obj = obj.reset_index(drop=False) self.date_format = "iso" self.orient = "records" self.index = index
[ "def", "__init__", "(", "self", ",", "obj", ",", "orient", ":", "Optional", "[", "str", "]", ",", "date_format", ":", "str", ",", "double_precision", ":", "int", ",", "ensure_ascii", ":", "bool", ",", "date_unit", ":", "str", ",", "index", ":", "bool", ",", "default_handler", ":", "Optional", "[", "Callable", "[", "[", "Any", "]", ",", "JSONSerializable", "]", "]", "=", "None", ",", "indent", ":", "int", "=", "0", ",", ")", ":", "super", "(", ")", ".", "__init__", "(", "obj", ",", "orient", ",", "date_format", ",", "double_precision", ",", "ensure_ascii", ",", "date_unit", ",", "index", ",", "default_handler", "=", "default_handler", ",", "indent", "=", "indent", ",", ")", "if", "date_format", "!=", "\"iso\"", ":", "msg", "=", "(", "\"Trying to write with `orient='table'` and \"", "f\"`date_format='{date_format}'`. Table Schema requires dates \"", "\"to be formatted with `date_format='iso'`\"", ")", "raise", "ValueError", "(", "msg", ")", "self", ".", "schema", "=", "build_table_schema", "(", "obj", ",", "index", "=", "self", ".", "index", ")", "# NotImplemented on a column MultiIndex", "if", "obj", ".", "ndim", "==", "2", "and", "isinstance", "(", "obj", ".", "columns", ",", "MultiIndex", ")", ":", "raise", "NotImplementedError", "(", "\"orient='table' is not supported for MultiIndex\"", ")", "# TODO: Do this timedelta properly in objToJSON.c See GH #15137", "if", "(", "(", "obj", ".", "ndim", "==", "1", ")", "and", "(", "obj", ".", "name", "in", "set", "(", "obj", ".", "index", ".", "names", ")", ")", "or", "len", "(", "obj", ".", "columns", "&", "obj", ".", "index", ".", "names", ")", ")", ":", "msg", "=", "\"Overlapping names between the index and columns\"", "raise", "ValueError", "(", "msg", ")", "obj", "=", "obj", ".", "copy", "(", ")", "timedeltas", "=", "obj", ".", "select_dtypes", "(", "include", "=", "[", "\"timedelta\"", "]", ")", ".", "columns", "if", "len", "(", "timedeltas", ")", ":", "obj", "[", "timedeltas", "]", "=", "obj", "[", "timedeltas", "]", ".", "applymap", "(", "lambda", "x", ":", "x", ".", "isoformat", "(", ")", ")", "# Convert PeriodIndex to datetimes before serializing", "if", "is_period_dtype", "(", "obj", ".", "index", ")", ":", "obj", ".", "index", "=", "obj", ".", "index", ".", "to_timestamp", "(", ")", "# exclude index from obj if index=False", "if", "not", "self", ".", "index", ":", "self", ".", "obj", "=", "obj", ".", "reset_index", "(", "drop", "=", "True", ")", "else", ":", "self", ".", "obj", "=", "obj", ".", "reset_index", "(", "drop", "=", "False", ")", "self", ".", "date_format", "=", "\"iso\"", "self", ".", "orient", "=", "\"records\"", "self", ".", "index", "=", "index" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/json/_json.py#L252-L321
sigmaai/self-driving-golf-cart
8d891600af3d851add27a10ae45cf3c2108bb87c
ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/debug_helper.py
python
DebugHelper.draw_arrow
(self, marker, lifetime, color)
draw arrow from ros marker
draw arrow from ros marker
[ "draw", "arrow", "from", "ros", "marker" ]
def draw_arrow(self, marker, lifetime, color): """ draw arrow from ros marker """ if marker.points: if not len(marker.points) == 2: rospy.logwarn( "Drawing arrow from points requires two points. Received {}".format( len(marker.points))) return thickness = marker.scale.x arrow_size = marker.scale.y start = carla.Location( x=marker.points[0].x, y=-marker.points[0].y, z=marker.points[0].z) end = carla.Location( x=marker.points[1].x, y=-marker.points[1].y, z=marker.points[1].z) rospy.loginfo("Draw Arrow from {} to {} (color: {}, lifetime: {}, " "thickness: {}, arrow_size: {})".format( start, end, color, lifetime, thickness, arrow_size)) self.debug.draw_arrow( start, end, thickness=thickness, arrow_size=arrow_size, color=color, life_time=lifetime) else: rospy.logwarn( "Drawing arrow from Position/Orientation not yet supported. " "Please use points.")
[ "def", "draw_arrow", "(", "self", ",", "marker", ",", "lifetime", ",", "color", ")", ":", "if", "marker", ".", "points", ":", "if", "not", "len", "(", "marker", ".", "points", ")", "==", "2", ":", "rospy", ".", "logwarn", "(", "\"Drawing arrow from points requires two points. Received {}\"", ".", "format", "(", "len", "(", "marker", ".", "points", ")", ")", ")", "return", "thickness", "=", "marker", ".", "scale", ".", "x", "arrow_size", "=", "marker", ".", "scale", ".", "y", "start", "=", "carla", ".", "Location", "(", "x", "=", "marker", ".", "points", "[", "0", "]", ".", "x", ",", "y", "=", "-", "marker", ".", "points", "[", "0", "]", ".", "y", ",", "z", "=", "marker", ".", "points", "[", "0", "]", ".", "z", ")", "end", "=", "carla", ".", "Location", "(", "x", "=", "marker", ".", "points", "[", "1", "]", ".", "x", ",", "y", "=", "-", "marker", ".", "points", "[", "1", "]", ".", "y", ",", "z", "=", "marker", ".", "points", "[", "1", "]", ".", "z", ")", "rospy", ".", "loginfo", "(", "\"Draw Arrow from {} to {} (color: {}, lifetime: {}, \"", "\"thickness: {}, arrow_size: {})\"", ".", "format", "(", "start", ",", "end", ",", "color", ",", "lifetime", ",", "thickness", ",", "arrow_size", ")", ")", "self", ".", "debug", ".", "draw_arrow", "(", "start", ",", "end", ",", "thickness", "=", "thickness", ",", "arrow_size", "=", "arrow_size", ",", "color", "=", "color", ",", "life_time", "=", "lifetime", ")", "else", ":", "rospy", ".", "logwarn", "(", "\"Drawing arrow from Position/Orientation not yet supported. \"", "\"Please use points.\"", ")" ]
https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/debug_helper.py#L77-L107
cinder/Cinder
e83f5bb9c01a63eec20168d02953a0879e5100f7
docs/libs/bs4/dammit.py
python
EntitySubstitution.substitute_xml
(cls, value, make_quoted_attribute=False)
return value
Substitute XML entities for special XML characters. :param value: A string to be substituted. The less-than sign will become &lt;, the greater-than sign will become &gt;, and any ampersands will become &amp;. If you want ampersands that appear to be part of an entity definition to be left alone, use substitute_xml_containing_entities() instead. :param make_quoted_attribute: If True, then the string will be quoted, as befits an attribute value.
Substitute XML entities for special XML characters.
[ "Substitute", "XML", "entities", "for", "special", "XML", "characters", "." ]
def substitute_xml(cls, value, make_quoted_attribute=False): """Substitute XML entities for special XML characters. :param value: A string to be substituted. The less-than sign will become &lt;, the greater-than sign will become &gt;, and any ampersands will become &amp;. If you want ampersands that appear to be part of an entity definition to be left alone, use substitute_xml_containing_entities() instead. :param make_quoted_attribute: If True, then the string will be quoted, as befits an attribute value. """ # Escape angle brackets and ampersands. value = cls.AMPERSAND_OR_BRACKET.sub( cls._substitute_xml_entity, value) if make_quoted_attribute: value = cls.quoted_attribute_value(value) return value
[ "def", "substitute_xml", "(", "cls", ",", "value", ",", "make_quoted_attribute", "=", "False", ")", ":", "# Escape angle brackets and ampersands.", "value", "=", "cls", ".", "AMPERSAND_OR_BRACKET", ".", "sub", "(", "cls", ".", "_substitute_xml_entity", ",", "value", ")", "if", "make_quoted_attribute", ":", "value", "=", "cls", ".", "quoted_attribute_value", "(", "value", ")", "return", "value" ]
https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/libs/bs4/dammit.py#L137-L155
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/aixlink.py
python
generate
(env)
Add Builders and construction variables for Visual Age linker to an Environment.
Add Builders and construction variables for Visual Age linker to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "Visual", "Age", "linker", "to", "an", "Environment", "." ]
def generate(env): """ Add Builders and construction variables for Visual Age linker to an Environment. """ link.generate(env) env['SMARTLINKFLAGS'] = smart_linkflags env['LINKFLAGS'] = SCons.Util.CLVar('$SMARTLINKFLAGS') env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -qmkshrobj -qsuppress=1501-218') env['SHLIBSUFFIX'] = '.a'
[ "def", "generate", "(", "env", ")", ":", "link", ".", "generate", "(", "env", ")", "env", "[", "'SMARTLINKFLAGS'", "]", "=", "smart_linkflags", "env", "[", "'LINKFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'$SMARTLINKFLAGS'", ")", "env", "[", "'SHLINKFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'$LINKFLAGS -qmkshrobj -qsuppress=1501-218'", ")", "env", "[", "'SHLIBSUFFIX'", "]", "=", "'.a'" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/aixlink.py#L51-L61
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/yapf/yapf/yapflib/split_penalty.py
python
_SetStronglyConnected
(*nodes)
Set a STRONGLY_CONNECTED penalty annotation for the given nodes.
Set a STRONGLY_CONNECTED penalty annotation for the given nodes.
[ "Set", "a", "STRONGLY_CONNECTED", "penalty", "annotation", "for", "the", "given", "nodes", "." ]
def _SetStronglyConnected(*nodes): """Set a STRONGLY_CONNECTED penalty annotation for the given nodes.""" for node in nodes: _RecAnnotate(node, pytree_utils.Annotation.SPLIT_PENALTY, STRONGLY_CONNECTED)
[ "def", "_SetStronglyConnected", "(", "*", "nodes", ")", ":", "for", "node", "in", "nodes", ":", "_RecAnnotate", "(", "node", ",", "pytree_utils", ".", "Annotation", ".", "SPLIT_PENALTY", ",", "STRONGLY_CONNECTED", ")" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/yapf/yapf/yapflib/split_penalty.py#L431-L435
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/layers/python/layers/layers.py
python
dropout
(inputs, keep_prob=0.5, noise_shape=None, is_training=True, outputs_collections=None, scope=None)
Returns a dropout op applied to the input. With probability `keep_prob`, outputs the input element scaled up by `1 / keep_prob`, otherwise outputs `0`. The scaling is so that the expected sum is unchanged. Args: inputs: The tensor to pass to the nn.dropout op. keep_prob: A scalar `Tensor` with the same type as x. The probability that each element is kept. noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for randomly generated keep/drop flags. is_training: A bool `Tensor` indicating whether or not the model is in training mode. If so, dropout is applied and values scaled. Otherwise, inputs is returned. outputs_collections: Collection to add the outputs. scope: Optional scope for name_scope. Returns: A tensor representing the output of the operation.
Returns a dropout op applied to the input.
[ "Returns", "a", "dropout", "op", "applied", "to", "the", "input", "." ]
def dropout(inputs, keep_prob=0.5, noise_shape=None, is_training=True, outputs_collections=None, scope=None): """Returns a dropout op applied to the input. With probability `keep_prob`, outputs the input element scaled up by `1 / keep_prob`, otherwise outputs `0`. The scaling is so that the expected sum is unchanged. Args: inputs: The tensor to pass to the nn.dropout op. keep_prob: A scalar `Tensor` with the same type as x. The probability that each element is kept. noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for randomly generated keep/drop flags. is_training: A bool `Tensor` indicating whether or not the model is in training mode. If so, dropout is applied and values scaled. Otherwise, inputs is returned. outputs_collections: Collection to add the outputs. scope: Optional scope for name_scope. Returns: A tensor representing the output of the operation. """ with variable_scope.variable_scope( scope, 'Dropout', [inputs], custom_getter=_model_variable_getter) as sc: inputs = ops.convert_to_tensor(inputs) layer = core_layers.Dropout(rate=1 - keep_prob, noise_shape=noise_shape, name=sc.name, _scope=sc) outputs = layer.apply(inputs, training=is_training) return utils.collect_named_outputs( outputs_collections, sc.original_name_scope, outputs)
[ "def", "dropout", "(", "inputs", ",", "keep_prob", "=", "0.5", ",", "noise_shape", "=", "None", ",", "is_training", "=", "True", ",", "outputs_collections", "=", "None", ",", "scope", "=", "None", ")", ":", "with", "variable_scope", ".", "variable_scope", "(", "scope", ",", "'Dropout'", ",", "[", "inputs", "]", ",", "custom_getter", "=", "_model_variable_getter", ")", "as", "sc", ":", "inputs", "=", "ops", ".", "convert_to_tensor", "(", "inputs", ")", "layer", "=", "core_layers", ".", "Dropout", "(", "rate", "=", "1", "-", "keep_prob", ",", "noise_shape", "=", "noise_shape", ",", "name", "=", "sc", ".", "name", ",", "_scope", "=", "sc", ")", "outputs", "=", "layer", ".", "apply", "(", "inputs", ",", "training", "=", "is_training", ")", "return", "utils", ".", "collect_named_outputs", "(", "outputs_collections", ",", "sc", ".", "original_name_scope", ",", "outputs", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/layers/layers.py#L1374-L1410
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/front/caffe/extractors/native_caffe.py
python
blob_name
(i)
Implements legacy schema for blobs naming: 0-th blob is called 'weights' 1-th blob is called 'biases' then, next blobs are called according to the new default schema with 'custom_' prefix: custom_2, custom_3 and so on.
Implements legacy schema for blobs naming: 0-th blob is called 'weights' 1-th blob is called 'biases' then, next blobs are called according to the new default schema with 'custom_' prefix: custom_2, custom_3 and so on.
[ "Implements", "legacy", "schema", "for", "blobs", "naming", ":", "0", "-", "th", "blob", "is", "called", "weights", "1", "-", "th", "blob", "is", "called", "biases", "then", "next", "blobs", "are", "called", "according", "to", "the", "new", "default", "schema", "with", "custom_", "prefix", ":", "custom_2", "custom_3", "and", "so", "on", "." ]
def blob_name(i): """ Implements legacy schema for blobs naming: 0-th blob is called 'weights' 1-th blob is called 'biases' then, next blobs are called according to the new default schema with 'custom_' prefix: custom_2, custom_3 and so on. """ predefined_names = ['weights', 'biases'] if i < len(predefined_names): return predefined_names[i] else: return 'custom_{}'.format(i)
[ "def", "blob_name", "(", "i", ")", ":", "predefined_names", "=", "[", "'weights'", ",", "'biases'", "]", "if", "i", "<", "len", "(", "predefined_names", ")", ":", "return", "predefined_names", "[", "i", "]", "else", ":", "return", "'custom_{}'", ".", "format", "(", "i", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/caffe/extractors/native_caffe.py#L10-L22
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/perf/metrics/io.py
python
IOMetric.AddSummaryResults
(self, browser, results)
Add summary results to the results object.
Add summary results to the results object.
[ "Add", "summary", "results", "to", "the", "results", "object", "." ]
def AddSummaryResults(self, browser, results): """Add summary results to the results object.""" io_stats = browser.io_stats if not io_stats['Browser']: return def AddSummariesForProcessType(process_type_io, process_type_trace): """For a given process type, add all relevant summary results. Args: process_type_io: Type of process (eg Browser or Renderer). process_type_trace: String to be added to the trace name in the results. """ if 'ReadOperationCount' in io_stats[process_type_io]: results.AddSummary('read_operations_' + process_type_trace, 'count', io_stats[process_type_io] ['ReadOperationCount'], data_type='unimportant') if 'WriteOperationCount' in io_stats[process_type_io]: results.AddSummary('write_operations_' + process_type_trace, 'count', io_stats[process_type_io] ['WriteOperationCount'], data_type='unimportant') if 'ReadTransferCount' in io_stats[process_type_io]: results.AddSummary('read_bytes_' + process_type_trace, 'kb', io_stats[process_type_io] ['ReadTransferCount'] / 1024, data_type='unimportant') if 'WriteTransferCount' in io_stats[process_type_io]: results.AddSummary('write_bytes_' + process_type_trace, 'kb', io_stats[process_type_io] ['WriteTransferCount'] / 1024, data_type='unimportant') AddSummariesForProcessType('Browser', 'browser') AddSummariesForProcessType('Renderer', 'renderer') AddSummariesForProcessType('Gpu', 'gpu')
[ "def", "AddSummaryResults", "(", "self", ",", "browser", ",", "results", ")", ":", "io_stats", "=", "browser", ".", "io_stats", "if", "not", "io_stats", "[", "'Browser'", "]", ":", "return", "def", "AddSummariesForProcessType", "(", "process_type_io", ",", "process_type_trace", ")", ":", "\"\"\"For a given process type, add all relevant summary results.\n\n Args:\n process_type_io: Type of process (eg Browser or Renderer).\n process_type_trace: String to be added to the trace name in the results.\n \"\"\"", "if", "'ReadOperationCount'", "in", "io_stats", "[", "process_type_io", "]", ":", "results", ".", "AddSummary", "(", "'read_operations_'", "+", "process_type_trace", ",", "'count'", ",", "io_stats", "[", "process_type_io", "]", "[", "'ReadOperationCount'", "]", ",", "data_type", "=", "'unimportant'", ")", "if", "'WriteOperationCount'", "in", "io_stats", "[", "process_type_io", "]", ":", "results", ".", "AddSummary", "(", "'write_operations_'", "+", "process_type_trace", ",", "'count'", ",", "io_stats", "[", "process_type_io", "]", "[", "'WriteOperationCount'", "]", ",", "data_type", "=", "'unimportant'", ")", "if", "'ReadTransferCount'", "in", "io_stats", "[", "process_type_io", "]", ":", "results", ".", "AddSummary", "(", "'read_bytes_'", "+", "process_type_trace", ",", "'kb'", ",", "io_stats", "[", "process_type_io", "]", "[", "'ReadTransferCount'", "]", "/", "1024", ",", "data_type", "=", "'unimportant'", ")", "if", "'WriteTransferCount'", "in", "io_stats", "[", "process_type_io", "]", ":", "results", ".", "AddSummary", "(", "'write_bytes_'", "+", "process_type_trace", ",", "'kb'", ",", "io_stats", "[", "process_type_io", "]", "[", "'WriteTransferCount'", "]", "/", "1024", ",", "data_type", "=", "'unimportant'", ")", "AddSummariesForProcessType", "(", "'Browser'", ",", "'browser'", ")", "AddSummariesForProcessType", "(", "'Renderer'", ",", "'renderer'", ")", "AddSummariesForProcessType", "(", "'Gpu'", ",", "'gpu'", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/perf/metrics/io.py#L24-L60
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
KeyboardState.SetMetaDown
(*args, **kwargs)
return _core_.KeyboardState_SetMetaDown(*args, **kwargs)
SetMetaDown(self, bool down)
SetMetaDown(self, bool down)
[ "SetMetaDown", "(", "self", "bool", "down", ")" ]
def SetMetaDown(*args, **kwargs): """SetMetaDown(self, bool down)""" return _core_.KeyboardState_SetMetaDown(*args, **kwargs)
[ "def", "SetMetaDown", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "KeyboardState_SetMetaDown", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L4392-L4394
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/agents/tools/wrappers.py
python
ExternalProcess._receive
(self)
Wait for a message from the worker process and return its payload. Raises: Exception: An exception was raised inside the worker process. KeyError: The reveived message is of an unknown type. Returns: Payload object of the message.
Wait for a message from the worker process and return its payload.
[ "Wait", "for", "a", "message", "from", "the", "worker", "process", "and", "return", "its", "payload", "." ]
def _receive(self): """Wait for a message from the worker process and return its payload. Raises: Exception: An exception was raised inside the worker process. KeyError: The reveived message is of an unknown type. Returns: Payload object of the message. """ message, payload = self._conn.recv() # Re-raise exceptions in the main process. if message == self._EXCEPTION: stacktrace = payload raise Exception(stacktrace) if message == self._RESULT: return payload raise KeyError('Received message of unexpected type {}'.format(message))
[ "def", "_receive", "(", "self", ")", ":", "message", ",", "payload", "=", "self", ".", "_conn", ".", "recv", "(", ")", "# Re-raise exceptions in the main process.", "if", "message", "==", "self", ".", "_EXCEPTION", ":", "stacktrace", "=", "payload", "raise", "Exception", "(", "stacktrace", ")", "if", "message", "==", "self", ".", "_RESULT", ":", "return", "payload", "raise", "KeyError", "(", "'Received message of unexpected type {}'", ".", "format", "(", "message", ")", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/tools/wrappers.py#L418-L435
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/dataset/dataset.py
python
FileInstantDataset.init
(self, **kwargs)
should be called only once in user's python scripts to initialize setings of dataset instance
should be called only once in user's python scripts to initialize setings of dataset instance
[ "should", "be", "called", "only", "once", "in", "user", "s", "python", "scripts", "to", "initialize", "setings", "of", "dataset", "instance" ]
def init(self, **kwargs): """ should be called only once in user's python scripts to initialize setings of dataset instance """ super(FileInstantDataset, self).init(**kwargs)
[ "def", "init", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "FileInstantDataset", ",", "self", ")", ".", "init", "(", "*", "*", "kwargs", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/dataset/dataset.py#L1302-L1306
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
adodbapi/adodbapi.py
python
Connection._rollback
(self)
In case a database does provide transactions this method causes the the database to roll back to the start of any pending transaction. Closing a connection without committing the changes first will cause an implicit rollback to be performed. If the database does not support the functionality required by the method, the interface should throw an exception in case the method is used. The preferred approach is to not implement the method and thus have Python generate an AttributeError in case the method is requested. This allows the programmer to check for database capabilities using the standard hasattr() function. For some dynamically configured interfaces it may not be appropriate to require dynamically making the method available. These interfaces should then raise a NotSupportedError to indicate the non-ability to perform the roll back when the method is invoked.
In case a database does provide transactions this method causes the the database to roll back to the start of any pending transaction. Closing a connection without committing the changes first will cause an implicit rollback to be performed.
[ "In", "case", "a", "database", "does", "provide", "transactions", "this", "method", "causes", "the", "the", "database", "to", "roll", "back", "to", "the", "start", "of", "any", "pending", "transaction", ".", "Closing", "a", "connection", "without", "committing", "the", "changes", "first", "will", "cause", "an", "implicit", "rollback", "to", "be", "performed", "." ]
def _rollback(self): """In case a database does provide transactions this method causes the the database to roll back to the start of any pending transaction. Closing a connection without committing the changes first will cause an implicit rollback to be performed. If the database does not support the functionality required by the method, the interface should throw an exception in case the method is used. The preferred approach is to not implement the method and thus have Python generate an AttributeError in case the method is requested. This allows the programmer to check for database capabilities using the standard hasattr() function. For some dynamically configured interfaces it may not be appropriate to require dynamically making the method available. These interfaces should then raise a NotSupportedError to indicate the non-ability to perform the roll back when the method is invoked. """ self.messages = [] if ( self.transaction_level ): # trying to roll back with no open transaction causes an error try: self.transaction_level = self.connector.RollbackTrans() if verbose > 1: print("rollback done on connection at %X" % id(self)) if not self._autocommit and not ( self.connector.Attributes & adc.adXactAbortRetaining ): # If attributes has adXactAbortRetaining it performs retaining aborts that is, # calling RollbackTrans automatically starts a new transaction. Not all providers support this. # If not, we will have to start a new transaction by this command: if ( not self.transaction_level ): # if self.transaction_level == 0 or self.transaction_level is None: self.transaction_level = self.connector.BeginTrans() except Exception as e: self._raiseConnectionError(api.ProgrammingError, e)
[ "def", "_rollback", "(", "self", ")", ":", "self", ".", "messages", "=", "[", "]", "if", "(", "self", ".", "transaction_level", ")", ":", "# trying to roll back with no open transaction causes an error", "try", ":", "self", ".", "transaction_level", "=", "self", ".", "connector", ".", "RollbackTrans", "(", ")", "if", "verbose", ">", "1", ":", "print", "(", "\"rollback done on connection at %X\"", "%", "id", "(", "self", ")", ")", "if", "not", "self", ".", "_autocommit", "and", "not", "(", "self", ".", "connector", ".", "Attributes", "&", "adc", ".", "adXactAbortRetaining", ")", ":", "# If attributes has adXactAbortRetaining it performs retaining aborts that is,", "# calling RollbackTrans automatically starts a new transaction. Not all providers support this.", "# If not, we will have to start a new transaction by this command:", "if", "(", "not", "self", ".", "transaction_level", ")", ":", "# if self.transaction_level == 0 or self.transaction_level is None:", "self", ".", "transaction_level", "=", "self", ".", "connector", ".", "BeginTrans", "(", ")", "except", "Exception", "as", "e", ":", "self", ".", "_raiseConnectionError", "(", "api", ".", "ProgrammingError", ",", "e", ")" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/adodbapi/adodbapi.py#L409-L443
BVLC/caffe
9b891540183ddc834a02b2bd81b31afae71b2153
scripts/cpp_lint.py
python
IsBlankLine
(line)
return not line or line.isspace()
Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank.
Returns true if the given line is blank.
[ "Returns", "true", "if", "the", "given", "line", "is", "blank", "." ]
def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace()
[ "def", "IsBlankLine", "(", "line", ")", ":", "return", "not", "line", "or", "line", ".", "isspace", "(", ")" ]
https://github.com/BVLC/caffe/blob/9b891540183ddc834a02b2bd81b31afae71b2153/scripts/cpp_lint.py#L2373-L2385
Kitware/kwiver
7ed70308905698b6e88d27ae3dc028c9b016ca0a
python/kwiver/vital/modules/loaders.py
python
ModuleLoader._findPluginFilePaths
(self, namespace)
Searches for modules in `namespace` that are reachable from the paths defined in the `PYTHONPATH` environment variable. Args: namespace (str): the importable name of a python module or package Yields: str: mod_rel_path - the paths (relative to PYTHONPATH) of the modules in the namespace.
Searches for modules in `namespace` that are reachable from the paths defined in the `PYTHONPATH` environment variable.
[ "Searches", "for", "modules", "in", "namespace", "that", "are", "reachable", "from", "the", "paths", "defined", "in", "the", "PYTHONPATH", "environment", "variable", "." ]
def _findPluginFilePaths(self, namespace): """ Searches for modules in `namespace` that are reachable from the paths defined in the `PYTHONPATH` environment variable. Args: namespace (str): the importable name of a python module or package Yields: str: mod_rel_path - the paths (relative to PYTHONPATH) of the modules in the namespace. """ already_seen = set() py_exts = ['.py', '.pyc', '.pyo'] for ext in py_exts: if namespace.endswith(ext): logger.warn(('do not specify .py extension for the {} ' 'sprokit python module').format(namespace)) namespace = namespace[:-len(ext)] namespace_rel_path = namespace.replace('.', os.path.sep) # Look in each location in the path for path in sys.path: # Within this, we want to look for a package for the namespace namespace_path = os.path.join(path, namespace_rel_path) if os.path.isdir(namespace_path): # Find all top-level modules in the namespace package for possible in os.listdir(namespace_path): poss_path = os.path.join(namespace_path, possible) if os.path.isdir(poss_path): if not self._isPackage(poss_path): continue base = possible else: base, ext = os.path.splitext(possible) if base == '__init__' or ext != '.py': continue if base not in already_seen: already_seen.add(base) mod_rel_path = os.path.join(namespace_rel_path, possible) yield mod_rel_path else: # namespace was not a package, check if it was a pyfile base = namespace_path if base not in already_seen: for ext in py_exts: mod_fpath = base + ext if os.path.isfile(mod_fpath): already_seen.add(base) mod_rel_path = namespace_rel_path + ext yield mod_rel_path # Dont test remaining pyc / pyo extensions. break
[ "def", "_findPluginFilePaths", "(", "self", ",", "namespace", ")", ":", "already_seen", "=", "set", "(", ")", "py_exts", "=", "[", "'.py'", ",", "'.pyc'", ",", "'.pyo'", "]", "for", "ext", "in", "py_exts", ":", "if", "namespace", ".", "endswith", "(", "ext", ")", ":", "logger", ".", "warn", "(", "(", "'do not specify .py extension for the {} '", "'sprokit python module'", ")", ".", "format", "(", "namespace", ")", ")", "namespace", "=", "namespace", "[", ":", "-", "len", "(", "ext", ")", "]", "namespace_rel_path", "=", "namespace", ".", "replace", "(", "'.'", ",", "os", ".", "path", ".", "sep", ")", "# Look in each location in the path", "for", "path", "in", "sys", ".", "path", ":", "# Within this, we want to look for a package for the namespace", "namespace_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "namespace_rel_path", ")", "if", "os", ".", "path", ".", "isdir", "(", "namespace_path", ")", ":", "# Find all top-level modules in the namespace package", "for", "possible", "in", "os", ".", "listdir", "(", "namespace_path", ")", ":", "poss_path", "=", "os", ".", "path", ".", "join", "(", "namespace_path", ",", "possible", ")", "if", "os", ".", "path", ".", "isdir", "(", "poss_path", ")", ":", "if", "not", "self", ".", "_isPackage", "(", "poss_path", ")", ":", "continue", "base", "=", "possible", "else", ":", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "possible", ")", "if", "base", "==", "'__init__'", "or", "ext", "!=", "'.py'", ":", "continue", "if", "base", "not", "in", "already_seen", ":", "already_seen", ".", "add", "(", "base", ")", "mod_rel_path", "=", "os", ".", "path", ".", "join", "(", "namespace_rel_path", ",", "possible", ")", "yield", "mod_rel_path", "else", ":", "# namespace was not a package, check if it was a pyfile", "base", "=", "namespace_path", "if", "base", "not", "in", "already_seen", ":", "for", "ext", "in", "py_exts", ":", "mod_fpath", "=", "base", "+", "ext", "if", "os", ".", "path", ".", "isfile", "(", "mod_fpath", ")", ":", "already_seen", ".", "add", "(", "base", ")", "mod_rel_path", "=", "namespace_rel_path", "+", "ext", "yield", "mod_rel_path", "# Dont test remaining pyc / pyo extensions.", "break" ]
https://github.com/Kitware/kwiver/blob/7ed70308905698b6e88d27ae3dc028c9b016ca0a/python/kwiver/vital/modules/loaders.py#L87-L143
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/build/vs_toolchain.py
python
_CopyRuntime2015
(target_dir, source_dir, dll_pattern)
Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't exist, but the target directory does exist.
Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't exist, but the target directory does exist.
[ "Copy", "both", "the", "msvcp", "and", "vccorlib", "runtime", "DLLs", "only", "if", "the", "target", "doesn", "t", "exist", "but", "the", "target", "directory", "does", "exist", "." ]
def _CopyRuntime2015(target_dir, source_dir, dll_pattern): """Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't exist, but the target directory does exist.""" for file_part in ('msvcp', 'vccorlib'): dll = dll_pattern % file_part target = os.path.join(target_dir, dll) source = os.path.join(source_dir, dll) _CopyRuntimeImpl(target, source)
[ "def", "_CopyRuntime2015", "(", "target_dir", ",", "source_dir", ",", "dll_pattern", ")", ":", "for", "file_part", "in", "(", "'msvcp'", ",", "'vccorlib'", ")", ":", "dll", "=", "dll_pattern", "%", "file_part", "target", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "dll", ")", "source", "=", "os", ".", "path", ".", "join", "(", "source_dir", ",", "dll", ")", "_CopyRuntimeImpl", "(", "target", ",", "source", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/build/vs_toolchain.py#L107-L114
opengauss-mirror/openGauss-server
e383f1b77720a00ddbe4c0655bc85914d9b02a2b
src/gausskernel/dbmind/tools/anomaly_detection/detector/tools/slow_sql/diagnosing.py
python
diagnose_user
(dbagent, query, start_time)
return zip_rca
Get RCA of system resource. :param dbagent: obj, interface for sqlite3. :param query: str, query. :param start_time: int, start_time. :return
Get RCA of system resource. :param dbagent: obj, interface for sqlite3. :param query: str, query. :param start_time: int, start_time. :return
[ "Get", "RCA", "of", "system", "resource", ".", ":", "param", "dbagent", ":", "obj", "interface", "for", "sqlite3", ".", ":", "param", "query", ":", "str", "query", ".", ":", "param", "start_time", ":", "int", "start_time", ".", ":", "return" ]
def diagnose_user(dbagent, query, start_time): """ Get RCA of system resource. :param dbagent: obj, interface for sqlite3. :param query: str, query. :param start_time: int, start_time. :return """ rca = [] suggestion = [] plan = Plan() timestamp, start_time, finish_time, explain = dbagent.fetch_all_result('select timestamp, start_time, finish_time, ' ' explain from wdr where start_time == "{start_time}"' .format(start_time=start_time))[0] plan.parse(explain) operators = plan.sorted_operators if not len(operators): return [] heaviest_opt = operators[0] for operator in operators: if str.startswith(operator.name, 'Vector Streaming(type: REDISTRIBUTE)'): rca.append(PLAN_CAUSE['Redistribute']['DataSkew']) suggestion.append(PLAN_SUGGESTION['Redistribute']['DataSkew']) zip_rca = [[x_rca, x_sug] for x_rca, x_sug in zip(rca, suggestion)] zip_rca.insert(0, finish_time) zip_rca.insert(0, start_time) return zip_rca if heaviest_opt.type == 'Scan': analyze_scan(dbagent, query, timestamp, rca, suggestion) elif heaviest_opt.type == 'Sort': analyze_sort(dbagent, start_time, finish_time, heaviest_opt, rca, suggestion) elif heaviest_opt.type == 'Other': if str.startswith(heaviest_opt.name, 'Update'): analyze_scan(dbagent, query, timestamp, rca, suggestion) elif str.startswith(heaviest_opt.name, 'Insert'): rca.append(PLAN_CAUSE['Insert']['DataRes']) suggestion.append(PLAN_SUGGESTION['Insert']['DataRes']) elif str.startswith(heaviest_opt.name, 'Delete'): rca.append(PLAN_CAUSE['Delete']['DataRes']) suggestion.append(PLAN_SUGGESTION['Delete']['DataRes']) analyze_join(heaviest_opt, rca, suggestion) elif heaviest_opt.type == 'Aggregate': analyze_agg(heaviest_opt, rca, suggestion) do_resource_check(dbagent, query, timestamp, rca, suggestion) zip_rca = [[x_rca, x_sug] for x_rca, x_sug in zip(rca, suggestion)] zip_rca.insert(0, finish_time) zip_rca.insert(0, start_time) return zip_rca
[ "def", "diagnose_user", "(", "dbagent", ",", "query", ",", "start_time", ")", ":", "rca", "=", "[", "]", "suggestion", "=", "[", "]", "plan", "=", "Plan", "(", ")", "timestamp", ",", "start_time", ",", "finish_time", ",", "explain", "=", "dbagent", ".", "fetch_all_result", "(", "'select timestamp, start_time, finish_time, '", "' explain from wdr where start_time == \"{start_time}\"'", ".", "format", "(", "start_time", "=", "start_time", ")", ")", "[", "0", "]", "plan", ".", "parse", "(", "explain", ")", "operators", "=", "plan", ".", "sorted_operators", "if", "not", "len", "(", "operators", ")", ":", "return", "[", "]", "heaviest_opt", "=", "operators", "[", "0", "]", "for", "operator", "in", "operators", ":", "if", "str", ".", "startswith", "(", "operator", ".", "name", ",", "'Vector Streaming(type: REDISTRIBUTE)'", ")", ":", "rca", ".", "append", "(", "PLAN_CAUSE", "[", "'Redistribute'", "]", "[", "'DataSkew'", "]", ")", "suggestion", ".", "append", "(", "PLAN_SUGGESTION", "[", "'Redistribute'", "]", "[", "'DataSkew'", "]", ")", "zip_rca", "=", "[", "[", "x_rca", ",", "x_sug", "]", "for", "x_rca", ",", "x_sug", "in", "zip", "(", "rca", ",", "suggestion", ")", "]", "zip_rca", ".", "insert", "(", "0", ",", "finish_time", ")", "zip_rca", ".", "insert", "(", "0", ",", "start_time", ")", "return", "zip_rca", "if", "heaviest_opt", ".", "type", "==", "'Scan'", ":", "analyze_scan", "(", "dbagent", ",", "query", ",", "timestamp", ",", "rca", ",", "suggestion", ")", "elif", "heaviest_opt", ".", "type", "==", "'Sort'", ":", "analyze_sort", "(", "dbagent", ",", "start_time", ",", "finish_time", ",", "heaviest_opt", ",", "rca", ",", "suggestion", ")", "elif", "heaviest_opt", ".", "type", "==", "'Other'", ":", "if", "str", ".", "startswith", "(", "heaviest_opt", ".", "name", ",", "'Update'", ")", ":", "analyze_scan", "(", "dbagent", ",", "query", ",", "timestamp", ",", "rca", ",", "suggestion", ")", "elif", "str", ".", "startswith", "(", "heaviest_opt", ".", "name", ",", "'Insert'", ")", ":", "rca", ".", "append", "(", "PLAN_CAUSE", "[", "'Insert'", "]", "[", "'DataRes'", "]", ")", "suggestion", ".", "append", "(", "PLAN_SUGGESTION", "[", "'Insert'", "]", "[", "'DataRes'", "]", ")", "elif", "str", ".", "startswith", "(", "heaviest_opt", ".", "name", ",", "'Delete'", ")", ":", "rca", ".", "append", "(", "PLAN_CAUSE", "[", "'Delete'", "]", "[", "'DataRes'", "]", ")", "suggestion", ".", "append", "(", "PLAN_SUGGESTION", "[", "'Delete'", "]", "[", "'DataRes'", "]", ")", "analyze_join", "(", "heaviest_opt", ",", "rca", ",", "suggestion", ")", "elif", "heaviest_opt", ".", "type", "==", "'Aggregate'", ":", "analyze_agg", "(", "heaviest_opt", ",", "rca", ",", "suggestion", ")", "do_resource_check", "(", "dbagent", ",", "query", ",", "timestamp", ",", "rca", ",", "suggestion", ")", "zip_rca", "=", "[", "[", "x_rca", ",", "x_sug", "]", "for", "x_rca", ",", "x_sug", "in", "zip", "(", "rca", ",", "suggestion", ")", "]", "zip_rca", ".", "insert", "(", "0", ",", "finish_time", ")", "zip_rca", ".", "insert", "(", "0", ",", "start_time", ")", "return", "zip_rca" ]
https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/anomaly_detection/detector/tools/slow_sql/diagnosing.py#L257-L308
lballabio/quantlib-old
136336947ed4fea9ecc1da6edad188700e821739
gensrc/gensrc/addins/excel.py
python
ExcelAddin.generateRegisterFunctions
(self, cat)
Generate the code for registering addin functions with Excel.
Generate the code for registering addin functions with Excel.
[ "Generate", "the", "code", "for", "registering", "addin", "functions", "with", "Excel", "." ]
def generateRegisterFunctions(self, cat): """Generate the code for registering addin functions with Excel.""" registerCode = '' unregisterCode = '' for func in cat.functions(self.name_, supportedplatform.MANUAL): self.functionCount_ += 1 registerCode += self.generateRegisterFunction(func, cat.xlFunctionWizardCategory()) unregisterCode += self.generateRegisterFunction(func, cat.xlFunctionWizardCategory(), False) self.outputRegisterFile(registerCode, unregisterCode, cat.name())
[ "def", "generateRegisterFunctions", "(", "self", ",", "cat", ")", ":", "registerCode", "=", "''", "unregisterCode", "=", "''", "for", "func", "in", "cat", ".", "functions", "(", "self", ".", "name_", ",", "supportedplatform", ".", "MANUAL", ")", ":", "self", ".", "functionCount_", "+=", "1", "registerCode", "+=", "self", ".", "generateRegisterFunction", "(", "func", ",", "cat", ".", "xlFunctionWizardCategory", "(", ")", ")", "unregisterCode", "+=", "self", ".", "generateRegisterFunction", "(", "func", ",", "cat", ".", "xlFunctionWizardCategory", "(", ")", ",", "False", ")", "self", ".", "outputRegisterFile", "(", "registerCode", ",", "unregisterCode", ",", "cat", ".", "name", "(", ")", ")" ]
https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/addins/excel.py#L245-L255
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/interpolate/fitpack2.py
python
UnivariateSpline._from_tck
(cls, tck, ext=0)
return self
Construct a spline object from given tck
Construct a spline object from given tck
[ "Construct", "a", "spline", "object", "from", "given", "tck" ]
def _from_tck(cls, tck, ext=0): """Construct a spline object from given tck""" self = cls.__new__(cls) t, c, k = tck self._eval_args = tck # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier self._data = (None, None, None, None, None, k, None, len(t), t, c, None, None, None, None) self.ext = ext return self
[ "def", "_from_tck", "(", "cls", ",", "tck", ",", "ext", "=", "0", ")", ":", "self", "=", "cls", ".", "__new__", "(", "cls", ")", "t", ",", "c", ",", "k", "=", "tck", "self", ".", "_eval_args", "=", "tck", "# _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier", "self", ".", "_data", "=", "(", "None", ",", "None", ",", "None", ",", "None", ",", "None", ",", "k", ",", "None", ",", "len", "(", "t", ")", ",", "t", ",", "c", ",", "None", ",", "None", ",", "None", ",", "None", ")", "self", ".", "ext", "=", "ext", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/fitpack2.py#L194-L203
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/extras.py
python
issequence
(seq)
return False
Is seq a sequence (ndarray, list or tuple)?
Is seq a sequence (ndarray, list or tuple)?
[ "Is", "seq", "a", "sequence", "(", "ndarray", "list", "or", "tuple", ")", "?" ]
def issequence(seq): """Is seq a sequence (ndarray, list or tuple)?""" if isinstance(seq, (ndarray, tuple, list)): return True return False
[ "def", "issequence", "(", "seq", ")", ":", "if", "isinstance", "(", "seq", ",", "(", "ndarray", ",", "tuple", ",", "list", ")", ")", ":", "return", "True", "return", "False" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/extras.py#L55-L59
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/api.py
python
get
(url, params=None, **kwargs)
return request('get', url, params=params, **kwargs)
Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
Sends a GET request.
[ "Sends", "a", "GET", "request", "." ]
def get(url, params=None, **kwargs): """Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return request('get', url, params=params, **kwargs)
[ "def", "get", "(", "url", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "request", "(", "'get'", ",", "url", ",", "params", "=", "params", ",", "*", "*", "kwargs", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/api.py#L58-L69
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
RadioBox.FindString
(*args, **kwargs)
return _controls_.RadioBox_FindString(*args, **kwargs)
FindString(self, String s) -> int
FindString(self, String s) -> int
[ "FindString", "(", "self", "String", "s", ")", "-", ">", "int" ]
def FindString(*args, **kwargs): """FindString(self, String s) -> int""" return _controls_.RadioBox_FindString(*args, **kwargs)
[ "def", "FindString", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "RadioBox_FindString", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L2615-L2617
gromacs/gromacs
7dec3a3f99993cf5687a122de3e12de31c21c399
docs/doxygen/reporter.py
python
Reporter._write
(self, message)
Implement actual message writing.
Implement actual message writing.
[ "Implement", "actual", "message", "writing", "." ]
def _write(self, message): """Implement actual message writing.""" wholemsg = '' if message.location: wholemsg += str(message.location) + ': ' wholemsg += message.message if message.details: wholemsg += '\n ' + '\n '.join(message.details) wholemsg += '\n' sys.stderr.write(wholemsg) if self._logfp: self._logfp.write(wholemsg) self._had_warnings = True
[ "def", "_write", "(", "self", ",", "message", ")", ":", "wholemsg", "=", "''", "if", "message", ".", "location", ":", "wholemsg", "+=", "str", "(", "message", ".", "location", ")", "+", "': '", "wholemsg", "+=", "message", ".", "message", "if", "message", ".", "details", ":", "wholemsg", "+=", "'\\n '", "+", "'\\n '", ".", "join", "(", "message", ".", "details", ")", "wholemsg", "+=", "'\\n'", "sys", ".", "stderr", ".", "write", "(", "wholemsg", ")", "if", "self", ".", "_logfp", ":", "self", ".", "_logfp", ".", "write", "(", "wholemsg", ")", "self", ".", "_had_warnings", "=", "True" ]
https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/docs/doxygen/reporter.py#L191-L203
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
uCSIsCJKCompatibility
(code)
return ret
Check whether the character is part of CJKCompatibility UCS Block
Check whether the character is part of CJKCompatibility UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "CJKCompatibility", "UCS", "Block" ]
def uCSIsCJKCompatibility(code): """Check whether the character is part of CJKCompatibility UCS Block """ ret = libxml2mod.xmlUCSIsCJKCompatibility(code) return ret
[ "def", "uCSIsCJKCompatibility", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsCJKCompatibility", "(", "code", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L2137-L2141
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/framework/ops.py
python
get_to_proto_function
(collection_name)
Returns the to_proto function for collection_name.
Returns the to_proto function for collection_name.
[ "Returns", "the", "to_proto", "function", "for", "collection_name", "." ]
def get_to_proto_function(collection_name): """Returns the to_proto function for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[1] except LookupError: return None
[ "def", "get_to_proto_function", "(", "collection_name", ")", ":", "try", ":", "return", "_proto_function_registry", ".", "lookup", "(", "collection_name", ")", "[", "1", "]", "except", "LookupError", ":", "return", "None" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/ops.py#L4071-L4076
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
is_array
(a)
return isinstance(a, ArrayRef)
Return `True` if `a` is a Z3 array expression. >>> a = Array('a', IntSort(), IntSort()) >>> is_array(a) True >>> is_array(Store(a, 0, 1)) True >>> is_array(a[0]) False
Return `True` if `a` is a Z3 array expression.
[ "Return", "True", "if", "a", "is", "a", "Z3", "array", "expression", "." ]
def is_array(a): """Return `True` if `a` is a Z3 array expression. >>> a = Array('a', IntSort(), IntSort()) >>> is_array(a) True >>> is_array(Store(a, 0, 1)) True >>> is_array(a[0]) False """ return isinstance(a, ArrayRef)
[ "def", "is_array", "(", "a", ")", ":", "return", "isinstance", "(", "a", ",", "ArrayRef", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L4576-L4587
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/network/download.py
python
parse_content_disposition
(content_disposition, default_filename)
return filename or default_filename
Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty.
Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty.
[ "Parse", "the", "filename", "value", "from", "a", "Content", "-", "Disposition", "header", "and", "return", "the", "default", "filename", "if", "the", "result", "is", "empty", "." ]
def parse_content_disposition(content_disposition, default_filename): # type: (str, str) -> str """ Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty. """ _type, params = cgi.parse_header(content_disposition) filename = params.get('filename') if filename: # We need to sanitize the filename to prevent directory traversal # in case the filename contains ".." path parts. filename = sanitize_content_filename(filename) return filename or default_filename
[ "def", "parse_content_disposition", "(", "content_disposition", ",", "default_filename", ")", ":", "# type: (str, str) -> str", "_type", ",", "params", "=", "cgi", ".", "parse_header", "(", "content_disposition", ")", "filename", "=", "params", ".", "get", "(", "'filename'", ")", "if", "filename", ":", "# We need to sanitize the filename to prevent directory traversal", "# in case the filename contains \"..\" path parts.", "filename", "=", "sanitize_content_filename", "(", "filename", ")", "return", "filename", "or", "default_filename" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/network/download.py#L89-L101
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/serialutil.py
python
SerialBase.inter_byte_timeout
(self, ic_timeout)
Change inter-byte timeout setting.
Change inter-byte timeout setting.
[ "Change", "inter", "-", "byte", "timeout", "setting", "." ]
def inter_byte_timeout(self, ic_timeout): """Change inter-byte timeout setting.""" if ic_timeout is not None: if ic_timeout < 0: raise ValueError("Not a valid timeout: {!r}".format(ic_timeout)) try: ic_timeout + 1 # test if it's a number, will throw a TypeError if not... except TypeError: raise ValueError("Not a valid timeout: {!r}".format(ic_timeout)) self._inter_byte_timeout = ic_timeout if self.is_open: self._reconfigure_port()
[ "def", "inter_byte_timeout", "(", "self", ",", "ic_timeout", ")", ":", "if", "ic_timeout", "is", "not", "None", ":", "if", "ic_timeout", "<", "0", ":", "raise", "ValueError", "(", "\"Not a valid timeout: {!r}\"", ".", "format", "(", "ic_timeout", ")", ")", "try", ":", "ic_timeout", "+", "1", "# test if it's a number, will throw a TypeError if not...", "except", "TypeError", ":", "raise", "ValueError", "(", "\"Not a valid timeout: {!r}\"", ".", "format", "(", "ic_timeout", ")", ")", "self", ".", "_inter_byte_timeout", "=", "ic_timeout", "if", "self", ".", "is_open", ":", "self", ".", "_reconfigure_port", "(", ")" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialutil.py#L396-L408
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_basestc.py
python
EditraBaseStc.SetBlockCaret
(self)
Change caret style to block
Change caret style to block
[ "Change", "caret", "style", "to", "block" ]
def SetBlockCaret(self): """Change caret style to block""" if hasattr(self, 'SetCaretStyle'): # wxPython 2.9 or greater self.SetCaretStyle(wx.stc.STC_CARETSTYLE_BLOCK) else: # Alternatively, just make the caret a bit thicker! # best we can do on 2.8 self.SetCaretWidth(3)
[ "def", "SetBlockCaret", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'SetCaretStyle'", ")", ":", "# wxPython 2.9 or greater", "self", ".", "SetCaretStyle", "(", "wx", ".", "stc", ".", "STC_CARETSTYLE_BLOCK", ")", "else", ":", "# Alternatively, just make the caret a bit thicker!", "# best we can do on 2.8", "self", ".", "SetCaretWidth", "(", "3", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_basestc.py#L310-L317
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/parser/source_reader.py
python
source_reader_t.create_xml_file
(self, source_file, destination=None)
return xml_file
This method will generate a xml file using an external tool. The method will return the file path of the generated xml file. :param source_file: path to the source file that should be parsed. :type source_file: str :param destination: if given, will be used as target file path for the xml generator. :type destination: str :rtype: path to xml file.
This method will generate a xml file using an external tool.
[ "This", "method", "will", "generate", "a", "xml", "file", "using", "an", "external", "tool", "." ]
def create_xml_file(self, source_file, destination=None): """ This method will generate a xml file using an external tool. The method will return the file path of the generated xml file. :param source_file: path to the source file that should be parsed. :type source_file: str :param destination: if given, will be used as target file path for the xml generator. :type destination: str :rtype: path to xml file. """ xml_file = destination # If file specified, remove it to start else create new file name if xml_file: utils.remove_file_no_raise(xml_file, self.__config) else: xml_file = utils.create_temp_file_name(suffix='.xml') ffname = source_file if not os.path.isabs(ffname): ffname = self.__file_full_name(source_file) command_line = self.__create_command_line(ffname, xml_file) process = subprocess.Popen( args=command_line, shell=True, stdout=subprocess.PIPE) try: results = [] while process.poll() is None: line = process.stdout.readline() if line.strip(): results.append(line.rstrip()) for line in process.stdout.readlines(): if line.strip(): results.append(line.rstrip()) exit_status = process.returncode msg = os.linesep.join([str(s) for s in results]) if self.__config.ignore_gccxml_output: if not os.path.isfile(xml_file): raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + ": %s status:%s" % (msg, exit_status)) else: if msg or exit_status or not \ os.path.isfile(xml_file): if not os.path.isfile(xml_file): raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + " xml file does not exist") else: raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + ": %s status:%s" % (msg, exit_status)) except Exception: utils.remove_file_no_raise(xml_file, self.__config) raise finally: process.wait() process.stdout.close() return xml_file
[ "def", "create_xml_file", "(", "self", ",", "source_file", ",", "destination", "=", "None", ")", ":", "xml_file", "=", "destination", "# If file specified, remove it to start else create new file name", "if", "xml_file", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "else", ":", "xml_file", "=", "utils", ".", "create_temp_file_name", "(", "suffix", "=", "'.xml'", ")", "ffname", "=", "source_file", "if", "not", "os", ".", "path", ".", "isabs", "(", "ffname", ")", ":", "ffname", "=", "self", ".", "__file_full_name", "(", "source_file", ")", "command_line", "=", "self", ".", "__create_command_line", "(", "ffname", ",", "xml_file", ")", "process", "=", "subprocess", ".", "Popen", "(", "args", "=", "command_line", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "try", ":", "results", "=", "[", "]", "while", "process", ".", "poll", "(", ")", "is", "None", ":", "line", "=", "process", ".", "stdout", ".", "readline", "(", ")", "if", "line", ".", "strip", "(", ")", ":", "results", ".", "append", "(", "line", ".", "rstrip", "(", ")", ")", "for", "line", "in", "process", ".", "stdout", ".", "readlines", "(", ")", ":", "if", "line", ".", "strip", "(", ")", ":", "results", ".", "append", "(", "line", ".", "rstrip", "(", ")", ")", "exit_status", "=", "process", ".", "returncode", "msg", "=", "os", ".", "linesep", ".", "join", "(", "[", "str", "(", "s", ")", "for", "s", "in", "results", "]", ")", "if", "self", ".", "__config", ".", "ignore_gccxml_output", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "xml_file", ")", ":", "raise", "RuntimeError", "(", "\"Error occurred while running \"", "+", "self", ".", "__config", ".", "xml_generator", ".", "upper", "(", ")", "+", "\": %s status:%s\"", "%", "(", "msg", ",", "exit_status", ")", ")", "else", ":", "if", "msg", "or", "exit_status", "or", "not", "os", ".", "path", ".", "isfile", "(", "xml_file", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "xml_file", ")", ":", "raise", "RuntimeError", "(", "\"Error occurred while running \"", "+", "self", ".", "__config", ".", "xml_generator", ".", "upper", "(", ")", "+", "\" xml file does not exist\"", ")", "else", ":", "raise", "RuntimeError", "(", "\"Error occurred while running \"", "+", "self", ".", "__config", ".", "xml_generator", ".", "upper", "(", ")", "+", "\": %s status:%s\"", "%", "(", "msg", ",", "exit_status", ")", ")", "except", "Exception", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "raise", "finally", ":", "process", ".", "wait", "(", ")", "process", ".", "stdout", ".", "close", "(", ")", "return", "xml_file" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/parser/source_reader.py#L202-L274
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/internal/python_message.py
python
_AddPropertiesForRepeatedField
(field, cls)
Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add values to these containers, we perform type-checking in the case of repeated scalar fields, and we also set any necessary "has" bits as a side-effect. Args: field: A FieldDescriptor for this field. cls: The class we're constructing.
Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below).
[ "Adds", "a", "public", "property", "for", "a", "repeated", "protocol", "message", "field", ".", "Clients", "can", "use", "this", "property", "to", "get", "the", "value", "of", "the", "field", "which", "will", "be", "either", "a", "_RepeatedScalarFieldContainer", "or", "_RepeatedCompositeFieldContainer", "(", "see", "below", ")", "." ]
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add values to these containers, we perform type-checking in the case of repeated scalar fields, and we also set any necessary "has" bits as a side-effect. Args: field: A FieldDescriptor for this field. cls: The class we're constructing. """ proto_field_name = field.name property_name = _PropertyName(proto_field_name) def getter(self): field_value = self._fields.get(field) if field_value is None: # Construct a new object to represent this field. field_value = field._default_constructor(self) # Atomically check if another thread has preempted us and, if not, swap # in the new object we just created. If someone has preempted us, we # take that object and discard ours. # WARNING: We are relying on setdefault() being atomic. This is true # in CPython but we haven't investigated others. This warning appears # in several other locations in this file. field_value = self._fields.setdefault(field, field_value) return field_value getter.__module__ = None getter.__doc__ = 'Getter for %s.' % proto_field_name # We define a setter just so we can throw an exception with a more # helpful error message. def setter(self, new_value): raise AttributeError('Assignment not allowed to repeated field ' '"%s" in protocol message object.' % proto_field_name) doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name setattr(cls, property_name, property(getter, setter, doc=doc))
[ "def", "_AddPropertiesForRepeatedField", "(", "field", ",", "cls", ")", ":", "proto_field_name", "=", "field", ".", "name", "property_name", "=", "_PropertyName", "(", "proto_field_name", ")", "def", "getter", "(", "self", ")", ":", "field_value", "=", "self", ".", "_fields", ".", "get", "(", "field", ")", "if", "field_value", "is", "None", ":", "# Construct a new object to represent this field.", "field_value", "=", "field", ".", "_default_constructor", "(", "self", ")", "# Atomically check if another thread has preempted us and, if not, swap", "# in the new object we just created. If someone has preempted us, we", "# take that object and discard ours.", "# WARNING: We are relying on setdefault() being atomic. This is true", "# in CPython but we haven't investigated others. This warning appears", "# in several other locations in this file.", "field_value", "=", "self", ".", "_fields", ".", "setdefault", "(", "field", ",", "field_value", ")", "return", "field_value", "getter", ".", "__module__", "=", "None", "getter", ".", "__doc__", "=", "'Getter for %s.'", "%", "proto_field_name", "# We define a setter just so we can throw an exception with a more", "# helpful error message.", "def", "setter", "(", "self", ",", "new_value", ")", ":", "raise", "AttributeError", "(", "'Assignment not allowed to repeated field '", "'\"%s\" in protocol message object.'", "%", "proto_field_name", ")", "doc", "=", "'Magic attribute generated for \"%s\" proto field.'", "%", "proto_field_name", "setattr", "(", "cls", ",", "property_name", ",", "property", "(", "getter", ",", "setter", ",", "doc", "=", "doc", ")", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/internal/python_message.py#L594-L635
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/cubecolourdialog.py
python
rad2deg
(x)
return 180.0*x/pi
Transforms radians into degrees. :param `x`: a float representing an angle in radians.
Transforms radians into degrees.
[ "Transforms", "radians", "into", "degrees", "." ]
def rad2deg(x): """ Transforms radians into degrees. :param `x`: a float representing an angle in radians. """ return 180.0*x/pi
[ "def", "rad2deg", "(", "x", ")", ":", "return", "180.0", "*", "x", "/", "pi" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/cubecolourdialog.py#L1205-L1212
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/text_file.py
python
TextFile.open
(self, filename)
Open a new file named 'filename'. This overrides both the 'filename' and 'file' arguments to the constructor.
Open a new file named 'filename'. This overrides both the 'filename' and 'file' arguments to the constructor.
[ "Open", "a", "new", "file", "named", "filename", ".", "This", "overrides", "both", "the", "filename", "and", "file", "arguments", "to", "the", "constructor", "." ]
def open(self, filename): """Open a new file named 'filename'. This overrides both the 'filename' and 'file' arguments to the constructor.""" self.filename = filename self.file = io.open(self.filename, 'r', errors=self.errors) self.current_line = 0
[ "def", "open", "(", "self", ",", "filename", ")", ":", "self", ".", "filename", "=", "filename", "self", ".", "file", "=", "io", ".", "open", "(", "self", ".", "filename", ",", "'r'", ",", "errors", "=", "self", ".", "errors", ")", "self", ".", "current_line", "=", "0" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/text_file.py#L111-L116
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/warnings.py
python
formatwarning
(message, category, filename, lineno, line=None)
return s
Function to format a warning the standard way.
Function to format a warning the standard way.
[ "Function", "to", "format", "a", "warning", "the", "standard", "way", "." ]
def formatwarning(message, category, filename, lineno, line=None): """Function to format a warning the standard way.""" try: unicodetype = unicode except NameError: unicodetype = () try: message = str(message) except UnicodeEncodeError: pass s = "%s: %s: %s\n" % (lineno, category.__name__, message) line = linecache.getline(filename, lineno) if line is None else line if line: line = line.strip() if isinstance(s, unicodetype) and isinstance(line, str): line = unicode(line, 'latin1') s += " %s\n" % line if isinstance(s, unicodetype) and isinstance(filename, str): enc = sys.getfilesystemencoding() if enc: try: filename = unicode(filename, enc) except UnicodeDecodeError: pass s = "%s:%s" % (filename, s) return s
[ "def", "formatwarning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "line", "=", "None", ")", ":", "try", ":", "unicodetype", "=", "unicode", "except", "NameError", ":", "unicodetype", "=", "(", ")", "try", ":", "message", "=", "str", "(", "message", ")", "except", "UnicodeEncodeError", ":", "pass", "s", "=", "\"%s: %s: %s\\n\"", "%", "(", "lineno", ",", "category", ".", "__name__", ",", "message", ")", "line", "=", "linecache", ".", "getline", "(", "filename", ",", "lineno", ")", "if", "line", "is", "None", "else", "line", "if", "line", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "isinstance", "(", "s", ",", "unicodetype", ")", "and", "isinstance", "(", "line", ",", "str", ")", ":", "line", "=", "unicode", "(", "line", ",", "'latin1'", ")", "s", "+=", "\" %s\\n\"", "%", "line", "if", "isinstance", "(", "s", ",", "unicodetype", ")", "and", "isinstance", "(", "filename", ",", "str", ")", ":", "enc", "=", "sys", ".", "getfilesystemencoding", "(", ")", "if", "enc", ":", "try", ":", "filename", "=", "unicode", "(", "filename", ",", "enc", ")", "except", "UnicodeDecodeError", ":", "pass", "s", "=", "\"%s:%s\"", "%", "(", "filename", ",", "s", ")", "return", "s" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/warnings.py#L40-L65
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/spatial/kdtree.py
python
minkowski_distance
(x, y, p=2)
Compute the L**p distance between two arrays. Parameters ---------- x : (M, K) array_like Input array. y : (N, K) array_like Input array. p : float, 1 <= p <= infinity Which Minkowski p-norm to use. Examples -------- >>> from scipy.spatial import minkowski_distance >>> minkowski_distance([[0,0],[0,0]], [[1,1],[0,1]]) array([ 1.41421356, 1. ])
Compute the L**p distance between two arrays.
[ "Compute", "the", "L", "**", "p", "distance", "between", "two", "arrays", "." ]
def minkowski_distance(x, y, p=2): """ Compute the L**p distance between two arrays. Parameters ---------- x : (M, K) array_like Input array. y : (N, K) array_like Input array. p : float, 1 <= p <= infinity Which Minkowski p-norm to use. Examples -------- >>> from scipy.spatial import minkowski_distance >>> minkowski_distance([[0,0],[0,0]], [[1,1],[0,1]]) array([ 1.41421356, 1. ]) """ x = np.asarray(x) y = np.asarray(y) if p == np.inf or p == 1: return minkowski_distance_p(x, y, p) else: return minkowski_distance_p(x, y, p)**(1./p)
[ "def", "minkowski_distance", "(", "x", ",", "y", ",", "p", "=", "2", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "y", "=", "np", ".", "asarray", "(", "y", ")", "if", "p", "==", "np", ".", "inf", "or", "p", "==", "1", ":", "return", "minkowski_distance_p", "(", "x", ",", "y", ",", "p", ")", "else", ":", "return", "minkowski_distance_p", "(", "x", ",", "y", ",", "p", ")", "**", "(", "1.", "/", "p", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/spatial/kdtree.py#L49-L74
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/util.py
python
TimeZoneOffset.utcoffset
(self, dt)
return datetime.timedelta(minutes=self.__offset)
Get the a timedelta with the time zone's offset from UTC. Returns: The time zone offset from UTC, as a timedelta.
Get the a timedelta with the time zone's offset from UTC.
[ "Get", "the", "a", "timedelta", "with", "the", "time", "zone", "s", "offset", "from", "UTC", "." ]
def utcoffset(self, dt): """Get the a timedelta with the time zone's offset from UTC. Returns: The time zone offset from UTC, as a timedelta. """ return datetime.timedelta(minutes=self.__offset)
[ "def", "utcoffset", "(", "self", ",", "dt", ")", ":", "return", "datetime", ".", "timedelta", "(", "minutes", "=", "self", ".", "__offset", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/util.py#L420-L426
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
PyPickerBase.UpdateTextCtrlFromPicker
(*args, **kwargs)
return _controls_.PyPickerBase_UpdateTextCtrlFromPicker(*args, **kwargs)
UpdateTextCtrlFromPicker(self)
UpdateTextCtrlFromPicker(self)
[ "UpdateTextCtrlFromPicker", "(", "self", ")" ]
def UpdateTextCtrlFromPicker(*args, **kwargs): """UpdateTextCtrlFromPicker(self)""" return _controls_.PyPickerBase_UpdateTextCtrlFromPicker(*args, **kwargs)
[ "def", "UpdateTextCtrlFromPicker", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "PyPickerBase_UpdateTextCtrlFromPicker", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L6879-L6881
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/graph_editor/match.py
python
OpMatcher.input_ops
(self, *args)
return self
Add input matches.
Add input matches.
[ "Add", "input", "matches", "." ]
def input_ops(self, *args): """Add input matches.""" if self.input_op_matches is not None: raise ValueError("input_op_matches is already set.") self.input_op_matches = [] for input_match in args: self.input_op_matches.append(_make_graph_match(input_match)) return self
[ "def", "input_ops", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "input_op_matches", "is", "not", "None", ":", "raise", "ValueError", "(", "\"input_op_matches is already set.\"", ")", "self", ".", "input_op_matches", "=", "[", "]", "for", "input_match", "in", "args", ":", "self", ".", "input_op_matches", ".", "append", "(", "_make_graph_match", "(", "input_match", ")", ")", "return", "self" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/match.py#L122-L129
YosysHQ/nextpnr
74c99f9195eeb47d106ca74b7abb894cfd47cc03
3rdparty/pybind11/pybind11/setup_helpers.py
python
ParallelCompile.function
(self)
return compile_function
Builds a function object usable as distutils.ccompiler.CCompiler.compile.
Builds a function object usable as distutils.ccompiler.CCompiler.compile.
[ "Builds", "a", "function", "object", "usable", "as", "distutils", ".", "ccompiler", ".", "CCompiler", ".", "compile", "." ]
def function(self): """ Builds a function object usable as distutils.ccompiler.CCompiler.compile. """ def compile_function( compiler, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None, ): # These lines are directly from distutils.ccompiler.CCompiler macros, objects, extra_postargs, pp_opts, build = compiler._setup_compile( output_dir, macros, include_dirs, sources, depends, extra_postargs ) cc_args = compiler._get_cc_args(pp_opts, debug, extra_preargs) # The number of threads; start with default. threads = self.default # Determine the number of compilation threads, unless set by an environment variable. if self.envvar is not None: threads = int(os.environ.get(self.envvar, self.default)) def _single_compile(obj): try: src, ext = build[obj] except KeyError: return if not os.path.exists(obj) or self.needs_recompile(obj, src): compiler._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) try: import multiprocessing from multiprocessing.pool import ThreadPool except ImportError: threads = 1 if threads == 0: try: threads = multiprocessing.cpu_count() threads = self.max if self.max and self.max < threads else threads except NotImplementedError: threads = 1 if threads > 1: for _ in ThreadPool(threads).imap_unordered(_single_compile, objects): pass else: for ob in objects: _single_compile(ob) return objects return compile_function
[ "def", "function", "(", "self", ")", ":", "def", "compile_function", "(", "compiler", ",", "sources", ",", "output_dir", "=", "None", ",", "macros", "=", "None", ",", "include_dirs", "=", "None", ",", "debug", "=", "0", ",", "extra_preargs", "=", "None", ",", "extra_postargs", "=", "None", ",", "depends", "=", "None", ",", ")", ":", "# These lines are directly from distutils.ccompiler.CCompiler", "macros", ",", "objects", ",", "extra_postargs", ",", "pp_opts", ",", "build", "=", "compiler", ".", "_setup_compile", "(", "output_dir", ",", "macros", ",", "include_dirs", ",", "sources", ",", "depends", ",", "extra_postargs", ")", "cc_args", "=", "compiler", ".", "_get_cc_args", "(", "pp_opts", ",", "debug", ",", "extra_preargs", ")", "# The number of threads; start with default.", "threads", "=", "self", ".", "default", "# Determine the number of compilation threads, unless set by an environment variable.", "if", "self", ".", "envvar", "is", "not", "None", ":", "threads", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "self", ".", "envvar", ",", "self", ".", "default", ")", ")", "def", "_single_compile", "(", "obj", ")", ":", "try", ":", "src", ",", "ext", "=", "build", "[", "obj", "]", "except", "KeyError", ":", "return", "if", "not", "os", ".", "path", ".", "exists", "(", "obj", ")", "or", "self", ".", "needs_recompile", "(", "obj", ",", "src", ")", ":", "compiler", ".", "_compile", "(", "obj", ",", "src", ",", "ext", ",", "cc_args", ",", "extra_postargs", ",", "pp_opts", ")", "try", ":", "import", "multiprocessing", "from", "multiprocessing", ".", "pool", "import", "ThreadPool", "except", "ImportError", ":", "threads", "=", "1", "if", "threads", "==", "0", ":", "try", ":", "threads", "=", "multiprocessing", ".", "cpu_count", "(", ")", "threads", "=", "self", ".", "max", "if", "self", ".", "max", "and", "self", ".", "max", "<", "threads", "else", "threads", "except", "NotImplementedError", ":", "threads", "=", "1", "if", "threads", ">", "1", ":", "for", "_", "in", "ThreadPool", "(", "threads", ")", ".", "imap_unordered", "(", "_single_compile", ",", "objects", ")", ":", "pass", "else", ":", "for", "ob", "in", "objects", ":", "_single_compile", "(", "ob", ")", "return", "objects", "return", "compile_function" ]
https://github.com/YosysHQ/nextpnr/blob/74c99f9195eeb47d106ca74b7abb894cfd47cc03/3rdparty/pybind11/pybind11/setup_helpers.py#L364-L425
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/pyplugin_installer/installer_data.py
python
Repositories.all
(self)
return self.mRepositories
return dict of all repositories
return dict of all repositories
[ "return", "dict", "of", "all", "repositories" ]
def all(self) -> Dict[str, Dict[str, Any]]: """ return dict of all repositories """ return self.mRepositories
[ "def", "all", "(", "self", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "return", "self", ".", "mRepositories" ]
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/pyplugin_installer/installer_data.py#L185-L187
goldeneye-source/ges-code
2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d
thirdparty/protobuf-2.3.0/python/google/protobuf/descriptor.py
python
EnumValueDescriptor.__init__
(self, name, index, number, type=None, options=None)
Arguments are as described in the attribute description above.
Arguments are as described in the attribute description above.
[ "Arguments", "are", "as", "described", "in", "the", "attribute", "description", "above", "." ]
def __init__(self, name, index, number, type=None, options=None): """Arguments are as described in the attribute description above.""" super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions') self.name = name self.index = index self.number = number self.type = type
[ "def", "__init__", "(", "self", ",", "name", ",", "index", ",", "number", ",", "type", "=", "None", ",", "options", "=", "None", ")", ":", "super", "(", "EnumValueDescriptor", ",", "self", ")", ".", "__init__", "(", "options", ",", "'EnumValueOptions'", ")", "self", ".", "name", "=", "name", "self", ".", "index", "=", "index", "self", ".", "number", "=", "number", "self", ".", "type", "=", "type" ]
https://github.com/goldeneye-source/ges-code/blob/2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d/thirdparty/protobuf-2.3.0/python/google/protobuf/descriptor.py#L473-L479
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
python
ScalarPanel._prepend_name
(self, names, name)
Predends name if not in list
Predends name if not in list
[ "Predends", "name", "if", "not", "in", "list" ]
def _prepend_name(self, names, name): """ Predends name if not in list """ if names.count(name) == 0: names.insert(name, 0)
[ "def", "_prepend_name", "(", "self", ",", "names", ",", "name", ")", ":", "if", "names", ".", "count", "(", "name", ")", "==", "0", ":", "names", ".", "insert", "(", "name", ",", "0", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L1884-L1889
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
HLTrigger/Configuration/python/customizeHLTforPatatrack.py
python
customiseEcalLocalReconstruction
(process)
return process
from RecoLocalCalo.EcalRecProducers.ecalRecHitGPU_cfi import ecalRecHitGPU as _ecalRecHitGPU process.hltEcalRecHitGPU = _ecalRecHitGPU.clone( uncalibrecHitsInLabelEB = ("hltEcalUncalibRecHitGPU","EcalUncalibRecHitsEB"), uncalibrecHitsInLabelEE = ("hltEcalUncalibRecHitGPU","EcalUncalibRecHitsEE"), ) from RecoLocalCalo.EcalRecProducers.ecalCPURecHitProducer_cfi import ecalCPURecHitProducer as _ecalCPURecHitProducer process.hltEcalRecHitSoA = _ecalCPURecHitProducer.clone( recHitsInLabelEB = ("hltEcalRecHitGPU", "EcalRecHitsEB"), recHitsInLabelEE = ("hltEcalRecHitGPU", "EcalRecHitsEE"), ) # SwitchProducer wrapping the legacy ECAL calibrated rechits producer or a converter from SoA to legacy format from RecoLocalCalo.EcalRecProducers.ecalRecHitConvertGPU2CPUFormat_cfi import ecalRecHitConvertGPU2CPUFormat as _ecalRecHitConvertGPU2CPUFormat process.hltEcalRecHit = SwitchProducerCUDA( # legacy producer cpu = process.hltEcalRecHit, # convert the ECAL calibrated rechits from SoA to legacy format cuda = _ecalRecHitConvertGPU2CPUFormat.clone( recHitsLabelGPUEB = ("hltEcalRecHitSoA", "EcalRecHitsEB"), recHitsLabelGPUEE = ("hltEcalRecHitSoA", "EcalRecHitsEE"), ) )
from RecoLocalCalo.EcalRecProducers.ecalRecHitGPU_cfi import ecalRecHitGPU as _ecalRecHitGPU process.hltEcalRecHitGPU = _ecalRecHitGPU.clone( uncalibrecHitsInLabelEB = ("hltEcalUncalibRecHitGPU","EcalUncalibRecHitsEB"), uncalibrecHitsInLabelEE = ("hltEcalUncalibRecHitGPU","EcalUncalibRecHitsEE"), )
[ "from", "RecoLocalCalo", ".", "EcalRecProducers", ".", "ecalRecHitGPU_cfi", "import", "ecalRecHitGPU", "as", "_ecalRecHitGPU", "process", ".", "hltEcalRecHitGPU", "=", "_ecalRecHitGPU", ".", "clone", "(", "uncalibrecHitsInLabelEB", "=", "(", "hltEcalUncalibRecHitGPU", "EcalUncalibRecHitsEB", ")", "uncalibrecHitsInLabelEE", "=", "(", "hltEcalUncalibRecHitGPU", "EcalUncalibRecHitsEE", ")", ")" ]
def customiseEcalLocalReconstruction(process): hasHLTEcalPreshowerSeq = any(seq in process.__dict__ for seq in ['HLTDoFullUnpackingEgammaEcalMFSequence', 'HLTDoFullUnpackingEgammaEcalSequence']) if not (hasHLTEcalPreshowerSeq or 'HLTDoFullUnpackingEgammaEcalWithoutPreshowerSequence' in process.__dict__): return process # FIXME replace the Sequences with empty ones to avoid expanding them during the (re)definition of Modules and EDAliases process.HLTDoFullUnpackingEgammaEcalWithoutPreshowerSequence = cms.Sequence() if hasHLTEcalPreshowerSeq: process.HLTDoFullUnpackingEgammaEcalMFSequence = cms.Sequence() process.HLTDoFullUnpackingEgammaEcalSequence = cms.Sequence() # Event Setup process.load("EventFilter.EcalRawToDigi.ecalElectronicsMappingGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalGainRatiosGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalPedestalsGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalPulseCovariancesGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalPulseShapesGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalSamplesCorrelationGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalTimeBiasCorrectionsGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalTimeCalibConstantsGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalMultifitParametersGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalRechitADCToGeVConstantGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalRechitChannelStatusGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalIntercalibConstantsGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalLaserAPDPNRatiosGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalLaserAPDPNRatiosRefGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalLaserAlphasGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalLinearCorrectionsGPUESProducer_cfi") process.load("RecoLocalCalo.EcalRecProducers.ecalRecHitParametersGPUESProducer_cfi") # Modules and EDAliases # ECAL unpacker running on gpu from EventFilter.EcalRawToDigi.ecalRawToDigiGPU_cfi import ecalRawToDigiGPU as _ecalRawToDigiGPU process.hltEcalDigisGPU = _ecalRawToDigiGPU.clone() # SwitchProducer wrapping the legacy ECAL unpacker or the ECAL digi converter from SoA format on gpu to legacy format on cpu if not isinstance(process.hltEcalDigis, SwitchProducerCUDA): if 'hltEcalDigisLegacy' in process.__dict__: raise Exception('unsupported configuration: "process.hltEcalDigis" is not SwitchProducerCUDA, but "process.hltEcalDigisLegacy" already exists') process.hltEcalDigisLegacy = process.hltEcalDigis.clone() process.hltEcalDigis = SwitchProducerCUDA( # legacy producer cpu = cms.EDAlias( hltEcalDigisLegacy = cms.VPSet( cms.PSet(type = cms.string("EBDigiCollection")), cms.PSet(type = cms.string("EEDigiCollection")), cms.PSet(type = cms.string("EBDetIdedmEDCollection")), cms.PSet(type = cms.string("EEDetIdedmEDCollection")), cms.PSet(type = cms.string("EBSrFlagsSorted")), cms.PSet(type = cms.string("EESrFlagsSorted")), cms.PSet(type = cms.string("EcalElectronicsIdedmEDCollection"), fromProductInstance = cms.string("EcalIntegrityBlockSizeErrors")), cms.PSet(type = cms.string("EcalElectronicsIdedmEDCollection"), fromProductInstance = cms.string("EcalIntegrityTTIdErrors")), cms.PSet(type = cms.string("EcalElectronicsIdedmEDCollection"), fromProductInstance = cms.string("EcalIntegrityZSXtalIdErrors")), cms.PSet(type = cms.string("EcalPnDiodeDigisSorted")), cms.PSet(type = cms.string("EcalPseudoStripInputDigisSorted"), fromProductInstance = cms.string("EcalPseudoStripInputs")), cms.PSet(type = cms.string("EcalTriggerPrimitiveDigisSorted"), fromProductInstance = cms.string("EcalTriggerPrimitives")), ) ) ) # convert ECAL digis from SoA format on gpu to legacy format on cpu from EventFilter.EcalRawToDigi.ecalCPUDigisProducer_cfi import ecalCPUDigisProducer as _ecalCPUDigisProducer process.hltEcalDigis.cuda = _ecalCPUDigisProducer.clone( digisInLabelEB = ("hltEcalDigisGPU", "ebDigis"), digisInLabelEE = ("hltEcalDigisGPU", "eeDigis"), produceDummyIntegrityCollections = True ) # ECAL multifit running on gpu from RecoLocalCalo.EcalRecProducers.ecalUncalibRecHitProducerGPU_cfi import ecalUncalibRecHitProducerGPU as _ecalUncalibRecHitProducerGPU process.hltEcalUncalibRecHitGPU = _ecalUncalibRecHitProducerGPU.clone( digisLabelEB = ("hltEcalDigisGPU", "ebDigis"), digisLabelEE = ("hltEcalDigisGPU", "eeDigis"), shouldRunTimingComputation = False ) # copy the ECAL uncalibrated rechits from gpu to cpu in SoA format from RecoLocalCalo.EcalRecProducers.ecalCPUUncalibRecHitProducer_cfi import ecalCPUUncalibRecHitProducer as _ecalCPUUncalibRecHitProducer process.hltEcalUncalibRecHitSoA = _ecalCPUUncalibRecHitProducer.clone( recHitsInLabelEB = ("hltEcalUncalibRecHitGPU", "EcalUncalibRecHitsEB"), recHitsInLabelEE = ("hltEcalUncalibRecHitGPU", "EcalUncalibRecHitsEE"), ) # SwitchProducer wrapping the legacy ECAL uncalibrated rechits producer or a converter from SoA to legacy format if not isinstance(process.hltEcalUncalibRecHit, SwitchProducerCUDA): process.hltEcalUncalibRecHit = SwitchProducerCUDA( # legacy producer cpu = process.hltEcalUncalibRecHit ) # convert the ECAL uncalibrated rechits from SoA to legacy format from RecoLocalCalo.EcalRecProducers.ecalUncalibRecHitConvertGPU2CPUFormat_cfi import ecalUncalibRecHitConvertGPU2CPUFormat as _ecalUncalibRecHitConvertGPU2CPUFormat process.hltEcalUncalibRecHit.cuda = _ecalUncalibRecHitConvertGPU2CPUFormat.clone( recHitsLabelGPUEB = ("hltEcalUncalibRecHitSoA", "EcalUncalibRecHitsEB"), recHitsLabelGPUEE = ("hltEcalUncalibRecHitSoA", "EcalUncalibRecHitsEE"), ) # Reconstructing the ECAL calibrated rechits on gpu works, but is extremely slow. # Disable it for the time being, until the performance has been addressed. """ from RecoLocalCalo.EcalRecProducers.ecalRecHitGPU_cfi import ecalRecHitGPU as _ecalRecHitGPU process.hltEcalRecHitGPU = _ecalRecHitGPU.clone( uncalibrecHitsInLabelEB = ("hltEcalUncalibRecHitGPU","EcalUncalibRecHitsEB"), uncalibrecHitsInLabelEE = ("hltEcalUncalibRecHitGPU","EcalUncalibRecHitsEE"), ) from RecoLocalCalo.EcalRecProducers.ecalCPURecHitProducer_cfi import ecalCPURecHitProducer as _ecalCPURecHitProducer process.hltEcalRecHitSoA = _ecalCPURecHitProducer.clone( recHitsInLabelEB = ("hltEcalRecHitGPU", "EcalRecHitsEB"), recHitsInLabelEE = ("hltEcalRecHitGPU", "EcalRecHitsEE"), ) # SwitchProducer wrapping the legacy ECAL calibrated rechits producer or a converter from SoA to legacy format from RecoLocalCalo.EcalRecProducers.ecalRecHitConvertGPU2CPUFormat_cfi import ecalRecHitConvertGPU2CPUFormat as _ecalRecHitConvertGPU2CPUFormat process.hltEcalRecHit = SwitchProducerCUDA( # legacy producer cpu = process.hltEcalRecHit, # convert the ECAL calibrated rechits from SoA to legacy format cuda = _ecalRecHitConvertGPU2CPUFormat.clone( recHitsLabelGPUEB = ("hltEcalRecHitSoA", "EcalRecHitsEB"), recHitsLabelGPUEE = ("hltEcalRecHitSoA", "EcalRecHitsEE"), ) ) """ # SwitchProducer wrapping the legacy ECAL rechits producer # the gpu unpacker does not produce the TPs used for the recovery, so the SwitchProducer alias does not provide them: # - the cpu uncalibrated rechit producer may mark them for recovery, read the TPs explicitly from the legacy unpacker # - the gpu uncalibrated rechit producer does not flag them for recovery, so the TPs are not necessary if not isinstance(process.hltEcalRecHit, SwitchProducerCUDA): process.hltEcalRecHit = SwitchProducerCUDA( cpu = process.hltEcalRecHit.clone( triggerPrimitiveDigiCollection = ('hltEcalDigisLegacy', 'EcalTriggerPrimitives') ), cuda = process.hltEcalRecHit.clone( triggerPrimitiveDigiCollection = 'unused' ) ) # Tasks and Sequences process.HLTDoFullUnpackingEgammaEcalWithoutPreshowerTask = cms.Task( process.hltEcalDigisGPU, # unpack ECAL digis on gpu process.hltEcalDigisLegacy, # legacy producer, referenced in the SwitchProducer process.hltEcalDigis, # SwitchProducer process.hltEcalUncalibRecHitGPU, # run ECAL local reconstruction and multifit on gpu process.hltEcalUncalibRecHitSoA, # needed by hltEcalPhiSymFilter - copy to host process.hltEcalUncalibRecHit, # needed by hltEcalPhiSymFilter - convert to legacy format # process.hltEcalRecHitGPU, # make ECAL calibrated rechits on gpu # process.hltEcalRecHitSoA, # copy to host process.hltEcalDetIdToBeRecovered, # legacy producer process.hltEcalRecHit) # legacy producer process.HLTDoFullUnpackingEgammaEcalWithoutPreshowerSequence = cms.Sequence( process.HLTDoFullUnpackingEgammaEcalWithoutPreshowerTask) if hasHLTEcalPreshowerSeq: process.HLTPreshowerTask = cms.Task( process.hltEcalPreshowerDigis, # unpack ECAL preshower digis on the host process.hltEcalPreshowerRecHit) # build ECAL preshower rechits on the host process.HLTPreshowerSequence = cms.Sequence(process.HLTPreshowerTask) process.HLTDoFullUnpackingEgammaEcalTask = cms.Task( process.HLTDoFullUnpackingEgammaEcalWithoutPreshowerTask, process.HLTPreshowerTask) process.HLTDoFullUnpackingEgammaEcalSequence = cms.Sequence( process.HLTDoFullUnpackingEgammaEcalTask) process.HLTDoFullUnpackingEgammaEcalMFSequence = cms.Sequence( process.HLTDoFullUnpackingEgammaEcalTask) # done return process
[ "def", "customiseEcalLocalReconstruction", "(", "process", ")", ":", "hasHLTEcalPreshowerSeq", "=", "any", "(", "seq", "in", "process", ".", "__dict__", "for", "seq", "in", "[", "'HLTDoFullUnpackingEgammaEcalMFSequence'", ",", "'HLTDoFullUnpackingEgammaEcalSequence'", "]", ")", "if", "not", "(", "hasHLTEcalPreshowerSeq", "or", "'HLTDoFullUnpackingEgammaEcalWithoutPreshowerSequence'", "in", "process", ".", "__dict__", ")", ":", "return", "process", "# FIXME replace the Sequences with empty ones to avoid expanding them during the (re)definition of Modules and EDAliases", "process", ".", "HLTDoFullUnpackingEgammaEcalWithoutPreshowerSequence", "=", "cms", ".", "Sequence", "(", ")", "if", "hasHLTEcalPreshowerSeq", ":", "process", ".", "HLTDoFullUnpackingEgammaEcalMFSequence", "=", "cms", ".", "Sequence", "(", ")", "process", ".", "HLTDoFullUnpackingEgammaEcalSequence", "=", "cms", ".", "Sequence", "(", ")", "# Event Setup", "process", ".", "load", "(", "\"EventFilter.EcalRawToDigi.ecalElectronicsMappingGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalGainRatiosGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalPedestalsGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalPulseCovariancesGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalPulseShapesGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalSamplesCorrelationGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalTimeBiasCorrectionsGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalTimeCalibConstantsGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalMultifitParametersGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalRechitADCToGeVConstantGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalRechitChannelStatusGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalIntercalibConstantsGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalLaserAPDPNRatiosGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalLaserAPDPNRatiosRefGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalLaserAlphasGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalLinearCorrectionsGPUESProducer_cfi\"", ")", "process", ".", "load", "(", "\"RecoLocalCalo.EcalRecProducers.ecalRecHitParametersGPUESProducer_cfi\"", ")", "# Modules and EDAliases", "# ECAL unpacker running on gpu", "from", "EventFilter", ".", "EcalRawToDigi", ".", "ecalRawToDigiGPU_cfi", "import", "ecalRawToDigiGPU", "as", "_ecalRawToDigiGPU", "process", ".", "hltEcalDigisGPU", "=", "_ecalRawToDigiGPU", ".", "clone", "(", ")", "# SwitchProducer wrapping the legacy ECAL unpacker or the ECAL digi converter from SoA format on gpu to legacy format on cpu", "if", "not", "isinstance", "(", "process", ".", "hltEcalDigis", ",", "SwitchProducerCUDA", ")", ":", "if", "'hltEcalDigisLegacy'", "in", "process", ".", "__dict__", ":", "raise", "Exception", "(", "'unsupported configuration: \"process.hltEcalDigis\" is not SwitchProducerCUDA, but \"process.hltEcalDigisLegacy\" already exists'", ")", "process", ".", "hltEcalDigisLegacy", "=", "process", ".", "hltEcalDigis", ".", "clone", "(", ")", "process", ".", "hltEcalDigis", "=", "SwitchProducerCUDA", "(", "# legacy producer", "cpu", "=", "cms", ".", "EDAlias", "(", "hltEcalDigisLegacy", "=", "cms", ".", "VPSet", "(", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EBDigiCollection\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EEDigiCollection\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EBDetIdedmEDCollection\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EEDetIdedmEDCollection\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EBSrFlagsSorted\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EESrFlagsSorted\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EcalElectronicsIdedmEDCollection\"", ")", ",", "fromProductInstance", "=", "cms", ".", "string", "(", "\"EcalIntegrityBlockSizeErrors\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EcalElectronicsIdedmEDCollection\"", ")", ",", "fromProductInstance", "=", "cms", ".", "string", "(", "\"EcalIntegrityTTIdErrors\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EcalElectronicsIdedmEDCollection\"", ")", ",", "fromProductInstance", "=", "cms", ".", "string", "(", "\"EcalIntegrityZSXtalIdErrors\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EcalPnDiodeDigisSorted\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EcalPseudoStripInputDigisSorted\"", ")", ",", "fromProductInstance", "=", "cms", ".", "string", "(", "\"EcalPseudoStripInputs\"", ")", ")", ",", "cms", ".", "PSet", "(", "type", "=", "cms", ".", "string", "(", "\"EcalTriggerPrimitiveDigisSorted\"", ")", ",", "fromProductInstance", "=", "cms", ".", "string", "(", "\"EcalTriggerPrimitives\"", ")", ")", ",", ")", ")", ")", "# convert ECAL digis from SoA format on gpu to legacy format on cpu", "from", "EventFilter", ".", "EcalRawToDigi", ".", "ecalCPUDigisProducer_cfi", "import", "ecalCPUDigisProducer", "as", "_ecalCPUDigisProducer", "process", ".", "hltEcalDigis", ".", "cuda", "=", "_ecalCPUDigisProducer", ".", "clone", "(", "digisInLabelEB", "=", "(", "\"hltEcalDigisGPU\"", ",", "\"ebDigis\"", ")", ",", "digisInLabelEE", "=", "(", "\"hltEcalDigisGPU\"", ",", "\"eeDigis\"", ")", ",", "produceDummyIntegrityCollections", "=", "True", ")", "# ECAL multifit running on gpu", "from", "RecoLocalCalo", ".", "EcalRecProducers", ".", "ecalUncalibRecHitProducerGPU_cfi", "import", "ecalUncalibRecHitProducerGPU", "as", "_ecalUncalibRecHitProducerGPU", "process", ".", "hltEcalUncalibRecHitGPU", "=", "_ecalUncalibRecHitProducerGPU", ".", "clone", "(", "digisLabelEB", "=", "(", "\"hltEcalDigisGPU\"", ",", "\"ebDigis\"", ")", ",", "digisLabelEE", "=", "(", "\"hltEcalDigisGPU\"", ",", "\"eeDigis\"", ")", ",", "shouldRunTimingComputation", "=", "False", ")", "# copy the ECAL uncalibrated rechits from gpu to cpu in SoA format", "from", "RecoLocalCalo", ".", "EcalRecProducers", ".", "ecalCPUUncalibRecHitProducer_cfi", "import", "ecalCPUUncalibRecHitProducer", "as", "_ecalCPUUncalibRecHitProducer", "process", ".", "hltEcalUncalibRecHitSoA", "=", "_ecalCPUUncalibRecHitProducer", ".", "clone", "(", "recHitsInLabelEB", "=", "(", "\"hltEcalUncalibRecHitGPU\"", ",", "\"EcalUncalibRecHitsEB\"", ")", ",", "recHitsInLabelEE", "=", "(", "\"hltEcalUncalibRecHitGPU\"", ",", "\"EcalUncalibRecHitsEE\"", ")", ",", ")", "# SwitchProducer wrapping the legacy ECAL uncalibrated rechits producer or a converter from SoA to legacy format", "if", "not", "isinstance", "(", "process", ".", "hltEcalUncalibRecHit", ",", "SwitchProducerCUDA", ")", ":", "process", ".", "hltEcalUncalibRecHit", "=", "SwitchProducerCUDA", "(", "# legacy producer", "cpu", "=", "process", ".", "hltEcalUncalibRecHit", ")", "# convert the ECAL uncalibrated rechits from SoA to legacy format", "from", "RecoLocalCalo", ".", "EcalRecProducers", ".", "ecalUncalibRecHitConvertGPU2CPUFormat_cfi", "import", "ecalUncalibRecHitConvertGPU2CPUFormat", "as", "_ecalUncalibRecHitConvertGPU2CPUFormat", "process", ".", "hltEcalUncalibRecHit", ".", "cuda", "=", "_ecalUncalibRecHitConvertGPU2CPUFormat", ".", "clone", "(", "recHitsLabelGPUEB", "=", "(", "\"hltEcalUncalibRecHitSoA\"", ",", "\"EcalUncalibRecHitsEB\"", ")", ",", "recHitsLabelGPUEE", "=", "(", "\"hltEcalUncalibRecHitSoA\"", ",", "\"EcalUncalibRecHitsEE\"", ")", ",", ")", "# Reconstructing the ECAL calibrated rechits on gpu works, but is extremely slow.", "# Disable it for the time being, until the performance has been addressed.", "# SwitchProducer wrapping the legacy ECAL rechits producer", "# the gpu unpacker does not produce the TPs used for the recovery, so the SwitchProducer alias does not provide them:", "# - the cpu uncalibrated rechit producer may mark them for recovery, read the TPs explicitly from the legacy unpacker", "# - the gpu uncalibrated rechit producer does not flag them for recovery, so the TPs are not necessary", "if", "not", "isinstance", "(", "process", ".", "hltEcalRecHit", ",", "SwitchProducerCUDA", ")", ":", "process", ".", "hltEcalRecHit", "=", "SwitchProducerCUDA", "(", "cpu", "=", "process", ".", "hltEcalRecHit", ".", "clone", "(", "triggerPrimitiveDigiCollection", "=", "(", "'hltEcalDigisLegacy'", ",", "'EcalTriggerPrimitives'", ")", ")", ",", "cuda", "=", "process", ".", "hltEcalRecHit", ".", "clone", "(", "triggerPrimitiveDigiCollection", "=", "'unused'", ")", ")", "# Tasks and Sequences", "process", ".", "HLTDoFullUnpackingEgammaEcalWithoutPreshowerTask", "=", "cms", ".", "Task", "(", "process", ".", "hltEcalDigisGPU", ",", "# unpack ECAL digis on gpu", "process", ".", "hltEcalDigisLegacy", ",", "# legacy producer, referenced in the SwitchProducer", "process", ".", "hltEcalDigis", ",", "# SwitchProducer", "process", ".", "hltEcalUncalibRecHitGPU", ",", "# run ECAL local reconstruction and multifit on gpu", "process", ".", "hltEcalUncalibRecHitSoA", ",", "# needed by hltEcalPhiSymFilter - copy to host", "process", ".", "hltEcalUncalibRecHit", ",", "# needed by hltEcalPhiSymFilter - convert to legacy format", "# process.hltEcalRecHitGPU, # make ECAL calibrated rechits on gpu", "# process.hltEcalRecHitSoA, # copy to host", "process", ".", "hltEcalDetIdToBeRecovered", ",", "# legacy producer", "process", ".", "hltEcalRecHit", ")", "# legacy producer", "process", ".", "HLTDoFullUnpackingEgammaEcalWithoutPreshowerSequence", "=", "cms", ".", "Sequence", "(", "process", ".", "HLTDoFullUnpackingEgammaEcalWithoutPreshowerTask", ")", "if", "hasHLTEcalPreshowerSeq", ":", "process", ".", "HLTPreshowerTask", "=", "cms", ".", "Task", "(", "process", ".", "hltEcalPreshowerDigis", ",", "# unpack ECAL preshower digis on the host", "process", ".", "hltEcalPreshowerRecHit", ")", "# build ECAL preshower rechits on the host", "process", ".", "HLTPreshowerSequence", "=", "cms", ".", "Sequence", "(", "process", ".", "HLTPreshowerTask", ")", "process", ".", "HLTDoFullUnpackingEgammaEcalTask", "=", "cms", ".", "Task", "(", "process", ".", "HLTDoFullUnpackingEgammaEcalWithoutPreshowerTask", ",", "process", ".", "HLTPreshowerTask", ")", "process", ".", "HLTDoFullUnpackingEgammaEcalSequence", "=", "cms", ".", "Sequence", "(", "process", ".", "HLTDoFullUnpackingEgammaEcalTask", ")", "process", ".", "HLTDoFullUnpackingEgammaEcalMFSequence", "=", "cms", ".", "Sequence", "(", "process", ".", "HLTDoFullUnpackingEgammaEcalTask", ")", "# done", "return", "process" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/HLTrigger/Configuration/python/customizeHLTforPatatrack.py#L402-L585
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/ogl/_composit.py
python
DivisionShape.GetLeftSideStyle
(self)
return self._leftSideStyle
Return the style used for the left side of the division.
Return the style used for the left side of the division.
[ "Return", "the", "style", "used", "for", "the", "left", "side", "of", "the", "division", "." ]
def GetLeftSideStyle(self): """Return the style used for the left side of the division.""" return self._leftSideStyle
[ "def", "GetLeftSideStyle", "(", "self", ")", ":", "return", "self", ".", "_leftSideStyle" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_composit.py#L991-L993
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
AnyButton.SetBitmapCurrent
(*args, **kwargs)
return _controls_.AnyButton_SetBitmapCurrent(*args, **kwargs)
SetBitmapCurrent(self, Bitmap bitmap)
SetBitmapCurrent(self, Bitmap bitmap)
[ "SetBitmapCurrent", "(", "self", "Bitmap", "bitmap", ")" ]
def SetBitmapCurrent(*args, **kwargs): """SetBitmapCurrent(self, Bitmap bitmap)""" return _controls_.AnyButton_SetBitmapCurrent(*args, **kwargs)
[ "def", "SetBitmapCurrent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "AnyButton_SetBitmapCurrent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L92-L94
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/ops.py
python
_arith_method_SERIES
(cls, op, special)
return wrapper
Wrapper function for Series arithmetic operations, to avoid code duplication.
Wrapper function for Series arithmetic operations, to avoid code duplication.
[ "Wrapper", "function", "for", "Series", "arithmetic", "operations", "to", "avoid", "code", "duplication", "." ]
def _arith_method_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ str_rep = _get_opstr(op, cls) op_name = _get_op_name(op, special) eval_kwargs = _gen_eval_kwargs(op_name) fill_zeros = _gen_fill_zeros(op_name) construct_result = (_construct_divmod_result if op in [divmod, rdivmod] else _construct_result) def na_op(x, y): import pandas.core.computation.expressions as expressions try: result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs) except TypeError: result = masked_arith_op(x, y, op) result = missing.fill_zeros(result, x, y, op_name, fill_zeros) return result def safe_na_op(lvalues, rvalues): """ return the result of evaluating na_op on the passed in values try coercion to object type if the native types are not compatible Parameters ---------- lvalues : array-like rvalues : array-like Raises ------ TypeError: invalid operation """ try: with np.errstate(all='ignore'): return na_op(lvalues, rvalues) except Exception: if is_object_dtype(lvalues): return libalgos.arrmap_object(lvalues, lambda x: op(x, rvalues)) raise def wrapper(left, right): if isinstance(right, ABCDataFrame): return NotImplemented left, right = _align_method_SERIES(left, right) res_name = get_op_result_name(left, right) right = maybe_upcast_for_op(right) if is_categorical_dtype(left): raise TypeError("{typ} cannot perform the operation " "{op}".format(typ=type(left).__name__, op=str_rep)) elif is_datetime64_dtype(left) or is_datetime64tz_dtype(left): # Give dispatch_to_index_op a chance for tests like # test_dt64_series_add_intlike, which the index dispatching handles # specifically. result = dispatch_to_index_op(op, left, right, pd.DatetimeIndex) return construct_result(left, result, index=left.index, name=res_name, dtype=result.dtype) elif (is_extension_array_dtype(left) or (is_extension_array_dtype(right) and not is_scalar(right))): # GH#22378 disallow scalar to exclude e.g. "category", "Int64" return dispatch_to_extension_op(op, left, right) elif is_timedelta64_dtype(left): result = dispatch_to_index_op(op, left, right, pd.TimedeltaIndex) return construct_result(left, result, index=left.index, name=res_name) elif is_timedelta64_dtype(right): # We should only get here with non-scalar or timedelta64('NaT') # values for right # Note: we cannot use dispatch_to_index_op because # that may incorrectly raise TypeError when we # should get NullFrequencyError result = op(pd.Index(left), right) return construct_result(left, result, index=left.index, name=res_name, dtype=result.dtype) lvalues = left.values rvalues = right if isinstance(rvalues, ABCSeries): rvalues = rvalues.values result = safe_na_op(lvalues, rvalues) return construct_result(left, result, index=left.index, name=res_name, dtype=None) wrapper.__name__ = op_name return wrapper
[ "def", "_arith_method_SERIES", "(", "cls", ",", "op", ",", "special", ")", ":", "str_rep", "=", "_get_opstr", "(", "op", ",", "cls", ")", "op_name", "=", "_get_op_name", "(", "op", ",", "special", ")", "eval_kwargs", "=", "_gen_eval_kwargs", "(", "op_name", ")", "fill_zeros", "=", "_gen_fill_zeros", "(", "op_name", ")", "construct_result", "=", "(", "_construct_divmod_result", "if", "op", "in", "[", "divmod", ",", "rdivmod", "]", "else", "_construct_result", ")", "def", "na_op", "(", "x", ",", "y", ")", ":", "import", "pandas", ".", "core", ".", "computation", ".", "expressions", "as", "expressions", "try", ":", "result", "=", "expressions", ".", "evaluate", "(", "op", ",", "str_rep", ",", "x", ",", "y", ",", "*", "*", "eval_kwargs", ")", "except", "TypeError", ":", "result", "=", "masked_arith_op", "(", "x", ",", "y", ",", "op", ")", "result", "=", "missing", ".", "fill_zeros", "(", "result", ",", "x", ",", "y", ",", "op_name", ",", "fill_zeros", ")", "return", "result", "def", "safe_na_op", "(", "lvalues", ",", "rvalues", ")", ":", "\"\"\"\n return the result of evaluating na_op on the passed in values\n\n try coercion to object type if the native types are not compatible\n\n Parameters\n ----------\n lvalues : array-like\n rvalues : array-like\n\n Raises\n ------\n TypeError: invalid operation\n \"\"\"", "try", ":", "with", "np", ".", "errstate", "(", "all", "=", "'ignore'", ")", ":", "return", "na_op", "(", "lvalues", ",", "rvalues", ")", "except", "Exception", ":", "if", "is_object_dtype", "(", "lvalues", ")", ":", "return", "libalgos", ".", "arrmap_object", "(", "lvalues", ",", "lambda", "x", ":", "op", "(", "x", ",", "rvalues", ")", ")", "raise", "def", "wrapper", "(", "left", ",", "right", ")", ":", "if", "isinstance", "(", "right", ",", "ABCDataFrame", ")", ":", "return", "NotImplemented", "left", ",", "right", "=", "_align_method_SERIES", "(", "left", ",", "right", ")", "res_name", "=", "get_op_result_name", "(", "left", ",", "right", ")", "right", "=", "maybe_upcast_for_op", "(", "right", ")", "if", "is_categorical_dtype", "(", "left", ")", ":", "raise", "TypeError", "(", "\"{typ} cannot perform the operation \"", "\"{op}\"", ".", "format", "(", "typ", "=", "type", "(", "left", ")", ".", "__name__", ",", "op", "=", "str_rep", ")", ")", "elif", "is_datetime64_dtype", "(", "left", ")", "or", "is_datetime64tz_dtype", "(", "left", ")", ":", "# Give dispatch_to_index_op a chance for tests like", "# test_dt64_series_add_intlike, which the index dispatching handles", "# specifically.", "result", "=", "dispatch_to_index_op", "(", "op", ",", "left", ",", "right", ",", "pd", ".", "DatetimeIndex", ")", "return", "construct_result", "(", "left", ",", "result", ",", "index", "=", "left", ".", "index", ",", "name", "=", "res_name", ",", "dtype", "=", "result", ".", "dtype", ")", "elif", "(", "is_extension_array_dtype", "(", "left", ")", "or", "(", "is_extension_array_dtype", "(", "right", ")", "and", "not", "is_scalar", "(", "right", ")", ")", ")", ":", "# GH#22378 disallow scalar to exclude e.g. \"category\", \"Int64\"", "return", "dispatch_to_extension_op", "(", "op", ",", "left", ",", "right", ")", "elif", "is_timedelta64_dtype", "(", "left", ")", ":", "result", "=", "dispatch_to_index_op", "(", "op", ",", "left", ",", "right", ",", "pd", ".", "TimedeltaIndex", ")", "return", "construct_result", "(", "left", ",", "result", ",", "index", "=", "left", ".", "index", ",", "name", "=", "res_name", ")", "elif", "is_timedelta64_dtype", "(", "right", ")", ":", "# We should only get here with non-scalar or timedelta64('NaT')", "# values for right", "# Note: we cannot use dispatch_to_index_op because", "# that may incorrectly raise TypeError when we", "# should get NullFrequencyError", "result", "=", "op", "(", "pd", ".", "Index", "(", "left", ")", ",", "right", ")", "return", "construct_result", "(", "left", ",", "result", ",", "index", "=", "left", ".", "index", ",", "name", "=", "res_name", ",", "dtype", "=", "result", ".", "dtype", ")", "lvalues", "=", "left", ".", "values", "rvalues", "=", "right", "if", "isinstance", "(", "rvalues", ",", "ABCSeries", ")", ":", "rvalues", "=", "rvalues", ".", "values", "result", "=", "safe_na_op", "(", "lvalues", ",", "rvalues", ")", "return", "construct_result", "(", "left", ",", "result", ",", "index", "=", "left", ".", "index", ",", "name", "=", "res_name", ",", "dtype", "=", "None", ")", "wrapper", ".", "__name__", "=", "op_name", "return", "wrapper" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/ops.py#L1490-L1588
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py
python
IMAP4.enable
(self, capability)
return typ, data
Send an RFC5161 enable string to the server. (typ, [data]) = <intance>.enable(capability)
Send an RFC5161 enable string to the server.
[ "Send", "an", "RFC5161", "enable", "string", "to", "the", "server", "." ]
def enable(self, capability): """Send an RFC5161 enable string to the server. (typ, [data]) = <intance>.enable(capability) """ if 'ENABLE' not in self.capabilities: raise IMAP4.error("Server does not support ENABLE") typ, data = self._simple_command('ENABLE', capability) if typ == 'OK' and 'UTF8=ACCEPT' in capability.upper(): self._mode_utf8() return typ, data
[ "def", "enable", "(", "self", ",", "capability", ")", ":", "if", "'ENABLE'", "not", "in", "self", ".", "capabilities", ":", "raise", "IMAP4", ".", "error", "(", "\"Server does not support ENABLE\"", ")", "typ", ",", "data", "=", "self", ".", "_simple_command", "(", "'ENABLE'", ",", "capability", ")", "if", "typ", "==", "'OK'", "and", "'UTF8=ACCEPT'", "in", "capability", ".", "upper", "(", ")", ":", "self", ".", "_mode_utf8", "(", ")", "return", "typ", ",", "data" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py#L497-L507
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Validation/RecoTrack/python/plotting/plotting.py
python
PlotGroup.onlyForPileup
(self)
return self._onlyForPileup
Return True if the PlotGroup is intended only for pileup samples
Return True if the PlotGroup is intended only for pileup samples
[ "Return", "True", "if", "the", "PlotGroup", "is", "intended", "only", "for", "pileup", "samples" ]
def onlyForPileup(self): """Return True if the PlotGroup is intended only for pileup samples""" return self._onlyForPileup
[ "def", "onlyForPileup", "(", "self", ")", ":", "return", "self", ".", "_onlyForPileup" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/plotting.py#L2323-L2325
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/weights_broadcast_ops.py
python
assert_broadcastable
(weights, values)
Asserts `weights` can be broadcast to `values`. In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. We let weights be either scalar, or the same rank as the target values, with each dimension either 1, or the same as the corresponding values dimension. Args: weights: `Tensor` of weights. values: `Tensor` of values to which weights are applied. Returns: `Operation` raising `InvalidArgumentError` if `weights` has incorrect shape. `no_op` if static checks determine `weights` has correct shape. Raises: ValueError: If static checks determine `weights` has incorrect shape.
Asserts `weights` can be broadcast to `values`.
[ "Asserts", "weights", "can", "be", "broadcast", "to", "values", "." ]
def assert_broadcastable(weights, values): """Asserts `weights` can be broadcast to `values`. In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. We let weights be either scalar, or the same rank as the target values, with each dimension either 1, or the same as the corresponding values dimension. Args: weights: `Tensor` of weights. values: `Tensor` of values to which weights are applied. Returns: `Operation` raising `InvalidArgumentError` if `weights` has incorrect shape. `no_op` if static checks determine `weights` has correct shape. Raises: ValueError: If static checks determine `weights` has incorrect shape. """ with ops.name_scope(None, "assert_broadcastable", (weights, values)) as scope: with ops.name_scope(None, "weights", (weights,)) as weights_scope: weights = ops.convert_to_tensor(weights, name=weights_scope) weights_shape = array_ops.shape(weights, name="shape") weights_rank = array_ops.rank(weights, name="rank") weights_rank_static = tensor_util.constant_value(weights_rank) with ops.name_scope(None, "values", (values,)) as values_scope: values = ops.convert_to_tensor(values, name=values_scope) values_shape = array_ops.shape(values, name="shape") values_rank = array_ops.rank(values, name="rank") values_rank_static = tensor_util.constant_value(values_rank) # Try static checks. if weights_rank_static is not None and values_rank_static is not None: if weights_rank_static == 0: return control_flow_ops.no_op(name="static_scalar_check_success") if weights_rank_static != values_rank_static: raise ValueError( f"{_ASSERT_BROADCASTABLE_ERROR_PREFIX} values.rank=" f"{values_rank_static}. weights.rank={weights_rank_static}. " f"values.shape={values.shape}. weights.shape={weights.shape}. " f"Received weights={weights}, values={values}") weights_shape_static = tensor_util.constant_value(weights_shape) values_shape_static = tensor_util.constant_value(values_shape) if weights_shape_static is not None and values_shape_static is not None: # Sanity check, this should always be true since we checked rank above. ndims = len(values_shape_static) assert ndims == len(weights_shape_static) for i in range(ndims): if weights_shape_static[i] not in (1, values_shape_static[i]): raise ValueError( f"{_ASSERT_BROADCASTABLE_ERROR_PREFIX} Mismatch at dim {i}. " f"values.shape={values_shape_static}, weights.shape=" f"{weights_shape_static}. Received weights={weights}, " f"values={values}") return control_flow_ops.no_op(name="static_dims_check_success") # Dynamic checks. is_scalar = math_ops.equal(0, weights_rank, name="is_scalar") data = ( _ASSERT_BROADCASTABLE_ERROR_PREFIX, "weights.shape=", weights.name, weights_shape, "values.shape=", values.name, values_shape, "is_scalar=", is_scalar, ) is_valid_shape = control_flow_ops.cond( is_scalar, lambda: is_scalar, lambda: _has_valid_nonscalar_shape( # pylint: disable=g-long-lambda weights_rank, weights_shape, values_rank, values_shape), name="is_valid_shape") return control_flow_ops.Assert(is_valid_shape, data, name=scope)
[ "def", "assert_broadcastable", "(", "weights", ",", "values", ")", ":", "with", "ops", ".", "name_scope", "(", "None", ",", "\"assert_broadcastable\"", ",", "(", "weights", ",", "values", ")", ")", "as", "scope", ":", "with", "ops", ".", "name_scope", "(", "None", ",", "\"weights\"", ",", "(", "weights", ",", ")", ")", "as", "weights_scope", ":", "weights", "=", "ops", ".", "convert_to_tensor", "(", "weights", ",", "name", "=", "weights_scope", ")", "weights_shape", "=", "array_ops", ".", "shape", "(", "weights", ",", "name", "=", "\"shape\"", ")", "weights_rank", "=", "array_ops", ".", "rank", "(", "weights", ",", "name", "=", "\"rank\"", ")", "weights_rank_static", "=", "tensor_util", ".", "constant_value", "(", "weights_rank", ")", "with", "ops", ".", "name_scope", "(", "None", ",", "\"values\"", ",", "(", "values", ",", ")", ")", "as", "values_scope", ":", "values", "=", "ops", ".", "convert_to_tensor", "(", "values", ",", "name", "=", "values_scope", ")", "values_shape", "=", "array_ops", ".", "shape", "(", "values", ",", "name", "=", "\"shape\"", ")", "values_rank", "=", "array_ops", ".", "rank", "(", "values", ",", "name", "=", "\"rank\"", ")", "values_rank_static", "=", "tensor_util", ".", "constant_value", "(", "values_rank", ")", "# Try static checks.", "if", "weights_rank_static", "is", "not", "None", "and", "values_rank_static", "is", "not", "None", ":", "if", "weights_rank_static", "==", "0", ":", "return", "control_flow_ops", ".", "no_op", "(", "name", "=", "\"static_scalar_check_success\"", ")", "if", "weights_rank_static", "!=", "values_rank_static", ":", "raise", "ValueError", "(", "f\"{_ASSERT_BROADCASTABLE_ERROR_PREFIX} values.rank=\"", "f\"{values_rank_static}. weights.rank={weights_rank_static}. \"", "f\"values.shape={values.shape}. weights.shape={weights.shape}. \"", "f\"Received weights={weights}, values={values}\"", ")", "weights_shape_static", "=", "tensor_util", ".", "constant_value", "(", "weights_shape", ")", "values_shape_static", "=", "tensor_util", ".", "constant_value", "(", "values_shape", ")", "if", "weights_shape_static", "is", "not", "None", "and", "values_shape_static", "is", "not", "None", ":", "# Sanity check, this should always be true since we checked rank above.", "ndims", "=", "len", "(", "values_shape_static", ")", "assert", "ndims", "==", "len", "(", "weights_shape_static", ")", "for", "i", "in", "range", "(", "ndims", ")", ":", "if", "weights_shape_static", "[", "i", "]", "not", "in", "(", "1", ",", "values_shape_static", "[", "i", "]", ")", ":", "raise", "ValueError", "(", "f\"{_ASSERT_BROADCASTABLE_ERROR_PREFIX} Mismatch at dim {i}. \"", "f\"values.shape={values_shape_static}, weights.shape=\"", "f\"{weights_shape_static}. Received weights={weights}, \"", "f\"values={values}\"", ")", "return", "control_flow_ops", ".", "no_op", "(", "name", "=", "\"static_dims_check_success\"", ")", "# Dynamic checks.", "is_scalar", "=", "math_ops", ".", "equal", "(", "0", ",", "weights_rank", ",", "name", "=", "\"is_scalar\"", ")", "data", "=", "(", "_ASSERT_BROADCASTABLE_ERROR_PREFIX", ",", "\"weights.shape=\"", ",", "weights", ".", "name", ",", "weights_shape", ",", "\"values.shape=\"", ",", "values", ".", "name", ",", "values_shape", ",", "\"is_scalar=\"", ",", "is_scalar", ",", ")", "is_valid_shape", "=", "control_flow_ops", ".", "cond", "(", "is_scalar", ",", "lambda", ":", "is_scalar", ",", "lambda", ":", "_has_valid_nonscalar_shape", "(", "# pylint: disable=g-long-lambda", "weights_rank", ",", "weights_shape", ",", "values_rank", ",", "values_shape", ")", ",", "name", "=", "\"is_valid_shape\"", ")", "return", "control_flow_ops", ".", "Assert", "(", "is_valid_shape", ",", "data", ",", "name", "=", "scope", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/weights_broadcast_ops.py#L60-L131
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBAddress.GetLineEntry
(self)
return _lldb.SBAddress_GetLineEntry(self)
GetLineEntry(SBAddress self) -> SBLineEntry
GetLineEntry(SBAddress self) -> SBLineEntry
[ "GetLineEntry", "(", "SBAddress", "self", ")", "-", ">", "SBLineEntry" ]
def GetLineEntry(self): """GetLineEntry(SBAddress self) -> SBLineEntry""" return _lldb.SBAddress_GetLineEntry(self)
[ "def", "GetLineEntry", "(", "self", ")", ":", "return", "_lldb", ".", "SBAddress_GetLineEntry", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L991-L993
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenuItem.SetLabel
(self, text)
Sets the label text for this item from the text (excluding the accelerator). :param string `text`: the new item label (excluding the accelerator).
Sets the label text for this item from the text (excluding the accelerator).
[ "Sets", "the", "label", "text", "for", "this", "item", "from", "the", "text", "(", "excluding", "the", "accelerator", ")", "." ]
def SetLabel(self, text): """ Sets the label text for this item from the text (excluding the accelerator). :param string `text`: the new item label (excluding the accelerator). """ if text: indx = text.find("\t") if indx >= 0: self._accelStr = text[indx+1:] label = text[0:indx] else: self._accelStr = "" label = text self._mnemonicIdx, self._label = GetAccelIndex(label) else: self._mnemonicIdx = wx.NOT_FOUND self._label = "" if self._parentMenu: self._parentMenu.UpdateItem(self)
[ "def", "SetLabel", "(", "self", ",", "text", ")", ":", "if", "text", ":", "indx", "=", "text", ".", "find", "(", "\"\\t\"", ")", "if", "indx", ">=", "0", ":", "self", ".", "_accelStr", "=", "text", "[", "indx", "+", "1", ":", "]", "label", "=", "text", "[", "0", ":", "indx", "]", "else", ":", "self", ".", "_accelStr", "=", "\"\"", "label", "=", "text", "self", ".", "_mnemonicIdx", ",", "self", ".", "_label", "=", "GetAccelIndex", "(", "label", ")", "else", ":", "self", ".", "_mnemonicIdx", "=", "wx", ".", "NOT_FOUND", "self", ".", "_label", "=", "\"\"", "if", "self", ".", "_parentMenu", ":", "self", ".", "_parentMenu", ".", "UpdateItem", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L5153-L5178
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Sizer.FitInside
(*args, **kwargs)
return _core_.Sizer_FitInside(*args, **kwargs)
FitInside(self, Window window) Tell the sizer to resize the *virtual size* of the *window* to match the sizer's minimal size. This will not alter the on screen size of the window, but may cause the addition/removal/alteration of scrollbars required to view the virtual area in windows which manage it. :see: `wx.ScrolledWindow.SetScrollbars`
FitInside(self, Window window)
[ "FitInside", "(", "self", "Window", "window", ")" ]
def FitInside(*args, **kwargs): """ FitInside(self, Window window) Tell the sizer to resize the *virtual size* of the *window* to match the sizer's minimal size. This will not alter the on screen size of the window, but may cause the addition/removal/alteration of scrollbars required to view the virtual area in windows which manage it. :see: `wx.ScrolledWindow.SetScrollbars` """ return _core_.Sizer_FitInside(*args, **kwargs)
[ "def", "FitInside", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Sizer_FitInside", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L14889-L14901
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/asyncio/events.py
python
set_event_loop
(loop)
Equivalent to calling get_event_loop_policy().set_event_loop(loop).
Equivalent to calling get_event_loop_policy().set_event_loop(loop).
[ "Equivalent", "to", "calling", "get_event_loop_policy", "()", ".", "set_event_loop", "(", "loop", ")", "." ]
def set_event_loop(loop): """Equivalent to calling get_event_loop_policy().set_event_loop(loop).""" get_event_loop_policy().set_event_loop(loop)
[ "def", "set_event_loop", "(", "loop", ")", ":", "get_event_loop_policy", "(", ")", ".", "set_event_loop", "(", "loop", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/events.py#L754-L756
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/jpsro.py
python
_rmwcce
(meta_game, per_player_repeats, ignore_repeats=False)
return dist, dict()
Random maximum welfare CCE.
Random maximum welfare CCE.
[ "Random", "maximum", "welfare", "CCE", "." ]
def _rmwcce(meta_game, per_player_repeats, ignore_repeats=False): """Random maximum welfare CCE.""" del ignore_repeats num_players = len(per_player_repeats) cost = np.ravel(np.sum(meta_game, axis=0)) cost += np.ravel(np.random.normal(size=meta_game.shape[1:])) * 1e-6 a_mat, _ = _cce_constraints( meta_game, [0.0] * num_players, remove_null=True, zero_tolerance=1e-8) e_vec = np.zeros([a_mat.shape[0]]) x, _ = _linear(meta_game, a_mat, e_vec, cost=cost) dist = np.reshape(x, meta_game.shape[1:]) return dist, dict()
[ "def", "_rmwcce", "(", "meta_game", ",", "per_player_repeats", ",", "ignore_repeats", "=", "False", ")", ":", "del", "ignore_repeats", "num_players", "=", "len", "(", "per_player_repeats", ")", "cost", "=", "np", ".", "ravel", "(", "np", ".", "sum", "(", "meta_game", ",", "axis", "=", "0", ")", ")", "cost", "+=", "np", ".", "ravel", "(", "np", ".", "random", ".", "normal", "(", "size", "=", "meta_game", ".", "shape", "[", "1", ":", "]", ")", ")", "*", "1e-6", "a_mat", ",", "_", "=", "_cce_constraints", "(", "meta_game", ",", "[", "0.0", "]", "*", "num_players", ",", "remove_null", "=", "True", ",", "zero_tolerance", "=", "1e-8", ")", "e_vec", "=", "np", ".", "zeros", "(", "[", "a_mat", ".", "shape", "[", "0", "]", "]", ")", "x", ",", "_", "=", "_linear", "(", "meta_game", ",", "a_mat", ",", "e_vec", ",", "cost", "=", "cost", ")", "dist", "=", "np", ".", "reshape", "(", "x", ",", "meta_game", ".", "shape", "[", "1", ":", "]", ")", "return", "dist", ",", "dict", "(", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/jpsro.py#L955-L967
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
LogTextCtrl.__init__
(self, *args, **kwargs)
__init__(self, wxTextCtrl pTextCtrl) -> LogTextCtrl
__init__(self, wxTextCtrl pTextCtrl) -> LogTextCtrl
[ "__init__", "(", "self", "wxTextCtrl", "pTextCtrl", ")", "-", ">", "LogTextCtrl" ]
def __init__(self, *args, **kwargs): """__init__(self, wxTextCtrl pTextCtrl) -> LogTextCtrl""" _misc_.LogTextCtrl_swiginit(self,_misc_.new_LogTextCtrl(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_misc_", ".", "LogTextCtrl_swiginit", "(", "self", ",", "_misc_", ".", "new_LogTextCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L1749-L1751
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
ipc/ipdl/ipdl/parser.py
python
p_ActorType
(p)
ActorType : ID ':' State
ActorType : ID ':' State
[ "ActorType", ":", "ID", ":", "State" ]
def p_ActorType(p): """ActorType : ID ':' State""" loc = locFromTok(p, 1) p[0] = TypeSpec(loc, QualifiedId(loc, p[1]), state=p[3])
[ "def", "p_ActorType", "(", "p", ")", ":", "loc", "=", "locFromTok", "(", "p", ",", "1", ")", "p", "[", "0", "]", "=", "TypeSpec", "(", "loc", ",", "QualifiedId", "(", "loc", ",", "p", "[", "1", "]", ")", ",", "state", "=", "p", "[", "3", "]", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/ipc/ipdl/ipdl/parser.py#L676-L679
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/cpu/dropout.py
python
_dropout_cpu
()
return
Dropout cpu register
Dropout cpu register
[ "Dropout", "cpu", "register" ]
def _dropout_cpu(): """Dropout cpu register""" return
[ "def", "_dropout_cpu", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/cpu/dropout.py#L28-L30
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/html/parser.py
python
HTMLParser.__init__
(self, *, convert_charrefs=True)
Initialize and reset this instance. If convert_charrefs is True (the default), all character references are automatically converted to the corresponding Unicode characters.
Initialize and reset this instance.
[ "Initialize", "and", "reset", "this", "instance", "." ]
def __init__(self, *, convert_charrefs=True): """Initialize and reset this instance. If convert_charrefs is True (the default), all character references are automatically converted to the corresponding Unicode characters. """ self.convert_charrefs = convert_charrefs self.reset()
[ "def", "__init__", "(", "self", ",", "*", ",", "convert_charrefs", "=", "True", ")", ":", "self", ".", "convert_charrefs", "=", "convert_charrefs", "self", ".", "reset", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/html/parser.py#L87-L94
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/abins/atomsdata.py
python
AtomsData._check_item
(item: Dict[str, Any], n_atoms: Optional[int] = None)
return item
Raise an error if Atoms data item is unsuitable :param item: element to be added :param n_atoms: Number of atoms in data. If provided, check that "sort" value is not higher than expected.
Raise an error if Atoms data item is unsuitable
[ "Raise", "an", "error", "if", "Atoms", "data", "item", "is", "unsuitable" ]
def _check_item(item: Dict[str, Any], n_atoms: Optional[int] = None) -> Dict[str, Any]: """ Raise an error if Atoms data item is unsuitable :param item: element to be added :param n_atoms: Number of atoms in data. If provided, check that "sort" value is not higher than expected. """ if not isinstance(item, dict): raise ValueError("Every element of AtomsData should be a dictionary.") if not sorted(item.keys()) == sorted(abins.constants.ALL_KEYWORDS_ATOMS_DATA): raise ValueError("Invalid structure of the dictionary to be added.") # "symbol" if not item["symbol"] in abins.constants.ALL_SYMBOLS: # Check is symbol was loaded as type bytes utf8_symbol = item["symbol"].decode("utf-8") if utf8_symbol in abins.constants.ALL_SYMBOLS: item["symbol"] = utf8_symbol else: raise ValueError("Invalid value of symbol.") # "coord" coord = item["coord"] if not isinstance(coord, np.ndarray): raise ValueError("Coordinates of an atom should have a form of a numpy array.") if len(coord.shape) != 1: raise ValueError("Coordinates should have a form of 1D numpy array.") if coord.shape[0] != 3: raise ValueError("Coordinates should have a form of numpy array with three elements.") if coord.dtype.num != abins.constants.FLOAT_ID: raise ValueError("Coordinates array should have real float dtype.") # "sort" sort = item["sort"] if not isinstance(sort, numbers.Integral): raise ValueError("Parameter 'sort' should be integer.") if sort < 0: raise ValueError("Parameter 'sort' cannot be negative.") if n_atoms is not None and (sort + 1) > n_atoms: raise ValueError("Parameter 'sort' should not exceed atom indices") # "mass" mass = item["mass"] if not isinstance(mass, numbers.Real): raise ValueError("Mass of atom should be a real number.") if mass < 0: raise ValueError("Mass of atom cannot be negative.") return item
[ "def", "_check_item", "(", "item", ":", "Dict", "[", "str", ",", "Any", "]", ",", "n_atoms", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "if", "not", "isinstance", "(", "item", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"Every element of AtomsData should be a dictionary.\"", ")", "if", "not", "sorted", "(", "item", ".", "keys", "(", ")", ")", "==", "sorted", "(", "abins", ".", "constants", ".", "ALL_KEYWORDS_ATOMS_DATA", ")", ":", "raise", "ValueError", "(", "\"Invalid structure of the dictionary to be added.\"", ")", "# \"symbol\"", "if", "not", "item", "[", "\"symbol\"", "]", "in", "abins", ".", "constants", ".", "ALL_SYMBOLS", ":", "# Check is symbol was loaded as type bytes", "utf8_symbol", "=", "item", "[", "\"symbol\"", "]", ".", "decode", "(", "\"utf-8\"", ")", "if", "utf8_symbol", "in", "abins", ".", "constants", ".", "ALL_SYMBOLS", ":", "item", "[", "\"symbol\"", "]", "=", "utf8_symbol", "else", ":", "raise", "ValueError", "(", "\"Invalid value of symbol.\"", ")", "# \"coord\"", "coord", "=", "item", "[", "\"coord\"", "]", "if", "not", "isinstance", "(", "coord", ",", "np", ".", "ndarray", ")", ":", "raise", "ValueError", "(", "\"Coordinates of an atom should have a form of a numpy array.\"", ")", "if", "len", "(", "coord", ".", "shape", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Coordinates should have a form of 1D numpy array.\"", ")", "if", "coord", ".", "shape", "[", "0", "]", "!=", "3", ":", "raise", "ValueError", "(", "\"Coordinates should have a form of numpy array with three elements.\"", ")", "if", "coord", ".", "dtype", ".", "num", "!=", "abins", ".", "constants", ".", "FLOAT_ID", ":", "raise", "ValueError", "(", "\"Coordinates array should have real float dtype.\"", ")", "# \"sort\"", "sort", "=", "item", "[", "\"sort\"", "]", "if", "not", "isinstance", "(", "sort", ",", "numbers", ".", "Integral", ")", ":", "raise", "ValueError", "(", "\"Parameter 'sort' should be integer.\"", ")", "if", "sort", "<", "0", ":", "raise", "ValueError", "(", "\"Parameter 'sort' cannot be negative.\"", ")", "if", "n_atoms", "is", "not", "None", "and", "(", "sort", "+", "1", ")", ">", "n_atoms", ":", "raise", "ValueError", "(", "\"Parameter 'sort' should not exceed atom indices\"", ")", "# \"mass\"", "mass", "=", "item", "[", "\"mass\"", "]", "if", "not", "isinstance", "(", "mass", ",", "numbers", ".", "Real", ")", ":", "raise", "ValueError", "(", "\"Mass of atom should be a real number.\"", ")", "if", "mass", "<", "0", ":", "raise", "ValueError", "(", "\"Mass of atom cannot be negative.\"", ")", "return", "item" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/atomsdata.py#L49-L102
gtcasl/gpuocelot
fa63920ee7c5f9a86e264cd8acd4264657cbd190
ocelot/scripts/build_environment.py
python
getDebianArchitecture
()
return arch[0]
Determines the debian architecture return {deb_arch}
Determines the debian architecture return {deb_arch}
[ "Determines", "the", "debian", "architecture", "return", "{", "deb_arch", "}" ]
def getDebianArchitecture(): """Determines the debian architecture return {deb_arch} """ # check for supported OS if os.name != 'posix': raise ValueError, 'Error: unknown OS. Can only build .deb on linux.' try: dpkg_arch_path = which('dpkg-architecture') except: raise ValueError, "Failed to find 'dpkg-architecture' needed for .deb" \ ". Try installing dpkg-dev" # setup .deb environment variables arch = os.popen( \ 'dpkg-architecture -c \'echo $DEB_BUILD_ARCH\'').read().split() if len(arch) == 0: raise ValueError, 'Failed to get architecture from dpkg-architecture' return arch[0]
[ "def", "getDebianArchitecture", "(", ")", ":", "# check for supported OS", "if", "os", ".", "name", "!=", "'posix'", ":", "raise", "ValueError", ",", "'Error: unknown OS. Can only build .deb on linux.'", "try", ":", "dpkg_arch_path", "=", "which", "(", "'dpkg-architecture'", ")", "except", ":", "raise", "ValueError", ",", "\"Failed to find 'dpkg-architecture' needed for .deb\"", "\". Try installing dpkg-dev\"", "# setup .deb environment variables", "arch", "=", "os", ".", "popen", "(", "'dpkg-architecture -c \\'echo $DEB_BUILD_ARCH\\''", ")", ".", "read", "(", ")", ".", "split", "(", ")", "if", "len", "(", "arch", ")", "==", "0", ":", "raise", "ValueError", ",", "'Failed to get architecture from dpkg-architecture'", "return", "arch", "[", "0", "]" ]
https://github.com/gtcasl/gpuocelot/blob/fa63920ee7c5f9a86e264cd8acd4264657cbd190/ocelot/scripts/build_environment.py#L11-L34
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
native_client_sdk/src/build_tools/update_nacl_manifest.py
python
VersionFinder._GetAvailableArchivesFor
(self, version_string)
return filter(lambda a: a + '.json' in manifests, archives)
Downloads a list of all available archives for a given version. Args: version_string: The version to find archives for. (e.g. "18.0.1025.164") Returns: A list of strings, each of which is a platform-specific archive URL. (e.g. "gs://nativeclient_mirror/nacl/nacl_sdk/18.0.1025.164/" "naclsdk_linux.tar.bz2"). All returned URLs will use the gs:// schema.
Downloads a list of all available archives for a given version.
[ "Downloads", "a", "list", "of", "all", "available", "archives", "for", "a", "given", "version", "." ]
def _GetAvailableArchivesFor(self, version_string): """Downloads a list of all available archives for a given version. Args: version_string: The version to find archives for. (e.g. "18.0.1025.164") Returns: A list of strings, each of which is a platform-specific archive URL. (e.g. "gs://nativeclient_mirror/nacl/nacl_sdk/18.0.1025.164/" "naclsdk_linux.tar.bz2"). All returned URLs will use the gs:// schema.""" files = self.delegate.GsUtil_ls(GS_BUCKET_PATH + version_string) assert all(file.startswith('gs://') for file in files) archives = [f for f in files if not f.endswith('.json')] manifests = [f for f in files if f.endswith('.json')] # don't include any archives that don't have an associated manifest. return filter(lambda a: a + '.json' in manifests, archives)
[ "def", "_GetAvailableArchivesFor", "(", "self", ",", "version_string", ")", ":", "files", "=", "self", ".", "delegate", ".", "GsUtil_ls", "(", "GS_BUCKET_PATH", "+", "version_string", ")", "assert", "all", "(", "file", ".", "startswith", "(", "'gs://'", ")", "for", "file", "in", "files", ")", "archives", "=", "[", "f", "for", "f", "in", "files", "if", "not", "f", ".", "endswith", "(", "'.json'", ")", "]", "manifests", "=", "[", "f", "for", "f", "in", "files", "if", "f", ".", "endswith", "(", "'.json'", ")", "]", "# don't include any archives that don't have an associated manifest.", "return", "filter", "(", "lambda", "a", ":", "a", "+", "'.json'", "in", "manifests", ",", "archives", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/native_client_sdk/src/build_tools/update_nacl_manifest.py#L574-L593
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/site.py
python
addsitepackages
(known_paths)
return known_paths
Add site-packages (and possibly site-python) to sys.path
Add site-packages (and possibly site-python) to sys.path
[ "Add", "site", "-", "packages", "(", "and", "possibly", "site", "-", "python", ")", "to", "sys", ".", "path" ]
def addsitepackages(known_paths): """Add site-packages (and possibly site-python) to sys.path""" for sitedir in getsitepackages(): if os.path.isdir(sitedir): addsitedir(sitedir, known_paths) return known_paths
[ "def", "addsitepackages", "(", "known_paths", ")", ":", "for", "sitedir", "in", "getsitepackages", "(", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "sitedir", ")", ":", "addsitedir", "(", "sitedir", ",", "known_paths", ")", "return", "known_paths" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/site.py#L309-L315
google/usd_from_gltf
6d288cce8b68744494a226574ae1d7ba6a9c46eb
tools/ufginstall/ufginstall.py
python
DracoDep.install
(self)
Installs Draco dependency.
Installs Draco dependency.
[ "Installs", "Draco", "dependency", "." ]
def install(self): """Installs Draco dependency.""" url = 'https://github.com/google/draco/archive/1.3.5.zip' path = os.path.join(cfg.src_dir, 'draco.zip') force = self.forced() dl_dir = download_archive(url, path, force) with cwd(dl_dir): extra_args = ['-DCMAKE_POSITION_INDEPENDENT_CODE=1'] # Fix case-sensitivity bug in cmake script. patches = [ ('${draco_build_dir}/DracoConfig.cmake', '${draco_build_dir}/dracoConfig.cmake')] patch_file_text('CMakeLists.txt', patches) run_cmake(force, extra_args)
[ "def", "install", "(", "self", ")", ":", "url", "=", "'https://github.com/google/draco/archive/1.3.5.zip'", "path", "=", "os", ".", "path", ".", "join", "(", "cfg", ".", "src_dir", ",", "'draco.zip'", ")", "force", "=", "self", ".", "forced", "(", ")", "dl_dir", "=", "download_archive", "(", "url", ",", "path", ",", "force", ")", "with", "cwd", "(", "dl_dir", ")", ":", "extra_args", "=", "[", "'-DCMAKE_POSITION_INDEPENDENT_CODE=1'", "]", "# Fix case-sensitivity bug in cmake script.", "patches", "=", "[", "(", "'${draco_build_dir}/DracoConfig.cmake'", ",", "'${draco_build_dir}/dracoConfig.cmake'", ")", "]", "patch_file_text", "(", "'CMakeLists.txt'", ",", "patches", ")", "run_cmake", "(", "force", ",", "extra_args", ")" ]
https://github.com/google/usd_from_gltf/blob/6d288cce8b68744494a226574ae1d7ba6a9c46eb/tools/ufginstall/ufginstall.py#L139-L152