signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
async def login ( self , request , id_ ) : """Login an user by ID ."""
session = await self . load ( request ) session [ 'id' ] = id_
def make_connection ( transport , ** kwargs ) : """Creates a connection instance based on the transport This function creates the EapiConnection object based on the desired transport . It looks up the transport class in the TRANSPORTS global dictionary . Args : transport ( string ) : The transport to use ...
if transport not in TRANSPORTS : raise TypeError ( 'invalid transport specified' ) klass = TRANSPORTS [ transport ] return klass ( ** kwargs )
def irrad_frac ( b , component , solve_for = None , ** kwargs ) : """Create a constraint to ensure that energy is conserved and all incident light is accounted for ."""
comp_ps = b . get_component ( component = component ) irrad_frac_refl_bol = comp_ps . get_parameter ( qualifier = 'irrad_frac_refl_bol' ) irrad_frac_lost_bol = comp_ps . get_parameter ( qualifier = 'irrad_frac_lost_bol' ) if solve_for in [ irrad_frac_lost_bol , None ] : lhs = irrad_frac_lost_bol rhs = 1.0 - irr...
def reset_exiter ( cls , exiter ) : """Class state : - Overwrites ` cls . _ exiter ` . Python state : - Overwrites sys . excepthook ."""
assert ( isinstance ( exiter , Exiter ) ) # NB : mutate the class variables ! This is done before mutating the exception hook , because the # uncaught exception handler uses cls . _ exiter to exit . cls . _exiter = exiter # NB : mutate process - global state ! sys . excepthook = cls . _log_unhandled_exception_and_exit
def apply_T6 ( word ) : '''If a VVV - sequence contains a long vowel , there is a syllable boundary between it and the third vowel , e . g . [ kor . ke . aa ] , [ yh . ti . öön ] , [ ruu . an ] , [ mää . yt . te ] .'''
T6 = '' WORD = word . split ( '.' ) for i , v in enumerate ( WORD ) : if contains_VVV ( v ) : VV = [ v . find ( j ) for j in LONG_VOWELS if v . find ( j ) > 0 ] if VV : I = VV [ 0 ] T6 = ' T6' if I + 2 == len ( v ) or is_vowel ( v [ I + 2 ] ) : WOR...
def list ( self ) : '''List all the databases on the given path . : return :'''
databases = [ ] for dbname in os . listdir ( self . path ) : databases . append ( dbname ) return list ( reversed ( sorted ( databases ) ) )
def _get_block_data ( self , mat , block ) : """Retrieve a block from a 3D or 4D volume Parameters mat : a 3D or 4D volume block : a tuple containing block information : - a triple containing the lowest - coordinate voxel in the block - a triple containing the size in voxels of the block Returns In th...
( pt , sz ) = block if len ( mat . shape ) == 3 : return mat [ pt [ 0 ] : pt [ 0 ] + sz [ 0 ] , pt [ 1 ] : pt [ 1 ] + sz [ 1 ] , pt [ 2 ] : pt [ 2 ] + sz [ 2 ] ] . copy ( ) elif len ( mat . shape ) == 4 : return mat [ pt [ 0 ] : pt [ 0 ] + sz [ 0 ] , pt [ 1 ] : pt [ 1 ] + sz [ 1 ] , pt [ 2 ] : pt [ 2 ] + sz [ 2...
def tarjan_recursive ( g ) : """Returns the strongly connected components of the graph @ g in a topological order . @ g is the graph represented as a dictionary { < vertex > : < successors of vertex > } . This function recurses - - - large graphs may cause a stack overflow ."""
S = [ ] S_set = set ( ) index = { } lowlink = { } ret = [ ] def visit ( v ) : index [ v ] = len ( index ) lowlink [ v ] = index [ v ] S . append ( v ) S_set . add ( v ) for w in g . get ( v , ( ) ) : if w not in index : visit ( w ) lowlink [ v ] = min ( lowlink [ w ] ...
def check_set ( set = None , family = 'ipv4' ) : '''Check that given ipset set exists . . . versionadded : : 2014.7.0 CLI Example : . . code - block : : bash salt ' * ' ipset . check _ set setname'''
if not set : return 'Error: Set needs to be specified' setinfo = _find_set_info ( set ) if not setinfo : return False return True
def rrtmg_lw_gen_source ( ext , build_dir ) : '''Add RRTMG _ LW fortran source if Fortran 90 compiler available , if no compiler is found do not try to build the extension .'''
thispath = config . local_path module_src = [ ] for item in modules : fullname = join ( thispath , 'rrtmg_lw_v4.85' , 'gcm_model' , 'modules' , item ) module_src . append ( fullname ) for item in src : if item in mod_src : fullname = join ( thispath , 'sourcemods' , item ) else : fullnam...
def _nac ( self , q_direction ) : """nac _ term = ( A1 ( x ) A2 ) / B * coef ."""
num_atom = self . _pcell . get_number_of_atoms ( ) nac_q = np . zeros ( ( num_atom , num_atom , 3 , 3 ) , dtype = 'double' ) if ( np . abs ( q_direction ) < 1e-5 ) . all ( ) : return nac_q rec_lat = np . linalg . inv ( self . _pcell . get_cell ( ) ) nac_factor = self . _dynmat . get_nac_factor ( ) Z = self . _dynma...
def poll_queue ( job_id , pid , poll_time ) : """Check the queue of executing / submitted jobs and exit when there is a free slot ."""
if config . distribution . serialize_jobs : first_time = True while True : jobs = logs . dbcmd ( GET_JOBS ) failed = [ job . id for job in jobs if not psutil . pid_exists ( job . pid ) ] if failed : logs . dbcmd ( "UPDATE job SET status='failed', is_running=0 " "WHERE id in (...
def _interpret_regexp ( self , string , flags ) : '''Perform sctring escape - for regexp literals'''
self . index = 0 self . length = len ( string ) self . source = string self . lineNumber = 0 self . lineStart = 0 octal = False st = '' inside_square = 0 while ( self . index < self . length ) : template = '[%s]' if not inside_square else '%s' ch = self . source [ self . index ] self . index += 1 if ch ...
def buildPrices ( data , roles = None , regex = default_price_regex , default = None , additional = { } ) : '''Create a dictionary with price information . Multiple ways are supported . : rtype : : obj : ` dict ` : keys are role as str , values are the prices as cent count'''
if isinstance ( data , dict ) : data = [ ( item [ 0 ] , convertPrice ( item [ 1 ] ) ) for item in data . items ( ) ] return dict ( [ v for v in data if v [ 1 ] is not None ] ) elif isinstance ( data , ( str , float , int ) ) and not isinstance ( data , bool ) : if default is None : raise ValueError ...
def forwards_func ( apps , schema_editor ) : """manage migrate backup _ app 0004 _ BackupRun _ ini _ file _ 20160203_1415"""
print ( "\n" ) create_count = 0 BackupRun = apps . get_model ( "backup_app" , "BackupRun" ) # historical version of BackupRun backup_runs = BackupRun . objects . all ( ) for backup_run in backup_runs : # Use the origin BackupRun model to get access to write _ config ( ) temp = OriginBackupRun ( name = backup_run . ...
def tables ( self ) : '''Yields table names .'''
with self . conn . cursor ( ) as cur : cur . execute ( self . TABLES_QUERY ) for row in cur : yield row
def arcte_with_lazy_pagerank ( adjacency_matrix , rho , epsilon , number_of_threads = None ) : """Extracts local community features for all graph nodes based on the partitioning of node - centric similarity vectors . Inputs : - A in R ^ ( nxn ) : Adjacency matrix of an undirected network represented as a SciPy Sp...
adjacency_matrix = sparse . csr_matrix ( adjacency_matrix ) number_of_nodes = adjacency_matrix . shape [ 0 ] if number_of_threads is None : number_of_threads = get_threads_number ( ) if number_of_threads == 1 : # Calculate natural random walk transition probability matrix . rw_transition , out_degree , in_degre...
def collect_fields ( self , runtime_type : GraphQLObjectType , selection_set : SelectionSetNode , fields : Dict [ str , List [ FieldNode ] ] , visited_fragment_names : Set [ str ] , ) -> Dict [ str , List [ FieldNode ] ] : """Collect fields . Given a selection _ set , adds all of the fields in that selection to t...
for selection in selection_set . selections : if isinstance ( selection , FieldNode ) : if not self . should_include_node ( selection ) : continue name = get_field_entry_key ( selection ) fields . setdefault ( name , [ ] ) . append ( selection ) elif isinstance ( selection , ...
def set_filters ( self , filters ) : """set and validate filters dict"""
if not isinstance ( filters , dict ) : raise Exception ( "filters must be a dict" ) self . filters = { } for key in filters . keys ( ) : value = filters [ key ] self . add_filter ( key , value )
def to_dict ( self ) : """Returns a dict of all of it ' s necessary components . Not the same as the _ _ dict _ _ method"""
data = dict ( ) data [ 'max_age' ] = self . max_age data [ 'cache_dir' ] = self . cache_dir return data
def session_path ( self , path = None ) : """Set and / or get current session path : param path : if defined , then set this value as a current session directory . If this value starts with a directory separator , then it is treated as an absolute path . In this case this value replaces a current one , otherwis...
if path is not None : if path . startswith ( self . directory_sep ( ) ) is True : self . __session_path = self . normalize_path ( path ) else : self . __session_path = self . join_path ( self . __session_path , path ) return self . __session_path
def print_plans ( self , plans ) : """Print method for plans ."""
for plan in plans : print ( 'Name: {} "{}" Price: {} USD' . format ( plan . name , plan . slug , plan . pricing [ 'hour' ] ) ) self . pprint ( plan . specs ) print ( '\n' )
def source_lines ( self , filename ) : """Return a list for source lines of file ` filename ` ."""
with self . filesystem . open ( filename ) as f : return f . readlines ( )
def set_iomem ( self , iomem ) : """Set I / O memory size for this router . : param iomem : I / O memory size"""
yield from self . _hypervisor . send ( 'c3600 set_iomem "{name}" {size}' . format ( name = self . _name , size = iomem ) ) log . info ( 'Router "{name}" [{id}]: I/O memory updated from {old_iomem}% to {new_iomem}%' . format ( name = self . _name , id = self . _id , old_iomem = self . _iomem , new_iomem = iomem ) ) self...
def document_created_message ( self , request , document ) : """Send messages . success message after successful document creation ."""
messages . success ( request , _ ( "Document {} was created" . format ( document ) ) )
def cli ( env , volume_id ) : """Lists snapshot schedules for a given volume"""
file_manager = SoftLayer . FileStorageManager ( env . client ) snapshot_schedules = file_manager . list_volume_schedules ( volume_id ) table = formatting . Table ( [ 'id' , 'active' , 'type' , 'replication' , 'date_created' , 'minute' , 'hour' , 'day' , 'week' , 'day_of_week' , 'date_of_month' , 'month_of_year' , 'maxi...
def requireCompatibleAPI ( ) : """If PyQt4 ' s API should be configured to be compatible with PySide ' s ( i . e . QString and QVariant should not be explicitly exported , cf . documentation of sip . setapi ( ) ) , call this function to check that the PyQt4 was properly imported . ( It will always be configur...
if 'PyQt4.QtCore' in sys . modules : import sip for api in ( 'QVariant' , 'QString' ) : if sip . getapi ( api ) != 2 : raise RuntimeError ( '%s API already set to V%d, but should be 2' % ( api , sip . getapi ( api ) ) )
def swd_read8 ( self , offset ) : """Gets a unit of ` ` 8 ` ` bits from the input buffer . Args : self ( JLink ) : the ` ` JLink ` ` instance offset ( int ) : the offset ( in bits ) from which to start reading Returns : The integer read from the input buffer ."""
value = self . _dll . JLINK_SWD_GetU8 ( offset ) return ctypes . c_uint8 ( value ) . value
def group_by_witness ( self ) : """Groups results by witness , providing a single summary field giving the n - grams found in it , a count of their number , and the count of their combined occurrences ."""
if self . _matches . empty : # Ensure that the right columns are used , even though the # results are empty . self . _matches = pd . DataFrame ( { } , columns = [ constants . WORK_FIELDNAME , constants . SIGLUM_FIELDNAME , constants . LABEL_FIELDNAME , constants . NGRAMS_FIELDNAME , constants . NUMBER_FIELDNAME , c...
def run ( ) : """CLI endpoint ."""
sys . path . insert ( 0 , os . getcwd ( ) ) logging . basicConfig ( level = logging . INFO , handlers = [ logging . StreamHandler ( ) ] ) parser = argparse . ArgumentParser ( description = "Manage Application" , add_help = False ) parser . add_argument ( 'app' , metavar = 'app' , type = str , help = 'Application module...
def bash ( filename ) : """Runs a bash script in the local directory"""
sys . stdout . flush ( ) subprocess . call ( "bash {}" . format ( filename ) , shell = True )
def get_next_step ( self ) : """Find the proper step when user clicks the Next button . : returns : The step to be switched to . : rtype : WizardStep instance or None"""
if self . layer_purpose != layer_purpose_aggregation : subcategory = self . parent . step_kw_subcategory . selected_subcategory ( ) else : subcategory = { 'key' : None } if is_raster_layer ( self . parent . layer ) : return self . parent . step_kw_source # Check if it can go to inasafe field step inasafe_fi...
def _do_report ( self , report , in_port , msg ) : """the process when the querier received a REPORT message ."""
datapath = msg . datapath ofproto = datapath . ofproto parser = datapath . ofproto_parser if ofproto . OFP_VERSION == ofproto_v1_0 . OFP_VERSION : size = 65535 else : size = ofproto . OFPCML_MAX update = False self . _mcast . setdefault ( report . address , { } ) if in_port not in self . _mcast [ report . addre...
def old_projection ( model , data , theta = None , chain = None , n = 100 , extents = None , uncertainties = True , title = None , fig = None , figsize = None ) : """Project the maximum likelihood values and sampled posterior points as spectra . : param model : The model employed . : type model : : class ...
if not isinstance ( data , ( tuple , list ) ) or any ( [ not isinstance ( each , specutils . Spectrum1D ) for each in data ] ) : raise TypeError ( "Data must be a list-type of Spectrum1D objects." ) K = len ( data ) factor = 2.0 lbdim = 0.5 * factor trdim = 0.2 * factor whspace = 0.10 width = np . max ( [ len ( eac...
def _prune ( self , filename : str , df : pd . DataFrame ) -> pd . DataFrame : """Depth - first search through the dependency graph and prune dependent DataFrames along the way ."""
dependencies = [ ] for _ , depf , data in self . _config . out_edges ( filename , data = True ) : deps = data . get ( "dependencies" ) if deps is None : msg = f"Edge missing `dependencies` attribute: {filename}->{depf}" raise ValueError ( msg ) dependencies . append ( ( depf , deps ) ) if no...
def define ( self , value , lineno , namespace = None ) : """Defines label value . It can be anything . Even an AST"""
if self . defined : error ( lineno , "label '%s' already defined at line %i" % ( self . name , self . lineno ) ) self . value = value self . lineno = lineno self . namespace = NAMESPACE if namespace is None else namespace
def replace ( self , ** kwargs ) : """Returns a new Delorean object after applying replace on the existing datetime object . . . testsetup : : from datetime import datetime from delorean import Delorean . . doctest : : > > > d = Delorean ( datetime ( 2015 , 1 , 1 , 12 , 15 ) , timezone = ' UTC ' ) > >...
return Delorean ( datetime = self . _dt . replace ( ** kwargs ) , timezone = self . timezone )
def get_asset_contents_by_record_type ( self , asset_content_record_type ) : """Gets an ` ` AssetContentList ` ` containing the given asset record ` ` Type ` ` . In plenary mode , the returned list contains all known asset contents or an error results . Otherwise , the returned list may contain only those ass...
return AssetContentList ( self . _provider_session . get_asset_contents_by_record_type ( asset_content_record_type ) , self . _config_map )
def complete_io ( self , iocb , msg ) : """Called by a handler to return data to the client ."""
if _debug : IOController . _debug ( "complete_io %r %r" , iocb , msg ) # if it completed , leave it alone if iocb . ioState == COMPLETED : pass # if it already aborted , leave it alone elif iocb . ioState == ABORTED : pass else : # change the state iocb . ioState = COMPLETED iocb . ioResponse = msg ...
def setError ( self , msg = None , title = None ) : """Shows and error message"""
if msg is not None : self . messageLabel . setText ( msg ) if title is not None : self . titleLabel . setText ( title )
def status_is ( weather , status , weather_code_registry ) : """Checks if the weather status code of a * Weather * object corresponds to the detailed status indicated . The lookup is performed against the provided * WeatherCodeRegistry * object . : param weather : the * Weather * object whose status code is t...
weather_status = weather_code_registry . status_for ( weather . get_weather_code ( ) ) . lower ( ) return weather_status == status
def send_message ( self , target , content , uid = None ) : """Sends a message through IRC"""
# Compute maximum length of payload prefix = "PRIVMSG {0} :" . format ( target ) single_prefix = self . _make_line ( "MSG:" ) single_prefix_len = len ( single_prefix ) max_len = 510 - len ( prefix ) content_len = len ( content ) if ( content_len + single_prefix_len ) < max_len : # One pass message self . _connectio...
def console_print_rect ( con : tcod . console . Console , x : int , y : int , w : int , h : int , fmt : str ) -> int : """Print a string constrained to a rectangle . If h > 0 and the bottom of the rectangle is reached , the string is truncated . If h = 0, the string is only truncated if it reaches the bottom ...
return int ( lib . TCOD_console_printf_rect ( _console ( con ) , x , y , w , h , _fmt ( fmt ) ) )
def run_vcfanno ( vcf_file , data , decomposed = False ) : """Run vcfanno , providing annotations from external databases if needed . Puts together lua and conf files from multiple inputs by file names ."""
conf_files = dd . get_vcfanno ( data ) if conf_files : with_basepaths = collections . defaultdict ( list ) gemini_basepath = _back_compatible_gemini ( conf_files , data ) for f in conf_files : name = os . path . splitext ( os . path . basename ( f ) ) [ 0 ] if f . endswith ( ".lua" ) : ...
def search_online ( word , printer = True ) : '''search the word or phrase on http : / / dict . youdao . com .'''
url = 'http://dict.youdao.com/w/ %s' % word expl = get_text ( url ) if printer : colorful_print ( expl ) return expl
def address ( self , compressed = True , testnet = False ) : """Address property that returns the Base58Check encoded version of the HASH160. Args : compressed ( bool ) : Whether or not the compressed key should be used . testnet ( bool ) : Whether or not the key is intended for testnet usage . False in...
version = '0x' return version + binascii . hexlify ( self . keccak [ 12 : ] ) . decode ( 'ascii' )
def backup_mediafiles ( self ) : """Create backup file and write it to storage ."""
# Create file name extension = "tar%s" % ( '.gz' if self . compress else '' ) filename = utils . filename_generate ( extension , servername = self . servername , content_type = self . content_type ) tarball = self . _create_tar ( filename ) # Apply trans if self . encrypt : encrypted_file = utils . encrypt_file ( t...
def rbac_policy_create ( request , ** kwargs ) : """Create a RBAC Policy . : param request : request context : param target _ tenant : target tenant of the policy : param tenant _ id : owner tenant of the policy ( Not recommended ) : param object _ type : network or qos _ policy : param object _ id : obje...
body = { 'rbac_policy' : kwargs } rbac_policy = neutronclient ( request ) . create_rbac_policy ( body = body ) . get ( 'rbac_policy' ) return RBACPolicy ( rbac_policy )
def from_pb ( cls , policy_pb ) : """Factory : create a policy from a protobuf message . Args : policy _ pb ( google . iam . policy _ pb2 . Policy ) : message returned by ` ` get _ iam _ policy ` ` gRPC API . Returns : : class : ` Policy ` : the parsed policy"""
policy = cls ( policy_pb . etag , policy_pb . version ) for binding in policy_pb . bindings : policy [ binding . role ] = sorted ( binding . members ) return policy
def _check_update_ ( self ) : """Check if the current version of the library is outdated ."""
try : data = requests . get ( "https://pypi.python.org/pypi/jira/json" , timeout = 2.001 ) . json ( ) released_version = data [ 'info' ] [ 'version' ] if parse_version ( released_version ) > parse_version ( __version__ ) : warnings . warn ( "You are running an outdated version of JIRA Python %s. Cur...
def get_regions ( self ) : """GetRegions . [ Preview API ] : rtype : : class : ` < ProfileRegions > < azure . devops . v5_1 . profile - regions . models . ProfileRegions > `"""
response = self . _send ( http_method = 'GET' , location_id = 'b129ca90-999d-47bb-ab37-0dcf784ee633' , version = '5.1-preview.1' ) return self . _deserialize ( 'ProfileRegions' , response )
def build_vocab ( data : Iterable [ str ] , num_words : Optional [ int ] = None , min_count : int = 1 , pad_to_multiple_of : Optional [ int ] = None ) -> Vocab : """Creates a vocabulary mapping from words to ids . Increasing integer ids are assigned by word frequency , using lexical sorting as a tie breaker . The...
vocab_symbols_set = set ( C . VOCAB_SYMBOLS ) raw_vocab = Counter ( token for line in data for token in utils . get_tokens ( line ) if token not in vocab_symbols_set ) # For words with the same count , they will be ordered reverse alphabetically . # Not an issue since we only care for consistency pruned_vocab = [ w for...
def from_bundle ( cls , b , feature ) : """Initialize a Pulsation feature from the bundle ."""
feature_ps = b . get_feature ( feature ) freq = feature_ps . get_value ( 'freq' , unit = u . d ** - 1 ) radamp = feature_ps . get_value ( 'radamp' , unit = u . dimensionless_unscaled ) l = feature_ps . get_value ( 'l' , unit = u . dimensionless_unscaled ) m = feature_ps . get_value ( 'm' , unit = u . dimensionless_unsc...
def create_service ( self , * args , ** kwargs ) : """Create a service to current scope . See : class : ` pykechain . Client . create _ service ` for available parameters . . . versionadded : : 1.13"""
return self . _client . create_service ( * args , scope = self . id , ** kwargs )
def displayEmptyInputWarningBox ( display = True , parent = None ) : """Displays a warning box for the ' input ' parameter ."""
if sys . version_info [ 0 ] >= 3 : from tkinter . messagebox import showwarning else : from tkMessageBox import showwarning if display : msg = 'No valid input files found! ' + 'Please check the value for the "input" parameter.' showwarning ( parent = parent , message = msg , title = "No valid inputs!" )...
def get_rank_based_enrichment ( self , ranked_genes : List [ str ] , pval_thresh : float = 0.05 , X_frac : float = 0.25 , X_min : int = 5 , L : int = None , adjust_pval_thresh : bool = True , escore_pval_thresh : float = None , exact_pval : str = 'always' , gene_set_ids : List [ str ] = None , table : np . ndarray = No...
# make sure X _ frac is a float ( e . g . , if specified as 0) X_frac = float ( X_frac ) if table is not None : if not np . issubdtype ( table . dtype , np . longdouble ) : raise TypeError ( 'The provided array for storing the dynamic ' 'programming table must be of type ' '"longdouble"!' ) if L is None : ...
def threads_init ( gtk = True ) : """Enables multithreading support in Xlib and PyGTK . See the module docstring for more info . : Parameters : gtk : bool May be set to False to skip the PyGTK module ."""
# enable X11 multithreading x11 . XInitThreads ( ) if gtk : from gtk . gdk import threads_init threads_init ( )
def update_hacluster_vip ( service , relation_data ) : """Configure VIP resources based on provided configuration @ param service : Name of the service being configured @ param relation _ data : Pointer to dictionary of relation data ."""
cluster_config = get_hacluster_config ( ) vip_group = [ ] vips_to_delete = [ ] for vip in cluster_config [ 'vip' ] . split ( ) : if is_ipv6 ( vip ) : res_vip = 'ocf:heartbeat:IPv6addr' vip_params = 'ipv6addr' else : res_vip = 'ocf:heartbeat:IPaddr2' vip_params = 'ip' iface , ...
def del_edge ( self , e ) : '''API : del _ edge ( self , e ) Description : Removes edge from graph . Input : e : Tuple that represents edge , in ( source , sink ) form . Pre : Graph should contain this edge . Post : self . edge _ attr , self . neighbors and self . in _ neighbors are updated .'''
if self . graph_type is DIRECTED_GRAPH : try : del self . edge_attr [ e ] except KeyError : raise Exception ( 'Edge %s does not exists!' % str ( e ) ) self . neighbors [ e [ 0 ] ] . remove ( e [ 1 ] ) self . in_neighbors [ e [ 1 ] ] . remove ( e [ 0 ] ) else : try : del self ...
def primes ( n ) : """Simple test function Taken from http : / / www . huyng . com / posts / python - performance - analysis /"""
if n == 2 : return [ 2 ] elif n < 2 : return [ ] s = list ( range ( 3 , n + 1 , 2 ) ) mroot = n ** 0.5 half = ( n + 1 ) // 2 - 1 i = 0 m = 3 while m <= mroot : if s [ i ] : j = ( m * m - 3 ) // 2 s [ j ] = 0 while j < half : s [ j ] = 0 j += m i = i + 1 ...
def SearchFetchable ( session = None , ** kwargs ) : """Search okcupid . com with the given parameters . Parameters are registered to this function through : meth : ` ~ okcupyd . filter . Filters . register _ filter _ builder ` of : data : ` ~ okcupyd . html _ search . search _ filters ` . : returns : A : cla...
session = session or Session . login ( ) return util . Fetchable . fetch_marshall ( SearchHTMLFetcher ( session , ** kwargs ) , util . SimpleProcessor ( session , lambda match_card_div : Profile ( session = session , ** MatchCardExtractor ( match_card_div ) . as_dict ) , _match_card_xpb ) )
async def dispense ( self , mount : top_types . Mount , volume : float = None , rate : float = 1.0 ) : """Dispense a volume of liquid in microliters ( uL ) using this pipette at the current location . If no volume is specified , ` dispense ` will dispense all volume currently present in pipette mount : Mount ...
this_pipette = self . _attached_instruments [ mount ] if not this_pipette : raise top_types . PipetteNotAttachedError ( "No pipette attached to {} mount" . format ( mount . name ) ) if volume is None : disp_vol = this_pipette . current_volume mod_log . debug ( "No dispense volume specified. Dispensing all "...
def explore_json ( self , datasource_type = None , datasource_id = None ) : """Serves all request that GET or POST form _ data This endpoint evolved to be the entry point of many different requests that GETs or POSTs a form _ data . ` self . generate _ json ` receives this input and returns different payloa...
csv = request . args . get ( 'csv' ) == 'true' query = request . args . get ( 'query' ) == 'true' results = request . args . get ( 'results' ) == 'true' samples = request . args . get ( 'samples' ) == 'true' force = request . args . get ( 'force' ) == 'true' form_data = get_form_data ( ) [ 0 ] datasource_id , datasourc...
def pic_totalremotedischarge_v1 ( self ) : """Update the receiver link sequence ."""
flu = self . sequences . fluxes . fastaccess rec = self . sequences . receivers . fastaccess flu . totalremotedischarge = rec . q [ 0 ]
def QA_SU_save_stock_xdxr ( engine , client = DATABASE ) : """save stock _ xdxr Arguments : engine { [ type ] } - - [ description ] Keyword Arguments : client { [ type ] } - - [ description ] ( default : { DATABASE } )"""
engine = select_save_engine ( engine ) engine . QA_SU_save_stock_xdxr ( client = client )
def scale_down_dynos ( self ) : """Turn off web and worker dynos , plus clock process if there is one and it ' s active ."""
processes = [ "web" , "worker" ] if self . clock_is_on : processes . append ( "clock" ) for process in processes : self . scale_down_dyno ( process )
def focusOutEvent ( self , ev ) : """Redefine focusOut events to stop editing"""
Kittens . widgets . ClickableTreeWidget . focusOutEvent ( self , ev ) # if focus is going to a child of ours , do nothing wid = QApplication . focusWidget ( ) while wid : if wid is self : return wid = wid . parent ( ) # else we ' re truly losing focus - - stop the editor self . _startOrStopEditing ( )
def prompt_for_config ( context , no_input = False ) : """Prompts the user to enter new config , using context as a source for the field names and sample values . : param no _ input : Prompt the user at command line for manual configuration ?"""
cookiecutter_dict = OrderedDict ( [ ] ) env = StrictEnvironment ( context = context ) # First pass : Handle simple and raw variables , plus choices . # These must be done first because the dictionaries keys and # values might refer to them . for key , raw in iteritems ( context [ u'cookiecutter' ] ) : if key . star...
def make_query ( catalog ) : """A function to prepare a query"""
query = { } request = api . get_request ( ) index = get_search_index_for ( catalog ) limit = request . form . get ( "limit" ) q = request . form . get ( "q" ) if len ( q ) > 0 : query [ index ] = q + "*" else : return None portal_type = request . form . get ( "portal_type" ) if portal_type : if not isinstan...
def notify_owner ( func ) : '''A decorator for mutating methods of property container classes that notifies owners of the property container about mutating changes . Args : func ( callable ) : the container method to wrap in a notification Returns : wrapped method Examples : A ` ` _ _ setitem _ _ ` ` ...
def wrapper ( self , * args , ** kwargs ) : old = self . _saved_copy ( ) result = func ( self , * args , ** kwargs ) self . _notify_owners ( old ) return result wrapper . __doc__ = "Container method ``%s`` instrumented to notify property owners" % func . __name__ return wrapper
def unq_argument ( self ) -> str : """Parse unquoted argument . Raises : EndOfInput : If past the end of input ."""
start = self . offset self . dfa ( [ { # state 0 : argument "" : lambda : 0 , ";" : lambda : - 1 , " " : lambda : - 1 , "\t" : lambda : - 1 , "\r" : lambda : - 1 , "\n" : lambda : - 1 , "{" : lambda : - 1 , '/' : lambda : 1 } , { # state 1 : comment ? "" : lambda : 0 , "/" : self . _back_break , "*" : self . _back_brea...
def running_state ( self , running_state ) : """Sets the running _ state of this MaintenanceWindow . : param running _ state : The running _ state of this MaintenanceWindow . # noqa : E501 : type : str"""
allowed_values = [ "ONGOING" , "PENDING" , "ENDED" ] # noqa : E501 if running_state not in allowed_values : raise ValueError ( "Invalid value for `running_state` ({0}), must be one of {1}" # noqa : E501 . format ( running_state , allowed_values ) ) self . _running_state = running_state
def base_uri ( self ) : """Resolution base for JSON schema . Also used as the default graph ID for RDF ."""
if self . _base_uri is None : if self . _resolver is not None : self . _base_uri = self . resolver . resolution_scope else : self . _base_uri = 'http://pudo.github.io/jsongraph' return URIRef ( self . _base_uri )
def clear ( self , fg , attr , bg ) : """Clear the double - buffer . This does not clear the screen buffer and so the next call to deltas will still show all changes . : param fg : The foreground colour to use for the new buffer . : param attr : The attribute value to use for the new buffer . : param bg : T...
line = [ ( ord ( u" " ) , fg , attr , bg , 1 ) for _ in range ( self . _width ) ] self . _double_buffer = [ line [ : ] for _ in range ( self . _height ) ]
def log_path ( self , new_path ) : """Setter for ` log _ path ` , use with caution ."""
if self . has_active_service : raise DeviceError ( self , 'Cannot change `log_path` when there is service running.' ) old_path = self . _log_path if new_path == old_path : return if os . listdir ( new_path ) : raise DeviceError ( self , 'Logs already exist at %s, cannot override.' % new_path ) if os . path ...
def Delete ( self ) : """Delete disk . This request will error if disk is protected and cannot be removed ( e . g . a system disk ) > > > clc . v2 . Server ( " WA1BTDIX01 " ) . Disks ( ) . disks [ 2 ] . Delete ( ) . WaitUntilComplete ( )"""
disk_set = [ { 'diskId' : o . id , 'sizeGB' : o . size } for o in self . parent . disks if o != self ] self . parent . disks = [ o for o in self . parent . disks if o != self ] self . parent . server . dirty = True return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . parent . serv...
def _get_headers ( self ) : """assumes comment have been stripped with extract : return :"""
header = self . lines [ 0 ] self . lines = self . lines [ 1 : ] self . headers = [ self . clean ( h ) for h in header . split ( self . seperator ) ] if self . is_strip : self . headers = self . headers [ 1 : - 1 ] return self . headers
def hash_from_stream ( n , hash_stream ) : """Not standard hashing algorithm ! Install NumPy for better hashing service . > > > from Redy . Tools . _ py _ hash import hash _ from _ stream > > > s = iter ( ( 1 , 2 , 3 ) ) > > > assert hash _ from _ stream ( 3 , map ( hash , s ) ) = = hash ( ( 1 , 2 , 3 ) )""...
_to_int64 = to_int64 x = 0x345678 multiplied = _to_int64 ( 1000003 ) for n in range ( n - 1 , - 1 , - 1 ) : h = next ( hash_stream ) x = _to_int64 ( ( x ^ h ) * multiplied ) multiplied += _to_int64 ( 82520 + _to_int64 ( 2 * n ) ) multiplied = _to_int64 ( multiplied ) x += 97531 x = _to_int64 ( x ) if x ...
def get_cmd_output_now ( self , exe , suggest_filename = None , root_symlink = False , timeout = 300 , stderr = True , chroot = True , runat = None , env = None , binary = False , sizelimit = None , pred = None ) : """Execute a command and save the output to a file for inclusion in the report ."""
if not self . test_predicate ( cmd = True , pred = pred ) : self . _log_info ( "skipped cmd output '%s' due to predicate (%s)" % ( exe , self . get_predicate ( cmd = True , pred = pred ) ) ) return None return self . _get_cmd_output_now ( exe , timeout = timeout , stderr = stderr , chroot = chroot , runat = run...
def get_file_info ( obj , fieldname , default = None ) : """Extract file data from a file field : param obj : Content object : type obj : ATContentType / DexterityContentType : param fieldname : Schema name of the field : type fieldname : str / unicode : returns : File data mapping : rtype : dict"""
# extract the file field from the object if omitted field = get_field ( obj , fieldname ) # get the value with the fieldmanager fm = IFieldManager ( field ) # return None if we have no file data if fm . get_size ( obj ) == 0 : return None out = { "content_type" : fm . get_content_type ( obj ) , "filename" : fm . ge...
def stop_transmit ( self , * ports ) : """Stop traffic on ports . : param ports : list of ports to stop traffic on , if empty start on all ports ."""
port_list = self . set_ports_list ( * ports ) self . api . call_rc ( 'ixStopTransmit {}' . format ( port_list ) ) time . sleep ( 0.2 )
def insertRows ( self , position , rows , parent = QtCore . QModelIndex ( ) ) : """Inserts new parameters and emits an emptied False signal : param position : row location to insert new parameter : type position : int : param rows : number of new parameters to insert : type rows : int : param parent : Req...
self . beginInsertRows ( parent , position , position + rows - 1 ) for i in range ( rows ) : self . model . insertRow ( position ) # self . _ selectionmap [ self . _ paramid ] . hintRequested . connect ( self . hintRequested ) self . endInsertRows ( ) if self . rowCount ( ) == 1 : self . emptied . emit ( Fa...
def maxlike ( self , nseeds = 50 ) : """Returns the best - fit parameters , choosing the best of multiple starting guesses : param nseeds : ( optional ) Number of starting guesses , uniformly distributed throughout allowed ranges . Default = 50. : return : list of best - fit parameters : ` ` [ mA , mB , a...
mA_0 , age0 , feh0 = self . ic . random_points ( nseeds ) mB_0 , foo1 , foo2 = self . ic . random_points ( nseeds ) mA_fixed = np . maximum ( mA_0 , mB_0 ) mB_fixed = np . minimum ( mA_0 , mB_0 ) mA_0 , mB_0 = ( mA_fixed , mB_fixed ) d0 = 10 ** ( rand . uniform ( 0 , np . log10 ( self . max_distance ) , size = nseeds )...
def document_geom ( geom ) : """Create a structured documentation for the geom It replaces ` { usage } ` , ` { common _ parameters } ` and ` { aesthetics } ` with generated documentation ."""
# Dedented so that it lineups ( in sphinx ) with the part # generated parts when put together docstring = dedent ( geom . __doc__ ) # usage signature = make_signature ( geom . __name__ , geom . DEFAULT_PARAMS , common_geom_params , common_geom_param_values ) usage = GEOM_SIGNATURE_TPL . format ( signature = signature )...
def initialize_indices ( self , ** kwargs ) : """creates all the indicies that are defined in the rdf definitions kwargs : action : which action is to be perfomed initialize : ( default ) tests to see if the index exisits if not creates it reset : deletes all of the indexes and recreate them update : st...
action = kwargs . get ( 'action' , 'initialize' ) if action == 'update' : kwargs [ 'reset_idx' ] = False elif action == 'reset' : kwargs [ 'reset_idx' ] = True idx_list = self . list_indexes ( ) for idx , values in idx_list . items ( ) : if ( action == 'initialize' and not self . es . indices . exists ( idx...
def download ( ctx ) : """Download data ."""
log . debug ( 'chemdataextractor.data.download' ) count = 0 for package in PACKAGES : success = package . download ( ) if success : count += 1 click . echo ( 'Successfully downloaded %s new data packages (%s existing)' % ( count , len ( PACKAGES ) - count ) )
def remove ( self ) : """remove this object from Ariane server : return : null if successfully removed else self"""
LOGGER . debug ( "Cluster.remove - " + self . name ) if self . id is None : return None else : params = SessionService . complete_transactional_req ( { 'name' : self . name } ) if MappingService . driver_type != DriverFactory . DRIVER_REST : params [ 'OPERATION' ] = 'deleteCluster' args = { ...
def download_blood_vessels ( ) : """data representing the bifurcation of blood vessels ."""
local_path , _ = _download_file ( 'pvtu_blood_vessels/blood_vessels.zip' ) filename = os . path . join ( local_path , 'T0000000500.pvtu' ) mesh = vtki . read ( filename ) mesh . set_active_vectors ( 'velocity' ) return mesh
def _write_header ( data , fp , relation_name , index ) : """Write header containing attribute names and types"""
fp . write ( "@relation {0}\n\n" . format ( relation_name ) ) if index : data = data . reset_index ( ) attribute_names = _sanitize_column_names ( data ) for column , series in data . iteritems ( ) : name = attribute_names [ column ] fp . write ( "@attribute {0}\t" . format ( name ) ) if is_categorical_d...
def remove ( self , parent ) : '''remove ROI'''
parent . p0 . removeItem ( self . ROIplot ) parent . p0 . removeItem ( self . dotplot )
def makeTrp ( segID , N , CA , C , O , geo ) : '''Creates a Tryptophan residue'''
# # R - Group CA_CB_length = geo . CA_CB_length C_CA_CB_angle = geo . C_CA_CB_angle N_C_CA_CB_diangle = geo . N_C_CA_CB_diangle CB_CG_length = geo . CB_CG_length CA_CB_CG_angle = geo . CA_CB_CG_angle N_CA_CB_CG_diangle = geo . N_CA_CB_CG_diangle CG_CD1_length = geo . CG_CD1_length CB_CG_CD1_angle = geo . CB_CG_CD1_angl...
def symlink_exists ( self , symlink ) : """Checks whether a symbolic link exists in the guest . in symlink of type str Path to the alleged symbolic link . Guest path style . return exists of type bool Returns @ c true if the symbolic link exists . Returns @ c false if it does not exist , if the file syste...
if not isinstance ( symlink , basestring ) : raise TypeError ( "symlink can only be an instance of type basestring" ) exists = self . _call ( "symlinkExists" , in_p = [ symlink ] ) return exists
def _set_function_node_output ( self , node_id , node_attr , no_call , next_nds = None , ** kw ) : """Set the function node output from node inputs . : param node _ id : Function node id . : type node _ id : str : param node _ attr : Dictionary of node attributes . : type node _ attr : dict [ str , T ] ...
# Namespace shortcuts for speed . o_nds , dist = node_attr [ 'outputs' ] , self . dist # List of nodes that can still be estimated by the function node . output_nodes = next_nds or set ( self . _succ [ node_id ] ) . difference ( dist ) if not output_nodes : # This function is not needed . self . workflow . remove_n...
def is_stopword_record ( self , record ) : """Determine whether a single MeCab record represents a stopword . This mostly determines words to strip based on their parts of speech . If common _ words is set to True ( default ) , it will also strip common verbs and nouns such as くる and よう . If more _ stopwords ...
# preserve negations if record . root == 'ない' : return False return ( record . pos in STOPWORD_CATEGORIES or record . subclass1 in STOPWORD_CATEGORIES or record . root in STOPWORD_ROOTS )
def unwrap ( self , value , fields = None , session = None ) : '''If ` ` autoload ` ` is False , return a DBRef object . Otherwise load the object .'''
self . validate_unwrap ( value ) value . type = self . type return value
def get_color ( value , alpha ) : """Return color depending on value type"""
color = QColor ( ) for typ in COLORS : if isinstance ( value , typ ) : color = QColor ( COLORS [ typ ] ) color . setAlphaF ( alpha ) return color
def save_user_cmd ( email , name = None , groups = None , locale = 'en_US' , timezone = 'US/Eastern' ) : """Command to save a user : param email : user email : param name : user name : param groups : user permission groups : return : A command that validate date and save the user"""
if name is None : name = email if groups is None : groups = [ ] return SaveUserCmd ( name = name , email = email , groups = groups , locale = locale , timezone = timezone )
def nx_dag_node_rank ( graph , nodes = None ) : """Returns rank of nodes that define the " level " each node is on in a topological sort . This is the same as the Graphviz dot rank . Ignore : simple _ graph = ut . simplify _ graph ( exi _ graph ) adj _ dict = ut . nx _ to _ adj _ dict ( simple _ graph ) i...
import utool as ut source = list ( ut . nx_source_nodes ( graph ) ) [ 0 ] longest_paths = dict ( [ ( target , dag_longest_path ( graph , source , target ) ) for target in graph . nodes ( ) ] ) node_to_rank = ut . map_dict_vals ( len , longest_paths ) if nodes is None : return node_to_rank else : ranks = ut . di...
def get_login_url ( self , state = None ) : """Generates and returns URL for redirecting to Login Page of RunKeeper , which is the Authorization Endpoint of Health Graph API . @ param state : State string . Passed to client web application at the end of the Login Process . @ return : URL for redirecting to ...
payload = { 'response_type' : 'code' , 'client_id' : self . _client_id , 'redirect_uri' : self . _redirect_uri , } if state is not None : payload [ 'state' ] = state return "%s?%s" % ( settings . API_AUTHORIZATION_URL , urllib . urlencode ( payload ) )
def ExecuteStoredProcedure ( self , sproc_link , params , options = None ) : """Executes a store procedure . : param str sproc _ link : The link to the stored procedure . : param dict params : List or None : param dict options : The request options for the request . : return : The Stored Procedure r...
if options is None : options = { } initial_headers = dict ( self . default_headers ) initial_headers . update ( { http_constants . HttpHeaders . Accept : ( runtime_constants . MediaTypes . Json ) } ) if params and not type ( params ) is list : params = [ params ] path = base . GetPathFromLink ( sproc_link ) spr...