signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def duplicate ( self ) : '''Returns a copy of the current treatment . @ returns : Treatment .'''
return self . __class__ ( name = self . name , description = self . description , rate_type = self . rate_type , rate = self . rate , interval = self . interval )
def get_bank_name ( clabe : str ) -> str : """Regresa el nombre del banco basado en los primeros 3 digitos https : / / es . wikipedia . org / wiki / CLABE # D . C3 . ADgito _ control"""
code = clabe [ : 3 ] try : bank_name = BANK_NAMES [ BANKS [ code ] ] except KeyError : raise ValueError ( f"Ningún banco tiene código '{code}'" ) else : return bank_name
def read ( self , size = None ) : '''Read at most size bytes , returned as a string . If the size argument is negative or omitted , read until EOF is reached . Notice that when in non - blocking mode , less data than what was requested may be returned , even if no size parameter was given .'''
if self . closed : raise ValueError ( 'File closed' ) if self . _mode in _allowed_write : raise Exception ( 'File opened for write only' ) if not self . _done_header : self . _read_header ( ) # The encrypted file has been entirely read , so return as much as they want # and remove the returned portion from ...
def _get_cairo_bmp ( self , mdc , key , rect , is_selected , view_frozen ) : """Returns a wx . Bitmap of cell key in size rect"""
bmp = wx . EmptyBitmap ( rect . width , rect . height ) mdc . SelectObject ( bmp ) mdc . SetBackgroundMode ( wx . SOLID ) mdc . SetBackground ( wx . WHITE_BRUSH ) mdc . Clear ( ) mdc . SetDeviceOrigin ( 0 , 0 ) context = wx . lib . wxcairo . ContextFromDC ( mdc ) context . save ( ) # Zoom context zoom = self . zoom con...
def __init_from_np2d ( self , mat , params_str , ref_dataset ) : """Initialize data from a 2 - D numpy matrix ."""
if len ( mat . shape ) != 2 : raise ValueError ( 'Input numpy.ndarray must be 2 dimensional' ) self . handle = ctypes . c_void_p ( ) if mat . dtype == np . float32 or mat . dtype == np . float64 : data = np . array ( mat . reshape ( mat . size ) , dtype = mat . dtype , copy = False ) else : # change non - float...
def inspect_data ( self , capacity = None , voltage = None , err_est = False , diff_est = False ) : """check and inspect the data"""
logging . debug ( "inspecting the data" ) if capacity is None : capacity = self . capacity if voltage is None : voltage = self . voltage if capacity is None or voltage is None : raise NullData self . len_capacity = len ( capacity ) self . len_voltage = len ( voltage ) if self . len_capacity <= 1 : raise...
def get ( self , key = None , ** kwargs ) : """Ensures that only one result is returned from DB and raises an exception otherwise . Can work in 3 different way . - If no argument is given , only does " ensuring about one and only object " job . - If key given as only argument , retrieves the object from DB . ...
clone = copy . deepcopy ( self ) # If we are in a slice , adjust the start and rows if self . _start : clone . adapter . set_params ( start = self . _start ) if self . _rows : clone . adapter . set_params ( rows = self . _rows ) if key : data , key = clone . adapter . get ( key ) elif kwargs : data , ke...
def DisableInterfaces ( interface ) : """Tries to disable an interface . Only works on Vista and 7. Args : interface : Name of the interface to disable . Returns : res which is a tuple of ( stdout , stderr , exit _ status , time _ taken ) ."""
set_tested_versions = [ 'vista' , '2008' ] set_args = [ '/c' , 'netsh' , 'set' , 'interface' , interface , 'DISABLED' ] host_version = platform . platform ( ) . lower ( ) for version in set_tested_versions : if host_version . find ( version ) != - 1 : # pylint : disable = undefined - variable res = client_u...
def _fromfile ( self , fh ) : """Initialize instance from open file ."""
fh . seek ( 0 ) data = fh . read ( 4096 ) if ( len ( data ) < 7 ) or not ( b'0' < data [ 1 : 2 ] < b'8' ) : raise ValueError ( "Not a Netpbm file:\n%s" % data [ : 32 ] ) try : self . _read_pam_header ( data ) except Exception : try : self . _read_pnm_header ( data ) except Exception : ra...
def main ( ) : """This is the mainline . It first invokes the pipermail archiver to add the message to the archive , then calls the function above to do whatever with the archived message after it ' s URL and path are known ."""
listname = sys . argv [ 2 ] hostname = sys . argv [ 1 ] # We must get the list unlocked here because it is already locked in # ArchRunner . This is safe because we aren ' t actually changing our list # object . ArchRunner ' s lock plus pipermail ' s archive lock will prevent # any race conditions . mlist = MailList . M...
def XML ( content , source = None ) : """Parses the XML text using the ET . XML function , but handling the ParseError in a user - friendly way ."""
try : tree = ET . XML ( content ) except ET . ParseError as err : x_parse_error ( err , content , source ) return tree
def container ( self , node , elem , module , path ) : """Create a sample container element and proceed with its children ."""
nel , newm , path = self . sample_element ( node , elem , module , path ) if path is None : return if self . annots : pres = node . search_one ( "presence" ) if pres is not None : nel . append ( etree . Comment ( " presence: %s " % pres . arg ) ) self . process_children ( node , nel , newm , path )
def _xml_to_dict ( self , element ) : """Take an XML element , iterate over it and build a dict : param element : An xml . etree . ElementTree . Element , or a list of the same : returns : A dictionary"""
return_dict = { } for el in element : return_dict [ el . tag ] = None children = el . getchildren ( ) if children : return_dict [ el . tag ] = self . _xml_to_dict ( children ) else : return_dict [ el . tag ] = el . text return return_dict
def any ( * validators ) : """If any of the specified validators pass the validation succeeds"""
def validate_any ( fields ) : errors = { } for validator in validators : validation_errors = validator ( fields ) if not validation_errors : return errors . update ( validation_errors ) return errors validate_any . __doc__ = " or " . join ( validator . __doc__ for validat...
def _call ( self , x , out = None ) : """Return ` ` self ( x [ , out ] ) ` ` ."""
if self . domain . is_real : return self . _call_real ( x , out ) elif self . domain . is_complex : result_parts = [ self . _call_real ( x . real , getattr ( out , 'real' , None ) ) , self . _call_real ( x . imag , getattr ( out , 'imag' , None ) ) ] if out is None : out = self . range . element ( )...
def vector_angle ( pairs ) : """Find the angles between pairs of unit vectors . Parameters pairs : ( n , 2 , 3 ) float Unit vector pairs Returns angles : ( n , ) float Angles between vectors in radians"""
pairs = np . asanyarray ( pairs , dtype = np . float64 ) if len ( pairs ) == 0 : return np . array ( [ ] ) elif util . is_shape ( pairs , ( 2 , 3 ) ) : pairs = pairs . reshape ( ( - 1 , 2 , 3 ) ) elif not util . is_shape ( pairs , ( - 1 , 2 , ( 2 , 3 ) ) ) : raise ValueError ( 'pairs must be (n,2,(2|3))!' )...
def fingerprint_correlation ( P , obs1 , obs2 = None , tau = 1 , k = None , ncv = None ) : r"""Compute dynamical fingerprint crosscorrelation . The dynamical fingerprint autocorrelation is the timescale amplitude spectrum of the autocorrelation of the given observables under the action of the dynamics P Par...
return fingerprint ( P , obs1 , obs2 = obs2 , tau = tau , k = k , ncv = ncv )
def parse_host ( entity , default_port = DEFAULT_PORT ) : """Validates a host string Returns a 2 - tuple of host followed by port where port is default _ port if it wasn ' t specified in the string . : Parameters : - ` entity ` : A host or host : port string where host could be a hostname or IP address . ...
host = entity port = default_port if entity [ 0 ] == '[' : host , port = parse_ipv6_literal_host ( entity , default_port ) elif entity . endswith ( ".sock" ) : return entity , default_port elif entity . find ( ':' ) != - 1 : if entity . count ( ':' ) > 1 : raise ValueError ( "Reserved characters suc...
async def write_deal ( self , ** params ) : """Writes deal to database Accepts : - cid - access _ type - buyer public key - seller public key - price - coinid"""
if params . get ( "message" ) : params = json . loads ( params . get ( "message" , "{}" ) ) if not params : return { "error" : 400 , "reason" : "Missed required fields" } cid = int ( params . get ( "cid" , 0 ) ) access_type = params . get ( "access_type" ) buyer = params . get ( "buyer" ) seller = params . get ...
def shakemap_contour ( shakemap_layer_path , output_file_path = '' , active_band = 1 ) : """Creating contour from a shakemap layer . : param shakemap _ layer _ path : The shake map raster layer path . : type shakemap _ layer _ path : basestring : param output _ file _ path : The path where the contour will be...
# Set output path if not output_file_path : output_file_path = unique_filename ( suffix = '.shp' , dir = temp_dir ( ) ) output_directory = os . path . dirname ( output_file_path ) output_file_name = os . path . basename ( output_file_path ) output_base_name = os . path . splitext ( output_file_name ) [ 0 ] # Based ...
def divide_work ( list_of_indexes , batch_size ) : """Given a sequential list of indexes split them into num _ parts . : param list _ of _ indexes : [ int ] list of indexes to be divided up : param batch _ size : number of items to put in batch ( not exact obviously ) : return : [ ( int , int ) ] list of ( in...
grouped_indexes = [ list_of_indexes [ i : i + batch_size ] for i in range ( 0 , len ( list_of_indexes ) , batch_size ) ] return [ ( batch [ 0 ] , len ( batch ) ) for batch in grouped_indexes ]
def reverse_colors ( self ) : """Flips the foreground and background colors ."""
self . _bgcolor , self . _fgcolor = self . _fgcolor , self . _bgcolor
def _loopreport ( self ) : '''Loop over the report progress'''
while 1 : eventlet . sleep ( 0.2 ) ac2popenlist = { } for action in self . session . _actions : for popen in action . _popenlist : if popen . poll ( ) is None : lst = ac2popenlist . setdefault ( action . activity , [ ] ) lst . append ( popen ) if n...
def publishToMyself ( self , roomId , name , data ) : """Publish to only myself"""
self . publishToRoom ( roomId , name , data , [ self ] )
def get ( self , reg , ty ) : """Load a value from a machine register into a VEX temporary register . All values must be loaded out of registers before they can be used with operations , etc and stored back into them when the instruction is over . See Put ( ) . : param reg : Register number as an integer , or...
offset = self . lookup_register ( self . irsb_c . irsb . arch , reg ) if offset == self . irsb_c . irsb . arch . ip_offset : return self . constant ( self . addr , ty ) rdt = self . irsb_c . rdreg ( offset , ty ) return VexValue ( self . irsb_c , rdt )
def col_iter ( self ) : """Get an iterator over all columns in the Sudoku"""
for k in utils . range_ ( self . side ) : yield self . col ( k )
def added ( self , context ) : """Ingredient method called before anything else ."""
context . ansi = ANSIFormatter ( self . _enable ) context . aprint = context . ansi . aprint
def is_requirement ( line ) : """Return True if the requirement line is a package requirement ; that is , it is not blank , a comment , a URL , or an included file ."""
return not ( line == '' or line . startswith ( '-r' ) or line . startswith ( '#' ) or line . startswith ( '-e' ) or line . startswith ( 'git+' ) )
def _get_value ( self , entity ) : """Override _ get _ value ( ) to * not * raise UnprojectedPropertyError ."""
value = self . _get_user_value ( entity ) if value is None and entity . _projection : # Invoke super _ get _ value ( ) to raise the proper exception . return super ( StructuredProperty , self ) . _get_value ( entity ) return value
def _get_user ( self , user ) : """Generate user filtering tokens ."""
return ' ' . join ( [ user . username , user . first_name , user . last_name ] )
def encode_multipart_formdata ( fields , boundary = None , charset = None ) : """Encode a dictionary of ` ` fields ` ` using the multipart / form - data format . : param fields : Dictionary of fields or list of ( key , value ) field tuples . The key is treated as the field name , and the value as the body of ...
charset = charset or 'utf-8' body = BytesIO ( ) if boundary is None : boundary = choose_boundary ( ) for fieldname , value in mapping_iterator ( fields ) : body . write ( ( '--%s\r\n' % boundary ) . encode ( charset ) ) if isinstance ( value , tuple ) : filename , data = value body . write (...
def add ( self , routeID , edges ) : """add ( string , list ( string ) ) - > None Adds a new route with the given id consisting of the given list of edge IDs ."""
self . _connection . _beginMessage ( tc . CMD_SET_ROUTE_VARIABLE , tc . ADD , routeID , 1 + 4 + sum ( map ( len , edges ) ) + 4 * len ( edges ) ) self . _connection . _packStringList ( edges ) self . _connection . _sendExact ( )
def load ( cls , file ) : """Loads a : class : ` ~ pypot . primitive . move . Move ` from a json file ."""
d = json . load ( file ) return cls . create ( d )
def put ( self , endpoint , ** kwargs ) : """Send HTTP PUT to the endpoint . : arg str endpoint : The endpoint to send to . : returns : JSON decoded result . : raises : requests . RequestException on timeout or connection error ."""
kwargs . update ( self . kwargs . copy ( ) ) if "data" in kwargs : kwargs [ "headers" ] . update ( { "Content-Type" : "application/json;charset=UTF-8" } ) response = requests . put ( self . make_url ( endpoint ) , ** kwargs ) return _decode_response ( response )
def get_mean_and_stddevs ( self , sctx , rctx , dctx , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values ."""
# Get original mean and standard deviations mean , stddevs = super ( ) . get_mean_and_stddevs ( sctx , rctx , dctx , imt , stddev_types ) cff = SInterCan15Mid . SITE_COEFFS [ imt ] mean += np . log ( cff [ 'mf' ] ) return mean , stddevs
def _ip_int_from_prefix ( self , prefixlen = None ) : """Turn the prefix length netmask into a int for comparison . Args : prefixlen : An integer , the prefix length . Returns : An integer ."""
if prefixlen is None : prefixlen = self . _prefixlen return self . _ALL_ONES ^ ( self . _ALL_ONES >> prefixlen )
def _get_block_hash ( self , number ) : """Get block hash by block number . : param number : : return :"""
num = _format_block_number ( number ) hash_key = header_prefix + num + num_suffix return self . db . get ( hash_key )
def set_state ( self , state = None , ** kwargs ) : """Set the view state of the camera Should be a dict ( or kwargs ) as returned by get _ state . It can be an incomlete dict , in which case only the specified properties are set . Parameters state : dict The camera state . * * kwargs : dict Unused ...
D = state or { } D . update ( kwargs ) for key , val in D . items ( ) : if key not in self . _state_props : raise KeyError ( 'Not a valid camera state property %r' % key ) setattr ( self , key , val )
def get_var_arr ( self ) : '''getter'''
if isinstance ( self . __var_arr , np . ndarray ) : return self . __var_arr else : raise TypeError ( )
def get_game_high_scores ( token , user_id , chat_id = None , message_id = None , inline_message_id = None ) : """Use this method to get data for high score tables . Will return the score of the specified user and several of his neighbors in a game . On success , returns an Array of GameHighScore objects . This m...
method_url = r'getGameHighScores' payload = { 'user_id' : user_id } if chat_id : payload [ 'chat_id' ] = chat_id if message_id : payload [ 'message_id' ] = message_id if inline_message_id : payload [ 'inline_message_id' ] = inline_message_id return _make_request ( token , method_url , params = payload )
def _move_install_requirements_markers ( self ) : """Move requirements in ` install _ requires ` that are using environment markers ` extras _ require ` ."""
# divide the install _ requires into two sets , simple ones still # handled by install _ requires and more complex ones handled # by extras _ require . def is_simple_req ( req ) : return not req . marker spec_inst_reqs = getattr ( self , 'install_requires' , None ) or ( ) inst_reqs = list ( pkg_resources . parse_re...
def read ( self ) : """Read pin value @ rtype : int @ return : I { 0 } when LOW , I { 1 } when HIGH"""
val = self . _fd . read ( ) self . _fd . seek ( 0 ) return int ( val )
def signature ( self , name , file_name , file_type , file_content , owner = None , ** kwargs ) : """Create the Signature TI object . Args : owner : file _ content : file _ name : file _ type : name : * * kwargs : Return :"""
return Signature ( self . tcex , name , file_name , file_type , file_content , owner = owner , ** kwargs )
def delete_quick ( self , get_count = False ) : """Deletes the table without cascading and without user prompt . If this table has populated dependent tables , this will fail ."""
query = 'DELETE FROM ' + self . full_table_name + self . where_clause self . connection . query ( query ) count = self . connection . query ( "SELECT ROW_COUNT()" ) . fetchone ( ) [ 0 ] if get_count else None self . _log ( query [ : 255 ] ) return count
def get_display_names_metadata ( self ) : """Gets the metadata for all display _ names . return : ( osid . Metadata ) - metadata for the display _ names * compliance : mandatory - - This method must be implemented . *"""
metadata = dict ( self . _display_names_metadata ) metadata . update ( { 'existing_string_values' : [ t [ 'text' ] for t in self . my_osid_object_form . _my_map [ 'displayNames' ] ] } ) return Metadata ( ** metadata )
def on_pubmsg ( self , connection , event ) : """Log any public messages , and also handle the command event ."""
for message in event . arguments ( ) : self . log ( event , message ) command_args = filter ( None , message . split ( ) ) command_name = command_args . pop ( 0 ) for handler in self . events [ "command" ] : if handler . event . args [ "command" ] == command_name : self . handle_comm...
def permutations ( x ) : '''Given a listlike , x , return all permutations of x Returns the permutations of x in the lexical order of their indices : e . g . > > > x = [ 1 , 2 , 3 , 4 ] > > > for p in permutations ( x ) : > > > print p [ 1 , 2 , 3 , 4 ] [ 1 , 2 , 4 , 3 ] [ 1 , 3 , 2 , 4 ] [ 1 , 3 ...
# The algorithm is attributed to Narayana Pandit from his # Ganita Kaumundi ( 1356 ) . The following is from # http : / / en . wikipedia . org / wiki / Permutation # Systematic _ generation _ of _ all _ permutations # 1 . Find the largest index k such that a [ k ] < a [ k + 1 ] . # If no such index exists , the permuta...
def get_params ( ) : """Parse command line arguments"""
parser = argparse . ArgumentParser ( ) parser . add_argument ( '-g' , '--debug' , dest = 'debug' , action = 'store_true' ) parser . add_argument ( '-t' , '--token' , dest = 'token' , help = "GitHub token" ) parser . add_argument ( '-o' , '--owner' , dest = 'owner' , help = 'GitHub owner (user or org) to be analyzed' ) ...
def zonearea ( idf , zonename , debug = False ) : """zone area"""
zone = idf . getobject ( 'ZONE' , zonename ) surfs = idf . idfobjects [ 'BuildingSurface:Detailed' . upper ( ) ] zone_surfs = [ s for s in surfs if s . Zone_Name == zone . Name ] floors = [ s for s in zone_surfs if s . Surface_Type . upper ( ) == 'FLOOR' ] if debug : print ( len ( floors ) ) print ( [ floor . a...
async def delete_entry_tag ( self , entry , tag ) : """DELETE / api / entries / { entry } / tags / { tag } . { _ format } Permanently remove one tag for an entry : param entry : \ w + an integer The Entry ID : param tag : string The Tag : return data related to the ext"""
params = { 'access_token' : self . token } url = '/api/entries/{entry}/tags/{tag}.{ext}' . format ( entry = entry , tag = tag , ext = self . format ) return await self . query ( url , "delete" , ** params )
def tree_to_xml ( self ) : """Traverses treeview and generates a ElementTree object"""
# Need to remove filter or hidden items will not be saved . self . filter_remove ( remember = True ) tree = self . treeview root = ET . Element ( 'interface' ) items = tree . get_children ( ) for item in items : node = self . tree_node_to_xml ( '' , item ) root . append ( node ) # restore filter self . filter_r...
def time ( self , time ) : """Add a request for a specific time to the query . This modifies the query in - place , but returns ` self ` so that multiple queries can be chained together on one line . This replaces any existing temporal queries that have been set . Parameters time : datetime . datetime T...
self . _set_query ( self . time_query , time = self . _format_time ( time ) ) return self
def _x_open ( self ) : """Open a channel for use This method opens a virtual connection ( a channel ) . RULE : This method MUST NOT be called when the channel is already open . PARAMETERS : out _ of _ band : shortstr ( DEPRECATED ) out - of - band settings Configures out - of - band transfers on thi...
if self . is_open : return args = AMQPWriter ( ) args . write_shortstr ( '' ) # out _ of _ band : deprecated self . _send_method ( ( 20 , 10 ) , args ) return self . wait ( allowed_methods = [ ( 20 , 11 ) , # Channel . open _ ok ] )
def computeOverlap ( self ) : """Compute estimate of overlap matrix between the states . Returns result _ vals : dictonary Possible keys in the result _ vals dictionary : ' scalar ' : np . ndarray , float , shape = ( K , K ) One minus the largest nontrival eigenvalue ( largest is 1 or - 1) ' eigenvalues...
W = np . matrix ( self . getWeights ( ) , np . float64 ) O = np . multiply ( self . N_k , W . T * W ) ( eigenvals , eigevec ) = linalg . eig ( O ) # sort in descending order eigenvals = np . sort ( eigenvals ) [ : : - 1 ] overlap_scalar = 1 - eigenvals [ 1 ] # 1 minus the second largest eigenvalue results_vals = dict (...
def make_model ( self , * args , ** kwargs ) : """Assemble a Cytoscape JS network from INDRA Statements . This method assembles a Cytoscape JS network from the set of INDRA Statements added to the assembler . Parameters grouping : bool If True , the nodes with identical incoming and outgoing edges are g...
for stmt in self . statements : if isinstance ( stmt , RegulateActivity ) : self . _add_regulate_activity ( stmt ) elif isinstance ( stmt , RegulateAmount ) : self . _add_regulate_amount ( stmt ) elif isinstance ( stmt , Modification ) : self . _add_modification ( stmt ) elif isi...
def write_rec ( table_name , objid , data , index_name_values ) : """Write ( upsert ) a record using a tran ."""
with DatastoreTransaction ( ) as tx : entity = tx . get_upsert ( ) entity . key . CopyFrom ( make_key ( table_name , objid ) ) prop = entity . property . add ( ) prop . name = 'id' prop . value . string_value = objid prop = entity . property . add ( ) prop . name = 'value' prop . value ....
def _import_class_or_module ( self , name ) : """Import a class using its fully - qualified * name * ."""
try : path , base = self . py_sig_re . match ( name ) . groups ( ) except : raise ValueError ( "Invalid class or module '%s' specified for inheritance diagram" % name ) fullname = ( path or '' ) + base path = ( path and path . rstrip ( '.' ) ) if not path : path = base try : module = __import__ ( path ,...
def shares ( self ) : """A : class : ` Feed < pypump . models . feed . Feed > ` of the people who ' ve shared the object . Example : > > > for person in mynote . shares : . . . print ( person . webfinger ) pypumptest1 @ pumpity . net pypumptest2 @ pumpyourself . com"""
endpoint = self . links [ "shares" ] if self . _shares is None : self . _shares = Feed ( endpoint , pypump = self . _pump ) return self . _shares
def reverse ( self , query , exactly_one = True , timeout = DEFAULT_SENTINEL , language = False , addressdetails = True ) : """Return an address by location point . : param query : The coordinates for which you wish to obtain the closest human - readable addresses . : type query : : class : ` geopy . point . ...
try : lat , lon = self . _coerce_point_to_string ( query ) . split ( ',' ) except ValueError : raise ValueError ( "Must be a coordinate pair or Point" ) params = { 'lat' : lat , 'lon' : lon , 'format' : 'json' , } if language : params [ 'accept-language' ] = language params [ 'addressdetails' ] = 1 if addre...
def merge ( corpus_1 , corpus_2 , match_by = [ 'ayjid' ] , match_threshold = 1. , index_by = 'ayjid' ) : """Combines two : class : ` . Corpus ` instances . The default behavior is to match : class : ` . Paper ` \ s using the fields in ` ` match _ by ` ` \ . If several fields are specified , ` ` match _ threshol...
def norm ( value ) : if type ( value ) in [ str , unicode ] : return value . strip ( ) . lower ( ) return value combined = [ ] exclude_1 = [ ] exclude_2 = [ ] # Attempt to match Papers for paper_1 in corpus_1 : for paper_2 in corpus_2 : # The user can provide their own matching logic . In this case ...
def log_url ( self , url_data , do_print ) : """Log URL statistics ."""
self . number += 1 if not url_data . valid : self . errors += 1 if do_print : self . errors_printed += 1 num_warnings = len ( url_data . warnings ) self . warnings += num_warnings if do_print : self . warnings_printed += num_warnings if url_data . content_type : key = url_data . content_type . s...
def get_instance ( model , instance_id ) : """Get an instance by id . : param model : a string , model name in rio . models : param id : an integer , instance id . : return : None or a SQLAlchemy Model instance ."""
try : model = get_model ( model ) except ImportError : return None return model . query . get ( instance_id )
def get_user_data ( user = None , group = None , data_kind = DINGOS_USER_DATA_TYPE_NAME ) : """Returns either stored settings of a given user or default settings . This behavior reflects the need for views to have some settings at hand when running . The settings are returned as dict object ."""
logger . debug ( "Get user settings called" ) if not user . is_authenticated ( ) : user = None try : user_config = UserData . objects . get ( user = user , group = group , data_kind = data_kind ) return user_config . retrieve ( ) except : return None
def set_split_extents ( self ) : """Sets split extents ( : attr : ` split _ begs ` and : attr : ` split _ ends ` ) calculated using selected attributes set from : meth : ` _ _ init _ _ ` ."""
self . check_split_parameters ( ) self . update_tile_extent_bounds ( ) if self . indices_per_axis is not None : self . set_split_extents_by_indices_per_axis ( ) elif ( self . split_size is not None ) or ( self . split_num_slices_per_axis is not None ) : self . set_split_extents_by_split_size ( ) elif self . til...
def pformat_xml ( xml ) : """Return pretty formatted XML ."""
try : from lxml import etree # delayed import if not isinstance ( xml , bytes ) : xml = xml . encode ( 'utf-8' ) xml = etree . parse ( io . BytesIO ( xml ) ) xml = etree . tostring ( xml , pretty_print = True , xml_declaration = True , encoding = xml . docinfo . encoding ) xml = bytes2st...
def _submit ( self ) : '''submit the issue to github . When we get here we should have : { ' user _ prompt _ issue ' : ' I want to do the thing . ' , ' user _ prompt _ repo ' : ' vsoch / hello - world ' , ' user _ prompt _ title ' : ' Error with this thing ' , ' record _ asciinema ' : ' / tmp / helpme . 93o...
body = self . data [ 'user_prompt_issue' ] title = self . data [ 'user_prompt_title' ] repo = self . data [ 'user_prompt_repo' ] # Step 1 : Environment envars = self . data . get ( 'record_environment' ) body = body + envars_to_markdown ( envars ) # Step 2 : Asciinema asciinema = self . data . get ( 'record_asciinema' ...
async def answer_location ( self , latitude : base . Float , longitude : base . Float , live_period : typing . Union [ base . Integer , None ] = None , disable_notification : typing . Union [ base . Boolean , None ] = None , reply_markup = None , reply = False ) -> Message : """Use this method to send point on the ...
return await self . bot . send_location ( chat_id = self . chat . id , latitude = latitude , longitude = longitude , live_period = live_period , disable_notification = disable_notification , reply_to_message_id = self . message_id if reply else None , reply_markup = reply_markup )
def get_value ( d , name , field ) : """Handle gets from ' multidicts ' made of lists It handles cases : ` ` { " key " : [ value ] } ` ` and ` ` { " key " : value } ` `"""
multiple = core . is_multiple ( field ) value = d . get ( name , core . missing ) if value is core . missing : return core . missing if multiple and value is not core . missing : return [ decode_argument ( v , name ) if isinstance ( v , basestring ) else v for v in value ] ret = value if value and isinstance ( ...
def are_imaging_dicoms ( dicom_input ) : """This function will check the dicom headers to see which type of series it is Possibilities are fMRI , DTI , Anatomical ( if no clear type is found anatomical is used ) : param dicom _ input : directory with dicom files or a list of dicom objects"""
# if it is philips and multiframe dicom then we assume it is ok if common . is_philips ( dicom_input ) : if common . is_multiframe_dicom ( dicom_input ) : return True # for all others if there is image position patient we assume it is ok header = dicom_input [ 0 ] return Tag ( 0x0020 , 0x0037 ) in header
def power_list ( number_bases , power_values ) : """Constructs a list of numbers where each element is a base number raised to the power of corresponding number in the provided list of indices using the map function . Examples : power _ list ( [ 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 , 100 ] , [ 1 , 2 , 3...
return list ( map ( pow , number_bases , power_values ) )
def _parseDOM ( istack ) : """Recursively go through element array and create DOM . Args : istack ( list ) : List of : class : ` . HTMLElement ` objects . Returns : list : DOM tree as list ."""
ostack = [ ] end_tag_index = 0 def neither_nonpair_or_end_or_comment ( el ) : return not ( el . isNonPairTag ( ) or el . isEndTag ( ) or el . isComment ( ) ) index = 0 while index < len ( istack ) : el = istack [ index ] # check if this is pair tag end_tag_index = _indexOfEndTag ( istack [ index : ] ) ...
def metric ( cls , name , count , elapsed ) : """A metric function that buffers through numpy : arg str name : name of the metric : arg int count : number of items : arg float elapsed : time in seconds"""
if name is None : warnings . warn ( "Ignoring unnamed metric" , stacklevel = 3 ) return with cls . lock : # register with atexit on first call if cls . dump_atexit and not cls . instances : atexit . register ( cls . dump ) try : self = cls . instances [ name ] except KeyError : ...
def volume_list ( provider ) : '''List block storage volumes CLI Example : . . code - block : : bash salt minionname cloud . volume _ list my - nova'''
client = _get_client ( ) info = client . extra_action ( action = 'volume_list' , provider = provider , names = 'name' ) return info [ 'name' ]
def locale_first_weekday ( ) : """figure if week starts on monday or sunday"""
first_weekday = 6 # by default settle on monday try : process = os . popen ( "locale first_weekday week-1stday" ) week_offset , week_start = process . read ( ) . split ( '\n' ) [ : 2 ] process . close ( ) week_start = dt . date ( * time . strptime ( week_start , "%Y%m%d" ) [ : 3 ] ) week_offset = dt...
def fetch_single_representation ( self , item_xlink_href ) : """This function will render a formatted URL for accessing the PLoS ' server SingleRepresentation of an object ."""
# A dict of URLs for PLoS subjournals journal_urls = { 'pgen' : 'http://www.plosgenetics.org/article/{0}' , 'pcbi' : 'http://www.ploscompbiol.org/article/{0}' , 'ppat' : 'http://www.plospathogens.org/article/{0}' , 'pntd' : 'http://www.plosntds.org/article/{0}' , 'pmed' : 'http://www.plosmedicine.org/article/{0}' , 'pb...
def libvlc_vlm_set_output ( p_instance , psz_name , psz_output ) : '''Set the output for a media . @ param p _ instance : the instance . @ param psz _ name : the media to work on . @ param psz _ output : the output MRL ( the parameter to the " sout " variable ) . @ return : 0 on success , - 1 on error .'''
f = _Cfunctions . get ( 'libvlc_vlm_set_output' , None ) or _Cfunction ( 'libvlc_vlm_set_output' , ( ( 1 , ) , ( 1 , ) , ( 1 , ) , ) , None , ctypes . c_int , Instance , ctypes . c_char_p , ctypes . c_char_p ) return f ( p_instance , psz_name , psz_output )
def cleanup_sweep_threads ( ) : '''Not used . Keeping this function in case we decide not to use daemonized threads and it becomes necessary to clean up the running threads upon exit .'''
for dict_name , obj in globals ( ) . items ( ) : if isinstance ( obj , ( TimedDict , ) ) : logging . info ( 'Stopping thread for TimedDict {dict_name}' . format ( dict_name = dict_name ) ) obj . stop_sweep ( )
def from_job_desc ( cls , warm_start_config ) : """Creates an instance of ` ` WarmStartConfig ` ` class , from warm start configuration response from DescribeTrainingJob . Args : warm _ start _ config ( dict ) : The expected format of the ` ` warm _ start _ config ` ` contains two first - class fields : *...
if not warm_start_config or WARM_START_TYPE not in warm_start_config or PARENT_HYPERPARAMETER_TUNING_JOBS not in warm_start_config : return None parents = [ ] for parent in warm_start_config [ PARENT_HYPERPARAMETER_TUNING_JOBS ] : parents . append ( parent [ HYPERPARAMETER_TUNING_JOB_NAME ] ) return cls ( warm_...
def thaw_args ( subparsers ) : """Add command line options for the thaw operation"""
thaw_parser = subparsers . add_parser ( 'thaw' ) thaw_parser . add_argument ( '--gpg-password-path' , dest = 'gpg_pass_path' , help = 'Vault path of GPG passphrase location' ) thaw_parser . add_argument ( '--ignore-missing' , dest = 'ignore_missing' , help = 'Warn when secrets are missing from icefiles' 'instead of exi...
def get_base_path ( path ) : """Determines the longest possible beginning of a path that does not contain a % - Symbol . / this / is / a / pa % th would become / this / is / a : param str path : the path to get the base from : return : the path ' s base"""
if "%" not in path : return path path = os . path . split ( path ) [ 0 ] while "%" in path : path = os . path . split ( path ) [ 0 ] return path
def save ( self ) : """Save this entry . If the entry does not have an : attr : ` id ` , a new id will be assigned , and the : attr : ` id ` attribute set accordingly . Pre - save processing of the fields saved can be done by overriding the : meth : ` prepare _ save ` method . Additional actions to be don...
id = self . id or self . objects . id ( self . name ) self . objects [ id ] = self . prepare_save ( dict ( self ) ) self . id = id self . post_save ( ) return id
def add_ipdu ( self , information , timeout = - 1 ) : """Add an HP iPDU and bring all components under management by discovery of its management module . Bring the management module under exclusive management by the appliance , configure any management or data collection settings , and create a private set of a...
uri = self . URI + "/discover" return self . _client . create ( information , uri = uri , timeout = timeout )
def update ( self ) : """Update uptime stat using the input method ."""
# Init new stats stats = self . get_init_value ( ) if self . input_method == 'local' : # Update stats using the standard system lib self . uptime = datetime . now ( ) - datetime . fromtimestamp ( psutil . boot_time ( ) ) # Convert uptime to string ( because datetime is not JSONifi ) stats = str ( self . upt...
def _inc_lat ( self , latitude , delta ) : """Shift the latitude by the required number of pixels ( i . e . text lines ) ."""
y = self . _convert_latitude ( latitude ) y += delta return 360 / pi * atan ( exp ( ( 180 - y * 360 / ( 2 ** self . _zoom ) / self . _size ) * pi / 180 ) ) - 90
def abort ( self ) : """Abort all SBIs associated with the subarray ."""
for sbi_id in self . sbi_ids : sbi = SchedulingBlockInstance ( sbi_id ) sbi . abort ( ) self . set_state ( 'ABORTED' )
def gettext ( self , singular , plural = None , n = 1 , locale = None ) -> str : """Get text : param singular : : param plural : : param n : : param locale : : return :"""
if locale is None : locale = self . ctx_locale . get ( ) if locale not in self . locales : if n is 1 : return singular else : return plural translator = self . locales [ locale ] if plural is None : return translator . gettext ( singular ) else : return translator . ngettext ( singul...
def drop_networks ( self ) -> None : """Drop all networks ."""
for network in self . session . query ( Network ) . all ( ) : self . drop_network ( network )
def bytescale ( data , cmin = None , cmax = None , high = 255 , low = 0 ) : """Byte scales an array ( image ) . Byte scaling means converting the input image to uint8 dtype and scaling the range to ` ` ( low , high ) ` ` ( default 0-255 ) . If the input image already has dtype uint8 , no scaling is done . P...
if data . dtype == uint8 : return data if high > 255 : raise ValueError ( "`high` should be less than or equal to 255." ) if low < 0 : raise ValueError ( "`low` should be greater than or equal to 0." ) if high < low : raise ValueError ( "`high` should be greater than or equal to `low`." ) if cmin is Non...
def set_common_datas ( self , element , name , datas ) : """Populated common data for an element from dictionnary datas"""
element . name = str ( name ) if "description" in datas : element . description = str ( datas [ "description" ] ) . strip ( ) if isinstance ( element , Sampleable ) and element . sample is None and "sample" in datas : element . sample = str ( datas [ "sample" ] ) . strip ( ) if isinstance ( element , Displayabl...
def from_array ( array ) : """Deserialize a new MaskPosition from a given dictionary . : return : new MaskPosition instance . : rtype : MaskPosition"""
if array is None or not array : return None # end if assert_type_or_raise ( array , dict , parameter_name = "array" ) data = { } data [ 'point' ] = u ( array . get ( 'point' ) ) data [ 'x_shift' ] = float ( array . get ( 'x_shift' ) ) data [ 'y_shift' ] = float ( array . get ( 'y_shift' ) ) data [ 'scale' ] = float...
def resolve_resource_id_refs ( self , input_dict , supported_resource_id_refs ) : """Resolve resource references within a GetAtt dict . Example : { " Fn : : GetAtt " : [ " LogicalId " , " Arn " ] } = > { " Fn : : GetAtt " : [ " ResolvedLogicalId " , " Arn " ] } Theoretically , only the first element of the ar...
if not self . can_handle ( input_dict ) : return input_dict key = self . intrinsic_name value = input_dict [ key ] # Value must be an array with * at least * two elements . If not , this is invalid GetAtt syntax . We just pass along # the input to CFN for it to do the " official " validation . if not isinstance ( v...
def generateThumbnail ( self ) : """Generates a square thumbnail"""
image = pilImage . open ( ROOT / self . source . name ) box , width , height = cropBox ( self . width , self . height ) # Resize image . thumbnail ( ( width , height ) , pilImage . ANTIALIAS ) # Crop from center box = cropBox ( * image . size ) [ 0 ] image = image . crop ( box ) # save self . thumbnail = self . source ...
def get_formatter_for_filename ( fn , ** options ) : """Lookup and instantiate a formatter by filename pattern . Raises ClassNotFound if not found ."""
fn = basename ( fn ) for modname , name , _ , filenames , _ in itervalues ( FORMATTERS ) : for filename in filenames : if _fn_matches ( fn , filename ) : if name not in _formatter_cache : _load_formatters ( modname ) return _formatter_cache [ name ] ( ** options ) for...
def getFriendlyString ( self ) : """Returns the version , printed in a friendly way . More precisely , it trims trailing zero components ."""
if self . _friendlyString is not None : return self . _friendlyString resultComponents = [ self . getIntMajor ( ) , self . getIntMinor ( ) , self . getIntBuild ( ) , self . getIntRevision ( ) ] for i in range ( len ( resultComponents ) - 1 , - 1 , - 1 ) : if resultComponents [ i ] == 0 : del resultCompo...
def create_instance ( self , collection_or_class , attributes , lazy = False , call_hook = True , deserialize = True , db_loader = None ) : """Creates an instance of a ` Document ` class corresponding to the given collection name or class . : param collection _ or _ class : The name of the collection or a referen...
creation_args = { 'backend' : self , 'autoload' : self . _autoload_embedded , 'lazy' : lazy , 'db_loader' : db_loader } if collection_or_class in self . classes : cls = collection_or_class elif collection_or_class in self . collections : cls = self . collections [ collection_or_class ] else : raise Attribut...
def draw ( self , data ) : """Display decoded characters at the current cursor position and advances the cursor if : data : ` ~ pyte . modes . DECAWM ` is set . : param str data : text to display . . . versionchanged : : 0.5.0 Character width is taken into account . Specifically , zero - width and unprint...
data = data . translate ( self . g1_charset if self . charset else self . g0_charset ) for char in data : char_width = wcwidth ( char ) # If this was the last column in a line and auto wrap mode is # enabled , move the cursor to the beginning of the next line , # otherwise replace characters already dis...
def find ( self , path , all = False ) : """Looks for files in PIPELINE . STYLESHEETS and PIPELINE . JAVASCRIPT"""
matches = [ ] for elem in chain ( settings . STYLESHEETS . values ( ) , settings . JAVASCRIPT . values ( ) ) : if normpath ( elem [ 'output_filename' ] ) == normpath ( path ) : match = safe_join ( settings . PIPELINE_ROOT , path ) if not all : return match matches . append ( matc...
def stats ( self , where , start , end , pw , archiver = "" , timeout = DEFAULT_TIMEOUT ) : """With the given WHERE clause , retrieves all statistical data between the 2 given timestamps , using the given pointwidth Arguments : [ where ] : the where clause ( e . g . ' path like " keti " ' , ' SourceName = " TED...
return self . query ( "select statistical({3}) data in ({0}, {1}) where {2}" . format ( start , end , where , pw ) , archiver , timeout ) . get ( 'timeseries' , { } )
def process_metadata ( pkg_name , metadata_lines ) : """Create a dictionary containing the relevant fields . The following is an example of the generated dictionary : : Example : ' name ' : ' six ' , ' version ' : ' 1.11.0 ' , ' repository ' : ' pypi . python . org / pypi / six ' , ' licence ' : ' MIT '...
# Initialise a dictionary with all the fields to report on . tpip_pkg = dict ( PkgName = pkg_name , PkgType = 'python package' , PkgMgrURL = 'https://pypi.org/project/%s/' % pkg_name , ) # Extract the metadata into a list for each field as there may be multiple # entries for each one . for line in metadata_lines : ...
def on_change_checkout ( self ) : '''When you change checkin _ date or checkout _ date it will checked it and update the qty of hotel service line @ param self : object pointer'''
if not self . ser_checkin_date : time_a = time . strftime ( DEFAULT_SERVER_DATETIME_FORMAT ) self . ser_checkin_date = time_a if not self . ser_checkout_date : self . ser_checkout_date = time_a if self . ser_checkout_date < self . ser_checkin_date : raise _ ( 'Checkout must be greater or equal checkin d...