idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
55,700 | def scope_in ( ctx ) : logger . debug ( '# scope_in' ) logger . debug ( ctx ) ctx = ctx . clone ( ) compiled_story = None if not ctx . is_empty_stack ( ) : compiled_story = ctx . get_child_story ( ) logger . debug ( '# child' ) logger . debug ( compiled_story ) ctx . matched = True ctx . message = modify_stack_in_message ( ctx . message , lambda stack : stack [ : - 1 ] + [ { 'data' : matchers . serialize ( callable . WaitForReturn ( ) ) , 'step' : stack [ - 1 ] [ 'step' ] , 'topic' : stack [ - 1 ] [ 'topic' ] } ] ) try : if not compiled_story and ctx . is_scope_level_part ( ) : compiled_story = ctx . get_current_story_part ( ) except story_context . MissedStoryPart : pass if not compiled_story : compiled_story = ctx . compiled_story ( ) logger . debug ( '# [>] going deeper' ) ctx . message = modify_stack_in_message ( ctx . message , lambda stack : stack + [ stack_utils . build_empty_stack_item ( compiled_story . topic ) ] ) logger . debug ( ctx ) return ctx | - build new scope on the top of stack - and current scope will wait for it result |
55,701 | def str2date ( self , date_str ) : try : a_datetime = datetime . strptime ( date_str , self . _default_date_template ) return a_datetime . date ( ) except : pass for template in date_template_list : try : a_datetime = datetime . strptime ( date_str , template ) self . _default_date_template = template return a_datetime . date ( ) except : pass raise ValueError ( "Unable to parse date from: %r!" % date_str ) | Parse date from string . |
55,702 | def _str2datetime ( self , datetime_str ) : try : a_datetime = datetime . strptime ( datetime_str , self . _default_datetime_template ) return a_datetime except : pass for template in datetime_template_list : try : a_datetime = datetime . strptime ( datetime_str , template ) self . _default_datetime_template = template return a_datetime except : pass a_datetime = parse ( datetime_str ) self . str2datetime = parse return a_datetime | Parse datetime from string . |
55,703 | def define ( self ) : if len ( self . states ) == 0 : for char in self . alphabet : self . add_arc ( 0 , 0 , char ) self [ 0 ] . final = False | If DFA is empty create a sink state |
55,704 | def add_state ( self ) : sid = len ( self . states ) self . states . append ( DFAState ( sid ) ) return sid | Adds a new state |
55,705 | def _epsilon_closure ( self , state ) : closure = set ( [ state . stateid ] ) stack = [ state ] while True : if not stack : break s = stack . pop ( ) for arc in s : if self . isyms . find ( arc . ilabel ) != EPSILON or arc . nextstate in closure : continue closure . add ( arc . nextstate ) stack . append ( self . states [ arc . nextstate ] ) return closure | Returns the \ epsilon - closure for the state given as input . |
55,706 | def invert ( self ) : for state in self . states : if state . final : state . final = False else : state . final = True | Inverts the DFA final states |
55,707 | def as_list ( self ) : if hasattr ( self , 'cust_list' ) : return self . cust_list if hasattr ( self , 'attr_check' ) : self . attr_check ( ) cls_bltns = set ( dir ( self . __class__ ) ) ret = [ a for a in dir ( self ) if a not in cls_bltns and getattr ( self , a ) ] return ret | returns a list version of the object based on it s attributes |
55,708 | def as_dict ( self ) : if hasattr ( self , 'cust_dict' ) : return self . cust_dict if hasattr ( self , 'attr_check' ) : self . attr_check ( ) cls_bltns = set ( dir ( self . __class__ ) ) return { a : getattr ( self , a ) for a in dir ( self ) if a not in cls_bltns } | returns an dict version of the object based on it s attributes |
55,709 | def as_odict ( self ) : if hasattr ( self , 'cust_odict' ) : return self . cust_odict if hasattr ( self , 'attr_check' ) : self . attr_check ( ) odc = odict ( ) for attr in self . attrorder : odc [ attr ] = getattr ( self , attr ) return odc | returns an odict version of the object based on it s attributes |
55,710 | def fetch_and_parse ( url , bodyLines ) : pageHtml = fetch_page ( url ) return parse ( url , pageHtml , bodyLines ) | Takes a url and returns a dictionary of data with bodyLines lines |
55,711 | def copy_rec ( source , dest ) : if os . path . isdir ( source ) : for child in os . listdir ( source ) : new_dest = os . path . join ( dest , child ) os . makedirs ( new_dest , exist_ok = True ) copy_rec ( os . path . join ( source , child ) , new_dest ) elif os . path . isfile ( source ) : logging . info ( ' Copy "{}" to "{}"' . format ( source , dest ) ) shutil . copy ( source , dest ) else : logging . info ( ' Ignoring "{}"' . format ( source ) ) | Copy files between diferent directories . |
55,712 | def build ( self ) : signed = bool ( self . options ( ) & Builder . Options . Signed ) buildpath = self . buildPath ( ) if not buildpath : raise errors . InvalidBuildPath ( buildpath ) for key , value in self . environment ( ) . items ( ) : log . info ( 'SET {0}={1}' . format ( key , value ) ) os . environ [ key ] = value if os . path . exists ( buildpath ) : shutil . rmtree ( buildpath ) os . makedirs ( buildpath ) outpath = self . outputPath ( ) if not os . path . exists ( outpath ) : os . makedirs ( outpath ) src = self . licenseFile ( ) if src and os . path . exists ( src ) : targ = os . path . join ( buildpath , 'license.txt' ) shutil . copyfile ( src , targ ) if self . options ( ) & Builder . Options . GenerateRevision : self . generateRevision ( ) if self . options ( ) & Builder . Options . GenerateDocs : self . generateDocumentation ( buildpath ) if self . options ( ) & Builder . Options . GenerateSetupFile : setuppath = os . path . join ( self . sourcePath ( ) , '..' ) egg = ( self . options ( ) & Builder . Options . GenerateEgg ) != 0 self . generateSetupFile ( setuppath , egg = egg ) if self . options ( ) & Builder . Options . GenerateExecutable : if not self . generateExecutable ( signed = signed ) : return if self . options ( ) & Builder . Options . GenerateZipFile : self . generateZipFile ( self . outputPath ( ) ) if self . options ( ) & Builder . Options . GenerateInstaller : self . generateInstaller ( buildpath , signed = signed ) | Builds this object into the desired output information . |
55,713 | def generateRevision ( self ) : revpath = self . sourcePath ( ) if not os . path . exists ( revpath ) : return revfile = os . path . join ( revpath , self . revisionFilename ( ) ) mode = '' try : args = [ 'svn' , 'info' , revpath ] proc = subprocess . Popen ( args , stdout = subprocess . PIPE ) mode = 'svn' except WindowsError : try : args = [ 'git' , 'rev-parse' , 'HEAD' , revpath ] proc = subprocess . Popen ( args , stdout = subprocess . PIPE ) mode = 'git' except WindowsError : return rev = None if mode == 'svn' : for line in proc . stdout : data = re . match ( '^Revision: (\d+)' , line ) if data : rev = int ( data . group ( 1 ) ) break if rev is not None : try : f = open ( revfile , 'w' ) f . write ( '__revision__ = {0}\n' . format ( rev ) ) f . close ( ) except IOError : pass | Generates the revision file for this builder . |
55,714 | def generateSetupFile ( self , outpath = '.' , egg = False ) : outpath = os . path . abspath ( outpath ) outfile = os . path . join ( outpath , 'setup.py' ) opts = { 'name' : self . name ( ) , 'distname' : self . distributionName ( ) , 'version' : self . version ( ) , 'author' : self . author ( ) , 'author_email' : self . authorEmail ( ) , 'keywords' : self . keywords ( ) , 'license' : self . license ( ) , 'brief' : self . brief ( ) , 'description' : self . description ( ) , 'url' : self . companyUrl ( ) } wrap_dict = lambda x : map ( lambda k : "r'{0}': [{1}]" . format ( k [ 0 ] , ',\n' . join ( wrap_str ( k [ 1 ] ) ) ) , x . items ( ) ) opts [ 'dependencies' ] = ',\n' . join ( wrap_str ( self . dependencies ( ) ) ) opts [ 'classifiers' ] = ',\n' . join ( wrap_str ( self . classifiers ( ) ) ) if os . path . isfile ( self . sourcePath ( ) ) : basepath = os . path . normpath ( os . path . dirname ( self . sourcePath ( ) ) ) else : basepath = os . path . normpath ( self . sourcePath ( ) ) self . generatePlugins ( basepath ) exts = set ( ) for root , folders , files in os . walk ( basepath ) : for file_ in files : _ , ext = os . path . splitext ( file_ ) if ext not in ( '.py' , '.pyc' , '.pyo' ) : exts . add ( '*' + ext ) exts = list ( exts ) text = templ . SETUPFILE . format ( ** opts ) if not os . path . exists ( outfile ) : f = open ( outfile , 'w' ) f . write ( text ) f . close ( ) manfile = os . path . join ( outpath , 'MANIFEST.in' ) if not os . path . exists ( manfile ) : f = open ( manfile , 'w' ) f . write ( 'include *.md *.txt *.ini *.cfg *.rst\n' ) f . write ( 'recursive-include {0} {1}\n' . format ( self . name ( ) , ' ' . join ( exts ) ) ) f . close ( ) if egg : cmd = 'cd {0} && $PYTHON setup.py bdist_egg' . format ( outpath ) cmd = os . path . expandvars ( cmd ) cmdexec ( cmd ) | Generates the setup file for this builder . |
55,715 | def generateZipFile ( self , outpath = '.' ) : fname = self . installName ( ) + '.zip' outfile = os . path . abspath ( os . path . join ( outpath , fname ) ) if os . path . exists ( outfile ) : try : os . remove ( outfile ) except OSError : log . warning ( 'Could not remove zipfile: %s' , outfile ) return False zfile = zipfile . ZipFile ( outfile , 'w' ) if os . path . isfile ( self . sourcePath ( ) ) : zfile . write ( self . sourcePath ( ) , os . path . basename ( self . sourcePath ( ) ) ) else : basepath = os . path . abspath ( os . path . join ( self . sourcePath ( ) , '..' ) ) baselen = len ( basepath ) + 1 for root , folders , filenames in os . walk ( basepath ) : if '.svn' in root or '.git' in root : continue part = root [ baselen : ] . split ( os . path . sep ) [ 0 ] if part in ( 'build' , 'dist' ) or part . endswith ( '.egg-info' ) : continue for filename in filenames : ext = os . path . splitext ( filename ) [ 1 ] if ext in self . ignoreFileTypes ( ) : continue arcroot = root [ baselen : ] . replace ( '\\' , '/' ) arcname = os . path . join ( arcroot , filename ) log . info ( 'Archiving %s...' , arcname ) zfile . write ( os . path . join ( root , filename ) , arcname ) zfile . close ( ) return True | Generates the zip file for this builder . |
55,716 | def step_undefined_step_snippets_should_exist_for_table ( context ) : assert context . table , "REQUIRES: table" for row in context . table . rows : step = row [ "Step" ] step_undefined_step_snippet_should_exist_for ( context , step ) | Checks if undefined - step snippets are provided . |
55,717 | def step_undefined_step_snippets_should_not_exist_for_table ( context ) : assert context . table , "REQUIRES: table" for row in context . table . rows : step = row [ "Step" ] step_undefined_step_snippet_should_not_exist_for ( context , step ) | Checks if undefined - step snippets are not provided . |
55,718 | def mixin ( cls ) : cls . _events = { } cls . bind = Pyevent . bind . __func__ cls . unbind = Pyevent . unbind . __func__ cls . trigger = Pyevent . trigger . __func__ return cls | A decorator which adds event methods to a class giving it the ability to bind to and trigger events |
55,719 | def _read_options ( paths , fname_def = None ) : def reader_func ( fname = fname_def , sect = None , sett = None , default = None ) : cur_dir = os . path . dirname ( os . path . realpath ( __file__ ) ) config_dir = os . path . join ( cur_dir , * paths ) config_files = [ ( f [ : - 4 ] , f ) for f in os . listdir ( config_dir ) if f [ - 4 : ] == ".cfg" ] sample_files = [ ( f [ : - 11 ] , f ) for f in os . listdir ( config_dir ) if f [ - 11 : ] == ".cfg_sample" ] if fname : config_files = [ f for f in config_files if f [ 0 ] == fname ] sample_files = [ f for f in sample_files if f [ 0 ] == fname ] config_files = dict ( config_files ) sample_files = dict ( sample_files ) cfg_files = sample_files for fn , f in config_files . iteritems ( ) : cfg_files [ fn ] = f sample_files_exposed = [ ] confg = { } for src , fil in cfg_files . iteritems ( ) : confg [ src ] = { } cfpr = ConfigParser . ConfigParser ( ) cfpr . read ( os . path . join ( config_dir , fil ) ) for sec in cfpr . sections ( ) : confg [ src ] [ sec ] = dict ( cfpr . items ( sec ) ) if ".cfg_sample" in fil : sample_files_exposed . append ( fil ) if len ( sample_files_exposed ) > 0 : msg = ", " . join ( sample_files_exposed ) body = "{} sample configuration files have been exposed. " "Rename *.cfg_sample to *.cfg, and populate the " "correct settings in the config and settings " "directories to avoid this warning." msg = body . format ( msg ) warnings . warn ( msg ) keys = [ ] if fname : keys . append ( fname ) if sect : keys . append ( sect ) if sett : keys . append ( sett ) try : return get_from_nested ( keys , confg ) except KeyError : if default is not None : return default else : raise return reader_func | Builds a configuration reader function |
55,720 | def returnLabelState ( peptide , labelDescriptor , labelSymbols = None , labelAminoacids = None ) : if labelSymbols is None : labelSymbols = modSymbolsFromLabelInfo ( labelDescriptor ) if labelAminoacids is None : labelAminoacids = modAminoacidsFromLabelInfo ( labelDescriptor ) sequence = maspy . peptidemethods . removeModifications ( peptide ) modPositions = maspy . peptidemethods . returnModPositions ( peptide , indexStart = 0 , removeModString = False ) labelState = None _validator = lambda seq , aa : ( True if seq . find ( aa ) == - 1 else False ) if all ( [ _validator ( sequence , aa ) for aa in labelAminoacids ] ) : if 'nTerm' not in labelAminoacids and 'cTerm' not in labelAminoacids : labelState = - 1 if labelState is None : peptideLabelPositions = dict ( ) for labelSymbol in labelSymbols : if labelSymbol in viewkeys ( modPositions ) : for sequencePosition in modPositions [ labelSymbol ] : peptideLabelPositions . setdefault ( sequencePosition , list ( ) ) peptideLabelPositions [ sequencePosition ] . append ( labelSymbol ) for sequencePosition in list ( viewkeys ( peptideLabelPositions ) ) : peptideLabelPositions [ sequencePosition ] = sorted ( peptideLabelPositions [ sequencePosition ] ) predictedLabelStates = dict ( ) for predictedLabelState , labelStateInfo in viewitems ( labelDescriptor . labels ) : expectedLabelMods = expectedLabelPosition ( peptide , labelStateInfo , sequence = sequence , modPositions = modPositions ) predictedLabelStates [ predictedLabelState ] = expectedLabelMods if peptideLabelPositions == expectedLabelMods : labelState = predictedLabelState if labelState is None : labelState = - 2 elif labelState != - 1 : _comb = set ( itertools . combinations ( range ( len ( predictedLabelStates ) ) , 2 ) ) for state1 , state2 in _comb : if predictedLabelStates [ state1 ] == predictedLabelStates [ state2 ] : labelState = - 3 break return labelState | Calculates the label state of a given peptide for the label setup described in labelDescriptor |
55,721 | def modSymbolsFromLabelInfo ( labelDescriptor ) : modSymbols = set ( ) for labelStateEntry in viewvalues ( labelDescriptor . labels ) : for labelPositionEntry in viewvalues ( labelStateEntry [ 'aminoAcidLabels' ] ) : for modSymbol in aux . toList ( labelPositionEntry ) : if modSymbol != '' : modSymbols . add ( modSymbol ) return modSymbols | Returns a set of all modiciation symbols which were used in the labelDescriptor |
55,722 | def modAminoacidsFromLabelInfo ( labelDescriptor ) : modAminoacids = set ( ) for labelStateEntry in viewvalues ( labelDescriptor . labels ) : for labelPositionEntry in viewkeys ( labelStateEntry [ 'aminoAcidLabels' ] ) : for modAminoacid in aux . toList ( labelPositionEntry ) : if modAminoacid != '' : modAminoacids . add ( modAminoacid ) return modAminoacids | Returns a set of all amino acids and termini which can bear a label as described in labelDescriptor . |
55,723 | def expectedLabelPosition ( peptide , labelStateInfo , sequence = None , modPositions = None ) : if modPositions is None : modPositions = maspy . peptidemethods . returnModPositions ( peptide , indexStart = 0 ) if sequence is None : sequence = maspy . peptidemethods . removeModifications ( peptide ) currLabelMods = dict ( ) for labelPosition , labelSymbols in viewitems ( labelStateInfo [ 'aminoAcidLabels' ] ) : labelSymbols = aux . toList ( labelSymbols ) if labelSymbols == [ '' ] : pass elif labelPosition == 'nTerm' : currLabelMods . setdefault ( 0 , list ( ) ) currLabelMods [ 0 ] . extend ( labelSymbols ) else : for sequencePosition in aux . findAllSubstrings ( sequence , labelPosition ) : currLabelMods . setdefault ( sequencePosition , list ( ) ) currLabelMods [ sequencePosition ] . extend ( labelSymbols ) if labelStateInfo [ 'excludingModifications' ] is not None : for excludingMod , excludedLabelSymbol in viewitems ( labelStateInfo [ 'excludingModifications' ] ) : if excludingMod not in modPositions : continue for excludingModPos in modPositions [ excludingMod ] : if excludingModPos not in currLabelMods : continue if excludedLabelSymbol not in currLabelMods [ excludingModPos ] : continue if len ( currLabelMods [ excludingModPos ] ) == 1 : del ( currLabelMods [ excludingModPos ] ) else : excludedModIndex = currLabelMods [ excludingModPos ] . index ( excludedLabelSymbol ) currLabelMods [ excludingModPos ] . pop ( excludedModIndex ) for sequencePosition in list ( viewkeys ( currLabelMods ) ) : currLabelMods [ sequencePosition ] = sorted ( currLabelMods [ sequencePosition ] ) return currLabelMods | Returns a modification description of a certain label state of a peptide . |
55,724 | def addLabel ( self , aminoAcidLabels , excludingModifications = None ) : if excludingModifications is not None : self . excludingModifictions = True labelEntry = { 'aminoAcidLabels' : aminoAcidLabels , 'excludingModifications' : excludingModifications } self . labels [ self . _labelCounter ] = labelEntry self . _labelCounter += 1 | Adds a new labelstate . |
55,725 | def get_gen_slice ( ctx = Bubble ( ) , iterable = [ ] , amount = - 1 , index = - 1 ) : ctx . gbc . say ( 'get_gen_slice' , stuff = iterable , verbosity = 10 ) i = - 1 if amount > 0 : if index < 0 : index = 0 else : for item in iterable : i += 1 item [ buts ( 'index' ) ] = i ctx . gbc . say ( 'Get gen NO slice:item %d' % i , verbosity = 100 ) ctx . gbc . say ( 'Get gen NO slice:a:%d i:%d' % ( amount , index ) , verbosity = 100 ) ctx . gbc . say ( 'Get gen NO slice:item' , stuff = item , verbosity = 1000 ) yield item until = index + amount if six . PY2 : sli = xrange ( index , until ) else : sli = range ( index , until ) ctx . gbc . say ( 'Get gen slice:range %s' % str ( sli ) , verbosity = 1000 ) for item in iterable : i += 1 if i in sli : ctx . gbc . say ( 'Get gen slice:item %d' % i , verbosity = 100 ) ctx . gbc . say ( 'Get gen slice:a:%d i:%d' % ( amount , index ) , verbosity = 100 ) ctx . gbc . say ( 'Get gen slice:item' , stuff = item , verbosity = 1000 ) item [ buts ( 'index' ) ] = i yield item elif i > until : break else : pass | very crude way of slicing a generator |
55,726 | def _get_scripts ( self , scripts_path_rel , files_deployment , script_type , project_path ) : scripts_dict = { } if scripts_path_rel : self . _logger . debug ( 'Getting scripts with {0} definitions' . format ( script_type ) ) scripts_dict = pgpm . lib . utils . misc . collect_scripts_from_sources ( scripts_path_rel , files_deployment , project_path , False , self . _logger ) if len ( scripts_dict ) == 0 : self . _logger . debug ( 'No {0} definitions were found in {1} folder' . format ( script_type , scripts_path_rel ) ) else : self . _logger . debug ( 'No {0} folder was specified' . format ( script_type ) ) return scripts_dict | Gets scripts from specified folders |
55,727 | def _resolve_dependencies ( self , cur , dependencies ) : list_of_deps_ids = [ ] _list_of_deps_unresolved = [ ] _is_deps_resolved = True for k , v in dependencies . items ( ) : pgpm . lib . utils . db . SqlScriptsHelper . set_search_path ( cur , self . _pgpm_schema_name ) cur . execute ( "SELECT _find_schema('{0}', '{1}')" . format ( k , v ) ) pgpm_v_ext = tuple ( cur . fetchone ( ) [ 0 ] [ 1 : - 1 ] . split ( ',' ) ) try : list_of_deps_ids . append ( int ( pgpm_v_ext [ 0 ] ) ) except : pass if not pgpm_v_ext [ 0 ] : _is_deps_resolved = False _list_of_deps_unresolved . append ( "{0}: {1}" . format ( k , v ) ) return _is_deps_resolved , list_of_deps_ids , _list_of_deps_unresolved | Function checks if dependant packages are installed in DB |
55,728 | def _reorder_types ( self , types_script ) : self . _logger . debug ( 'Running types definitions scripts' ) self . _logger . debug ( 'Reordering types definitions scripts to avoid "type does not exist" exceptions' ) _type_statements = sqlparse . split ( types_script ) _type_statements_dict = { } type_unordered_scripts = [ ] type_drop_scripts = [ ] for _type_statement in _type_statements : _type_statement_parsed = sqlparse . parse ( _type_statement ) if len ( _type_statement_parsed ) > 0 : if _type_statement_parsed [ 0 ] . get_type ( ) == 'CREATE' : _type_body_r = r'\bcreate\s+\b(?:type|domain)\s+\b(\w+\.\w+|\w+)\b' _type_name = re . compile ( _type_body_r , flags = re . IGNORECASE ) . findall ( _type_statement ) [ 0 ] _type_statements_dict [ str ( _type_name ) ] = { 'script' : _type_statement , 'deps' : [ ] } elif _type_statement_parsed [ 0 ] . get_type ( ) == 'DROP' : type_drop_scripts . append ( _type_statement ) else : type_unordered_scripts . append ( _type_statement ) for _type_key in _type_statements_dict . keys ( ) : for _type_key_sub , _type_value in _type_statements_dict . items ( ) : if _type_key != _type_key_sub : if pgpm . lib . utils . misc . find_whole_word ( _type_key ) ( _type_value [ 'script' ] ) : _type_value [ 'deps' ] . append ( _type_key ) _deps_unresolved = True _type_script_order = 0 _type_names = [ ] type_ordered_scripts = [ ] while _deps_unresolved : for k , v in _type_statements_dict . items ( ) : if not v [ 'deps' ] : _type_names . append ( k ) v [ 'order' ] = _type_script_order _type_script_order += 1 if not v [ 'script' ] in type_ordered_scripts : type_ordered_scripts . append ( v [ 'script' ] ) else : _dep_exists = True for _dep in v [ 'deps' ] : if _dep not in _type_names : _dep_exists = False if _dep_exists : _type_names . append ( k ) v [ 'order' ] = _type_script_order _type_script_order += 1 if not v [ 'script' ] in type_ordered_scripts : type_ordered_scripts . append ( v [ 'script' ] ) else : v [ 'order' ] = - 1 _deps_unresolved = False for k , v in _type_statements_dict . items ( ) : if v [ 'order' ] == - 1 : _deps_unresolved = True return type_drop_scripts , type_ordered_scripts , type_unordered_scripts | Takes type scripts and reorders them to avoid Type doesn t exist exception |
55,729 | def find_table_links ( self ) : html = urlopen ( self . model_url ) . read ( ) doc = lh . fromstring ( html ) href_list = [ area . attrib [ 'href' ] for area in doc . cssselect ( 'map area' ) ] tables = self . _inception_table_links ( href_list ) return tables | When given a url this function will find all the available table names for that EPA dataset . |
55,730 | def find_definition_urls ( self , set_of_links ) : definition_dict = { } re_link_name = re . compile ( '.*p_table_name=(\w+)&p_topic.*' ) for link in set_of_links : if link . startswith ( 'http://' ) : table_dict = { } html = urlopen ( link ) . read ( ) doc = lh . fromstring ( html ) unordered_list = doc . cssselect ( '#main ul' ) [ - 1 ] for li in unordered_list . iterchildren ( ) : a = li . find ( 'a' ) table_dict . update ( { a . text : a . attrib [ 'href' ] } ) link_name = re_link_name . sub ( r'\1' , link ) . upper ( ) definition_dict . update ( { link_name : table_dict } ) return definition_dict | Find the available definition URLs for the columns in a table . |
55,731 | def create_agency ( self ) : agency = self . agency links = self . find_table_links ( ) definition_dict = self . find_definition_urls ( links ) with open ( agency + '.txt' , 'w' ) as f : f . write ( str ( definition_dict ) ) | Create an agency text file of definitions . |
55,732 | def loop_through_agency ( self ) : agency = self . agency with open ( agency + '.txt' ) as f : data = eval ( f . read ( ) ) for table in data : for column in data [ table ] : value_link = data [ table ] [ column ] data [ table ] [ column ] = self . grab_definition ( value_link ) data = json . dumps ( data ) with open ( agency + '_values.json' , 'w' ) as f : f . write ( str ( data ) ) | Loop through an agency to grab the definitions for its tables . |
55,733 | def grab_definition ( self , url ) : re_description = re . compile ( 'Description:(.+?\\n)' ) re_table_name = re . compile ( "(\w+ Table.+)" ) if url . startswith ( '//' ) : url = 'http:' + url elif url . startswith ( '/' ) : url = 'http://www.epa.gov' + url try : html = urlopen ( url ) . read ( ) doc = lh . fromstring ( html ) main = doc . cssselect ( '#main' ) [ 0 ] text = main . text_content ( ) definition = re_description . search ( text ) . group ( 1 ) . strip ( ) except ( AttributeError , IndexError , TypeError , HTTPError ) : print url else : value = re_table_name . sub ( '' , definition ) return value return url | Grab the column definition of a table from the EPA using a combination of regular expressions and lxml . |
55,734 | def main ( * argv , filesystem = None , do_exit = True , stdout = None , stderr = None ) : try : mdcli = MdCLI ( ) mdcli . filesystem = filesystem mdcli . stdout = stdout or sys . stdout mdcli . stderr = stderr or sys . stderr retval = mdcli . main ( * argv , loop = LOOP_NEVER ) if do_exit : sys . exit ( retval ) else : return retval except KeyboardInterrupt : pass | Main method for the cli . |
55,735 | def get_optparser ( self ) : p = Cmdln . get_optparser ( self ) p . add_option ( "-M" , "--maildir" , action = "store" , dest = "maildir" ) p . add_option ( "-V" , "--verbose" , action = "store_true" , dest = "verbose" ) return p | Override to allow specification of the maildir |
55,736 | def form ( context , form , ** kwargs ) : if not isinstance ( form , ( forms . BaseForm , TapeformFieldset ) ) : raise template . TemplateSyntaxError ( 'Provided form should be a `Form` instance, actual type: {0}' . format ( form . __class__ . __name__ ) ) return render_to_string ( form . get_layout_template ( kwargs . get ( 'using' , None ) ) , form . get_layout_context ( ) , ) | The form template tag will render a tape - form enabled form using the template provided by get_layout_template method of the form using the context generated by get_layout_context method of the form . |
55,737 | def formfield ( context , bound_field , ** kwargs ) : if not isinstance ( bound_field , forms . BoundField ) : raise template . TemplateSyntaxError ( 'Provided field should be a `BoundField` instance, actual type: {0}' . format ( bound_field . __class__ . __name__ ) ) return render_to_string ( bound_field . form . get_field_template ( bound_field , kwargs . get ( 'using' , None ) ) , bound_field . form . get_field_context ( bound_field ) , ) | The formfield template tag will render a form field of a tape - form enabled form using the template provided by get_field_template method of the form together with the context generated by get_field_context method of the form . |
55,738 | def wrap_as_node ( self , func ) : 'wrap a function as a node' name = self . get_name ( func ) @ wraps ( func ) def wrapped ( * args , ** kwargs ) : 'wrapped version of func' message = self . get_message_from_call ( * args , ** kwargs ) self . logger . info ( 'calling "%s" with %r' , name , message ) result = func ( message ) if isinstance ( result , GeneratorType ) : results = [ self . wrap_result ( name , item ) for item in result if item is not NoResult ] self . logger . debug ( '%s returned generator yielding %d items' , func , len ( results ) ) [ self . route ( name , item ) for item in results ] return tuple ( results ) else : if result is NoResult : return result result = self . wrap_result ( name , result ) self . logger . debug ( '%s returned single value %s' , func , result ) self . route ( name , result ) return result return wrapped | wrap a function as a node |
55,739 | def node ( self , fields , subscribe_to = None , entry_point = False , ignore = None , ** wrapper_options ) : def outer ( func ) : 'outer level function' self . logger . debug ( 'wrapping %s' , func ) wrapped = self . wrap_as_node ( func ) if hasattr ( self , 'wrap_node' ) : self . logger . debug ( 'wrapping node "%s" in custom wrapper' , wrapped ) wrapped = self . wrap_node ( wrapped , wrapper_options ) name = self . get_name ( func ) self . register ( name , wrapped , fields , subscribe_to , entry_point , ignore ) return wrapped return outer | \ Decorate a function to make it a node . |
55,740 | def resolve_node_modules ( self ) : 'import the modules specified in init' if not self . resolved_node_modules : try : self . resolved_node_modules = [ importlib . import_module ( mod , self . node_package ) for mod in self . node_modules ] except ImportError : self . resolved_node_modules = [ ] raise return self . resolved_node_modules | import the modules specified in init |
55,741 | def get_message_from_call ( self , * args , ** kwargs ) : if len ( args ) == 1 and isinstance ( args [ 0 ] , dict ) : self . logger . debug ( 'called with arg dictionary' ) result = args [ 0 ] elif len ( args ) == 0 and kwargs != { } : self . logger . debug ( 'called with kwargs' ) result = kwargs else : self . logger . error ( 'get_message_from_call could not handle "%r", "%r"' , args , kwargs ) raise TypeError ( 'Pass either keyword arguments or a dictionary argument' ) return self . message_class ( result ) | \ Get message object from a call . |
55,742 | def register ( self , name , func , fields , subscribe_to , entry_point , ignore ) : self . fields [ name ] = fields self . functions [ name ] = func self . register_route ( subscribe_to , name ) if ignore : self . register_ignore ( ignore , name ) if entry_point : self . add_entry_point ( name ) self . logger . info ( 'registered %s' , name ) | Register a named function in the graph |
55,743 | def add_entry_point ( self , destination ) : self . routes . setdefault ( '__entry_point' , set ( ) ) . add ( destination ) return self . routes [ '__entry_point' ] | \ Add an entry point |
55,744 | def register_route ( self , origins , destination ) : self . names . add ( destination ) self . logger . debug ( 'added "%s" to names' , destination ) origins = origins or [ ] if not isinstance ( origins , list ) : origins = [ origins ] self . regexes . setdefault ( destination , [ re . compile ( origin ) for origin in origins ] ) self . regenerate_routes ( ) return self . regexes [ destination ] | Add routes to the routing dictionary |
55,745 | def register_ignore ( self , origins , destination ) : if not isinstance ( origins , list ) : origins = [ origins ] self . ignore_regexes . setdefault ( destination , [ re . compile ( origin ) for origin in origins ] ) self . regenerate_routes ( ) return self . ignore_regexes [ destination ] | Add routes to the ignore dictionary |
55,746 | def regenerate_routes ( self ) : 'regenerate the routes after a new route is added' for destination , origins in self . regexes . items ( ) : resolved = [ name for name in self . names if name is not destination and any ( origin . search ( name ) for origin in origins ) ] ignores = self . ignore_regexes . get ( destination , [ ] ) for origin in resolved : destinations = self . routes . setdefault ( origin , set ( ) ) if any ( ignore . search ( origin ) for ignore in ignores ) : self . logger . info ( 'ignoring route "%s" -> "%s"' , origin , destination ) try : destinations . remove ( destination ) self . logger . debug ( 'removed "%s" -> "%s"' , origin , destination ) except KeyError : pass continue if destination not in destinations : self . logger . info ( 'added route "%s" -> "%s"' , origin , destination ) destinations . add ( destination ) | regenerate the routes after a new route is added |
55,747 | def route ( self , origin , message ) : self . resolve_node_modules ( ) if not self . routing_enabled : return subs = self . routes . get ( origin , set ( ) ) for destination in subs : self . logger . debug ( 'routing "%s" -> "%s"' , origin , destination ) self . dispatch ( origin , destination , message ) | \ Using the routing dictionary dispatch a message to all subscribers |
55,748 | def dispatch ( self , origin , destination , message ) : func = self . functions [ destination ] self . logger . debug ( 'calling %r directly' , func ) return func ( _origin = origin , ** message ) | \ dispatch a message to a named function |
55,749 | def wrap_result ( self , name , result ) : if not isinstance ( result , tuple ) : result = tuple ( [ result ] ) try : return dict ( zip ( self . fields [ name ] , result ) ) except KeyError : msg = '"%s" has no associated fields' self . logger . exception ( msg , name ) raise ValueError ( msg % name ) | Wrap a result from a function with it s stated fields |
55,750 | def get_name ( self , func ) : if hasattr ( func , 'name' ) : return func . name return '%s.%s' % ( func . __module__ , func . __name__ ) | Get the name to reference a function by |
55,751 | def main ( ) : if len ( argv ) < 2 : print 'Usage: ' print ' Get A String %s CFG_fileA FST_fileB' % argv [ 0 ] return alphabet = createalphabet ( ) cfgtopda = CfgPDA ( alphabet ) print '* Parsing Grammar:' , mma = cfgtopda . yyparse ( argv [ 1 ] ) print 'OK' flex_a = Flexparser ( alphabet ) print '* Parsing Regex:' , mmb = flex_a . yyparse ( argv [ 2 ] ) print mmb print 'OK' print '* Minimize Automaton:' , mmb . minimize ( ) print 'OK' print mmb print '* Diff:' , ops = PdaDiff ( mma , mmb , alphabet ) mmc = ops . diff ( ) print 'OK' print '* Get String:' , print ops . get_string ( ) | Testing function for PDA - DFA Diff Operation |
55,752 | def _intesect ( self ) : p1automaton = self . mma p2automaton = self . mmb p3automaton = PDA ( self . alphabet ) self . _break_terms ( ) p1counter = 0 p3counter = 0 p2states = list ( p2automaton . states ) print 'PDA States: ' + repr ( p1automaton . n ) print 'DFA States: ' + repr ( len ( list ( p2states ) ) ) ignorechars = p1automaton . nonterminals + [ 0 ] + [ '@closing' ] del ( ignorechars [ ignorechars . index ( 'S' ) ] ) while p1counter < p1automaton . n + 1 : p1state = p1automaton . s [ p1counter ] p2counter = 0 while p2counter < len ( list ( p2states ) ) : p2state = p2states [ p2counter ] tempstate = PDAState ( ) tempstate . id = ( p1state . id , p2state . stateid ) tempstate . sym = p1state . sym tempstate . type = p1state . type tempstate . trans = { } found = 0 for char in self . alphabet : if char in ignorechars : continue p2dest = self . _delta ( p2automaton , p2state , char ) if p2dest is not None : for potential in p1state . trans : if char in p1state . trans [ potential ] : found = 1 p1dest = potential if ( p1dest , p2dest . stateid ) not in tempstate . trans : tempstate . trans [ ( p1dest , p2dest . stateid ) ] = [ ] tempstate . trans [ ( p1dest , p2dest . stateid ) ] . append ( char ) if found == 0 and p1state . type == 3 and len ( p1state . trans ) > 0 : assert 1 == 1 , 'Check Failed: A READ state with transitions' ' did not participate in the cross product' if p2dest is not None : for nonterm in p1automaton . nonterminals + [ 0 ] + [ '@closing' ] : for potential in p1state . trans : if nonterm in p1state . trans [ potential ] : p1dest = potential if ( p1dest , p2state . stateid ) not in tempstate . trans : tempstate . trans [ ( p1dest , p2state . stateid ) ] = [ ] tempstate . trans [ ( p1dest , p2state . stateid ) ] . append ( nonterm ) p3automaton . s [ p3counter ] = tempstate p3counter = p3counter + 1 p2counter = p2counter + 1 p1counter = p1counter + 1 p3automaton . n = p3counter - 1 p3automaton . accepted = [ ] for state in p2automaton . states : if state . final != TropicalWeight ( float ( 'inf' ) ) : p3automaton . accepted . append ( state . stateid ) return p3automaton | The intesection of a PDA and a DFA |
55,753 | def diff ( self ) : self . mmb . complement ( self . alphabet ) self . mmb . minimize ( ) print 'start intersection' self . mmc = self . _intesect ( ) print 'end intersection' return self . mmc | The Difference between a PDA and a DFA |
55,754 | def refresh_devices ( self ) : try : response = self . api . get ( "/api/v2/devices" , { 'properties' : 'all' } ) for device_data in response [ 'DeviceList' ] : self . devices . append ( Device ( device_data , self ) ) except APIError as e : print ( "API error: " ) for key , value in e . data . iteritems : print ( str ( key ) + ": " + str ( value ) ) | Queries hub for list of devices and creates new device objects |
55,755 | def refresh_details ( self ) : try : return self . api_iface . _api_get ( "/api/v2/devices/" + str ( self . device_id ) ) except APIError as e : print ( "API error: " ) for key , value in e . data . iteritems : print ( str ( key ) + ": " + str ( value ) ) | Query hub and refresh all details of a device but NOT status includes grouplist not present in refresh_all_devices |
55,756 | def send_command ( self , command ) : data = { "command" : command , "device_id" : self . device_id } try : response = self . api_iface . _api_post ( "/api/v2/commands" , data ) return Command ( response , self ) except APIError as e : print ( "API error: " ) for key , value in e . data . iteritems : print ( str ( key ) + ": " + str ( value ) ) | Send a command to a device |
55,757 | def _update_details ( self , data ) : self . device_id = data [ 'DeviceID' ] self . device_name = data [ 'DeviceName' ] self . properties = data | Intakes dict of details and sets necessary properties in device |
55,758 | def _update_details ( self , data ) : for api_name in self . _properties : if api_name in data : setattr ( self , "_" + api_name , data [ api_name ] ) else : try : getattr ( self , "_" + api_name ) except AttributeError : setattr ( self , "_" + api_name , '' ) | Intakes dict of details and sets necessary properties in command |
55,759 | def query_status ( self ) : try : data = self . api_iface . _api_get ( self . link ) self . _update_details ( data ) except APIError as e : print ( "API error: " ) for key , value in e . data . iteritems : print ( str ( key ) + ": " + str ( value ) ) | Query the hub for the status of this command |
55,760 | def tracks ( self ) : if self . _tracks is None : self . _tracks = TrackList ( self . version , self . id ) return self . _tracks | Tracks list context |
55,761 | def extension ( names ) : for name in names : if not NAME_PATTERN . match ( name ) : raise ValueError ( 'invalid extension name: %s' % name ) def decorator ( f , names = names ) : return Extension ( f , names = names ) return decorator | Makes a function to be an extension . |
55,762 | def register ( self , extensions ) : for ext in reversed ( extensions ) : for name in ext . names : try : self . _extensions [ name ] . appendleft ( ext ) except KeyError : self . _extensions [ name ] = deque ( [ ext ] ) | Registers extensions . |
55,763 | def eval_extensions ( self , value , name , option , format ) : try : exts = self . _extensions [ name ] except KeyError : raise ValueError ( 'no suitable extension: %s' % name ) for ext in exts : rv = ext ( self , value , name , option , format ) if rv is not None : return rv | Evaluates extensions in the registry . If some extension handles the format string it returns a string . Otherwise returns None . |
55,764 | def GetShowDetails ( self ) : fileName = os . path . splitext ( os . path . basename ( self . fileInfo . origPath ) ) [ 0 ] episodeNumSubstring = set ( re . findall ( "(?<=[0-9])[xXeE][0-9]+(?:[xXeE_.-][0-9]+)*" , fileName ) ) if len ( episodeNumSubstring ) != 1 : goodlogging . Log . Info ( "TVFILE" , "Incompatible filename no episode match detected: {0}" . format ( self . fileInfo . origPath ) ) return False episodeNumSet = set ( re . findall ( "(?<=[xXeE_.-])[0-9]+" , episodeNumSubstring . pop ( ) ) ) episodeNumList = [ int ( i ) for i in episodeNumSet ] episodeNumList . sort ( ) episodeNum = "{0}" . format ( episodeNumList [ 0 ] ) if len ( episodeNumList ) > 1 : episodeNumReference = episodeNumList [ 0 ] for episodeNumIter in episodeNumList [ 1 : ] : if episodeNumIter == ( episodeNumReference + 1 ) : strNum = "{0}" . format ( episodeNumIter ) if len ( strNum ) == 1 : strNum = "0{0}" . format ( strNum ) self . showInfo . multiPartEpisodeNumbers . append ( strNum ) episodeNumReference = episodeNumIter else : break if len ( episodeNum ) == 1 : episodeNum = "0{0}" . format ( episodeNum ) self . showInfo . episodeNum = episodeNum seasonNumSet = set ( re . findall ( "[sS]([0-9]+)" , fileName ) ) preceedingS = True if len ( seasonNumSet ) == 1 : seasonNum = seasonNumSet . pop ( ) else : seasonNumSet = set ( re . findall ( "([0-9]+)[xX](?:[0-9]+[xX])*" , fileName ) ) preceedingS = False if len ( seasonNumSet ) == 1 : seasonNum = seasonNumSet . pop ( ) else : goodlogging . Log . Info ( "TVFILE" , "Incompatible filename no season match detected: {0}" . format ( self . fileInfo . origPath ) ) return False if len ( seasonNum ) == 1 : seasonNum = "0{0}" . format ( seasonNum ) self . showInfo . seasonNum = seasonNum if preceedingS is True : showNameList = re . findall ( "(.+?)\s*[_.-]*\s*[sS][0-9]+[xXeE][0-9]+.*" , fileName ) else : showNameList = re . findall ( "(.+?)\s*[_.-]*\s*[0-9]+[xXeE][0-9]+.*" , fileName ) if len ( showNameList ) == 1 : showName = util . StripSpecialCharacters ( showNameList [ 0 ] . lower ( ) , stripAll = True ) else : goodlogging . Log . Info ( "TVFILE" , "Incompatible filename no show name detected: {0}" . format ( self . fileInfo . origPath ) ) return False self . fileInfo . showName = showName return True | Extract show name season number and episode number from file name . |
55,765 | def GenerateNewFilePath ( self , fileDir = None ) : newFileName = self . GenerateNewFileName ( ) if newFileName is not None : if fileDir is None : fileDir = os . path . dirname ( self . fileInfo . origPath ) self . fileInfo . newPath = os . path . join ( fileDir , newFileName ) | Create new file path . If a fileDir is provided it will be used otherwise the original file path is used . Updates file info object with new path . |
55,766 | def Print ( self ) : goodlogging . Log . Info ( "TVFILE" , "TV File details are:" ) goodlogging . Log . IncreaseIndent ( ) goodlogging . Log . Info ( "TVFILE" , "Original File Path = {0}" . format ( self . fileInfo . origPath ) ) if self . showInfo . showName is not None : goodlogging . Log . Info ( "TVFILE" , "Show Name (from guide) = {0}" . format ( self . showInfo . showName ) ) elif self . fileInfo . showName is not None : goodlogging . Log . Info ( "TVFILE" , "Show Name (from file) = {0}" . format ( self . fileInfo . showName ) ) if self . showInfo . seasonNum is not None and self . showInfo . episodeNum is not None : goodlogging . Log . Info ( "TVFILE" , "Season & Episode = S{0}E{1}" . format ( self . showInfo . seasonNum , self . showInfo . episodeNum ) ) if self . showInfo . episodeName is not None : goodlogging . Log . Info ( "TVFILE" , "Episode Name: = {0}" . format ( self . showInfo . episodeName ) ) if self . fileInfo . newPath is not None : goodlogging . Log . Info ( "TVFILE" , "New File Path = {0}" . format ( self . fileInfo . newPath ) ) goodlogging . Log . DecreaseIndent ( ) | Print contents of showInfo and FileInfo object |
55,767 | def connectProcess ( connection , processProtocol , commandLine = '' , env = { } , usePTY = None , childFDs = None , * args , ** kwargs ) : processOpenDeferred = defer . Deferred ( ) process = SSHProcess ( processProtocol , commandLine , env , usePTY , childFDs , * args , ** kwargs ) process . processOpen = processOpenDeferred . callback process . openFailed = processOpenDeferred . errback connection . openChannel ( process ) return processOpenDeferred | Opens a SSHSession channel and connects a ProcessProtocol to it |
55,768 | def call_builder_init ( cls , kb_app , sphinx_app : Sphinx ) : conf_dir = sphinx_app . confdir plugins_dir = sphinx_app . config . kaybee_settings . plugins_dir full_plugins_dir = os . path . join ( conf_dir , plugins_dir ) if os . path . exists ( full_plugins_dir ) : sys . path . insert ( 0 , conf_dir ) plugin_package = importlib . import_module ( plugins_dir ) importscan . scan ( plugin_package ) else : logger . info ( f'## Kaybee: No plugin dir at {plugins_dir}' ) dectate . commit ( kb_app ) for callback in cls . get_callbacks ( kb_app , SphinxEvent . BI ) : callback ( kb_app , sphinx_app ) | On builder init event commit registry and do callbacks |
55,769 | def call_purge_doc ( cls , kb_app , sphinx_app : Sphinx , sphinx_env : BuildEnvironment , docname : str ) : for callback in EventAction . get_callbacks ( kb_app , SphinxEvent . EPD ) : callback ( kb_app , sphinx_app , sphinx_env , docname ) | On env - purge - doc do callbacks |
55,770 | def call_env_before_read_docs ( cls , kb_app , sphinx_app : Sphinx , sphinx_env : BuildEnvironment , docnames : List [ str ] ) : for callback in EventAction . get_callbacks ( kb_app , SphinxEvent . EBRD ) : callback ( kb_app , sphinx_app , sphinx_env , docnames ) | On env - read - docs do callbacks |
55,771 | def call_env_doctree_read ( cls , kb_app , sphinx_app : Sphinx , doctree : doctree ) : for callback in EventAction . get_callbacks ( kb_app , SphinxEvent . DREAD ) : callback ( kb_app , sphinx_app , doctree ) | On doctree - read do callbacks |
55,772 | def call_env_updated ( cls , kb_app , sphinx_app : Sphinx , sphinx_env : BuildEnvironment ) : for callback in EventAction . get_callbacks ( kb_app , SphinxEvent . EU ) : callback ( kb_app , sphinx_app , sphinx_env ) | On the env - updated event do callbacks |
55,773 | def call_html_collect_pages ( cls , kb_app , sphinx_app : Sphinx ) : EventAction . get_callbacks ( kb_app , SphinxEvent . HCP ) for callback in EventAction . get_callbacks ( kb_app , SphinxEvent . HCP ) : yield callback ( kb_app , sphinx_app ) | On html - collect - pages do callbacks |
55,774 | def call_env_check_consistency ( cls , kb_app , builder : StandaloneHTMLBuilder , sphinx_env : BuildEnvironment ) : for callback in EventAction . get_callbacks ( kb_app , SphinxEvent . ECC ) : callback ( kb_app , builder , sphinx_env ) | On env - check - consistency do callbacks |
55,775 | def get_layout_template ( self , template_name = None ) : if template_name : return template_name if self . layout_template : return self . layout_template return defaults . LAYOUT_DEFAULT_TEMPLATE | Returns the layout template to use when rendering the form to HTML . |
55,776 | def get_layout_context ( self ) : errors = self . non_field_errors ( ) for field in self . hidden_fields ( ) : errors . extend ( field . errors ) return { 'form' : self , 'errors' : errors , 'hidden_fields' : self . hidden_fields ( ) , 'visible_fields' : self . visible_fields ( ) , } | Returns the context which is used when rendering the form to HTML . |
55,777 | def get_field_template ( self , bound_field , template_name = None ) : if template_name : return template_name templates = self . field_template_overrides or { } template_name = templates . get ( bound_field . name , None ) if template_name : return template_name template_name = templates . get ( bound_field . field . __class__ , None ) if template_name : return template_name if self . field_template : return self . field_template return defaults . FIELD_DEFAULT_TEMPLATE | Returns the field template to use when rendering a form field to HTML . |
55,778 | def get_field_label_css_class ( self , bound_field ) : class_name = self . field_label_css_class if bound_field . errors and self . field_label_invalid_css_class : class_name = join_css_class ( class_name , self . field_label_invalid_css_class ) return class_name or None | Returns the optional label CSS class to use when rendering a field template . |
55,779 | def get_field_context ( self , bound_field ) : widget = bound_field . field . widget widget_class_name = widget . __class__ . __name__ . lower ( ) field_id = widget . attrs . get ( 'id' ) or bound_field . auto_id if field_id : field_id = widget . id_for_label ( field_id ) return { 'form' : self , 'field' : bound_field , 'field_id' : field_id , 'field_name' : bound_field . name , 'errors' : bound_field . errors , 'required' : bound_field . field . required , 'label' : bound_field . label , 'label_css_class' : self . get_field_label_css_class ( bound_field ) , 'help_text' : mark_safe ( bound_field . help_text ) if bound_field . help_text else None , 'container_css_class' : self . get_field_container_css_class ( bound_field ) , 'widget_class_name' : widget_class_name , 'widget_input_type' : getattr ( widget , 'input_type' , None ) or widget_class_name } | Returns the context which is used when rendering a form field to HTML . |
55,780 | def apply_widget_template ( self , field_name ) : field = self . fields [ field_name ] template_name = self . get_widget_template ( field_name , field ) if template_name : field . widget . template_name = template_name | Applies widget template overrides if available . |
55,781 | def get_widget_template ( self , field_name , field ) : templates = self . widget_template_overrides or { } template_name = templates . get ( field_name , None ) if template_name : return template_name template_name = templates . get ( field . widget . __class__ , None ) if template_name : return template_name return None | Returns the optional widget template to use when rendering the widget for a form field . |
55,782 | def apply_widget_css_class ( self , field_name ) : field = self . fields [ field_name ] class_name = self . get_widget_css_class ( field_name , field ) if class_name : field . widget . attrs [ 'class' ] = join_css_class ( field . widget . attrs . get ( 'class' , None ) , class_name ) | Applies CSS classes to widgets if available . |
55,783 | def apply_widget_invalid_options ( self , field_name ) : field = self . fields [ field_name ] class_name = self . get_widget_invalid_css_class ( field_name , field ) if class_name : field . widget . attrs [ 'class' ] = join_css_class ( field . widget . attrs . get ( 'class' , None ) , class_name ) field . widget . attrs [ 'aria-invalid' ] = 'true' | Applies additional widget options for an invalid field . |
55,784 | def use_quandl_data ( self , authtoken ) : dfs = { } st = self . start . strftime ( "%Y-%m-%d" ) at = authtoken for pair in self . pairs : symbol = "" . join ( pair ) qsym = "CURRFX/{}" . format ( symbol ) dfs [ symbol ] = qdl . get ( qsym , authtoken = at , trim_start = st ) [ 'Rate' ] self . build_conversion_table ( dfs ) | Use quandl data to build conversion table |
55,785 | def build_conversion_table ( self , dataframes ) : self . data = pd . DataFrame ( dataframes ) tmp_pairs = [ s . split ( "/" ) for s in self . data . columns ] self . data . columns = pd . MultiIndex . from_tuples ( tmp_pairs ) | Build conversion table from a dictionary of dataframes |
55,786 | def match_tweet ( self , tweet , user_stream ) : if user_stream : if len ( self . track ) > 0 : return self . is_tweet_match_track ( tweet ) return True return self . is_tweet_match_track ( tweet ) or self . is_tweet_match_follow ( tweet ) | Check if a tweet matches the defined criteria |
55,787 | def connectMSExchange ( server ) : if not sspi : return False , 'No sspi module found.' code , response = server . ehlo ( ) if code != SMTP_EHLO_OKAY : return False , 'Server did not respond to EHLO command.' sspi_client = sspi . ClientAuth ( 'NTLM' ) sec_buffer = None err , sec_buffer = sspi_client . authorize ( sec_buffer ) buffer = sec_buffer [ 0 ] . Buffer ntlm_message = base64 . encodestring ( buffer ) . replace ( '\n' , '' ) code , response = server . docmd ( 'AUTH' , 'NTLM ' + ntlm_message ) if code != SMTP_AUTH_CHALLENGE : msg = 'Server did not respond as expected to NTLM negotiate message' return False , msg err , sec_buffer = sspi_client . authorize ( base64 . decodestring ( response ) ) buffer = sec_buffer [ 0 ] . Buffer ntlm_message = base64 . encodestring ( buffer ) . replace ( '\n' , '' ) code , response = server . docmd ( '' , ntlm_message ) if code != SMTP_AUTH_OKAY : return False , response return True , '' | Creates a connection for the inputted server to a Microsoft Exchange server . |
55,788 | def set_entries ( self , entries : List [ Tuple [ str , str ] ] , titles , resources ) : self . entries = [ ] for flag , pagename in entries : title = titles [ pagename ] . children [ 0 ] resource = resources . get ( pagename , None ) if resource and hasattr ( resource , 'is_published' ) and not resource . is_published : continue self . entries . append ( dict ( title = title , href = pagename , resource = resource ) ) self . result_count = len ( self . entries ) | Provide the template the data for the toc entries |
55,789 | def render ( self , builder , context , sphinx_app : Sphinx ) : context [ 'sphinx_app' ] = sphinx_app context [ 'toctree' ] = self html = builder . templates . render ( self . template + '.html' , context ) return html | Given a Sphinx builder and context with site in it generate HTML |
55,790 | def parse_code ( url ) : result = urlparse ( url ) query = parse_qs ( result . query ) return query [ 'code' ] | Parse the code parameter from the a URL |
55,791 | def user_token ( scopes , client_id = None , client_secret = None , redirect_uri = None ) : webbrowser . open_new ( authorize_url ( client_id = client_id , redirect_uri = redirect_uri , scopes = scopes ) ) code = parse_code ( raw_input ( 'Enter the URL that you were redirected to: ' ) ) return User ( code , client_id = client_id , client_secret = client_secret , redirect_uri = redirect_uri ) | Generate a user access token |
55,792 | def consume_file ( self , infile ) : reader = tag . reader . GFF3Reader ( infilename = infile ) self . consume ( reader ) | Load the specified GFF3 file into memory . |
55,793 | def consume ( self , entrystream ) : for entry in entrystream : if isinstance ( entry , tag . directive . Directive ) and entry . type == 'sequence-region' : self . consume_seqreg ( entry ) elif isinstance ( entry , tag . feature . Feature ) : self . consume_feature ( entry ) | Load a stream of entries into memory . |
55,794 | def query ( self , seqid , start , end , strict = True ) : return sorted ( [ intvl . data for intvl in self [ seqid ] . search ( start , end , strict ) ] ) | Query the index for features in the specified range . |
55,795 | def cli ( ctx , stage ) : if not ctx . bubble : ctx . say_yellow ( 'There is no bubble present, will not show any transformer functions' ) raise click . Abort ( ) rule_functions = get_registered_rule_functions ( ) ctx . gbc . say ( 'before loading functions:' + str ( len ( rule_functions ) ) ) load_rule_functions ( ctx ) ctx . gbc . say ( 'after loading functions:' + str ( len ( rule_functions ) ) ) ctx . gbc . say ( 'rule_functions:' , stuff = rule_functions , verbosity = 10 ) rule_functions . set_parent ( ctx . gbc ) for f in rule_functions : ctx . say ( 'fun: ' + f , verbosity = 1 ) ctx . gbc . say ( 'funs: ' , stuff = rule_functions . get_rule_functions ( ) , verbosity = 100 ) return True | Show the functions that are available bubble system and custom . |
55,796 | def to_utc ( a_datetime , keep_utc_tzinfo = False ) : if a_datetime . tzinfo : utc_datetime = a_datetime . astimezone ( utc ) if keep_utc_tzinfo is False : utc_datetime = utc_datetime . replace ( tzinfo = None ) return utc_datetime else : return a_datetime | Convert a time awared datetime to utc datetime . |
55,797 | def utc_to_tz ( utc_datetime , tzinfo , keep_tzinfo = False ) : tz_awared_datetime = utc_datetime . replace ( tzinfo = utc ) . astimezone ( tzinfo ) if keep_tzinfo is False : tz_awared_datetime = tz_awared_datetime . replace ( tzinfo = None ) return tz_awared_datetime | Convert a UTC datetime to a time awared local time |
55,798 | def repr_data_size ( size_in_bytes , precision = 2 ) : if size_in_bytes < 1024 : return "%s B" % size_in_bytes magnitude_of_data = [ "B" , "KB" , "MB" , "GB" , "TB" , "PB" , "EB" , "ZB" , "YB" ] index = 0 while 1 : index += 1 size_in_bytes , mod = divmod ( size_in_bytes , 1024 ) if size_in_bytes < 1024 : break template = "{0:.%sf} {1}" % precision s = template . format ( size_in_bytes + mod / 1024.0 , magnitude_of_data [ index ] ) return s | Return human readable string represent of a file size . Doesn t support size greater than 1EB . |
55,799 | def render_toctrees ( kb_app : kb , sphinx_app : Sphinx , doctree : doctree , fromdocname : str ) : settings : KaybeeSettings = sphinx_app . config . kaybee_settings if not settings . articles . use_toctree : return builder : StandaloneHTMLBuilder = sphinx_app . builder env : BuildEnvironment = sphinx_app . env registered_toctree = ToctreeAction . get_for_context ( kb_app ) for node in doctree . traverse ( toctree ) : if node . attributes [ 'hidden' ] : continue custom_toctree = registered_toctree ( fromdocname ) context = builder . globalcontext . copy ( ) context [ 'sphinx_app' ] = sphinx_app entries = node . attributes [ 'entries' ] custom_toctree . set_entries ( entries , env . titles , sphinx_app . env . resources ) output = custom_toctree . render ( builder , context , sphinx_app ) listing = [ nodes . raw ( '' , output , format = 'html' ) ] node . replace_self ( listing ) | Look in doctrees for toctree and replace with custom render |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.