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
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectAnnulusAbsorption2.py
python
IndirectAnnulusAbsorption.validateInputs
(self)
return issues
Validate algorithm options.
Validate algorithm options.
[ "Validate", "algorithm", "options", "." ]
def validateInputs(self): """ Validate algorithm options. """ self._setup() issues = dict() if self._use_can_corrections and self._can_chemical_formula == '': issues['CanChemicalFormula'] = 'Must be set to use can corrections' if self._use_can_corrections and self._can_ws_name is None: issues['UseCanCorrections'] = 'Must specify a can workspace to use can corrections' # Geometry validation: can inner < sample inner < sample outer < can outer if self._sample_outer_radius <= self._sample_inner_radius: issues['SampleOuterRadius'] = 'Must be greater than SampleInnerRadius' if self._can_ws_name is not None: if self._sample_inner_radius <= self._can_inner_radius: issues['SampleInnerRadius'] = 'Must be greater than CanInnerRadius' if self._can_outer_radius <= self._sample_outer_radius: issues['CanOuterRadius'] = 'Must be greater than SampleOuterRadius' return issues
[ "def", "validateInputs", "(", "self", ")", ":", "self", ".", "_setup", "(", ")", "issues", "=", "dict", "(", ")", "if", "self", ".", "_use_can_corrections", "and", "self", ".", "_can_chemical_formula", "==", "''", ":", "issues", "[", "'CanChemicalFormula'", "]", "=", "'Must be set to use can corrections'", "if", "self", ".", "_use_can_corrections", "and", "self", ".", "_can_ws_name", "is", "None", ":", "issues", "[", "'UseCanCorrections'", "]", "=", "'Must specify a can workspace to use can corrections'", "# Geometry validation: can inner < sample inner < sample outer < can outer", "if", "self", ".", "_sample_outer_radius", "<=", "self", ".", "_sample_inner_radius", ":", "issues", "[", "'SampleOuterRadius'", "]", "=", "'Must be greater than SampleInnerRadius'", "if", "self", ".", "_can_ws_name", "is", "not", "None", ":", "if", "self", ".", "_sample_inner_radius", "<=", "self", ".", "_can_inner_radius", ":", "issues", "[", "'SampleInnerRadius'", "]", "=", "'Must be greater than CanInnerRadius'", "if", "self", ".", "_can_outer_radius", "<=", "self", ".", "_sample_outer_radius", ":", "issues", "[", "'CanOuterRadius'", "]", "=", "'Must be greater than SampleOuterRadius'", "return", "issues" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectAnnulusAbsorption2.py#L394-L419
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/tex.py
python
InternalLaTeXAuxAction
(XXXLaTeXAction, target = None, source= None, env=None)
return result
A builder for LaTeX files that checks the output in the aux file and decides how many times to use LaTeXAction, and BibTeXAction.
A builder for LaTeX files that checks the output in the aux file and decides how many times to use LaTeXAction, and BibTeXAction.
[ "A", "builder", "for", "LaTeX", "files", "that", "checks", "the", "output", "in", "the", "aux", "file", "and", "decides", "how", "many", "times", "to", "use", "LaTeXAction", "and", "BibTeXAction", "." ]
def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None): """A builder for LaTeX files that checks the output in the aux file and decides how many times to use LaTeXAction, and BibTeXAction.""" global must_rerun_latex # This routine is called with two actions. In this file for DVI builds # with LaTeXAction and from the pdflatex.py with PDFLaTeXAction # set this up now for the case where the user requests a different extension # for the target filename if (XXXLaTeXAction == LaTeXAction): callerSuffix = ".dvi" else: callerSuffix = env['PDFSUFFIX'] basename = SCons.Util.splitext(str(source[0]))[0] basedir = os.path.split(str(source[0]))[0] basefile = os.path.split(str(basename))[1] abspath = os.path.abspath(basedir) targetext = os.path.splitext(str(target[0]))[1] targetdir = os.path.split(str(target[0]))[0] saved_env = {} for var in SCons.Scanner.LaTeX.LaTeX.env_variables: saved_env[var] = modify_env_var(env, var, abspath) # Create base file names with the target directory since the auxiliary files # will be made there. That's because the *COM variables have the cd # command in the prolog. We check # for the existence of files before opening them--even ones like the # aux file that TeX always creates--to make it possible to write tests # with stubs that don't necessarily generate all of the same files. targetbase = os.path.join(targetdir, basefile) # if there is a \makeindex there will be a .idx and thus # we have to run makeindex at least once to keep the build # happy even if there is no index. # Same for glossaries, nomenclature, and acronyms src_content = source[0].get_text_contents() run_makeindex = makeindex_re.search(src_content) and not os.path.isfile(targetbase + '.idx') run_nomenclature = makenomenclature_re.search(src_content) and not os.path.isfile(targetbase + '.nlo') run_glossary = makeglossary_re.search(src_content) and not os.path.isfile(targetbase + '.glo') run_glossaries = makeglossaries_re.search(src_content) and not os.path.isfile(targetbase + '.glo') run_acronyms = makeacronyms_re.search(src_content) and not os.path.isfile(targetbase + '.acn') saved_hashes = {} suffix_nodes = {} for suffix in all_suffixes+sum(newglossary_suffix, []): theNode = env.fs.File(targetbase + suffix) suffix_nodes[suffix] = theNode saved_hashes[suffix] = theNode.get_csig() if Verbose: print "hashes: ",saved_hashes must_rerun_latex = True # .aux files already processed by BibTex already_bibtexed = [] # # routine to update MD5 hash and compare # def check_MD5(filenode, suffix): global must_rerun_latex # two calls to clear old csig filenode.clear_memoized_values() filenode.ninfo = filenode.new_ninfo() new_md5 = filenode.get_csig() if saved_hashes[suffix] == new_md5: if Verbose: print "file %s not changed" % (targetbase+suffix) return False # unchanged saved_hashes[suffix] = new_md5 must_rerun_latex = True if Verbose: print "file %s changed, rerunning Latex, new hash = " % (targetbase+suffix), new_md5 return True # changed # generate the file name that latex will generate resultfilename = targetbase + callerSuffix count = 0 while (must_rerun_latex and count < int(env.subst('$LATEXRETRIES'))) : result = XXXLaTeXAction(target, source, env) if result != 0: return result count = count + 1 must_rerun_latex = False # Decide if various things need to be run, or run again. # Read the log file to find warnings/errors logfilename = targetbase + '.log' logContent = '' if os.path.isfile(logfilename): logContent = open(logfilename, "rb").read() # Read the fls file to find all .aux files flsfilename = targetbase + '.fls' flsContent = '' auxfiles = [] if os.path.isfile(flsfilename): flsContent = open(flsfilename, "rb").read() auxfiles = openout_aux_re.findall(flsContent) # remove duplicates dups = {} for x in auxfiles: dups[x] = 1 auxfiles = list(dups.keys()) bcffiles = [] if os.path.isfile(flsfilename): flsContent = open(flsfilename, "rb").read() bcffiles = openout_bcf_re.findall(flsContent) # remove duplicates dups = {} for x in bcffiles: dups[x] = 1 bcffiles = list(dups.keys()) if Verbose: print "auxfiles ",auxfiles print "bcffiles ",bcffiles # Now decide if bibtex will need to be run. # The information that bibtex reads from the .aux file is # pass-independent. If we find (below) that the .bbl file is unchanged, # then the last latex saw a correct bibliography. # Therefore only do this once # Go through all .aux files and remember the files already done. for auxfilename in auxfiles: if auxfilename not in already_bibtexed: already_bibtexed.append(auxfilename) target_aux = os.path.join(targetdir, auxfilename) if os.path.isfile(target_aux): content = open(target_aux, "rb").read() if content.find("bibdata") != -1: if Verbose: print "Need to run bibtex on ",auxfilename bibfile = env.fs.File(SCons.Util.splitext(target_aux)[0]) result = BibTeXAction(bibfile, bibfile, env) if result != 0: check_file_error_message(env['BIBTEX'], 'blg') must_rerun_latex = True # Now decide if biber will need to be run. # When the backend for biblatex is biber (by choice or default) the # citation information is put in the .bcf file. # The information that biber reads from the .bcf file is # pass-independent. If we find (below) that the .bbl file is unchanged, # then the last latex saw a correct bibliography. # Therefore only do this once # Go through all .bcf files and remember the files already done. for bcffilename in bcffiles: if bcffilename not in already_bibtexed: already_bibtexed.append(bcffilename) target_bcf = os.path.join(targetdir, bcffilename) if os.path.isfile(target_bcf): content = open(target_bcf, "rb").read() if content.find("bibdata") != -1: if Verbose: print "Need to run biber on ",bcffilename bibfile = env.fs.File(SCons.Util.splitext(target_bcf)[0]) result = BiberAction(bibfile, bibfile, env) if result != 0: check_file_error_message(env['BIBER'], 'blg') must_rerun_latex = True # Now decide if latex will need to be run again due to index. if check_MD5(suffix_nodes['.idx'],'.idx') or (count == 1 and run_makeindex): # We must run makeindex if Verbose: print "Need to run makeindex" idxfile = suffix_nodes['.idx'] result = MakeIndexAction(idxfile, idxfile, env) if result != 0: check_file_error_message(env['MAKEINDEX'], 'ilg') return result # TO-DO: need to add a way for the user to extend this list for whatever # auxiliary files they create in other (or their own) packages # Harder is case is where an action needs to be called -- that should be rare (I hope?) for index in check_suffixes: check_MD5(suffix_nodes[index],index) # Now decide if latex will need to be run again due to nomenclature. if check_MD5(suffix_nodes['.nlo'],'.nlo') or (count == 1 and run_nomenclature): # We must run makeindex if Verbose: print "Need to run makeindex for nomenclature" nclfile = suffix_nodes['.nlo'] result = MakeNclAction(nclfile, nclfile, env) if result != 0: check_file_error_message('%s (nomenclature)' % env['MAKENCL'], 'nlg') #return result # Now decide if latex will need to be run again due to glossary. if check_MD5(suffix_nodes['.glo'],'.glo') or (count == 1 and run_glossaries) or (count == 1 and run_glossary): # We must run makeindex if Verbose: print "Need to run makeindex for glossary" glofile = suffix_nodes['.glo'] result = MakeGlossaryAction(glofile, glofile, env) if result != 0: check_file_error_message('%s (glossary)' % env['MAKEGLOSSARY'], 'glg') #return result # Now decide if latex will need to be run again due to acronyms. if check_MD5(suffix_nodes['.acn'],'.acn') or (count == 1 and run_acronyms): # We must run makeindex if Verbose: print "Need to run makeindex for acronyms" acrfile = suffix_nodes['.acn'] result = MakeAcronymsAction(acrfile, acrfile, env) if result != 0: check_file_error_message('%s (acronyms)' % env['MAKEACRONYMS'], 'alg') return result # Now decide if latex will need to be run again due to newglossary command. for ig in range(len(newglossary_suffix)): if check_MD5(suffix_nodes[newglossary_suffix[ig][2]],newglossary_suffix[ig][2]) or (count == 1): # We must run makeindex if Verbose: print "Need to run makeindex for newglossary" newglfile = suffix_nodes[newglossary_suffix[ig][2]] MakeNewGlossaryAction = SCons.Action.Action("$MAKENEWGLOSSARYCOM ${SOURCE.filebase}%s -s ${SOURCE.filebase}.ist -t ${SOURCE.filebase}%s -o ${SOURCE.filebase}%s" % (newglossary_suffix[ig][2],newglossary_suffix[ig][0],newglossary_suffix[ig][1]), "$MAKENEWGLOSSARYCOMSTR") result = MakeNewGlossaryAction(newglfile, newglfile, env) if result != 0: check_file_error_message('%s (newglossary)' % env['MAKENEWGLOSSARY'], newglossary_suffix[ig][0]) return result # Now decide if latex needs to be run yet again to resolve warnings. if warning_rerun_re.search(logContent): must_rerun_latex = True if Verbose: print "rerun Latex due to latex or package rerun warning" if rerun_citations_re.search(logContent): must_rerun_latex = True if Verbose: print "rerun Latex due to 'Rerun to get citations correct' warning" if undefined_references_re.search(logContent): must_rerun_latex = True if Verbose: print "rerun Latex due to undefined references or citations" if (count >= int(env.subst('$LATEXRETRIES')) and must_rerun_latex): print "reached max number of retries on Latex ,",int(env.subst('$LATEXRETRIES')) # end of while loop # rename Latex's output to what the target name is if not (str(target[0]) == resultfilename and os.path.isfile(resultfilename)): if os.path.isfile(resultfilename): print "move %s to %s" % (resultfilename, str(target[0]), ) shutil.move(resultfilename,str(target[0])) # Original comment (when TEXPICTS was not restored): # The TEXPICTS enviroment variable is needed by a dvi -> pdf step # later on Mac OSX so leave it # # It is also used when searching for pictures (implicit dependencies). # Why not set the variable again in the respective builder instead # of leaving local modifications in the environment? What if multiple # latex builds in different directories need different TEXPICTS? for var in SCons.Scanner.LaTeX.LaTeX.env_variables: if var == 'TEXPICTS': continue if saved_env[var] is _null: try: del env['ENV'][var] except KeyError: pass # was never set else: env['ENV'][var] = saved_env[var] return result
[ "def", "InternalLaTeXAuxAction", "(", "XXXLaTeXAction", ",", "target", "=", "None", ",", "source", "=", "None", ",", "env", "=", "None", ")", ":", "global", "must_rerun_latex", "# This routine is called with two actions. In this file for DVI builds", "# with LaTeXAction and from the pdflatex.py with PDFLaTeXAction", "# set this up now for the case where the user requests a different extension", "# for the target filename", "if", "(", "XXXLaTeXAction", "==", "LaTeXAction", ")", ":", "callerSuffix", "=", "\".dvi\"", "else", ":", "callerSuffix", "=", "env", "[", "'PDFSUFFIX'", "]", "basename", "=", "SCons", ".", "Util", ".", "splitext", "(", "str", "(", "source", "[", "0", "]", ")", ")", "[", "0", "]", "basedir", "=", "os", ".", "path", ".", "split", "(", "str", "(", "source", "[", "0", "]", ")", ")", "[", "0", "]", "basefile", "=", "os", ".", "path", ".", "split", "(", "str", "(", "basename", ")", ")", "[", "1", "]", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "basedir", ")", "targetext", "=", "os", ".", "path", ".", "splitext", "(", "str", "(", "target", "[", "0", "]", ")", ")", "[", "1", "]", "targetdir", "=", "os", ".", "path", ".", "split", "(", "str", "(", "target", "[", "0", "]", ")", ")", "[", "0", "]", "saved_env", "=", "{", "}", "for", "var", "in", "SCons", ".", "Scanner", ".", "LaTeX", ".", "LaTeX", ".", "env_variables", ":", "saved_env", "[", "var", "]", "=", "modify_env_var", "(", "env", ",", "var", ",", "abspath", ")", "# Create base file names with the target directory since the auxiliary files", "# will be made there. That's because the *COM variables have the cd", "# command in the prolog. We check", "# for the existence of files before opening them--even ones like the", "# aux file that TeX always creates--to make it possible to write tests", "# with stubs that don't necessarily generate all of the same files.", "targetbase", "=", "os", ".", "path", ".", "join", "(", "targetdir", ",", "basefile", ")", "# if there is a \\makeindex there will be a .idx and thus", "# we have to run makeindex at least once to keep the build", "# happy even if there is no index.", "# Same for glossaries, nomenclature, and acronyms", "src_content", "=", "source", "[", "0", "]", ".", "get_text_contents", "(", ")", "run_makeindex", "=", "makeindex_re", ".", "search", "(", "src_content", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "targetbase", "+", "'.idx'", ")", "run_nomenclature", "=", "makenomenclature_re", ".", "search", "(", "src_content", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "targetbase", "+", "'.nlo'", ")", "run_glossary", "=", "makeglossary_re", ".", "search", "(", "src_content", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "targetbase", "+", "'.glo'", ")", "run_glossaries", "=", "makeglossaries_re", ".", "search", "(", "src_content", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "targetbase", "+", "'.glo'", ")", "run_acronyms", "=", "makeacronyms_re", ".", "search", "(", "src_content", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "targetbase", "+", "'.acn'", ")", "saved_hashes", "=", "{", "}", "suffix_nodes", "=", "{", "}", "for", "suffix", "in", "all_suffixes", "+", "sum", "(", "newglossary_suffix", ",", "[", "]", ")", ":", "theNode", "=", "env", ".", "fs", ".", "File", "(", "targetbase", "+", "suffix", ")", "suffix_nodes", "[", "suffix", "]", "=", "theNode", "saved_hashes", "[", "suffix", "]", "=", "theNode", ".", "get_csig", "(", ")", "if", "Verbose", ":", "print", "\"hashes: \"", ",", "saved_hashes", "must_rerun_latex", "=", "True", "# .aux files already processed by BibTex", "already_bibtexed", "=", "[", "]", "#", "# routine to update MD5 hash and compare", "#", "def", "check_MD5", "(", "filenode", ",", "suffix", ")", ":", "global", "must_rerun_latex", "# two calls to clear old csig", "filenode", ".", "clear_memoized_values", "(", ")", "filenode", ".", "ninfo", "=", "filenode", ".", "new_ninfo", "(", ")", "new_md5", "=", "filenode", ".", "get_csig", "(", ")", "if", "saved_hashes", "[", "suffix", "]", "==", "new_md5", ":", "if", "Verbose", ":", "print", "\"file %s not changed\"", "%", "(", "targetbase", "+", "suffix", ")", "return", "False", "# unchanged", "saved_hashes", "[", "suffix", "]", "=", "new_md5", "must_rerun_latex", "=", "True", "if", "Verbose", ":", "print", "\"file %s changed, rerunning Latex, new hash = \"", "%", "(", "targetbase", "+", "suffix", ")", ",", "new_md5", "return", "True", "# changed", "# generate the file name that latex will generate", "resultfilename", "=", "targetbase", "+", "callerSuffix", "count", "=", "0", "while", "(", "must_rerun_latex", "and", "count", "<", "int", "(", "env", ".", "subst", "(", "'$LATEXRETRIES'", ")", ")", ")", ":", "result", "=", "XXXLaTeXAction", "(", "target", ",", "source", ",", "env", ")", "if", "result", "!=", "0", ":", "return", "result", "count", "=", "count", "+", "1", "must_rerun_latex", "=", "False", "# Decide if various things need to be run, or run again.", "# Read the log file to find warnings/errors", "logfilename", "=", "targetbase", "+", "'.log'", "logContent", "=", "''", "if", "os", ".", "path", ".", "isfile", "(", "logfilename", ")", ":", "logContent", "=", "open", "(", "logfilename", ",", "\"rb\"", ")", ".", "read", "(", ")", "# Read the fls file to find all .aux files", "flsfilename", "=", "targetbase", "+", "'.fls'", "flsContent", "=", "''", "auxfiles", "=", "[", "]", "if", "os", ".", "path", ".", "isfile", "(", "flsfilename", ")", ":", "flsContent", "=", "open", "(", "flsfilename", ",", "\"rb\"", ")", ".", "read", "(", ")", "auxfiles", "=", "openout_aux_re", ".", "findall", "(", "flsContent", ")", "# remove duplicates", "dups", "=", "{", "}", "for", "x", "in", "auxfiles", ":", "dups", "[", "x", "]", "=", "1", "auxfiles", "=", "list", "(", "dups", ".", "keys", "(", ")", ")", "bcffiles", "=", "[", "]", "if", "os", ".", "path", ".", "isfile", "(", "flsfilename", ")", ":", "flsContent", "=", "open", "(", "flsfilename", ",", "\"rb\"", ")", ".", "read", "(", ")", "bcffiles", "=", "openout_bcf_re", ".", "findall", "(", "flsContent", ")", "# remove duplicates", "dups", "=", "{", "}", "for", "x", "in", "bcffiles", ":", "dups", "[", "x", "]", "=", "1", "bcffiles", "=", "list", "(", "dups", ".", "keys", "(", ")", ")", "if", "Verbose", ":", "print", "\"auxfiles \"", ",", "auxfiles", "print", "\"bcffiles \"", ",", "bcffiles", "# Now decide if bibtex will need to be run.", "# The information that bibtex reads from the .aux file is", "# pass-independent. If we find (below) that the .bbl file is unchanged,", "# then the last latex saw a correct bibliography.", "# Therefore only do this once", "# Go through all .aux files and remember the files already done.", "for", "auxfilename", "in", "auxfiles", ":", "if", "auxfilename", "not", "in", "already_bibtexed", ":", "already_bibtexed", ".", "append", "(", "auxfilename", ")", "target_aux", "=", "os", ".", "path", ".", "join", "(", "targetdir", ",", "auxfilename", ")", "if", "os", ".", "path", ".", "isfile", "(", "target_aux", ")", ":", "content", "=", "open", "(", "target_aux", ",", "\"rb\"", ")", ".", "read", "(", ")", "if", "content", ".", "find", "(", "\"bibdata\"", ")", "!=", "-", "1", ":", "if", "Verbose", ":", "print", "\"Need to run bibtex on \"", ",", "auxfilename", "bibfile", "=", "env", ".", "fs", ".", "File", "(", "SCons", ".", "Util", ".", "splitext", "(", "target_aux", ")", "[", "0", "]", ")", "result", "=", "BibTeXAction", "(", "bibfile", ",", "bibfile", ",", "env", ")", "if", "result", "!=", "0", ":", "check_file_error_message", "(", "env", "[", "'BIBTEX'", "]", ",", "'blg'", ")", "must_rerun_latex", "=", "True", "# Now decide if biber will need to be run.", "# When the backend for biblatex is biber (by choice or default) the", "# citation information is put in the .bcf file.", "# The information that biber reads from the .bcf file is", "# pass-independent. If we find (below) that the .bbl file is unchanged,", "# then the last latex saw a correct bibliography.", "# Therefore only do this once", "# Go through all .bcf files and remember the files already done.", "for", "bcffilename", "in", "bcffiles", ":", "if", "bcffilename", "not", "in", "already_bibtexed", ":", "already_bibtexed", ".", "append", "(", "bcffilename", ")", "target_bcf", "=", "os", ".", "path", ".", "join", "(", "targetdir", ",", "bcffilename", ")", "if", "os", ".", "path", ".", "isfile", "(", "target_bcf", ")", ":", "content", "=", "open", "(", "target_bcf", ",", "\"rb\"", ")", ".", "read", "(", ")", "if", "content", ".", "find", "(", "\"bibdata\"", ")", "!=", "-", "1", ":", "if", "Verbose", ":", "print", "\"Need to run biber on \"", ",", "bcffilename", "bibfile", "=", "env", ".", "fs", ".", "File", "(", "SCons", ".", "Util", ".", "splitext", "(", "target_bcf", ")", "[", "0", "]", ")", "result", "=", "BiberAction", "(", "bibfile", ",", "bibfile", ",", "env", ")", "if", "result", "!=", "0", ":", "check_file_error_message", "(", "env", "[", "'BIBER'", "]", ",", "'blg'", ")", "must_rerun_latex", "=", "True", "# Now decide if latex will need to be run again due to index.", "if", "check_MD5", "(", "suffix_nodes", "[", "'.idx'", "]", ",", "'.idx'", ")", "or", "(", "count", "==", "1", "and", "run_makeindex", ")", ":", "# We must run makeindex", "if", "Verbose", ":", "print", "\"Need to run makeindex\"", "idxfile", "=", "suffix_nodes", "[", "'.idx'", "]", "result", "=", "MakeIndexAction", "(", "idxfile", ",", "idxfile", ",", "env", ")", "if", "result", "!=", "0", ":", "check_file_error_message", "(", "env", "[", "'MAKEINDEX'", "]", ",", "'ilg'", ")", "return", "result", "# TO-DO: need to add a way for the user to extend this list for whatever", "# auxiliary files they create in other (or their own) packages", "# Harder is case is where an action needs to be called -- that should be rare (I hope?)", "for", "index", "in", "check_suffixes", ":", "check_MD5", "(", "suffix_nodes", "[", "index", "]", ",", "index", ")", "# Now decide if latex will need to be run again due to nomenclature.", "if", "check_MD5", "(", "suffix_nodes", "[", "'.nlo'", "]", ",", "'.nlo'", ")", "or", "(", "count", "==", "1", "and", "run_nomenclature", ")", ":", "# We must run makeindex", "if", "Verbose", ":", "print", "\"Need to run makeindex for nomenclature\"", "nclfile", "=", "suffix_nodes", "[", "'.nlo'", "]", "result", "=", "MakeNclAction", "(", "nclfile", ",", "nclfile", ",", "env", ")", "if", "result", "!=", "0", ":", "check_file_error_message", "(", "'%s (nomenclature)'", "%", "env", "[", "'MAKENCL'", "]", ",", "'nlg'", ")", "#return result", "# Now decide if latex will need to be run again due to glossary.", "if", "check_MD5", "(", "suffix_nodes", "[", "'.glo'", "]", ",", "'.glo'", ")", "or", "(", "count", "==", "1", "and", "run_glossaries", ")", "or", "(", "count", "==", "1", "and", "run_glossary", ")", ":", "# We must run makeindex", "if", "Verbose", ":", "print", "\"Need to run makeindex for glossary\"", "glofile", "=", "suffix_nodes", "[", "'.glo'", "]", "result", "=", "MakeGlossaryAction", "(", "glofile", ",", "glofile", ",", "env", ")", "if", "result", "!=", "0", ":", "check_file_error_message", "(", "'%s (glossary)'", "%", "env", "[", "'MAKEGLOSSARY'", "]", ",", "'glg'", ")", "#return result", "# Now decide if latex will need to be run again due to acronyms.", "if", "check_MD5", "(", "suffix_nodes", "[", "'.acn'", "]", ",", "'.acn'", ")", "or", "(", "count", "==", "1", "and", "run_acronyms", ")", ":", "# We must run makeindex", "if", "Verbose", ":", "print", "\"Need to run makeindex for acronyms\"", "acrfile", "=", "suffix_nodes", "[", "'.acn'", "]", "result", "=", "MakeAcronymsAction", "(", "acrfile", ",", "acrfile", ",", "env", ")", "if", "result", "!=", "0", ":", "check_file_error_message", "(", "'%s (acronyms)'", "%", "env", "[", "'MAKEACRONYMS'", "]", ",", "'alg'", ")", "return", "result", "# Now decide if latex will need to be run again due to newglossary command.", "for", "ig", "in", "range", "(", "len", "(", "newglossary_suffix", ")", ")", ":", "if", "check_MD5", "(", "suffix_nodes", "[", "newglossary_suffix", "[", "ig", "]", "[", "2", "]", "]", ",", "newglossary_suffix", "[", "ig", "]", "[", "2", "]", ")", "or", "(", "count", "==", "1", ")", ":", "# We must run makeindex", "if", "Verbose", ":", "print", "\"Need to run makeindex for newglossary\"", "newglfile", "=", "suffix_nodes", "[", "newglossary_suffix", "[", "ig", "]", "[", "2", "]", "]", "MakeNewGlossaryAction", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$MAKENEWGLOSSARYCOM ${SOURCE.filebase}%s -s ${SOURCE.filebase}.ist -t ${SOURCE.filebase}%s -o ${SOURCE.filebase}%s\"", "%", "(", "newglossary_suffix", "[", "ig", "]", "[", "2", "]", ",", "newglossary_suffix", "[", "ig", "]", "[", "0", "]", ",", "newglossary_suffix", "[", "ig", "]", "[", "1", "]", ")", ",", "\"$MAKENEWGLOSSARYCOMSTR\"", ")", "result", "=", "MakeNewGlossaryAction", "(", "newglfile", ",", "newglfile", ",", "env", ")", "if", "result", "!=", "0", ":", "check_file_error_message", "(", "'%s (newglossary)'", "%", "env", "[", "'MAKENEWGLOSSARY'", "]", ",", "newglossary_suffix", "[", "ig", "]", "[", "0", "]", ")", "return", "result", "# Now decide if latex needs to be run yet again to resolve warnings.", "if", "warning_rerun_re", ".", "search", "(", "logContent", ")", ":", "must_rerun_latex", "=", "True", "if", "Verbose", ":", "print", "\"rerun Latex due to latex or package rerun warning\"", "if", "rerun_citations_re", ".", "search", "(", "logContent", ")", ":", "must_rerun_latex", "=", "True", "if", "Verbose", ":", "print", "\"rerun Latex due to 'Rerun to get citations correct' warning\"", "if", "undefined_references_re", ".", "search", "(", "logContent", ")", ":", "must_rerun_latex", "=", "True", "if", "Verbose", ":", "print", "\"rerun Latex due to undefined references or citations\"", "if", "(", "count", ">=", "int", "(", "env", ".", "subst", "(", "'$LATEXRETRIES'", ")", ")", "and", "must_rerun_latex", ")", ":", "print", "\"reached max number of retries on Latex ,\"", ",", "int", "(", "env", ".", "subst", "(", "'$LATEXRETRIES'", ")", ")", "# end of while loop", "# rename Latex's output to what the target name is", "if", "not", "(", "str", "(", "target", "[", "0", "]", ")", "==", "resultfilename", "and", "os", ".", "path", ".", "isfile", "(", "resultfilename", ")", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "resultfilename", ")", ":", "print", "\"move %s to %s\"", "%", "(", "resultfilename", ",", "str", "(", "target", "[", "0", "]", ")", ",", ")", "shutil", ".", "move", "(", "resultfilename", ",", "str", "(", "target", "[", "0", "]", ")", ")", "# Original comment (when TEXPICTS was not restored):", "# The TEXPICTS enviroment variable is needed by a dvi -> pdf step", "# later on Mac OSX so leave it", "#", "# It is also used when searching for pictures (implicit dependencies).", "# Why not set the variable again in the respective builder instead", "# of leaving local modifications in the environment? What if multiple", "# latex builds in different directories need different TEXPICTS?", "for", "var", "in", "SCons", ".", "Scanner", ".", "LaTeX", ".", "LaTeX", ".", "env_variables", ":", "if", "var", "==", "'TEXPICTS'", ":", "continue", "if", "saved_env", "[", "var", "]", "is", "_null", ":", "try", ":", "del", "env", "[", "'ENV'", "]", "[", "var", "]", "except", "KeyError", ":", "pass", "# was never set", "else", ":", "env", "[", "'ENV'", "]", "[", "var", "]", "=", "saved_env", "[", "var", "]", "return", "result" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/tex.py#L196-L487
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/push/search/util/search_schema_parser.py
python
SearchSchemaParser.__StartElement
(self, elem)
Start element handler. Args: elem: current element.
Start element handler.
[ "Start", "element", "handler", "." ]
def __StartElement(self, elem): """Start element handler. Args: elem: current element. """ self._current_tag = elem.tag self._element_start(elem)
[ "def", "__StartElement", "(", "self", ",", "elem", ")", ":", "self", ".", "_current_tag", "=", "elem", ".", "tag", "self", ".", "_element_start", "(", "elem", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/push/search/util/search_schema_parser.py#L156-L163
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/resmokelib/suitesconfig.py
python
_get_suite_config
(suite_name_or_path)
return SuiteFinder.get_config_obj(suite_name_or_path)
Attempt to read YAML configuration from 'suite_path' for the suite.
Attempt to read YAML configuration from 'suite_path' for the suite.
[ "Attempt", "to", "read", "YAML", "configuration", "from", "suite_path", "for", "the", "suite", "." ]
def _get_suite_config(suite_name_or_path): """Attempt to read YAML configuration from 'suite_path' for the suite.""" return SuiteFinder.get_config_obj(suite_name_or_path)
[ "def", "_get_suite_config", "(", "suite_name_or_path", ")", ":", "return", "SuiteFinder", ".", "get_config_obj", "(", "suite_name_or_path", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/suitesconfig.py#L117-L119
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/git.py
python
Repository.get_merge_base
(self, commit)
return self._callgito("merge-base", ["HEAD", commit]).rstrip()
Get the merge base between 'commit' and HEAD.
Get the merge base between 'commit' and HEAD.
[ "Get", "the", "merge", "base", "between", "commit", "and", "HEAD", "." ]
def get_merge_base(self, commit): """Get the merge base between 'commit' and HEAD.""" return self._callgito("merge-base", ["HEAD", commit]).rstrip()
[ "def", "get_merge_base", "(", "self", ",", "commit", ")", ":", "return", "self", ".", "_callgito", "(", "\"merge-base\"", ",", "[", "\"HEAD\"", ",", "commit", "]", ")", ".", "rstrip", "(", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/git.py#L148-L150
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/maximal-rectangle.py
python
Solution2.maximalRectangle
(self, matrix)
return result
:type matrix: List[List[str]] :rtype: int
:type matrix: List[List[str]] :rtype: int
[ ":", "type", "matrix", ":", "List", "[", "List", "[", "str", "]]", ":", "rtype", ":", "int" ]
def maximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if not matrix: return 0 result = 0 m = len(matrix) n = len(matrix[0]) L = [0 for _ in xrange(n)] H = [0 for _ in xrange(n)] R = [n for _ in xrange(n)] for i in xrange(m): left = 0 for j in xrange(n): if matrix[i][j] == '1': L[j] = max(L[j], left) H[j] += 1 else: L[j] = 0 H[j] = 0 R[j] = n left = j + 1 right = n for j in reversed(xrange(n)): if matrix[i][j] == '1': R[j] = min(R[j], right) result = max(result, H[j] * (R[j] - L[j])) else: right = j return result
[ "def", "maximalRectangle", "(", "self", ",", "matrix", ")", ":", "if", "not", "matrix", ":", "return", "0", "result", "=", "0", "m", "=", "len", "(", "matrix", ")", "n", "=", "len", "(", "matrix", "[", "0", "]", ")", "L", "=", "[", "0", "for", "_", "in", "xrange", "(", "n", ")", "]", "H", "=", "[", "0", "for", "_", "in", "xrange", "(", "n", ")", "]", "R", "=", "[", "n", "for", "_", "in", "xrange", "(", "n", ")", "]", "for", "i", "in", "xrange", "(", "m", ")", ":", "left", "=", "0", "for", "j", "in", "xrange", "(", "n", ")", ":", "if", "matrix", "[", "i", "]", "[", "j", "]", "==", "'1'", ":", "L", "[", "j", "]", "=", "max", "(", "L", "[", "j", "]", ",", "left", ")", "H", "[", "j", "]", "+=", "1", "else", ":", "L", "[", "j", "]", "=", "0", "H", "[", "j", "]", "=", "0", "R", "[", "j", "]", "=", "n", "left", "=", "j", "+", "1", "right", "=", "n", "for", "j", "in", "reversed", "(", "xrange", "(", "n", ")", ")", ":", "if", "matrix", "[", "i", "]", "[", "j", "]", "==", "'1'", ":", "R", "[", "j", "]", "=", "min", "(", "R", "[", "j", "]", ",", "right", ")", "result", "=", "max", "(", "result", ",", "H", "[", "j", "]", "*", "(", "R", "[", "j", "]", "-", "L", "[", "j", "]", ")", ")", "else", ":", "right", "=", "j", "return", "result" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximal-rectangle.py#L33-L68
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLSumForeground.py
python
ReflectometryILLSumForeground._directOnly
(self)
return self.getProperty(Prop.DIRECT_FOREGROUND_WS).isDefault
Return true if only the direct beam should be processed.
Return true if only the direct beam should be processed.
[ "Return", "true", "if", "only", "the", "direct", "beam", "should", "be", "processed", "." ]
def _directOnly(self): """Return true if only the direct beam should be processed.""" return self.getProperty(Prop.DIRECT_FOREGROUND_WS).isDefault
[ "def", "_directOnly", "(", "self", ")", ":", "return", "self", ".", "getProperty", "(", "Prop", ".", "DIRECT_FOREGROUND_WS", ")", ".", "isDefault" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLSumForeground.py#L214-L216
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/saving/saved_model/utils.py
python
get_training_arg_index
(call_fn)
Returns the index of 'training' in the layer call function arguments. Args: call_fn: Call function. Returns: - n: index of 'training' in the call function arguments. - -1: if 'training' is not found in the arguments, but layer.call accepts variable keyword arguments - None: if layer doesn't expect a training argument.
Returns the index of 'training' in the layer call function arguments.
[ "Returns", "the", "index", "of", "training", "in", "the", "layer", "call", "function", "arguments", "." ]
def get_training_arg_index(call_fn): """Returns the index of 'training' in the layer call function arguments. Args: call_fn: Call function. Returns: - n: index of 'training' in the call function arguments. - -1: if 'training' is not found in the arguments, but layer.call accepts variable keyword arguments - None: if layer doesn't expect a training argument. """ arg_list = tf_inspect.getfullargspec(call_fn).args if tf_inspect.ismethod(call_fn): arg_list = arg_list[1:] if 'training' in arg_list: return arg_list.index('training') else: return -1
[ "def", "get_training_arg_index", "(", "call_fn", ")", ":", "arg_list", "=", "tf_inspect", ".", "getfullargspec", "(", "call_fn", ")", ".", "args", "if", "tf_inspect", ".", "ismethod", "(", "call_fn", ")", ":", "arg_list", "=", "arg_list", "[", "1", ":", "]", "if", "'training'", "in", "arg_list", ":", "return", "arg_list", ".", "index", "(", "'training'", ")", "else", ":", "return", "-", "1" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/saving/saved_model/utils.py#L143-L161
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/examples/adding_an_op/zero_out_grad_2.py
python
_zero_out_grad
(op, grad)
return [to_zero_grad]
The gradients for `zero_out`. Args: op: The `zero_out` `Operation` that we are differentiating, which we can use to find the inputs and outputs of the original op. grad: Gradient with respect to the output of the `zero_out` op. Returns: Gradients with respect to the input of `zero_out`.
The gradients for `zero_out`.
[ "The", "gradients", "for", "zero_out", "." ]
def _zero_out_grad(op, grad): """The gradients for `zero_out`. Args: op: The `zero_out` `Operation` that we are differentiating, which we can use to find the inputs and outputs of the original op. grad: Gradient with respect to the output of the `zero_out` op. Returns: Gradients with respect to the input of `zero_out`. """ to_zero = op.inputs[0] shape = array_ops.shape(to_zero) index = array_ops.zeros_like(shape) first_grad = array_ops.reshape(grad, [-1])[0] to_zero_grad = sparse_ops.sparse_to_dense([index], shape, first_grad, 0) return [to_zero_grad]
[ "def", "_zero_out_grad", "(", "op", ",", "grad", ")", ":", "to_zero", "=", "op", ".", "inputs", "[", "0", "]", "shape", "=", "array_ops", ".", "shape", "(", "to_zero", ")", "index", "=", "array_ops", ".", "zeros_like", "(", "shape", ")", "first_grad", "=", "array_ops", ".", "reshape", "(", "grad", ",", "[", "-", "1", "]", ")", "[", "0", "]", "to_zero_grad", "=", "sparse_ops", ".", "sparse_to_dense", "(", "[", "index", "]", ",", "shape", ",", "first_grad", ",", "0", ")", "return", "[", "to_zero_grad", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/examples/adding_an_op/zero_out_grad_2.py#L28-L44
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/gyp/pylib/gyp/mac_tool.py
python
MacTool._DetectInputEncoding
(self, file_name)
Reads the first few bytes from file_name and tries to guess the text encoding. Returns None as a guess if it can't detect it.
Reads the first few bytes from file_name and tries to guess the text encoding. Returns None as a guess if it can't detect it.
[ "Reads", "the", "first", "few", "bytes", "from", "file_name", "and", "tries", "to", "guess", "the", "text", "encoding", ".", "Returns", "None", "as", "a", "guess", "if", "it", "can", "t", "detect", "it", "." ]
def _DetectInputEncoding(self, file_name): """Reads the first few bytes from file_name and tries to guess the text encoding. Returns None as a guess if it can't detect it.""" with open(file_name, "rb") as fp: try: header = fp.read(3) except Exception: return None if header.startswith(b"\xFE\xFF"): return "UTF-16" elif header.startswith(b"\xFF\xFE"): return "UTF-16" elif header.startswith(b"\xEF\xBB\xBF"): return "UTF-8" else: return None
[ "def", "_DetectInputEncoding", "(", "self", ",", "file_name", ")", ":", "with", "open", "(", "file_name", ",", "\"rb\"", ")", "as", "fp", ":", "try", ":", "header", "=", "fp", ".", "read", "(", "3", ")", "except", "Exception", ":", "return", "None", "if", "header", ".", "startswith", "(", "b\"\\xFE\\xFF\"", ")", ":", "return", "\"UTF-16\"", "elif", "header", ".", "startswith", "(", "b\"\\xFF\\xFE\"", ")", ":", "return", "\"UTF-16\"", "elif", "header", ".", "startswith", "(", "b\"\\xEF\\xBB\\xBF\"", ")", ":", "return", "\"UTF-8\"", "else", ":", "return", "None" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/mac_tool.py#L159-L174
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiTabArt.SetNormalFont
(*args, **kwargs)
return _aui.AuiTabArt_SetNormalFont(*args, **kwargs)
SetNormalFont(self, Font font)
SetNormalFont(self, Font font)
[ "SetNormalFont", "(", "self", "Font", "font", ")" ]
def SetNormalFont(*args, **kwargs): """SetNormalFont(self, Font font)""" return _aui.AuiTabArt_SetNormalFont(*args, **kwargs)
[ "def", "SetNormalFont", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiTabArt_SetNormalFont", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L2294-L2296
OPAE/opae-sdk
221124343c8275243a249eb72d69e0ea2d568d1b
python/opae.admin/opae/admin/tools/fpgasupdate.py
python
do_partial_reconf
(addr, filename)
return (0, output + '\nPartial Reconfiguration OK')
Call out to fpgaconf for Partial Reconfiguration. addr - the canonical ssss:bb:dd.f of the device to PR. filename - the GBS file path. returns a 2-tuple of the process exit status and a message.
Call out to fpgaconf for Partial Reconfiguration.
[ "Call", "out", "to", "fpgaconf", "for", "Partial", "Reconfiguration", "." ]
def do_partial_reconf(addr, filename): """Call out to fpgaconf for Partial Reconfiguration. addr - the canonical ssss:bb:dd.f of the device to PR. filename - the GBS file path. returns a 2-tuple of the process exit status and a message. """ conf_args = ['fpgaconf', '--segment', '0x' + addr[:4], '--bus', '0x' + addr[5:7], '--device', '0x' + addr[8:10], '--function', '0x' + addr[11:], filename] LOG.debug('command: %s', ' '.join(conf_args)) try: output = subprocess.check_output(conf_args, stderr=subprocess.STDOUT) output = output.decode(sys.getdefaultencoding()) except subprocess.CalledProcessError as exc: return (exc.returncode, exc.output.decode(sys.getdefaultencoding()) + '\nPartial Reconfiguration failed') return (0, output + '\nPartial Reconfiguration OK')
[ "def", "do_partial_reconf", "(", "addr", ",", "filename", ")", ":", "conf_args", "=", "[", "'fpgaconf'", ",", "'--segment'", ",", "'0x'", "+", "addr", "[", ":", "4", "]", ",", "'--bus'", ",", "'0x'", "+", "addr", "[", "5", ":", "7", "]", ",", "'--device'", ",", "'0x'", "+", "addr", "[", "8", ":", "10", "]", ",", "'--function'", ",", "'0x'", "+", "addr", "[", "11", ":", "]", ",", "filename", "]", "LOG", ".", "debug", "(", "'command: %s'", ",", "' '", ".", "join", "(", "conf_args", ")", ")", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "conf_args", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "output", "=", "output", ".", "decode", "(", "sys", ".", "getdefaultencoding", "(", ")", ")", "except", "subprocess", ".", "CalledProcessError", "as", "exc", ":", "return", "(", "exc", ".", "returncode", ",", "exc", ".", "output", ".", "decode", "(", "sys", ".", "getdefaultencoding", "(", ")", ")", "+", "'\\nPartial Reconfiguration failed'", ")", "return", "(", "0", ",", "output", "+", "'\\nPartial Reconfiguration OK'", ")" ]
https://github.com/OPAE/opae-sdk/blob/221124343c8275243a249eb72d69e0ea2d568d1b/python/opae.admin/opae/admin/tools/fpgasupdate.py#L239-L262
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.StyleSetEOLFilled
(*args, **kwargs)
return _stc.StyledTextCtrl_StyleSetEOLFilled(*args, **kwargs)
StyleSetEOLFilled(self, int style, bool filled) Set a style to have its end of line filled or not.
StyleSetEOLFilled(self, int style, bool filled)
[ "StyleSetEOLFilled", "(", "self", "int", "style", "bool", "filled", ")" ]
def StyleSetEOLFilled(*args, **kwargs): """ StyleSetEOLFilled(self, int style, bool filled) Set a style to have its end of line filled or not. """ return _stc.StyledTextCtrl_StyleSetEOLFilled(*args, **kwargs)
[ "def", "StyleSetEOLFilled", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_StyleSetEOLFilled", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2562-L2568
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
CalibMuon/DTCalibration/python/Workflow/DTT0WireWorkflow.py
python
DTT0WireWorkflow.prepare_workflow
(self)
Generalized function to prepare workflow dependent on workflow mode
Generalized function to prepare workflow dependent on workflow mode
[ "Generalized", "function", "to", "prepare", "workflow", "dependent", "on", "workflow", "mode" ]
def prepare_workflow(self): """ Generalized function to prepare workflow dependent on workflow mode""" function_name = "prepare_" + self.options.workflow_mode + "_" + self.options.command try: fill_function = getattr(self, function_name) except AttributeError: errmsg = "Class `{}` does not implement `{}`" raise NotImplementedError(errmsg.format(my_cls.__class__.__name__, method_name)) log.debug("Preparing workflow with function %s" % function_name) # call chosen function fill_function()
[ "def", "prepare_workflow", "(", "self", ")", ":", "function_name", "=", "\"prepare_\"", "+", "self", ".", "options", ".", "workflow_mode", "+", "\"_\"", "+", "self", ".", "options", ".", "command", "try", ":", "fill_function", "=", "getattr", "(", "self", ",", "function_name", ")", "except", "AttributeError", ":", "errmsg", "=", "\"Class `{}` does not implement `{}`\"", "raise", "NotImplementedError", "(", "errmsg", ".", "format", "(", "my_cls", ".", "__class__", ".", "__name__", ",", "method_name", ")", ")", "log", ".", "debug", "(", "\"Preparing workflow with function %s\"", "%", "function_name", ")", "# call chosen function", "fill_function", "(", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/CalibMuon/DTCalibration/python/Workflow/DTT0WireWorkflow.py#L21-L33
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/_grad_ops.py
python
ConcatOffset.__init__
(self, N=2, axis=0)
Initialize ConcatOffset
Initialize ConcatOffset
[ "Initialize", "ConcatOffset" ]
def __init__(self, N=2, axis=0): """Initialize ConcatOffset"""
[ "def", "__init__", "(", "self", ",", "N", "=", "2", ",", "axis", "=", "0", ")", ":" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/_grad_ops.py#L215-L216
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py
python
TPen.color
(self, *args)
Return or set the pencolor and fillcolor. Arguments: Several input formats are allowed. They use 0, 1, 2, or 3 arguments as follows: color() Return the current pencolor and the current fillcolor as a pair of color specification strings as are returned by pencolor and fillcolor. color(colorstring), color((r,g,b)), color(r,g,b) inputs as in pencolor, set both, fillcolor and pencolor, to the given value. color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2)) equivalent to pencolor(colorstring1) and fillcolor(colorstring2) and analogously, if the other input format is used. If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors. For mor info see: pencolor, fillcolor Example (for a Turtle instance named turtle): >>> turtle.color('red', 'green') >>> turtle.color() ('red', 'green') >>> colormode(255) >>> color((40, 80, 120), (160, 200, 240)) >>> color() ('#285078', '#a0c8f0')
Return or set the pencolor and fillcolor.
[ "Return", "or", "set", "the", "pencolor", "and", "fillcolor", "." ]
def color(self, *args): """Return or set the pencolor and fillcolor. Arguments: Several input formats are allowed. They use 0, 1, 2, or 3 arguments as follows: color() Return the current pencolor and the current fillcolor as a pair of color specification strings as are returned by pencolor and fillcolor. color(colorstring), color((r,g,b)), color(r,g,b) inputs as in pencolor, set both, fillcolor and pencolor, to the given value. color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2)) equivalent to pencolor(colorstring1) and fillcolor(colorstring2) and analogously, if the other input format is used. If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors. For mor info see: pencolor, fillcolor Example (for a Turtle instance named turtle): >>> turtle.color('red', 'green') >>> turtle.color() ('red', 'green') >>> colormode(255) >>> color((40, 80, 120), (160, 200, 240)) >>> color() ('#285078', '#a0c8f0') """ if args: l = len(args) if l == 1: pcolor = fcolor = args[0] elif l == 2: pcolor, fcolor = args elif l == 3: pcolor = fcolor = args pcolor = self._colorstr(pcolor) fcolor = self._colorstr(fcolor) self.pen(pencolor=pcolor, fillcolor=fcolor) else: return self._color(self._pencolor), self._color(self._fillcolor)
[ "def", "color", "(", "self", ",", "*", "args", ")", ":", "if", "args", ":", "l", "=", "len", "(", "args", ")", "if", "l", "==", "1", ":", "pcolor", "=", "fcolor", "=", "args", "[", "0", "]", "elif", "l", "==", "2", ":", "pcolor", ",", "fcolor", "=", "args", "elif", "l", "==", "3", ":", "pcolor", "=", "fcolor", "=", "args", "pcolor", "=", "self", ".", "_colorstr", "(", "pcolor", ")", "fcolor", "=", "self", ".", "_colorstr", "(", "fcolor", ")", "self", ".", "pen", "(", "pencolor", "=", "pcolor", ",", "fillcolor", "=", "fcolor", ")", "else", ":", "return", "self", ".", "_color", "(", "self", ".", "_pencolor", ")", ",", "self", ".", "_color", "(", "self", ".", "_fillcolor", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L2090-L2134
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/android_platform/development/scripts/stack_core.py
python
PreProcessLog.__init__
(self, load_vaddrs)
Bind load_vaddrs to the PreProcessLog closure. Args: load_vaddrs: LOAD segment min_vaddrs keyed on mapped executable
Bind load_vaddrs to the PreProcessLog closure. Args: load_vaddrs: LOAD segment min_vaddrs keyed on mapped executable
[ "Bind", "load_vaddrs", "to", "the", "PreProcessLog", "closure", ".", "Args", ":", "load_vaddrs", ":", "LOAD", "segment", "min_vaddrs", "keyed", "on", "mapped", "executable" ]
def __init__(self, load_vaddrs): """Bind load_vaddrs to the PreProcessLog closure. Args: load_vaddrs: LOAD segment min_vaddrs keyed on mapped executable """ self._load_vaddrs = load_vaddrs; # This is mapping from apk's offset to shared libraries. self._shared_libraries_mapping = dict() # The list of directires in which instead of default output dir, # the shared libraries is found. self._so_dirs = []
[ "def", "__init__", "(", "self", ",", "load_vaddrs", ")", ":", "self", ".", "_load_vaddrs", "=", "load_vaddrs", "# This is mapping from apk's offset to shared libraries.", "self", ".", "_shared_libraries_mapping", "=", "dict", "(", ")", "# The list of directires in which instead of default output dir,", "# the shared libraries is found.", "self", ".", "_so_dirs", "=", "[", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/android_platform/development/scripts/stack_core.py#L194-L204
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/Paste/paste/proxy.py
python
parse_headers
(message)
return headers_out
Turn a Message object into a list of WSGI-style headers.
Turn a Message object into a list of WSGI-style headers.
[ "Turn", "a", "Message", "object", "into", "a", "list", "of", "WSGI", "-", "style", "headers", "." ]
def parse_headers(message): """ Turn a Message object into a list of WSGI-style headers. """ headers_out = [] if six.PY3: for header, value in message.items(): if header.lower() not in filtered_headers: headers_out.append((header, value)) else: for full_header in message.headers: if not full_header: # Shouldn't happen, but we'll just ignore continue if full_header[0].isspace(): # Continuation line, add to the last header if not headers_out: raise ValueError( "First header starts with a space (%r)" % full_header) last_header, last_value = headers_out.pop() value = last_value + ' ' + full_header.strip() headers_out.append((last_header, value)) continue try: header, value = full_header.split(':', 1) except: raise ValueError("Invalid header: %r" % full_header) value = value.strip() if header.lower() not in filtered_headers: headers_out.append((header, value)) return headers_out
[ "def", "parse_headers", "(", "message", ")", ":", "headers_out", "=", "[", "]", "if", "six", ".", "PY3", ":", "for", "header", ",", "value", "in", "message", ".", "items", "(", ")", ":", "if", "header", ".", "lower", "(", ")", "not", "in", "filtered_headers", ":", "headers_out", ".", "append", "(", "(", "header", ",", "value", ")", ")", "else", ":", "for", "full_header", "in", "message", ".", "headers", ":", "if", "not", "full_header", ":", "# Shouldn't happen, but we'll just ignore", "continue", "if", "full_header", "[", "0", "]", ".", "isspace", "(", ")", ":", "# Continuation line, add to the last header", "if", "not", "headers_out", ":", "raise", "ValueError", "(", "\"First header starts with a space (%r)\"", "%", "full_header", ")", "last_header", ",", "last_value", "=", "headers_out", ".", "pop", "(", ")", "value", "=", "last_value", "+", "' '", "+", "full_header", ".", "strip", "(", ")", "headers_out", ".", "append", "(", "(", "last_header", ",", "value", ")", ")", "continue", "try", ":", "header", ",", "value", "=", "full_header", ".", "split", "(", "':'", ",", "1", ")", "except", ":", "raise", "ValueError", "(", "\"Invalid header: %r\"", "%", "full_header", ")", "value", "=", "value", ".", "strip", "(", ")", "if", "header", ".", "lower", "(", ")", "not", "in", "filtered_headers", ":", "headers_out", ".", "append", "(", "(", "header", ",", "value", ")", ")", "return", "headers_out" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/proxy.py#L250-L280
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/losses/util.py
python
get_regularization_losses
(scope=None)
return ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES, scope)
Gets the list of regularization losses. Args: scope: An optional scope name for filtering the losses to return. Returns: A list of regularization losses as Tensors.
Gets the list of regularization losses.
[ "Gets", "the", "list", "of", "regularization", "losses", "." ]
def get_regularization_losses(scope=None): """Gets the list of regularization losses. Args: scope: An optional scope name for filtering the losses to return. Returns: A list of regularization losses as Tensors. """ return ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES, scope)
[ "def", "get_regularization_losses", "(", "scope", "=", "None", ")", ":", "return", "ops", ".", "get_collection", "(", "ops", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ",", "scope", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/losses/util.py#L59-L68
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/engine/node.py
python
Node.iterate_inbound
(self)
Yields tuples representing the data inbound from other nodes. Yields: tuples like: (inbound_layer, node_index, tensor_index, tensor).
Yields tuples representing the data inbound from other nodes.
[ "Yields", "tuples", "representing", "the", "data", "inbound", "from", "other", "nodes", "." ]
def iterate_inbound(self): """Yields tuples representing the data inbound from other nodes. Yields: tuples like: (inbound_layer, node_index, tensor_index, tensor). """ for kt in self.keras_inputs: keras_history = kt._keras_history layer = keras_history.layer node_index = keras_history.node_index tensor_index = keras_history.tensor_index yield layer, node_index, tensor_index, kt
[ "def", "iterate_inbound", "(", "self", ")", ":", "for", "kt", "in", "self", ".", "keras_inputs", ":", "keras_history", "=", "kt", ".", "_keras_history", "layer", "=", "keras_history", ".", "layer", "node_index", "=", "keras_history", ".", "node_index", "tensor_index", "=", "keras_history", ".", "tensor_index", "yield", "layer", ",", "node_index", ",", "tensor_index", ",", "kt" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/node.py#L130-L141
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/maya/scripts/walterVariantsMenu.py
python
VariantsMenu._createMenu
(self, primPath, index, variantSet)
return VariantSetMenu(primPath, variantSet, self)
Implementation of BaseVariantsMenu.
Implementation of BaseVariantsMenu.
[ "Implementation", "of", "BaseVariantsMenu", "." ]
def _createMenu(self, primPath, index, variantSet): """Implementation of BaseVariantsMenu.""" return VariantSetMenu(primPath, variantSet, self)
[ "def", "_createMenu", "(", "self", ",", "primPath", ",", "index", ",", "variantSet", ")", ":", "return", "VariantSetMenu", "(", "primPath", ",", "variantSet", ",", "self", ")" ]
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/walterVariantsMenu.py#L52-L54
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/algorithms/sfm/OpenSfM/opensfm/commands/match_features.py
python
match_candidates_by_order
(images, max_neighbors)
return pairs
Find candidate matching pairs by sequence order.
Find candidate matching pairs by sequence order.
[ "Find", "candidate", "matching", "pairs", "by", "sequence", "order", "." ]
def match_candidates_by_order(images, max_neighbors): """Find candidate matching pairs by sequence order.""" if max_neighbors <= 0: return set() n = (max_neighbors + 1) // 2 pairs = set() for i, image in enumerate(images): a = max(0, i - n) b = min(len(images), i + n) for j in range(a, b): if i != j: pairs.add(tuple(sorted((images[i], images[j])))) return pairs
[ "def", "match_candidates_by_order", "(", "images", ",", "max_neighbors", ")", ":", "if", "max_neighbors", "<=", "0", ":", "return", "set", "(", ")", "n", "=", "(", "max_neighbors", "+", "1", ")", "//", "2", "pairs", "=", "set", "(", ")", "for", "i", ",", "image", "in", "enumerate", "(", "images", ")", ":", "a", "=", "max", "(", "0", ",", "i", "-", "n", ")", "b", "=", "min", "(", "len", "(", "images", ")", ",", "i", "+", "n", ")", "for", "j", "in", "range", "(", "a", ",", "b", ")", ":", "if", "i", "!=", "j", ":", "pairs", ".", "add", "(", "tuple", "(", "sorted", "(", "(", "images", "[", "i", "]", ",", "images", "[", "j", "]", ")", ")", ")", ")", "return", "pairs" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/commands/match_features.py#L145-L158
uncrustify/uncrustify
719cf9d153a9ec14be8d5f01536121ced71d8bc9
scripts/option_reducer.py
python
write_config_file2
(args)
Writes two option lists into a config file Parameters ---------------------------------------------------------------------------- :param args: list< tuple< str, str > >, list< tuple< str, str > >, str, int this function is intended to be called by multiprocessing.pool.map() therefore all arguments are inside a list / tuple: config_list: list< tuple< str, str > > the first list of tuples containing option names and values test_list: list< tuple< str, str > > the second list of tuples containing option names and values tmp_dir: str path to a directory in which the config file is going to be written idx: int index that is going to be used for the filename
Writes two option lists into a config file
[ "Writes", "two", "option", "lists", "into", "a", "config", "file" ]
def write_config_file2(args): """ Writes two option lists into a config file Parameters ---------------------------------------------------------------------------- :param args: list< tuple< str, str > >, list< tuple< str, str > >, str, int this function is intended to be called by multiprocessing.pool.map() therefore all arguments are inside a list / tuple: config_list: list< tuple< str, str > > the first list of tuples containing option names and values test_list: list< tuple< str, str > > the second list of tuples containing option names and values tmp_dir: str path to a directory in which the config file is going to be written idx: int index that is going to be used for the filename """ config_list0, config_list1, tmp_dir, idx = args with open("%s%suncr-r-%d.cfg" % (tmp_dir, os_path_sep, idx), 'w') as f: print_config(config_list0, target_file_obj=f) print("", end='\n', file=f) print_config(config_list1, target_file_obj=f)
[ "def", "write_config_file2", "(", "args", ")", ":", "config_list0", ",", "config_list1", ",", "tmp_dir", ",", "idx", "=", "args", "with", "open", "(", "\"%s%suncr-r-%d.cfg\"", "%", "(", "tmp_dir", ",", "os_path_sep", ",", "idx", ")", ",", "'w'", ")", "as", "f", ":", "print_config", "(", "config_list0", ",", "target_file_obj", "=", "f", ")", "print", "(", "\"\"", ",", "end", "=", "'\\n'", ",", "file", "=", "f", ")", "print_config", "(", "config_list1", ",", "target_file_obj", "=", "f", ")" ]
https://github.com/uncrustify/uncrustify/blob/719cf9d153a9ec14be8d5f01536121ced71d8bc9/scripts/option_reducer.py#L286-L317
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathDressupHoldingTags.py
python
Create
(baseObject, name="DressupTag")
return obj
Create(basePath, name='DressupTag') ... create tag dressup object for the given base path.
Create(basePath, name='DressupTag') ... create tag dressup object for the given base path.
[ "Create", "(", "basePath", "name", "=", "DressupTag", ")", "...", "create", "tag", "dressup", "object", "for", "the", "given", "base", "path", "." ]
def Create(baseObject, name="DressupTag"): """ Create(basePath, name='DressupTag') ... create tag dressup object for the given base path. """ if not baseObject.isDerivedFrom("Path::Feature"): PathLog.error( translate("Path_DressupTag", "The selected object is not a path") + "\n" ) return None if baseObject.isDerivedFrom("Path::FeatureCompoundPython"): PathLog.error(translate("Path_DressupTag", "Please select a Profile object")) return None obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython", name) dbo = ObjectTagDressup(obj, baseObject) job = PathUtils.findParentJob(baseObject) job.Proxy.addOperation(obj, baseObject) dbo.setup(obj, True) return obj
[ "def", "Create", "(", "baseObject", ",", "name", "=", "\"DressupTag\"", ")", ":", "if", "not", "baseObject", ".", "isDerivedFrom", "(", "\"Path::Feature\"", ")", ":", "PathLog", ".", "error", "(", "translate", "(", "\"Path_DressupTag\"", ",", "\"The selected object is not a path\"", ")", "+", "\"\\n\"", ")", "return", "None", "if", "baseObject", ".", "isDerivedFrom", "(", "\"Path::FeatureCompoundPython\"", ")", ":", "PathLog", ".", "error", "(", "translate", "(", "\"Path_DressupTag\"", ",", "\"Please select a Profile object\"", ")", ")", "return", "None", "obj", "=", "FreeCAD", ".", "ActiveDocument", ".", "addObject", "(", "\"Path::FeaturePython\"", ",", "name", ")", "dbo", "=", "ObjectTagDressup", "(", "obj", ",", "baseObject", ")", "job", "=", "PathUtils", ".", "findParentJob", "(", "baseObject", ")", "job", ".", "Proxy", ".", "addOperation", "(", "obj", ",", "baseObject", ")", "dbo", ".", "setup", "(", "obj", ",", "True", ")", "return", "obj" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathDressupHoldingTags.py#L1383-L1402
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/Direct/RunDescriptor.py
python
RunList.get_last_ind2sum
(self,sum_runs)
return ind
Get last run number contributing to sum
Get last run number contributing to sum
[ "Get", "last", "run", "number", "contributing", "to", "sum" ]
def get_last_ind2sum(self,sum_runs): """Get last run number contributing to sum""" if self._last_ind2sum >= 0 and self._last_ind2sum < len(self._run_numbers): ind = self._last_ind2sum else: if sum_runs: ind = len(self._run_numbers) - 1 else: ind = 0 return ind
[ "def", "get_last_ind2sum", "(", "self", ",", "sum_runs", ")", ":", "if", "self", ".", "_last_ind2sum", ">=", "0", "and", "self", ".", "_last_ind2sum", "<", "len", "(", "self", ".", "_run_numbers", ")", ":", "ind", "=", "self", ".", "_last_ind2sum", "else", ":", "if", "sum_runs", ":", "ind", "=", "len", "(", "self", ".", "_run_numbers", ")", "-", "1", "else", ":", "ind", "=", "0", "return", "ind" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/RunDescriptor.py#L287-L297
pskun/finance_news_analysis
6ac13e32deede37a4cf57bba8b2897941ae3d80d
utils/file_operator.py
python
FileMultiReadWrite.read
(self)
return line
从文件中读
从文件中读
[ "从文件中读" ]
def read(self): ''' 从文件中读 ''' self.lock() line = self.file.readline() if line == "": line = None self.unlock() return line
[ "def", "read", "(", "self", ")", ":", "self", ".", "lock", "(", ")", "line", "=", "self", ".", "file", ".", "readline", "(", ")", "if", "line", "==", "\"\"", ":", "line", "=", "None", "self", ".", "unlock", "(", ")", "return", "line" ]
https://github.com/pskun/finance_news_analysis/blob/6ac13e32deede37a4cf57bba8b2897941ae3d80d/utils/file_operator.py#L46-L53
telefonicaid/fiware-orion
27c3202b9ddcfb9e3635a0af8d373f76e89b1d24
scripts/cpplint.py
python
_ClassState.CheckFinished
(self, filename, error)
Checks that all classes have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
Checks that all classes have been completely parsed.
[ "Checks", "that", "all", "classes", "have", "been", "completely", "parsed", "." ]
def CheckFinished(self, filename, error): """Checks that all classes have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ if self.classinfo_stack: # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. error(filename, self.classinfo_stack[0].linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % self.classinfo_stack[0].name)
[ "def", "CheckFinished", "(", "self", ",", "filename", ",", "error", ")", ":", "if", "self", ".", "classinfo_stack", ":", "# Note: This test can result in false positives if #ifdef constructs", "# get in the way of brace matching. See the testBuildClass test in", "# cpplint_unittest.py for an example of this.", "error", "(", "filename", ",", "self", ".", "classinfo_stack", "[", "0", "]", ".", "linenum", ",", "'build/class'", ",", "5", ",", "'Failed to find complete declaration of class %s'", "%", "self", ".", "classinfo_stack", "[", "0", "]", ".", "name", ")" ]
https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/cpplint.py#L1301-L1315
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py
python
GetIncludedBuildFiles
(build_file_path, aux_data, included=None)
return included
Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merged into build_file_path's dict. aux_data is a dict containing a key for each build file or included build file. Those keys provide access to dicts whose "included" keys contain lists of all other files included by the build file. included should be left at its default None value by external callers. It is used for recursion. The returned list will not contain any duplicate entries. Each build file in the list will be relative to the current directory.
Return a list of all build files included into build_file_path.
[ "Return", "a", "list", "of", "all", "build", "files", "included", "into", "build_file_path", "." ]
def GetIncludedBuildFiles(build_file_path, aux_data, included=None): """Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merged into build_file_path's dict. aux_data is a dict containing a key for each build file or included build file. Those keys provide access to dicts whose "included" keys contain lists of all other files included by the build file. included should be left at its default None value by external callers. It is used for recursion. The returned list will not contain any duplicate entries. Each build file in the list will be relative to the current directory. """ if included == None: included = [] if build_file_path in included: return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get('included', []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included
[ "def", "GetIncludedBuildFiles", "(", "build_file_path", ",", "aux_data", ",", "included", "=", "None", ")", ":", "if", "included", "==", "None", ":", "included", "=", "[", "]", "if", "build_file_path", "in", "included", ":", "return", "included", "included", ".", "append", "(", "build_file_path", ")", "for", "included_build_file", "in", "aux_data", "[", "build_file_path", "]", ".", "get", "(", "'included'", ",", "[", "]", ")", ":", "GetIncludedBuildFiles", "(", "included_build_file", ",", "aux_data", ",", "included", ")", "return", "included" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py#L143-L173
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/annotate.py
python
AnnotateReporter.report
(self, morfs, config, directory=None)
Run the report. See `coverage.report()` for arguments.
Run the report.
[ "Run", "the", "report", "." ]
def report(self, morfs, config, directory=None): """Run the report. See `coverage.report()` for arguments. """ self.report_files(self.annotate_file, morfs, config, directory)
[ "def", "report", "(", "self", ",", "morfs", ",", "config", ",", "directory", "=", "None", ")", ":", "self", ".", "report_files", "(", "self", ".", "annotate_file", ",", "morfs", ",", "config", ",", "directory", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/annotate.py#L36-L42
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/android/appstats.py
python
OutputBeautifier.__PrintHeaderHelper
(self, snapshot, show_labels, show_timestamp, show_mem, show_net, show_trailer)
return ' '.join(titles)
Helper method to concat various header entries together into one header. This will line up with a entry built by __PrintStatsHelper if the same values are passed to it.
Helper method to concat various header entries together into one header. This will line up with a entry built by __PrintStatsHelper if the same values are passed to it.
[ "Helper", "method", "to", "concat", "various", "header", "entries", "together", "into", "one", "header", ".", "This", "will", "line", "up", "with", "a", "entry", "built", "by", "__PrintStatsHelper", "if", "the", "same", "values", "are", "passed", "to", "it", "." ]
def __PrintHeaderHelper(self, snapshot, show_labels, show_timestamp, show_mem, show_net, show_trailer): """Helper method to concat various header entries together into one header. This will line up with a entry built by __PrintStatsHelper if the same values are passed to it.""" titles = [] if show_labels: titles.append(self.__PrintPidLabelHeader(snapshot)) if show_timestamp: titles.append(self.__PrintTimestampHeader()) if show_mem: titles.append(self.__PrintMemoryStatsHeader()) if show_net: titles.append(self.__PrintNetworkStatsHeader()) if show_trailer: titles.append(self.__PrintTrailingHeader(snapshot)) return ' '.join(titles)
[ "def", "__PrintHeaderHelper", "(", "self", ",", "snapshot", ",", "show_labels", ",", "show_timestamp", ",", "show_mem", ",", "show_net", ",", "show_trailer", ")", ":", "titles", "=", "[", "]", "if", "show_labels", ":", "titles", ".", "append", "(", "self", ".", "__PrintPidLabelHeader", "(", "snapshot", ")", ")", "if", "show_timestamp", ":", "titles", ".", "append", "(", "self", ".", "__PrintTimestampHeader", "(", ")", ")", "if", "show_mem", ":", "titles", ".", "append", "(", "self", ".", "__PrintMemoryStatsHeader", "(", ")", ")", "if", "show_net", ":", "titles", ".", "append", "(", "self", ".", "__PrintNetworkStatsHeader", "(", ")", ")", "if", "show_trailer", ":", "titles", ".", "append", "(", "self", ".", "__PrintTrailingHeader", "(", "snapshot", ")", ")", "return", "' '", ".", "join", "(", "titles", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/appstats.py#L675-L701
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/build_swift/build_swift/presets.py
python
PresetParser.presets
(self)
return self._presets.values()
Returns a list of all parsed presets in the order they were parsed.
Returns a list of all parsed presets in the order they were parsed.
[ "Returns", "a", "list", "of", "all", "parsed", "presets", "in", "the", "order", "they", "were", "parsed", "." ]
def presets(self): """Returns a list of all parsed presets in the order they were parsed. """ return self._presets.values()
[ "def", "presets", "(", "self", ")", ":", "return", "self", ".", "_presets", ".", "values", "(", ")" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/build_swift/build_swift/presets.py#L236-L240
hcdth011/ROS-Hydro-SLAM
629448eecd2c9a3511158115fa53ea9e4ae41359
rpg_vikit/vikit_py/src/vikit_py/transformations.py
python
projection_matrix
(point, normal, direction=None, perspective=None, pseudo=False)
return M
Return matrix to project onto plane defined by point and normal. Using either perspective point, projection direction, or none of both. If pseudo is True, perspective projections will preserve relative depth such that Perspective = dot(Orthogonal, PseudoPerspective). >>> P = projection_matrix((0, 0, 0), (1, 0, 0)) >>> numpy.allclose(P[1:, 1:], numpy.identity(4)[1:, 1:]) True >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> persp = numpy.random.random(3) - 0.5 >>> P0 = projection_matrix(point, normal) >>> P1 = projection_matrix(point, normal, direction=direct) >>> P2 = projection_matrix(point, normal, perspective=persp) >>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True) >>> is_same_transform(P2, numpy.dot(P0, P3)) True >>> P = projection_matrix((3, 0, 0), (1, 1, 0), (1, 0, 0)) >>> v0 = (numpy.random.rand(4, 5) - 0.5) * 20.0 >>> v0[3] = 1.0 >>> v1 = numpy.dot(P, v0) >>> numpy.allclose(v1[1], v0[1]) True >>> numpy.allclose(v1[0], 3.0-v1[1]) True
Return matrix to project onto plane defined by point and normal.
[ "Return", "matrix", "to", "project", "onto", "plane", "defined", "by", "point", "and", "normal", "." ]
def projection_matrix(point, normal, direction=None, perspective=None, pseudo=False): """Return matrix to project onto plane defined by point and normal. Using either perspective point, projection direction, or none of both. If pseudo is True, perspective projections will preserve relative depth such that Perspective = dot(Orthogonal, PseudoPerspective). >>> P = projection_matrix((0, 0, 0), (1, 0, 0)) >>> numpy.allclose(P[1:, 1:], numpy.identity(4)[1:, 1:]) True >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> persp = numpy.random.random(3) - 0.5 >>> P0 = projection_matrix(point, normal) >>> P1 = projection_matrix(point, normal, direction=direct) >>> P2 = projection_matrix(point, normal, perspective=persp) >>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True) >>> is_same_transform(P2, numpy.dot(P0, P3)) True >>> P = projection_matrix((3, 0, 0), (1, 1, 0), (1, 0, 0)) >>> v0 = (numpy.random.rand(4, 5) - 0.5) * 20.0 >>> v0[3] = 1.0 >>> v1 = numpy.dot(P, v0) >>> numpy.allclose(v1[1], v0[1]) True >>> numpy.allclose(v1[0], 3.0-v1[1]) True """ M = numpy.identity(4) point = numpy.array(point[:3], dtype=numpy.float64, copy=False) normal = unit_vector(normal[:3]) if perspective is not None: # perspective projection perspective = numpy.array(perspective[:3], dtype=numpy.float64, copy=False) M[0, 0] = M[1, 1] = M[2, 2] = numpy.dot(perspective-point, normal) M[:3, :3] -= numpy.outer(perspective, normal) if pseudo: # preserve relative depth M[:3, :3] -= numpy.outer(normal, normal) M[:3, 3] = numpy.dot(point, normal) * (perspective+normal) else: M[:3, 3] = numpy.dot(point, normal) * perspective M[3, :3] = -normal M[3, 3] = numpy.dot(perspective, normal) elif direction is not None: # parallel projection direction = numpy.array(direction[:3], dtype=numpy.float64, copy=False) scale = numpy.dot(direction, normal) M[:3, :3] -= numpy.outer(direction, normal) / scale M[:3, 3] = direction * (numpy.dot(point, normal) / scale) else: # orthogonal projection M[:3, :3] -= numpy.outer(normal, normal) M[:3, 3] = numpy.dot(point, normal) * normal return M
[ "def", "projection_matrix", "(", "point", ",", "normal", ",", "direction", "=", "None", ",", "perspective", "=", "None", ",", "pseudo", "=", "False", ")", ":", "M", "=", "numpy", ".", "identity", "(", "4", ")", "point", "=", "numpy", ".", "array", "(", "point", "[", ":", "3", "]", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "normal", "=", "unit_vector", "(", "normal", "[", ":", "3", "]", ")", "if", "perspective", "is", "not", "None", ":", "# perspective projection", "perspective", "=", "numpy", ".", "array", "(", "perspective", "[", ":", "3", "]", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "M", "[", "0", ",", "0", "]", "=", "M", "[", "1", ",", "1", "]", "=", "M", "[", "2", ",", "2", "]", "=", "numpy", ".", "dot", "(", "perspective", "-", "point", ",", "normal", ")", "M", "[", ":", "3", ",", ":", "3", "]", "-=", "numpy", ".", "outer", "(", "perspective", ",", "normal", ")", "if", "pseudo", ":", "# preserve relative depth", "M", "[", ":", "3", ",", ":", "3", "]", "-=", "numpy", ".", "outer", "(", "normal", ",", "normal", ")", "M", "[", ":", "3", ",", "3", "]", "=", "numpy", ".", "dot", "(", "point", ",", "normal", ")", "*", "(", "perspective", "+", "normal", ")", "else", ":", "M", "[", ":", "3", ",", "3", "]", "=", "numpy", ".", "dot", "(", "point", ",", "normal", ")", "*", "perspective", "M", "[", "3", ",", ":", "3", "]", "=", "-", "normal", "M", "[", "3", ",", "3", "]", "=", "numpy", ".", "dot", "(", "perspective", ",", "normal", ")", "elif", "direction", "is", "not", "None", ":", "# parallel projection", "direction", "=", "numpy", ".", "array", "(", "direction", "[", ":", "3", "]", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "scale", "=", "numpy", ".", "dot", "(", "direction", ",", "normal", ")", "M", "[", ":", "3", ",", ":", "3", "]", "-=", "numpy", ".", "outer", "(", "direction", ",", "normal", ")", "/", "scale", "M", "[", ":", "3", ",", "3", "]", "=", "direction", "*", "(", "numpy", ".", "dot", "(", "point", ",", "normal", ")", "/", "scale", ")", "else", ":", "# orthogonal projection", "M", "[", ":", "3", ",", ":", "3", "]", "-=", "numpy", ".", "outer", "(", "normal", ",", "normal", ")", "M", "[", ":", "3", ",", "3", "]", "=", "numpy", ".", "dot", "(", "point", ",", "normal", ")", "*", "normal", "return", "M" ]
https://github.com/hcdth011/ROS-Hydro-SLAM/blob/629448eecd2c9a3511158115fa53ea9e4ae41359/rpg_vikit/vikit_py/src/vikit_py/transformations.py#L441-L500
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl_check_compatibility.py
python
get_field_type
(field: Union[syntax.Field, syntax.Command], idl_file: syntax.IDLParsedSpec, idl_file_path: str)
return field_type
Resolve and get field type of a field from the IDL file.
Resolve and get field type of a field from the IDL file.
[ "Resolve", "and", "get", "field", "type", "of", "a", "field", "from", "the", "IDL", "file", "." ]
def get_field_type(field: Union[syntax.Field, syntax.Command], idl_file: syntax.IDLParsedSpec, idl_file_path: str) -> Optional[Union[syntax.Enum, syntax.Struct, syntax.Type]]: """Resolve and get field type of a field from the IDL file.""" parser_ctxt = errors.ParserContext(idl_file_path, errors.ParserErrorCollection()) field_type = idl_file.spec.symbols.resolve_field_type(parser_ctxt, field, field.name, field.type) if parser_ctxt.errors.has_errors(): parser_ctxt.errors.dump_errors() return field_type
[ "def", "get_field_type", "(", "field", ":", "Union", "[", "syntax", ".", "Field", ",", "syntax", ".", "Command", "]", ",", "idl_file", ":", "syntax", ".", "IDLParsedSpec", ",", "idl_file_path", ":", "str", ")", "->", "Optional", "[", "Union", "[", "syntax", ".", "Enum", ",", "syntax", ".", "Struct", ",", "syntax", ".", "Type", "]", "]", ":", "parser_ctxt", "=", "errors", ".", "ParserContext", "(", "idl_file_path", ",", "errors", ".", "ParserErrorCollection", "(", ")", ")", "field_type", "=", "idl_file", ".", "spec", ".", "symbols", ".", "resolve_field_type", "(", "parser_ctxt", ",", "field", ",", "field", ".", "name", ",", "field", ".", "type", ")", "if", "parser_ctxt", ".", "errors", ".", "has_errors", "(", ")", ":", "parser_ctxt", ".", "errors", ".", "dump_errors", "(", ")", "return", "field_type" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl_check_compatibility.py#L274-L282
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/pgen2/parse.py
python
Parser.classify
(self, type, value, context)
return ilabel
Turn a token into a label. (Internal)
Turn a token into a label. (Internal)
[ "Turn", "a", "token", "into", "a", "label", ".", "(", "Internal", ")" ]
def classify(self, type, value, context): """Turn a token into a label. (Internal)""" if type == token.NAME: # Keep a listing of all used names self.used_names.add(value) # Check for reserved words ilabel = self.grammar.keywords.get(value) if ilabel is not None: return ilabel ilabel = self.grammar.tokens.get(type) if ilabel is None: raise ParseError("bad token", type, value, context) return ilabel
[ "def", "classify", "(", "self", ",", "type", ",", "value", ",", "context", ")", ":", "if", "type", "==", "token", ".", "NAME", ":", "# Keep a listing of all used names", "self", ".", "used_names", ".", "add", "(", "value", ")", "# Check for reserved words", "ilabel", "=", "self", ".", "grammar", ".", "keywords", ".", "get", "(", "value", ")", "if", "ilabel", "is", "not", "None", ":", "return", "ilabel", "ilabel", "=", "self", ".", "grammar", ".", "tokens", ".", "get", "(", "type", ")", "if", "ilabel", "is", "None", ":", "raise", "ParseError", "(", "\"bad token\"", ",", "type", ",", "value", ",", "context", ")", "return", "ilabel" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/pgen2/parse.py#L161-L173
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/arch/micro_asm.py
python
t_ANY_COMMENT
(t)
r'\#[^\n]*(?=\n)
r'\#[^\n]*(?=\n)
[ "r", "\\", "#", "[", "^", "\\", "n", "]", "*", "(", "?", "=", "\\", "n", ")" ]
def t_ANY_COMMENT(t): r'\#[^\n]*(?=\n)'
[ "def", "t_ANY_COMMENT", "(", "t", ")", ":" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/arch/micro_asm.py#L207-L208
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
TextAttrBorder.SetStyle
(*args, **kwargs)
return _richtext.TextAttrBorder_SetStyle(*args, **kwargs)
SetStyle(self, int style)
SetStyle(self, int style)
[ "SetStyle", "(", "self", "int", "style", ")" ]
def SetStyle(*args, **kwargs): """SetStyle(self, int style)""" return _richtext.TextAttrBorder_SetStyle(*args, **kwargs)
[ "def", "SetStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "TextAttrBorder_SetStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L349-L351
scribusproject/scribus
41ec7c775a060912cf251682a8b1437f753f80f4
scribus/plugins/scriptplugin/scripts/FontSample.py
python
create_empty_samplepage
(pageNum, getSizeOnly)
return pageNum
Creates a new page and increments page number by one. Note getSizeOnly is now evaluated. Will still generate page number increment but will not actually create the new page or place the number on the page.
Creates a new page and increments page number by one.
[ "Creates", "a", "new", "page", "and", "increments", "page", "number", "by", "one", "." ]
def create_empty_samplepage(pageNum, getSizeOnly): """Creates a new page and increments page number by one. Note getSizeOnly is now evaluated. Will still generate page number increment but will not actually create the new page or place the number on the page.""" if not getSizeOnly: scribus.newPage(-1) pageNum = pageNum + 1 set_odd_even(pageNum) if not getSizeOnly: if userPrefs['wantPageNumbers']: add_page_num(pageNum) return pageNum
[ "def", "create_empty_samplepage", "(", "pageNum", ",", "getSizeOnly", ")", ":", "if", "not", "getSizeOnly", ":", "scribus", ".", "newPage", "(", "-", "1", ")", "pageNum", "=", "pageNum", "+", "1", "set_odd_even", "(", "pageNum", ")", "if", "not", "getSizeOnly", ":", "if", "userPrefs", "[", "'wantPageNumbers'", "]", ":", "add_page_num", "(", "pageNum", ")", "return", "pageNum" ]
https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scriptplugin/scripts/FontSample.py#L651-L663
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/asyncio/base_events.py
python
BaseEventLoop.set_task_factory
(self, factory)
Set a task factory that will be used by loop.create_task(). If factory is None the default task factory will be set. If factory is a callable, it should have a signature matching '(loop, coro)', where 'loop' will be a reference to the active event loop, 'coro' will be a coroutine object. The callable must return a Future.
Set a task factory that will be used by loop.create_task().
[ "Set", "a", "task", "factory", "that", "will", "be", "used", "by", "loop", ".", "create_task", "()", "." ]
def set_task_factory(self, factory): """Set a task factory that will be used by loop.create_task(). If factory is None the default task factory will be set. If factory is a callable, it should have a signature matching '(loop, coro)', where 'loop' will be a reference to the active event loop, 'coro' will be a coroutine object. The callable must return a Future. """ if factory is not None and not callable(factory): raise TypeError('task factory must be a callable or None') self._task_factory = factory
[ "def", "set_task_factory", "(", "self", ",", "factory", ")", ":", "if", "factory", "is", "not", "None", "and", "not", "callable", "(", "factory", ")", ":", "raise", "TypeError", "(", "'task factory must be a callable or None'", ")", "self", ".", "_task_factory", "=", "factory" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/asyncio/base_events.py#L411-L423
apache/kudu
90895ce76590f10730ad7aac3613b69d89ff5422
build-support/check_compatibility.py
python
get_git_hash
(revname)
return check_output(["git", "rev-parse", revname], cwd=get_repo_dir()).decode('utf-8').strip()
Convert 'revname' to its SHA-1 hash.
Convert 'revname' to its SHA-1 hash.
[ "Convert", "revname", "to", "its", "SHA", "-", "1", "hash", "." ]
def get_git_hash(revname): """ Convert 'revname' to its SHA-1 hash. """ return check_output(["git", "rev-parse", revname], cwd=get_repo_dir()).decode('utf-8').strip()
[ "def", "get_git_hash", "(", "revname", ")", ":", "return", "check_output", "(", "[", "\"git\"", ",", "\"rev-parse\"", ",", "revname", "]", ",", "cwd", "=", "get_repo_dir", "(", ")", ")", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")" ]
https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/check_compatibility.py#L91-L94
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
samples/networking/01-simple-connection/client.py
python
GameClientRepository.gotCreateReady
(self)
Ready to enter the world. Expand our interest to include any other zones
Ready to enter the world. Expand our interest to include any other zones
[ "Ready", "to", "enter", "the", "world", ".", "Expand", "our", "interest", "to", "include", "any", "other", "zones" ]
def gotCreateReady(self): """ Ready to enter the world. Expand our interest to include any other zones """ # This method checks whether we actually have a valid doID range # to create distributed objects yet if not self.haveCreateAuthority(): # Not ready yet. return # we are ready now, so ignore further createReady events self.ignore(self.uniqueName('createReady')) print("Client Ready") base.messenger.send("client-ready")
[ "def", "gotCreateReady", "(", "self", ")", ":", "# This method checks whether we actually have a valid doID range", "# to create distributed objects yet", "if", "not", "self", ".", "haveCreateAuthority", "(", ")", ":", "# Not ready yet.", "return", "# we are ready now, so ignore further createReady events", "self", ".", "ignore", "(", "self", ".", "uniqueName", "(", "'createReady'", ")", ")", "print", "(", "\"Client Ready\"", ")", "base", ".", "messenger", ".", "send", "(", "\"client-ready\"", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/samples/networking/01-simple-connection/client.py#L104-L118
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
TopLevelWindow.GetDefaultSize
(*args, **kwargs)
return _windows_.TopLevelWindow_GetDefaultSize(*args, **kwargs)
GetDefaultSize() -> Size
GetDefaultSize() -> Size
[ "GetDefaultSize", "()", "-", ">", "Size" ]
def GetDefaultSize(*args, **kwargs): """GetDefaultSize() -> Size""" return _windows_.TopLevelWindow_GetDefaultSize(*args, **kwargs)
[ "def", "GetDefaultSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "TopLevelWindow_GetDefaultSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L502-L504
bayandin/chromedriver
d40a2092b50f2fca817221eeb5ea093e0e642c10
util.py
python
MaybeDelete
(path)
Deletes the given file or directory (recurisvely), if it exists.
Deletes the given file or directory (recurisvely), if it exists.
[ "Deletes", "the", "given", "file", "or", "directory", "(", "recurisvely", ")", "if", "it", "exists", "." ]
def MaybeDelete(path): """Deletes the given file or directory (recurisvely), if it exists.""" if os.path.exists(path): Delete(path)
[ "def", "MaybeDelete", "(", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "Delete", "(", "path", ")" ]
https://github.com/bayandin/chromedriver/blob/d40a2092b50f2fca817221eeb5ea093e0e642c10/util.py#L111-L114
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
ParseArguments
(args)
return filenames
Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint.
Parses the command line arguments.
[ "Parses", "the", "command", "line", "arguments", "." ]
def ParseArguments(args): """Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint. """ try: (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', 'counting=', 'filter=', 'root=']) except getopt.GetoptError: PrintUsage('Invalid arguments.') verbosity = _VerboseLevel() output_format = _OutputFormat() filters = '' counting_style = '' for (opt, val) in opts: if opt == '--help': PrintUsage(None) elif opt == '--output': if not val in ('emacs', 'vs7', 'eclipse'): PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.') output_format = val elif opt == '--verbose': verbosity = int(val) elif opt == '--filter': filters = val if not filters: PrintCategories() elif opt == '--counting': if val not in ('total', 'toplevel', 'detailed'): PrintUsage('Valid counting options are total, toplevel, and detailed') counting_style = val elif opt == '--root': global _root _root = val if not filenames: PrintUsage('No files were specified.') _SetOutputFormat(output_format) _SetVerboseLevel(verbosity) _SetFilters(filters) _SetCountingStyle(counting_style) return filenames
[ "def", "ParseArguments", "(", "args", ")", ":", "try", ":", "(", "opts", ",", "filenames", ")", "=", "getopt", ".", "getopt", "(", "args", ",", "''", ",", "[", "'help'", ",", "'output='", ",", "'verbose='", ",", "'counting='", ",", "'filter='", ",", "'root='", "]", ")", "except", "getopt", ".", "GetoptError", ":", "PrintUsage", "(", "'Invalid arguments.'", ")", "verbosity", "=", "_VerboseLevel", "(", ")", "output_format", "=", "_OutputFormat", "(", ")", "filters", "=", "''", "counting_style", "=", "''", "for", "(", "opt", ",", "val", ")", "in", "opts", ":", "if", "opt", "==", "'--help'", ":", "PrintUsage", "(", "None", ")", "elif", "opt", "==", "'--output'", ":", "if", "not", "val", "in", "(", "'emacs'", ",", "'vs7'", ",", "'eclipse'", ")", ":", "PrintUsage", "(", "'The only allowed output formats are emacs, vs7 and eclipse.'", ")", "output_format", "=", "val", "elif", "opt", "==", "'--verbose'", ":", "verbosity", "=", "int", "(", "val", ")", "elif", "opt", "==", "'--filter'", ":", "filters", "=", "val", "if", "not", "filters", ":", "PrintCategories", "(", ")", "elif", "opt", "==", "'--counting'", ":", "if", "val", "not", "in", "(", "'total'", ",", "'toplevel'", ",", "'detailed'", ")", ":", "PrintUsage", "(", "'Valid counting options are total, toplevel, and detailed'", ")", "counting_style", "=", "val", "elif", "opt", "==", "'--root'", ":", "global", "_root", "_root", "=", "val", "if", "not", "filenames", ":", "PrintUsage", "(", "'No files were specified.'", ")", "_SetOutputFormat", "(", "output_format", ")", "_SetVerboseLevel", "(", "verbosity", ")", "_SetFilters", "(", "filters", ")", "_SetCountingStyle", "(", "counting_style", ")", "return", "filenames" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L3949-L4002
yyzybb537/libgo
4af17b7c67643c4d54aa354dcc77963ea07847d0
third_party/boost.context/tools/build/src/build/type.py
python
set_scanner
(type, scanner)
Sets a scanner class that will be used for this 'type'.
Sets a scanner class that will be used for this 'type'.
[ "Sets", "a", "scanner", "class", "that", "will", "be", "used", "for", "this", "type", "." ]
def set_scanner (type, scanner): """ Sets a scanner class that will be used for this 'type'. """ if __debug__: from .scanner import Scanner assert isinstance(type, basestring) assert issubclass(scanner, Scanner) validate (type) __types [type]['scanner'] = scanner
[ "def", "set_scanner", "(", "type", ",", "scanner", ")", ":", "if", "__debug__", ":", "from", ".", "scanner", "import", "Scanner", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "issubclass", "(", "scanner", ",", "Scanner", ")", "validate", "(", "type", ")", "__types", "[", "type", "]", "[", "'scanner'", "]", "=", "scanner" ]
https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/type.py#L145-L153
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/msw/gizmos.py
python
TreeListColumnInfo.IsShown
(*args, **kwargs)
return _gizmos.TreeListColumnInfo_IsShown(*args, **kwargs)
IsShown(self) -> bool
IsShown(self) -> bool
[ "IsShown", "(", "self", ")", "-", ">", "bool" ]
def IsShown(*args, **kwargs): """IsShown(self) -> bool""" return _gizmos.TreeListColumnInfo_IsShown(*args, **kwargs)
[ "def", "IsShown", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListColumnInfo_IsShown", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/msw/gizmos.py#L428-L430
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
PrintDialogData.IsOk
(*args, **kwargs)
return _windows_.PrintDialogData_IsOk(*args, **kwargs)
IsOk(self) -> bool
IsOk(self) -> bool
[ "IsOk", "(", "self", ")", "-", ">", "bool" ]
def IsOk(*args, **kwargs): """IsOk(self) -> bool""" return _windows_.PrintDialogData_IsOk(*args, **kwargs)
[ "def", "IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PrintDialogData_IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L5146-L5148
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/core/android_action_runner.py
python
AndroidActionRunner.TurnScreenOff
(self)
If device screen is on, turn screen off. If the screen is already off, log a warning and return immediately. Raises: Timeout: If the screen is on and device fails to turn screen off.
If device screen is on, turn screen off. If the screen is already off, log a warning and return immediately.
[ "If", "device", "screen", "is", "on", "turn", "screen", "off", ".", "If", "the", "screen", "is", "already", "off", "log", "a", "warning", "and", "return", "immediately", "." ]
def TurnScreenOff(self): """If device screen is on, turn screen off. If the screen is already off, log a warning and return immediately. Raises: Timeout: If the screen is on and device fails to turn screen off. """ def is_screen_off(): return not self._platform_backend.device.IsScreenOn() self._platform_backend.device.SetScreen(False) util.WaitFor(is_screen_off, 5)
[ "def", "TurnScreenOff", "(", "self", ")", ":", "def", "is_screen_off", "(", ")", ":", "return", "not", "self", ".", "_platform_backend", ".", "device", ".", "IsScreenOn", "(", ")", "self", ".", "_platform_backend", ".", "device", ".", "SetScreen", "(", "False", ")", "util", ".", "WaitFor", "(", "is_screen_off", ",", "5", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/core/android_action_runner.py#L130-L142
osrf/gazebo
f570338107862253229a0514ffea10deab4f4517
tools/cpplint.py
python
_ClassState.CheckFinished
(self, filename, error)
Checks that all classes have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
Checks that all classes have been completely parsed.
[ "Checks", "that", "all", "classes", "have", "been", "completely", "parsed", "." ]
def CheckFinished(self, filename, error): """Checks that all classes have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ if self.classinfo_stack: # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. error(filename, self.classinfo_stack[0].linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % self.classinfo_stack[0].name)
[ "def", "CheckFinished", "(", "self", ",", "filename", ",", "error", ")", ":", "if", "self", ".", "classinfo_stack", ":", "# Note: This test can result in false positives if #ifdef constructs", "# get in the way of brace matching. See the testBuildClass test in", "# cpplint_unittest.py for an example of this.", "error", "(", "filename", ",", "self", ".", "classinfo_stack", "[", "0", "]", ".", "linenum", ",", "'build/class'", ",", "5", ",", "'Failed to find complete declaration of class %s'", "%", "self", ".", "classinfo_stack", "[", "0", "]", ".", "name", ")" ]
https://github.com/osrf/gazebo/blob/f570338107862253229a0514ffea10deab4f4517/tools/cpplint.py#L1286-L1300
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
CustomTreeCtrl.OnMouse
(self, event)
Handles a bunch of ``wx.EVT_MOUSE_EVENTS`` events for :class:`CustomTreeCtrl`. :param `event`: a :class:`MouseEvent` event to be processed.
Handles a bunch of ``wx.EVT_MOUSE_EVENTS`` events for :class:`CustomTreeCtrl`.
[ "Handles", "a", "bunch", "of", "wx", ".", "EVT_MOUSE_EVENTS", "events", "for", ":", "class", ":", "CustomTreeCtrl", "." ]
def OnMouse(self, event): """ Handles a bunch of ``wx.EVT_MOUSE_EVENTS`` events for :class:`CustomTreeCtrl`. :param `event`: a :class:`MouseEvent` event to be processed. """ if not self._anchor: return pt = self.CalcUnscrolledPosition(event.GetPosition()) # Is the mouse over a tree item button? flags = 0 thisItem, flags = self._anchor.HitTest(pt, self, flags, 0) underMouse = thisItem underMouseChanged = underMouse != self._underMouse if underMouse and (flags & TREE_HITTEST_ONITEM) and not event.LeftIsDown() and \ not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()): underMouse = underMouse else: underMouse = None if underMouse != self._underMouse: if self._underMouse: # unhighlight old item self._underMouse = None self._underMouse = underMouse # Determines what item we are hovering over and need a tooltip for hoverItem = thisItem # We do not want a tooltip if we are dragging, or if the edit timer is running if underMouseChanged and not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()): if hoverItem is not None: # Ask the tree control what tooltip (if any) should be shown hevent = TreeEvent(wxEVT_TREE_ITEM_GETTOOLTIP, self.GetId()) hevent._item = hoverItem hevent.SetEventObject(self) if self.GetEventHandler().ProcessEvent(hevent) and hevent.IsAllowed(): self.SetToolTip(hevent._label) elif self.HasAGWFlag(TR_TOOLTIP_ON_LONG_ITEMS): tip = self.GetToolTipString() if hoverItem.IsSeparator(): if tip: self.SetToolTipString('') else: maxsize = self.GetItemSize(hoverItem) itemText = hoverItem.GetText() dc = wx.ClientDC(self) if dc.GetMultiLineTextExtent(itemText)[0] > maxsize: if tip != itemText: self.SetToolTipString(itemText) else: if tip: self.SetToolTipString('') if hoverItem.IsHyperText() and (flags & TREE_HITTEST_ONITEMLABEL) and hoverItem.IsEnabled(): self.SetCursor(wx.StockCursor(wx.CURSOR_HAND)) self._isonhyperlink = True else: if self._isonhyperlink: self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) self._isonhyperlink = False # we process left mouse up event (enables in-place edit), right down # (pass to the user code), left dbl click (activate item) and # dragging/moving events for items drag-and-drop if not (event.LeftDown() or event.LeftUp() or event.RightDown() or event.LeftDClick() or \ event.Dragging() or ((event.Moving() or event.RightUp()) and self._isDragging)): event.Skip() return flags = 0 item, flags = self._anchor.HitTest(pt, self, flags, 0) if event.Dragging() and not self._isDragging and ((flags & TREE_HITTEST_ONITEMICON) or (flags & TREE_HITTEST_ONITEMLABEL)): if self._dragCount == 0: self._dragStart = pt self._countDrag = 0 self._dragCount = self._dragCount + 1 if self._dragCount != 3: # wait until user drags a bit further... return command = (event.RightIsDown() and [wxEVT_TREE_BEGIN_RDRAG] or [wxEVT_TREE_BEGIN_DRAG])[0] nevent = TreeEvent(command, self.GetId()) nevent._item = self._current nevent.SetEventObject(self) newpt = self.CalcScrolledPosition(pt) nevent.SetPoint(newpt) # by default the dragging is not supported, the user code must # explicitly allow the event for it to take place nevent.Veto() if self.GetEventHandler().ProcessEvent(nevent) and nevent.IsAllowed(): # we're going to drag this item self._isDragging = True # remember the old cursor because we will change it while # dragging self._oldCursor = self._cursor # in a single selection control, hide the selection temporarily if not (self.GetAGWWindowStyleFlag() & TR_MULTIPLE): self._oldSelection = self.GetSelection() if self._oldSelection: self._oldSelection.SetHilight(False) self.RefreshLine(self._oldSelection) else: selections = self.GetSelections() if len(selections) == 1: self._oldSelection = selections[0] self._oldSelection.SetHilight(False) self.RefreshLine(self._oldSelection) if self._dragImage: del self._dragImage # Create the custom draw image from the icons and the text of the item self._dragImage = DragImage(self, self._current) self._dragImage.BeginDrag(wx.Point(0,0), self) self._dragImage.Show() self._dragImage.Move(self.CalcScrolledPosition(pt)) elif event.Dragging() and self._isDragging: self._dragImage.Move(self.CalcScrolledPosition(pt)) if self._countDrag == 0 and item: self._oldItem = item if item != self._dropTarget: # unhighlight the previous drop target if self._dropTarget: self._dropTarget.SetHilight(False) self.RefreshLine(self._dropTarget) if item: item.SetHilight(True) self.RefreshLine(item) self._countDrag = self._countDrag + 1 self._dropTarget = item self.Update() if self._countDrag >= 3: # Here I am trying to avoid ugly repainting problems... hope it works self.RefreshLine(self._oldItem) self._countDrag = 0 elif (event.LeftUp() or event.RightUp()) and self._isDragging: if self._dragImage: self._dragImage.EndDrag() if self._dropTarget: self._dropTarget.SetHilight(False) if self._oldSelection: self._oldSelection.SetHilight(True) self.RefreshLine(self._oldSelection) self._oldSelection = None # generate the drag end event event = TreeEvent(wxEVT_TREE_END_DRAG, self.GetId()) event._item = item event._pointDrag = self.CalcScrolledPosition(pt) event.SetEventObject(self) self.GetEventHandler().ProcessEvent(event) self._isDragging = False self._dropTarget = None self.SetCursor(self._oldCursor) if wx.Platform in ["__WXMSW__", "__WXMAC__"]: self.Refresh() else: # Probably this is not enough on GTK. Try a Refresh() if it does not work. wx.YieldIfNeeded() else: # If we got to this point, we are not dragging or moving the mouse. # Because the code in carbon/toplevel.cpp will only set focus to the tree # if we skip for EVT_LEFT_DOWN, we MUST skip this event here for focus to work. # We skip even if we didn't hit an item because we still should # restore focus to the tree control even if we didn't exactly hit an item. if event.LeftDown(): self._hasFocus = True self.SetFocusIgnoringChildren() event.Skip() # here we process only the messages which happen on tree items self._dragCount = 0 if item == None: if self._editCtrl != None and item != self._editCtrl.item(): self._editCtrl.StopEditing() return # we hit the blank area if event.RightDown(): if self._editCtrl != None and item != self._editCtrl.item(): self._editCtrl.StopEditing() self._hasFocus = True self.SetFocusIgnoringChildren() # If the item is already selected, do not update the selection. # Multi-selections should not be cleared if a selected item is clicked. if not self.IsSelected(item): self.DoSelectItem(item, True, False) nevent = TreeEvent(wxEVT_TREE_ITEM_RIGHT_CLICK, self.GetId()) nevent._item = item nevent._pointDrag = self.CalcScrolledPosition(pt) nevent.SetEventObject(self) event.Skip(not self.GetEventHandler().ProcessEvent(nevent)) # Consistent with MSW (for now), send the ITEM_MENU *after* # the RIGHT_CLICK event. TODO: This behaviour may change. nevent2 = TreeEvent(wxEVT_TREE_ITEM_MENU, self.GetId()) nevent2._item = item nevent2._pointDrag = self.CalcScrolledPosition(pt) nevent2.SetEventObject(self) self.GetEventHandler().ProcessEvent(nevent2) elif event.LeftUp(): # this facilitates multiple-item drag-and-drop if self.HasAGWFlag(TR_MULTIPLE): selections = self.GetSelections() if len(selections) > 1 and not event.CmdDown() and not event.ShiftDown(): self.DoSelectItem(item, True, False) if self._lastOnSame: if item == self._current and (flags & TREE_HITTEST_ONITEMLABEL) and self.HasAGWFlag(TR_EDIT_LABELS): if self._editTimer: if self._editTimer.IsRunning(): self._editTimer.Stop() else: self._editTimer = TreeEditTimer(self) self._editTimer.Start(_DELAY, True) self._lastOnSame = False else: # !RightDown() && !LeftUp() ==> LeftDown() || LeftDClick() if not item or not item.IsEnabled(): if self._editCtrl != None and item != self._editCtrl.item(): self._editCtrl.StopEditing() return if self._editCtrl != None and item != self._editCtrl.item(): self._editCtrl.StopEditing() self._hasFocus = True self.SetFocusIgnoringChildren() if event.LeftDown(): self._lastOnSame = item == self._current if flags & TREE_HITTEST_ONITEMBUTTON: # only toggle the item for a single click, double click on # the button doesn't do anything (it toggles the item twice) if event.LeftDown(): self.Toggle(item) # don't select the item if the button was clicked return if item.GetType() > 0 and (flags & TREE_HITTEST_ONITEMCHECKICON) and (flags & TREE_HITTEST_ONITEMLABEL == 0): if event.LeftDown(): if flags & TREE_HITTEST_ONITEM and self.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT): self.DoSelectItem(item, not self.HasAGWFlag(TR_MULTIPLE)) if self.IsItem3State(item): checked = self.GetItem3StateValue(item) checked = (checked+1)%3 else: checked = not self.IsItemChecked(item) self.CheckItem(item, checked) return # clear the previously selected items, if the # user clicked outside of the present selection. # otherwise, perform the deselection on mouse-up. # this allows multiple drag and drop to work. # but if Cmd is down, toggle selection of the clicked item if not self.IsSelected(item) or event.CmdDown(): if flags & TREE_HITTEST_ONITEM: # how should the selection work for this event? if item.IsHyperText(): self.SetItemVisited(item, True) is_multiple, extended_select, unselect_others = EventFlagsToSelType(self.GetAGWWindowStyleFlag(), event.ShiftDown(), event.CmdDown()) self.DoSelectItem(item, unselect_others, extended_select) # Handle hyperlink items... which are a bit odd sometimes elif self.IsSelected(item) and item.IsHyperText(): self.HandleHyperLink(item) # For some reason, Windows isn't recognizing a left double-click, # so we need to simulate it here. Allow 200 milliseconds for now. if event.LeftDClick(): # double clicking should not start editing the item label if self._editTimer: self._editTimer.Stop() self._lastOnSame = False # send activate event first nevent = TreeEvent(wxEVT_TREE_ITEM_ACTIVATED, self.GetId()) nevent._item = item nevent._pointDrag = self.CalcScrolledPosition(pt) nevent.SetEventObject(self) if not self.GetEventHandler().ProcessEvent(nevent): # if the user code didn't process the activate event, # handle it ourselves by toggling the item when it is # double clicked ## if item.HasPlus(): self.Toggle(item)
[ "def", "OnMouse", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "_anchor", ":", "return", "pt", "=", "self", ".", "CalcUnscrolledPosition", "(", "event", ".", "GetPosition", "(", ")", ")", "# Is the mouse over a tree item button?", "flags", "=", "0", "thisItem", ",", "flags", "=", "self", ".", "_anchor", ".", "HitTest", "(", "pt", ",", "self", ",", "flags", ",", "0", ")", "underMouse", "=", "thisItem", "underMouseChanged", "=", "underMouse", "!=", "self", ".", "_underMouse", "if", "underMouse", "and", "(", "flags", "&", "TREE_HITTEST_ONITEM", ")", "and", "not", "event", ".", "LeftIsDown", "(", ")", "and", "not", "self", ".", "_isDragging", "and", "(", "not", "self", ".", "_editTimer", "or", "not", "self", ".", "_editTimer", ".", "IsRunning", "(", ")", ")", ":", "underMouse", "=", "underMouse", "else", ":", "underMouse", "=", "None", "if", "underMouse", "!=", "self", ".", "_underMouse", ":", "if", "self", ".", "_underMouse", ":", "# unhighlight old item", "self", ".", "_underMouse", "=", "None", "self", ".", "_underMouse", "=", "underMouse", "# Determines what item we are hovering over and need a tooltip for", "hoverItem", "=", "thisItem", "# We do not want a tooltip if we are dragging, or if the edit timer is running", "if", "underMouseChanged", "and", "not", "self", ".", "_isDragging", "and", "(", "not", "self", ".", "_editTimer", "or", "not", "self", ".", "_editTimer", ".", "IsRunning", "(", ")", ")", ":", "if", "hoverItem", "is", "not", "None", ":", "# Ask the tree control what tooltip (if any) should be shown", "hevent", "=", "TreeEvent", "(", "wxEVT_TREE_ITEM_GETTOOLTIP", ",", "self", ".", "GetId", "(", ")", ")", "hevent", ".", "_item", "=", "hoverItem", "hevent", ".", "SetEventObject", "(", "self", ")", "if", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "hevent", ")", "and", "hevent", ".", "IsAllowed", "(", ")", ":", "self", ".", "SetToolTip", "(", "hevent", ".", "_label", ")", "elif", "self", ".", "HasAGWFlag", "(", "TR_TOOLTIP_ON_LONG_ITEMS", ")", ":", "tip", "=", "self", ".", "GetToolTipString", "(", ")", "if", "hoverItem", ".", "IsSeparator", "(", ")", ":", "if", "tip", ":", "self", ".", "SetToolTipString", "(", "''", ")", "else", ":", "maxsize", "=", "self", ".", "GetItemSize", "(", "hoverItem", ")", "itemText", "=", "hoverItem", ".", "GetText", "(", ")", "dc", "=", "wx", ".", "ClientDC", "(", "self", ")", "if", "dc", ".", "GetMultiLineTextExtent", "(", "itemText", ")", "[", "0", "]", ">", "maxsize", ":", "if", "tip", "!=", "itemText", ":", "self", ".", "SetToolTipString", "(", "itemText", ")", "else", ":", "if", "tip", ":", "self", ".", "SetToolTipString", "(", "''", ")", "if", "hoverItem", ".", "IsHyperText", "(", ")", "and", "(", "flags", "&", "TREE_HITTEST_ONITEMLABEL", ")", "and", "hoverItem", ".", "IsEnabled", "(", ")", ":", "self", ".", "SetCursor", "(", "wx", ".", "StockCursor", "(", "wx", ".", "CURSOR_HAND", ")", ")", "self", ".", "_isonhyperlink", "=", "True", "else", ":", "if", "self", ".", "_isonhyperlink", ":", "self", ".", "SetCursor", "(", "wx", ".", "StockCursor", "(", "wx", ".", "CURSOR_ARROW", ")", ")", "self", ".", "_isonhyperlink", "=", "False", "# we process left mouse up event (enables in-place edit), right down", "# (pass to the user code), left dbl click (activate item) and", "# dragging/moving events for items drag-and-drop", "if", "not", "(", "event", ".", "LeftDown", "(", ")", "or", "event", ".", "LeftUp", "(", ")", "or", "event", ".", "RightDown", "(", ")", "or", "event", ".", "LeftDClick", "(", ")", "or", "event", ".", "Dragging", "(", ")", "or", "(", "(", "event", ".", "Moving", "(", ")", "or", "event", ".", "RightUp", "(", ")", ")", "and", "self", ".", "_isDragging", ")", ")", ":", "event", ".", "Skip", "(", ")", "return", "flags", "=", "0", "item", ",", "flags", "=", "self", ".", "_anchor", ".", "HitTest", "(", "pt", ",", "self", ",", "flags", ",", "0", ")", "if", "event", ".", "Dragging", "(", ")", "and", "not", "self", ".", "_isDragging", "and", "(", "(", "flags", "&", "TREE_HITTEST_ONITEMICON", ")", "or", "(", "flags", "&", "TREE_HITTEST_ONITEMLABEL", ")", ")", ":", "if", "self", ".", "_dragCount", "==", "0", ":", "self", ".", "_dragStart", "=", "pt", "self", ".", "_countDrag", "=", "0", "self", ".", "_dragCount", "=", "self", ".", "_dragCount", "+", "1", "if", "self", ".", "_dragCount", "!=", "3", ":", "# wait until user drags a bit further...", "return", "command", "=", "(", "event", ".", "RightIsDown", "(", ")", "and", "[", "wxEVT_TREE_BEGIN_RDRAG", "]", "or", "[", "wxEVT_TREE_BEGIN_DRAG", "]", ")", "[", "0", "]", "nevent", "=", "TreeEvent", "(", "command", ",", "self", ".", "GetId", "(", ")", ")", "nevent", ".", "_item", "=", "self", ".", "_current", "nevent", ".", "SetEventObject", "(", "self", ")", "newpt", "=", "self", ".", "CalcScrolledPosition", "(", "pt", ")", "nevent", ".", "SetPoint", "(", "newpt", ")", "# by default the dragging is not supported, the user code must", "# explicitly allow the event for it to take place", "nevent", ".", "Veto", "(", ")", "if", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "nevent", ")", "and", "nevent", ".", "IsAllowed", "(", ")", ":", "# we're going to drag this item", "self", ".", "_isDragging", "=", "True", "# remember the old cursor because we will change it while", "# dragging", "self", ".", "_oldCursor", "=", "self", ".", "_cursor", "# in a single selection control, hide the selection temporarily", "if", "not", "(", "self", ".", "GetAGWWindowStyleFlag", "(", ")", "&", "TR_MULTIPLE", ")", ":", "self", ".", "_oldSelection", "=", "self", ".", "GetSelection", "(", ")", "if", "self", ".", "_oldSelection", ":", "self", ".", "_oldSelection", ".", "SetHilight", "(", "False", ")", "self", ".", "RefreshLine", "(", "self", ".", "_oldSelection", ")", "else", ":", "selections", "=", "self", ".", "GetSelections", "(", ")", "if", "len", "(", "selections", ")", "==", "1", ":", "self", ".", "_oldSelection", "=", "selections", "[", "0", "]", "self", ".", "_oldSelection", ".", "SetHilight", "(", "False", ")", "self", ".", "RefreshLine", "(", "self", ".", "_oldSelection", ")", "if", "self", ".", "_dragImage", ":", "del", "self", ".", "_dragImage", "# Create the custom draw image from the icons and the text of the item ", "self", ".", "_dragImage", "=", "DragImage", "(", "self", ",", "self", ".", "_current", ")", "self", ".", "_dragImage", ".", "BeginDrag", "(", "wx", ".", "Point", "(", "0", ",", "0", ")", ",", "self", ")", "self", ".", "_dragImage", ".", "Show", "(", ")", "self", ".", "_dragImage", ".", "Move", "(", "self", ".", "CalcScrolledPosition", "(", "pt", ")", ")", "elif", "event", ".", "Dragging", "(", ")", "and", "self", ".", "_isDragging", ":", "self", ".", "_dragImage", ".", "Move", "(", "self", ".", "CalcScrolledPosition", "(", "pt", ")", ")", "if", "self", ".", "_countDrag", "==", "0", "and", "item", ":", "self", ".", "_oldItem", "=", "item", "if", "item", "!=", "self", ".", "_dropTarget", ":", "# unhighlight the previous drop target", "if", "self", ".", "_dropTarget", ":", "self", ".", "_dropTarget", ".", "SetHilight", "(", "False", ")", "self", ".", "RefreshLine", "(", "self", ".", "_dropTarget", ")", "if", "item", ":", "item", ".", "SetHilight", "(", "True", ")", "self", ".", "RefreshLine", "(", "item", ")", "self", ".", "_countDrag", "=", "self", ".", "_countDrag", "+", "1", "self", ".", "_dropTarget", "=", "item", "self", ".", "Update", "(", ")", "if", "self", ".", "_countDrag", ">=", "3", ":", "# Here I am trying to avoid ugly repainting problems... hope it works", "self", ".", "RefreshLine", "(", "self", ".", "_oldItem", ")", "self", ".", "_countDrag", "=", "0", "elif", "(", "event", ".", "LeftUp", "(", ")", "or", "event", ".", "RightUp", "(", ")", ")", "and", "self", ".", "_isDragging", ":", "if", "self", ".", "_dragImage", ":", "self", ".", "_dragImage", ".", "EndDrag", "(", ")", "if", "self", ".", "_dropTarget", ":", "self", ".", "_dropTarget", ".", "SetHilight", "(", "False", ")", "if", "self", ".", "_oldSelection", ":", "self", ".", "_oldSelection", ".", "SetHilight", "(", "True", ")", "self", ".", "RefreshLine", "(", "self", ".", "_oldSelection", ")", "self", ".", "_oldSelection", "=", "None", "# generate the drag end event", "event", "=", "TreeEvent", "(", "wxEVT_TREE_END_DRAG", ",", "self", ".", "GetId", "(", ")", ")", "event", ".", "_item", "=", "item", "event", ".", "_pointDrag", "=", "self", ".", "CalcScrolledPosition", "(", "pt", ")", "event", ".", "SetEventObject", "(", "self", ")", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "event", ")", "self", ".", "_isDragging", "=", "False", "self", ".", "_dropTarget", "=", "None", "self", ".", "SetCursor", "(", "self", ".", "_oldCursor", ")", "if", "wx", ".", "Platform", "in", "[", "\"__WXMSW__\"", ",", "\"__WXMAC__\"", "]", ":", "self", ".", "Refresh", "(", ")", "else", ":", "# Probably this is not enough on GTK. Try a Refresh() if it does not work.", "wx", ".", "YieldIfNeeded", "(", ")", "else", ":", "# If we got to this point, we are not dragging or moving the mouse.", "# Because the code in carbon/toplevel.cpp will only set focus to the tree", "# if we skip for EVT_LEFT_DOWN, we MUST skip this event here for focus to work.", "# We skip even if we didn't hit an item because we still should", "# restore focus to the tree control even if we didn't exactly hit an item.", "if", "event", ".", "LeftDown", "(", ")", ":", "self", ".", "_hasFocus", "=", "True", "self", ".", "SetFocusIgnoringChildren", "(", ")", "event", ".", "Skip", "(", ")", "# here we process only the messages which happen on tree items", "self", ".", "_dragCount", "=", "0", "if", "item", "==", "None", ":", "if", "self", ".", "_editCtrl", "!=", "None", "and", "item", "!=", "self", ".", "_editCtrl", ".", "item", "(", ")", ":", "self", ".", "_editCtrl", ".", "StopEditing", "(", ")", "return", "# we hit the blank area", "if", "event", ".", "RightDown", "(", ")", ":", "if", "self", ".", "_editCtrl", "!=", "None", "and", "item", "!=", "self", ".", "_editCtrl", ".", "item", "(", ")", ":", "self", ".", "_editCtrl", ".", "StopEditing", "(", ")", "self", ".", "_hasFocus", "=", "True", "self", ".", "SetFocusIgnoringChildren", "(", ")", "# If the item is already selected, do not update the selection.", "# Multi-selections should not be cleared if a selected item is clicked.", "if", "not", "self", ".", "IsSelected", "(", "item", ")", ":", "self", ".", "DoSelectItem", "(", "item", ",", "True", ",", "False", ")", "nevent", "=", "TreeEvent", "(", "wxEVT_TREE_ITEM_RIGHT_CLICK", ",", "self", ".", "GetId", "(", ")", ")", "nevent", ".", "_item", "=", "item", "nevent", ".", "_pointDrag", "=", "self", ".", "CalcScrolledPosition", "(", "pt", ")", "nevent", ".", "SetEventObject", "(", "self", ")", "event", ".", "Skip", "(", "not", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "nevent", ")", ")", "# Consistent with MSW (for now), send the ITEM_MENU *after*", "# the RIGHT_CLICK event. TODO: This behaviour may change.", "nevent2", "=", "TreeEvent", "(", "wxEVT_TREE_ITEM_MENU", ",", "self", ".", "GetId", "(", ")", ")", "nevent2", ".", "_item", "=", "item", "nevent2", ".", "_pointDrag", "=", "self", ".", "CalcScrolledPosition", "(", "pt", ")", "nevent2", ".", "SetEventObject", "(", "self", ")", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "nevent2", ")", "elif", "event", ".", "LeftUp", "(", ")", ":", "# this facilitates multiple-item drag-and-drop", "if", "self", ".", "HasAGWFlag", "(", "TR_MULTIPLE", ")", ":", "selections", "=", "self", ".", "GetSelections", "(", ")", "if", "len", "(", "selections", ")", ">", "1", "and", "not", "event", ".", "CmdDown", "(", ")", "and", "not", "event", ".", "ShiftDown", "(", ")", ":", "self", ".", "DoSelectItem", "(", "item", ",", "True", ",", "False", ")", "if", "self", ".", "_lastOnSame", ":", "if", "item", "==", "self", ".", "_current", "and", "(", "flags", "&", "TREE_HITTEST_ONITEMLABEL", ")", "and", "self", ".", "HasAGWFlag", "(", "TR_EDIT_LABELS", ")", ":", "if", "self", ".", "_editTimer", ":", "if", "self", ".", "_editTimer", ".", "IsRunning", "(", ")", ":", "self", ".", "_editTimer", ".", "Stop", "(", ")", "else", ":", "self", ".", "_editTimer", "=", "TreeEditTimer", "(", "self", ")", "self", ".", "_editTimer", ".", "Start", "(", "_DELAY", ",", "True", ")", "self", ".", "_lastOnSame", "=", "False", "else", ":", "# !RightDown() && !LeftUp() ==> LeftDown() || LeftDClick()", "if", "not", "item", "or", "not", "item", ".", "IsEnabled", "(", ")", ":", "if", "self", ".", "_editCtrl", "!=", "None", "and", "item", "!=", "self", ".", "_editCtrl", ".", "item", "(", ")", ":", "self", ".", "_editCtrl", ".", "StopEditing", "(", ")", "return", "if", "self", ".", "_editCtrl", "!=", "None", "and", "item", "!=", "self", ".", "_editCtrl", ".", "item", "(", ")", ":", "self", ".", "_editCtrl", ".", "StopEditing", "(", ")", "self", ".", "_hasFocus", "=", "True", "self", ".", "SetFocusIgnoringChildren", "(", ")", "if", "event", ".", "LeftDown", "(", ")", ":", "self", ".", "_lastOnSame", "=", "item", "==", "self", ".", "_current", "if", "flags", "&", "TREE_HITTEST_ONITEMBUTTON", ":", "# only toggle the item for a single click, double click on", "# the button doesn't do anything (it toggles the item twice)", "if", "event", ".", "LeftDown", "(", ")", ":", "self", ".", "Toggle", "(", "item", ")", "# don't select the item if the button was clicked", "return", "if", "item", ".", "GetType", "(", ")", ">", "0", "and", "(", "flags", "&", "TREE_HITTEST_ONITEMCHECKICON", ")", "and", "(", "flags", "&", "TREE_HITTEST_ONITEMLABEL", "==", "0", ")", ":", "if", "event", ".", "LeftDown", "(", ")", ":", "if", "flags", "&", "TREE_HITTEST_ONITEM", "and", "self", ".", "HasAGWFlag", "(", "TR_FULL_ROW_HIGHLIGHT", ")", ":", "self", ".", "DoSelectItem", "(", "item", ",", "not", "self", ".", "HasAGWFlag", "(", "TR_MULTIPLE", ")", ")", "if", "self", ".", "IsItem3State", "(", "item", ")", ":", "checked", "=", "self", ".", "GetItem3StateValue", "(", "item", ")", "checked", "=", "(", "checked", "+", "1", ")", "%", "3", "else", ":", "checked", "=", "not", "self", ".", "IsItemChecked", "(", "item", ")", "self", ".", "CheckItem", "(", "item", ",", "checked", ")", "return", "# clear the previously selected items, if the", "# user clicked outside of the present selection.", "# otherwise, perform the deselection on mouse-up.", "# this allows multiple drag and drop to work.", "# but if Cmd is down, toggle selection of the clicked item", "if", "not", "self", ".", "IsSelected", "(", "item", ")", "or", "event", ".", "CmdDown", "(", ")", ":", "if", "flags", "&", "TREE_HITTEST_ONITEM", ":", "# how should the selection work for this event?", "if", "item", ".", "IsHyperText", "(", ")", ":", "self", ".", "SetItemVisited", "(", "item", ",", "True", ")", "is_multiple", ",", "extended_select", ",", "unselect_others", "=", "EventFlagsToSelType", "(", "self", ".", "GetAGWWindowStyleFlag", "(", ")", ",", "event", ".", "ShiftDown", "(", ")", ",", "event", ".", "CmdDown", "(", ")", ")", "self", ".", "DoSelectItem", "(", "item", ",", "unselect_others", ",", "extended_select", ")", "# Handle hyperlink items... which are a bit odd sometimes", "elif", "self", ".", "IsSelected", "(", "item", ")", "and", "item", ".", "IsHyperText", "(", ")", ":", "self", ".", "HandleHyperLink", "(", "item", ")", "# For some reason, Windows isn't recognizing a left double-click,", "# so we need to simulate it here. Allow 200 milliseconds for now.", "if", "event", ".", "LeftDClick", "(", ")", ":", "# double clicking should not start editing the item label", "if", "self", ".", "_editTimer", ":", "self", ".", "_editTimer", ".", "Stop", "(", ")", "self", ".", "_lastOnSame", "=", "False", "# send activate event first", "nevent", "=", "TreeEvent", "(", "wxEVT_TREE_ITEM_ACTIVATED", ",", "self", ".", "GetId", "(", ")", ")", "nevent", ".", "_item", "=", "item", "nevent", ".", "_pointDrag", "=", "self", ".", "CalcScrolledPosition", "(", "pt", ")", "nevent", ".", "SetEventObject", "(", "self", ")", "if", "not", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "nevent", ")", ":", "# if the user code didn't process the activate event,", "# handle it ourselves by toggling the item when it is", "# double clicked", "## if item.HasPlus():", "self", ".", "Toggle", "(", "item", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L7598-L7968
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/__init__.py
python
ResourceManager.extraction_error
(self)
Give an error message for problems extracting file(s)
Give an error message for problems extracting file(s)
[ "Give", "an", "error", "message", "for", "problems", "extracting", "file", "(", "s", ")" ]
def extraction_error(self): """Give an error message for problems extracting file(s)""" old_exc = sys.exc_info()[1] cache_path = self.extraction_path or get_default_cache() tmpl = textwrap.dedent(""" Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: {old_exc} The Python egg cache directory is currently set to: {cache_path} Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. """).lstrip() err = ExtractionError(tmpl.format(**locals())) err.manager = self err.cache_path = cache_path err.original_error = old_exc raise err
[ "def", "extraction_error", "(", "self", ")", ":", "old_exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "cache_path", "=", "self", ".", "extraction_path", "or", "get_default_cache", "(", ")", "tmpl", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n Can't extract file(s) to egg cache\n\n The following error occurred while trying to extract file(s)\n to the Python egg cache:\n\n {old_exc}\n\n The Python egg cache directory is currently set to:\n\n {cache_path}\n\n Perhaps your account does not have write access to this directory?\n You can change the cache directory by setting the PYTHON_EGG_CACHE\n environment variable to point to an accessible directory.\n \"\"\"", ")", ".", "lstrip", "(", ")", "err", "=", "ExtractionError", "(", "tmpl", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ")", "err", ".", "manager", "=", "self", "err", ".", "cache_path", "=", "cache_path", "err", ".", "original_error", "=", "old_exc", "raise", "err" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/__init__.py#L1166-L1192
mingchen/protobuf-ios
0958df34558cd54cb7b6e6ca5c8855bf3d475046
compiler/python/mox.py
python
And.__init__
(self, *args)
Initialize. Args: *args: One or more Comparator
Initialize.
[ "Initialize", "." ]
def __init__(self, *args): """Initialize. Args: *args: One or more Comparator """ self._comparators = args
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_comparators", "=", "args" ]
https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/mox.py#L1050-L1057
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
TextAreaBase.GetStyle
(*args, **kwargs)
return _core_.TextAreaBase_GetStyle(*args, **kwargs)
GetStyle(self, long position, wxTextAttr style) -> bool
GetStyle(self, long position, wxTextAttr style) -> bool
[ "GetStyle", "(", "self", "long", "position", "wxTextAttr", "style", ")", "-", ">", "bool" ]
def GetStyle(*args, **kwargs): """GetStyle(self, long position, wxTextAttr style) -> bool""" return _core_.TextAreaBase_GetStyle(*args, **kwargs)
[ "def", "GetStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "TextAreaBase_GetStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13424-L13426
adventuregamestudio/ags
efa89736d868e9dfda4200149d33ba8637746399
Common/libsrc/freetype-2.1.3/src/tools/docmaker/tohtml.py
python
HtmlFormatter.make_html_para
( self, words )
return "<p>" + line + "</p>"
convert a paragraph's words into tagged HTML text, handle xrefs
convert a paragraph's words into tagged HTML text, handle xrefs
[ "convert", "a", "paragraph", "s", "words", "into", "tagged", "HTML", "text", "handle", "xrefs" ]
def make_html_para( self, words ): """ convert a paragraph's words into tagged HTML text, handle xrefs """ line = "" if words: line = self.make_html_word( words[0] ) for word in words[1:]: line = line + " " + self.make_html_word( word ) return "<p>" + line + "</p>"
[ "def", "make_html_para", "(", "self", ",", "words", ")", ":", "line", "=", "\"\"", "if", "words", ":", "line", "=", "self", ".", "make_html_word", "(", "words", "[", "0", "]", ")", "for", "word", "in", "words", "[", "1", ":", "]", ":", "line", "=", "line", "+", "\" \"", "+", "self", ".", "make_html_word", "(", "word", ")", "return", "\"<p>\"", "+", "line", "+", "\"</p>\"" ]
https://github.com/adventuregamestudio/ags/blob/efa89736d868e9dfda4200149d33ba8637746399/Common/libsrc/freetype-2.1.3/src/tools/docmaker/tohtml.py#L195-L203
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html.py
python
HtmlHelpController.ReadCustomization
(*args, **kwargs)
return _html.HtmlHelpController_ReadCustomization(*args, **kwargs)
ReadCustomization(self, ConfigBase cfg, String path=EmptyString)
ReadCustomization(self, ConfigBase cfg, String path=EmptyString)
[ "ReadCustomization", "(", "self", "ConfigBase", "cfg", "String", "path", "=", "EmptyString", ")" ]
def ReadCustomization(*args, **kwargs): """ReadCustomization(self, ConfigBase cfg, String path=EmptyString)""" return _html.HtmlHelpController_ReadCustomization(*args, **kwargs)
[ "def", "ReadCustomization", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlHelpController_ReadCustomization", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1994-L1996
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/multiprocessing/connection.py
python
arbitrary_address
(family)
Return an arbitrary free address for the given family
Return an arbitrary free address for the given family
[ "Return", "an", "arbitrary", "free", "address", "for", "the", "given", "family" ]
def arbitrary_address(family): ''' Return an arbitrary free address for the given family ''' if family == 'AF_INET': return ('localhost', 0) elif family == 'AF_UNIX': # Prefer abstract sockets if possible to avoid problems with the address # size. When coding portable applications, some implementations have # sun_path as short as 92 bytes in the sockaddr_un struct. if util.abstract_sockets_supported: return f"\0listener-{os.getpid()}-{next(_mmap_counter)}" return tempfile.mktemp(prefix='listener-', dir=util.get_temp_dir()) elif family == 'AF_PIPE': return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' % (os.getpid(), next(_mmap_counter)), dir="") else: raise ValueError('unrecognized family')
[ "def", "arbitrary_address", "(", "family", ")", ":", "if", "family", "==", "'AF_INET'", ":", "return", "(", "'localhost'", ",", "0", ")", "elif", "family", "==", "'AF_UNIX'", ":", "# Prefer abstract sockets if possible to avoid problems with the address", "# size. When coding portable applications, some implementations have", "# sun_path as short as 92 bytes in the sockaddr_un struct.", "if", "util", ".", "abstract_sockets_supported", ":", "return", "f\"\\0listener-{os.getpid()}-{next(_mmap_counter)}\"", "return", "tempfile", ".", "mktemp", "(", "prefix", "=", "'listener-'", ",", "dir", "=", "util", ".", "get_temp_dir", "(", ")", ")", "elif", "family", "==", "'AF_PIPE'", ":", "return", "tempfile", ".", "mktemp", "(", "prefix", "=", "r'\\\\.\\pipe\\pyc-%d-%d-'", "%", "(", "os", ".", "getpid", "(", ")", ",", "next", "(", "_mmap_counter", ")", ")", ",", "dir", "=", "\"\"", ")", "else", ":", "raise", "ValueError", "(", "'unrecognized family'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/connection.py#L69-L86
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py
python
_turtle_docrevise
(docstr)
return newdocstr
To reduce docstrings from RawTurtle class for functions
To reduce docstrings from RawTurtle class for functions
[ "To", "reduce", "docstrings", "from", "RawTurtle", "class", "for", "functions" ]
def _turtle_docrevise(docstr): """To reduce docstrings from RawTurtle class for functions """ import re if docstr is None: return None turtlename = _CFG["exampleturtle"] newdocstr = docstr.replace("%s." % turtlename,"") parexp = re.compile(r' \(.+ %s\):' % turtlename) newdocstr = parexp.sub(":", newdocstr) return newdocstr
[ "def", "_turtle_docrevise", "(", "docstr", ")", ":", "import", "re", "if", "docstr", "is", "None", ":", "return", "None", "turtlename", "=", "_CFG", "[", "\"exampleturtle\"", "]", "newdocstr", "=", "docstr", ".", "replace", "(", "\"%s.\"", "%", "turtlename", ",", "\"\"", ")", "parexp", "=", "re", ".", "compile", "(", "r' \\(.+ %s\\):'", "%", "turtlename", ")", "newdocstr", "=", "parexp", ".", "sub", "(", "\":\"", ",", "newdocstr", ")", "return", "newdocstr" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py#L3914-L3924
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftfunctions/svgtext.py
python
_get_text_techdraw
(text, tcolor, fontsize, anchor, align, fontname, angle, base, linespacing)
return svg
Return the SVG representation of text for TechDraw display. `text` is a list of textual elements; they are iterated, styled, and added around a `<text>` tag. :: <text ...> text[0] </text> <text ...> text[1] </text>
Return the SVG representation of text for TechDraw display.
[ "Return", "the", "SVG", "representation", "of", "text", "for", "TechDraw", "display", "." ]
def _get_text_techdraw(text, tcolor, fontsize, anchor, align, fontname, angle, base, linespacing): """Return the SVG representation of text for TechDraw display. `text` is a list of textual elements; they are iterated, styled, and added around a `<text>` tag. :: <text ...> text[0] </text> <text ...> text[1] </text> """ svg = "" for i in range(len(text)): _t = text[i].replace("&", "&amp;") _t = _t.replace("<", "&lt;") t = _t.replace(">", "&gt;") # TODO: remove when Python 2 is no longer supported if six.PY2 and not isinstance(t, six.text_type): t = t.decode("utf8") # possible workaround if UTF8 is unsupported # import unicodedata as U # v = list() # for c in U.normalize("NFKD", t): # if not U.combining(c): # v.append(c) # # t = u"".join(v) # t = t.encode("utf8") svg += '<text ' svg += 'stroke-width="0" stroke="{}" '.format(tcolor) svg += 'fill="{}" font-size="{}" '.format(tcolor, fontsize) svg += 'style="text-anchor:{};text-align:{};'.format(anchor, align.lower()) svg += 'font-family:{}" '.format(fontname) svg += 'transform="' svg += 'rotate({},{},{}) '.format(math.degrees(angle), base.x, base.y - i * linespacing) svg += 'translate({},{}) '.format(base.x, base.y - i * linespacing) svg += 'scale(1,-1)"' # svg += 'freecad:skip="1"' svg += '>\n' svg += t svg += '</text>\n' return svg
[ "def", "_get_text_techdraw", "(", "text", ",", "tcolor", ",", "fontsize", ",", "anchor", ",", "align", ",", "fontname", ",", "angle", ",", "base", ",", "linespacing", ")", ":", "svg", "=", "\"\"", "for", "i", "in", "range", "(", "len", "(", "text", ")", ")", ":", "_t", "=", "text", "[", "i", "]", ".", "replace", "(", "\"&\"", ",", "\"&amp;\"", ")", "_t", "=", "_t", ".", "replace", "(", "\"<\"", ",", "\"&lt;\"", ")", "t", "=", "_t", ".", "replace", "(", "\">\"", ",", "\"&gt;\"", ")", "# TODO: remove when Python 2 is no longer supported", "if", "six", ".", "PY2", "and", "not", "isinstance", "(", "t", ",", "six", ".", "text_type", ")", ":", "t", "=", "t", ".", "decode", "(", "\"utf8\"", ")", "# possible workaround if UTF8 is unsupported", "# import unicodedata as U", "# v = list()", "# for c in U.normalize(\"NFKD\", t):", "# if not U.combining(c):", "# v.append(c)", "#", "# t = u\"\".join(v)", "# t = t.encode(\"utf8\")", "svg", "+=", "'<text '", "svg", "+=", "'stroke-width=\"0\" stroke=\"{}\" '", ".", "format", "(", "tcolor", ")", "svg", "+=", "'fill=\"{}\" font-size=\"{}\" '", ".", "format", "(", "tcolor", ",", "fontsize", ")", "svg", "+=", "'style=\"text-anchor:{};text-align:{};'", ".", "format", "(", "anchor", ",", "align", ".", "lower", "(", ")", ")", "svg", "+=", "'font-family:{}\" '", ".", "format", "(", "fontname", ")", "svg", "+=", "'transform=\"'", "svg", "+=", "'rotate({},{},{}) '", ".", "format", "(", "math", ".", "degrees", "(", "angle", ")", ",", "base", ".", "x", ",", "base", ".", "y", "-", "i", "*", "linespacing", ")", "svg", "+=", "'translate({},{}) '", ".", "format", "(", "base", ".", "x", ",", "base", ".", "y", "-", "i", "*", "linespacing", ")", "svg", "+=", "'scale(1,-1)\"'", "# svg += 'freecad:skip=\"1\"'", "svg", "+=", "'>\\n'", "svg", "+=", "t", "svg", "+=", "'</text>\\n'", "return", "svg" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftfunctions/svgtext.py#L39-L87
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
Gather.forward
(self, x)
return singa.ConcatOn(xs, self.axis)
forward of Gather Args: x (CTensor): input tensor. Returns: the output CTensor.
forward of Gather Args: x (CTensor): input tensor. Returns: the output CTensor.
[ "forward", "of", "Gather", "Args", ":", "x", "(", "CTensor", ")", ":", "input", "tensor", ".", "Returns", ":", "the", "output", "CTensor", "." ]
def forward(self, x): """ forward of Gather Args: x (CTensor): input tensor. Returns: the output CTensor. """ self.x_shape = list(x.shape()) self.axis = self.axis % len(self.x_shape) # handle the negative value _shape = self.x_shape[self.axis] xs = [] for indice in self.indices: # each indice is a sub-indice if isinstance(indice, (tuple, list, np.ndarray)): sub_xs = [] for idx in indice: idx = int(idx % _shape) tmp_tensor = singa.SliceOn(x, idx, idx + 1, self.axis) sub_xs.append(tmp_tensor) sub_xs = singa.VecTensor(sub_xs) tmp_tensor = singa.ConcatOn(sub_xs, self.axis) _slice_shape = list(tmp_tensor.shape()) _slice_shape.insert(self.axis, 1) # add a new axis to concat tmp_tensor = singa.Reshape(tmp_tensor, _slice_shape) else: indice = int(indice % _shape) tmp_tensor = singa.SliceOn(x, indice, indice + 1, self.axis) xs.append(tmp_tensor) xs = singa.VecTensor(xs) return singa.ConcatOn(xs, self.axis)
[ "def", "forward", "(", "self", ",", "x", ")", ":", "self", ".", "x_shape", "=", "list", "(", "x", ".", "shape", "(", ")", ")", "self", ".", "axis", "=", "self", ".", "axis", "%", "len", "(", "self", ".", "x_shape", ")", "# handle the negative value", "_shape", "=", "self", ".", "x_shape", "[", "self", ".", "axis", "]", "xs", "=", "[", "]", "for", "indice", "in", "self", ".", "indices", ":", "# each indice is a sub-indice", "if", "isinstance", "(", "indice", ",", "(", "tuple", ",", "list", ",", "np", ".", "ndarray", ")", ")", ":", "sub_xs", "=", "[", "]", "for", "idx", "in", "indice", ":", "idx", "=", "int", "(", "idx", "%", "_shape", ")", "tmp_tensor", "=", "singa", ".", "SliceOn", "(", "x", ",", "idx", ",", "idx", "+", "1", ",", "self", ".", "axis", ")", "sub_xs", ".", "append", "(", "tmp_tensor", ")", "sub_xs", "=", "singa", ".", "VecTensor", "(", "sub_xs", ")", "tmp_tensor", "=", "singa", ".", "ConcatOn", "(", "sub_xs", ",", "self", ".", "axis", ")", "_slice_shape", "=", "list", "(", "tmp_tensor", ".", "shape", "(", ")", ")", "_slice_shape", ".", "insert", "(", "self", ".", "axis", ",", "1", ")", "# add a new axis to concat", "tmp_tensor", "=", "singa", ".", "Reshape", "(", "tmp_tensor", ",", "_slice_shape", ")", "else", ":", "indice", "=", "int", "(", "indice", "%", "_shape", ")", "tmp_tensor", "=", "singa", ".", "SliceOn", "(", "x", ",", "indice", ",", "indice", "+", "1", ",", "self", ".", "axis", ")", "xs", ".", "append", "(", "tmp_tensor", ")", "xs", "=", "singa", ".", "VecTensor", "(", "xs", ")", "return", "singa", ".", "ConcatOn", "(", "xs", ",", "self", ".", "axis", ")" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L4448-L4478
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ipaddress.py
python
_BaseV6._string_from_ip_int
(cls, ip_int=None)
return ':'.join(hextets)
Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones.
Turns a 128-bit integer into hexadecimal notation.
[ "Turns", "a", "128", "-", "bit", "integer", "into", "hexadecimal", "notation", "." ]
def _string_from_ip_int(cls, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(cls._ip) if ip_int > cls._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] hextets = cls._compress_hextets(hextets) return ':'.join(hextets)
[ "def", "_string_from_ip_int", "(", "cls", ",", "ip_int", "=", "None", ")", ":", "if", "ip_int", "is", "None", ":", "ip_int", "=", "int", "(", "cls", ".", "_ip", ")", "if", "ip_int", ">", "cls", ".", "_ALL_ONES", ":", "raise", "ValueError", "(", "'IPv6 address is too large'", ")", "hex_str", "=", "'%032x'", "%", "ip_int", "hextets", "=", "[", "'%x'", "%", "int", "(", "hex_str", "[", "x", ":", "x", "+", "4", "]", ",", "16", ")", "for", "x", "in", "range", "(", "0", ",", "32", ",", "4", ")", "]", "hextets", "=", "cls", ".", "_compress_hextets", "(", "hextets", ")", "return", "':'", ".", "join", "(", "hextets", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ipaddress.py#L1787-L1810
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
HyperlinkCtrl.GetVisitedColour
(*args, **kwargs)
return _controls_.HyperlinkCtrl_GetVisitedColour(*args, **kwargs)
GetVisitedColour(self) -> Colour
GetVisitedColour(self) -> Colour
[ "GetVisitedColour", "(", "self", ")", "-", ">", "Colour" ]
def GetVisitedColour(*args, **kwargs): """GetVisitedColour(self) -> Colour""" return _controls_.HyperlinkCtrl_GetVisitedColour(*args, **kwargs)
[ "def", "GetVisitedColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "HyperlinkCtrl_GetVisitedColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L6646-L6648
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
Define
(d, flavor)
return QuoteShellArgument(ninja_syntax.escape("-D" + d), flavor)
Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.
Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.
[ "Takes", "a", "preprocessor", "define", "and", "returns", "a", "-", "D", "parameter", "that", "s", "ninja", "-", "and", "shell", "-", "escaped", "." ]
def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == "win": # cl.exe replaces literal # characters with = in preprocessor definitions for # some reason. Octal-encode to work around that. d = d.replace("#", "\\%03o" % ord("#")) return QuoteShellArgument(ninja_syntax.escape("-D" + d), flavor)
[ "def", "Define", "(", "d", ",", "flavor", ")", ":", "if", "flavor", "==", "\"win\"", ":", "# cl.exe replaces literal # characters with = in preprocessor definitions for", "# some reason. Octal-encode to work around that.", "d", "=", "d", ".", "replace", "(", "\"#\"", ",", "\"\\\\%03o\"", "%", "ord", "(", "\"#\"", ")", ")", "return", "QuoteShellArgument", "(", "ninja_syntax", ".", "escape", "(", "\"-D\"", "+", "d", ")", ",", "flavor", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L85-L92
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
AboutDialogInfo.GetIcon
(*args, **kwargs)
return _misc_.AboutDialogInfo_GetIcon(*args, **kwargs)
GetIcon(self) -> Icon Return the current icon value.
GetIcon(self) -> Icon
[ "GetIcon", "(", "self", ")", "-", ">", "Icon" ]
def GetIcon(*args, **kwargs): """ GetIcon(self) -> Icon Return the current icon value. """ return _misc_.AboutDialogInfo_GetIcon(*args, **kwargs)
[ "def", "GetIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "AboutDialogInfo_GetIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L6754-L6760
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Position.__eq__
(*args, **kwargs)
return _core_.Position___eq__(*args, **kwargs)
__eq__(self, PyObject other) -> bool Test for equality of wx.Position objects.
__eq__(self, PyObject other) -> bool
[ "__eq__", "(", "self", "PyObject", "other", ")", "-", ">", "bool" ]
def __eq__(*args, **kwargs): """ __eq__(self, PyObject other) -> bool Test for equality of wx.Position objects. """ return _core_.Position___eq__(*args, **kwargs)
[ "def", "__eq__", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Position___eq__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2110-L2116
dmlc/xgboost
2775c2a1abd4b5b759ff517617434c8b9aeb4cc0
python-package/xgboost/core.py
python
_ProxyDMatrix._set_data_from_csr
(self, csr)
Set data from scipy csr
Set data from scipy csr
[ "Set", "data", "from", "scipy", "csr" ]
def _set_data_from_csr(self, csr): """Set data from scipy csr""" from .data import _array_interface _LIB.XGProxyDMatrixSetDataCSR( self.handle, _array_interface(csr.indptr), _array_interface(csr.indices), _array_interface(csr.data), ctypes.c_size_t(csr.shape[1]), )
[ "def", "_set_data_from_csr", "(", "self", ",", "csr", ")", ":", "from", ".", "data", "import", "_array_interface", "_LIB", ".", "XGProxyDMatrixSetDataCSR", "(", "self", ".", "handle", ",", "_array_interface", "(", "csr", ".", "indptr", ")", ",", "_array_interface", "(", "csr", ".", "indices", ")", ",", "_array_interface", "(", "csr", ".", "data", ")", ",", "ctypes", ".", "c_size_t", "(", "csr", ".", "shape", "[", "1", "]", ")", ",", ")" ]
https://github.com/dmlc/xgboost/blob/2775c2a1abd4b5b759ff517617434c8b9aeb4cc0/python-package/xgboost/core.py#L1132-L1142
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
llvm/utils/benchmark/tools/strip_asm.py
python
process_identifiers
(l)
return new_line
process_identifiers - process all identifiers and modify them to have consistent names across all platforms; specifically across ELF and MachO. For example, MachO inserts an additional understore at the beginning of names. This function removes that.
process_identifiers - process all identifiers and modify them to have consistent names across all platforms; specifically across ELF and MachO. For example, MachO inserts an additional understore at the beginning of names. This function removes that.
[ "process_identifiers", "-", "process", "all", "identifiers", "and", "modify", "them", "to", "have", "consistent", "names", "across", "all", "platforms", ";", "specifically", "across", "ELF", "and", "MachO", ".", "For", "example", "MachO", "inserts", "an", "additional", "understore", "at", "the", "beginning", "of", "names", ".", "This", "function", "removes", "that", "." ]
def process_identifiers(l): """ process_identifiers - process all identifiers and modify them to have consistent names across all platforms; specifically across ELF and MachO. For example, MachO inserts an additional understore at the beginning of names. This function removes that. """ parts = re.split(r'([a-zA-Z0-9_]+)', l) new_line = '' for tk in parts: if is_identifier(tk): if tk.startswith('__Z'): tk = tk[1:] elif tk.startswith('_') and len(tk) > 1 and \ tk[1].isalpha() and tk[1] != 'Z': tk = tk[1:] new_line += tk return new_line
[ "def", "process_identifiers", "(", "l", ")", ":", "parts", "=", "re", ".", "split", "(", "r'([a-zA-Z0-9_]+)'", ",", "l", ")", "new_line", "=", "''", "for", "tk", "in", "parts", ":", "if", "is_identifier", "(", "tk", ")", ":", "if", "tk", ".", "startswith", "(", "'__Z'", ")", ":", "tk", "=", "tk", "[", "1", ":", "]", "elif", "tk", ".", "startswith", "(", "'_'", ")", "and", "len", "(", "tk", ")", ">", "1", "and", "tk", "[", "1", "]", ".", "isalpha", "(", ")", "and", "tk", "[", "1", "]", "!=", "'Z'", ":", "tk", "=", "tk", "[", "1", ":", "]", "new_line", "+=", "tk", "return", "new_line" ]
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/llvm/utils/benchmark/tools/strip_asm.py#L64-L81
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/utils/group/cubic.py
python
Fd3m
()
return (_inv_group().change_origin([1 / 8, 1 / 8, 1 / 8]) @ Td()).replace( unit_cell=np.asarray([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]]) )
Nonsymmorphic "point group" of the diamond and pyrochlore lattices with a cubic unit cell of side length 1.
Nonsymmorphic "point group" of the diamond and pyrochlore lattices with a cubic unit cell of side length 1.
[ "Nonsymmorphic", "point", "group", "of", "the", "diamond", "and", "pyrochlore", "lattices", "with", "a", "cubic", "unit", "cell", "of", "side", "length", "1", "." ]
def Fd3m() -> PointGroup: """Nonsymmorphic "point group" of the diamond and pyrochlore lattices with a cubic unit cell of side length 1.""" return (_inv_group().change_origin([1 / 8, 1 / 8, 1 / 8]) @ Td()).replace( unit_cell=np.asarray([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]]) )
[ "def", "Fd3m", "(", ")", "->", "PointGroup", ":", "return", "(", "_inv_group", "(", ")", ".", "change_origin", "(", "[", "1", "/", "8", ",", "1", "/", "8", ",", "1", "/", "8", "]", ")", "@", "Td", "(", ")", ")", ".", "replace", "(", "unit_cell", "=", "np", ".", "asarray", "(", "[", "[", "0", ",", "0.5", ",", "0.5", "]", ",", "[", "0.5", ",", "0", ",", "0.5", "]", ",", "[", "0.5", ",", "0.5", ",", "0", "]", "]", ")", ")" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/utils/group/cubic.py#L113-L118
olliw42/storm32bgc
99d62a6130ae2950514022f50eb669c45a8cc1ba
old/betacopter/old/betacopter36dev-v003/modules/uavcan/libuavcan/dsdl_compiler/pyuavcan/uavcan/dsdl/parser.py
python
parse_namespaces
(source_dirs, search_dirs=None)
return output_types
Use only this function to parse DSDL definitions. This function takes a list of root namespace directories (containing DSDL definition files to parse) and an optional list of search directories (containing DSDL definition files that can be referenced from the types that are going to be parsed). Returns the list of parsed type definitions, where type of each element is CompoundType. Args: source_dirs List of root namespace directories to parse. search_dirs List of root namespace directories with referenced types (optional). This list is automaitcally extended with source_dirs. Example: >>> import uavcan >>> a = uavcan.dsdl.parse_namespaces(['../dsdl/uavcan']) >>> len(a) 77 >>> a[0] uavcan.Timestamp >>> a[0].fields [truncated uint48 husec] >>> a[0].constants [saturated uint48 UNKNOWN = 0, saturated uint48 USEC_PER_LSB = 100]
Use only this function to parse DSDL definitions. This function takes a list of root namespace directories (containing DSDL definition files to parse) and an optional list of search directories (containing DSDL definition files that can be referenced from the types that are going to be parsed).
[ "Use", "only", "this", "function", "to", "parse", "DSDL", "definitions", ".", "This", "function", "takes", "a", "list", "of", "root", "namespace", "directories", "(", "containing", "DSDL", "definition", "files", "to", "parse", ")", "and", "an", "optional", "list", "of", "search", "directories", "(", "containing", "DSDL", "definition", "files", "that", "can", "be", "referenced", "from", "the", "types", "that", "are", "going", "to", "be", "parsed", ")", "." ]
def parse_namespaces(source_dirs, search_dirs=None): ''' Use only this function to parse DSDL definitions. This function takes a list of root namespace directories (containing DSDL definition files to parse) and an optional list of search directories (containing DSDL definition files that can be referenced from the types that are going to be parsed). Returns the list of parsed type definitions, where type of each element is CompoundType. Args: source_dirs List of root namespace directories to parse. search_dirs List of root namespace directories with referenced types (optional). This list is automaitcally extended with source_dirs. Example: >>> import uavcan >>> a = uavcan.dsdl.parse_namespaces(['../dsdl/uavcan']) >>> len(a) 77 >>> a[0] uavcan.Timestamp >>> a[0].fields [truncated uint48 husec] >>> a[0].constants [saturated uint48 UNKNOWN = 0, saturated uint48 USEC_PER_LSB = 100] ''' def walk(): import fnmatch from functools import partial def on_walk_error(directory, ex): raise DsdlException('OS error in [%s]: %s' % (directory, str(ex))) for source_dir in source_dirs: walker = os.walk(source_dir, onerror=partial(on_walk_error, source_dir), followlinks=True) for root, _dirnames, filenames in walker: for filename in fnmatch.filter(filenames, '*.uavcan'): filename = os.path.join(root, filename) yield filename all_default_dtid = {} # (kind, dtid) : filename def ensure_unique_dtid(t, filename): if t.default_dtid is None: return key = t.kind, t.default_dtid if key in all_default_dtid: first = pretty_filename(all_default_dtid[key]) second = pretty_filename(filename) error('Default data type ID collision: [%s] [%s]', first, second) all_default_dtid[key] = filename parser = Parser(source_dirs + (search_dirs or [])) output_types = [] for filename in walk(): t = parser.parse(filename) ensure_unique_dtid(t, filename) output_types.append(t) return output_types
[ "def", "parse_namespaces", "(", "source_dirs", ",", "search_dirs", "=", "None", ")", ":", "def", "walk", "(", ")", ":", "import", "fnmatch", "from", "functools", "import", "partial", "def", "on_walk_error", "(", "directory", ",", "ex", ")", ":", "raise", "DsdlException", "(", "'OS error in [%s]: %s'", "%", "(", "directory", ",", "str", "(", "ex", ")", ")", ")", "for", "source_dir", "in", "source_dirs", ":", "walker", "=", "os", ".", "walk", "(", "source_dir", ",", "onerror", "=", "partial", "(", "on_walk_error", ",", "source_dir", ")", ",", "followlinks", "=", "True", ")", "for", "root", ",", "_dirnames", ",", "filenames", "in", "walker", ":", "for", "filename", "in", "fnmatch", ".", "filter", "(", "filenames", ",", "'*.uavcan'", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")", "yield", "filename", "all_default_dtid", "=", "{", "}", "# (kind, dtid) : filename", "def", "ensure_unique_dtid", "(", "t", ",", "filename", ")", ":", "if", "t", ".", "default_dtid", "is", "None", ":", "return", "key", "=", "t", ".", "kind", ",", "t", ".", "default_dtid", "if", "key", "in", "all_default_dtid", ":", "first", "=", "pretty_filename", "(", "all_default_dtid", "[", "key", "]", ")", "second", "=", "pretty_filename", "(", "filename", ")", "error", "(", "'Default data type ID collision: [%s] [%s]'", ",", "first", ",", "second", ")", "all_default_dtid", "[", "key", "]", "=", "filename", "parser", "=", "Parser", "(", "source_dirs", "+", "(", "search_dirs", "or", "[", "]", ")", ")", "output_types", "=", "[", "]", "for", "filename", "in", "walk", "(", ")", ":", "t", "=", "parser", ".", "parse", "(", "filename", ")", "ensure_unique_dtid", "(", "t", ",", "filename", ")", "output_types", ".", "append", "(", "t", ")", "return", "output_types" ]
https://github.com/olliw42/storm32bgc/blob/99d62a6130ae2950514022f50eb669c45a8cc1ba/old/betacopter/old/betacopter36dev-v003/modules/uavcan/libuavcan/dsdl_compiler/pyuavcan/uavcan/dsdl/parser.py#L702-L756
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TreeCtrl.AssignImageList
(*args, **kwargs)
return _controls_.TreeCtrl_AssignImageList(*args, **kwargs)
AssignImageList(self, ImageList imageList)
AssignImageList(self, ImageList imageList)
[ "AssignImageList", "(", "self", "ImageList", "imageList", ")" ]
def AssignImageList(*args, **kwargs): """AssignImageList(self, ImageList imageList)""" return _controls_.TreeCtrl_AssignImageList(*args, **kwargs)
[ "def", "AssignImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_AssignImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5252-L5254
luliyucoordinate/Leetcode
96afcdc54807d1d184e881a075d1dbf3371e31fb
src/0917-Reverse-Only-Letters/0917.py
python
Solution.reverseOnlyLetters
(self, S)
return ''.join([i if not i.isalpha() else p.pop() for i in S])
:type S: str :rtype: str
:type S: str :rtype: str
[ ":", "type", "S", ":", "str", ":", "rtype", ":", "str" ]
def reverseOnlyLetters(self, S): """ :type S: str :rtype: str """ if S == '': return '' p = [i for i in S if i.isalpha()] return ''.join([i if not i.isalpha() else p.pop() for i in S])
[ "def", "reverseOnlyLetters", "(", "self", ",", "S", ")", ":", "if", "S", "==", "''", ":", "return", "''", "p", "=", "[", "i", "for", "i", "in", "S", "if", "i", ".", "isalpha", "(", ")", "]", "return", "''", ".", "join", "(", "[", "i", "if", "not", "i", ".", "isalpha", "(", ")", "else", "p", ".", "pop", "(", ")", "for", "i", "in", "S", "]", ")" ]
https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0917-Reverse-Only-Letters/0917.py#L2-L10
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/tools/api/generator/create_python_api.py
python
_ModuleInitCodeBuilder.format_import
(self, source_module_name, source_name, dest_name)
Formats import statement. Args: source_module_name: (string) Source module to import from. source_name: (string) Source symbol name to import. dest_name: (string) Destination alias name. Returns: An import statement string.
Formats import statement.
[ "Formats", "import", "statement", "." ]
def format_import(self, source_module_name, source_name, dest_name): """Formats import statement. Args: source_module_name: (string) Source module to import from. source_name: (string) Source symbol name to import. dest_name: (string) Destination alias name. Returns: An import statement string. """ if self._lazy_loading: return " '%s': ('%s', '%s')," % (dest_name, source_module_name, source_name) else: if source_module_name: if source_name == dest_name: return 'from %s import %s' % (source_module_name, source_name) else: return 'from %s import %s as %s' % (source_module_name, source_name, dest_name) else: if source_name == dest_name: return 'import %s' % source_name else: return 'import %s as %s' % (source_name, dest_name)
[ "def", "format_import", "(", "self", ",", "source_module_name", ",", "source_name", ",", "dest_name", ")", ":", "if", "self", ".", "_lazy_loading", ":", "return", "\" '%s': ('%s', '%s'),\"", "%", "(", "dest_name", ",", "source_module_name", ",", "source_name", ")", "else", ":", "if", "source_module_name", ":", "if", "source_name", "==", "dest_name", ":", "return", "'from %s import %s'", "%", "(", "source_module_name", ",", "source_name", ")", "else", ":", "return", "'from %s import %s as %s'", "%", "(", "source_module_name", ",", "source_name", ",", "dest_name", ")", "else", ":", "if", "source_name", "==", "dest_name", ":", "return", "'import %s'", "%", "source_name", "else", ":", "return", "'import %s as %s'", "%", "(", "source_name", ",", "dest_name", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tools/api/generator/create_python_api.py#L275-L300
gv22ga/dlib-face-recognition-android
42d6305cbd85833f2b85bb79b70ab9ab004153c9
tools/lint/cpplint.py
python
CheckSectionSpacing
(filename, clean_lines, class_info, linenum, error)
Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found.
[ "Checks", "for", "additional", "blank", "line", "issues", "related", "to", "sections", ".", "Currently", "the", "only", "thing", "checked", "here", "is", "blank", "line", "before", "protected", "/", "private", ".", "Args", ":", "filename", ":", "The", "name", "of", "the", "current", "file", ".", "clean_lines", ":", "A", "CleansedLines", "instance", "containing", "the", "file", ".", "class_info", ":", "A", "_ClassInfo", "objects", ".", "linenum", ":", "The", "number", "of", "the", "line", "to", "check", ".", "error", ":", "The", "function", "to", "call", "with", "any", "errors", "found", "." ]
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1))
[ "def", "CheckSectionSpacing", "(", "filename", ",", "clean_lines", ",", "class_info", ",", "linenum", ",", "error", ")", ":", "# Skip checks if the class is small, where small means 25 lines or less.", "# 25 lines seems like a good cutoff since that's the usual height of", "# terminals, and any class that can't fit in one screen can't really", "# be considered \"small\".", "#", "# Also skip checks if we are on the first line. This accounts for", "# classes that look like", "# class Foo { public: ... };", "#", "# If we didn't find the end of the class, last_line would be zero,", "# and the check will be skipped by the first condition.", "if", "(", "class_info", ".", "last_line", "-", "class_info", ".", "starting_linenum", "<=", "24", "or", "linenum", "<=", "class_info", ".", "starting_linenum", ")", ":", "return", "matched", "=", "Match", "(", "r'\\s*(public|protected|private):'", ",", "clean_lines", ".", "lines", "[", "linenum", "]", ")", "if", "matched", ":", "# Issue warning if the line before public/protected/private was", "# not a blank line, but don't do this if the previous line contains", "# \"class\" or \"struct\". This can happen two ways:", "# - We are at the beginning of the class.", "# - We are forward-declaring an inner class that is semantically", "# private, but needed to be public for implementation reasons.", "# Also ignores cases where the previous line ends with a backslash as can be", "# common when defining classes in C macros.", "prev_line", "=", "clean_lines", ".", "lines", "[", "linenum", "-", "1", "]", "if", "(", "not", "IsBlankLine", "(", "prev_line", ")", "and", "not", "Search", "(", "r'\\b(class|struct)\\b'", ",", "prev_line", ")", "and", "not", "Search", "(", "r'\\\\$'", ",", "prev_line", ")", ")", ":", "# Try a bit harder to find the beginning of the class. This is to", "# account for multi-line base-specifier lists, e.g.:", "# class Derived", "# : public Base {", "end_class_head", "=", "class_info", ".", "starting_linenum", "for", "i", "in", "range", "(", "class_info", ".", "starting_linenum", ",", "linenum", ")", ":", "if", "Search", "(", "r'\\{\\s*$'", ",", "clean_lines", ".", "lines", "[", "i", "]", ")", ":", "end_class_head", "=", "i", "break", "if", "end_class_head", "<", "linenum", "-", "1", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'\"%s:\" should be preceded by a blank line'", "%", "matched", ".", "group", "(", "1", ")", ")" ]
https://github.com/gv22ga/dlib-face-recognition-android/blob/42d6305cbd85833f2b85bb79b70ab9ab004153c9/tools/lint/cpplint.py#L3436-L3486
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py
python
mean_squared_error
(labels, predictions, weights=None, metrics_collections=None, updates_collections=None, name=None)
return mean(squared_error, weights, metrics_collections, updates_collections, name or 'mean_squared_error')
Computes the mean squared error between the labels and predictions. The `mean_squared_error` function creates two local variables, `total` and `count` that are used to compute the mean squared error. This average is weighted by `weights`, and it is ultimately returned as `mean_squared_error`: an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_squared_error`. Internally, a `squared_error` operation computes the element-wise square of the difference between `predictions` and `labels`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `squared_error`, and it increments `count` with the reduced sum of `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: A `Tensor` of the same shape as `predictions`. predictions: A `Tensor` of arbitrary shape. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that `mean_squared_error` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: mean_squared_error: A `Tensor` representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_squared_error`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. RuntimeError: If eager execution is enabled.
Computes the mean squared error between the labels and predictions.
[ "Computes", "the", "mean", "squared", "error", "between", "the", "labels", "and", "predictions", "." ]
def mean_squared_error(labels, predictions, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the mean squared error between the labels and predictions. The `mean_squared_error` function creates two local variables, `total` and `count` that are used to compute the mean squared error. This average is weighted by `weights`, and it is ultimately returned as `mean_squared_error`: an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_squared_error`. Internally, a `squared_error` operation computes the element-wise square of the difference between `predictions` and `labels`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `squared_error`, and it increments `count` with the reduced sum of `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: A `Tensor` of the same shape as `predictions`. predictions: A `Tensor` of arbitrary shape. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that `mean_squared_error` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: mean_squared_error: A `Tensor` representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_squared_error`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. RuntimeError: If eager execution is enabled. """ if context.executing_eagerly(): raise RuntimeError('tf.metrics.mean_squared_error is not supported when ' 'eager execution is enabled.') predictions, labels, weights = _remove_squeezable_dimensions( predictions=predictions, labels=labels, weights=weights) squared_error = math_ops.squared_difference(labels, predictions) return mean(squared_error, weights, metrics_collections, updates_collections, name or 'mean_squared_error')
[ "def", "mean_squared_error", "(", "labels", ",", "predictions", ",", "weights", "=", "None", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")", ":", "if", "context", ".", "executing_eagerly", "(", ")", ":", "raise", "RuntimeError", "(", "'tf.metrics.mean_squared_error is not supported when '", "'eager execution is enabled.'", ")", "predictions", ",", "labels", ",", "weights", "=", "_remove_squeezable_dimensions", "(", "predictions", "=", "predictions", ",", "labels", "=", "labels", ",", "weights", "=", "weights", ")", "squared_error", "=", "math_ops", ".", "squared_difference", "(", "labels", ",", "predictions", ")", "return", "mean", "(", "squared_error", ",", "weights", ",", "metrics_collections", ",", "updates_collections", ",", "name", "or", "'mean_squared_error'", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py#L1266-L1323
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
demo/agw/AUI.py
python
ProgressGauge.GetPath
(self, gc, rc, r)
return path
Returns a rounded GraphicsPath.
Returns a rounded GraphicsPath.
[ "Returns", "a", "rounded", "GraphicsPath", "." ]
def GetPath(self, gc, rc, r): """ Returns a rounded GraphicsPath. """ x, y, w, h = rc path = gc.CreatePath() path.AddRoundedRectangle(x, y, w, h, r) path.CloseSubpath() return path
[ "def", "GetPath", "(", "self", ",", "gc", ",", "rc", ",", "r", ")", ":", "x", ",", "y", ",", "w", ",", "h", "=", "rc", "path", "=", "gc", ".", "CreatePath", "(", ")", "path", ".", "AddRoundedRectangle", "(", "x", ",", "y", ",", "w", ",", "h", ",", "r", ")", "path", ".", "CloseSubpath", "(", ")", "return", "path" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/demo/agw/AUI.py#L859-L866
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/appdirs.py
python
_get_win_folder_from_registry
(csidl_name)
return dir
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.
[ "This", "is", "a", "fallback", "technique", "at", "best", ".", "I", "m", "not", "sure", "if", "using", "the", "registry", "for", "this", "guarantees", "us", "the", "correct", "answer", "for", "all", "CSIDL_", "*", "names", "." ]
def _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ if PY3: import winreg as _winreg else: import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) dir, type = _winreg.QueryValueEx(key, shell_folder_name) return dir
[ "def", "_get_win_folder_from_registry", "(", "csidl_name", ")", ":", "if", "PY3", ":", "import", "winreg", "as", "_winreg", "else", ":", "import", "_winreg", "shell_folder_name", "=", "{", "\"CSIDL_APPDATA\"", ":", "\"AppData\"", ",", "\"CSIDL_COMMON_APPDATA\"", ":", "\"Common AppData\"", ",", "\"CSIDL_LOCAL_APPDATA\"", ":", "\"Local AppData\"", ",", "}", "[", "csidl_name", "]", "key", "=", "_winreg", ".", "OpenKey", "(", "_winreg", ".", "HKEY_CURRENT_USER", ",", "r\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\"", ")", "dir", ",", "type", "=", "_winreg", ".", "QueryValueEx", "(", "key", ",", "shell_folder_name", ")", "return", "dir" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/appdirs.py#L455-L476
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/mavlink_px4.py
python
MAVLink.set_gps_global_origin_encode
(self, target_system, latitude, longitude, altitude)
return msg
As local waypoints exist, the global MISSION reference allows to transform between the local coordinate frame and the global (GPS) coordinate frame. This can be necessary when e.g. in- and outdoor settings are connected and the MAV should move from in- to outdoor. target_system : System ID (uint8_t) latitude : global position * 1E7 (int32_t) longitude : global position * 1E7 (int32_t) altitude : global position * 1000 (int32_t)
As local waypoints exist, the global MISSION reference allows to transform between the local coordinate frame and the global (GPS) coordinate frame. This can be necessary when e.g. in- and outdoor settings are connected and the MAV should move from in- to outdoor.
[ "As", "local", "waypoints", "exist", "the", "global", "MISSION", "reference", "allows", "to", "transform", "between", "the", "local", "coordinate", "frame", "and", "the", "global", "(", "GPS", ")", "coordinate", "frame", ".", "This", "can", "be", "necessary", "when", "e", ".", "g", ".", "in", "-", "and", "outdoor", "settings", "are", "connected", "and", "the", "MAV", "should", "move", "from", "in", "-", "to", "outdoor", "." ]
def set_gps_global_origin_encode(self, target_system, latitude, longitude, altitude): ''' As local waypoints exist, the global MISSION reference allows to transform between the local coordinate frame and the global (GPS) coordinate frame. This can be necessary when e.g. in- and outdoor settings are connected and the MAV should move from in- to outdoor. target_system : System ID (uint8_t) latitude : global position * 1E7 (int32_t) longitude : global position * 1E7 (int32_t) altitude : global position * 1000 (int32_t) ''' msg = MAVLink_set_gps_global_origin_message(target_system, latitude, longitude, altitude) msg.pack(self) return msg
[ "def", "set_gps_global_origin_encode", "(", "self", ",", "target_system", ",", "latitude", ",", "longitude", ",", "altitude", ")", ":", "msg", "=", "MAVLink_set_gps_global_origin_message", "(", "target_system", ",", "latitude", ",", "longitude", ",", "altitude", ")", "msg", ".", "pack", "(", "self", ")", "return", "msg" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L3661-L3677
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/sparse_ops.py
python
sparse_slice
(sp_input, start, size, name=None)
Slice a `SparseTensor` based on the `start` and `size`. For example, if the input is input_tensor = shape = [2, 7] [ a d e ] [b c ] Graphically the output tensors are: sparse.slice([0, 0], [2, 4]) = shape = [2, 4] [ a ] [b c ] sparse.slice([0, 4], [2, 3]) = shape = [2, 3] [ d e ] [ ] Args: sp_input: The `SparseTensor` to split. start: 1-D. tensor represents the start of the slice. size: 1-D. tensor represents the size of the slice. name: A name for the operation (optional). Returns: A `SparseTensor` objects resulting from splicing. Raises: TypeError: If `sp_input` is not a `SparseTensor`.
Slice a `SparseTensor` based on the `start` and `size`.
[ "Slice", "a", "SparseTensor", "based", "on", "the", "start", "and", "size", "." ]
def sparse_slice(sp_input, start, size, name=None): """Slice a `SparseTensor` based on the `start` and `size`. For example, if the input is input_tensor = shape = [2, 7] [ a d e ] [b c ] Graphically the output tensors are: sparse.slice([0, 0], [2, 4]) = shape = [2, 4] [ a ] [b c ] sparse.slice([0, 4], [2, 3]) = shape = [2, 3] [ d e ] [ ] Args: sp_input: The `SparseTensor` to split. start: 1-D. tensor represents the start of the slice. size: 1-D. tensor represents the size of the slice. name: A name for the operation (optional). Returns: A `SparseTensor` objects resulting from splicing. Raises: TypeError: If `sp_input` is not a `SparseTensor`. """ sp_input = _convert_to_sparse_tensor(sp_input) start = ops.convert_to_tensor(start, dtypes.int64) size = ops.convert_to_tensor(size, dtypes.int64) with ops.name_scope(name, "SparseSlice", [sp_input]) as name: output_indices, output_values, output_shape = gen_sparse_ops.sparse_slice( sp_input.indices, sp_input.values, sp_input.dense_shape, start, size, name=name) return sparse_tensor.SparseTensor(output_indices, output_values, output_shape)
[ "def", "sparse_slice", "(", "sp_input", ",", "start", ",", "size", ",", "name", "=", "None", ")", ":", "sp_input", "=", "_convert_to_sparse_tensor", "(", "sp_input", ")", "start", "=", "ops", ".", "convert_to_tensor", "(", "start", ",", "dtypes", ".", "int64", ")", "size", "=", "ops", ".", "convert_to_tensor", "(", "size", ",", "dtypes", ".", "int64", ")", "with", "ops", ".", "name_scope", "(", "name", ",", "\"SparseSlice\"", ",", "[", "sp_input", "]", ")", "as", "name", ":", "output_indices", ",", "output_values", ",", "output_shape", "=", "gen_sparse_ops", ".", "sparse_slice", "(", "sp_input", ".", "indices", ",", "sp_input", ".", "values", ",", "sp_input", ".", "dense_shape", ",", "start", ",", "size", ",", "name", "=", "name", ")", "return", "sparse_tensor", ".", "SparseTensor", "(", "output_indices", ",", "output_values", ",", "output_shape", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/sparse_ops.py#L1121-L1166
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/encodings/zlib_codec.py
python
zlib_encode
(input,errors='strict')
return (output, len(input))
Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec.
Encodes the object input and returns a tuple (output object, length consumed).
[ "Encodes", "the", "object", "input", "and", "returns", "a", "tuple", "(", "output", "object", "length", "consumed", ")", "." ]
def zlib_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = zlib.compress(input) return (output, len(input))
[ "def", "zlib_encode", "(", "input", ",", "errors", "=", "'strict'", ")", ":", "assert", "errors", "==", "'strict'", "output", "=", "zlib", ".", "compress", "(", "input", ")", "return", "(", "output", ",", "len", "(", "input", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/encodings/zlib_codec.py#L14-L26
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_pytorch/nndct_shared/utils/registry.py
python
Registry.list
(self)
return self._registry.keys()
Lists registered items. Returns: A list of names of registered objects.
Lists registered items.
[ "Lists", "registered", "items", "." ]
def list(self): """Lists registered items. Returns: A list of names of registered objects. """ return self._registry.keys()
[ "def", "list", "(", "self", ")", ":", "return", "self", ".", "_registry", ".", "keys", "(", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_pytorch/nndct_shared/utils/registry.py#L55-L61
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/training/saver.py
python
BaseSaverBuilder.OpListToDict
(op_list)
return names_to_saveables
Create a dictionary of names to operation lists. Args: op_list: A list, tuple, or set of Variables or SaveableObjects. Returns: A dictionary of names to the operations that must be saved under that name. Variables with save_slice_info are grouped together under the same key in no particular order. Raises: TypeError: If the type of op_list or its elements is not supported. ValueError: If at least two saveables share the same name.
Create a dictionary of names to operation lists.
[ "Create", "a", "dictionary", "of", "names", "to", "operation", "lists", "." ]
def OpListToDict(op_list): """Create a dictionary of names to operation lists. Args: op_list: A list, tuple, or set of Variables or SaveableObjects. Returns: A dictionary of names to the operations that must be saved under that name. Variables with save_slice_info are grouped together under the same key in no particular order. Raises: TypeError: If the type of op_list or its elements is not supported. ValueError: If at least two saveables share the same name. """ if not isinstance(op_list, (list, tuple, set)): raise TypeError("Variables to save should be passed in a dict or a " "list: %s" % op_list) op_list = set(op_list) names_to_saveables = {} # pylint: disable=protected-access for var in op_list: if isinstance(var, BaseSaverBuilder.SaveableObject): names_to_saveables[var.name] = var elif isinstance(var, variables.PartitionedVariable): if var.name in names_to_saveables: raise ValueError("At least two variables have the same name: %s" % var.name) names_to_saveables[var.name] = var elif isinstance(var, variables.Variable) and var._save_slice_info: name = var._save_slice_info.full_name if name in names_to_saveables: if not isinstance(names_to_saveables[name], list): raise ValueError("Mixing slices and non-slices with the same name: " "%s" % name) names_to_saveables[name].append(var) else: names_to_saveables[name] = [var] else: if context.in_graph_mode(): var = ops.internal_convert_to_tensor(var, as_ref=True) if not BaseSaverBuilder._IsVariable(var): raise TypeError("Variable to save is not a Variable: %s" % var) if var.op.type == "ReadVariableOp": name = var.op.inputs[0].op.name else: name = var.op.name if name in names_to_saveables: raise ValueError("At least two variables have the same name: %s" % name) names_to_saveables[name] = var else: if not isinstance(var, resource_variable_ops.ResourceVariable): raise ValueError("Can only save/restore ResourceVariable eager " "mode is enabled, type: %s." % type(var)) set_var = names_to_saveables.setdefault(var._shared_name, var) if set_var is not var: raise ValueError( ("Two different ResourceVariable objects with the same " "shared_name '%s' were passed to the Saver. This likely means " "that they were created in different Graphs or isolation " "contexts, and may not be checkpointed together.") % ( var._shared_name,)) # pylint: enable=protected-access return names_to_saveables
[ "def", "OpListToDict", "(", "op_list", ")", ":", "if", "not", "isinstance", "(", "op_list", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "raise", "TypeError", "(", "\"Variables to save should be passed in a dict or a \"", "\"list: %s\"", "%", "op_list", ")", "op_list", "=", "set", "(", "op_list", ")", "names_to_saveables", "=", "{", "}", "# pylint: disable=protected-access", "for", "var", "in", "op_list", ":", "if", "isinstance", "(", "var", ",", "BaseSaverBuilder", ".", "SaveableObject", ")", ":", "names_to_saveables", "[", "var", ".", "name", "]", "=", "var", "elif", "isinstance", "(", "var", ",", "variables", ".", "PartitionedVariable", ")", ":", "if", "var", ".", "name", "in", "names_to_saveables", ":", "raise", "ValueError", "(", "\"At least two variables have the same name: %s\"", "%", "var", ".", "name", ")", "names_to_saveables", "[", "var", ".", "name", "]", "=", "var", "elif", "isinstance", "(", "var", ",", "variables", ".", "Variable", ")", "and", "var", ".", "_save_slice_info", ":", "name", "=", "var", ".", "_save_slice_info", ".", "full_name", "if", "name", "in", "names_to_saveables", ":", "if", "not", "isinstance", "(", "names_to_saveables", "[", "name", "]", ",", "list", ")", ":", "raise", "ValueError", "(", "\"Mixing slices and non-slices with the same name: \"", "\"%s\"", "%", "name", ")", "names_to_saveables", "[", "name", "]", ".", "append", "(", "var", ")", "else", ":", "names_to_saveables", "[", "name", "]", "=", "[", "var", "]", "else", ":", "if", "context", ".", "in_graph_mode", "(", ")", ":", "var", "=", "ops", ".", "internal_convert_to_tensor", "(", "var", ",", "as_ref", "=", "True", ")", "if", "not", "BaseSaverBuilder", ".", "_IsVariable", "(", "var", ")", ":", "raise", "TypeError", "(", "\"Variable to save is not a Variable: %s\"", "%", "var", ")", "if", "var", ".", "op", ".", "type", "==", "\"ReadVariableOp\"", ":", "name", "=", "var", ".", "op", ".", "inputs", "[", "0", "]", ".", "op", ".", "name", "else", ":", "name", "=", "var", ".", "op", ".", "name", "if", "name", "in", "names_to_saveables", ":", "raise", "ValueError", "(", "\"At least two variables have the same name: %s\"", "%", "name", ")", "names_to_saveables", "[", "name", "]", "=", "var", "else", ":", "if", "not", "isinstance", "(", "var", ",", "resource_variable_ops", ".", "ResourceVariable", ")", ":", "raise", "ValueError", "(", "\"Can only save/restore ResourceVariable eager \"", "\"mode is enabled, type: %s.\"", "%", "type", "(", "var", ")", ")", "set_var", "=", "names_to_saveables", ".", "setdefault", "(", "var", ".", "_shared_name", ",", "var", ")", "if", "set_var", "is", "not", "var", ":", "raise", "ValueError", "(", "(", "\"Two different ResourceVariable objects with the same \"", "\"shared_name '%s' were passed to the Saver. This likely means \"", "\"that they were created in different Graphs or isolation \"", "\"contexts, and may not be checkpointed together.\"", ")", "%", "(", "var", ".", "_shared_name", ",", ")", ")", "# pylint: enable=protected-access", "return", "names_to_saveables" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/saver.py#L505-L570
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/protobuf/python/google/protobuf/internal/cpp_message.py
python
InitMessage
(message_descriptor, cls)
Constructs a new message instance (called before instance's __init__).
Constructs a new message instance (called before instance's __init__).
[ "Constructs", "a", "new", "message", "instance", "(", "called", "before", "instance", "s", "__init__", ")", "." ]
def InitMessage(message_descriptor, cls): """Constructs a new message instance (called before instance's __init__).""" cls._extensions_by_name = {} _AddInitMethod(message_descriptor, cls) _AddMessageMethods(message_descriptor, cls) _AddPropertiesForExtensions(message_descriptor, cls) copy_reg.pickle(cls, lambda obj: (cls, (), obj.__getstate__()))
[ "def", "InitMessage", "(", "message_descriptor", ",", "cls", ")", ":", "cls", ".", "_extensions_by_name", "=", "{", "}", "_AddInitMethod", "(", "message_descriptor", ",", "cls", ")", "_AddMessageMethods", "(", "message_descriptor", ",", "cls", ")", "_AddPropertiesForExtensions", "(", "message_descriptor", ",", "cls", ")", "copy_reg", ".", "pickle", "(", "cls", ",", "lambda", "obj", ":", "(", "cls", ",", "(", ")", ",", "obj", ".", "__getstate__", "(", ")", ")", ")" ]
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/internal/cpp_message.py#L382-L388
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/markdown/extensions/admonition.py
python
AdmonitionExtension.extendMarkdown
(self, md, md_globals)
Add Admonition to Markdown instance.
Add Admonition to Markdown instance.
[ "Add", "Admonition", "to", "Markdown", "instance", "." ]
def extendMarkdown(self, md, md_globals): """ Add Admonition to Markdown instance. """ md.registerExtension(self) md.parser.blockprocessors.add('admonition', AdmonitionProcessor(md.parser), '_begin')
[ "def", "extendMarkdown", "(", "self", ",", "md", ",", "md_globals", ")", ":", "md", ".", "registerExtension", "(", "self", ")", "md", ".", "parser", ".", "blockprocessors", ".", "add", "(", "'admonition'", ",", "AdmonitionProcessor", "(", "md", ".", "parser", ")", ",", "'_begin'", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/markdown/extensions/admonition.py#L86-L92
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/vm/caffe/misc.py
python
set_mode_cpu
()
Set to the CPU mode. [**PyCaffe Style**] Returns ------- None References ---------- The implementation of `set_mode_cpu(_caffe.cpp, L51)`_.
Set to the CPU mode. [**PyCaffe Style**]
[ "Set", "to", "the", "CPU", "mode", ".", "[", "**", "PyCaffe", "Style", "**", "]" ]
def set_mode_cpu(): """Set to the CPU mode. [**PyCaffe Style**] Returns ------- None References ---------- The implementation of `set_mode_cpu(_caffe.cpp, L51)`_. """ config.EnableCPU()
[ "def", "set_mode_cpu", "(", ")", ":", "config", ".", "EnableCPU", "(", ")" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/caffe/misc.py#L20-L32
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch/optionstatus.py
python
OptionStatus.save
(self)
Write the current state of the local object back to the CloudSearch service.
Write the current state of the local object back to the CloudSearch service.
[ "Write", "the", "current", "state", "of", "the", "local", "object", "back", "to", "the", "CloudSearch", "service", "." ]
def save(self): """ Write the current state of the local object back to the CloudSearch service. """ if self.save_fn: data = self.save_fn(self.domain.name, self.to_json()) self.refresh(data)
[ "def", "save", "(", "self", ")", ":", "if", "self", ".", "save_fn", ":", "data", "=", "self", ".", "save_fn", "(", "self", ".", "domain", ".", "name", ",", "self", ".", "to_json", "(", ")", ")", "self", ".", "refresh", "(", "data", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch/optionstatus.py#L106-L113
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/pylib/host_driven/setup.py
python
_GetTestsFromModule
(test_module, **kwargs)
return tests
Gets a list of test objects from |test_module|. Args: test_module: Module from which to get the set of test methods. kwargs: Keyword args to pass into the constructor of test cases. Returns: A list of test case objects each initialized for a particular test method defined in |test_module|.
Gets a list of test objects from |test_module|.
[ "Gets", "a", "list", "of", "test", "objects", "from", "|test_module|", "." ]
def _GetTestsFromModule(test_module, **kwargs): """Gets a list of test objects from |test_module|. Args: test_module: Module from which to get the set of test methods. kwargs: Keyword args to pass into the constructor of test cases. Returns: A list of test case objects each initialized for a particular test method defined in |test_module|. """ tests = [] for name in dir(test_module): attr = getattr(test_module, name) if _IsTestCaseClass(attr): tests.extend(_GetTestsFromClass(attr, **kwargs)) return tests
[ "def", "_GetTestsFromModule", "(", "test_module", ",", "*", "*", "kwargs", ")", ":", "tests", "=", "[", "]", "for", "name", "in", "dir", "(", "test_module", ")", ":", "attr", "=", "getattr", "(", "test_module", ",", "name", ")", "if", "_IsTestCaseClass", "(", "attr", ")", ":", "tests", ".", "extend", "(", "_GetTestsFromClass", "(", "attr", ",", "*", "*", "kwargs", ")", ")", "return", "tests" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/host_driven/setup.py#L108-L125
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/search/common/utils.py
python
SearchUtils.NoSearchResults
(self, folder_name, style, response_type, callback=None)
return search_results
Prepares KML/JSONP output in case of no search results. Args: folder_name: Name of the folder which is used in folder->name in the response. style: Style information for KML. response_type: Response type can be KML or JSONP, depending on the client. callback: Call back function for the JSONP response. Returns: search_results: An empty KML/JSONP file with no search results.
Prepares KML/JSONP output in case of no search results.
[ "Prepares", "KML", "/", "JSONP", "output", "in", "case", "of", "no", "search", "results", "." ]
def NoSearchResults(self, folder_name, style, response_type, callback=None): """Prepares KML/JSONP output in case of no search results. Args: folder_name: Name of the folder which is used in folder->name in the response. style: Style information for KML. response_type: Response type can be KML or JSONP, depending on the client. callback: Call back function for the JSONP response. Returns: search_results: An empty KML/JSONP file with no search results. """ search_results = "" if response_type == "KML": search_results = self.kml_template.substitute( foldername=folder_name, style=style, lookat="", placemark="") elif response_type == "JSONP": search_results = self.json_template.substitute( foldername=folder_name, json_placemark="") search_results = self.jsonp_functioncall % (callback, search_results) else: self.logger.debug("%s response_type not supported", response_type) self.logger.info("search didn't return any results") return search_results
[ "def", "NoSearchResults", "(", "self", ",", "folder_name", ",", "style", ",", "response_type", ",", "callback", "=", "None", ")", ":", "search_results", "=", "\"\"", "if", "response_type", "==", "\"KML\"", ":", "search_results", "=", "self", ".", "kml_template", ".", "substitute", "(", "foldername", "=", "folder_name", ",", "style", "=", "style", ",", "lookat", "=", "\"\"", ",", "placemark", "=", "\"\"", ")", "elif", "response_type", "==", "\"JSONP\"", ":", "search_results", "=", "self", ".", "json_template", ".", "substitute", "(", "foldername", "=", "folder_name", ",", "json_placemark", "=", "\"\"", ")", "search_results", "=", "self", ".", "jsonp_functioncall", "%", "(", "callback", ",", "search_results", ")", "else", ":", "self", ".", "logger", ".", "debug", "(", "\"%s response_type not supported\"", ",", "response_type", ")", "self", ".", "logger", ".", "info", "(", "\"search didn't return any results\"", ")", "return", "search_results" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/search/common/utils.py#L170-L196
Zilliqa/Zilliqa
9c464cd6910cc4e83e84f49ea44d6bb7a7074ecc
scripts/run-clang-tidy.py
python
get_tidy_invocation
(f, clang_tidy_binary, checks, tmpdir, build_path, header_filter, extra_arg, extra_arg_before, quiet, config, warn_as_erro)
return start
Gets a command line for clang-tidy.
Gets a command line for clang-tidy.
[ "Gets", "a", "command", "line", "for", "clang", "-", "tidy", "." ]
def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path, header_filter, extra_arg, extra_arg_before, quiet, config, warn_as_erro): """Gets a command line for clang-tidy.""" start = [clang_tidy_binary] if header_filter is not None: start.append('-header-filter=' + header_filter) else: # Show warnings in all in-project headers by default. start.append('-header-filter=^' + build_path + '/.*') if checks: start.append('-checks=' + checks) if tmpdir is not None: start.append('-export-fixes') # Get a temporary file. We immediately close the handle so clang-tidy can # overwrite it. (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir) os.close(handle) start.append(name) for arg in extra_arg: start.append('-extra-arg=%s' % arg) for arg in extra_arg_before: start.append('-extra-arg-before=%s' % arg) start.append('-p=' + build_path) if quiet: start.append('-quiet') if config: start.append('-config=' + config) if warn_as_erro: start.append('-warnings-as-errors=' + warn_as_erro) start.append(f) return start
[ "def", "get_tidy_invocation", "(", "f", ",", "clang_tidy_binary", ",", "checks", ",", "tmpdir", ",", "build_path", ",", "header_filter", ",", "extra_arg", ",", "extra_arg_before", ",", "quiet", ",", "config", ",", "warn_as_erro", ")", ":", "start", "=", "[", "clang_tidy_binary", "]", "if", "header_filter", "is", "not", "None", ":", "start", ".", "append", "(", "'-header-filter='", "+", "header_filter", ")", "else", ":", "# Show warnings in all in-project headers by default.", "start", ".", "append", "(", "'-header-filter=^'", "+", "build_path", "+", "'/.*'", ")", "if", "checks", ":", "start", ".", "append", "(", "'-checks='", "+", "checks", ")", "if", "tmpdir", "is", "not", "None", ":", "start", ".", "append", "(", "'-export-fixes'", ")", "# Get a temporary file. We immediately close the handle so clang-tidy can", "# overwrite it.", "(", "handle", ",", "name", ")", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.yaml'", ",", "dir", "=", "tmpdir", ")", "os", ".", "close", "(", "handle", ")", "start", ".", "append", "(", "name", ")", "for", "arg", "in", "extra_arg", ":", "start", ".", "append", "(", "'-extra-arg=%s'", "%", "arg", ")", "for", "arg", "in", "extra_arg_before", ":", "start", ".", "append", "(", "'-extra-arg-before=%s'", "%", "arg", ")", "start", ".", "append", "(", "'-p='", "+", "build_path", ")", "if", "quiet", ":", "start", ".", "append", "(", "'-quiet'", ")", "if", "config", ":", "start", ".", "append", "(", "'-config='", "+", "config", ")", "if", "warn_as_erro", ":", "start", ".", "append", "(", "'-warnings-as-errors='", "+", "warn_as_erro", ")", "start", ".", "append", "(", "f", ")", "return", "start" ]
https://github.com/Zilliqa/Zilliqa/blob/9c464cd6910cc4e83e84f49ea44d6bb7a7074ecc/scripts/run-clang-tidy.py#L77-L108
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/roslaunch/src/roslaunch/parent.py
python
ROSLaunchParent.__init__
(self, run_id, roslaunch_files, is_core=False, port=None, local_only=False, process_listeners=None, verbose=False, force_screen=False, is_rostest=False, roslaunch_strs=None, num_workers=NUM_WORKERS, timeout=None)
@param run_id: UUID of roslaunch session @type run_id: str @param roslaunch_files: list of launch configuration files to load @type roslaunch_files: [str] @param is_core bool: if True, this launch is a roscore instance. This affects the error behavior if a master is already running (i.e. it fails). @type is_core: bool @param process_listeners: (optional) list of process listeners to register with process monitor once launch is running @type process_listeners: [L{roslaunch.pmon.ProcessListener}] @param port: (optional) override master port number from what is specified in the master URI. @type port: int @param verbose: (optional) print verbose output @type verbose: boolean @param force_screen: (optional) force output of all nodes to screen @type force_screen: boolean @param is_rostest bool: if True, this launch is a rostest instance. This affects validation checks. @type is_rostest: bool @param num_workers: If this is the core, the number of worker-threads to use. @type num_workers: int @param timeout: If this is the core, the socket-timeout to use. @type timeout: Float or None @throws RLException
[]
def __init__(self, run_id, roslaunch_files, is_core=False, port=None, local_only=False, process_listeners=None, verbose=False, force_screen=False, is_rostest=False, roslaunch_strs=None, num_workers=NUM_WORKERS, timeout=None): """ @param run_id: UUID of roslaunch session @type run_id: str @param roslaunch_files: list of launch configuration files to load @type roslaunch_files: [str] @param is_core bool: if True, this launch is a roscore instance. This affects the error behavior if a master is already running (i.e. it fails). @type is_core: bool @param process_listeners: (optional) list of process listeners to register with process monitor once launch is running @type process_listeners: [L{roslaunch.pmon.ProcessListener}] @param port: (optional) override master port number from what is specified in the master URI. @type port: int @param verbose: (optional) print verbose output @type verbose: boolean @param force_screen: (optional) force output of all nodes to screen @type force_screen: boolean @param is_rostest bool: if True, this launch is a rostest instance. This affects validation checks. @type is_rostest: bool @param num_workers: If this is the core, the number of worker-threads to use. @type num_workers: int @param timeout: If this is the core, the socket-timeout to use. @type timeout: Float or None @throws RLException """ self.logger = logging.getLogger('roslaunch.parent') self.run_id = run_id self.process_listeners = process_listeners self.roslaunch_files = roslaunch_files self.roslaunch_strs = roslaunch_strs self.is_core = is_core self.is_rostest = is_rostest self.port = port self.local_only = local_only self.verbose = verbose self.num_workers = num_workers self.timeout = timeout # I don't think we should have to pass in so many options from # the outside into the roslaunch parent. One possibility is to # allow alternate config loaders to be passed in. self.force_screen = force_screen # flag to prevent multiple shutdown attempts self._shutting_down = False self.config = self.runner = self.server = self.pm = self.remote_runner = None
[ "def", "__init__", "(", "self", ",", "run_id", ",", "roslaunch_files", ",", "is_core", "=", "False", ",", "port", "=", "None", ",", "local_only", "=", "False", ",", "process_listeners", "=", "None", ",", "verbose", "=", "False", ",", "force_screen", "=", "False", ",", "is_rostest", "=", "False", ",", "roslaunch_strs", "=", "None", ",", "num_workers", "=", "NUM_WORKERS", ",", "timeout", "=", "None", ")", ":", "self", ".", "logger", "=", "logging", ".", "getLogger", "(", "'roslaunch.parent'", ")", "self", ".", "run_id", "=", "run_id", "self", ".", "process_listeners", "=", "process_listeners", "self", ".", "roslaunch_files", "=", "roslaunch_files", "self", ".", "roslaunch_strs", "=", "roslaunch_strs", "self", ".", "is_core", "=", "is_core", "self", ".", "is_rostest", "=", "is_rostest", "self", ".", "port", "=", "port", "self", ".", "local_only", "=", "local_only", "self", ".", "verbose", "=", "verbose", "self", ".", "num_workers", "=", "num_workers", "self", ".", "timeout", "=", "timeout", "# I don't think we should have to pass in so many options from", "# the outside into the roslaunch parent. One possibility is to", "# allow alternate config loaders to be passed in.", "self", ".", "force_screen", "=", "force_screen", "# flag to prevent multiple shutdown attempts", "self", ".", "_shutting_down", "=", "False", "self", ".", "config", "=", "self", ".", "runner", "=", "self", ".", "server", "=", "self", ".", "pm", "=", "self", ".", "remote_runner", "=", "None" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/parent.py#L75-L128
clementine-player/Clementine
111379dfd027802b59125829fcf87e3e1d0ad73b
dist/cpplint.py
python
CleansedLines.NumLines
(self)
return self.num_lines
Returns the number of lines represented.
Returns the number of lines represented.
[ "Returns", "the", "number", "of", "lines", "represented", "." ]
def NumLines(self): """Returns the number of lines represented.""" return self.num_lines
[ "def", "NumLines", "(", "self", ")", ":", "return", "self", ".", "num_lines" ]
https://github.com/clementine-player/Clementine/blob/111379dfd027802b59125829fcf87e3e1d0ad73b/dist/cpplint.py#L1305-L1307
makefile/frcnn
8d9b9ebf8be8315ba2f374d460121b0adf1df29c
python/caffe/draw.py
python
get_layer_label
(layer, rankdir)
return node_label
Define node label based on layer type. Parameters ---------- layer : ? rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. Returns ------- string : A label for the current layer
Define node label based on layer type.
[ "Define", "node", "label", "based", "on", "layer", "type", "." ]
def get_layer_label(layer, rankdir): """Define node label based on layer type. Parameters ---------- layer : ? rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. Returns ------- string : A label for the current layer """ if rankdir in ('TB', 'BT'): # If graph orientation is vertical, horizontal space is free and # vertical space is not; separate words with spaces separator = ' ' else: # If graph orientation is horizontal, vertical space is free and # horizontal space is not; separate words with newlines separator = '\\n' if layer.type == 'Convolution' or layer.type == 'Deconvolution': # Outer double quotes needed or else colon characters don't parse # properly node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, layer.type, separator, layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size) else 1, separator, layer.convolution_param.stride[0] if len(layer.convolution_param.stride) else 1, separator, layer.convolution_param.pad[0] if len(layer.convolution_param.pad) else 0) elif layer.type == 'Pooling': pooling_types_dict = get_pooling_types_dict() node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, pooling_types_dict[layer.pooling_param.pool], layer.type, separator, layer.pooling_param.kernel_size, separator, layer.pooling_param.stride, separator, layer.pooling_param.pad) else: node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type) return node_label
[ "def", "get_layer_label", "(", "layer", ",", "rankdir", ")", ":", "if", "rankdir", "in", "(", "'TB'", ",", "'BT'", ")", ":", "# If graph orientation is vertical, horizontal space is free and", "# vertical space is not; separate words with spaces", "separator", "=", "' '", "else", ":", "# If graph orientation is horizontal, vertical space is free and", "# horizontal space is not; separate words with newlines", "separator", "=", "'\\\\n'", "if", "layer", ".", "type", "==", "'Convolution'", "or", "layer", ".", "type", "==", "'Deconvolution'", ":", "# Outer double quotes needed or else colon characters don't parse", "# properly", "node_label", "=", "'\"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d\"'", "%", "(", "layer", ".", "name", ",", "separator", ",", "layer", ".", "type", ",", "separator", ",", "layer", ".", "convolution_param", ".", "kernel_size", "[", "0", "]", "if", "len", "(", "layer", ".", "convolution_param", ".", "kernel_size", ")", "else", "1", ",", "separator", ",", "layer", ".", "convolution_param", ".", "stride", "[", "0", "]", "if", "len", "(", "layer", ".", "convolution_param", ".", "stride", ")", "else", "1", ",", "separator", ",", "layer", ".", "convolution_param", ".", "pad", "[", "0", "]", "if", "len", "(", "layer", ".", "convolution_param", ".", "pad", ")", "else", "0", ")", "elif", "layer", ".", "type", "==", "'Pooling'", ":", "pooling_types_dict", "=", "get_pooling_types_dict", "(", ")", "node_label", "=", "'\"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d\"'", "%", "(", "layer", ".", "name", ",", "separator", ",", "pooling_types_dict", "[", "layer", ".", "pooling_param", ".", "pool", "]", ",", "layer", ".", "type", ",", "separator", ",", "layer", ".", "pooling_param", ".", "kernel_size", ",", "separator", ",", "layer", ".", "pooling_param", ".", "stride", ",", "separator", ",", "layer", ".", "pooling_param", ".", "pad", ")", "else", ":", "node_label", "=", "'\"%s%s(%s)\"'", "%", "(", "layer", ".", "name", ",", "separator", ",", "layer", ".", "type", ")", "return", "node_label" ]
https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/python/caffe/draw.py#L62-L114
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/processor/conversion/ror/ability_subprocessor.py
python
RoRAbilitySubprocessor.game_entity_stance_ability
(line)
return ability_forward_ref
Adds the GameEntityStance ability to a line. :param line: Unit/Building line that gets the ability. :type line: ...dataformat.converter_object.ConverterObjectGroup :returns: The forward reference for the ability. :rtype: ...dataformat.forward_ref.ForwardRef
Adds the GameEntityStance ability to a line.
[ "Adds", "the", "GameEntityStance", "ability", "to", "a", "line", "." ]
def game_entity_stance_ability(line): """ Adds the GameEntityStance ability to a line. :param line: Unit/Building line that gets the ability. :type line: ...dataformat.converter_object.ConverterObjectGroup :returns: The forward reference for the ability. :rtype: ...dataformat.forward_ref.ForwardRef """ current_unit = line.get_head_unit() current_unit_id = line.get_head_unit_id() dataset = line.data name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) game_entity_name = name_lookup_dict[current_unit_id][0] ability_ref = f"{game_entity_name}.GameEntityStance" ability_raw_api_object = RawAPIObject(ability_ref, "GameEntityStance", dataset.nyan_api_objects) ability_raw_api_object.add_raw_parent("engine.ability.type.GameEntityStance") ability_location = ForwardRef(line, game_entity_name) ability_raw_api_object.set_location(ability_location) # Stances search_range = current_unit["search_radius"].get_value() stance_names = ["Aggressive", "StandGround"] # Attacking is preferred ability_preferences = [] if line.is_projectile_shooter(): ability_preferences.append(ForwardRef(line, f"{game_entity_name}.Attack")) elif line.is_melee() or line.is_ranged(): if line.has_command(7): ability_preferences.append(ForwardRef(line, f"{game_entity_name}.Attack")) if line.has_command(105): ability_preferences.append(ForwardRef(line, f"{game_entity_name}.Heal")) # Units are preferred before buildings type_preferences = [ dataset.pregen_nyan_objects["util.game_entity_type.types.Unit"].get_nyan_object(), dataset.pregen_nyan_objects["util.game_entity_type.types.Building"].get_nyan_object(), ] stances = [] for stance_name in stance_names: stance_api_ref = f"engine.util.game_entity_stance.type.{stance_name}" stance_ref = f"{game_entity_name}.GameEntityStance.{stance_name}" stance_raw_api_object = RawAPIObject(stance_ref, stance_name, dataset.nyan_api_objects) stance_raw_api_object.add_raw_parent(stance_api_ref) stance_location = ForwardRef(line, ability_ref) stance_raw_api_object.set_location(stance_location) # Search range stance_raw_api_object.add_raw_member("search_range", search_range, "engine.util.game_entity_stance.GameEntityStance") # Ability preferences stance_raw_api_object.add_raw_member("ability_preference", ability_preferences, "engine.util.game_entity_stance.GameEntityStance") # Type preferences stance_raw_api_object.add_raw_member("type_preference", type_preferences, "engine.util.game_entity_stance.GameEntityStance") line.add_raw_api_object(stance_raw_api_object) stance_forward_ref = ForwardRef(line, stance_ref) stances.append(stance_forward_ref) ability_raw_api_object.add_raw_member("stances", stances, "engine.ability.type.GameEntityStance") line.add_raw_api_object(ability_raw_api_object) ability_forward_ref = ForwardRef(line, ability_raw_api_object.get_id()) return ability_forward_ref
[ "def", "game_entity_stance_ability", "(", "line", ")", ":", "current_unit", "=", "line", ".", "get_head_unit", "(", ")", "current_unit_id", "=", "line", ".", "get_head_unit_id", "(", ")", "dataset", "=", "line", ".", "data", "name_lookup_dict", "=", "internal_name_lookups", ".", "get_entity_lookups", "(", "dataset", ".", "game_version", ")", "game_entity_name", "=", "name_lookup_dict", "[", "current_unit_id", "]", "[", "0", "]", "ability_ref", "=", "f\"{game_entity_name}.GameEntityStance\"", "ability_raw_api_object", "=", "RawAPIObject", "(", "ability_ref", ",", "\"GameEntityStance\"", ",", "dataset", ".", "nyan_api_objects", ")", "ability_raw_api_object", ".", "add_raw_parent", "(", "\"engine.ability.type.GameEntityStance\"", ")", "ability_location", "=", "ForwardRef", "(", "line", ",", "game_entity_name", ")", "ability_raw_api_object", ".", "set_location", "(", "ability_location", ")", "# Stances", "search_range", "=", "current_unit", "[", "\"search_radius\"", "]", ".", "get_value", "(", ")", "stance_names", "=", "[", "\"Aggressive\"", ",", "\"StandGround\"", "]", "# Attacking is preferred", "ability_preferences", "=", "[", "]", "if", "line", ".", "is_projectile_shooter", "(", ")", ":", "ability_preferences", ".", "append", "(", "ForwardRef", "(", "line", ",", "f\"{game_entity_name}.Attack\"", ")", ")", "elif", "line", ".", "is_melee", "(", ")", "or", "line", ".", "is_ranged", "(", ")", ":", "if", "line", ".", "has_command", "(", "7", ")", ":", "ability_preferences", ".", "append", "(", "ForwardRef", "(", "line", ",", "f\"{game_entity_name}.Attack\"", ")", ")", "if", "line", ".", "has_command", "(", "105", ")", ":", "ability_preferences", ".", "append", "(", "ForwardRef", "(", "line", ",", "f\"{game_entity_name}.Heal\"", ")", ")", "# Units are preferred before buildings", "type_preferences", "=", "[", "dataset", ".", "pregen_nyan_objects", "[", "\"util.game_entity_type.types.Unit\"", "]", ".", "get_nyan_object", "(", ")", ",", "dataset", ".", "pregen_nyan_objects", "[", "\"util.game_entity_type.types.Building\"", "]", ".", "get_nyan_object", "(", ")", ",", "]", "stances", "=", "[", "]", "for", "stance_name", "in", "stance_names", ":", "stance_api_ref", "=", "f\"engine.util.game_entity_stance.type.{stance_name}\"", "stance_ref", "=", "f\"{game_entity_name}.GameEntityStance.{stance_name}\"", "stance_raw_api_object", "=", "RawAPIObject", "(", "stance_ref", ",", "stance_name", ",", "dataset", ".", "nyan_api_objects", ")", "stance_raw_api_object", ".", "add_raw_parent", "(", "stance_api_ref", ")", "stance_location", "=", "ForwardRef", "(", "line", ",", "ability_ref", ")", "stance_raw_api_object", ".", "set_location", "(", "stance_location", ")", "# Search range", "stance_raw_api_object", ".", "add_raw_member", "(", "\"search_range\"", ",", "search_range", ",", "\"engine.util.game_entity_stance.GameEntityStance\"", ")", "# Ability preferences", "stance_raw_api_object", ".", "add_raw_member", "(", "\"ability_preference\"", ",", "ability_preferences", ",", "\"engine.util.game_entity_stance.GameEntityStance\"", ")", "# Type preferences", "stance_raw_api_object", ".", "add_raw_member", "(", "\"type_preference\"", ",", "type_preferences", ",", "\"engine.util.game_entity_stance.GameEntityStance\"", ")", "line", ".", "add_raw_api_object", "(", "stance_raw_api_object", ")", "stance_forward_ref", "=", "ForwardRef", "(", "line", ",", "stance_ref", ")", "stances", ".", "append", "(", "stance_forward_ref", ")", "ability_raw_api_object", ".", "add_raw_member", "(", "\"stances\"", ",", "stances", ",", "\"engine.ability.type.GameEntityStance\"", ")", "line", ".", "add_raw_api_object", "(", "ability_raw_api_object", ")", "ability_forward_ref", "=", "ForwardRef", "(", "line", ",", "ability_raw_api_object", ".", "get_id", "(", ")", ")", "return", "ability_forward_ref" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/ror/ability_subprocessor.py#L348-L432
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/fftpack/basic.py
python
rfft
(x, n=None, axis=-1, overwrite_x=False)
return _raw_fft(tmp,n,axis,1,overwrite_x,work_function)
Discrete Fourier transform of a real sequence. Parameters ---------- x : array_like, real-valued The data to transform. n : int, optional Defines the length of the Fourier transform. If `n` is not specified (the default) then ``n = x.shape[axis]``. If ``n < x.shape[axis]``, `x` is truncated, if ``n > x.shape[axis]``, `x` is zero-padded. axis : int, optional The axis along which the transform is applied. The default is the last axis. overwrite_x : bool, optional If set to true, the contents of `x` can be overwritten. Default is False. Returns ------- z : real ndarray The returned real array contains:: [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] if n is even [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] if n is odd where:: y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k*2*pi/n) j = 0..n-1 See Also -------- fft, irfft, numpy.fft.rfft Notes ----- Within numerical accuracy, ``y == rfft(irfft(y))``. Both single and double precision routines are implemented. Half precision inputs will be converted to single precision. Non floating-point inputs will be converted to double precision. Long-double precision inputs are not supported. To get an output with a complex datatype, consider using the related function `numpy.fft.rfft`. Examples -------- >>> from scipy.fftpack import fft, rfft >>> a = [9, -9, 1, 3] >>> fft(a) array([ 4. +0.j, 8.+12.j, 16. +0.j, 8.-12.j]) >>> rfft(a) array([ 4., 8., 12., 16.])
Discrete Fourier transform of a real sequence.
[ "Discrete", "Fourier", "transform", "of", "a", "real", "sequence", "." ]
def rfft(x, n=None, axis=-1, overwrite_x=False): """ Discrete Fourier transform of a real sequence. Parameters ---------- x : array_like, real-valued The data to transform. n : int, optional Defines the length of the Fourier transform. If `n` is not specified (the default) then ``n = x.shape[axis]``. If ``n < x.shape[axis]``, `x` is truncated, if ``n > x.shape[axis]``, `x` is zero-padded. axis : int, optional The axis along which the transform is applied. The default is the last axis. overwrite_x : bool, optional If set to true, the contents of `x` can be overwritten. Default is False. Returns ------- z : real ndarray The returned real array contains:: [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] if n is even [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] if n is odd where:: y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k*2*pi/n) j = 0..n-1 See Also -------- fft, irfft, numpy.fft.rfft Notes ----- Within numerical accuracy, ``y == rfft(irfft(y))``. Both single and double precision routines are implemented. Half precision inputs will be converted to single precision. Non floating-point inputs will be converted to double precision. Long-double precision inputs are not supported. To get an output with a complex datatype, consider using the related function `numpy.fft.rfft`. Examples -------- >>> from scipy.fftpack import fft, rfft >>> a = [9, -9, 1, 3] >>> fft(a) array([ 4. +0.j, 8.+12.j, 16. +0.j, 8.-12.j]) >>> rfft(a) array([ 4., 8., 12., 16.]) """ tmp = _asfarray(x) if not numpy.isrealobj(tmp): raise TypeError("1st argument must be real sequence") try: work_function = _DTYPE_TO_RFFT[tmp.dtype] except KeyError: raise ValueError("type %s is not supported" % tmp.dtype) overwrite_x = overwrite_x or _datacopied(tmp, x) return _raw_fft(tmp,n,axis,1,overwrite_x,work_function)
[ "def", "rfft", "(", "x", ",", "n", "=", "None", ",", "axis", "=", "-", "1", ",", "overwrite_x", "=", "False", ")", ":", "tmp", "=", "_asfarray", "(", "x", ")", "if", "not", "numpy", ".", "isrealobj", "(", "tmp", ")", ":", "raise", "TypeError", "(", "\"1st argument must be real sequence\"", ")", "try", ":", "work_function", "=", "_DTYPE_TO_RFFT", "[", "tmp", ".", "dtype", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"type %s is not supported\"", "%", "tmp", ".", "dtype", ")", "overwrite_x", "=", "overwrite_x", "or", "_datacopied", "(", "tmp", ",", "x", ")", "return", "_raw_fft", "(", "tmp", ",", "n", ",", "axis", ",", "1", ",", "overwrite_x", ",", "work_function", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/fftpack/basic.py#L374-L444
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py
python
Maildir.add_folder
(self, folder)
return result
Create a folder and return a Maildir instance representing it.
Create a folder and return a Maildir instance representing it.
[ "Create", "a", "folder", "and", "return", "a", "Maildir", "instance", "representing", "it", "." ]
def add_folder(self, folder): """Create a folder and return a Maildir instance representing it.""" path = os.path.join(self._path, '.' + folder) result = Maildir(path, factory=self._factory) maildirfolder_path = os.path.join(path, 'maildirfolder') if not os.path.exists(maildirfolder_path): os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY, 0666)) return result
[ "def", "add_folder", "(", "self", ",", "folder", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "'.'", "+", "folder", ")", "result", "=", "Maildir", "(", "path", ",", "factory", "=", "self", ".", "_factory", ")", "maildirfolder_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'maildirfolder'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "maildirfolder_path", ")", ":", "os", ".", "close", "(", "os", ".", "open", "(", "maildirfolder_path", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_WRONLY", ",", "0666", ")", ")", "return", "result" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L428-L436
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/fsm/FSM.py
python
FSM.demand
(self, request, *args)
Requests a state transition, by code that does not expect the request to be denied. If the request is denied, raises a `RequestDenied` exception. Unlike `request()`, this method allows a new request to be made while the FSM is currently in transition. In this case, the request is queued up and will be executed when the current transition finishes. Multiple requests will queue up in sequence. The return value of this function can be used in an `await` expression to suspend the current coroutine until the transition is done.
Requests a state transition, by code that does not expect the request to be denied. If the request is denied, raises a `RequestDenied` exception.
[ "Requests", "a", "state", "transition", "by", "code", "that", "does", "not", "expect", "the", "request", "to", "be", "denied", ".", "If", "the", "request", "is", "denied", "raises", "a", "RequestDenied", "exception", "." ]
def demand(self, request, *args): """Requests a state transition, by code that does not expect the request to be denied. If the request is denied, raises a `RequestDenied` exception. Unlike `request()`, this method allows a new request to be made while the FSM is currently in transition. In this case, the request is queued up and will be executed when the current transition finishes. Multiple requests will queue up in sequence. The return value of this function can be used in an `await` expression to suspend the current coroutine until the transition is done. """ self.fsmLock.acquire() try: assert isinstance(request, str) self.notify.debug("%s.demand(%s, %s" % ( self._name, request, str(args)[1:])) if not self.state: # Queue up the request. fut = AsyncFuture() self.__requestQueue.append((PythonUtil.Functor( self.demand, request, *args), fut)) return fut result = self.request(request, *args) if not result: raise RequestDenied("%s (from state: %s)" % (request, self.state)) return result._future or self.__doneFuture finally: self.fsmLock.release()
[ "def", "demand", "(", "self", ",", "request", ",", "*", "args", ")", ":", "self", ".", "fsmLock", ".", "acquire", "(", ")", "try", ":", "assert", "isinstance", "(", "request", ",", "str", ")", "self", ".", "notify", ".", "debug", "(", "\"%s.demand(%s, %s\"", "%", "(", "self", ".", "_name", ",", "request", ",", "str", "(", "args", ")", "[", "1", ":", "]", ")", ")", "if", "not", "self", ".", "state", ":", "# Queue up the request.", "fut", "=", "AsyncFuture", "(", ")", "self", ".", "__requestQueue", ".", "append", "(", "(", "PythonUtil", ".", "Functor", "(", "self", ".", "demand", ",", "request", ",", "*", "args", ")", ",", "fut", ")", ")", "return", "fut", "result", "=", "self", ".", "request", "(", "request", ",", "*", "args", ")", "if", "not", "result", ":", "raise", "RequestDenied", "(", "\"%s (from state: %s)\"", "%", "(", "request", ",", "self", ".", "state", ")", ")", "return", "result", ".", "_future", "or", "self", ".", "__doneFuture", "finally", ":", "self", ".", "fsmLock", ".", "release", "(", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/fsm/FSM.py#L294-L327
koth/kcws
88efbd36a7022de4e6e90f5a1fb880cf87cfae9f
third_party/python/cpplint/cpplint.py
python
_VerboseLevel
()
return _cpplint_state.verbose_level
Returns the module's verbosity setting.
Returns the module's verbosity setting.
[ "Returns", "the", "module", "s", "verbosity", "setting", "." ]
def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level
[ "def", "_VerboseLevel", "(", ")", ":", "return", "_cpplint_state", ".", "verbose_level" ]
https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/python/cpplint/cpplint.py#L862-L864
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Alignment/OfflineValidation/python/TkAlAllInOneTool/overlapValidation.py
python
OverlapValidation.appendToPlots
(self)
return '("{file}", "{title}", {color}, {style}),'.format(file=self.getCompareStrings(plain=True)["DEFAULT"], **self.getRepMap())
if no argument or "" is passed a string with an instantiation is returned, else the validation is appended to the list
if no argument or "" is passed a string with an instantiation is returned, else the validation is appended to the list
[ "if", "no", "argument", "or", "is", "passed", "a", "string", "with", "an", "instantiation", "is", "returned", "else", "the", "validation", "is", "appended", "to", "the", "list" ]
def appendToPlots(self): """ if no argument or "" is passed a string with an instantiation is returned, else the validation is appended to the list """ return '("{file}", "{title}", {color}, {style}),'.format(file=self.getCompareStrings(plain=True)["DEFAULT"], **self.getRepMap())
[ "def", "appendToPlots", "(", "self", ")", ":", "return", "'(\"{file}\", \"{title}\", {color}, {style}),'", ".", "format", "(", "file", "=", "self", ".", "getCompareStrings", "(", "plain", "=", "True", ")", "[", "\"DEFAULT\"", "]", ",", "*", "*", "self", ".", "getRepMap", "(", ")", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/OfflineValidation/python/TkAlAllInOneTool/overlapValidation.py#L41-L46
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Menu.InsertMenu
(*args, **kwargs)
return _core_.Menu_InsertMenu(*args, **kwargs)
InsertMenu(self, size_t pos, int id, String text, Menu submenu, String help=EmptyString) -> MenuItem
InsertMenu(self, size_t pos, int id, String text, Menu submenu, String help=EmptyString) -> MenuItem
[ "InsertMenu", "(", "self", "size_t", "pos", "int", "id", "String", "text", "Menu", "submenu", "String", "help", "=", "EmptyString", ")", "-", ">", "MenuItem" ]
def InsertMenu(*args, **kwargs): """InsertMenu(self, size_t pos, int id, String text, Menu submenu, String help=EmptyString) -> MenuItem""" return _core_.Menu_InsertMenu(*args, **kwargs)
[ "def", "InsertMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_InsertMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L12068-L12070
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/layers/local.py
python
get_locallyconnected_mask
(input_shape, kernel_shape, strides, padding, data_format)
return mask
Return a mask representing connectivity of a locally-connected operation. This method returns a masking numpy array of 0s and 1s (of type `np.float32`) that, when element-wise multiplied with a fully-connected weight tensor, masks out the weights between disconnected input-output pairs and thus implements local connectivity through a sparse fully-connected weight tensor. Assume an unshared convolution with given parameters is applied to an input having N spatial dimensions with `input_shape = (d_in1, ..., d_inN)` to produce an output with spatial shape `(d_out1, ..., d_outN)` (determined by layer parameters such as `strides`). This method returns a mask which can be broadcast-multiplied (element-wise) with a 2*(N+1)-D weight matrix (equivalent to a fully-connected layer between (N+1)-D activations (N spatial + 1 channel dimensions for input and output) to make it perform an unshared convolution with given `kernel_shape`, `strides`, `padding` and `data_format`. Args: input_shape: tuple of size N: `(d_in1, ..., d_inN)` spatial shape of the input. kernel_shape: tuple of size N, spatial shape of the convolutional kernel / receptive field. strides: tuple of size N, strides along each spatial dimension. padding: type of padding, string `"same"` or `"valid"`. data_format: a string, `"channels_first"` or `"channels_last"`. Returns: a `np.float32`-type `np.ndarray` of shape `(1, d_in1, ..., d_inN, 1, d_out1, ..., d_outN)` if `data_format == `"channels_first"`, or `(d_in1, ..., d_inN, 1, d_out1, ..., d_outN, 1)` if `data_format == "channels_last"`. Raises: ValueError: if `data_format` is neither `"channels_first"` nor `"channels_last"`.
Return a mask representing connectivity of a locally-connected operation.
[ "Return", "a", "mask", "representing", "connectivity", "of", "a", "locally", "-", "connected", "operation", "." ]
def get_locallyconnected_mask(input_shape, kernel_shape, strides, padding, data_format): """Return a mask representing connectivity of a locally-connected operation. This method returns a masking numpy array of 0s and 1s (of type `np.float32`) that, when element-wise multiplied with a fully-connected weight tensor, masks out the weights between disconnected input-output pairs and thus implements local connectivity through a sparse fully-connected weight tensor. Assume an unshared convolution with given parameters is applied to an input having N spatial dimensions with `input_shape = (d_in1, ..., d_inN)` to produce an output with spatial shape `(d_out1, ..., d_outN)` (determined by layer parameters such as `strides`). This method returns a mask which can be broadcast-multiplied (element-wise) with a 2*(N+1)-D weight matrix (equivalent to a fully-connected layer between (N+1)-D activations (N spatial + 1 channel dimensions for input and output) to make it perform an unshared convolution with given `kernel_shape`, `strides`, `padding` and `data_format`. Args: input_shape: tuple of size N: `(d_in1, ..., d_inN)` spatial shape of the input. kernel_shape: tuple of size N, spatial shape of the convolutional kernel / receptive field. strides: tuple of size N, strides along each spatial dimension. padding: type of padding, string `"same"` or `"valid"`. data_format: a string, `"channels_first"` or `"channels_last"`. Returns: a `np.float32`-type `np.ndarray` of shape `(1, d_in1, ..., d_inN, 1, d_out1, ..., d_outN)` if `data_format == `"channels_first"`, or `(d_in1, ..., d_inN, 1, d_out1, ..., d_outN, 1)` if `data_format == "channels_last"`. Raises: ValueError: if `data_format` is neither `"channels_first"` nor `"channels_last"`. """ mask = conv_utils.conv_kernel_mask( input_shape=input_shape, kernel_shape=kernel_shape, strides=strides, padding=padding) ndims = int(mask.ndim / 2) if data_format == 'channels_first': mask = np.expand_dims(mask, 0) mask = np.expand_dims(mask, -ndims - 1) elif data_format == 'channels_last': mask = np.expand_dims(mask, ndims) mask = np.expand_dims(mask, -1) else: raise ValueError('Unrecognized data_format: ' + str(data_format)) return mask
[ "def", "get_locallyconnected_mask", "(", "input_shape", ",", "kernel_shape", ",", "strides", ",", "padding", ",", "data_format", ")", ":", "mask", "=", "conv_utils", ".", "conv_kernel_mask", "(", "input_shape", "=", "input_shape", ",", "kernel_shape", "=", "kernel_shape", ",", "strides", "=", "strides", ",", "padding", "=", "padding", ")", "ndims", "=", "int", "(", "mask", ".", "ndim", "/", "2", ")", "if", "data_format", "==", "'channels_first'", ":", "mask", "=", "np", ".", "expand_dims", "(", "mask", ",", "0", ")", "mask", "=", "np", ".", "expand_dims", "(", "mask", ",", "-", "ndims", "-", "1", ")", "elif", "data_format", "==", "'channels_last'", ":", "mask", "=", "np", ".", "expand_dims", "(", "mask", ",", "ndims", ")", "mask", "=", "np", ".", "expand_dims", "(", "mask", ",", "-", "1", ")", "else", ":", "raise", "ValueError", "(", "'Unrecognized data_format: '", "+", "str", "(", "data_format", ")", ")", "return", "mask" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/layers/local.py#L643-L702
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/browser/web_contents.py
python
WebContents.HasReachedQuiescence
(self)
return has_reached_quiescence
Determine whether the page has reached quiescence after loading. Returns: True if 2 seconds have passed since last resource received, false otherwise. Raises: exceptions.Error: See EvaluateJavaScript() for a detailed list of possible exceptions.
Determine whether the page has reached quiescence after loading.
[ "Determine", "whether", "the", "page", "has", "reached", "quiescence", "after", "loading", "." ]
def HasReachedQuiescence(self): """Determine whether the page has reached quiescence after loading. Returns: True if 2 seconds have passed since last resource received, false otherwise. Raises: exceptions.Error: See EvaluateJavaScript() for a detailed list of possible exceptions. """ # Inclusion of the script that provides # window.__telemetry_testHasReachedNetworkQuiescence() # is idempotent, it's run on every call because WebContents doesn't track # page loads and we need to execute anew for every newly loaded page. has_reached_quiescence = ( self.EvaluateJavaScript(self._quiescence_js + "window.__telemetry_testHasReachedNetworkQuiescence()")) return has_reached_quiescence
[ "def", "HasReachedQuiescence", "(", "self", ")", ":", "# Inclusion of the script that provides", "# window.__telemetry_testHasReachedNetworkQuiescence()", "# is idempotent, it's run on every call because WebContents doesn't track", "# page loads and we need to execute anew for every newly loaded page.", "has_reached_quiescence", "=", "(", "self", ".", "EvaluateJavaScript", "(", "self", ".", "_quiescence_js", "+", "\"window.__telemetry_testHasReachedNetworkQuiescence()\"", ")", ")", "return", "has_reached_quiescence" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/browser/web_contents.py#L138-L156
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/pytorch/losses/rl_losses.py
python
BatchQPGLoss.loss
(self, policy_logits, action_values)
return total_loss
Constructs a PyTorch Crierion that computes the QPG loss for batches. Args: policy_logits: `B x A` tensor corresponding to policy logits. action_values: `B x A` tensor corresponding to Q-values. Returns: loss: A 0-D `float` tensor corresponding the loss.
Constructs a PyTorch Crierion that computes the QPG loss for batches.
[ "Constructs", "a", "PyTorch", "Crierion", "that", "computes", "the", "QPG", "loss", "for", "batches", "." ]
def loss(self, policy_logits, action_values): """Constructs a PyTorch Crierion that computes the QPG loss for batches. Args: policy_logits: `B x A` tensor corresponding to policy logits. action_values: `B x A` tensor corresponding to Q-values. Returns: loss: A 0-D `float` tensor corresponding the loss. """ _assert_rank_and_shape_compatibility([policy_logits, action_values], 2) advantages = compute_advantages(policy_logits, action_values) _assert_rank_and_shape_compatibility([advantages], 1) total_adv = torch.mean(advantages, dim=0) total_loss = total_adv if self._entropy_cost: policy_entropy = torch.mean(compute_entropy(policy_logits)) entropy_loss = torch.mul(float(self._entropy_cost), policy_entropy) total_loss = torch.add(total_loss, entropy_loss) return total_loss
[ "def", "loss", "(", "self", ",", "policy_logits", ",", "action_values", ")", ":", "_assert_rank_and_shape_compatibility", "(", "[", "policy_logits", ",", "action_values", "]", ",", "2", ")", "advantages", "=", "compute_advantages", "(", "policy_logits", ",", "action_values", ")", "_assert_rank_and_shape_compatibility", "(", "[", "advantages", "]", ",", "1", ")", "total_adv", "=", "torch", ".", "mean", "(", "advantages", ",", "dim", "=", "0", ")", "total_loss", "=", "total_adv", "if", "self", ".", "_entropy_cost", ":", "policy_entropy", "=", "torch", ".", "mean", "(", "compute_entropy", "(", "policy_logits", ")", ")", "entropy_loss", "=", "torch", ".", "mul", "(", "float", "(", "self", ".", "_entropy_cost", ")", ",", "policy_entropy", ")", "total_loss", "=", "torch", ".", "add", "(", "total_loss", ",", "entropy_loss", ")", "return", "total_loss" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/pytorch/losses/rl_losses.py#L109-L130
opengauss-mirror/openGauss-server
e383f1b77720a00ddbe4c0655bc85914d9b02a2b
src/gausskernel/dbmind/tools/predictor/python/run.py
python
configure_training
()
API for configuring model, needs to be called before prediction or train CURL format: curl -X POST -d '{"max_epoch":"200", "learning_rate":"0.01", "hidden_units":"60", "batch_size": "1000", "dim_red": "0.7","model_name":"rlstm"}' -H 'Content-Type: application/json' 'https://127.0.0.1:5000/configure' JSON Parameters: 'max_epoch': [OPTIONAL] default 500 'learning_rate': [OPTIONAL] default 1 'hidden_units': [OPTIONAL] default 50 'batch_size': [OPTIONAL] default 5000 'template_name' [OPTIONAL] network type of the target model, default rlstm model 'model_name': [COMPULSORY] model name to be saved, can be a already trained model 'labels': [COMPULSORY] target labels to predict 'dim_red': [OPTIONAL] part of variance explained by PCA, default -1 means no PCA :return: 0: Success F: TypeError I: Invalid parameter type M: Missing compulsory argument
API for configuring model, needs to be called before prediction or train CURL format: curl -X POST -d '{"max_epoch":"200", "learning_rate":"0.01", "hidden_units":"60", "batch_size": "1000", "dim_red": "0.7","model_name":"rlstm"}' -H 'Content-Type: application/json' 'https://127.0.0.1:5000/configure' JSON Parameters: 'max_epoch': [OPTIONAL] default 500 'learning_rate': [OPTIONAL] default 1 'hidden_units': [OPTIONAL] default 50 'batch_size': [OPTIONAL] default 5000 'template_name' [OPTIONAL] network type of the target model, default rlstm model 'model_name': [COMPULSORY] model name to be saved, can be a already trained model 'labels': [COMPULSORY] target labels to predict 'dim_red': [OPTIONAL] part of variance explained by PCA, default -1 means no PCA :return: 0: Success F: TypeError I: Invalid parameter type M: Missing compulsory argument
[ "API", "for", "configuring", "model", "needs", "to", "be", "called", "before", "prediction", "or", "train", "CURL", "format", ":", "curl", "-", "X", "POST", "-", "d", "{", "max_epoch", ":", "200", "learning_rate", ":", "0", ".", "01", "hidden_units", ":", "60", "batch_size", ":", "1000", "dim_red", ":", "0", ".", "7", "model_name", ":", "rlstm", "}", "-", "H", "Content", "-", "Type", ":", "application", "/", "json", "https", ":", "//", "127", ".", "0", ".", "0", ".", "1", ":", "5000", "/", "configure", "JSON", "Parameters", ":", "max_epoch", ":", "[", "OPTIONAL", "]", "default", "500", "learning_rate", ":", "[", "OPTIONAL", "]", "default", "1", "hidden_units", ":", "[", "OPTIONAL", "]", "default", "50", "batch_size", ":", "[", "OPTIONAL", "]", "default", "5000", "template_name", "[", "OPTIONAL", "]", "network", "type", "of", "the", "target", "model", "default", "rlstm", "model", "model_name", ":", "[", "COMPULSORY", "]", "model", "name", "to", "be", "saved", "can", "be", "a", "already", "trained", "model", "labels", ":", "[", "COMPULSORY", "]", "target", "labels", "to", "predict", "dim_red", ":", "[", "OPTIONAL", "]", "part", "of", "variance", "explained", "by", "PCA", "default", "-", "1", "means", "no", "PCA", ":", "return", ":", "0", ":", "Success", "F", ":", "TypeError", "I", ":", "Invalid", "parameter", "type", "M", ":", "Missing", "compulsory", "argument" ]
def configure_training(): ''' API for configuring model, needs to be called before prediction or train CURL format: curl -X POST -d '{"max_epoch":"200", "learning_rate":"0.01", "hidden_units":"60", "batch_size": "1000", "dim_red": "0.7","model_name":"rlstm"}' -H 'Content-Type: application/json' 'https://127.0.0.1:5000/configure' JSON Parameters: 'max_epoch': [OPTIONAL] default 500 'learning_rate': [OPTIONAL] default 1 'hidden_units': [OPTIONAL] default 50 'batch_size': [OPTIONAL] default 5000 'template_name' [OPTIONAL] network type of the target model, default rlstm model 'model_name': [COMPULSORY] model name to be saved, can be a already trained model 'labels': [COMPULSORY] target labels to predict 'dim_red': [OPTIONAL] part of variance explained by PCA, default -1 means no PCA :return: 0: Success F: TypeError I: Invalid parameter type M: Missing compulsory argument ''' global model_config global req_logger global model_logger global tb_url if request.method == 'POST': req_logger.info(request.data) arg_json = request.get_json() if 'model_name' in arg_json: model_name = arg_json['model_name'] model_config = ModelInfo(model_name) else: return 'M' return model_config.get_info(arg_json)
[ "def", "configure_training", "(", ")", ":", "global", "model_config", "global", "req_logger", "global", "model_logger", "global", "tb_url", "if", "request", ".", "method", "==", "'POST'", ":", "req_logger", ".", "info", "(", "request", ".", "data", ")", "arg_json", "=", "request", ".", "get_json", "(", ")", "if", "'model_name'", "in", "arg_json", ":", "model_name", "=", "arg_json", "[", "'model_name'", "]", "model_config", "=", "ModelInfo", "(", "model_name", ")", "else", ":", "return", "'M'", "return", "model_config", ".", "get_info", "(", "arg_json", ")" ]
https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/predictor/python/run.py#L72-L105