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
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
third_party/cpplint.py
python
CheckCasts
(filename, clean_lines, linenum, error)
Various cast related checks. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Various cast related checks.
[ "Various", "cast", "related", "checks", "." ]
def CheckCasts(filename, clean_lines, linenum, error): """Various cast related checks. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Check to see if they're using an conversion function cast. # I just try to capture the most common basic types, though there are more. # Parameterless conversion functions, such as bool(), are allowed as they are # probably a member operator declaration or default constructor. match = Search( r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b' r'(int|float|double|bool|char|int32|uint32|int64|uint64)' r'(\([^)].*)', line) expecting_function = ExpectingFunctionArgs(clean_lines, linenum) if match and not expecting_function: matched_type = match.group(2) # matched_new_or_template is used to silence two false positives: # - New operators # - Template arguments with function types # # For template arguments, we match on types immediately following # an opening bracket without any spaces. This is a fast way to # silence the common case where the function type is the first # template argument. False negative with less-than comparison is # avoided because those operators are usually followed by a space. # # function<double(double)> // bracket + no space = false positive # value < double(42) // bracket + space = true positive matched_new_or_template = match.group(1) # Avoid arrays by looking for brackets that come after the closing # parenthesis. if Match(r'\([^()]+\)\s*\[', match.group(3)): return # Other things to ignore: # - Function pointers # - Casts to pointer types # - Placement new # - Alias declarations matched_funcptr = match.group(3) if (matched_new_or_template is None and not (matched_funcptr and (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', matched_funcptr) or matched_funcptr.startswith('(*)'))) and not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and not Search(r'new\(\S+\)\s*' + matched_type, line)): error(filename, linenum, 'readability/casting', 4, 'Using deprecated casting style. ' 'Use static_cast<%s>(...) instead' % matched_type) if not expecting_function: CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) # This doesn't catch all cases. Consider (const char * const)"hello". # # (char *) "foo" should always be a const_cast (reinterpret_cast won't # compile). if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): pass else: # Check pointer casts for other than string constants CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) # In addition, we look for people taking the address of a cast. This # is dangerous -- casts can assign to temporaries, so the pointer doesn't # point where you think. # # Some non-identifier character is required before the '&' for the # expression to be recognized as a cast. These are casts: # expression = &static_cast<int*>(temporary()); # function(&(int*)(temporary())); # # This is not a cast: # reference_type&(int* function_param); match = Search( r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|' r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) if match: # Try a better error message when the & is bound to something # dereferenced by the casted pointer, as opposed to the casted # pointer itself. parenthesis_error = False match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) if match: _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) if x1 >= 0 and clean_lines.elided[y1][x1] == '(': _, y2, x2 = CloseExpression(clean_lines, y1, x1) if x2 >= 0: extended_line = clean_lines.elided[y2][x2:] if y2 < clean_lines.NumLines() - 1: extended_line += clean_lines.elided[y2 + 1] if Match(r'\s*(?:->|\[)', extended_line): parenthesis_error = True if parenthesis_error: error(filename, linenum, 'readability/casting', 4, ('Are you taking an address of something dereferenced ' 'from a cast? Wrapping the dereferenced expression in ' 'parentheses will make the binding more obvious')) else: error(filename, linenum, 'runtime/casting', 4, ('Are you taking an address of a cast? ' 'This is dangerous: could be a temp var. ' 'Take the address before doing the cast, rather than after'))
[ "def", "CheckCasts", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Check to see if they're using an conversion function cast.", "# I just try to capture the most common basic t...
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/third_party/cpplint.py#L5152-L5268
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/reduction_gui/reduction/sans/hfir_background_script.py
python
Background.to_xml
(self)
return xml_out
Create XML from the current data.
Create XML from the current data.
[ "Create", "XML", "from", "the", "current", "data", "." ]
def to_xml(self): """ Create XML from the current data. """ xml_out = "<Background>\n" xml_out += " <dark_current_corr>%s</dark_current_corr>\n" % str(self.dark_current_corr) xml_out += " <dark_current_file>%s</dark_current_file>\n" % self.dark_current_file xml_out += " <background_corr>%s</background_corr>\n" % str(self.background_corr) xml_out += " <background_file>%s</background_file>\n" % self.background_file xml_out += " <bck_trans_enabled>%s</bck_trans_enabled>\n" % str(self.bck_transmission_enabled) xml_out += " <bck_trans>%g</bck_trans>\n" % self.bck_transmission xml_out += " <bck_trans_spread>%g</bck_trans_spread>\n" % self.bck_transmission_spread xml_out += " <calculate_trans>%s</calculate_trans>\n" % str(self.calculate_transmission) xml_out += " <theta_dependent>%s</theta_dependent>\n" % str(self.theta_dependent) xml_out += " <trans_dark_current>%s</trans_dark_current>\n" % str(self.trans_dark_current) xml_out += self.trans_calculation_method.to_xml() xml_out += "</Background>\n" return xml_out
[ "def", "to_xml", "(", "self", ")", ":", "xml_out", "=", "\"<Background>\\n\"", "xml_out", "+=", "\" <dark_current_corr>%s</dark_current_corr>\\n\"", "%", "str", "(", "self", ".", "dark_current_corr", ")", "xml_out", "+=", "\" <dark_current_file>%s</dark_current_file>\\n\"...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_gui/reduction/sans/hfir_background_script.py#L170-L188
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Tools/parser/unparse.py
python
Unparser.fill
(self, text = "")
Indent a piece of text, according to the current indentation level
Indent a piece of text, according to the current indentation level
[ "Indent", "a", "piece", "of", "text", "according", "to", "the", "current", "indentation", "level" ]
def fill(self, text = ""): "Indent a piece of text, according to the current indentation level" self.f.write("\n"+" "*self._indent + text)
[ "def", "fill", "(", "self", ",", "text", "=", "\"\"", ")", ":", "self", ".", "f", ".", "write", "(", "\"\\n\"", "+", "\" \"", "*", "self", ".", "_indent", "+", "text", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Tools/parser/unparse.py#L39-L41
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Configuration/DataProcessing/python/Reco.py
python
Reco.expressProcessing
(self, globalTag, **args)
return process
_expressProcessing_ Proton collision data taking express processing
_expressProcessing_
[ "_expressProcessing_" ]
def expressProcessing(self, globalTag, **args): """ _expressProcessing_ Proton collision data taking express processing """ skims = args['skims'] # the AlCaReco skims for PCL should only run during AlCaSkimming step which uses the same configuration on the Tier0 side, for this reason we drop them here pclWkflws = [x for x in skims if "PromptCalibProd" in x] for wfl in pclWkflws: skims.remove(wfl) step = stepALCAPRODUCER(skims) dqmStep= dqmSeq(args,'') options = Options() options.__dict__.update(defaultOptions.__dict__) options.scenario = self.cbSc if ('nThreads' in args) : options.nThreads=args['nThreads'] eiStep='' options.step = 'RAW2DIGI,L1Reco,RECO'+self.recoSeq+eiStep+step+',DQM'+dqmStep+',ENDJOB' dictIO(options,args) options.conditions = gtNameAndConnect(globalTag, args) options.filein = 'tobeoverwritten.xyz' if 'inputSource' in args: options.filetype = args['inputSource'] process = cms.Process('RECO', cms.ModifierChain(self.eras, self.expressModifiers) ) if 'customs' in args: options.customisation_file=args['customs'] self._checkRepackedFlag(options,**args) cb = ConfigBuilder(options, process = process, with_output = True, with_input = True) cb.prepare() addMonitoring(process) return process
[ "def", "expressProcessing", "(", "self", ",", "globalTag", ",", "*", "*", "args", ")", ":", "skims", "=", "args", "[", "'skims'", "]", "# the AlCaReco skims for PCL should only run during AlCaSkimming step which uses the same configuration on the Tier0 side, for this reason we dr...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Configuration/DataProcessing/python/Reco.py#L96-L141
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/py/py/_path/svnwc.py
python
WCStatus.fromstring
(data, rootwcpath, rev=None, modrev=None, author=None)
return rootstatus
return a new WCStatus object from data 's'
return a new WCStatus object from data 's'
[ "return", "a", "new", "WCStatus", "object", "from", "data", "s" ]
def fromstring(data, rootwcpath, rev=None, modrev=None, author=None): """ return a new WCStatus object from data 's' """ rootstatus = WCStatus(rootwcpath, rev, modrev, author) update_rev = None for line in data.split('\n'): if not line.strip(): continue #print "processing %r" % line flags, rest = line[:8], line[8:] # first column c0,c1,c2,c3,c4,c5,x6,c7 = flags #if '*' in line: # print "flags", repr(flags), "rest", repr(rest) if c0 in '?XI': fn = line.split(None, 1)[1] if c0 == '?': wcpath = rootwcpath.join(fn, abs=1) rootstatus.unknown.append(wcpath) elif c0 == 'X': wcpath = rootwcpath.__class__( rootwcpath.localpath.join(fn, abs=1), auth=rootwcpath.auth) rootstatus.external.append(wcpath) elif c0 == 'I': wcpath = rootwcpath.join(fn, abs=1) rootstatus.ignored.append(wcpath) continue #elif c0 in '~!' or c4 == 'S': # raise NotImplementedError("received flag %r" % c0) m = WCStatus._rex_status.match(rest) if not m: if c7 == '*': fn = rest.strip() wcpath = rootwcpath.join(fn, abs=1) rootstatus.update_available.append(wcpath) continue if line.lower().find('against revision:')!=-1: update_rev = int(rest.split(':')[1].strip()) continue if line.lower().find('status on external') > -1: # XXX not sure what to do here... perhaps we want to # store some state instead of just continuing, as right # now it makes the top-level external get added twice # (once as external, once as 'normal' unchanged item) # because of the way SVN presents external items continue # keep trying raise ValueError("could not parse line %r" % line) else: rev, modrev, author, fn = m.groups() wcpath = rootwcpath.join(fn, abs=1) #assert wcpath.check() if c0 == 'M': assert wcpath.check(file=1), "didn't expect a directory with changed content here" rootstatus.modified.append(wcpath) elif c0 == 'A' or c3 == '+' : rootstatus.added.append(wcpath) elif c0 == 'D': rootstatus.deleted.append(wcpath) elif c0 == 'C': rootstatus.conflict.append(wcpath) elif c0 == '~': rootstatus.kindmismatch.append(wcpath) elif c0 == '!': rootstatus.incomplete.append(wcpath) elif c0 == 'R': rootstatus.replaced.append(wcpath) elif not c0.strip(): rootstatus.unchanged.append(wcpath) else: raise NotImplementedError("received flag %r" % c0) if c1 == 'M': rootstatus.prop_modified.append(wcpath) # XXX do we cover all client versions here? if c2 == 'L' or c5 == 'K': rootstatus.locked.append(wcpath) if c7 == '*': rootstatus.update_available.append(wcpath) if wcpath == rootwcpath: rootstatus.rev = rev rootstatus.modrev = modrev rootstatus.author = author if update_rev: rootstatus.update_rev = update_rev continue return rootstatus
[ "def", "fromstring", "(", "data", ",", "rootwcpath", ",", "rev", "=", "None", ",", "modrev", "=", "None", ",", "author", "=", "None", ")", ":", "rootstatus", "=", "WCStatus", "(", "rootwcpath", ",", "rev", ",", "modrev", ",", "author", ")", "update_rev...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/py/py/_path/svnwc.py#L926-L1018
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py
python
EscapeXcodeDefine
(s)
return re.sub(_xcode_define_re, r"\\\1", s)
We must escape the defines that we give to XCode so that it knows not to split on spaces and to respect backslash and quote literals. However, we must not quote the define, or Xcode will incorrectly interpret variables especially $(inherited).
We must escape the defines that we give to XCode so that it knows not to split on spaces and to respect backslash and quote literals. However, we must not quote the define, or Xcode will incorrectly interpret variables especially $(inherited).
[ "We", "must", "escape", "the", "defines", "that", "we", "give", "to", "XCode", "so", "that", "it", "knows", "not", "to", "split", "on", "spaces", "and", "to", "respect", "backslash", "and", "quote", "literals", ".", "However", "we", "must", "not", "quote...
def EscapeXcodeDefine(s): """We must escape the defines that we give to XCode so that it knows not to split on spaces and to respect backslash and quote literals. However, we must not quote the define, or Xcode will incorrectly interpret variables especially $(inherited).""" return re.sub(_xcode_define_re, r"\\\1", s)
[ "def", "EscapeXcodeDefine", "(", "s", ")", ":", "return", "re", ".", "sub", "(", "_xcode_define_re", ",", "r\"\\\\\\1\"", ",", "s", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py#L593-L598
reverbrain/elliptics
4b4f9b8094d7616c1ec50eb8605edb059b9f228e
bindings/python/src/route.py
python
RouteList.__str__
(self)
return "\n".join(map(str, self.routes))
x.__str__() <==> str(x)
x.__str__() <==> str(x)
[ "x", ".", "__str__", "()", "<", "==", ">", "str", "(", "x", ")" ]
def __str__(self): """x.__str__() <==> str(x)""" return "\n".join(map(str, self.routes))
[ "def", "__str__", "(", "self", ")", ":", "return", "\"\\n\"", ".", "join", "(", "map", "(", "str", ",", "self", ".", "routes", ")", ")" ]
https://github.com/reverbrain/elliptics/blob/4b4f9b8094d7616c1ec50eb8605edb059b9f228e/bindings/python/src/route.py#L439-L441
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBSymbolContext.SetSymbol
(self, *args)
return _lldb.SBSymbolContext_SetSymbol(self, *args)
SetSymbol(self, SBSymbol symbol)
SetSymbol(self, SBSymbol symbol)
[ "SetSymbol", "(", "self", "SBSymbol", "symbol", ")" ]
def SetSymbol(self, *args): """SetSymbol(self, SBSymbol symbol)""" return _lldb.SBSymbolContext_SetSymbol(self, *args)
[ "def", "SetSymbol", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBSymbolContext_SetSymbol", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L8304-L8306
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py
python
isgeneratorfunction
(object)
return bool((isfunction(object) or ismethod(object)) and object.__code__.co_flags & CO_GENERATOR)
Return true if the object is a user-defined generator function. Generator function objects provide the same attributes as functions. See help(isfunction) for a list of attributes.
Return true if the object is a user-defined generator function.
[ "Return", "true", "if", "the", "object", "is", "a", "user", "-", "defined", "generator", "function", "." ]
def isgeneratorfunction(object): """Return true if the object is a user-defined generator function. Generator function objects provide the same attributes as functions. See help(isfunction) for a list of attributes.""" return bool((isfunction(object) or ismethod(object)) and object.__code__.co_flags & CO_GENERATOR)
[ "def", "isgeneratorfunction", "(", "object", ")", ":", "return", "bool", "(", "(", "isfunction", "(", "object", ")", "or", "ismethod", "(", "object", ")", ")", "and", "object", ".", "__code__", ".", "co_flags", "&", "CO_GENERATOR", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py#L171-L177
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/image/detection.py
python
CreateMultiRandCropAugmenter
(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), min_eject_coverage=0.3, max_attempts=50, skip_prob=0)
return DetRandomSelectAug(augs, skip_prob=skip_prob)
Helper function to create multiple random crop augmenters. Parameters ---------- min_object_covered : float or list of float, default=0.1 The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied. min_eject_coverage : float or list of float, default=0.3 The minimum coverage of cropped sample w.r.t its original size. With this constraint, objects that have marginal area after crop will be discarded. aspect_ratio_range : tuple of floats or list of tuple of floats, default=(0.75, 1.33) The cropped area of the image must have an aspect ratio = width / height within this range. area_range : tuple of floats or list of tuple of floats, default=(0.05, 1.0) The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts : int or list of int, default=50 Number of attempts at generating a cropped/padded region of the image of the specified constraints. After max_attempts failures, return the original image. Examples -------- >>> # An example of creating multiple random crop augmenters >>> min_object_covered = [0.1, 0.3, 0.5, 0.7, 0.9] # use 5 augmenters >>> aspect_ratio_range = (0.75, 1.33) # use same range for all augmenters >>> area_range = [(0.1, 1.0), (0.2, 1.0), (0.2, 1.0), (0.3, 0.9), (0.5, 1.0)] >>> min_eject_coverage = 0.3 >>> max_attempts = 50 >>> aug = mx.image.det.CreateMultiRandCropAugmenter(min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, min_eject_coverage=min_eject_coverage, max_attempts=max_attempts, skip_prob=0) >>> aug.dumps() # show some details
Helper function to create multiple random crop augmenters.
[ "Helper", "function", "to", "create", "multiple", "random", "crop", "augmenters", "." ]
def CreateMultiRandCropAugmenter(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), min_eject_coverage=0.3, max_attempts=50, skip_prob=0): """Helper function to create multiple random crop augmenters. Parameters ---------- min_object_covered : float or list of float, default=0.1 The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied. min_eject_coverage : float or list of float, default=0.3 The minimum coverage of cropped sample w.r.t its original size. With this constraint, objects that have marginal area after crop will be discarded. aspect_ratio_range : tuple of floats or list of tuple of floats, default=(0.75, 1.33) The cropped area of the image must have an aspect ratio = width / height within this range. area_range : tuple of floats or list of tuple of floats, default=(0.05, 1.0) The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts : int or list of int, default=50 Number of attempts at generating a cropped/padded region of the image of the specified constraints. After max_attempts failures, return the original image. Examples -------- >>> # An example of creating multiple random crop augmenters >>> min_object_covered = [0.1, 0.3, 0.5, 0.7, 0.9] # use 5 augmenters >>> aspect_ratio_range = (0.75, 1.33) # use same range for all augmenters >>> area_range = [(0.1, 1.0), (0.2, 1.0), (0.2, 1.0), (0.3, 0.9), (0.5, 1.0)] >>> min_eject_coverage = 0.3 >>> max_attempts = 50 >>> aug = mx.image.det.CreateMultiRandCropAugmenter(min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, min_eject_coverage=min_eject_coverage, max_attempts=max_attempts, skip_prob=0) >>> aug.dumps() # show some details """ def align_parameters(params): """Align parameters as pairs""" out_params = [] num = 1 for p in params: if not isinstance(p, list): p = [p] out_params.append(p) num = max(num, len(p)) # align for each param for k, p in enumerate(out_params): if len(p) != num: assert len(p) == 1 out_params[k] = p * num return out_params aligned_params = align_parameters([min_object_covered, aspect_ratio_range, area_range, min_eject_coverage, max_attempts]) augs = [] for moc, arr, ar, mec, ma in zip(*aligned_params): augs.append(DetRandomCropAug(min_object_covered=moc, aspect_ratio_range=arr, area_range=ar, min_eject_coverage=mec, max_attempts=ma)) return DetRandomSelectAug(augs, skip_prob=skip_prob)
[ "def", "CreateMultiRandCropAugmenter", "(", "min_object_covered", "=", "0.1", ",", "aspect_ratio_range", "=", "(", "0.75", ",", "1.33", ")", ",", "area_range", "=", "(", "0.05", ",", "1.0", ")", ",", "min_eject_coverage", "=", "0.3", ",", "max_attempts", "=", ...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/image/detection.py#L417-L479
gnina/gnina
b9ae032f52fc7a8153987bde09c0efa3620d8bb6
caffe/scripts/cpp_lint.py
python
_NestingState.InnermostClass
(self)
return None
Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise.
Get class info on the top of the stack.
[ "Get", "class", "info", "on", "the", "top", "of", "the", "stack", "." ]
def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None
[ "def", "InnermostClass", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stack", ")", ",", "0", ",", "-", "1", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "i", "-", "1", "]", "if", "isinstance", "(", ...
https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/scripts/cpp_lint.py#L2164-L2174
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/docview.py
python
View.OnPrint
(self, dc, info)
Override this to print the view for the printing framework. The default implementation calls View.OnDraw.
Override this to print the view for the printing framework. The default implementation calls View.OnDraw.
[ "Override", "this", "to", "print", "the", "view", "for", "the", "printing", "framework", ".", "The", "default", "implementation", "calls", "View", ".", "OnDraw", "." ]
def OnPrint(self, dc, info): """ Override this to print the view for the printing framework. The default implementation calls View.OnDraw. """ self.OnDraw(dc)
[ "def", "OnPrint", "(", "self", ",", "dc", ",", "info", ")", ":", "self", ".", "OnDraw", "(", "dc", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L844-L849
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/vimeo/oauth/oauth_api.py
python
OAuthServer.get_callback
(self, oauth_request)
return oauth_request.get_parameter('oauth_callback')
Get the callback URL.
Get the callback URL.
[ "Get", "the", "callback", "URL", "." ]
def get_callback(self, oauth_request): """Get the callback URL.""" return oauth_request.get_parameter('oauth_callback')
[ "def", "get_callback", "(", "self", ",", "oauth_request", ")", ":", "return", "oauth_request", ".", "get_parameter", "(", "'oauth_callback'", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/vimeo/oauth/oauth_api.py#L440-L442
deweylab/RSEM
e4dda70e90fb5eb9b831306f1c381f8bbf71ef0e
pRSEM/Transcript.py
python
quicklyReadRSEMTI
(fin)
return transcripts
read RSEM's .ti file without parsing the additional information line (the last line in a transcript's block return a list of Transcripts objects
read RSEM's .ti file without parsing the additional information line (the last line in a transcript's block
[ "read", "RSEM", "s", ".", "ti", "file", "without", "parsing", "the", "additional", "information", "line", "(", "the", "last", "line", "in", "a", "transcript", "s", "block" ]
def quicklyReadRSEMTI(fin): """ read RSEM's .ti file without parsing the additional information line (the last line in a transcript's block return a list of Transcripts objects """ import Util lines = Util.readFile(fin); (ntranscripts, foo) = lines[0].split(); ntranscripts = int(ntranscripts); transcripts = []; for i in range(0, ntranscripts): tr = Transcript(); tr.quicklyConstructFromRSEMTI(lines[i*6+1:i*6+7]); transcripts.append(tr); if (i > 0) and (i % 20000 == 0): print "processed %d transcripts" % i; return transcripts;
[ "def", "quicklyReadRSEMTI", "(", "fin", ")", ":", "import", "Util", "lines", "=", "Util", ".", "readFile", "(", "fin", ")", "(", "ntranscripts", ",", "foo", ")", "=", "lines", "[", "0", "]", ".", "split", "(", ")", "ntranscripts", "=", "int", "(", ...
https://github.com/deweylab/RSEM/blob/e4dda70e90fb5eb9b831306f1c381f8bbf71ef0e/pRSEM/Transcript.py#L168-L188
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
TextBoxAttr.GetBottomOutline
(*args)
return _richtext.TextBoxAttr_GetBottomOutline(*args)
GetBottomOutline(self) -> TextAttrBorder GetBottomOutline(self) -> TextAttrBorder
GetBottomOutline(self) -> TextAttrBorder GetBottomOutline(self) -> TextAttrBorder
[ "GetBottomOutline", "(", "self", ")", "-", ">", "TextAttrBorder", "GetBottomOutline", "(", "self", ")", "-", ">", "TextAttrBorder" ]
def GetBottomOutline(*args): """ GetBottomOutline(self) -> TextAttrBorder GetBottomOutline(self) -> TextAttrBorder """ return _richtext.TextBoxAttr_GetBottomOutline(*args)
[ "def", "GetBottomOutline", "(", "*", "args", ")", ":", "return", "_richtext", ".", "TextBoxAttr_GetBottomOutline", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L796-L801
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
TextAttrBorder.MakeValid
(*args, **kwargs)
return _richtext.TextAttrBorder_MakeValid(*args, **kwargs)
MakeValid(self)
MakeValid(self)
[ "MakeValid", "(", "self", ")" ]
def MakeValid(*args, **kwargs): """MakeValid(self)""" return _richtext.TextAttrBorder_MakeValid(*args, **kwargs)
[ "def", "MakeValid", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "TextAttrBorder_MakeValid", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L402-L404
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/simulation.py
python
Simulation.run
(self, steps, write_at_start=False)
Advance the simulation a number of steps. Args: steps (int): Number of steps to advance the simulation. write_at_start (bool): When `True`, writers with triggers that evaluate `True` for the initial step will be executed before the time step loop. Note: Initialize the simulation's state before calling `run`. During each step `run`, `Simulation` applies its `operations` to the state in the order: Tuners, Updaters, Integrator, then Writers following the logic in this pseudocode:: if write_at_start: for writer in operations.writers: if writer.trigger(timestep): writer.write(timestep) end_step = timestep + steps while timestep < end_step: for tuner in operations.tuners: if tuner.trigger(timestep): tuner.tune(timestep) for updater in operations.updaters: if updater.trigger(timestep): updater.update(timestep) if operations.integrator is not None: operations.integrator(timestep) timestep += 1 for writer in operations.writers: if writer.trigger(timestep): writer.write(timestep) This order of operations ensures that writers (such as `hoomd.write.GSD`) capture the final output of the last step of the run loop. For example, a writer with a trigger ``hoomd.trigger.Periodic(period=100, phase=0)`` active during a ``run(500)`` would write on steps 100, 200, 300, 400, and 500. Set ``write_at_start=True`` on the first call to `run` to also obtain output at step 0. Warning: Using ``write_at_start=True`` in subsequent calls to `run` will result in duplicate output frames.
Advance the simulation a number of steps.
[ "Advance", "the", "simulation", "a", "number", "of", "steps", "." ]
def run(self, steps, write_at_start=False): """Advance the simulation a number of steps. Args: steps (int): Number of steps to advance the simulation. write_at_start (bool): When `True`, writers with triggers that evaluate `True` for the initial step will be executed before the time step loop. Note: Initialize the simulation's state before calling `run`. During each step `run`, `Simulation` applies its `operations` to the state in the order: Tuners, Updaters, Integrator, then Writers following the logic in this pseudocode:: if write_at_start: for writer in operations.writers: if writer.trigger(timestep): writer.write(timestep) end_step = timestep + steps while timestep < end_step: for tuner in operations.tuners: if tuner.trigger(timestep): tuner.tune(timestep) for updater in operations.updaters: if updater.trigger(timestep): updater.update(timestep) if operations.integrator is not None: operations.integrator(timestep) timestep += 1 for writer in operations.writers: if writer.trigger(timestep): writer.write(timestep) This order of operations ensures that writers (such as `hoomd.write.GSD`) capture the final output of the last step of the run loop. For example, a writer with a trigger ``hoomd.trigger.Periodic(period=100, phase=0)`` active during a ``run(500)`` would write on steps 100, 200, 300, 400, and 500. Set ``write_at_start=True`` on the first call to `run` to also obtain output at step 0. Warning: Using ``write_at_start=True`` in subsequent calls to `run` will result in duplicate output frames. """ # check if initialization has occurred if not hasattr(self, '_cpp_sys'): raise RuntimeError('Cannot run before state is set.') if self._state._in_context_manager: raise RuntimeError( "Cannot call run inside of a local snapshot context manager.") if not self.operations._scheduled: self.operations._schedule() steps_int = int(steps) if steps_int < 0 or steps_int > TIMESTEP_MAX - 1: raise ValueError(f"steps must be in the range [0, " f"{TIMESTEP_MAX-1}]") self._cpp_sys.run(steps_int, write_at_start)
[ "def", "run", "(", "self", ",", "steps", ",", "write_at_start", "=", "False", ")", ":", "# check if initialization has occurred", "if", "not", "hasattr", "(", "self", ",", "'_cpp_sys'", ")", ":", "raise", "RuntimeError", "(", "'Cannot run before state is set.'", "...
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/simulation.py#L368-L435
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Object.GetClassName
(*args, **kwargs)
return _core_.Object_GetClassName(*args, **kwargs)
GetClassName(self) -> String Returns the class name of the C++ class using wxRTTI.
GetClassName(self) -> String
[ "GetClassName", "(", "self", ")", "-", ">", "String" ]
def GetClassName(*args, **kwargs): """ GetClassName(self) -> String Returns the class name of the C++ class using wxRTTI. """ return _core_.Object_GetClassName(*args, **kwargs)
[ "def", "GetClassName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Object_GetClassName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L804-L810
facebookincubator/profilo
d3a275d0e7897cc4e3507d543459f3227e85c67f
deps/fmt/support/rst2md.py
python
convert
(rst_path)
return core.publish_file(source_path=rst_path, writer=MDWriter())
Converts RST file to Markdown.
Converts RST file to Markdown.
[ "Converts", "RST", "file", "to", "Markdown", "." ]
def convert(rst_path): """Converts RST file to Markdown.""" return core.publish_file(source_path=rst_path, writer=MDWriter())
[ "def", "convert", "(", "rst_path", ")", ":", "return", "core", ".", "publish_file", "(", "source_path", "=", "rst_path", ",", "writer", "=", "MDWriter", "(", ")", ")" ]
https://github.com/facebookincubator/profilo/blob/d3a275d0e7897cc4e3507d543459f3227e85c67f/deps/fmt/support/rst2md.py#L153-L155
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py
python
Radiobutton.invoke
(self)
return self.tk.call(self._w, "invoke")
Sets the option variable to the option value, selects the widget, and invokes the associated command. Returns the result of the command, or an empty string if no command is specified.
Sets the option variable to the option value, selects the widget, and invokes the associated command.
[ "Sets", "the", "option", "variable", "to", "the", "option", "value", "selects", "the", "widget", "and", "invokes", "the", "associated", "command", "." ]
def invoke(self): """Sets the option variable to the option value, selects the widget, and invokes the associated command. Returns the result of the command, or an empty string if no command is specified.""" return self.tk.call(self._w, "invoke")
[ "def", "invoke", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"invoke\"", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py#L1050-L1056
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/image/python/ops/interpolate_spline.py
python
interpolate_spline
(train_points, train_values, query_points, order, regularization_weight=0.0, name='interpolate_spline')
return query_values
r"""Interpolate signal using polyharmonic interpolation. The interpolant has the form $$f(x) = \sum_{i = 1}^n w_i \phi(||x - c_i||) + v^T x + b.$$ This is a sum of two terms: (1) a weighted sum of radial basis function (RBF) terms, with the centers \\(c_1, ... c_n\\), and (2) a linear term with a bias. The \\(c_i\\) vectors are 'training' points. In the code, b is absorbed into v by appending 1 as a final dimension to x. The coefficients w and v are estimated such that the interpolant exactly fits the value of the function at the \\(c_i\\) points, the vector w is orthogonal to each \\(c_i\\), and the vector w sums to 0. With these constraints, the coefficients can be obtained by solving a linear system. \\(\phi\\) is an RBF, parametrized by an interpolation order. Using order=2 produces the well-known thin-plate spline. We also provide the option to perform regularized interpolation. Here, the interpolant is selected to trade off between the squared loss on the training data and a certain measure of its curvature ([details](https://en.wikipedia.org/wiki/Polyharmonic_spline)). Using a regularization weight greater than zero has the effect that the interpolant will no longer exactly fit the training data. However, it may be less vulnerable to overfitting, particularly for high-order interpolation. Note the interpolation procedure is differentiable with respect to all inputs besides the order parameter. We support dynamically-shaped inputs, where batch_size, n, and m are None at graph construction time. However, d and k must be known. Args: train_points: `[batch_size, n, d]` float `Tensor` of n d-dimensional locations. These do not need to be regularly-spaced. train_values: `[batch_size, n, k]` float `Tensor` of n c-dimensional values evaluated at train_points. query_points: `[batch_size, m, d]` `Tensor` of m d-dimensional locations where we will output the interpolant's values. order: order of the interpolation. Common values are 1 for \\(\phi(r) = r\\), 2 for \\(\phi(r) = r^2 * log(r)\\) (thin-plate spline), or 3 for \\(\phi(r) = r^3\\). regularization_weight: weight placed on the regularization term. This will depend substantially on the problem, and it should always be tuned. For many problems, it is reasonable to use no regularization. If using a non-zero value, we recommend a small value like 0.001. name: name prefix for ops created by this function Returns: `[b, m, k]` float `Tensor` of query values. We use train_points and train_values to perform polyharmonic interpolation. The query values are the values of the interpolant evaluated at the locations specified in query_points.
r"""Interpolate signal using polyharmonic interpolation.
[ "r", "Interpolate", "signal", "using", "polyharmonic", "interpolation", "." ]
def interpolate_spline(train_points, train_values, query_points, order, regularization_weight=0.0, name='interpolate_spline'): r"""Interpolate signal using polyharmonic interpolation. The interpolant has the form $$f(x) = \sum_{i = 1}^n w_i \phi(||x - c_i||) + v^T x + b.$$ This is a sum of two terms: (1) a weighted sum of radial basis function (RBF) terms, with the centers \\(c_1, ... c_n\\), and (2) a linear term with a bias. The \\(c_i\\) vectors are 'training' points. In the code, b is absorbed into v by appending 1 as a final dimension to x. The coefficients w and v are estimated such that the interpolant exactly fits the value of the function at the \\(c_i\\) points, the vector w is orthogonal to each \\(c_i\\), and the vector w sums to 0. With these constraints, the coefficients can be obtained by solving a linear system. \\(\phi\\) is an RBF, parametrized by an interpolation order. Using order=2 produces the well-known thin-plate spline. We also provide the option to perform regularized interpolation. Here, the interpolant is selected to trade off between the squared loss on the training data and a certain measure of its curvature ([details](https://en.wikipedia.org/wiki/Polyharmonic_spline)). Using a regularization weight greater than zero has the effect that the interpolant will no longer exactly fit the training data. However, it may be less vulnerable to overfitting, particularly for high-order interpolation. Note the interpolation procedure is differentiable with respect to all inputs besides the order parameter. We support dynamically-shaped inputs, where batch_size, n, and m are None at graph construction time. However, d and k must be known. Args: train_points: `[batch_size, n, d]` float `Tensor` of n d-dimensional locations. These do not need to be regularly-spaced. train_values: `[batch_size, n, k]` float `Tensor` of n c-dimensional values evaluated at train_points. query_points: `[batch_size, m, d]` `Tensor` of m d-dimensional locations where we will output the interpolant's values. order: order of the interpolation. Common values are 1 for \\(\phi(r) = r\\), 2 for \\(\phi(r) = r^2 * log(r)\\) (thin-plate spline), or 3 for \\(\phi(r) = r^3\\). regularization_weight: weight placed on the regularization term. This will depend substantially on the problem, and it should always be tuned. For many problems, it is reasonable to use no regularization. If using a non-zero value, we recommend a small value like 0.001. name: name prefix for ops created by this function Returns: `[b, m, k]` float `Tensor` of query values. We use train_points and train_values to perform polyharmonic interpolation. The query values are the values of the interpolant evaluated at the locations specified in query_points. """ with ops.name_scope(name): train_points = ops.convert_to_tensor(train_points) train_values = ops.convert_to_tensor(train_values) query_points = ops.convert_to_tensor(query_points) # First, fit the spline to the observed data. with ops.name_scope('solve'): w, v = _solve_interpolation(train_points, train_values, order, regularization_weight) # Then, evaluate the spline at the query locations. with ops.name_scope('predict'): query_values = _apply_interpolation(query_points, train_points, w, v, order) return query_values
[ "def", "interpolate_spline", "(", "train_points", ",", "train_values", ",", "query_points", ",", "order", ",", "regularization_weight", "=", "0.0", ",", "name", "=", "'interpolate_spline'", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ")", ":", "tr...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/image/python/ops/interpolate_spline.py#L225-L299
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/importlib-metadata/py3/importlib_metadata/__init__.py
python
PathDistribution.__init__
(self, path: SimplePath)
Construct a distribution. :param path: SimplePath indicating the metadata directory.
Construct a distribution.
[ "Construct", "a", "distribution", "." ]
def __init__(self, path: SimplePath): """Construct a distribution. :param path: SimplePath indicating the metadata directory. """ self._path = path
[ "def", "__init__", "(", "self", ",", "path", ":", "SimplePath", ")", ":", "self", ".", "_path", "=", "path" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/importlib-metadata/py3/importlib_metadata/__init__.py#L911-L916
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typing/npdatetime.py
python
TimedeltaDivOp.generic
(self, args, kws)
(timedelta64, {int, float}) -> timedelta64 (timedelta64, timedelta64) -> float
(timedelta64, {int, float}) -> timedelta64 (timedelta64, timedelta64) -> float
[ "(", "timedelta64", "{", "int", "float", "}", ")", "-", ">", "timedelta64", "(", "timedelta64", "timedelta64", ")", "-", ">", "float" ]
def generic(self, args, kws): """ (timedelta64, {int, float}) -> timedelta64 (timedelta64, timedelta64) -> float """ left, right = args if not isinstance(left, types.NPTimedelta): return if isinstance(right, types.NPTimedelta): if (npdatetime.can_cast_timedelta_units(left.unit, right.unit) or npdatetime.can_cast_timedelta_units(right.unit, left.unit)): return signature(types.float64, left, right) elif isinstance(right, (types.Float)): return signature(left, left, right) elif isinstance(right, (types.Integer)): # Force integer types to convert to signed because it matches # timedelta64 semantics better. return signature(left, left, types.int64)
[ "def", "generic", "(", "self", ",", "args", ",", "kws", ")", ":", "left", ",", "right", "=", "args", "if", "not", "isinstance", "(", "left", ",", "types", ".", "NPTimedelta", ")", ":", "return", "if", "isinstance", "(", "right", ",", "types", ".", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typing/npdatetime.py#L95-L112
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
modules/freetype2/src/tools/docmaker/sources.py
python
SourceBlockFormat.__init__
( self, id, start, column, end )
create a block pattern, used to recognize special documentation blocks
create a block pattern, used to recognize special documentation blocks
[ "create", "a", "block", "pattern", "used", "to", "recognize", "special", "documentation", "blocks" ]
def __init__( self, id, start, column, end ): """create a block pattern, used to recognize special documentation blocks""" self.id = id self.start = re.compile( start, re.VERBOSE ) self.column = re.compile( column, re.VERBOSE ) self.end = re.compile( end, re.VERBOSE )
[ "def", "__init__", "(", "self", ",", "id", ",", "start", ",", "column", ",", "end", ")", ":", "self", ".", "id", "=", "id", "self", ".", "start", "=", "re", ".", "compile", "(", "start", ",", "re", ".", "VERBOSE", ")", "self", ".", "column", "=...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/modules/freetype2/src/tools/docmaker/sources.py#L39-L44
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py
python
TurtleScreen.onkey
(self, fun, key)
Bind fun to key-release event of key. Arguments: fun -- a function with no arguments key -- a string: key (e.g. "a") or key-symbol (e.g. "space") In order to be able to register key-events, TurtleScreen must have focus. (See method listen.) Example (for a TurtleScreen instance named screen): >>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkey(f, "Up") >>> screen.listen() Subsequently the turtle can be moved by repeatedly pressing the up-arrow key, consequently drawing a hexagon
Bind fun to key-release event of key.
[ "Bind", "fun", "to", "key", "-", "release", "event", "of", "key", "." ]
def onkey(self, fun, key): """Bind fun to key-release event of key. Arguments: fun -- a function with no arguments key -- a string: key (e.g. "a") or key-symbol (e.g. "space") In order to be able to register key-events, TurtleScreen must have focus. (See method listen.) Example (for a TurtleScreen instance named screen): >>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkey(f, "Up") >>> screen.listen() Subsequently the turtle can be moved by repeatedly pressing the up-arrow key, consequently drawing a hexagon """ if fun is None: if key in self._keys: self._keys.remove(key) elif key not in self._keys: self._keys.append(key) self._onkey(fun, key)
[ "def", "onkey", "(", "self", ",", "fun", ",", "key", ")", ":", "if", "fun", "is", "None", ":", "if", "key", "in", "self", ".", "_keys", ":", "self", ".", "_keys", ".", "remove", "(", "key", ")", "elif", "key", "not", "in", "self", ".", "_keys",...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L1314-L1342
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/closure_linter/closure_linter/ecmametadatapass.py
python
EcmaMetaDataPass._CreateContext
(self, type)
return EcmaContext(type, self._token, self._context)
Overridable by subclasses to create the appropriate context type.
Overridable by subclasses to create the appropriate context type.
[ "Overridable", "by", "subclasses", "to", "create", "the", "appropriate", "context", "type", "." ]
def _CreateContext(self, type): """Overridable by subclasses to create the appropriate context type.""" return EcmaContext(type, self._token, self._context)
[ "def", "_CreateContext", "(", "self", ",", "type", ")", ":", "return", "EcmaContext", "(", "type", ",", "self", ".", "_token", ",", "self", ".", "_context", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/ecmametadatapass.py#L199-L201
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/dexml/fields.py
python
Field.parse_done
(self,obj)
Finalize parsing for the given object. This method is called as a simple indicator that no more data will be forthcoming. No return value is expected.
Finalize parsing for the given object.
[ "Finalize", "parsing", "for", "the", "given", "object", "." ]
def parse_done(self,obj): """Finalize parsing for the given object. This method is called as a simple indicator that no more data will be forthcoming. No return value is expected. """ pass
[ "def", "parse_done", "(", "self", ",", "obj", ")", ":", "pass" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/dexml/fields.py#L89-L95
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/lib/python/bundy/server_common/tsig_keyring.py
python
Updater.deinit
(self)
Unregister from getting updates. The object will not be usable any more after this.
Unregister from getting updates. The object will not be usable any more after this.
[ "Unregister", "from", "getting", "updates", ".", "The", "object", "will", "not", "be", "usable", "any", "more", "after", "this", "." ]
def deinit(self): """ Unregister from getting updates. The object will not be usable any more after this. """ logger.debug(logger.DBGLVL_TRACE_BASIC, PYSERVER_COMMON_TSIG_KEYRING_DEINIT) self.__session.remove_remote_config('tsig_keys')
[ "def", "deinit", "(", "self", ")", ":", "logger", ".", "debug", "(", "logger", ".", "DBGLVL_TRACE_BASIC", ",", "PYSERVER_COMMON_TSIG_KEYRING_DEINIT", ")", "self", ".", "__session", ".", "remove_remote_config", "(", "'tsig_keys'", ")" ]
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/server_common/tsig_keyring.py#L86-L93
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/graph/common_lattices.py
python
Square
(length: int, *, pbc: bool = True, **kwargs)
return Hypercube(length, pbc=pbc, n_dim=2, **kwargs)
Constructs a square lattice of side `length` Periodic boundary conditions can also be imposed Args: length: Side length of the square; must always be >=1 pbc: Whether the square should have periodic boundary conditions (in both directions) kwargs: Additional keyword arguments are passed on to the constructor of :ref:`netket.graph.Lattice`. Examples: A 10x10 square lattice with periodic boundary conditions can be constructed as follows: >>> import netket >>> g=netket.graph.Square(10, pbc=True) >>> print(g.n_nodes) 100
Constructs a square lattice of side `length` Periodic boundary conditions can also be imposed
[ "Constructs", "a", "square", "lattice", "of", "side", "length", "Periodic", "boundary", "conditions", "can", "also", "be", "imposed" ]
def Square(length: int, *, pbc: bool = True, **kwargs) -> Lattice: """Constructs a square lattice of side `length` Periodic boundary conditions can also be imposed Args: length: Side length of the square; must always be >=1 pbc: Whether the square should have periodic boundary conditions (in both directions) kwargs: Additional keyword arguments are passed on to the constructor of :ref:`netket.graph.Lattice`. Examples: A 10x10 square lattice with periodic boundary conditions can be constructed as follows: >>> import netket >>> g=netket.graph.Square(10, pbc=True) >>> print(g.n_nodes) 100 """ return Hypercube(length, pbc=pbc, n_dim=2, **kwargs)
[ "def", "Square", "(", "length", ":", "int", ",", "*", ",", "pbc", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ")", "->", "Lattice", ":", "return", "Hypercube", "(", "length", ",", "pbc", "=", "pbc", ",", "n_dim", "=", "2", ",", "*", "*",...
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/graph/common_lattices.py#L192-L212
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/python_message.py
python
_GetFieldByName
(message_descriptor, field_name)
Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name.
Returns a field descriptor by field name.
[ "Returns", "a", "field", "descriptor", "by", "field", "name", "." ]
def _GetFieldByName(message_descriptor, field_name): """Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name. """ try: return message_descriptor.fields_by_name[field_name] except KeyError: raise ValueError('Protocol message has no "%s" field.' % field_name)
[ "def", "_GetFieldByName", "(", "message_descriptor", ",", "field_name", ")", ":", "try", ":", "return", "message_descriptor", ".", "fields_by_name", "[", "field_name", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Protocol message has no \"%s\" field.'",...
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L335-L347
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPML_HANDLE.GetUnionSelector
(self)
return TPM_CAP.HANDLES
TpmUnion method
TpmUnion method
[ "TpmUnion", "method" ]
def GetUnionSelector(self): # TPM_CAP """ TpmUnion method """ return TPM_CAP.HANDLES
[ "def", "GetUnionSelector", "(", "self", ")", ":", "# TPM_CAP", "return", "TPM_CAP", ".", "HANDLES" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L4564-L4566
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/mesh.py
python
NativeMeshTag._do_op
(self, other, op)
Helper function for NativeMeshTag operators
Helper function for NativeMeshTag operators
[ "Helper", "function", "for", "NativeMeshTag", "operators" ]
def _do_op(self, other, op): """Helper function for NativeMeshTag operators""" if isinstance(other, NativeMeshTag): return self._do_native_op(other, op) elif isinstance(other, list) or isinstance(other, np.ndarray): return self._do_list_op(other, op) elif isinstance(other, int) or isinstance(other, float): return self._do_scalar_op(other, op) else: raise TypeError("Incorrect operand type provided")
[ "def", "_do_op", "(", "self", ",", "other", ",", "op", ")", ":", "if", "isinstance", "(", "other", ",", "NativeMeshTag", ")", ":", "return", "self", ".", "_do_native_op", "(", "other", ",", "op", ")", "elif", "isinstance", "(", "other", ",", "list", ...
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/mesh.py#L613-L622
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/locations.py
python
distutils_scheme
(dist_name, user=False, home=None)
return scheme
Return a distutils install scheme
Return a distutils install scheme
[ "Return", "a", "distutils", "install", "scheme" ]
def distutils_scheme(dist_name, user=False, home=None): """ Return a distutils install scheme """ from distutils.dist import Distribution scheme = {} d = Distribution({'name': dist_name}) i = install(d) i.user = user or i.user i.home = home or i.home i.finalize_options() for key in SCHEME_KEYS: scheme[key] = getattr(i, 'install_'+key) #be backward-compatible with what pip has always done? scheme['scripts'] = bin_py if running_under_virtualenv(): scheme['headers'] = os.path.join(sys.prefix, 'include', 'site', 'python' + sys.version[:3], dist_name) return scheme
[ "def", "distutils_scheme", "(", "dist_name", ",", "user", "=", "False", ",", "home", "=", "None", ")", ":", "from", "distutils", ".", "dist", "import", "Distribution", "scheme", "=", "{", "}", "d", "=", "Distribution", "(", "{", "'name'", ":", "dist_name...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/locations.py#L131-L156
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
RobotModel.getLinearMomentum
(self)
return _robotsim.RobotModel_getLinearMomentum(self)
getLinearMomentum(RobotModel self) Returns the 3D linear momentum vector.
getLinearMomentum(RobotModel self)
[ "getLinearMomentum", "(", "RobotModel", "self", ")" ]
def getLinearMomentum(self): """ getLinearMomentum(RobotModel self) Returns the 3D linear momentum vector. """ return _robotsim.RobotModel_getLinearMomentum(self)
[ "def", "getLinearMomentum", "(", "self", ")", ":", "return", "_robotsim", ".", "RobotModel_getLinearMomentum", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L4859-L4868
koth/kcws
88efbd36a7022de4e6e90f5a1fb880cf87cfae9f
third_party/setuptools/pkg_resources.py
python
parse_requirements
(strs)
Yield ``Requirement`` objects for each specification in `strs` `strs` must be an instance of ``basestring``, or a (possibly-nested) iterable thereof.
Yield ``Requirement`` objects for each specification in `strs`
[ "Yield", "Requirement", "objects", "for", "each", "specification", "in", "strs" ]
def parse_requirements(strs): """Yield ``Requirement`` objects for each specification in `strs` `strs` must be an instance of ``basestring``, or a (possibly-nested) iterable thereof. """ # create a steppable iterator, so we can handle \-continuations lines = iter(yield_lines(strs)) def scan_list(ITEM, TERMINATOR, line, p, groups, item_name): items = [] while not TERMINATOR(line, p): if CONTINUE(line, p): try: line = next(lines) p = 0 except StopIteration: raise ValueError( "\\ must not appear on the last nonblank line" ) match = ITEM(line, p) if not match: msg = "Expected " + item_name + " in" raise ValueError(msg, line, "at", line[p:]) items.append(match.group(*groups)) p = match.end() match = COMMA(line, p) if match: # skip the comma p = match.end() elif not TERMINATOR(line, p): msg = "Expected ',' or end-of-list in" raise ValueError(msg, line, "at", line[p:]) match = TERMINATOR(line, p) if match: p = match.end() # skip the terminator, if any return line, p, items for line in lines: match = DISTRO(line) if not match: raise ValueError("Missing distribution spec", line) project_name = match.group(1) p = match.end() extras = [] match = OBRACKET(line, p) if match: p = match.end() line, p, extras = scan_list( DISTRO, CBRACKET, line, p, (1,), "'extra' name" ) line, p, specs = scan_list(VERSION, LINE_END, line, p, (1, 2), "version spec") specs = [(op, safe_version(val)) for op, val in specs] yield Requirement(project_name, specs, extras)
[ "def", "parse_requirements", "(", "strs", ")", ":", "# create a steppable iterator, so we can handle \\-continuations", "lines", "=", "iter", "(", "yield_lines", "(", "strs", ")", ")", "def", "scan_list", "(", "ITEM", ",", "TERMINATOR", ",", "line", ",", "p", ",",...
https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/setuptools/pkg_resources.py#L2626-L2687
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributions/transformed_distribution.py
python
TransformedDistribution.cdf
(self, value)
return value
Computes the cumulative distribution function by inverting the transform(s) and computing the score of the base distribution.
Computes the cumulative distribution function by inverting the transform(s) and computing the score of the base distribution.
[ "Computes", "the", "cumulative", "distribution", "function", "by", "inverting", "the", "transform", "(", "s", ")", "and", "computing", "the", "score", "of", "the", "base", "distribution", "." ]
def cdf(self, value): """ Computes the cumulative distribution function by inverting the transform(s) and computing the score of the base distribution. """ for transform in self.transforms[::-1]: value = transform.inv(value) if self._validate_args: self.base_dist._validate_sample(value) value = self.base_dist.cdf(value) value = self._monotonize_cdf(value) return value
[ "def", "cdf", "(", "self", ",", "value", ")", ":", "for", "transform", "in", "self", ".", "transforms", "[", ":", ":", "-", "1", "]", ":", "value", "=", "transform", ".", "inv", "(", "value", ")", "if", "self", ".", "_validate_args", ":", "self", ...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributions/transformed_distribution.py#L165-L176
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
src/bindings/python/src/openvino/runtime/opset1/ops.py
python
reduce_logical_and
( node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None )
return _get_node_factory_opset1().create( "ReduceLogicalAnd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims} )
Logical AND reduction operation on input tensor, eliminating the specified reduction axes. @param node: The tensor we want to reduce. @param reduction_axes: The axes to eliminate through AND operation. @param keep_dims: If set to True it holds axes that are used for reduction @param name: Optional name for output node. @return The new node performing reduction operation.
Logical AND reduction operation on input tensor, eliminating the specified reduction axes.
[ "Logical", "AND", "reduction", "operation", "on", "input", "tensor", "eliminating", "the", "specified", "reduction", "axes", "." ]
def reduce_logical_and( node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None ) -> Node: """Logical AND reduction operation on input tensor, eliminating the specified reduction axes. @param node: The tensor we want to reduce. @param reduction_axes: The axes to eliminate through AND operation. @param keep_dims: If set to True it holds axes that are used for reduction @param name: Optional name for output node. @return The new node performing reduction operation. """ return _get_node_factory_opset1().create( "ReduceLogicalAnd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims} )
[ "def", "reduce_logical_and", "(", "node", ":", "NodeInput", ",", "reduction_axes", ":", "NodeInput", ",", "keep_dims", ":", "bool", "=", "False", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Node", ":", "return", "_get_node_facto...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset1/ops.py#L2241-L2254
UlordChain/UlordChain
b6288141e9744e89b1901f330c3797ff5f161d62
contrib/linearize/linearize-data.py
python
BlockDataCopier.copyOneBlock
(self)
Find the next block to be written in the input, and copy it to the output.
Find the next block to be written in the input, and copy it to the output.
[ "Find", "the", "next", "block", "to", "be", "written", "in", "the", "input", "and", "copy", "it", "to", "the", "output", "." ]
def copyOneBlock(self): '''Find the next block to be written in the input, and copy it to the output.''' extent = self.blockExtents.pop(self.blkCountOut) if self.blkCountOut in self.outOfOrderData: # If the data is cached, use it from memory and remove from the cache rawblock = self.outOfOrderData.pop(self.blkCountOut) self.outOfOrderSize -= len(rawblock) else: # Otherwise look up data on disk rawblock = self.fetchBlock(extent) self.writeBlock(extent.inhdr, extent.blkhdr, rawblock)
[ "def", "copyOneBlock", "(", "self", ")", ":", "extent", "=", "self", ".", "blockExtents", ".", "pop", "(", "self", ".", "blkCountOut", ")", "if", "self", ".", "blkCountOut", "in", "self", ".", "outOfOrderData", ":", "# If the data is cached, use it from memory a...
https://github.com/UlordChain/UlordChain/blob/b6288141e9744e89b1901f330c3797ff5f161d62/contrib/linearize/linearize-data.py#L181-L191
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/error.py
python
Error.to_dict
(self)
return result
Returns the model properties as a dict
Returns the model properties as a dict
[ "Returns", "the", "model", "properties", "as", "a", "dict" ]
def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Error, dict): for key, value in self.items(): result[key] = value return result
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "attr", ",", "_", "in", "six", ".", "iteritems", "(", "self", ".", "swagger_types", ")", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "isinstance", "(", ...
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/error.py#L72-L97
lballabio/quantlib-old
136336947ed4fea9ecc1da6edad188700e821739
gensrc/gensrc/addins/valueobjects.py
python
ValueObjects.generateHeaderInline
(self, func)
return self.bufferClassDeclInline_.set({ 'constructorDeclaration' : func.parameterList().generate( self.constructorDeclaration_), 'functionName' : func.name(), 'processorName' : processorName, 'serializeMembers' : func.parameterList().generate(self.serializeMembers_), 'memberDeclaration' : func.parameterList().generate(self.memberDeclaration_) })
Generate class definition source for prototype of given constructor function.
Generate class definition source for prototype of given constructor function.
[ "Generate", "class", "definition", "source", "for", "prototype", "of", "given", "constructor", "function", "." ]
def generateHeaderInline(self, func): """Generate class definition source for prototype of given constructor function.""" if func.processorName(): processorName = ValueObjects.PROCESSOR_NAME % { common.PROCESSOR_NAME : func.processorName() } else: processorName = "" return self.bufferClassDeclInline_.set({ 'constructorDeclaration' : func.parameterList().generate( self.constructorDeclaration_), 'functionName' : func.name(), 'processorName' : processorName, 'serializeMembers' : func.parameterList().generate(self.serializeMembers_), 'memberDeclaration' : func.parameterList().generate(self.memberDeclaration_) })
[ "def", "generateHeaderInline", "(", "self", ",", "func", ")", ":", "if", "func", ".", "processorName", "(", ")", ":", "processorName", "=", "ValueObjects", ".", "PROCESSOR_NAME", "%", "{", "common", ".", "PROCESSOR_NAME", ":", "func", ".", "processorName", "...
https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/addins/valueobjects.py#L72-L85
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py
python
EmacsMode.history_search_backward
(self, e)
Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.
Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.
[ "Search", "backward", "through", "the", "history", "for", "the", "string", "of", "characters", "between", "the", "start", "of", "the", "current", "line", "and", "the", "point", ".", "This", "is", "a", "non", "-", "incremental", "search", ".", "By", "defaul...
def history_search_backward(self, e): # () '''Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. By default, this command is unbound.''' if self.previous_func and hasattr(self._history,self.previous_func.__name__): self._history.lastcommand=getattr(self._history,self.previous_func.__name__) else: self._history.lastcommand=None q=self._history.history_search_backward(self.l_buffer) self.l_buffer=q self.l_buffer.point=q.point
[ "def", "history_search_backward", "(", "self", ",", "e", ")", ":", "# ()", "if", "self", ".", "previous_func", "and", "hasattr", "(", "self", ".", "_history", ",", "self", ".", "previous_func", ".", "__name__", ")", ":", "self", ".", "_history", ".", "la...
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py#L240-L250
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py
python
MaskedArray.argmax
(self, axis=None, fill_value=None, out=None)
return d.argmax(axis, out=out)
Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : {var}, optional Value used to fill in the masked values. If None, the output of maximum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- index_array : {integer_array} Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a.argmax() 5 >>> a.argmax(0) array([1, 1, 1]) >>> a.argmax(1) array([2, 2])
Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value.
[ "Returns", "array", "of", "indices", "of", "the", "maximum", "values", "along", "the", "given", "axis", ".", "Masked", "values", "are", "treated", "as", "if", "they", "had", "the", "value", "fill_value", "." ]
def argmax(self, axis=None, fill_value=None, out=None): """ Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : {var}, optional Value used to fill in the masked values. If None, the output of maximum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- index_array : {integer_array} Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a.argmax() 5 >>> a.argmax(0) array([1, 1, 1]) >>> a.argmax(1) array([2, 2]) """ if fill_value is None: fill_value = maximum_fill_value(self._data) d = self.filled(fill_value).view(ndarray) return d.argmax(axis, out=out)
[ "def", "argmax", "(", "self", ",", "axis", "=", "None", ",", "fill_value", "=", "None", ",", "out", "=", "None", ")", ":", "if", "fill_value", "is", "None", ":", "fill_value", "=", "maximum_fill_value", "(", "self", ".", "_data", ")", "d", "=", "self...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py#L4962-L4997
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/functools.py
python
_lt_from_le
(self, other, NotImplemented=NotImplemented)
return op_result and self != other
Return a < b. Computed by @total_ordering from (a <= b) and (a != b).
Return a < b. Computed by
[ "Return", "a", "<", "b", ".", "Computed", "by" ]
def _lt_from_le(self, other, NotImplemented=NotImplemented): 'Return a < b. Computed by @total_ordering from (a <= b) and (a != b).' op_result = self.__le__(other) if op_result is NotImplemented: return op_result return op_result and self != other
[ "def", "_lt_from_le", "(", "self", ",", "other", ",", "NotImplemented", "=", "NotImplemented", ")", ":", "op_result", "=", "self", ".", "__le__", "(", "other", ")", "if", "op_result", "is", "NotImplemented", ":", "return", "op_result", "return", "op_result", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/functools.py#L117-L122
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/message.py
python
Message.get_param
(self, param, failobj=None, header='content-type', unquote=True)
return failobj
Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 encoded. When it's a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE. Your application should be prepared to deal with 3-tuple return values, and can convert the parameter to a Unicode string like so: param = msg.get_param('foo') if isinstance(param, tuple): param = unicode(param[2], param[0] or 'us-ascii') In any case, the parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False.
Return the parameter value if found in the Content-Type header.
[ "Return", "the", "parameter", "value", "if", "found", "in", "the", "Content", "-", "Type", "header", "." ]
def get_param(self, param, failobj=None, header='content-type', unquote=True): """Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 encoded. When it's a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE. Your application should be prepared to deal with 3-tuple return values, and can convert the parameter to a Unicode string like so: param = msg.get_param('foo') if isinstance(param, tuple): param = unicode(param[2], param[0] or 'us-ascii') In any case, the parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False. """ if header not in self: return failobj for k, v in self._get_params_preserve(failobj, header): if k.lower() == param.lower(): if unquote: return _unquotevalue(v) else: return v return failobj
[ "def", "get_param", "(", "self", ",", "param", ",", "failobj", "=", "None", ",", "header", "=", "'content-type'", ",", "unquote", "=", "True", ")", ":", "if", "header", "not", "in", "self", ":", "return", "failobj", "for", "k", ",", "v", "in", "self"...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/message.py#L535-L569
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/python_message.py
python
_AddPropertiesForExtensions
(descriptor, cls)
Adds properties for all fields in this protocol message type.
Adds properties for all fields in this protocol message type.
[ "Adds", "properties", "for", "all", "fields", "in", "this", "protocol", "message", "type", "." ]
def _AddPropertiesForExtensions(descriptor, cls): """Adds properties for all fields in this protocol message type.""" extension_dict = descriptor.extensions_by_name for extension_name, extension_field in extension_dict.iteritems(): constant_name = extension_name.upper() + "_FIELD_NUMBER" setattr(cls, constant_name, extension_field.number)
[ "def", "_AddPropertiesForExtensions", "(", "descriptor", ",", "cls", ")", ":", "extension_dict", "=", "descriptor", ".", "extensions_by_name", "for", "extension_name", ",", "extension_field", "in", "extension_dict", ".", "iteritems", "(", ")", ":", "constant_name", ...
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/python_message.py#L520-L525
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py
python
unicode_set.printables
(cls)
return u''.join(filterfalse(unicode.isspace, cls._get_chars_for_ranges()))
all non-whitespace characters in this range
all non-whitespace characters in this range
[ "all", "non", "-", "whitespace", "characters", "in", "this", "range" ]
def printables(cls): "all non-whitespace characters in this range" return u''.join(filterfalse(unicode.isspace, cls._get_chars_for_ranges()))
[ "def", "printables", "(", "cls", ")", ":", "return", "u''", ".", "join", "(", "filterfalse", "(", "unicode", ".", "isspace", ",", "cls", ".", "_get_chars_for_ranges", "(", ")", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L6743-L6745
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/calendar.py
python
HTMLCalendar.formatweekheader
(self)
return '<tr>%s</tr>' % s
Return a header for a week as a table row.
Return a header for a week as a table row.
[ "Return", "a", "header", "for", "a", "week", "as", "a", "table", "row", "." ]
def formatweekheader(self): """ Return a header for a week as a table row. """ s = ''.join(self.formatweekday(i) for i in self.iterweekdays()) return '<tr>%s</tr>' % s
[ "def", "formatweekheader", "(", "self", ")", ":", "s", "=", "''", ".", "join", "(", "self", ".", "formatweekday", "(", "i", ")", "for", "i", "in", "self", ".", "iterweekdays", "(", ")", ")", "return", "'<tr>%s</tr>'", "%", "s" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/calendar.py#L402-L407
widelands/widelands
e9f047d46a23d81312237d52eabf7d74e8de52d6
utils/detect_revision.py
python
check_for_explicit_version
()
Checks for a file WL_RELEASE in the root directory. It then defaults to this version without further trying to find which revision we're on
Checks for a file WL_RELEASE in the root directory.
[ "Checks", "for", "a", "file", "WL_RELEASE", "in", "the", "root", "directory", "." ]
def check_for_explicit_version(): """Checks for a file WL_RELEASE in the root directory. It then defaults to this version without further trying to find which revision we're on """ fname = p.join(base_path, 'WL_RELEASE') if os.path.exists(fname): return open(fname).read().strip()
[ "def", "check_for_explicit_version", "(", ")", ":", "fname", "=", "p", ".", "join", "(", "base_path", ",", "'WL_RELEASE'", ")", "if", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "return", "open", "(", "fname", ")", ".", "read", "(", ")"...
https://github.com/widelands/widelands/blob/e9f047d46a23d81312237d52eabf7d74e8de52d6/utils/detect_revision.py#L75-L83
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tarfile.py
python
TarFile.makedir
(self, tarinfo, targetpath)
Make a directory called targetpath.
Make a directory called targetpath.
[ "Make", "a", "directory", "called", "targetpath", "." ]
def makedir(self, tarinfo, targetpath): """Make a directory called targetpath. """ try: # Use a safe mode for the directory, the real mode is set # later in _extract_member(). os.mkdir(targetpath, 0o700) except FileExistsError: pass
[ "def", "makedir", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "try", ":", "# Use a safe mode for the directory, the real mode is set", "# later in _extract_member().", "os", ".", "mkdir", "(", "targetpath", ",", "0o700", ")", "except", "FileExistsError", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tarfile.py#L2139-L2147
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/gcc.py
python
generate
(env)
Add Builders and construction variables for gcc to an Environment.
Add Builders and construction variables for gcc to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "gcc", "to", "an", "Environment", "." ]
def generate(env): """Add Builders and construction variables for gcc to an Environment.""" if 'CC' not in env: env['CC'] = env.Detect(compilers) or compilers[0] cc.generate(env) if env['PLATFORM'] in ['cygwin', 'win32']: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') else: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC') # determine compiler version version = detect_version(env, env['CC']) if version: env['CCVERSION'] = version
[ "def", "generate", "(", "env", ")", ":", "if", "'CC'", "not", "in", "env", ":", "env", "[", "'CC'", "]", "=", "env", ".", "Detect", "(", "compilers", ")", "or", "compilers", "[", "0", "]", "cc", ".", "generate", "(", "env", ")", "if", "env", "[...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/gcc.py#L46-L61
jubatus/jubatus
1251ce551bac980488a6313728e72b3fe0b79a9f
tools/codestyle/cpplint/cpplint.py
python
UpdateIncludeState
(filename, include_state, io=codecs)
return True
Fill up the include_state with new includes found from the file. Args: filename: the name of the header to read. include_state: an _IncludeState instance in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was succesfully added. False otherwise.
Fill up the include_state with new includes found from the file.
[ "Fill", "up", "the", "include_state", "with", "new", "includes", "found", "from", "the", "file", "." ]
def UpdateIncludeState(filename, include_state, io=codecs): """Fill up the include_state with new includes found from the file. Args: filename: the name of the header to read. include_state: an _IncludeState instance in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was succesfully added. False otherwise. """ headerfile = None try: headerfile = io.open(filename, 'r', 'utf8', 'replace') except IOError: return False linenum = 0 for line in headerfile: linenum += 1 clean_line = CleanseComments(line) match = _RE_PATTERN_INCLUDE.search(clean_line) if match: include = match.group(2) # The value formatting is cute, but not really used right now. # What matters here is that the key is in include_state. include_state.setdefault(include, '%s:%d' % (filename, linenum)) return True
[ "def", "UpdateIncludeState", "(", "filename", ",", "include_state", ",", "io", "=", "codecs", ")", ":", "headerfile", "=", "None", "try", ":", "headerfile", "=", "io", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", "excep...
https://github.com/jubatus/jubatus/blob/1251ce551bac980488a6313728e72b3fe0b79a9f/tools/codestyle/cpplint/cpplint.py#L3004-L3030
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
lldb/examples/python/crashlog.py
python
Interactive.do_quit
(self, line)
return True
Quit command
Quit command
[ "Quit", "command" ]
def do_quit(self, line): '''Quit command''' return True
[ "def", "do_quit", "(", "self", ",", "line", ")", ":", "return", "True" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/examples/python/crashlog.py#L786-L788
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/foldpanelbar.py
python
CaptionBarStyle.SetCaptionColour
(self, colour)
Sets caption colour for the caption bar. :param `colour`: a valid :class:`Colour` object. :note: If this is not set, the colour property is undefined and will not be used. Use :meth:`~CaptionBarStyle.CaptionColourUsed` to check if this style is used.
Sets caption colour for the caption bar.
[ "Sets", "caption", "colour", "for", "the", "caption", "bar", "." ]
def SetCaptionColour(self, colour): """ Sets caption colour for the caption bar. :param `colour`: a valid :class:`Colour` object. :note: If this is not set, the colour property is undefined and will not be used. Use :meth:`~CaptionBarStyle.CaptionColourUsed` to check if this style is used. """ self._textColour = colour self._textColourUsed = True
[ "def", "SetCaptionColour", "(", "self", ",", "colour", ")", ":", "self", ".", "_textColour", "=", "colour", "self", ".", "_textColourUsed", "=", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/foldpanelbar.py#L433-L444
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/retdec-3.2/scripts/type_extractor/type_extractor/func_info.py
python
FuncInfo.has_vararg
(self)
return getattr(self, 'vararg', False)
Returns True if function takes variable number of arguments, otherwise False.
Returns True if function takes variable number of arguments, otherwise False.
[ "Returns", "True", "if", "function", "takes", "variable", "number", "of", "arguments", "otherwise", "False", "." ]
def has_vararg(self): """Returns True if function takes variable number of arguments, otherwise False. """ return getattr(self, 'vararg', False)
[ "def", "has_vararg", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "'vararg'", ",", "False", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/retdec-3.2/scripts/type_extractor/type_extractor/func_info.py#L49-L53
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/google_appengine_cloudstorage/cloudstorage/api_utils.py
python
_run_until_rpc
()
Eagerly evaluate tasklets until it is blocking on some RPC. Usually ndb eventloop el isn't run until some code calls future.get_result(). When an async tasklet is called, the tasklet wrapper evaluates the tasklet code into a generator, enqueues a callback _help_tasklet_along onto the el.current queue, and returns a future. _help_tasklet_along, when called by the el, will get one yielded value from the generator. If the value if another future, set up a callback _on_future_complete to invoke _help_tasklet_along when the dependent future fulfills. If the value if a RPC, set up a callback _on_rpc_complete to invoke _help_tasklet_along when the RPC fulfills. Thus _help_tasklet_along drills down the chain of futures until some future is blocked by RPC. El runs all callbacks and constantly check pending RPC status.
Eagerly evaluate tasklets until it is blocking on some RPC.
[ "Eagerly", "evaluate", "tasklets", "until", "it", "is", "blocking", "on", "some", "RPC", "." ]
def _run_until_rpc(): """Eagerly evaluate tasklets until it is blocking on some RPC. Usually ndb eventloop el isn't run until some code calls future.get_result(). When an async tasklet is called, the tasklet wrapper evaluates the tasklet code into a generator, enqueues a callback _help_tasklet_along onto the el.current queue, and returns a future. _help_tasklet_along, when called by the el, will get one yielded value from the generator. If the value if another future, set up a callback _on_future_complete to invoke _help_tasklet_along when the dependent future fulfills. If the value if a RPC, set up a callback _on_rpc_complete to invoke _help_tasklet_along when the RPC fulfills. Thus _help_tasklet_along drills down the chain of futures until some future is blocked by RPC. El runs all callbacks and constantly check pending RPC status. """ el = eventloop.get_event_loop() while el.current: el.run0()
[ "def", "_run_until_rpc", "(", ")", ":", "el", "=", "eventloop", ".", "get_event_loop", "(", ")", "while", "el", ".", "current", ":", "el", ".", "run0", "(", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/google_appengine_cloudstorage/cloudstorage/api_utils.py#L283-L303
eerolanguage/clang
91360bee004a1cbdb95fe5eb605ef243152da41b
bindings/python/clang/cindex.py
python
TranslationUnit.get_extent
(self, filename, locations)
return SourceRange.from_locations(start_location, end_location)
Obtain a SourceRange from this translation unit. The bounds of the SourceRange must ultimately be defined by a start and end SourceLocation. For the locations argument, you can pass: - 2 SourceLocation instances in a 2-tuple or list. - 2 int file offsets via a 2-tuple or list. - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. e.g. get_extent('foo.c', (5, 10)) get_extent('foo.c', ((1, 1), (1, 15)))
Obtain a SourceRange from this translation unit.
[ "Obtain", "a", "SourceRange", "from", "this", "translation", "unit", "." ]
def get_extent(self, filename, locations): """Obtain a SourceRange from this translation unit. The bounds of the SourceRange must ultimately be defined by a start and end SourceLocation. For the locations argument, you can pass: - 2 SourceLocation instances in a 2-tuple or list. - 2 int file offsets via a 2-tuple or list. - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. e.g. get_extent('foo.c', (5, 10)) get_extent('foo.c', ((1, 1), (1, 15))) """ f = self.get_file(filename) if len(locations) < 2: raise Exception('Must pass object with at least 2 elements') start_location, end_location = locations if hasattr(start_location, '__len__'): start_location = SourceLocation.from_position(self, f, start_location[0], start_location[1]) elif isinstance(start_location, int): start_location = SourceLocation.from_offset(self, f, start_location) if hasattr(end_location, '__len__'): end_location = SourceLocation.from_position(self, f, end_location[0], end_location[1]) elif isinstance(end_location, int): end_location = SourceLocation.from_offset(self, f, end_location) assert isinstance(start_location, SourceLocation) assert isinstance(end_location, SourceLocation) return SourceRange.from_locations(start_location, end_location)
[ "def", "get_extent", "(", "self", ",", "filename", ",", "locations", ")", ":", "f", "=", "self", ".", "get_file", "(", "filename", ")", "if", "len", "(", "locations", ")", "<", "2", ":", "raise", "Exception", "(", "'Must pass object with at least 2 elements'...
https://github.com/eerolanguage/clang/blob/91360bee004a1cbdb95fe5eb605ef243152da41b/bindings/python/clang/cindex.py#L2272-L2310
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_py_abc.py
python
ABCMeta._abc_registry_clear
(cls)
Clear the registry (for debugging or testing).
Clear the registry (for debugging or testing).
[ "Clear", "the", "registry", "(", "for", "debugging", "or", "testing", ")", "." ]
def _abc_registry_clear(cls): """Clear the registry (for debugging or testing).""" cls._abc_registry.clear()
[ "def", "_abc_registry_clear", "(", "cls", ")", ":", "cls", ".", "_abc_registry", ".", "clear", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_py_abc.py#L83-L85
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/parse/standard_method.py
python
ms_next
(it)
return it.__ms_next__()
Implementation of `next`.
Implementation of `next`.
[ "Implementation", "of", "next", "." ]
def ms_next(it): """Implementation of `next`.""" return it.__ms_next__()
[ "def", "ms_next", "(", "it", ")", ":", "return", "it", ".", "__ms_next__", "(", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parse/standard_method.py#L1433-L1435
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/network/networkxtools.py
python
Footpath.get_priority
(self, is_opp=False)
return 1
Returns priority of road. To be overridden.
Returns priority of road.
[ "Returns", "priority", "of", "road", "." ]
def get_priority(self, is_opp=False): """ Returns priority of road. To be overridden. """ if is_opp: lanes = self._lanes_opp else: lanes = self._lanes speed_max = self.get_speed_max() n_lane = len(lanes) return 1
[ "def", "get_priority", "(", "self", ",", "is_opp", "=", "False", ")", ":", "if", "is_opp", ":", "lanes", "=", "self", ".", "_lanes_opp", "else", ":", "lanes", "=", "self", ".", "_lanes", "speed_max", "=", "self", ".", "get_speed_max", "(", ")", "n_lane...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/network/networkxtools.py#L2177-L2190
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ipaddress.py
python
_find_address_range
(addresses)
Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence.
Find a sequence of sorted deduplicated IPv#Address.
[ "Find", "a", "sequence", "of", "sorted", "deduplicated", "IPv#Address", "." ]
def _find_address_range(addresses): """Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence. """ it = iter(addresses) first = last = next(it) for ip in it: if ip._ip != last._ip + 1: yield first, last first = ip last = ip yield first, last
[ "def", "_find_address_range", "(", "addresses", ")", ":", "it", "=", "iter", "(", "addresses", ")", "first", "=", "last", "=", "next", "(", "it", ")", "for", "ip", "in", "it", ":", "if", "ip", ".", "_ip", "!=", "last", ".", "_ip", "+", "1", ":", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ipaddress.py#L166-L183
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_parser.py
python
p_scentranss_scentranss_places_arrow_places_colon_scenariomixin
(p)
scentranss : scentranss places ARROW places COLON scenariomixin
scentranss : scentranss places ARROW places COLON scenariomixin
[ "scentranss", ":", "scentranss", "places", "ARROW", "places", "COLON", "scenariomixin" ]
def p_scentranss_scentranss_places_arrow_places_colon_scenariomixin(p): 'scentranss : scentranss places ARROW places COLON scenariomixin' p[0] = p[1] tr = ScenarioTransition(PlaceList(*p[2]),PlaceList(*p[4]),p[6]) tr.lineno = get_lineno(p,5) p[0].append(tr)
[ "def", "p_scentranss_scentranss_places_arrow_places_colon_scenariomixin", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "tr", "=", "ScenarioTransition", "(", "PlaceList", "(", "*", "p", "[", "2", "]", ")", ",", "PlaceList", "(", "*", "...
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L1984-L1989
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/signaltools.py
python
correlate
(in1, in2, mode='full', method='auto')
r""" Cross-correlate two N-dimensional arrays. Cross-correlate `in1` and `in2`, with the output size determined by the `mode` argument. Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear cross-correlation of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. In 'valid' mode, either `in1` or `in2` must be at least as large as the other in every dimension. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. method : str {'auto', 'direct', 'fft'}, optional A string indicating which method to use to calculate the correlation. ``direct`` The correlation is determined directly from sums, the definition of correlation. ``fft`` The Fast Fourier Transform is used to perform the correlation more quickly (only available for numerical arrays.) ``auto`` Automatically chooses direct or Fourier method based on an estimate of which is faster (default). See `convolve` Notes for more detail. .. versionadded:: 0.19.0 Returns ------- correlate : array An N-dimensional array containing a subset of the discrete linear cross-correlation of `in1` with `in2`. See Also -------- choose_conv_method : contains more documentation on `method`. Notes ----- The correlation z of two d-dimensional arrays x and y is defined as:: z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...]) This way, if x and y are 1-D arrays and ``z = correlate(x, y, 'full')`` then .. math:: z[k] = (x * y)(k - N + 1) = \sum_{l=0}^{||x||-1}x_l y_{l-k+N-1}^{*} for :math:`k = 0, 1, ..., ||x|| + ||y|| - 2` where :math:`||x||` is the length of ``x``, :math:`N = \max(||x||,||y||)`, and :math:`y_m` is 0 when m is outside the range of y. ``method='fft'`` only works for numerical arrays as it relies on `fftconvolve`. In certain cases (i.e., arrays of objects or when rounding integers can lose precision), ``method='direct'`` is always used. Examples -------- Implement a matched filter using cross-correlation, to recover a signal that has passed through a noisy channel. >>> from scipy import signal >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128) >>> sig_noise = sig + np.random.randn(len(sig)) >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128 >>> import matplotlib.pyplot as plt >>> clock = np.arange(64, len(sig), 128) >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True) >>> ax_orig.plot(sig) >>> ax_orig.plot(clock, sig[clock], 'ro') >>> ax_orig.set_title('Original signal') >>> ax_noise.plot(sig_noise) >>> ax_noise.set_title('Signal with noise') >>> ax_corr.plot(corr) >>> ax_corr.plot(clock, corr[clock], 'ro') >>> ax_corr.axhline(0.5, ls=':') >>> ax_corr.set_title('Cross-correlated with rectangular pulse') >>> ax_orig.margins(0, 0.1) >>> fig.tight_layout() >>> fig.show()
r""" Cross-correlate two N-dimensional arrays.
[ "r", "Cross", "-", "correlate", "two", "N", "-", "dimensional", "arrays", "." ]
def correlate(in1, in2, mode='full', method='auto'): r""" Cross-correlate two N-dimensional arrays. Cross-correlate `in1` and `in2`, with the output size determined by the `mode` argument. Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear cross-correlation of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. In 'valid' mode, either `in1` or `in2` must be at least as large as the other in every dimension. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. method : str {'auto', 'direct', 'fft'}, optional A string indicating which method to use to calculate the correlation. ``direct`` The correlation is determined directly from sums, the definition of correlation. ``fft`` The Fast Fourier Transform is used to perform the correlation more quickly (only available for numerical arrays.) ``auto`` Automatically chooses direct or Fourier method based on an estimate of which is faster (default). See `convolve` Notes for more detail. .. versionadded:: 0.19.0 Returns ------- correlate : array An N-dimensional array containing a subset of the discrete linear cross-correlation of `in1` with `in2`. See Also -------- choose_conv_method : contains more documentation on `method`. Notes ----- The correlation z of two d-dimensional arrays x and y is defined as:: z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...]) This way, if x and y are 1-D arrays and ``z = correlate(x, y, 'full')`` then .. math:: z[k] = (x * y)(k - N + 1) = \sum_{l=0}^{||x||-1}x_l y_{l-k+N-1}^{*} for :math:`k = 0, 1, ..., ||x|| + ||y|| - 2` where :math:`||x||` is the length of ``x``, :math:`N = \max(||x||,||y||)`, and :math:`y_m` is 0 when m is outside the range of y. ``method='fft'`` only works for numerical arrays as it relies on `fftconvolve`. In certain cases (i.e., arrays of objects or when rounding integers can lose precision), ``method='direct'`` is always used. Examples -------- Implement a matched filter using cross-correlation, to recover a signal that has passed through a noisy channel. >>> from scipy import signal >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128) >>> sig_noise = sig + np.random.randn(len(sig)) >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128 >>> import matplotlib.pyplot as plt >>> clock = np.arange(64, len(sig), 128) >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True) >>> ax_orig.plot(sig) >>> ax_orig.plot(clock, sig[clock], 'ro') >>> ax_orig.set_title('Original signal') >>> ax_noise.plot(sig_noise) >>> ax_noise.set_title('Signal with noise') >>> ax_corr.plot(corr) >>> ax_corr.plot(clock, corr[clock], 'ro') >>> ax_corr.axhline(0.5, ls=':') >>> ax_corr.set_title('Cross-correlated with rectangular pulse') >>> ax_orig.margins(0, 0.1) >>> fig.tight_layout() >>> fig.show() """ in1 = asarray(in1) in2 = asarray(in2) if in1.ndim == in2.ndim == 0: return in1 * in2.conj() elif in1.ndim != in2.ndim: raise ValueError("in1 and in2 should have the same dimensionality") # Don't use _valfrommode, since correlate should not accept numeric modes try: val = _modedict[mode] except KeyError: raise ValueError("Acceptable mode flags are 'valid'," " 'same', or 'full'.") # this either calls fftconvolve or this function with method=='direct' if method in ('fft', 'auto'): return convolve(in1, _reverse_and_conj(in2), mode, method) elif method == 'direct': # fastpath to faster numpy.correlate for 1d inputs when possible if _np_conv_ok(in1, in2, mode): return np.correlate(in1, in2, mode) # _correlateND is far slower when in2.size > in1.size, so swap them # and then undo the effect afterward if mode == 'full'. Also, it fails # with 'valid' mode if in2 is larger than in1, so swap those, too. # Don't swap inputs for 'same' mode, since shape of in1 matters. swapped_inputs = ((mode == 'full') and (in2.size > in1.size) or _inputs_swap_needed(mode, in1.shape, in2.shape)) if swapped_inputs: in1, in2 = in2, in1 if mode == 'valid': ps = [i - j + 1 for i, j in zip(in1.shape, in2.shape)] out = np.empty(ps, in1.dtype) z = sigtools._correlateND(in1, in2, out, val) else: ps = [i + j - 1 for i, j in zip(in1.shape, in2.shape)] # zero pad input in1zpadded = np.zeros(ps, in1.dtype) sc = tuple(slice(0, i) for i in in1.shape) in1zpadded[sc] = in1.copy() if mode == 'full': out = np.empty(ps, in1.dtype) elif mode == 'same': out = np.empty(in1.shape, in1.dtype) z = sigtools._correlateND(in1zpadded, in2, out, val) if swapped_inputs: # Reverse and conjugate to undo the effect of swapping inputs z = _reverse_and_conj(z) return z else: raise ValueError("Acceptable method flags are 'auto'," " 'direct', or 'fft'.")
[ "def", "correlate", "(", "in1", ",", "in2", ",", "mode", "=", "'full'", ",", "method", "=", "'auto'", ")", ":", "in1", "=", "asarray", "(", "in1", ")", "in2", "=", "asarray", "(", "in2", ")", "if", "in1", ".", "ndim", "==", "in2", ".", "ndim", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/signaltools.py#L105-L269
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
Group.CreateMDArray
(self, *args)
return _gdal.Group_CreateMDArray(self, *args)
r"""CreateMDArray(Group self, char const * name, int nDimensions, ExtendedDataType data_type, char ** options=None) -> MDArray
r"""CreateMDArray(Group self, char const * name, int nDimensions, ExtendedDataType data_type, char ** options=None) -> MDArray
[ "r", "CreateMDArray", "(", "Group", "self", "char", "const", "*", "name", "int", "nDimensions", "ExtendedDataType", "data_type", "char", "**", "options", "=", "None", ")", "-", ">", "MDArray" ]
def CreateMDArray(self, *args): r"""CreateMDArray(Group self, char const * name, int nDimensions, ExtendedDataType data_type, char ** options=None) -> MDArray""" return _gdal.Group_CreateMDArray(self, *args)
[ "def", "CreateMDArray", "(", "self", ",", "*", "args", ")", ":", "return", "_gdal", ".", "Group_CreateMDArray", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L2651-L2653
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/clang/tools/scan-build-py/libscanbuild/arguments.py
python
create_intercept_parser
()
return parser
Creates a parser for command-line arguments to 'intercept'.
Creates a parser for command-line arguments to 'intercept'.
[ "Creates", "a", "parser", "for", "command", "-", "line", "arguments", "to", "intercept", "." ]
def create_intercept_parser(): """ Creates a parser for command-line arguments to 'intercept'. """ parser = create_default_parser() parser_add_cdb(parser) parser_add_prefer_wrapper(parser) parser_add_compilers(parser) advanced = parser.add_argument_group('advanced options') group = advanced.add_mutually_exclusive_group() group.add_argument( '--append', action='store_true', help="""Extend existing compilation database with new entries. Duplicate entries are detected and not present in the final output. The output is not continuously updated, it's done when the build command finished. """) parser.add_argument( dest='build', nargs=argparse.REMAINDER, help="""Command to run.""") return parser
[ "def", "create_intercept_parser", "(", ")", ":", "parser", "=", "create_default_parser", "(", ")", "parser_add_cdb", "(", "parser", ")", "parser_add_prefer_wrapper", "(", "parser", ")", "parser_add_compilers", "(", "parser", ")", "advanced", "=", "parser", ".", "a...
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/tools/scan-build-py/libscanbuild/arguments.py#L143-L164
genn-team/genn
75e1eb218cafa228bf36ae4613d1ce26e877b12c
pygenn/genn_groups.py
python
NeuronGroup.push_current_spike_events_to_device
(self)
Wrapper around GeNNModel.push_current_spike_events_to_device
Wrapper around GeNNModel.push_current_spike_events_to_device
[ "Wrapper", "around", "GeNNModel", ".", "push_current_spike_events_to_device" ]
def push_current_spike_events_to_device(self): """Wrapper around GeNNModel.push_current_spike_events_to_device""" self._model.push_current_spike_events_to_device(self.name)
[ "def", "push_current_spike_events_to_device", "(", "self", ")", ":", "self", ".", "_model", ".", "push_current_spike_events_to_device", "(", "self", ".", "name", ")" ]
https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_groups.py#L481-L483
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/cpplint.py
python
_SetVerboseLevel
(level)
return _cpplint_state.SetVerboseLevel(level)
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level)
[ "def", "_SetVerboseLevel", "(", "level", ")", ":", "return", "_cpplint_state", ".", "SetVerboseLevel", "(", "level", ")" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/cpplint.py#L861-L863
wywu/LAB
4b6debd302ae109fd104d4dd04dccc3418ae7471
python/caffe/io.py
python
array_to_datum
(arr, label=None)
return datum
Converts a 3-dimensional array to datum. If the array has dtype uint8, the output data will be encoded as a string. Otherwise, the output data will be stored in float format.
Converts a 3-dimensional array to datum. If the array has dtype uint8, the output data will be encoded as a string. Otherwise, the output data will be stored in float format.
[ "Converts", "a", "3", "-", "dimensional", "array", "to", "datum", ".", "If", "the", "array", "has", "dtype", "uint8", "the", "output", "data", "will", "be", "encoded", "as", "a", "string", ".", "Otherwise", "the", "output", "data", "will", "be", "stored"...
def array_to_datum(arr, label=None): """Converts a 3-dimensional array to datum. If the array has dtype uint8, the output data will be encoded as a string. Otherwise, the output data will be stored in float format. """ if arr.ndim != 3: raise ValueError('Incorrect array shape.') datum = caffe_pb2.Datum() datum.channels, datum.height, datum.width = arr.shape if arr.dtype == np.uint8: datum.data = arr.tostring() else: datum.float_data.extend(arr.astype(float).flat) if label is not None: datum.label = label return datum
[ "def", "array_to_datum", "(", "arr", ",", "label", "=", "None", ")", ":", "if", "arr", ".", "ndim", "!=", "3", ":", "raise", "ValueError", "(", "'Incorrect array shape.'", ")", "datum", "=", "caffe_pb2", ".", "Datum", "(", ")", "datum", ".", "channels", ...
https://github.com/wywu/LAB/blob/4b6debd302ae109fd104d4dd04dccc3418ae7471/python/caffe/io.py#L66-L81
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
samples/networking/05-small-chat/AIRepository.py
python
AIRepository.connectFailure
(self, statusCode, statusString)
something went wrong
something went wrong
[ "something", "went", "wrong" ]
def connectFailure(self, statusCode, statusString): """ something went wrong """ print("Couldn't connect. Make sure to run server.py first!") raise(StandardError, statusString)
[ "def", "connectFailure", "(", "self", ",", "statusCode", ",", "statusString", ")", ":", "print", "(", "\"Couldn't connect. Make sure to run server.py first!\"", ")", "raise", "(", "StandardError", ",", "statusString", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/samples/networking/05-small-chat/AIRepository.py#L41-L44
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py
python
safe_version
(version)
Convert an arbitrary string to a standard version string
Convert an arbitrary string to a standard version string
[ "Convert", "an", "arbitrary", "string", "to", "a", "standard", "version", "string" ]
def safe_version(version): """ Convert an arbitrary string to a standard version string """ try: # normalize the version return str(packaging.version.Version(version)) except packaging.version.InvalidVersion: version = version.replace(' ', '.') return re.sub('[^A-Za-z0-9.]+', '-', version)
[ "def", "safe_version", "(", "version", ")", ":", "try", ":", "# normalize the version", "return", "str", "(", "packaging", ".", "version", ".", "Version", "(", "version", ")", ")", "except", "packaging", ".", "version", ".", "InvalidVersion", ":", "version", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L1327-L1336
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/npyio.py
python
save
(file, arr)
Save an array to a binary file in NumPy ``.npy`` format. Parameters ---------- file : file or str File or filename to which the data is saved. If file is a file-object, then the filename is unchanged. If file is a string, a ``.npy`` extension will be appended to the file name if it does not already have one. arr : array_like Array data to be saved. See Also -------- savez : Save several arrays into a ``.npz`` archive savetxt, load Notes ----- For a description of the ``.npy`` format, see `format`. Examples -------- >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> np.save(outfile, x) >>> outfile.seek(0) # Only needed here to simulate closing & reopening file >>> np.load(outfile) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Save an array to a binary file in NumPy ``.npy`` format.
[ "Save", "an", "array", "to", "a", "binary", "file", "in", "NumPy", ".", "npy", "format", "." ]
def save(file, arr): """ Save an array to a binary file in NumPy ``.npy`` format. Parameters ---------- file : file or str File or filename to which the data is saved. If file is a file-object, then the filename is unchanged. If file is a string, a ``.npy`` extension will be appended to the file name if it does not already have one. arr : array_like Array data to be saved. See Also -------- savez : Save several arrays into a ``.npz`` archive savetxt, load Notes ----- For a description of the ``.npy`` format, see `format`. Examples -------- >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> np.save(outfile, x) >>> outfile.seek(0) # Only needed here to simulate closing & reopening file >>> np.load(outfile) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) """ own_fid = False if isinstance(file, basestring): if not file.endswith('.npy'): file = file + '.npy' fid = open(file, "wb") own_fid = True else: fid = file try: arr = np.asanyarray(arr) format.write_array(fid, arr) finally: if own_fid: fid.close()
[ "def", "save", "(", "file", ",", "arr", ")", ":", "own_fid", "=", "False", "if", "isinstance", "(", "file", ",", "basestring", ")", ":", "if", "not", "file", ".", "endswith", "(", "'.npy'", ")", ":", "file", "=", "file", "+", "'.npy'", "fid", "=", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/npyio.py#L406-L456
genn-team/genn
75e1eb218cafa228bf36ae4613d1ce26e877b12c
pygenn/genn_groups.py
python
CustomUpdate._synapse_group
(self)
return next(itervalues(self.var_refs))[1]
Get SynapseGroup associated with custom weight update
Get SynapseGroup associated with custom weight update
[ "Get", "SynapseGroup", "associated", "with", "custom", "weight", "update" ]
def _synapse_group(self): """Get SynapseGroup associated with custom weight update""" assert self.custom_wu_update # Return Python synapse group reference from # first (arbitrarily) variable reference return next(itervalues(self.var_refs))[1]
[ "def", "_synapse_group", "(", "self", ")", ":", "assert", "self", ".", "custom_wu_update", "# Return Python synapse group reference from ", "# first (arbitrarily) variable reference", "return", "next", "(", "itervalues", "(", "self", ".", "var_refs", ")", ")", "[", "1",...
https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_groups.py#L1577-L1583
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/loaders.py
python
instance_cache
(func)
return _wrapper
Cache the result of a method on a per instance basis. This is not a general purpose caching decorator. In order for this to be used, it must be used on methods on an instance, and that instance *must* provide a ``self._cache`` dictionary.
Cache the result of a method on a per instance basis.
[ "Cache", "the", "result", "of", "a", "method", "on", "a", "per", "instance", "basis", "." ]
def instance_cache(func): """Cache the result of a method on a per instance basis. This is not a general purpose caching decorator. In order for this to be used, it must be used on methods on an instance, and that instance *must* provide a ``self._cache`` dictionary. """ def _wrapper(self, *args, **kwargs): key = (func.__name__,) + args for pair in sorted(kwargs.items()): key += pair if key in self._cache: return self._cache[key] data = func(self, *args, **kwargs) self._cache[key] = data return data return _wrapper
[ "def", "instance_cache", "(", "func", ")", ":", "def", "_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "(", "func", ".", "__name__", ",", ")", "+", "args", "for", "pair", "in", "sorted", "(", "kwargs", "....
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/loaders.py#L117-L135
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/math_ops.py
python
_SparseSegmentReductionShape
(op)
return [tensor_shape.TensorShape([None]).concatenate(data_shape[1:])]
Common shape function for sparse segment reduction ops.
Common shape function for sparse segment reduction ops.
[ "Common", "shape", "function", "for", "sparse", "segment", "reduction", "ops", "." ]
def _SparseSegmentReductionShape(op): """Common shape function for sparse segment reduction ops.""" data_shape = op.inputs[0].get_shape() indices_shape = op.inputs[1].get_shape() indices_shape.assert_has_rank(1) segment_ids_shape = op.inputs[2].get_shape() segment_ids_shape.assert_has_rank(1) indices_shape.assert_is_compatible_with(segment_ids_shape) return [tensor_shape.TensorShape([None]).concatenate(data_shape[1:])]
[ "def", "_SparseSegmentReductionShape", "(", "op", ")", ":", "data_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", "indices_shape", "=", "op", ".", "inputs", "[", "1", "]", ".", "get_shape", "(", ")", "indices_shape", ".", "...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L1943-L1951
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/codecs.py
python
getdecoder
(encoding)
return lookup(encoding).decode
Lookup up the codec for the given encoding and return its decoder function. Raises a LookupError in case the encoding cannot be found.
Lookup up the codec for the given encoding and return its decoder function.
[ "Lookup", "up", "the", "codec", "for", "the", "given", "encoding", "and", "return", "its", "decoder", "function", "." ]
def getdecoder(encoding): """ Lookup up the codec for the given encoding and return its decoder function. Raises a LookupError in case the encoding cannot be found. """ return lookup(encoding).decode
[ "def", "getdecoder", "(", "encoding", ")", ":", "return", "lookup", "(", "encoding", ")", ".", "decode" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/codecs.py#L966-L974
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3util.py
python
exact_one_model
(f)
return True if f has exactly 1 model, False otherwise. EXAMPLES: >>> x, y = Ints('x y') >>> exact_one_model(And(0<=x**y,x <= 0)) False >>> exact_one_model(And(0<=x,x <= 0)) True >>> exact_one_model(And(0<=x,x <= 1)) False >>> exact_one_model(And(0<=x,x <= -1)) False
return True if f has exactly 1 model, False otherwise.
[ "return", "True", "if", "f", "has", "exactly", "1", "model", "False", "otherwise", "." ]
def exact_one_model(f): """ return True if f has exactly 1 model, False otherwise. EXAMPLES: >>> x, y = Ints('x y') >>> exact_one_model(And(0<=x**y,x <= 0)) False >>> exact_one_model(And(0<=x,x <= 0)) True >>> exact_one_model(And(0<=x,x <= 1)) False >>> exact_one_model(And(0<=x,x <= -1)) False """ models = get_models(f, k=2) if isinstance(models, list): return len(models) == 1 else: return False
[ "def", "exact_one_model", "(", "f", ")", ":", "models", "=", "get_models", "(", "f", ",", "k", "=", "2", ")", "if", "isinstance", "(", "models", ",", "list", ")", ":", "return", "len", "(", "models", ")", "==", "1", "else", ":", "return", "False" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3util.py#L384-L408
zeakey/DeepSkeleton
dc70170f8fd2ec8ca1157484ce66129981104486
scripts/cpp_lint.py
python
_NestingState.SeenOpenBrace
(self)
return (not self.stack) or self.stack[-1].seen_open_brace
Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace.
Check if we have seen the opening brace for the innermost block.
[ "Check", "if", "we", "have", "seen", "the", "opening", "brace", "for", "the", "innermost", "block", "." ]
def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace
[ "def", "SeenOpenBrace", "(", "self", ")", ":", "return", "(", "not", "self", ".", "stack", ")", "or", "self", ".", "stack", "[", "-", "1", "]", ".", "seen_open_brace" ]
https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/scripts/cpp_lint.py#L1931-L1938
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/errors_impl.py
python
_compact_stack_trace
(op)
return compact_traces
Returns a traceback for `op` with common file prefixes stripped.
Returns a traceback for `op` with common file prefixes stripped.
[ "Returns", "a", "traceback", "for", "op", "with", "common", "file", "prefixes", "stripped", "." ]
def _compact_stack_trace(op): """Returns a traceback for `op` with common file prefixes stripped.""" compact_traces = [] common_prefix = error_interpolation.traceback_files_common_prefix([[op]]) for frame in op.traceback: frame = list(frame) filename = frame[tf_stack.TB_FILENAME] if filename.startswith(common_prefix): filename = filename[len(common_prefix):] frame[tf_stack.TB_FILENAME] = filename compact_traces.append(tuple(frame)) return compact_traces
[ "def", "_compact_stack_trace", "(", "op", ")", ":", "compact_traces", "=", "[", "]", "common_prefix", "=", "error_interpolation", ".", "traceback_files_common_prefix", "(", "[", "[", "op", "]", "]", ")", "for", "frame", "in", "op", ".", "traceback", ":", "fr...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/errors_impl.py#L35-L46
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Spinbox.delete
(self, first, last=None)
return self.tk.call(self._w, 'delete', first, last)
Delete one or more elements of the spinbox. First is the index of the first character to delete, and last is the index of the character just after the last one to delete. If last isn't specified it defaults to first+1, i.e. a single character is deleted. This command returns an empty string.
Delete one or more elements of the spinbox.
[ "Delete", "one", "or", "more", "elements", "of", "the", "spinbox", "." ]
def delete(self, first, last=None): """Delete one or more elements of the spinbox. First is the index of the first character to delete, and last is the index of the character just after the last one to delete. If last isn't specified it defaults to first+1, i.e. a single character is deleted. This command returns an empty string. """ return self.tk.call(self._w, 'delete', first, last)
[ "def", "delete", "(", "self", ",", "first", ",", "last", "=", "None", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'delete'", ",", "first", ",", "last", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3416-L3425
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/gyp/pylib/gyp/generator/msvs.py
python
_GetOutputTargetExt
(spec)
return None
Returns the extension for this target, including the dot If product_extension is specified, set target_extension to this to avoid MSB8012, returns None otherwise. Ignores any target_extension settings in the input files. Arguments: spec: The target dictionary containing the properties of the target. Returns: A string with the extension, or None
Returns the extension for this target, including the dot
[ "Returns", "the", "extension", "for", "this", "target", "including", "the", "dot" ]
def _GetOutputTargetExt(spec): """Returns the extension for this target, including the dot If product_extension is specified, set target_extension to this to avoid MSB8012, returns None otherwise. Ignores any target_extension settings in the input files. Arguments: spec: The target dictionary containing the properties of the target. Returns: A string with the extension, or None """ target_extension = spec.get("product_extension") if target_extension: return "." + target_extension return None
[ "def", "_GetOutputTargetExt", "(", "spec", ")", ":", "target_extension", "=", "spec", ".", "get", "(", "\"product_extension\"", ")", "if", "target_extension", ":", "return", "\".\"", "+", "target_extension", "return", "None" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/generator/msvs.py#L1355-L1370
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/core/_internal.py
python
_add_trailing_padding
(value, padding)
return dtype(field_spec)
Inject the specified number of padding bytes at the end of a dtype
Inject the specified number of padding bytes at the end of a dtype
[ "Inject", "the", "specified", "number", "of", "padding", "bytes", "at", "the", "end", "of", "a", "dtype" ]
def _add_trailing_padding(value, padding): """Inject the specified number of padding bytes at the end of a dtype""" if value.fields is None: field_spec = dict( names=['f0'], formats=[value], offsets=[0], itemsize=value.itemsize ) else: fields = value.fields names = value.names field_spec = dict( names=names, formats=[fields[name][0] for name in names], offsets=[fields[name][1] for name in names], itemsize=value.itemsize ) field_spec['itemsize'] += padding return dtype(field_spec)
[ "def", "_add_trailing_padding", "(", "value", ",", "padding", ")", ":", "if", "value", ".", "fields", "is", "None", ":", "field_spec", "=", "dict", "(", "names", "=", "[", "'f0'", "]", ",", "formats", "=", "[", "value", "]", ",", "offsets", "=", "[",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/_internal.py#L759-L779
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/tix.py
python
Grid.anchor_set
(self, x, y)
Set the selection anchor to the cell at (x, y).
Set the selection anchor to the cell at (x, y).
[ "Set", "the", "selection", "anchor", "to", "the", "cell", "at", "(", "x", "y", ")", "." ]
def anchor_set(self, x, y): """Set the selection anchor to the cell at (x, y).""" self.tk.call(self, 'anchor', 'set', x, y)
[ "def", "anchor_set", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ",", "'anchor'", ",", "'set'", ",", "x", ",", "y", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/tix.py#L1805-L1807
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar.iterkeys
(self)
Dict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems().
Dict-like iterkeys() that returns an iterator of names of cookies
[ "Dict", "-", "like", "iterkeys", "()", "that", "returns", "an", "iterator", "of", "names", "of", "cookies" ]
def iterkeys(self): """Dict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems(). """ for cookie in iter(self): yield cookie.name
[ "def", "iterkeys", "(", "self", ")", ":", "for", "cookie", "in", "iter", "(", "self", ")", ":", "yield", "cookie", ".", "name" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/cookies.py#L435-L449
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/_config/localization.py
python
get_locales
(prefix=None, normalize=True, locale_getter=_default_locale_getter)
return _valid_locales(found, normalize)
Get all the locales that are available on the system. Parameters ---------- prefix : str If not ``None`` then return only those locales with the prefix provided. For example to get all English language locales (those that start with ``"en"``), pass ``prefix="en"``. normalize : bool Call ``locale.normalize`` on the resulting list of available locales. If ``True``, only locales that can be set without throwing an ``Exception`` are returned. locale_getter : callable The function to use to retrieve the current locales. This should return a string with each locale separated by a newline character. Returns ------- locales : list of strings A list of locale strings that can be set with ``locale.setlocale()``. For example:: locale.setlocale(locale.LC_ALL, locale_string) On error will return None (no locale available, e.g. Windows)
Get all the locales that are available on the system.
[ "Get", "all", "the", "locales", "that", "are", "available", "on", "the", "system", "." ]
def get_locales(prefix=None, normalize=True, locale_getter=_default_locale_getter): """ Get all the locales that are available on the system. Parameters ---------- prefix : str If not ``None`` then return only those locales with the prefix provided. For example to get all English language locales (those that start with ``"en"``), pass ``prefix="en"``. normalize : bool Call ``locale.normalize`` on the resulting list of available locales. If ``True``, only locales that can be set without throwing an ``Exception`` are returned. locale_getter : callable The function to use to retrieve the current locales. This should return a string with each locale separated by a newline character. Returns ------- locales : list of strings A list of locale strings that can be set with ``locale.setlocale()``. For example:: locale.setlocale(locale.LC_ALL, locale_string) On error will return None (no locale available, e.g. Windows) """ try: raw_locales = locale_getter() except subprocess.CalledProcessError: # Raised on (some? all?) Windows platforms because Note: "locale -a" # is not defined return None try: # raw_locales is "\n" separated list of locales # it may contain non-decodable parts, so split # extract what we can and then rejoin. raw_locales = raw_locales.split(b"\n") out_locales = [] for x in raw_locales: try: out_locales.append(str(x, encoding=options.display.encoding)) except UnicodeError: # 'locale -a' is used to populated 'raw_locales' and on # Redhat 7 Linux (and maybe others) prints locale names # using windows-1252 encoding. Bug only triggered by # a few special characters and when there is an # extensive list of installed locales. out_locales.append(str(x, encoding="windows-1252")) except TypeError: pass if prefix is None: return _valid_locales(out_locales, normalize) pattern = re.compile(f"{prefix}.*") found = pattern.findall("\n".join(out_locales)) return _valid_locales(found, normalize)
[ "def", "get_locales", "(", "prefix", "=", "None", ",", "normalize", "=", "True", ",", "locale_getter", "=", "_default_locale_getter", ")", ":", "try", ":", "raw_locales", "=", "locale_getter", "(", ")", "except", "subprocess", ".", "CalledProcessError", ":", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/_config/localization.py#L105-L166
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/utils.py
python
should_bypass_proxies
(url, no_proxy)
return False
Returns whether we should bypass proxies or not. :rtype: bool
Returns whether we should bypass proxies or not.
[ "Returns", "whether", "we", "should", "bypass", "proxies", "or", "not", "." ]
def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy_arg = no_proxy if no_proxy is None: no_proxy = get_proxy('no_proxy') netloc = urlparse(url).netloc if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the netloc, both with and without the port. no_proxy = ( host for host in no_proxy.replace(' ', '').split(',') if host ) ip = netloc.split(':')[0] if is_ipv4_address(ip): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True elif ip == proxy_ip: # If no_proxy ip was defined in plain IP notation instead of cidr notation & # matches the IP of the index return True else: for host in no_proxy: if netloc.endswith(host) or netloc.split(':')[0].endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True # If the system proxy settings indicate that this URL should be bypassed, # don't proxy. # The proxy_bypass function is incredibly buggy on OS X in early versions # of Python 2.6, so allow this call to fail. Only catch the specific # exceptions we've seen, though: this call failing in other ways can reveal # legitimate problems. with set_environ('no_proxy', no_proxy_arg): try: bypass = proxy_bypass(netloc) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
[ "def", "should_bypass_proxies", "(", "url", ",", "no_proxy", ")", ":", "get_proxy", "=", "lambda", "k", ":", "os", ".", "environ", ".", "get", "(", "k", ")", "or", "os", ".", "environ", ".", "get", "(", "k", ".", "upper", "(", ")", ")", "# First ch...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/utils.py#L629-L683
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
boolToText
(boolval)
return ret
Convenient way to turn bool into text
Convenient way to turn bool into text
[ "Convenient", "way", "to", "turn", "bool", "into", "text" ]
def boolToText(boolval): """Convenient way to turn bool into text """ ret = libxml2mod.xmlBoolToText(boolval) return ret
[ "def", "boolToText", "(", "boolval", ")", ":", "ret", "=", "libxml2mod", ".", "xmlBoolToText", "(", "boolval", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L1077-L1080
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Misc.place_slaves
(self)
return map(self._nametowidget, self.tk.splitlist( self.tk.call( 'place', 'slaves', self._w)))
Return a list of all slaves of this widget in its packing order.
Return a list of all slaves of this widget in its packing order.
[ "Return", "a", "list", "of", "all", "slaves", "of", "this", "widget", "in", "its", "packing", "order", "." ]
def place_slaves(self): """Return a list of all slaves of this widget in its packing order.""" return map(self._nametowidget, self.tk.splitlist( self.tk.call( 'place', 'slaves', self._w)))
[ "def", "place_slaves", "(", "self", ")", ":", "return", "map", "(", "self", ".", "_nametowidget", ",", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "'place'", ",", "'slaves'", ",", "self", ".", "_w", ")", ")", ")" ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1302-L1308
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/pyhit/pyhit.py
python
Node.comment
(self, param=None)
Return a +copy+ of the comment for the block or parameter given by *param*. When this method is called without arguments it returns the comments for the block itself. When called with the *param* name, the comment for that parameter is returned. !alert note title=The "comment" method returns a copy. This method returns a copy of the comment text. To modify the comment, the "setComment" method must be used.
Return a +copy+ of the comment for the block or parameter given by *param*.
[ "Return", "a", "+", "copy", "+", "of", "the", "comment", "for", "the", "block", "or", "parameter", "given", "by", "*", "param", "*", "." ]
def comment(self, param=None): """ Return a +copy+ of the comment for the block or parameter given by *param*. When this method is called without arguments it returns the comments for the block itself. When called with the *param* name, the comment for that parameter is returned. !alert note title=The "comment" method returns a copy. This method returns a copy of the comment text. To modify the comment, the "setComment" method must be used. """ comment = self.__hitparamcomments.get(param, self.__hitblockcomment) if comment is not None: return str(comment).strip('\n# ')
[ "def", "comment", "(", "self", ",", "param", "=", "None", ")", ":", "comment", "=", "self", ".", "__hitparamcomments", ".", "get", "(", "param", ",", "self", ".", "__hitblockcomment", ")", "if", "comment", "is", "not", "None", ":", "return", "str", "("...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/pyhit/pyhit.py#L88-L101
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/optparse.py
python
OptionParser._process_args
(self, largs, rargs, values)
_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate 'values', consuming options and arguments from 'rargs'. If 'allow_interspersed_args' is false, stop at the first non-option argument. If true, accumulate any interspersed non-option arguments in 'largs'.
_process_args(largs : [string], rargs : [string], values : Values)
[ "_process_args", "(", "largs", ":", "[", "string", "]", "rargs", ":", "[", "string", "]", "values", ":", "Values", ")" ]
def _process_args(self, largs, rargs, values): """_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate 'values', consuming options and arguments from 'rargs'. If 'allow_interspersed_args' is false, stop at the first non-option argument. If true, accumulate any interspersed non-option arguments in 'largs'. """ while rargs: arg = rargs[0] # We handle bare "--" explicitly, and bare "-" is handled by the # standard arg handler since the short arg case ensures that the # len of the opt string is greater than 1. if arg == "--": del rargs[0] return elif arg[0:2] == "--": # process a single long option (possibly with value(s)) self._process_long_opt(rargs, values) elif arg[:1] == "-" and len(arg) > 1: # process a cluster of short options (possibly with # value(s) for the last one only) self._process_short_opts(rargs, values) elif self.allow_interspersed_args: largs.append(arg) del rargs[0] else: return
[ "def", "_process_args", "(", "self", ",", "largs", ",", "rargs", ",", "values", ")", ":", "while", "rargs", ":", "arg", "=", "rargs", "[", "0", "]", "# We handle bare \"--\" explicitly, and bare \"-\" is handled by the", "# standard arg handler since the short arg case en...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/optparse.py#L1407-L1436
CleverRaven/Cataclysm-DDA
03e7363df0835ec1b39da973ea29f26f27833b38
tools/generate_changelog.py
python
CommitRepository.get_all_commits
(self, filter_by=None, sort_by=None)
Return all Commits in Repository. No order is guaranteed.
Return all Commits in Repository. No order is guaranteed.
[ "Return", "all", "Commits", "in", "Repository", ".", "No", "order", "is", "guaranteed", "." ]
def get_all_commits(self, filter_by=None, sort_by=None): """Return all Commits in Repository. No order is guaranteed.""" commit_list = self.ref_by_commit_hash.values() if filter_by is not None: commit_list = filter(filter_by, commit_list) if sort_by is not None: commit_list = sorted(commit_list, key=sort_by) for commit in commit_list: yield commit
[ "def", "get_all_commits", "(", "self", ",", "filter_by", "=", "None", ",", "sort_by", "=", "None", ")", ":", "commit_list", "=", "self", ".", "ref_by_commit_hash", ".", "values", "(", ")", "if", "filter_by", "is", "not", "None", ":", "commit_list", "=", ...
https://github.com/CleverRaven/Cataclysm-DDA/blob/03e7363df0835ec1b39da973ea29f26f27833b38/tools/generate_changelog.py#L281-L292
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/multi.py
python
MultiIndex._set_names
(self, names, level=None, validate: bool = True)
Set new names on index. Each name has to be a hashable type. Parameters ---------- values : str or sequence name(s) to set level : int, level name, or sequence of int/level names (default None) If the index is a MultiIndex (hierarchical), level(s) to set (None for all levels). Otherwise level must be None validate : bool, default True validate that the names match level lengths Raises ------ TypeError if each name is not hashable. Notes ----- sets names on levels. WARNING: mutates! Note that you generally want to set this *after* changing levels, so that it only acts on copies
Set new names on index. Each name has to be a hashable type.
[ "Set", "new", "names", "on", "index", ".", "Each", "name", "has", "to", "be", "a", "hashable", "type", "." ]
def _set_names(self, names, level=None, validate: bool = True): """ Set new names on index. Each name has to be a hashable type. Parameters ---------- values : str or sequence name(s) to set level : int, level name, or sequence of int/level names (default None) If the index is a MultiIndex (hierarchical), level(s) to set (None for all levels). Otherwise level must be None validate : bool, default True validate that the names match level lengths Raises ------ TypeError if each name is not hashable. Notes ----- sets names on levels. WARNING: mutates! Note that you generally want to set this *after* changing levels, so that it only acts on copies """ # GH 15110 # Don't allow a single string for names in a MultiIndex if names is not None and not is_list_like(names): raise ValueError("Names should be list-like for a MultiIndex") names = list(names) if validate: if level is not None and len(names) != len(level): raise ValueError("Length of names must match length of level.") if level is None and len(names) != self.nlevels: raise ValueError( "Length of names must match number of levels in MultiIndex." ) if level is None: level = range(self.nlevels) else: level = [self._get_level_number(lev) for lev in level] # set the name for lev, name in zip(level, names): if name is not None: # GH 20527 # All items in 'names' need to be hashable: if not is_hashable(name): raise TypeError( f"{type(self).__name__}.name must be a hashable type" ) # error: Cannot determine type of '__setitem__' self._names[lev] = name # type: ignore[has-type] # If .levels has been accessed, the names in our cache will be stale. self._reset_cache()
[ "def", "_set_names", "(", "self", ",", "names", ",", "level", "=", "None", ",", "validate", ":", "bool", "=", "True", ")", ":", "# GH 15110", "# Don't allow a single string for names in a MultiIndex", "if", "names", "is", "not", "None", "and", "not", "is_list_li...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/multi.py#L1395-L1452
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
python/build/lib.linux-x86_64-2.7/mxnet/model.py
python
FeedForward.load
(prefix, epoch, ctx=None, **kwargs)
return FeedForward(symbol, ctx=ctx, arg_params=arg_params, aux_params=aux_params, begin_epoch=epoch, **kwargs)
Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int epoch number of model we would like to load. ctx : Context or list of Context, optional The device context of training and prediction. kwargs : dict other parameters for model, including num_epoch, optimizer and numpy_batch_size Returns ------- model : FeedForward The loaded model that can be used for prediction. Notes ----- - ``prefix-symbol.json`` will be saved for symbol. - ``prefix-epoch.params`` will be saved for parameters.
Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int epoch number of model we would like to load. ctx : Context or list of Context, optional The device context of training and prediction. kwargs : dict other parameters for model, including num_epoch, optimizer and numpy_batch_size Returns ------- model : FeedForward The loaded model that can be used for prediction. Notes ----- - ``prefix-symbol.json`` will be saved for symbol. - ``prefix-epoch.params`` will be saved for parameters.
[ "Load", "model", "checkpoint", "from", "file", ".", "Parameters", "----------", "prefix", ":", "str", "Prefix", "of", "model", "name", ".", "epoch", ":", "int", "epoch", "number", "of", "model", "we", "would", "like", "to", "load", ".", "ctx", ":", "Cont...
def load(prefix, epoch, ctx=None, **kwargs): """Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int epoch number of model we would like to load. ctx : Context or list of Context, optional The device context of training and prediction. kwargs : dict other parameters for model, including num_epoch, optimizer and numpy_batch_size Returns ------- model : FeedForward The loaded model that can be used for prediction. Notes ----- - ``prefix-symbol.json`` will be saved for symbol. - ``prefix-epoch.params`` will be saved for parameters. """ symbol, arg_params, aux_params = load_checkpoint(prefix, epoch) return FeedForward(symbol, ctx=ctx, arg_params=arg_params, aux_params=aux_params, begin_epoch=epoch, **kwargs)
[ "def", "load", "(", "prefix", ",", "epoch", ",", "ctx", "=", "None", ",", "*", "*", "kwargs", ")", ":", "symbol", ",", "arg_params", ",", "aux_params", "=", "load_checkpoint", "(", "prefix", ",", "epoch", ")", "return", "FeedForward", "(", "symbol", ",...
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/model.py#L801-L826
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/command/install.py
python
install.finalize_other
(self)
Finalizes options for non-posix platforms
Finalizes options for non-posix platforms
[ "Finalizes", "options", "for", "non", "-", "posix", "platforms" ]
def finalize_other(self): """Finalizes options for non-posix platforms""" if self.user: if self.install_userbase is None: raise DistutilsPlatformError( "User base directory is not specified") self.install_base = self.install_platbase = self.install_userbase self.select_scheme(os.name + "_user") elif self.home is not None: self.install_base = self.install_platbase = self.home self.select_scheme("unix_home") else: if self.prefix is None: self.prefix = os.path.normpath(sys.prefix) self.install_base = self.install_platbase = self.prefix try: self.select_scheme(os.name) except KeyError: raise DistutilsPlatformError( "I don't know how to install stuff on '%s'" % os.name)
[ "def", "finalize_other", "(", "self", ")", ":", "if", "self", ".", "user", ":", "if", "self", ".", "install_userbase", "is", "None", ":", "raise", "DistutilsPlatformError", "(", "\"User base directory is not specified\"", ")", "self", ".", "install_base", "=", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/command/install.py#L433-L453
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
dmlc-core/tracker/dmlc_tracker/mpi.py
python
get_mpi_env
(envs)
return cmd
get the mpirun command for setting the envornment support both openmpi and mpich2
get the mpirun command for setting the envornment support both openmpi and mpich2
[ "get", "the", "mpirun", "command", "for", "setting", "the", "envornment", "support", "both", "openmpi", "and", "mpich2" ]
def get_mpi_env(envs): """get the mpirun command for setting the envornment support both openmpi and mpich2 """ # decide MPI version. (_, err) = subprocess.Popen('mpirun', stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() cmd = '' if 'Open MPI' in err: for k, v in envs.items(): cmd += ' -x %s=%s' % (k, str(v)) elif 'mpich' in err: for k, v in envs.items(): cmd += ' -env %s %s' % (k, str(v)) else: raise RuntimeError('Unknown MPI Version') return cmd
[ "def", "get_mpi_env", "(", "envs", ")", ":", "# decide MPI version.", "(", "_", ",", "err", ")", "=", "subprocess", ".", "Popen", "(", "'mpirun'", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", ".", "...
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/dmlc-core/tracker/dmlc_tracker/mpi.py#L11-L28
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_cocoa/gizmos.py
python
TreeListCtrl.IsColumnShown
(*args, **kwargs)
return _gizmos.TreeListCtrl_IsColumnShown(*args, **kwargs)
IsColumnShown(self, int column) -> bool
IsColumnShown(self, int column) -> bool
[ "IsColumnShown", "(", "self", "int", "column", ")", "-", ">", "bool" ]
def IsColumnShown(*args, **kwargs): """IsColumnShown(self, int column) -> bool""" return _gizmos.TreeListCtrl_IsColumnShown(*args, **kwargs)
[ "def", "IsColumnShown", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_IsColumnShown", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_cocoa/gizmos.py#L638-L640
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/optimize.py
python
OptimizationProblemBuilder.cost
(self)
return csum
Evaluates the cost function with the variables already bound.
Evaluates the cost function with the variables already bound.
[ "Evaluates", "the", "cost", "function", "with", "the", "variables", "already", "bound", "." ]
def cost(self): """Evaluates the cost function with the variables already bound.""" for v in self.optimizationVariables: assert v.value is not None,"All optimization variables must be bound" robset = False csum = 0.0 for obj in self.objectives: if obj.type == 'cost': #print(obj.weight,obj.expr.evalf(self.context)) csum += obj.weight*obj.expr.evalf(self.context) elif obj.soft: if obj.type == 'eq': r = obj.expr.evalf(self.context) csum += obj.weight*np.linalg.dot(r,r) elif obj.type == 'feas': if not obj.expr.evalf(self.context): csum += obj.weight elif obj.type == 'ineq': raise NotImplementedError("Soft inequalities") return csum
[ "def", "cost", "(", "self", ")", ":", "for", "v", "in", "self", ".", "optimizationVariables", ":", "assert", "v", ".", "value", "is", "not", "None", ",", "\"All optimization variables must be bound\"", "robset", "=", "False", "csum", "=", "0.0", "for", "obj"...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/optimize.py#L935-L954
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/appdirs.py
python
_win_path_to_bytes
(path)
return path
Encode Windows paths to bytes. Only used on Python 2. Motivation is to be consistent with other operating systems where paths are also returned as bytes. This avoids problems mixing bytes and Unicode elsewhere in the codebase. For more details and discussion see <https://github.com/pypa/pip/issues/3463>. If encoding using ASCII and MBCS fails, return the original Unicode path.
Encode Windows paths to bytes. Only used on Python 2.
[ "Encode", "Windows", "paths", "to", "bytes", ".", "Only", "used", "on", "Python", "2", "." ]
def _win_path_to_bytes(path): """Encode Windows paths to bytes. Only used on Python 2. Motivation is to be consistent with other operating systems where paths are also returned as bytes. This avoids problems mixing bytes and Unicode elsewhere in the codebase. For more details and discussion see <https://github.com/pypa/pip/issues/3463>. If encoding using ASCII and MBCS fails, return the original Unicode path. """ for encoding in ('ASCII', 'MBCS'): try: return path.encode(encoding) except (UnicodeEncodeError, LookupError): pass return path
[ "def", "_win_path_to_bytes", "(", "path", ")", ":", "for", "encoding", "in", "(", "'ASCII'", ",", "'MBCS'", ")", ":", "try", ":", "return", "path", ".", "encode", "(", "encoding", ")", "except", "(", "UnicodeEncodeError", ",", "LookupError", ")", ":", "p...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/appdirs.py#L1161-L1191
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/tldnVaporScope.py
python
tldnVaporScope.OnGUINotify
(self,id,control,event)
Notifications from the vignette
Notifications from the vignette
[ "Notifications", "from", "the", "vignette" ]
def OnGUINotify(self,id,control,event): "Notifications from the vignette" global boolScopeAtTop global boolScopeAtBottom global gInitialFOV global gThrottleShooting #PtDebugPrint("tldnVaporScope:GUINotify id=%d, event=%d control=" % (id,event),control,level=kDebugDumpLevel) if event == kDialogLoaded: # if the dialog was just loaded then show it control.show() elif event == kShowHide: if control.isEnabled(): # get the FOV and set the Zoom slider curCam = ptCamera() gInitialFOV = curCam.getFOV() zoomSlider = ptGUIControlKnob(control.getControlFromTag(kZoomSlider)) if gInitialFOV > kMinFOV: gInitialFOV = kMinFOV elif gInitialFOV < kMaxFOV: gInitialFOV = kMaxFOV zsliderValue = (gInitialFOV-kMaxFOV)/kDegreesPerSlider zoomSlider.setValue(zsliderValue) PtDebugPrint("tldnVaporScope:ShowDialog: current FOVh at %f - setting slider to %f" % (gInitialFOV,zsliderValue)) elif event == kValueChanged: if control is not None: knobID = control.getTagID() if knobID == kZoomSlider: newFOV = (control.getValue() * kDegreesPerSlider) + kMaxFOV curCam = ptCamera() curCam.setFOV(newFOV,0.5) PtDebugPrint("tldnVaporScope:ValueChange: slider=%f and setting FOV to %f" % (control.getValue(),newFOV)) elif event == kAction: if control is not None: btnID = control.getTagID() if btnID == kLeftScopeBtn: if isinstance(control,ptGUIControlButton) and control.isButtonDown(): PtDebugPrint("tldnVaporScope:GUINotify Left button down",level=kDebugDumpLevel) animVaporTurret.value.backwards(0) animVaporTurret.value.resume() else: PtDebugPrint("tldnVaporScope:GUINotify Left button up",level=kDebugDumpLevel) animVaporTurret.value.stop() elif btnID == kRightScopeBtn: if isinstance(control,ptGUIControlButton) and control.isButtonDown(): PtDebugPrint("tldnVaporScope:GUINotify Right button down",level=kDebugDumpLevel) animVaporTurret.value.backwards(1) animVaporTurret.value.resume() else: PtDebugPrint("tldnVaporScope:GUINotify Right button up",level=kDebugDumpLevel) animVaporTurret.value.stop() elif btnID == kUpScopeBtn: if isinstance(control,ptGUIControlButton) and control.isButtonDown(): if not boolScopeAtTop: PtDebugPrint("tldnVaporScope:GUINotify Up button down",level=kDebugDumpLevel) animVaporPitch.value.backwards(0) animVaporPitch.value.resume() else: PtDebugPrint("tldnVaporScope:GUINotify Up button up",level=kDebugDumpLevel) animVaporPitch.value.stop() if boolScopeAtBottom: boolScopeAtBottom = 0 self.SDL["scopeAtBottom"] = (0,) elif btnID == kDownScopeBtn: if isinstance(control,ptGUIControlButton) and control.isButtonDown(): if not boolScopeAtBottom: PtDebugPrint("tldnVaporScope:GUINotify Down button down",level=kDebugDumpLevel) animVaporPitch.value.backwards(1) animVaporPitch.value.resume() else: PtDebugPrint("tldnVaporScope:GUINotify Down button up",level=kDebugDumpLevel) animVaporPitch.value.stop() if boolScopeAtTop: boolScopeAtTop = 0 self.SDL["scopeAtTop"] = (0,) elif btnID == kFireScopeBtn: if not gThrottleShooting: PtDebugPrint("tldnVaporScope:GUINotify Shoot vapor",level=kDebugDumpLevel) respShootGun.run(self.key) ####-# reset the slider back to initialFOV, cause the animation of the scope will set it back ####-zoomSlider = ptGUIControlKnob(control.getOwnerDialog().getControlFromTag(kZoomSlider)) ####-zsliderValue = (gInitialFOV-kMaxFOV)/kDegreesPerSlider ####-zoomSlider.setValue(zsliderValue) # need to see if we hit anything and run their responder PtRequestLOSScreen(self.key,42,0.5,0.5,10000,PtLOSObjectType.kShootable,PtLOSReportType.kReportHitOrMiss) gThrottleShooting = 1 try: if Vignette.value: scopeDlg = PtGetDialogFromString(Vignette.value) if scopeDlg: try: fireBtn = ptGUIControlButton(scopeDlg.getControlFromTag(kFireScopeBtn)) fireBtn.disable() except KeyError: PtDebugPrint("tldnVaporScope:GUINotify can't find the fire button",level=kDebugDumpLevel) except KeyError: PtDebugPrint("tldnVaporScope:GUINotify can't find VaporScope dialog",level=kDebugDumpLevel) PtAtTimeCallback(self.key,kTimerThrottleTime,kTimerThrottleFiring) # wait for player to finish exit one-shot, then reenable clickable else: PtDebugPrint("tldnVaporScope:GUINotify Throttling",level=kDebugDumpLevel) elif btnID == kExitButton: self.IQuitTelescope()
[ "def", "OnGUINotify", "(", "self", ",", "id", ",", "control", ",", "event", ")", ":", "global", "boolScopeAtTop", "global", "boolScopeAtBottom", "global", "gInitialFOV", "global", "gThrottleShooting", "#PtDebugPrint(\"tldnVaporScope:GUINotify id=%d, event=%d control=\" % (id,...
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/tldnVaporScope.py#L203-L303
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
PreStyledTextCtrl
(*args, **kwargs)
return val
PreStyledTextCtrl() -> StyledTextCtrl
PreStyledTextCtrl() -> StyledTextCtrl
[ "PreStyledTextCtrl", "()", "-", ">", "StyledTextCtrl" ]
def PreStyledTextCtrl(*args, **kwargs): """PreStyledTextCtrl() -> StyledTextCtrl""" val = _stc.new_PreStyledTextCtrl(*args, **kwargs) return val
[ "def", "PreStyledTextCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_stc", ".", "new_PreStyledTextCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L7008-L7011
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/modtool/cli/base.py
python
ModToolException.show
(self, file=None)
displays the colored message
displays the colored message
[ "displays", "the", "colored", "message" ]
def show(self, file=None): """ displays the colored message """ click.secho(f'ModToolException: {self.format_message()}', fg='red')
[ "def", "show", "(", "self", ",", "file", "=", "None", ")", ":", "click", ".", "secho", "(", "f'ModToolException: {self.format_message()}'", ",", "fg", "=", "'red'", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/cli/base.py#L30-L32
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/activex/activex.py
python
ActiveXWindow.SetAXProp
(*args, **kwargs)
return _activex.ActiveXWindow_SetAXProp(*args, **kwargs)
SetAXProp(self, String name, PyObject value) Set a property of the ActiveX object by name.
SetAXProp(self, String name, PyObject value)
[ "SetAXProp", "(", "self", "String", "name", "PyObject", "value", ")" ]
def SetAXProp(*args, **kwargs): """ SetAXProp(self, String name, PyObject value) Set a property of the ActiveX object by name. """ return _activex.ActiveXWindow_SetAXProp(*args, **kwargs)
[ "def", "SetAXProp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_activex", ".", "ActiveXWindow_SetAXProp", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/activex/activex.py#L310-L316