signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def sizeHint ( self , option , index ) : """Size based on component duration and a fixed height"""
# calculate size by data component component = index . internalPointer ( ) width = self . component . duration ( ) * self . pixelsPerms * 1000 return QtCore . QSize ( width , 50 )
def findByPrefix ( self , term , limit = 20 , searchSynonyms = 'true' , searchAbbreviations = 'false' , searchAcronyms = 'false' , includeDeprecated = 'false' , category = None , prefix = None ) : """Find a concept by its prefix from : / vocabulary / autocomplete / { term } Arguments : term : Term prefix to fin...
kwargs = { 'term' : term , 'limit' : limit , 'searchSynonyms' : searchSynonyms , 'searchAbbreviations' : searchAbbreviations , 'searchAcronyms' : searchAcronyms , 'includeDeprecated' : includeDeprecated , 'category' : category , 'prefix' : prefix } kwargs = { k : dumps ( v ) if type ( v ) is dict else v for k , v in kw...
def list_upgrades ( refresh = True , ** kwargs ) : # pylint : disable = W0613 '''Check whether or not an upgrade is available for all packages CLI Example : . . code - block : : bash salt ' * ' pkg . list _ upgrades'''
if refresh : refresh_db ( ) res = _call_brew ( 'outdated --json=v1' ) ret = { } try : data = salt . utils . json . loads ( res [ 'stdout' ] ) except ValueError as err : msg = 'unable to interpret output from "brew outdated": {0}' . format ( err ) log . error ( msg ) raise CommandExecutionError ( msg...
def update_mutation_inputs ( service ) : """Args : service : The service being updated by the mutation Returns : ( list ) : a list of all of the fields availible for the service . Pk is a required field in order to filter the results"""
# grab the default list of field summaries inputs = _service_mutation_summaries ( service ) # visit each field for field in inputs : # if we ' re looking at the id field if field [ 'name' ] == 'id' : # make sure its required field [ 'required' ] = True # but no other field else : # is required ...
def url ( self ) : '''Executes the methods to send request , process the response and then publishes the url .'''
self . get_response ( ) url = self . process_response ( ) if url : logging . info ( 'Your paste has been published at %s' % ( url ) ) return url else : logging . error ( 'Did not get a URL back for the paste' ) raise PasteException ( "No URL for paste" )
def get_edot ( F , mc , e ) : """Compute eccentricity derivative from Taylor et al . ( 2015) : param F : Orbital frequency [ Hz ] : param mc : Chirp mass of binary [ Solar Mass ] : param e : Eccentricity of binary : returns : de / dt"""
# chirp mass mc *= SOLAR2S dedt = - 304 / ( 15 * mc ) * ( 2 * np . pi * mc * F ) ** ( 8 / 3 ) * e * ( 1 + 121 / 304 * e ** 2 ) / ( ( 1 - e ** 2 ) ** ( 5 / 2 ) ) return dedt
def fetch ( self , value_obj = None ) : '''Fetch the next two values'''
val = None try : val = next ( self . __iterable ) except StopIteration : return None if value_obj is None : value_obj = Value ( value = val ) else : value_obj . value = val return value_obj
def parse_range_list ( ranges ) : """Split a string like 2,3-5,8,9-11 into a list of integers . This is intended to ease adding command - line options for dealing with affinity ."""
if not ranges : return [ ] parts = ranges . split ( ',' ) out = [ ] for part in parts : fields = part . split ( '-' , 1 ) if len ( fields ) == 2 : start = int ( fields [ 0 ] ) end = int ( fields [ 1 ] ) out . extend ( range ( start , end + 1 ) ) else : out . append ( int ...
def sar ( patch , cols , splits , divs , ear = False ) : """Calculates an empirical species area or endemics area relationship Parameters divs : str Description of how to divide x _ col and y _ col . See notes . ear : bool If True , calculates an endemics area relationship Returns {1 } Result has 5 co...
def sar_y_func ( spatial_table , all_spp ) : return np . mean ( spatial_table [ 'n_spp' ] ) def ear_y_func ( spatial_table , all_spp ) : endemic_counter = 0 for spp in all_spp : spp_in_cell = [ spp in x for x in spatial_table [ 'spp_set' ] ] spp_n_cells = np . sum ( spp_in_cell ) if ...
def get_push_pop_stack ( ) : """Create pop and push nodes for substacks that are linked . Returns : A push and pop node which have ` push _ func ` and ` pop _ func ` annotations respectively , identifying them as such . They also have a ` pop ` and ` push ` annotation respectively , which links the push nod...
push = copy . deepcopy ( PUSH_STACK ) pop = copy . deepcopy ( POP_STACK ) anno . setanno ( push , 'pop' , pop ) anno . setanno ( push , 'gen_push' , True ) anno . setanno ( pop , 'push' , push ) op_id = _generate_op_id ( ) return push , pop , op_id
def clear_extensions ( self , group = None ) : """Clear all previously registered extensions ."""
if group is None : ComponentRegistry . _registered_extensions = { } return if group in self . _registered_extensions : self . _registered_extensions [ group ] = [ ]
def encode_timeseries_put ( self , tsobj ) : """Fills an TsPutReq message with the appropriate data and metadata from a TsObject . : param tsobj : a TsObject : type tsobj : TsObject : param req : the protobuf message to fill : type req : riak . pb . riak _ ts _ pb2 . TsPutReq"""
req = riak . pb . riak_ts_pb2 . TsPutReq ( ) req . table = str_to_bytes ( tsobj . table . name ) if tsobj . columns : raise NotImplementedError ( "columns are not implemented yet" ) if tsobj . rows and isinstance ( tsobj . rows , list ) : for row in tsobj . rows : tsr = req . rows . add ( ) # NB...
def move_out_8 ( self , session , space , offset , length , data , extended = False ) : """Moves an 8 - bit block of data from local memory to the specified address space and offset . Corresponds to viMoveOut8 * functions of the VISA library . : param session : Unique logical identifier to a session . : param...
raise NotImplementedError
def lower_bound ( fm , nr_subs = None , nr_imgs = None , scale_factor = 1 ) : """Compute the spatial bias lower bound for a fixmat . Input : fm : a fixmat instance nr _ subs : the number of subjects used for the prediction . Defaults to the total number of subjects in the fixmat minus 1 nr _ imgs : the nu...
nr_subs_total = len ( np . unique ( fm . SUBJECTINDEX ) ) if nr_subs is None : nr_subs = nr_subs_total - 1 assert ( nr_subs < nr_subs_total ) # initialize output structure ; every measure gets one dict with # category numbers as keys and numpy - arrays as values sb_scores = [ ] for measure in range ( len ( measures...
def get_fastq_files_props ( self , barcode = None ) : """Returns the DNAnexus file properties for all FASTQ files in the project that match the specified barcode , or all FASTQ files if not barcode is specified . Args : barcode : ` str ` . If set , then only FASTQ file properties for FASTQ files having the sp...
fastqs = self . get_fastq_dxfile_objects ( barcode = barcode ) # FastqNotFound Exception here if no FASTQs found for specified barcode . dico = { } for f in fastqs : # props = dxpy . api . file _ describe ( object _ id = f . id , input _ params = { " fields " : { " properties " : True } } ) [ " properties " ] props...
def get_mining_contracts ( ) : """Get all the mining contracts information available . Returns : This function returns two major dictionaries . The first one contains information about the coins for which mining contracts data is available : coin _ data : { symbol1 : { ' BlockNumber ' : . . . , ' Bloc...
# load data url = build_url ( 'miningcontracts' ) data = load_data ( url ) coin_data = data [ 'CoinData' ] mining_data = data [ 'MiningData' ] return coin_data , mining_data
def _create_new_jobs ( self , job , successor , new_block_id , new_call_stack ) : """Create a list of new VFG jobs for the successor state . : param VFGJob job : The VFGJob instance . : param SimState successor : The succeeding state . : param BlockID new _ block _ id : Block ID for the new VFGJob : param n...
# TODO : basic block stack is probably useless jumpkind = successor . history . jumpkind stmt_idx = successor . scratch . stmt_idx ins_addr = successor . scratch . ins_addr # Make a copy of the state in case we use it later successor_state = successor . copy ( ) successor_addr = successor_state . solver . eval ( succes...
def add_operation_recorder ( self , operation_recorder ) : # pylint : disable = line - too - long """* * Experimental : * * Add an operation recorder to this connection . * New in pywbem 0.12 as experimental . * If the connection already has a recorder with the same class , the request to add the recorder is ...
# noqa : E501 if operation_recorder is None : raise ValueError ( "Invalid value None for new operation recorder" ) for recorder in self . _operation_recorders : # pylint : disable = unidiomatic - typecheck if type ( recorder ) is type ( operation_recorder ) : raise ValueError ( _format ( "Cannot add the...
def set_symbols ( self , symbols , functional = None , sym_potcar_map = None ) : """Initialize the POTCAR from a set of symbols . Currently , the POTCARs can be fetched from a location specified in . pmgrc . yaml . Use pmg config to add this setting . Args : symbols ( [ str ] ) : A list of element symbols ...
del self [ : ] if sym_potcar_map : for el in symbols : self . append ( PotcarSingle ( sym_potcar_map [ el ] ) ) else : for el in symbols : p = PotcarSingle . from_symbol_and_functional ( el , functional ) self . append ( p )
def whoami ( self ) : """Get information about the access token . Official docs : https : / / monzo . com / docs / # authenticating - requests : returns : access token details : rtype : dict"""
endpoint = '/ping/whoami' response = self . _get_response ( method = 'get' , endpoint = endpoint , ) return response . json ( )
def add_set_membership ( self , values , column_name ) : """Append a set membership test , creating a query of the form ' WHERE name IN ( ? , ? . . . ? ) ' . : param values : A list of values , or a subclass of basestring . If this is non - None and non - empty this will add a set membership test to the state...
if values is not None and len ( values ) > 0 : if isinstance ( values , basestring ) : values = [ values ] question_marks = ', ' . join ( [ "%s" ] * len ( values ) ) self . where_clauses . append ( '{0} IN ({1})' . format ( column_name , question_marks ) ) for value in values : self . sq...
def basic_fc_small ( ) : """Small fully connected model ."""
hparams = common_hparams . basic_params1 ( ) hparams . learning_rate = 0.1 hparams . batch_size = 128 hparams . hidden_size = 256 hparams . num_hidden_layers = 2 hparams . initializer = "uniform_unit_scaling" hparams . initializer_gain = 1.0 hparams . weight_decay = 0.0 hparams . dropout = 0.0 return hparams
def into2dBlocks ( arr , n0 , n1 ) : """similar to blockshaped but splits an array into n0 * n1 blocks"""
s0 , s1 = arr . shape b = blockshaped ( arr , s0 // n0 , s1 // n1 ) return b . reshape ( n0 , n1 , * b . shape [ 1 : ] )
def _add_string_to_commastring ( self , field , string ) : # type : ( str , str ) - > bool """Add a string to a comma separated list of strings Args : field ( str ) : Field containing comma separated list string ( str ) : String to add Returns : bool : True if string added or False if string already prese...
if string in self . _get_stringlist_from_commastring ( field ) : return False strings = '%s,%s' % ( self . data . get ( field , '' ) , string ) if strings [ 0 ] == ',' : strings = strings [ 1 : ] self . data [ field ] = strings return True
def joint ( * parsers ) : '''Joint two or more parsers , implements the operator of ` ( + ) ` .'''
@ Parser def joint_parser ( text , index ) : values = [ ] prev_v = None for p in parsers : if prev_v : index = prev_v . index prev_v = v = p ( text , index ) if not v . status : return v values . append ( v ) return Value . combinate ( values ) ret...
def single_qubit_matrix_to_pauli_rotations ( mat : np . ndarray , atol : float = 0 ) -> List [ Tuple [ ops . Pauli , float ] ] : """Implements a single - qubit operation with few rotations . Args : mat : The 2x2 unitary matrix of the operation to implement . atol : A limit on the amount of absolute error intr...
def is_clifford_rotation ( half_turns ) : return near_zero_mod ( half_turns , 0.5 , atol = atol ) def to_quarter_turns ( half_turns ) : return round ( 2 * half_turns ) % 4 def is_quarter_turn ( half_turns ) : return ( is_clifford_rotation ( half_turns ) and to_quarter_turns ( half_turns ) % 2 == 1 ) def is_...
def _getFromTime ( self , atDate = None ) : """Time that the event starts ( in the local time zone ) ."""
return getLocalTime ( self . except_date , self . time_from , self . tz )
def deny ( self , ip ) : """Allow the specified IP to connect . : param ip : The IPv4 or IPv6 address to allow ."""
self . blacklist . append ( ip ) self . whitelist . clear ( )
def pickTextBackgroundColor ( self ) : """Prompts the user to select a text color ."""
clr = QColorDialog . getColor ( self . textBackgroundColor ( ) , self . window ( ) , 'Pick Background Color' ) if clr . isValid ( ) : self . setTextBackgroundColor ( clr )
def x_frame1D ( X , plot_limits = None , resolution = None ) : """Internal helper function for making plots , returns a set of input values to plot as well as lower and upper limits"""
assert X . shape [ 1 ] == 1 , "x_frame1D is defined for one-dimensional inputs" if plot_limits is None : from GPy . core . parameterization . variational import VariationalPosterior if isinstance ( X , VariationalPosterior ) : xmin , xmax = X . mean . min ( 0 ) , X . mean . max ( 0 ) else : ...
def _add_stats_box ( h1 : Histogram1D , ax : Axes , stats : Union [ str , bool ] = "all" ) : """Insert a small legend - like box with statistical information . Parameters stats : " all " | " total " | True What info to display Note Very basic implementation ."""
# place a text box in upper left in axes coords if stats in [ "all" , True ] : text = "Total: {0}\nMean: {1:.2f}\nStd.dev: {2:.2f}" . format ( h1 . total , h1 . mean ( ) , h1 . std ( ) ) elif stats == "total" : text = "Total: {0}" . format ( h1 . total ) else : raise ValueError ( "Invalid stats specificatio...
def workbook_data ( self ) : """return a readable XML form of the data ."""
document = XML ( fn = os . path . splitext ( self . fn ) [ 0 ] + '.xml' , root = Element . workbook ( ) ) shared_strings = [ str ( t . text ) for t in self . xml ( 'xl/sharedStrings.xml' ) . root . xpath ( ".//xl:t" , namespaces = self . NS ) ] for key in self . sheets . keys ( ) : worksheet = self . sheets [ key ]...
def select_from ( self , parent_path ) : """Iterate over all child paths of ` parent _ path ` matched by this selector . This can contain parent _ path itself ."""
path_cls = type ( parent_path ) is_dir = path_cls . is_dir exists = path_cls . exists scandir = parent_path . _accessor . scandir if not is_dir ( parent_path ) : return iter ( [ ] ) return self . _select_from ( parent_path , is_dir , exists , scandir )
def decode ( self , data , delimiter = ';' ) : """Decode a message from command string ."""
try : list_data = data . rstrip ( ) . split ( delimiter ) self . payload = list_data . pop ( ) ( self . node_id , self . child_id , self . type , self . ack , self . sub_type ) = [ int ( f ) for f in list_data ] except ValueError : _LOGGER . warning ( 'Error decoding message from gateway, ' 'bad data re...
def safe_dump ( d , fname , * args , ** kwargs ) : """Savely dump ` d ` to ` fname ` using yaml This method creates a copy of ` fname ` called ` ` fname + ' ~ ' ` ` before saving ` d ` to ` fname ` using : func : ` ordered _ yaml _ dump ` Parameters d : object The object to dump fname : str The path w...
if osp . exists ( fname ) : os . rename ( fname , fname + '~' ) lock = fasteners . InterProcessLock ( fname + '.lck' ) lock . acquire ( ) try : with open ( fname , 'w' ) as f : ordered_yaml_dump ( d , f , * args , ** kwargs ) except : raise finally : lock . release ( )
async def _start_async_tasks ( self ) : """Start asynchronous operations ."""
try : self . udisks = await udiskie . udisks2 . Daemon . create ( ) results = await self . _init ( ) return 0 if all ( results ) else 1 except Exception : traceback . print_exc ( ) return 1 finally : self . mainloop . quit ( )
def answer_inline_query ( self , inline_query_id , results , cache_time = None , is_personal = None , next_offset = None , switch_pm_text = None , switch_pm_parameter = None ) : """Use this method to send answers to an inline query . On success , True is returned . No more than 50 results per query are allowed . ...
return apihelper . answer_inline_query ( self . token , inline_query_id , results , cache_time , is_personal , next_offset , switch_pm_text , switch_pm_parameter )
def get_points ( self ) : """Get the set of points that is used to draw the object . Points are returned in * data * coordinates ."""
if hasattr ( self , 'points' ) : points = self . crdmap . to_data ( self . points ) else : points = [ ] return points
def get_resource ( self , arguments ) : """Gets the resource requested in the arguments"""
attribute_name = arguments [ '<attribute_name>' ] limit = arguments [ '--limit' ] page = arguments [ '--page' ] date_min = arguments [ '--date_min' ] date_max = arguments [ '--date_max' ] # feed in the config we have , and let the Exist class figure out the best # way to authenticate exist = Exist ( self . client_id , ...
def load_plugins ( self ) : """Load plugins from ` dyndnsc . plugins . builtin ` ."""
from dyndnsc . plugins . builtin import PLUGINS for plugin in PLUGINS : self . add_plugin ( plugin ( ) ) super ( BuiltinPluginManager , self ) . load_plugins ( )
def mouseDoubleClickEvent ( self , event ) : """Creates and shows editor for stimulus ( test ) selected"""
if event . button ( ) == QtCore . Qt . LeftButton : index = self . indexAt ( event . pos ( ) ) if index . isValid ( ) : selectedStimModel = self . model ( ) . data ( index , QtCore . Qt . UserRole ) self . stimEditor = selectedStimModel . showEditor ( ) self . stimEditor . show ( )
def user_delete ( user_id = None , name = None , profile = None , ** connection_args ) : '''Delete a user ( keystone user - delete ) CLI Examples : . . code - block : : bash salt ' * ' keystone . user _ delete c965f79c4f864eaaa9c3b41904e67082 salt ' * ' keystone . user _ delete user _ id = c965f79c4f864eaaa...
kstone = auth ( profile , ** connection_args ) if name : for user in kstone . users . list ( ) : if user . name == name : user_id = user . id break if not user_id : return { 'Error' : 'Unable to resolve user id' } kstone . users . delete ( user_id ) ret = 'User ID {0} deleted' . ...
def capture_screenshot ( self , name ) : """Capture screenshot and save it in screenshots folder : param name : screenshot name suffix : returns : screenshot path"""
filename = '{0:0=2d}_{1}' . format ( DriverWrappersPool . screenshots_number , name ) filename = '{}.png' . format ( get_valid_filename ( filename ) ) filepath = os . path . join ( DriverWrappersPool . screenshots_directory , filename ) if not os . path . exists ( DriverWrappersPool . screenshots_directory ) : os ....
def _restore_file_attributes ( self ) : # type : ( Descriptor ) - > None """Restore file attributes for file : param Descriptor self : this"""
if ( not self . _restore_file_properties . attributes or self . _ase . file_attributes is None ) : return # set file uid / gid and mode if blobxfer . util . on_windows ( ) : # noqa # TODO not implemented yet pass else : self . final_path . chmod ( int ( self . _ase . file_attributes . mode , 8 ) ) if os...
def alignment_display ( self ) : """Fills screen with uppercase E ' s for screen focus and alignment ."""
self . dirty . update ( range ( self . lines ) ) for y in range ( self . lines ) : for x in range ( self . columns ) : self . buffer [ y ] [ x ] = self . buffer [ y ] [ x ] . _replace ( data = "E" )
def generichash_blake2b_final ( state ) : """Finalize the blake2b hash state and return the digest . : param state : a initialized Blake2bState object as returned from : py : func : ` . crypto _ generichash _ blake2b _ init ` : type state : : py : class : ` . Blake2State ` : return : the blake2 digest of th...
ensure ( isinstance ( state , Blake2State ) , 'State must be a Blake2State object' , raising = exc . TypeError ) _digest = ffi . new ( "unsigned char[]" , crypto_generichash_BYTES_MAX ) rc = lib . crypto_generichash_blake2b_final ( state . _statebuf , _digest , state . digest_size ) ensure ( rc == 0 , 'Unexpected failu...
def _set_intf_ldp_sync ( self , v , load = False ) : """Setter method for intf _ ldp _ sync , mapped from YANG variable / routing _ system / interface / ve / ip / interface _ vlan _ ospf _ conf / ospf1 / intf _ ldp _ sync ( enumeration ) If this variable is read - only ( config : false ) in the source YANG file...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'enable' : { 'value' : 1 } , u'disable' : { 'value' : 2 } } , ) , is_leaf = True , yang_name = "intf-ldp-sync" , rest_name = "ld...
def populate ( self , size , names_library = None , reuse_names = False , random_branches = False , branch_range = ( 0 , 1 ) , support_range = ( 0 , 1 ) ) : """Generates a random topology by populating current node . : argument None names _ library : If provided , names library ( list , set , dict , etc . ) wil...
NewNode = self . __class__ if len ( self . children ) > 1 : connector = NewNode ( ) for ch in self . get_children ( ) : ch . detach ( ) connector . add_child ( child = ch ) root = NewNode ( ) self . add_child ( child = connector ) self . add_child ( child = root ) else : root = s...
def _get_supported_for_any_abi ( version = None , platform = None , impl = None , force_manylinux = False ) : """Generates supported tags for unspecified ABI types to support more intuitive cross - platform resolution ."""
unique_tags = { tag for abi in _gen_all_abis ( impl , version ) for tag in _get_supported ( version = version , platform = platform , impl = impl , abi = abi , force_manylinux = force_manylinux ) } return list ( unique_tags )
def loggray ( x , a , b ) : """Auxiliary function that specifies the logarithmic gray scale . a and b are the cutoffs ."""
linval = 10.0 + 990.0 * ( x - float ( a ) ) / ( b - a ) return ( np . log10 ( linval ) - 1.0 ) * 0.5 * 255.0
async def send ( self , request : Request , ** kwargs ) -> Response : """Send request object according to configuration . : param Request request : The request object to be sent ."""
if request . context is None : # Should not happen , but make mypy happy and does not hurt request . context = self . build_context ( ) if request . context . session is not self . driver . session : kwargs [ 'session' ] = request . context . session return Response ( request , await self . driver . send ( requ...
def get_stack_trace_with_labels ( self , depth = 16 , bMakePretty = True ) : """Tries to get a stack trace for the current function . Only works for functions with standard prologue and epilogue . @ type depth : int @ param depth : Maximum depth of stack trace . @ type bMakePretty : bool @ param bMakePret...
try : trace = self . __get_stack_trace ( depth , True , bMakePretty ) except Exception : trace = ( ) if not trace : trace = self . __get_stack_trace_manually ( depth , True , bMakePretty ) return trace
def get_info ( self , sm_id ) : """Extract a CompositionInfo instance containing the single model of index ` sm _ id ` ."""
sm = self . source_models [ sm_id ] num_samples = sm . samples if self . num_samples else 0 return self . __class__ ( self . gsim_lt , self . seed , num_samples , [ sm ] , self . tot_weight )
def present ( version , name , port = None , encoding = None , locale = None , datadir = None , allow_group_access = None , data_checksums = None , wal_segsize = None ) : '''Ensure that the named cluster is present with the specified properties . For more information about all of these options see man pg _ create...
msg = 'Cluster {0}/{1} is already present' . format ( version , name ) ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : msg } if __salt__ [ 'postgres.cluster_exists' ] ( version , name ) : # check cluster config is correct infos = __salt__ [ 'postgres.cluster_list' ] ( verbose = True ) in...
def create_similar ( self , content , width , height ) : """Create a new surface that is as compatible as possible for uploading to and the use in conjunction with this surface . For example the new surface will have the same fallback resolution and : class : ` FontOptions ` . Generally , the new surface wi...
return Surface . _from_pointer ( cairo . cairo_surface_create_similar ( self . _pointer , content , width , height ) , incref = False )
def bfill ( self , dim , limit = None ) : '''Fill NaN values by propogating values backward * Requires bottleneck . * Parameters dim : str Specifies the dimension along which to propagate values when filling . limit : int , default None The maximum number of consecutive NaN values to backward fill . I...
from . missing import bfill return bfill ( self , dim , limit = limit )
def unpack_fraction ( num : str ) -> str : """Returns unpacked fraction string 5/2 - > 2 1/2"""
nums = [ int ( n ) for n in num . split ( '/' ) if n ] if len ( nums ) == 2 and nums [ 0 ] > nums [ 1 ] : over = nums [ 0 ] // nums [ 1 ] rem = nums [ 0 ] % nums [ 1 ] return f'{over} {rem}/{nums[1]}' return num
def create_str ( help_string = NO_HELP , default = NO_DEFAULT ) : # type : ( str , Union [ str , NO _ DEFAULT _ TYPE ] ) - > str """Create a string parameter : param help _ string : : param default : : return :"""
# noinspection PyTypeChecker return ParamFunctions ( help_string = help_string , default = default , type_name = "str" , function_s2t = convert_string_to_string , function_t2s = convert_string_to_string , )
def createNetwork ( self , data , headers = None , query_params = None , content_type = "application/json" ) : """Create a new network It is method for POST / network"""
uri = self . client . base_url + "/network" return self . client . post ( uri , data , headers , query_params , content_type )
def delete ( self , stream , start_time , end_time , start_id = None , namespace = None ) : """Delete events in the stream with name ` stream ` that occurred between ` start _ time ` and ` end _ time ` ( both inclusive ) . An optional ` start _ id ` allows the client to delete events starting from after an ID r...
if isinstance ( start_time , types . StringTypes ) : start_time = parse ( start_time ) if isinstance ( end_time , types . StringTypes ) : end_time = parse ( end_time ) if isinstance ( start_time , datetime ) : start_time = datetime_to_kronos_time ( start_time ) if isinstance ( end_time , datetime ) : en...
def get_security_groups ( conn , vm_ ) : '''Return a list of security groups to use , defaulting to [ ' default ' ]'''
securitygroup_enabled = config . get_cloud_config_value ( 'securitygroup_enabled' , vm_ , __opts__ , default = True ) if securitygroup_enabled : return config . get_cloud_config_value ( 'securitygroup' , vm_ , __opts__ , default = [ 'default' ] ) else : return False
def posterior_to_xarray ( self ) : """Extract posterior samples from fit ."""
posterior = self . posterior posterior_model = self . posterior_model # filter posterior _ predictive and log _ likelihood posterior_predictive = self . posterior_predictive if posterior_predictive is None : posterior_predictive = [ ] elif isinstance ( posterior_predictive , str ) : posterior_predictive = [ pos...
def serialize_compound ( self , tag ) : """Return the literal representation of a compound tag ."""
separator , fmt = self . comma , '{{{}}}' with self . depth ( ) : if self . should_expand ( tag ) : separator , fmt = self . expand ( separator , fmt ) return fmt . format ( separator . join ( f'{self.stringify_compound_key(key)}{self.colon}{self.serialize(value)}' for key , value in tag . items ( ) ) )
def _get_mapreduce_spec ( cls , mr_id ) : """Get Mapreduce spec from mr id ."""
key = 'GAE-MR-spec: %s' % mr_id spec_json = memcache . get ( key ) if spec_json : return cls . from_json ( spec_json ) state = MapreduceState . get_by_job_id ( mr_id ) spec = state . mapreduce_spec spec_json = spec . to_json ( ) memcache . set ( key , spec_json ) return spec
def process_shells ( self , shells ) : """Processing a list of shells ."""
result = { 'success' : True , 'output' : [ ] } if self . parallel and len ( shells ) > 1 : result = self . process_shells_parallel ( shells ) elif len ( shells ) > 0 : result = self . process_shells_ordered ( shells ) return result
def _find_glob_matches ( in_files , metadata ) : """Group files that match by globs for merging , rather than by explicit pairs ."""
reg_files = copy . deepcopy ( in_files ) glob_files = [ ] for glob_search in [ x for x in metadata . keys ( ) if "*" in x ] : cur = [ ] for fname in in_files : if fnmatch . fnmatch ( fname , "*/%s" % glob_search ) : cur . append ( fname ) reg_files . remove ( fname ) assert c...
def _create_chain_entry ( user_id , task_id , task_class , args , kwargs , callbacks , parent = None ) : """Create and update status records for a new : py : class : ` UserTaskMixin ` in a Celery chain ."""
LOGGER . debug ( task_class ) if issubclass ( task_class . __class__ , UserTaskMixin ) : arguments_dict = task_class . arguments_as_dict ( * args , ** kwargs ) name = task_class . generate_name ( arguments_dict ) total_steps = task_class . calculate_total_steps ( arguments_dict ) parent_name = kwargs . ...
def safe_makedirs ( path ) : """A safe function for creating a directory tree ."""
try : os . makedirs ( path ) except OSError as err : if err . errno == errno . EEXIST : if not os . path . isdir ( path ) : raise else : raise
def set_outbound_cipher ( self , block_engine , block_size , mac_engine , mac_size , mac_key , sdctr = False , ) : """Switch outbound data cipher ."""
self . __block_engine_out = block_engine self . __sdctr_out = sdctr self . __block_size_out = block_size self . __mac_engine_out = mac_engine self . __mac_size_out = mac_size self . __mac_key_out = mac_key self . __sent_bytes = 0 self . __sent_packets = 0 # wait until the reset happens in both directions before clearin...
def add_path ( self , path , base = None , index = None , create = False ) : '''Add a new path to the list of search paths . Return False if it does not exist . : param path : The new search path . Relative paths are turned into an absolute and normalized form . If the path looks like a file ( not ending in...
base = os . path . abspath ( os . path . dirname ( base or self . base ) ) path = os . path . abspath ( os . path . join ( base , os . path . dirname ( path ) ) ) path += os . sep if path in self . path : self . path . remove ( path ) if create and not os . path . isdir ( path ) : os . mkdirs ( path ) if index ...
def init ( config , workdir = None , logfile = None , loglevel = logging . INFO , ** kwargs ) : """Initialize the Lago environment Args : config ( str ) : Path to LagoInitFile workdir ( str ) : Path to initalize the workdir , defaults to " $ PWD / . lago " * * kwargs ( dict ) : Pass arguments to : func : ` ...
setup_sdk_logging ( logfile , loglevel ) defaults = lago_config . get_section ( 'init' ) if workdir is None : workdir = os . path . abspath ( '.lago' ) defaults [ 'workdir' ] = workdir defaults [ 'virt_config' ] = config defaults . update ( kwargs ) workdir , prefix = cmd . do_init ( ** defaults ) return SDK ( work...
def parse_value ( cls , value : int , default : T = None ) -> T : """Parse specified value for IntEnum ; return default if not found ."""
return next ( ( item for item in cls if value == item . value ) , default )
def add ( self , v ) : "Add an individual to the population"
self . population . append ( v ) self . _current_popsize += 1 v . position = len ( self . _hist ) self . _hist . append ( v ) self . bsf = v self . estopping = v self . _density += self . get_density ( v )
def _write ( self , _new = False ) : """Writes the values of the attributes to the datastore . This method also creates the indices and saves the lists associated to the object ."""
pipeline = self . db . pipeline ( ) self . _create_membership ( pipeline ) self . _update_indices ( pipeline ) h = { } # attributes for k , v in self . attributes . iteritems ( ) : if isinstance ( v , DateTimeField ) : if v . auto_now : setattr ( self , k , datetime . now ( ) ) if v . au...
def _repaint ( self , drawing_context : DrawingContext . DrawingContext ) : """Repaint the canvas item . This will occur on a thread ."""
# canvas size canvas_width = self . canvas_size . width canvas_height = self . canvas_size . height with drawing_context . saver ( ) : if self . __color_map_data is not None : rgba_image = numpy . empty ( ( 4 , ) + self . __color_map_data . shape [ : - 1 ] , dtype = numpy . uint32 ) Image . get_rgb_...
def Print ( self , output_writer ) : """Prints a human readable version of the filter . Args : output _ writer ( CLIOutputWriter ) : output writer ."""
if self . _filters : output_writer . Write ( 'Filters:\n' ) for file_entry_filter in self . _filters : file_entry_filter . Print ( output_writer )
def _create_initial_epsf ( self , stars ) : """Create an initial ` EPSFModel ` object . The initial ePSF data are all zeros . If ` ` shape ` ` is not specified , the shape of the ePSF data array is determined from the shape of the input ` ` stars ` ` and the oversampling factor . If the size is even along a...
oversampling = self . oversampling shape = self . shape # define the ePSF shape if shape is not None : shape = np . atleast_1d ( shape ) . astype ( int ) if len ( shape ) == 1 : shape = np . repeat ( shape , 2 ) else : x_shape = np . int ( np . ceil ( stars . _max_shape [ 1 ] * oversampling [ 0 ] ) ...
def enable_rights ( self ) : """Enables rights management provided by : class : ` fatbotslim . handlers . RightsHandler ` ."""
if self . rights is None : handler_instance = RightsHandler ( self ) self . handlers . insert ( len ( self . default_handlers ) , handler_instance )
def parse_uri ( self , text : str ) -> URIRef : """Parse input text into URI : param text : can be one of 1 . URI , directly return 2 . prefix : name , query namespace for prefix , return expanded URI 3 . name , use default namespace to expand it and return it : return : URIRef"""
if self . check_uriref ( text ) : return self . check_uriref ( text ) elif isinstance ( text , str ) : text = text . strip ( ) m = URI_ABBR_PATTERN . match ( text ) if m : prefix , name = m . groups ( ) base = self . store . namespace ( prefix if prefix else '' ) if not base : ...
def payments_billing ( request , template = 'django_braintree/payments_billing.html' ) : """Renders both the past payments that have occurred on the users credit card , but also their CC information on file ( if any )"""
d = { } if request . method == 'POST' : # Credit Card is being changed / updated by the user form = UserCCDetailsForm ( request . user , True , request . POST ) if form . is_valid ( ) : response = form . save ( ) if response . is_success : messages . add_message ( request , messages ...
def decompose_surface ( obj , ** kwargs ) : """Decomposes the surface into Bezier surface patches of the same degree . This operation does not modify the input surface , instead it returns the surface patches . Keyword Arguments : * ` ` find _ span _ func ` ` : FindSpan implementation . * Default : * : func :...
def decompose ( srf , idx , split_func_list , ** kws ) : srf_list = [ ] knots = srf . knotvector [ idx ] [ srf . degree [ idx ] + 1 : - ( srf . degree [ idx ] + 1 ) ] while knots : knot = knots [ 0 ] srfs = split_func_list [ idx ] ( srf , param = knot , ** kws ) srf_list . append ( s...
def DbGetDeviceServerClassList ( self , argin ) : """Get list of Tango classes for a device server : param argin : device server process name : type : tango . DevString : return : list of classes for this device server : rtype : tango . DevVarStringArray"""
self . _log . debug ( "In DbGetDeviceServerClassList()" ) argin = replace_wildcard ( argin ) return self . db . get_server_class_list ( argin )
def drag_and_drop ( self , source_element , target_element , params = None ) : """Drag source element and drop at target element . Note : Target can either be a WebElement or a list with x - and y - coordinates ( integers ) : param source _ element : WebElement instance : param target _ element : WebElement i...
if not isinstance ( source_element , WebElement ) : source_element = self . get_visible_element ( source_element , params [ 'source' ] if params else None ) if not isinstance ( target_element , WebElement ) and not isinstance ( target_element , list ) : source_element = self . get_visible_element ( target_eleme...
def print_frame ( self , x : int , y : int , width : int , height : int , string : str = "" , clear : bool = True , bg_blend : int = tcod . constants . BKGND_DEFAULT , ) -> None : """Draw a framed rectangle with optional text . This uses the default background color and blend mode to fill the rectangle and the ...
self . __deprecate_defaults ( "draw_frame" , bg_blend ) string = _fmt ( string ) if string else ffi . NULL lib . TCOD_console_printf_frame ( self . console_c , x , y , width , height , clear , bg_blend , string )
def importer ( name ) : """Import by name"""
c1 , c2 = modsplit ( name ) module = importlib . import_module ( c1 ) return getattr ( module , c2 )
def get_schema_path ( self , path ) : """Compute the schema ' s absolute path from a schema relative path . : param path : relative path of the schema . : raises invenio _ jsonschemas . errors . JSONSchemaNotFound : If no schema was found in the specified path . : returns : The absolute path ."""
if path not in self . schemas : raise JSONSchemaNotFound ( path ) return os . path . join ( self . schemas [ path ] , path )
def incrby ( self , type , offset , increment ) : """Increments or decrements ( if a negative increment is given ) the specified bit field and returns the new value ."""
self . _command_stack . extend ( [ 'INCRBY' , type , offset , increment ] ) return self
def set_configuration ( self , min_value , max_value , rotation = "cw" , scale = "linear" , ticks = 12 , min_position = 0 , max_position = 360 ) : """: param min _ value : Any number : param max _ value : Any number above min _ value : param rotation : ( String ) cw or ccw : param scale : ( String ) linear or...
_json = { "min_value" : min_value , "max_value" : max_value , "rotation" : rotation , "scale_type" : scale , "num_ticks" : ticks , "min_position" : min_position , "max_position" : max_position } dial_config = { "dial_configuration" : _json } self . _update_state_from_response ( self . parent . set_dial ( dial_config , ...
def _start_container ( self , container , tool_d , s_containers , f_containers ) : """Start container that was passed in and return status"""
# use section to add info to manifest section = tool_d [ container ] [ 'section' ] del tool_d [ container ] [ 'section' ] manifest = Template ( self . manifest ) try : # try to start an existing container first c = self . d_client . containers . get ( container ) c . start ( ) s_containers . append ( contai...
def cmd ( send , msg , args ) : """Googles something . Syntax : { command } < term >"""
if not msg : send ( "Google what?" ) return key = args [ 'config' ] [ 'api' ] [ 'googleapikey' ] cx = args [ 'config' ] [ 'api' ] [ 'googlesearchid' ] data = get ( 'https://www.googleapis.com/customsearch/v1' , params = { 'key' : key , 'cx' : cx , 'q' : msg } ) . json ( ) if 'items' not in data : send ( "Go...
def _get_instance ( self ) : """Return the instance matching the running _ instance _ id ."""
try : instance = self . compute . virtual_machines . get ( self . running_instance_id , self . running_instance_id , expand = 'instanceView' ) except Exception as error : raise AzureCloudException ( 'Unable to retrieve instance: {0}' . format ( error ) ) return instance
def pmrapmdec_to_pmllpmbb ( pmra , pmdec , ra , dec , degree = False , epoch = 2000.0 ) : """NAME : pmrapmdec _ to _ pmllpmbb PURPOSE : rotate proper motions in ( ra , dec ) into proper motions in ( l , b ) INPUT : pmra - proper motion in ra ( multplied with cos ( dec ) ) [ mas / yr ] pmdec - proper mot...
theta , dec_ngp , ra_ngp = get_epoch_angles ( epoch ) # Whether to use degrees and scalar input is handled by decorators dec [ dec == dec_ngp ] += 10. ** - 16 # deal w / pole . sindec_ngp = nu . sin ( dec_ngp ) cosdec_ngp = nu . cos ( dec_ngp ) sindec = nu . sin ( dec ) cosdec = nu . cos ( dec ) sinrarangp = nu . sin (...
def GetClientsByStatus ( self ) : """Get all the clients in a dict of { status : [ client _ list ] } ."""
started = self . GetClients ( ) completed = self . GetCompletedClients ( ) outstanding = started - completed return { "STARTED" : started , "COMPLETED" : completed , "OUTSTANDING" : outstanding }
def update ( self , document_id , update_spec , namespace , timestamp ) : """Apply updates given in update _ spec to the document whose id matches that of doc ."""
document = self . doc_dict [ document_id ] . doc updated = self . apply_update ( document , update_spec ) if "_id" in updated : updated . pop ( "_id" ) updated [ self . unique_key ] = document_id self . upsert ( updated , namespace , timestamp ) return updated
def BE_vs_clean_SE ( self , delu_dict , delu_default = 0 , plot_eads = False , annotate_monolayer = True , JPERM2 = False ) : """For each facet , plot the clean surface energy against the most stable binding energy . Args : delu _ dict ( Dict ) : Dictionary of the chemical potentials to be set as constant ....
plt = pretty_plot ( width = 8 , height = 7 ) for hkl in self . all_slab_entries . keys ( ) : for clean_entry in self . all_slab_entries [ hkl ] . keys ( ) : all_delu_dict = self . set_all_variables ( delu_dict , delu_default ) if self . all_slab_entries [ hkl ] [ clean_entry ] : clean_se...
def get ( self , path , strict ) : """Gets the item for ` path ` . If ` strict ` is true , this method returns ` None ` when matching path is not found . Otherwise , this returns the result item of prefix searching . : param path : Path to get : param strict : Searching mode : type path : list : type st...
item , pathinfo = self . _get ( path , strict ) if item is None : if strict : return None , pathinfo else : return self . _item , pathinfo else : return item , pathinfo
def detach_volume ( self , volume ) : """Detach an EBS volume from this server : param volume : EBS Volume to detach : type volume : boto . ec2 . volume . Volume"""
if hasattr ( volume , "id" ) : volume_id = volume . id else : volume_id = volume return self . ec2 . detach_volume ( volume_id = volume_id , instance_id = self . instance_id )
def listdir ( self , pattern = None ) : """D . listdir ( ) - > List of items in this directory . Use : meth : ` files ` or : meth : ` dirs ` instead if you want a listing of just files or just subdirectories . The elements of the list are Path objects . With the optional ` pattern ` argument , this only lis...
if pattern is None : pattern = '*' return [ self / child for child in map ( self . _always_unicode , os . listdir ( self ) ) if self . _next_class ( child ) . fnmatch ( pattern ) ]
def wait ( self , * , block = True , timeout = None ) : """Signal that a party has reached the barrier . Warning : Barrier blocking is currently only supported by the stub and Redis backends . Warning : Re - using keys between blocking calls may lead to undefined behaviour . Make sure your barrier keys ...
cleared = not self . backend . decr ( self . key , 1 , 1 , self . ttl ) if cleared : self . backend . wait_notify ( self . key_events , self . ttl ) return True if block : return self . backend . wait ( self . key_events , timeout ) return False
def decrypt ( self , ciphertext , encoder = encoding . RawEncoder ) : """Decrypts the ciphertext using the ephemeral public key enclosed in the ciphertext and the SealedBox private key , returning the plaintext message . : param ciphertext : [ : class : ` bytes ` ] The encrypted message to decrypt : param e...
# Decode our ciphertext ciphertext = encoder . decode ( ciphertext ) plaintext = nacl . bindings . crypto_box_seal_open ( ciphertext , self . _public_key , self . _private_key , ) return plaintext