signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _handle_response ( self , response ) : """Internal helper for handling API responses from the Binance server . Raises the appropriate exceptions when necessary ; otherwise , returns the response ."""
if not str ( response . status_code ) . startswith ( '2' ) : raise BinanceAPIException ( response ) try : return response . json ( ) except ValueError : raise BinanceRequestException ( 'Invalid Response: %s' % response . text )
def decorate_method ( cls , func ) : """: param func : func to be decorated : return : func that is now decorated"""
func_args = [ arg for arg in function_arguments ( func ) if arg != 'self' ] method_return_types = Endpoint . _parse_function_return_types_from_doc ( func . __doc__ ) name = '%s.%s' % ( cls . path , func . __name__ ) @ wraps ( func ) def method_decorator ( self , * args , ** kwargs ) : for i in range ( len ( args ) ...
def workflow_start ( obj , queue , keep_data , name , workflow_args ) : """Send a workflow to the queue . NAME : The name of the workflow that should be started . WORKFLOW _ ARGS : Workflow arguments in the form key1 = value1 key2 = value2."""
try : start_workflow ( name = name , config = obj [ 'config' ] , queue = queue , clear_data_store = not keep_data , store_args = dict ( [ arg . split ( '=' , maxsplit = 1 ) for arg in workflow_args ] ) ) except ( WorkflowArgumentError , WorkflowImportError ) as e : click . echo ( _style ( obj [ 'show_color' ] ,...
def check ( cls ) : """Class method to check every settings . Will raise an ` ` ImproperlyConfigured ` ` exception with explanation ."""
if cls == AppSettings : return None exceptions = [ ] for setting in cls . settings . values ( ) : try : setting . check ( ) # pylama : ignore = W0703 except Exception as e : exceptions . append ( str ( e ) ) if exceptions : raise ImproperlyConfigured ( "\n" . join ( exceptions ) )
def setMaximum ( self , maximum ) : """setter to _ maximum . Args : maximum ( int or long ) : new _ maximum value"""
if not isinstance ( maximum , int ) : raise TypeError ( "Argument is not of type int or long" ) self . _maximum = maximum
def _process_backlogged_hosting_devices ( self , context ) : """Process currently backlogged devices . Go through the currently backlogged devices and process them . For devices which are now reachable ( compared to last time ) , we call ` process _ services ( ) ` passing the now reachable device ' s id . F...
driver_mgr = self . get_routing_service_helper ( ) . driver_manager res = self . _dev_status . check_backlogged_hosting_devices ( driver_mgr ) if res [ 'reachable' ] : self . process_services ( device_ids = res [ 'reachable' ] ) if res [ 'revived' ] : LOG . debug ( "Reporting revived hosting devices: %s " % res...
def get_on_tmdb ( uri , ** kwargs ) : """Get a resource on TMDB ."""
kwargs [ 'api_key' ] = app . config [ 'TMDB_API_KEY' ] response = requests_session . get ( ( TMDB_API_URL + uri ) . encode ( 'utf8' ) , params = kwargs ) response . raise_for_status ( ) return json . loads ( response . text )
def update_trackers ( self ) : """Updates the denormalized trackers associated with the forum instance ."""
direct_approved_topics = self . topics . filter ( approved = True ) . order_by ( '-last_post_on' ) # Compute the direct topics count and the direct posts count . self . direct_topics_count = direct_approved_topics . count ( ) self . direct_posts_count = direct_approved_topics . aggregate ( total_posts_count = Sum ( 'po...
def main ( search_engine , search_option , list_engines , query ) : """Quick search command tool for your terminal"""
engine_data = { } if list_engines : for name in engines : conf = get_config ( name ) optionals = filter ( lambda e : e != 'default' , conf . keys ( ) ) if optionals : click . echo ( '{command} -o {options}' . format ( command = name . replace ( '.json' , '' ) , options = ', ' . j...
def apply ( self , strain , detector_name , f_lower = None , distance_scale = 1 ) : """Add injections ( as seen by a particular detector ) to a time series . Parameters strain : TimeSeries Time series to inject signals into , of type float32 or float64. detector _ name : string Name of the detector used f...
if strain . dtype not in ( float32 , float64 ) : raise TypeError ( "Strain dtype must be float32 or float64, not " + str ( strain . dtype ) ) lalstrain = strain . lal ( ) # detector = Detector ( detector _ name ) earth_travel_time = lal . REARTH_SI / lal . C_SI t0 = float ( strain . start_time ) - earth_travel_time...
def ellipticity2phi_q ( e1 , e2 ) : """: param e1: : param e2: : return :"""
phi = np . arctan2 ( e2 , e1 ) / 2 c = np . sqrt ( e1 ** 2 + e2 ** 2 ) if c > 0.999 : c = 0.999 q = ( 1 - c ) / ( 1 + c ) return phi , q
def pos_tokenize ( self : object , fileids : str ) : """Segments , tokenizes , and POS tag a document in the corpus ."""
for para in self . paras ( fileids ) : yield [ self . pos_tagger ( word_tokenize ( sent ) ) for sent in sent_tokenize ( para ) ]
def new_table ( self , name , add_id = True , ** kwargs ) : '''Add a table to the schema , or update it it already exists . If updating , will only update data .'''
from . import Table from . exc import NotFoundError try : table = self . table ( name ) extant = True except NotFoundError : extant = False if 'sequence_id' not in kwargs : kwargs [ 'sequence_id' ] = self . _database . next_sequence_id ( Dataset , self . vid , Table ) table = Table ( name = ...
def solar_longitude ( day , orb = const . orb_present , days_per_year = None ) : """Estimates solar longitude from calendar day . Method is using an approximation from : cite : ` Berger _ 1978 ` section 3 ( lambda = 0 at spring equinox ) . * * Function - call arguments * * \n : param array day : Indicator o...
if days_per_year is None : days_per_year = const . days_per_year ecc = orb [ 'ecc' ] long_peri_rad = deg2rad ( orb [ 'long_peri' ] ) delta_lambda = ( day - 80. ) * 2 * pi / days_per_year beta = sqrt ( 1 - ecc ** 2 ) lambda_long_m = - 2 * ( ( ecc / 2 + ( ecc ** 3 ) / 8 ) * ( 1 + beta ) * sin ( - long_peri_rad ) - ( ...
def send_faucet_coins ( address_to_fund , satoshis , api_key , coin_symbol = 'bcy' ) : '''Send yourself test coins on the bitcoin or blockcypher testnet You can see your balance info at : - https : / / live . blockcypher . com / bcy / for BCY - https : / / live . blockcypher . com / btc - testnet / for BTC Te...
assert coin_symbol in ( 'bcy' , 'btc-testnet' ) assert is_valid_address_for_coinsymbol ( b58_address = address_to_fund , coin_symbol = coin_symbol ) assert satoshis > 0 assert api_key , 'api_key required' url = make_url ( coin_symbol , 'faucet' ) data = { 'address' : address_to_fund , 'amount' : satoshis , } params = {...
def __request_start ( self , queue_item ) : """Execute the request in given queue item . Args : queue _ item ( : class : ` nyawc . QueueItem ` ) : The request / response pair to scrape ."""
try : action = self . __options . callbacks . request_before_start ( self . queue , queue_item ) except Exception as e : action = None print ( e ) print ( traceback . format_exc ( ) ) if action == CrawlerActions . DO_STOP_CRAWLING : self . __should_stop = True if action == CrawlerActions . DO_SKIP_T...
def listar_por_ambiente ( self , id_ambiente ) : """List all VLANs from an environment . * * The itens returning from network is there to be compatible with other system * * : param id _ ambiente : Environment identifier . : return : Following dictionary : { ' vlan ' : [ { ' id ' : < id _ vlan > , ' nome ...
if not is_valid_int_param ( id_ambiente ) : raise InvalidParameterError ( u'Environment id is none or invalid.' ) url = 'vlan/ambiente/' + str ( id_ambiente ) + '/' code , xml = self . submit ( None , 'GET' , url ) key = 'vlan' return get_list_map ( self . response ( code , xml , [ key ] ) , key )
def adjust ( cols , light ) : """Create palette ."""
raw_colors = [ cols [ 0 ] , * cols , "#FFFFFF" , "#000000" , * cols , "#FFFFFF" ] return colors . generic_adjust ( raw_colors , light )
def encode ( in_bytes ) : """Encode a string using Consistent Overhead Byte Stuffing ( COBS ) . Input is any byte string . Output is also a byte string . Encoding guarantees no zero bytes in the output . The output string will be expanded slightly , by a predictable amount . An empty string is encoded to ' ...
if isinstance ( in_bytes , str ) : raise TypeError ( 'Unicode-objects must be encoded as bytes first' ) in_bytes_mv = _get_buffer_view ( in_bytes ) final_zero = True out_bytes = bytearray ( ) idx = 0 search_start_idx = 0 for in_char in in_bytes_mv : if in_char == b'\x00' : final_zero = True out_...
def index ( self ) : """main page rendering"""
self . _check_auth ( must_admin = False ) is_admin = self . _check_admin ( ) sess = cherrypy . session user = sess . get ( SESSION_KEY , None ) if self . auth_mode == 'none' : user_attrs = None else : user_attrs = self . _get_user ( user ) attrs_list = self . attributes . get_search_attributes ( ) return self ....
def google_storage ( self , scene , path ) : """Google Storage Downloader . : param scene : The scene id : type scene : String : param path : The directory path to where the image should be stored : type path : String : returns : Boolean"""
sat = self . scene_interpreter ( scene ) url = self . google_storage_url ( sat ) self . remote_file_exists ( url ) self . output ( 'Source: Google Storage' , normal = True , arrow = True ) return self . fetch ( url , path )
def experiments_fmri_create ( self , experiment_url , data_file ) : """Upload given data file as fMRI for experiment with given Url . Parameters experiment _ url : string Url for experiment resource data _ file : Abs . Path to file on disk Functional data file Returns scoserv . FunctionalDataHandle ...
# Get the experiment experiment = self . experiments_get ( experiment_url ) # Upload data FunctionalDataHandle . create ( experiment . links [ sco . REF_EXPERIMENTS_FMRI_CREATE ] , data_file ) # Get new fmri data handle and return it return self . experiments_get ( experiment_url ) . fmri_data
def validate_is_document_type ( option , value ) : """Validate the type of method arguments that expect a MongoDB document ."""
if not isinstance ( value , ( abc . MutableMapping , RawBSONDocument ) ) : raise TypeError ( "%s must be an instance of dict, bson.son.SON, " "bson.raw_bson.RawBSONDocument, or " "a type that inherits from " "collections.MutableMapping" % ( option , ) )
def iam ( self ) : """Generate iam details ."""
iam = { 'group' : self . format [ 'iam_group' ] . format ( ** self . data ) , 'lambda_role' : self . format [ 'iam_lambda_role' ] . format ( ** self . data ) , 'policy' : self . format [ 'iam_policy' ] . format ( ** self . data ) , 'profile' : self . format [ 'iam_profile' ] . format ( ** self . data ) , 'role' : self ...
def identify ( self , req , resp , resource , uri_kwargs ) : """Identify user using Authenticate header with Token auth ."""
header = req . get_header ( 'Authorization' , False ) auth = header . split ( ' ' ) if header else None if auth is None or auth [ 0 ] . lower ( ) != 'token' : return None if len ( auth ) != 2 : raise HTTPBadRequest ( "Invalid Authorization header" , "The Authorization header for Token auth should be in form:\n"...
def delete_multireddit ( self , name , * args , ** kwargs ) : """Delete a Multireddit . Any additional parameters are passed directly into : meth : ` ~ praw . _ _ init _ _ . BaseReddit . request `"""
url = self . config [ 'multireddit_about' ] . format ( user = self . user . name , multi = name ) # The modhash isn ' t necessary for OAuth requests if not self . _use_oauth : self . http . headers [ 'x-modhash' ] = self . modhash try : self . request ( url , data = { } , method = 'DELETE' , * args , ** kwargs ...
async def _dump_container_val ( self , writer , elem , container_type , params = None ) : """Single elem dump : param writer : : param elem : : param container _ type : : param params : : return :"""
elem_type = container_elem_type ( container_type , params ) await self . dump_field ( writer , elem , elem_type , params [ 1 : ] if params else None )
def value_to_int ( attrib , key ) : """Massage runs in an inning to 0 if an empty string , or key not found . Otherwise return the value"""
val = attrib . get ( key , 0 ) if isinstance ( val , str ) : if val . isspace ( ) or val == '' : return 0 return val
def int_to_string ( number , alphabet , padding = None ) : """Convert a number to a string , using the given alphabet . The output has the most significant digit first ."""
output = "" alpha_len = len ( alphabet ) while number : number , digit = divmod ( number , alpha_len ) output += alphabet [ digit ] if padding : remainder = max ( padding - len ( output ) , 0 ) output = output + alphabet [ 0 ] * remainder return output [ : : - 1 ]
def export ( self , sql_client , merge_rule = 'skip' , coerce = False ) : '''a method to export all the records in table to another table : param sql _ client : class object with sql client methods : param merge _ rule : string with name of rule to adopt for pre - existing records : param coerce : boolean to ...
title = '%s.export' % self . __class__ . __name__ # validate sql client method_list = [ 'list' , 'create' , 'read' , 'update' , 'delete' , 'remove' , 'export' , 'exists' , '_construct_inserts' , '_parse_columns' , '_compare_columns' , 'table' , 'session' , 'table_name' , 'database_name' ] for method in method_list : ...
def update_bookmark ( self , bookmark_id , favorite = None , archive = None , read_percent = None ) : """Updates given bookmark . The requested bookmark must belong to the current user . : param bookmark _ id : ID of the bookmark to update . : param favorite ( optional ) : Whether this article is favorited or...
rdb_url = self . _generate_url ( 'bookmarks/{0}' . format ( bookmark_id ) ) params = { } if favorite is not None : params [ 'favorite' ] = 1 if favorite == True else 0 if archive is not None : params [ 'archive' ] = 1 if archive == True else 0 if read_percent is not None : try : params [ 'read_perce...
def parse_criteria ( criteria_string ) : """Parses a powerful and simple string criteria and generates a proper mongo syntax criteria . Args : criteria _ string ( str ) : A string representing a search criteria . Also supports wild cards . E . g . , something like " * 2O " gets converted to { ' pretty _...
toks = criteria_string . split ( ) def parse_sym ( sym ) : if sym == "*" : return [ el . symbol for el in Element ] else : m = re . match ( r"\{(.*)\}" , sym ) if m : return [ s . strip ( ) for s in m . group ( 1 ) . split ( "," ) ] else : return [ sym ] d...
def get_gain ( self , attr_name ) : """Calculates the information gain from splitting on the given attribute ."""
subset_entropy = 0.0 for value in iterkeys ( self . _attr_value_counts [ attr_name ] ) : value_prob = self . get_value_prob ( attr_name , value ) e = self . get_entropy ( attr_name , value ) subset_entropy += value_prob * e return ( self . main_entropy - subset_entropy )
def console_get_char_background ( con : tcod . console . Console , x : int , y : int ) -> Color : """Return the background color at the x , y of this console . . . deprecated : : 8.4 Array access performs significantly faster than using this function . See : any : ` Console . bg ` ."""
return Color . _new_from_cdata ( lib . TCOD_console_get_char_background ( _console ( con ) , x , y ) )
def _platform_patterns ( self , platform = 'generic' , compiled = False ) : """Return all the patterns for specific platform ."""
patterns = self . _dict_compiled . get ( platform , None ) if compiled else self . _dict_text . get ( platform , None ) if patterns is None : raise KeyError ( "Unknown platform: {}" . format ( platform ) ) return patterns
def enrich ( self , columns ) : """This method appends at the end of the dataframe as many rows as items are found in the list of elemnents in the provided columns . This assumes that the length of the lists for the several specified columns is the same . As an example , for the row A { " C1 " : " V1 " , ...
for column in columns : if column not in self . data . columns : return self . data # Looking for the rows with columns with lists of more # than one element first_column = list ( self . data [ columns [ 0 ] ] ) count = 0 append_df = pandas . DataFrame ( ) for cell in first_column : if len ( cell ) >= 1...
def load ( self , tableName = 'rasters' , rasters = [ ] ) : '''Accepts a list of paths to raster files to load into the database . Returns the ids of the rasters loaded successfully in the same order as the list passed in .'''
# Create table if necessary Base . metadata . create_all ( self . _engine ) # Create a session Session = sessionmaker ( bind = self . _engine ) session = Session ( ) for raster in rasters : # Must read in using the raster2pgsql commandline tool . rasterPath = raster [ 'path' ] if 'srid' in raster : srid...
def _create_worker ( self , worker ) : """Common worker setup ."""
worker . sig_started . connect ( self . _start ) self . _workers . append ( worker )
def _get ( pseudodict , key , single = True ) : """Helper method for getting values from " multi - dict " s"""
matches = [ item [ 1 ] for item in pseudodict if item [ 0 ] == key ] if single : return matches [ 0 ] else : return matches
def export_ruptures_csv ( ekey , dstore ) : """: param ekey : export key , i . e . a pair ( datastore key , fmt ) : param dstore : datastore object"""
oq = dstore [ 'oqparam' ] if 'scenario' in oq . calculation_mode : return [ ] dest = dstore . export_path ( 'ruptures.csv' ) header = ( 'rupid multiplicity mag centroid_lon centroid_lat ' 'centroid_depth trt strike dip rake boundary' ) . split ( ) rows = [ ] for rgetter in gen_rupture_getters ( dstore ) : rups ...
def simulate ( s0 , transmat , steps = 1 ) : """Simulate the next state Parameters s0 : ndarray Vector with state variables at t = 0 transmat : ndarray The estimated transition / stochastic matrix . steps : int ( Default : 1 ) The number of steps to simulate model outputs ahead . If steps > 1 the a ...
# Single - Step simulation if steps == 1 : return np . dot ( s0 , transmat ) # Multi - Step simulation out = np . zeros ( shape = ( steps + 1 , len ( s0 ) ) , order = 'C' ) out [ 0 , : ] = s0 for i in range ( 1 , steps + 1 ) : out [ i , : ] = np . dot ( out [ i - 1 , : ] , transmat ) return out
def get_deposit ( self , deposit_id , ** params ) : """https : / / developers . coinbase . com / api / v2 # show - a - deposit"""
return self . api_client . get_deposit ( self . id , deposit_id , ** params )
def trimquality ( self ) : """Uses bbduk from the bbmap tool suite to quality and adapter trim"""
logging . info ( "Trimming fastq files" ) # Iterate through strains with fastq files with progressbar ( self . metadata ) as bar : for sample in bar : # As the metadata can be populated with ' NA ' ( string ) if there are no fastq files , only process if # : fastqfiles is a list if type ( sample . gener...
def _genotype_in_background ( rec , base_name , back_samples ) : """Check if the genotype in the record of interest is present in the background records ."""
def passes ( rec ) : return not rec . FILTER or len ( rec . FILTER ) == 0 return ( passes ( rec ) and any ( rec . genotype ( base_name ) . gt_alleles == rec . genotype ( back_name ) . gt_alleles for back_name in back_samples ) )
def is_capture ( self , move : Move ) -> bool : """Checks if the given pseudo - legal move is a capture ."""
return bool ( BB_SQUARES [ move . to_square ] & self . occupied_co [ not self . turn ] ) or self . is_en_passant ( move )
def expand_dims ( self , axis ) : """Insert a new axis , at a given position in the array shape Args : axis ( int ) : Position ( amongst axes ) where new axis is to be inserted ."""
if axis == - 1 : axis = self . ndim array = np . expand_dims ( self , axis ) if axis == 0 : # prepended an axis : no longer a Timeseries return array else : new_labels = self . labels . insert ( axis , None ) return Timeseries ( array , self . tspan , new_labels )
def add_xmlid ( cr , module , xmlid , model , res_id , noupdate = False ) : """Adds an entry in ir _ model _ data . Typically called in the pre script . One usage example is when an entry has been add in the XML and there is a high probability that the user has already created the entry manually . For example...
# Check if the XMLID doesn ' t already exists cr . execute ( "SELECT id FROM ir_model_data WHERE module=%s AND name=%s " "AND model=%s" , ( module , xmlid , model ) ) already_exists = cr . fetchone ( ) if already_exists : return False else : logged_query ( cr , "INSERT INTO ir_model_data (create_uid, create_dat...
def update_hash ( self , layers : Iterable ) : """Calculation of ` hash _ id ` of Layer . Which is determined by the properties of itself , and the ` hash _ id ` s of input layers"""
if self . graph_type == LayerType . input . value : return hasher = hashlib . md5 ( ) hasher . update ( LayerType ( self . graph_type ) . name . encode ( 'ascii' ) ) hasher . update ( str ( self . size ) . encode ( 'ascii' ) ) for i in self . input : if layers [ i ] . hash_id is None : raise ValueError ...
def wrapModel ( self , model ) : """Converts application - provided model objects to L { IResource } providers ."""
res = IResource ( model , None ) if res is None : frag = INavigableFragment ( model ) fragmentName = getattr ( frag , 'fragmentName' , None ) if fragmentName is not None : fragDocFactory = self . _getDocFactory ( fragmentName ) if fragDocFactory is not None : frag . docFactory = ...
def update_task_redundancy ( config , task_id , redundancy ) : """Update task redudancy for a project ."""
if task_id is None : msg = ( "Are you sure you want to update all the tasks redundancy?" ) if click . confirm ( msg ) : res = _update_tasks_redundancy ( config , task_id , redundancy ) click . echo ( res ) else : click . echo ( "Aborting." ) else : res = _update_tasks_redundancy ...
def context ( self , outdir , log_prefix ) : """Setup instance to extract metrics from the proper run : param outdir : run directory : param log _ prefix : log filenames prefix"""
try : self . _outdir = outdir self . _log_prefix = log_prefix yield finally : self . _log_prefix = None self . _outdir = None
def dependency_status ( data ) : """Return abstracted status of dependencies . - ` ` STATUS _ ERROR ` ` . . one dependency has error status or was deleted - ` ` STATUS _ DONE ` ` . . all dependencies have done status - ` ` None ` ` . . other"""
parents_statuses = set ( DataDependency . objects . filter ( child = data , kind = DataDependency . KIND_IO ) . distinct ( 'parent__status' ) . values_list ( 'parent__status' , flat = True ) ) if not parents_statuses : return Data . STATUS_DONE if None in parents_statuses : # Some parents have been deleted . re...
def write ( self , image , options , thumbnail ) : """Writes the thumbnail image"""
if options [ 'format' ] == 'JPEG' and options . get ( 'progressive' , settings . THUMBNAIL_PROGRESSIVE ) : image [ 'options' ] [ 'interlace' ] = 'line' image [ 'options' ] [ 'quality' ] = options [ 'quality' ] args = settings . THUMBNAIL_CONVERT . split ( ' ' ) args . append ( image [ 'source' ] + '[0]' ) for k in ...
def _load_sequences_to_reference_gene ( self , g_id , force_rerun = False ) : """Load orthologous strain sequences to reference Protein object , save as new pickle"""
protein_seqs_pickle_path = op . join ( self . sequences_by_gene_dir , '{}_protein_withseqs.pckl' . format ( g_id ) ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = protein_seqs_pickle_path ) : protein_pickle_path = self . gene_protein_pickles [ g_id ] protein_pickle = ssbio . io . load_pickle (...
async def destroy_unit ( self , * unit_names ) : """Destroy units by name ."""
connection = self . connection ( ) app_facade = client . ApplicationFacade . from_connection ( connection ) log . debug ( 'Destroying unit%s %s' , 's' if len ( unit_names ) == 1 else '' , ' ' . join ( unit_names ) ) return await app_facade . DestroyUnits ( list ( unit_names ) )
def execute ( function , name ) : """Execute a task , returning a TaskResult"""
try : return TaskResult ( name , True , None , function ( ) ) except Exception as exc : return TaskResult ( name , False , exc , None )
def init_config ( self , app ) : """Initialize configuration ."""
for k in dir ( config ) : if k . startswith ( 'JSONSCHEMAS_' ) : app . config . setdefault ( k , getattr ( config , k ) ) host_setting = app . config [ 'JSONSCHEMAS_HOST' ] if not host_setting or host_setting == 'localhost' : app . logger . warning ( 'JSONSCHEMAS_HOST is set to {0}' . format ( host_sett...
def find_modules ( self , requested_names ) : """find the module ( s ) given the name ( s )"""
found_modules = set ( ) for requested_name in requested_names : is_instance = " " in requested_name for module_name , module in self . py3_wrapper . output_modules . items ( ) : if module [ "type" ] == "py3status" : name = module [ "module" ] . module_nice_name else : nam...
def rapidfire ( self , max_nlaunch = - 1 , max_loops = 1 , sleep_time = 5 ) : """Keeps submitting ` Tasks ` until we are out of jobs or no job is ready to run . Args : max _ nlaunch : Maximum number of launches . default : no limit . max _ loops : Maximum number of loops sleep _ time : seconds to sleep betw...
num_launched , do_exit , launched = 0 , False , [ ] for count in range ( max_loops ) : if do_exit : break if count > 0 : time . sleep ( sleep_time ) tasks = self . fetch_tasks_to_run ( ) # I don ' t know why but we receive duplicated tasks . if any ( task in launched for task in task...
def get_objectives_by_query ( self , objective_query ) : """Gets a list of ` ` Objectives ` ` matching the given objective query . arg : objective _ query ( osid . learning . ObjectiveQuery ) : the objective query return : ( osid . learning . ObjectiveList ) - the returned ` ` ObjectiveList ` ` raise : Nu...
# Implemented from template for # osid . resource . ResourceQuerySession . get _ resources _ by _ query and_list = list ( ) or_list = list ( ) for term in objective_query . _query_terms : if '$in' in objective_query . _query_terms [ term ] and '$nin' in objective_query . _query_terms [ term ] : and_list . a...
def fatal ( msg , exitcode = 1 , ** kwargs ) : """Prints a message then exits the program . Optionally pause before exit with ` pause = True ` kwarg ."""
# NOTE : Can ' t use normal arg named ` pause ` since function has same name . pause_before_exit = kwargs . pop ( "pause" ) if "pause" in kwargs . keys ( ) else False echo ( "[FATAL] " + msg , ** kwargs ) if pause_before_exit : pause ( ) sys . exit ( exitcode )
def gen_shell ( opts , ** kwargs ) : '''Return the correct shell interface for the target system'''
if kwargs [ 'winrm' ] : try : import saltwinshell shell = saltwinshell . Shell ( opts , ** kwargs ) except ImportError : log . error ( 'The saltwinshell library is not available' ) sys . exit ( salt . defaults . exitcodes . EX_GENERIC ) else : shell = Shell ( opts , ** kwargs...
def reorder_translation_formset_by_language_code ( inline_admin_form ) : """Shuffle the forms in the formset of multilingual model in the order of their language _ ids ."""
lang_to_form = dict ( [ ( form . form . initial [ 'language_id' ] , form ) for form in inline_admin_form ] ) return [ lang_to_form [ language_code ] for language_code in get_language_code_list ( ) ]
def parse_localnamespacepath ( self , tup_tree ) : """Parse a LOCALNAMESPACEPATH element and return the namespace it represents as a unicode string . The namespace is formed by joining the namespace components ( one from each NAMESPACE child element ) with a slash ( e . g . to " root / cimv2 " ) . < ! ELEME...
self . check_node ( tup_tree , 'LOCALNAMESPACEPATH' , ( ) , ( ) , ( 'NAMESPACE' , ) ) if not kids ( tup_tree ) : raise CIMXMLParseError ( _format ( "Element {0!A} missing child elements (expecting one " "or more child elements 'NAMESPACE')" , name ( tup_tree ) ) , conn_id = self . conn_id ) # self . list _ of _ var...
def get_identity ( self , subject_id , entities = None ) : """Get all the identity information that has been received and are still valid about the subject . : param subject _ id : The identifier of the subject : param entities : The identifiers of the entities whoes assertions are interesting . If the list...
if not entities : entities = self . entities ( subject_id ) if not entities : return { } , [ ] res = { } oldees = [ ] for ( entity_id , item ) in self . _cache . get_multi ( entities , subject_id + '_' ) . items ( ) : try : info = self . get_info ( item ) except ToOld : oldees . ...
def rpc_request ( self , frame_out , connection_adapter = None ) : """Perform a RPC Request . : param specification . Frame frame _ out : Amqp frame . : rtype : dict"""
with self . rpc . lock : uuid = self . rpc . register_request ( frame_out . valid_responses ) self . _connection . write_frame ( self . channel_id , frame_out ) return self . rpc . get_request ( uuid , connection_adapter = connection_adapter )
def setup ( self ) : """performs data collection for qpid broker"""
options = "" amqps_prefix = "" # set amqps : / / when SSL is used if self . get_option ( "ssl" ) : amqps_prefix = "amqps://" # for either present option , add - - option = value to ' options ' variable for option in [ "ssl-certificate" , "ssl-key" ] : if self . get_option ( option ) : amqps_prefix = "am...
def _fetch ( self , default_path ) : """Internal method for fetching . This differs from : meth : ` . fetch ` in that it accepts a default path as an argument ."""
if not self . _path : path = default_path else : path = self . _path req_type = 'GET' if len ( self . _post_params ) == 0 else 'POST' url = '/' . join ( [ 'http:/' , self . spacegdn . endpoint , path ] ) resp = requests . request ( req_type , url , params = self . _get_params , data = self . _post_params , head...
def parse_dict ( self , attrs ) : """Read a dict to attributes ."""
attrs = attrs or { } ident = attrs . get ( "id" , "" ) classes = attrs . get ( "classes" , [ ] ) kvs = OrderedDict ( ( k , v ) for k , v in attrs . items ( ) if k not in ( "classes" , "id" ) ) return ident , classes , kvs
def clear ( self ) : """Command : 0x03 clear all leds Data : [ Command ]"""
header = bytearray ( ) header . append ( LightProtocolCommand . Clear ) return self . send ( header )
def get_entry ( self , key , column = None , table = None ) : """Get a specific entry ."""
if table is None : table = self . main_table if column is None : column = "id" if isinstance ( key , basestring ) : key = key . replace ( "'" , "''" ) query = 'SELECT * from "%s" where "%s"=="%s" LIMIT 1;' query = query % ( table , column , key ) self . own_cursor . execute ( query ) return self . own_curso...
def download_url ( url , destination = None , progress_bar = True ) : """Download a URL to a local file . Parameters url : str The URL to download . destination : str , None The destination of the file . If None is given the file is saved to a temporary directory . progress _ bar : bool Whether to sho...
def my_hook ( t ) : last_b = [ 0 ] def inner ( b = 1 , bsize = 1 , tsize = None ) : if tsize is not None : t . total = tsize if b > 0 : t . update ( ( b - last_b [ 0 ] ) * bsize ) last_b [ 0 ] = b return inner if progress_bar : with tqdm ( unit = 'B' , uni...
def create ( self , name , * args , ** kwargs ) : """Need to wrap the default call to handle exceptions ."""
try : return super ( ImageMemberManager , self ) . create ( name , * args , ** kwargs ) except Exception as e : if e . http_status == 403 : raise exc . UnsharableImage ( "You cannot share a public image." ) else : raise
def datetime_from_iso8601 ( date ) : """Small helper that parses ISO - 8601 date dates . > > > datetime _ from _ iso8601 ( " 2013-04-10T12:52:39 " ) datetime . datetime ( 2013 , 4 , 10 , 12 , 52 , 39) > > > datetime _ from _ iso8601 ( " 2013-01-07T12:55:19.257 " ) datetime . datetime ( 2013 , 1 , 7 , 12 , 5...
format = ISO8610_FORMAT if date . endswith ( "Z" ) : date = date [ : - 1 ] # Date date is UTC if re . match ( ".*\.\d+" , date ) : # Date includes microseconds format = ISO8610_FORMAT_MICROSECONDS return datetime . datetime . strptime ( date , format )
def _manageColumns ( self , action , varBind , ** context ) : """Apply a management action on all columns Parameters action : : py : class : ` str ` any of : py : class : ` MibInstrumController ` ' s states to apply on all columns but the one passed in ` varBind ` varBind : : py : class : ` ~ pysnmp . smi ....
name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: _manageColumns(%s, %s, %r)' % ( self , action , name , val ) ) ) cbFun = context [ 'cbFun' ] colLen = len ( self . name ) + 1 # Build a map of index names and values for automatic initialization indexVals = { } instId = name [ colLen : ]...
def get_logs ( self , project , release_id , ** kwargs ) : """GetLogs . [ Preview API ] Get logs for a release Id . : param str project : Project ID or project name : param int release _ id : Id of the release . : rtype : object"""
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if release_id is not None : route_values [ 'releaseId' ] = self . _serialize . url ( 'release_id' , release_id , 'int' ) response = self . _send ( http_method = 'GET' , location_id = ...
def build ( ctx , skip ) : """Build documentation as HTML . This command performs these steps : 1 . Removes any existing symlinks in the ` ` modules ` ` , ` ` packages ` ` , and ` ` _ static ` ` directories . 2 . Finds packages set up by EUPS that have Sphinx - enabled doc / directories and links their mo...
return_code = build_stack_docs ( ctx . obj [ 'root_project_dir' ] , skippedNames = skip ) if return_code > 0 : sys . exit ( return_code )
def _EnsureRequesterStarted ( self ) : """Checks if the analyzer is running and starts it if not ."""
if not self . _analyzer_started : self . _analyzer . start ( ) self . _analyzer_started = True
def _set_group_selection ( self ) : """Create group based selection . Used when selection is not passed directly but instead via a grouper . NOTE : this should be paired with a call to _ reset _ group _ selection"""
grp = self . grouper if not ( self . as_index and getattr ( grp , 'groupings' , None ) is not None and self . obj . ndim > 1 and self . _group_selection is None ) : return ax = self . obj . _info_axis groupers = [ g . name for g in grp . groupings if g . level is None and g . in_axis ] if len ( groupers ) : # GH128...
def p_ex_map_pair ( self , p ) : """ex _ map _ pair : ex _ map _ elem COLON ex _ map _ elem"""
try : p [ 0 ] = { p [ 1 ] : p [ 3 ] } except TypeError : msg = u"%s is an invalid hash key because it cannot be hashed." % repr ( p [ 1 ] ) self . errors . append ( ( msg , p . lineno ( 2 ) , self . path ) ) p [ 0 ] = { }
def get ( self , key ) : '''Get a value for a given key : param key : entry ' s key : return : corresponding value'''
if key in self . _data_fields : return self . _data_fields [ key ] if key in self . _sub_reports : return self . _sub_reports [ key ] return None
def __getDummyDateList ( ) : """Generate a dummy date list for testing without hitting the server"""
D = [ ] for y in xrange ( 2001 , 2010 ) : for d in xrange ( 1 , 365 , 1 ) : D . append ( 'A%04d%03d' % ( y , d ) ) return D
def logNormalRDD ( sc , mean , std , size , numPartitions = None , seed = None ) : """Generates an RDD comprised of i . i . d . samples from the log normal distribution with the input mean and standard distribution . : param sc : SparkContext used to create the RDD . : param mean : mean for the log Normal dis...
return callMLlibFunc ( "logNormalRDD" , sc . _jsc , float ( mean ) , float ( std ) , size , numPartitions , seed )
def _default_to_pandas ( self , op , * args , ** kwargs ) : """Helper method to use default pandas function"""
empty_self_str = "" if not self . empty else " for empty DataFrame" ErrorMessage . default_to_pandas ( "`{}.{}`{}" . format ( self . __name__ , op if isinstance ( op , str ) else op . __name__ , empty_self_str , ) ) if callable ( op ) : result = op ( self . _to_pandas ( ) , * args , ** kwargs ) elif isinstance ( op...
def install_webpi ( name , install_args = None , override_args = False ) : '''Instructs Chocolatey to install a package via the Microsoft Web PI service . name The name of the package to be installed . Only accepts a single argument . install _ args A list of install arguments you want to pass to the instal...
return install ( name , source = 'webpi' , install_args = install_args , override_args = override_args )
def incrementing_sleep ( self , previous_attempt_number , delay_since_first_attempt_ms ) : """Sleep an incremental amount of time after each attempt , starting at wait _ incrementing _ start and incrementing by wait _ incrementing _ increment"""
result = self . _wait_incrementing_start + ( self . _wait_incrementing_increment * ( previous_attempt_number - 1 ) ) if result < 0 : result = 0 return result
def remove_stacktrace_locals ( client , event ) : """Removes local variables from any frames . : param client : an ElasticAPM client : param event : a transaction or error event : return : The modified event"""
func = lambda frame : frame . pop ( "vars" , None ) return _process_stack_frames ( event , func )
def ReadHuntLogEntries ( self , hunt_id , offset , count , with_substring = None ) : """Reads hunt log entries of a given hunt using given query options ."""
all_entries = [ ] for flow_obj in self . _GetHuntFlows ( hunt_id ) : for entry in self . ReadFlowLogEntries ( flow_obj . client_id , flow_obj . flow_id , 0 , sys . maxsize , with_substring = with_substring ) : all_entries . append ( rdf_flow_objects . FlowLogEntry ( hunt_id = hunt_id , client_id = flow_obj ...
def smart_unicode_decode ( encoded_string ) : """Given an encoded string of unknown format , detect the format with chardet and return the unicode version . Example input from bug # 11: ( ' \xfe \xff \x00 I \x00 n \x00 s \x00 p \x00 e \x00 c \x00 t \x00 i \x00 o \x00 n \x00 ' ' \x00 R \x00 e \x00 p \x00 o \...
if not encoded_string : return u'' # optimization - - first try ascii try : return encoded_string . decode ( 'ascii' ) except UnicodeDecodeError : pass # detect encoding detected_encoding = chardet . detect ( encoded_string ) # bug 54 - - depending on chardet version , if encoding is not guessed , # either ...
def set_pending_boot_mode ( self , boot_mode ) : """Sets the boot mode of the system for next boot . : param boot _ mode : either ' uefi ' or ' legacy ' . : raises : IloInvalidInputError , on an invalid input . : raises : IloError , on an error from iLO ."""
sushy_system = self . _get_sushy_system ( PROLIANT_SYSTEM_ID ) if boot_mode . upper ( ) not in BOOT_MODE_MAP_REV . keys ( ) : msg = ( ( 'Invalid Boot mode: "%(boot_mode)s" specified, valid boot ' 'modes are either "uefi" or "legacy"' ) % { 'boot_mode' : boot_mode } ) raise exception . IloInvalidInputError ( msg...
def _make_carpet ( self , rescale_data ) : """Constructs the carpet from the input image . Optional rescaling of the data ."""
self . carpet = self . _unroll_array ( self . input_image , self . fixed_dim ) if rescale_data : self . carpet = row_wise_rescale ( self . carpet )
def save ( self , model , joining = None , touch = True ) : """Save a new model and attach it to the parent model . : type model : eloquent . Model : type joining : dict : type touch : bool : rtype : eloquent . Model"""
if joining is None : joining = { } model . save ( { 'touch' : False } ) self . attach ( model . get_key ( ) , joining , touch ) return model
def update_builds ( self , builds , project ) : """UpdateBuilds . Updates multiple builds . : param [ Build ] builds : The builds to update . : param str project : Project ID or project name : rtype : [ Build ]"""
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) content = self . _serialize . body ( builds , '[Build]' ) response = self . _send ( http_method = 'PATCH' , location_id = '0cd358e1-9217-4d94-8269-1c1ee6f93dcf' , version = '5.0' , route_...
def save ( self , status = None , callback_pos = None , id_workflow = None ) : """Save object to persistent storage ."""
if self . model is None : raise WorkflowsMissingModel ( ) with db . session . begin_nested ( ) : workflow_object_before_save . send ( self ) self . model . modified = datetime . now ( ) if status is not None : self . model . status = status if id_workflow is not None : workflow = Wor...
def set_output_format ( output_format ) : """Sets output format ; returns standard bits of table . These are : ttx : how to start a title for a set of tables xtt : how to end a title for a set of tables tx : how to start a table xt : how to close a table capx : how to start a caption for the table xcap ...
if output_format == 'wiki' : ttx = '== ' xtt = ' ==' tx = '' xt = '' capx = "'''" xcap = "'''" rx = '|' xr = '|' rspx = '|<|' xrsp = '>' cx = '|' xc = '|' hlx = '[' hxl = ' ' xhl = ']' elif output_format == "html" : ttx = '<b>' xtt = '</b><hr>' tx ...
def grab ( self , monitor ) : # type : ( Monitor ) - > ScreenShot """See : meth : ` MSSMixin . grab < mss . base . MSSMixin . grab > ` for full details ."""
# pylint : disable = too - many - locals # Convert PIL bbox style if isinstance ( monitor , tuple ) : monitor = { "left" : monitor [ 0 ] , "top" : monitor [ 1 ] , "width" : monitor [ 2 ] - monitor [ 0 ] , "height" : monitor [ 3 ] - monitor [ 1 ] , } core = self . core rect = CGRect ( ( monitor [ "left" ] , monitor ...
def nt_event_log_handler ( name , logname , appname , dllname = None , logtype = "Application" ) : """A Bark logging handler logging output to the NT Event Log . Similar to logging . handlers . NTEventLogHandler ."""
return wrap_log_handler ( logging . handlers . NTEventLogHandler ( appname , dllname = dllname , logtype = logtype ) )
def hot_threads ( self , node_id = None , params = None ) : """An API allowing to get the current hot threads on each node in the cluster . ` < https : / / www . elastic . co / guide / en / elasticsearch / reference / current / cluster - nodes - hot - threads . html > ` _ : arg node _ id : A comma - separated l...
# avoid python reserved words if params and "type_" in params : params [ "type" ] = params . pop ( "type_" ) return self . transport . perform_request ( "GET" , _make_path ( "_cluster" , "nodes" , node_id , "hotthreads" ) , params = params )
def find_needed_formatter ( input_format , output_format ) : """Find a data formatter given an input and output format input _ format - needed input format . see utils . input . dataformats output _ format - needed output format . see utils . input . dataformats"""
# Only take the formatters in the registry selected_registry = [ re . cls for re in registry if re . category == RegistryCategories . formatters ] needed_formatters = [ ] for formatter in selected_registry : # Initialize the formatter ( needed so it can discover its formats ) formatter_inst = formatter ( ) if i...
def push_source ( self , newstream , newfile = None ) : "Push an input source onto the lexer ' s input source stack ."
if isinstance ( newstream , basestring ) : newstream = StringIO ( newstream ) self . filestack . appendleft ( ( self . infile , self . instream , self . lineno ) ) self . infile = newfile self . instream = newstream self . lineno = 1