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_messa...
- 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...
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...
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 . state...
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 "{}...
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 ] = va...
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 Wind...
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' : sel...
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 =...
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 ( confi...
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 . remov...
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 ( modSymbo...
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 . a...
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 = dic...
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 . _label...
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' ...
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 , ...
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...
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 ...
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 ( ...
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 (...
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...
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 ...
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 ....
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_...
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 ( me...
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" ...
\ 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 . res...
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 ...
\ 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 (...
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...
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 ( destina...
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 '...
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 ) ) ) ignorech...
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 ...
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 ...
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 fil...
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" , "Sh...
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 = processOpen...
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...
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 . ...
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 ...
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 N...
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 . attr...
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 ( ...
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_b...
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...
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 =...
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...
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...
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 registe...
Look in doctrees for toctree and replace with custom render