signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def reset ( self , path , pretend = False ) : """Rolls all of the currently applied migrations back . : param path : The path : type path : str : param pretend : Whether we execute the migrations as dry - run : type pretend : bool : rtype : count"""
self . _notes = [ ] migrations = sorted ( self . _repository . get_ran ( ) , reverse = True ) count = len ( migrations ) if count == 0 : self . _note ( "<info>Nothing to rollback.</info>" ) else : for migration in migrations : self . _run_down ( path , { "migration" : migration } , pretend ) return coun...
def rates_angles ( fk_candidate_observations ) : """: param fk _ candidate _ observations : name of the fk * reals . astrom file to check against Object . planted"""
detections = fk_candidate_observations . get_sources ( ) for detection in detections : measures = detection . get_readings ( ) for measure in measures : def main ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( '--astrom-filename' , default = None , help = "Give the astrom file directly inst...
def has_too_few_calls ( self ) : """Test if there have not been enough calls : rtype boolean"""
if self . has_exact and self . _call_count < self . _exact : return True if self . has_minimum and self . _call_count < self . _minimum : return True return False
def hide_arp_holder_arp_entry_arp_ip_address ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hide_arp_holder = ET . SubElement ( config , "hide-arp-holder" , xmlns = "urn:brocade.com:mgmt:brocade-arp" ) arp_entry = ET . SubElement ( hide_arp_holder , "arp-entry" ) arp_ip_address = ET . SubElement ( arp_entry , "arp-ip-address" ) arp_ip_address . text = kwargs . pop ( 'arp_ip_...
def remove_nio ( self , port_number ) : """Removes the specified NIO as member of this ATM switch . : param port _ number : allocated port number"""
if port_number not in self . _nios : raise DynamipsError ( "Port {} is not allocated" . format ( port_number ) ) # remove VCs mapped with the port for source , destination in self . _active_mappings . copy ( ) . items ( ) : if len ( source ) == 3 and len ( destination ) == 3 : # remove the virtual channels mapp...
def removeIndividual ( self , individual ) : """Removes the specified individual from this repository ."""
q = models . Individual . delete ( ) . where ( models . Individual . id == individual . getId ( ) ) q . execute ( )
def resolve_randconfig ( self , args ) : """Get the name of the specturm file based on the job arguments"""
ttype = args . get ( 'ttype' ) if is_null ( ttype ) : sys . stderr . write ( 'Target type must be specified' ) return None name_keys = dict ( target_type = ttype , fullpath = True ) randconfig = self . randconfig ( ** name_keys ) rand_override = args . get ( 'rand_config' ) if is_not_null ( rand_override ) : ...
def do_pickle_ontology ( filename , g = None ) : """from a valid filename , generate the graph instance and pickle it too note : option to pass a pre - generated graph instance too 2015-09-17 : added code to increase recursion limit if cPickle fails see http : / / stackoverflow . com / questions / 2134706 / h...
ONTOSPY_LOCAL_MODELS = get_home_location ( ) pickledpath = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle" if not g : g = Ontospy ( ONTOSPY_LOCAL_MODELS + "/" + filename ) if not GLOBAL_DISABLE_CACHE : try : cPickle . dump ( g , open ( pickledpath , "wb" ) ) # print Style . DIM + " . . cached <...
def __is_exported ( self , name , module ) : """Returns ` True ` if and only if ` pydoc ` considers ` name ` to be a public identifier for this module where ` name ` was defined in the Python module ` module ` . If this module has an ` _ _ all _ _ ` attribute , then ` name ` is considered to be exported if ...
if hasattr ( self . module , '__all__' ) : return name in self . module . __all__ if not _is_exported ( name ) : return False if module is None : return False if module is not None and self . module . __name__ != module . __name__ : return name in self . _declared_variables return True
def _create_auth ( self , username = None , password = None ) : """Create an ~ uamqp . authentication . cbs _ auth _ async . SASTokenAuthAsync instance to authenticate the session . : param username : The name of the shared access policy . : type username : str : param password : The shared access key . :...
if self . sas_token : token = self . sas_token ( ) if callable ( self . sas_token ) else self . sas_token try : expiry = int ( parse_sas_token ( token ) [ 'se' ] ) except ( KeyError , TypeError , IndexError ) : raise ValueError ( "Supplied SAS token has no valid expiry value." ) return a...
def _build_opstackd ( ) : """Builds a dictionary that maps the name of an op - code to the number of elemnts it adds to the stack when executed . For some opcodes , the dictionary may contain a function which requires the # dis . Instruction object to determine the actual value . The dictionary mostly only ...
def _call_function_argc ( argc ) : func_obj = 1 args_pos = ( argc & 0xff ) args_kw = ( ( argc >> 8 ) & 0xff ) * 2 return func_obj + args_pos + args_kw def _make_function_argc ( argc ) : args_pos = ( argc + 0xff ) args_kw = ( ( argc >> 8 ) & 0xff ) * 2 annotations = ( argc >> 0x7fff ) ano...
def get_staking_leaderboard ( self , round_num = 0 , tournament = 1 ) : """Retrieves the leaderboard of the staking competition for the given round . Args : round _ num ( int , optional ) : The round you are interested in , defaults to current round . tournament ( int , optional ) : ID of the tournament ,...
msg = "getting stakes for tournament {} round {}" self . logger . info ( msg . format ( tournament , round_num ) ) query = ''' query($number: Int! $tournament: Int!) { rounds(number: $number tournament: $tournament) { leaderboard { ...
def get_matrix ( self ) : """Use numpy to create a real matrix object from the data : return : the matrix representation of the fvm"""
return np . array ( [ self . get_row_list ( i ) for i in range ( self . row_count ( ) ) ] )
def substitute ( expression : Union [ Expression , Pattern ] , substitution : Substitution ) -> Replacement : """Replaces variables in the given * expression * using the given * substitution * . > > > print ( substitute ( f ( x _ ) , { ' x ' : a } ) ) f ( a ) If nothing was substituted , the original expressi...
if isinstance ( expression , Pattern ) : expression = expression . expression return _substitute ( expression , substitution ) [ 0 ]
def RegisterAnyElement ( cls ) : '''If find registered TypeCode instance , add Wrapper class to TypeCode class serialmap and Re - RegisterType . Provides Any serialzation of any instances of the Wrapper .'''
for k , v in cls . types_dict . items ( ) : what = Any . serialmap . get ( k ) if what is None : continue if v in what . __class__ . seriallist : continue what . __class__ . seriallist . append ( v ) RegisterType ( what . __class__ , clobber = 1 , ** what . __dict__ )
def outer_horizontal_border_bottom ( self ) : """The complete outer bottom horizontal border section , including left and right margins . Returns : str : The bottom menu border ."""
return u"{lm}{lv}{hz}{rv}" . format ( lm = ' ' * self . margins . left , lv = self . border_style . bottom_left_corner , rv = self . border_style . bottom_right_corner , hz = self . outer_horizontals ( ) )
def _post_read_flds ( flds , header ) : """Process flds to handle sphericity ."""
if flds . shape [ 0 ] >= 3 and header [ 'rcmb' ] > 0 : # spherical vector header [ 'p_mesh' ] = np . roll ( np . arctan2 ( header [ 'y_mesh' ] , header [ 'x_mesh' ] ) , - 1 , 1 ) for ibk in range ( header [ 'ntb' ] ) : flds [ ... , ibk ] = _to_spherical ( flds [ ... , ibk ] , header ) header [ 'p_me...
def activate_component ( self , name ) : """Activates given Component . : param name : Component name . : type name : unicode : return : Method success . : rtype : bool"""
if not name in self . __engine . components_manager . components : raise manager . exceptions . ComponentExistsError ( "{0} | '{1}' Component isn't registered in the Components Manager!" . format ( self . __class__ . __name__ , name ) ) component = self . __engine . components_manager . components [ name ] if compo...
def get_configuration ( dev ) : r"""Get the current active configuration of the device . dev is the Device object to which the request will be sent to . This function differs from the Device . get _ active _ configuration method because the later may use cached data , while this function always does a dev...
bmRequestType = util . build_request_type ( util . CTRL_IN , util . CTRL_TYPE_STANDARD , util . CTRL_RECIPIENT_DEVICE ) return dev . ctrl_transfer ( bmRequestType , bRequest = 0x08 , data_or_wLength = 1 ) [ 0 ]
def delete_policy ( self , pol_id ) : """Deletes the policy from the local dictionary ."""
if pol_id not in self . policies : LOG . error ( "Invalid policy %s" , pol_id ) return del self . policies [ pol_id ] self . policy_cnt -= 1
def get_args ( path ) : '''Parse command line args & override defaults . Arguments : - path ( str ) Absolute filepath Returns : - ( tuple ) Name , email , license , project , ext , year'''
defaults = get_defaults ( path ) licenses = ', ' . join ( os . listdir ( cwd + licenses_loc ) ) p = parser ( description = 'tool for adding open source licenses to your projects. available licenses: %s' % licenses ) _name = False if defaults . get ( 'name' ) else True _email = False if defaults . get ( 'email' ) else T...
def add_port_to_free_pool ( self , port ) : """Add a new port to the free pool for allocation ."""
if port < 1 or port > 65535 : raise ValueError ( 'Port must be in the [1, 65535] range, not %d.' % port ) port_info = _PortInfo ( port = port ) self . _port_queue . append ( port_info )
def _compute_r2l2 ( self , tau , return_l = False ) : r"""Compute the anisotropic : math : ` r ^ 2 / l ^ 2 ` term for the given ` tau ` . Here , : math : ` \ tau = X _ i - X _ j ` is the difference vector . Computes . . math : : \ frac { r ^ 2 } { l ^ 2 } = \ sum _ i \ frac { \ tau _ i ^ 2 } { l _ { i } ^ { 2...
l_mat = scipy . tile ( self . params [ - self . num_dim : ] , ( tau . shape [ 0 ] , 1 ) ) tau_over_l = tau / l_mat tau_over_l [ ( tau == 0 ) & ( l_mat == 0 ) ] = 0.0 r2l2 = scipy . sum ( ( tau_over_l ) ** 2 , axis = 1 ) if return_l : return ( r2l2 , l_mat ) else : return r2l2
def connect ( self , callback , weak = False ) : """Connects a new callback to this signal . : param callback : The callback to connect . : param weak : If ` True ` , only holds a weak reference to the specified callback . ` callback ` will be called whenever ` emit ` gets called on the ` Signal ` instanc...
if weak : callback = ref ( callback , self . _callbacks . remove ) self . _callbacks . append ( callback )
def atomic_open ( filename , mode = 'w' ) : '''Works like a regular ` open ( ) ` but writes updates into a temporary file instead of the given file and moves it over when the file is closed . The file returned behaves as if it was a regular Python'''
if mode in ( 'r' , 'rb' , 'r+' , 'rb+' , 'a' , 'ab' ) : raise TypeError ( 'Read or append modes don\'t work with atomic_open' ) kwargs = { 'prefix' : '.___atomic_write' , 'dir' : os . path . dirname ( filename ) , 'delete' : False , } if six . PY3 and 'b' not in mode : kwargs [ 'newline' ] = '' ntf = tempfile ....
def _read_file_data ( self , path ) : """Attempts to read the contents of the given configuration file . : param path : Path to a configuration file . : raises : ConfigParseError if file does not exist or cannot be read . : return : Dictionary of configuration data ."""
_ , ext = os . path . splitext ( path ) # YAML files if ext in ( '.yml' , '.yaml' ) : try : with open ( path ) as f : return yaml . safe_load ( f ) except YAMLError as e : raise ConfigParseError ( path , e ) # JSON files elif ext == '.json' : try : return json . loads ( o...
def main ( ) : """NAME odp _ spn _ magic . py DESCRIPTION converts ODP ' s Molspin ' s . spn format files to magic _ measurements format files SYNTAX odp _ spn _ magic . py [ command line options ] OPTIONS - h : prints the help message and quits . - f FILE : specify . spn format input file , require...
# initialize some stuff noave = 0 methcode , inst = "" , "" phi , theta , peakfield , labfield = 0 , 0 , 0 , 0 dec = [ 315 , 225 , 180 , 135 , 45 , 90 , 270 , 270 , 270 , 90 , 180 , 180 , 0 , 0 , 0 ] inc = [ 0 , 0 , 0 , 0 , 0 , - 45 , - 45 , 0 , 45 , 45 , 45 , - 45 , - 90 , - 45 , 45 ] missing = 1 demag = "N" er_locati...
def reraise ( additional_msg ) : """Reraise an exception with an additional message ."""
exc_type , exc_value , exc_traceback = sys . exc_info ( ) msg = str ( exc_value ) + "\n" + additional_msg six . reraise ( exc_type , exc_type ( msg ) , exc_traceback )
def fcoe_fcoe_map_fcoe_map_fabric_map_fcoe_map_fabric_map_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fcoe = ET . SubElement ( config , "fcoe" , xmlns = "urn:brocade.com:mgmt:brocade-fcoe" ) fcoe_map = ET . SubElement ( fcoe , "fcoe-map" ) fcoe_map_name_key = ET . SubElement ( fcoe_map , "fcoe-map-name" ) fcoe_map_name_key . text = kwargs . pop ( 'fcoe_map_name' ) fcoe_map_fabric_map ...
def _render ( item : ConfigItem , indent : str = "" ) -> str : """Render a single config item , with the provided indent"""
optional = item . default_value != _NO_DEFAULT if is_configurable ( item . annotation ) : rendered_annotation = f"{item.annotation} (configurable)" else : rendered_annotation = str ( item . annotation ) rendered_item = "" . join ( [ # rendered _ comment , indent , "// " if optional else "" , f'"{item.name}": ' ...
def get ( filename , target = None , serial = None ) : """Gets a referenced file on the device ' s file system and copies it to the target ( or current working directory if unspecified ) . If no serial object is supplied , microfs will attempt to detect the connection itself . Returns True for success or ra...
if target is None : target = filename commands = [ "\n" . join ( [ "try:" , " from microbit import uart as u" , "except ImportError:" , " try:" , " from machine import UART" , " u = UART(0, {})" . format ( SERIAL_BAUD_RATE ) , " except Exception:" , " try:" , " from sys import stdout as u" , " except Exceptio...
def get_neutron_endpoint ( cls , json_resp ) : """Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service Sends a CRITICAL service check when none are found registered in the Catalog"""
catalog = json_resp . get ( 'token' , { } ) . get ( 'catalog' , [ ] ) match = 'neutron' neutron_endpoint = None for entry in catalog : if entry [ 'name' ] == match or 'Networking' in entry [ 'name' ] : valid_endpoints = { } for ep in entry [ 'endpoints' ] : interface = ep . get ( 'interf...
def decode ( token , key , algorithms = None , options = None , audience = None , issuer = None , subject = None , access_token = None ) : """Verifies a JWT string ' s signature and validates reserved claims . Args : token ( str ) : A signed JWS to be verified . key ( str or dict ) : A key to attempt to verif...
defaults = { 'verify_signature' : True , 'verify_aud' : True , 'verify_iat' : True , 'verify_exp' : True , 'verify_nbf' : True , 'verify_iss' : True , 'verify_sub' : True , 'verify_jti' : True , 'verify_at_hash' : True , 'require_aud' : False , 'require_iat' : False , 'require_exp' : False , 'require_nbf' : False , 're...
def make_parser ( func_sig , description , epilog , add_nos ) : '''Given the signature of a function , create an ArgumentParser'''
parser = ArgumentParser ( description = description , epilog = epilog ) used_char_args = { 'h' } # Arange the params so that single - character arguments are first . This # esnures they don ' t have to get - - long versions . sorted is stable , so the # parameters will otherwise still be in relative order . params = so...
def _to_values ( self , collection ) : """Regroup values in tuples or dicts for each " instance " . Exemple : Given this result from redis : [ ' id1 ' , ' name1 ' , ' id2 ' , ' name2 ' ] tuples : [ ( ' id1 ' , ' name1 ' ) , ( ' id2 ' , ' name2 ' ) ] dicts : [ { ' id ' : ' id1 ' , ' name ' : ' name1 ' } , { ' ...
result = zip ( * ( [ iter ( collection ) ] * len ( self . _values [ 'fields' ] [ 'names' ] ) ) ) if self . _values [ 'mode' ] == 'dicts' : result = ( dict ( zip ( self . _values [ 'fields' ] [ 'names' ] , a_result ) ) for a_result in result ) return result
def dropna ( self , axis = 0 , inplace = False , ** kwargs ) : """Analogous to Series . dropna . If fill _ value = NaN , returns a dense Series"""
# TODO : make more efficient # Validate axis self . _get_axis_number ( axis or 0 ) dense_valid = self . to_dense ( ) . dropna ( ) if inplace : raise NotImplementedError ( "Cannot perform inplace dropna" " operations on a SparseSeries" ) if isna ( self . fill_value ) : return dense_valid else : dense_valid =...
def _fill ( self , direction , limit = None ) : """Overridden method to join grouped columns in output"""
res = super ( ) . _fill ( direction , limit = limit ) output = OrderedDict ( ( grp . name , grp . grouper ) for grp in self . grouper . groupings ) from pandas import concat return concat ( ( self . _wrap_transformed_output ( output ) , res ) , axis = 1 )
def is_valid ( condition ) : """Verify condition ( format ) . > > > Condition . is _ valid ( ' { { foo } } = = 42 ' ) True > > > Condition . is _ valid ( ' " { { foo } } " = = 42 ' ) False > > > Condition . is _ valid ( ' not " { { foo } } " = = " 42 " ' ) True > > > Condition . is _ valid ( ' not { {...
matched = False if len ( condition ) > 0 : final_condition = re . sub ( '{{.*}}' , '42' , condition ) ast_tokens = Condition . get_tokens ( final_condition ) ast_compressed_tokens = Condition . compress_tokens ( ast_tokens ) for rule in Condition . RULES : if Condition . match_tokens ( ast_compr...
def inventory ( self , source_id , fetch = False , fmt = 'table' ) : """Prints a summary of all objects in the database . Input string or list of strings in * * ID * * or * * unum * * for specific objects . Parameters source _ id : int The id from the SOURCES table whose data across all tables is to be prin...
data_tables = { } t = self . query ( "SELECT * FROM sqlite_master WHERE type='table'" , fmt = 'table' ) all_tables = t [ 'name' ] . tolist ( ) for table in [ 'sources' ] + [ t for t in all_tables if t not in [ 'sources' , 'sqlite_sequence' ] ] : try : # Get the columns , pull out redundant ones , and query the tabl...
def get_url ( self , request , * , date = None , size_x = None , size_y = None , geometry = None ) : """Returns url to Sentinel Hub ' s OGC service for the product specified by the OgcRequest and date . : param request : OGC - type request with specified bounding box , cloud coverage for specific product . : ty...
url = self . get_base_url ( request ) authority = self . instance_id if hasattr ( self , 'instance_id' ) else request . theme params = self . _get_common_url_parameters ( request ) if request . service_type in ( ServiceType . WMS , ServiceType . WCS ) : params = { ** params , ** self . _get_wms_wcs_url_parameters (...
def get_objective_hierarchy_design_session ( self ) : """Gets the session for designing objective hierarchies . return : ( osid . learning . ObjectiveHierarchyDesignSession ) - an ObjectiveHierarchyDesignSession raise : OperationFailed - unable to complete request raise : Unimplemented - supports _ objectiv...
if not self . supports_objective_hierarchy_design ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) try : session = sessions . ObjectiveHierarchyDesignSession ( runtime = self . _runtime ) except AttributeError : raise OperationFailed ( ) retur...
def _unicode_to_native ( s ) : """Convert string from unicode to native format ( required in Python 2 ) ."""
if six . PY2 : return s . encode ( "utf-8" ) if isinstance ( s , unicode ) else s else : return s
def get_cached ( self , path , cache_name , ** kwargs ) : """Request a resource form the API , first checking if there is a cached response available . Returns the parsed JSON data ."""
if gw2api . cache_dir and gw2api . cache_time and cache_name : cache_file = os . path . join ( gw2api . cache_dir , cache_name ) if mtime ( cache_file ) >= time . time ( ) - gw2api . cache_time : with open ( cache_file , "r" ) as fp : tmp = json . load ( fp ) return self . make_respo...
def simplify_tags ( iob ) : """Simplify tags obtained from the dataset in order to follow Wikipedia scheme ( PER , LOC , ORG , MISC ) . ' PER ' , ' LOC ' and ' ORG ' keep their tags , while ' GPE _ LOC ' is simplified to ' LOC ' , ' GPE _ ORG ' to ' ORG ' and all remaining tags to ' MISC ' ."""
new_iob = [ ] for tag in iob : tag_match = re . match ( "([A-Z_]+)-([A-Z_]+)" , tag ) if tag_match : prefix = tag_match . group ( 1 ) suffix = tag_match . group ( 2 ) if suffix == "GPE_LOC" : suffix = "LOC" elif suffix == "GPE_ORG" : suffix = "ORG" ...
def get_grade_entries_by_ids ( self , grade_entry_ids ) : """Gets a ` ` GradeEntryList ` ` corresponding to the given ` ` IdList ` ` . arg : grade _ entry _ ids ( osid . id . IdList ) : the list of ` ` Ids ` ` to retrieve return : ( osid . grading . GradeEntryList ) - the returned ` ` GradeEntry ` ` list ...
# Implemented from template for # osid . resource . ResourceLookupSession . get _ resources _ by _ ids # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'grading' , collection = 'GradeEntry' , runtime = self . _runtime ) object_id_list = [ ] for i in grade_entry_ids : ob...
def write_to_screen ( self , screen , mouse_handlers , write_position , parent_style , erase_bg , z_index ) : "Fill the whole area of write _ position with dots ."
default_char = Char ( ' ' , 'class:background' ) dot = Char ( '.' , 'class:background' ) ypos = write_position . ypos xpos = write_position . xpos for y in range ( ypos , ypos + write_position . height ) : row = screen . data_buffer [ y ] for x in range ( xpos , xpos + write_position . width ) : row [ x...
def _integrate_fixed_trajectory ( self , h , T , step , relax ) : """Generates a solution trajectory of fixed length ."""
# initialize the solution using initial condition solution = np . hstack ( ( self . t , self . y ) ) while self . successful ( ) : self . integrate ( self . t + h , step , relax ) current_step = np . hstack ( ( self . t , self . y ) ) solution = np . vstack ( ( solution , current_step ) ) if ( h > 0 ) a...
def send ( self , content ) : """Write the content received from the SSH client to the standard input of the forked command . : param str content : string to be sent to the forked command"""
try : self . process . stdin . write ( content ) except IOError as e : # There was a problem with the child process . It probably # died and we can ' t proceed . The best option here is to # raise an exception informing the user that the informed # ProxyCommand is not working . raise ProxyCommandFailure ( " " ....
def update ( self , validate = False ) : """Update the image ' s state information by making a call to fetch the current image attributes from the service . : type validate : bool : param validate : By default , if EC2 returns no data about the image the update method returns quietly . If the validate par...
rs = self . connection . get_all_images ( [ self . id ] ) if len ( rs ) > 0 : img = rs [ 0 ] if img . id == self . id : self . _update ( img ) elif validate : raise ValueError ( '%s is not a valid Image ID' % self . id ) return self . state
def create_signature ( secret , value , digestmod = 'sha256' , encoding = 'utf-8' ) : """Create HMAC Signature from secret for value ."""
if isinstance ( secret , str ) : secret = secret . encode ( encoding ) if isinstance ( value , str ) : value = value . encode ( encoding ) if isinstance ( digestmod , str ) : digestmod = getattr ( hashlib , digestmod , hashlib . sha1 ) hm = hmac . new ( secret , digestmod = digestmod ) hm . update ( value )...
def _calc_uca_chunk ( self , data , dX , dY , direction , mag , flats , area_edges , plotflag = False , edge_todo_i_no_mask = True ) : """Calculates the upstream contributing area for the interior , and includes edge contributions if they are provided through area _ edges ."""
# Figure out which section the drainage goes towards , and what # proportion goes to the straight - sided ( as opposed to diagonal ) node . section , proportion = self . _calc_uca_section_proportion ( data , dX , dY , direction , flats ) # Build the drainage or adjacency matrix A = self . _mk_adjacency_matrix ( section...
def getMessage ( self , realm , return_to = None , immediate = False ) : """Produce a L { openid . message . Message } representing this request . @ param realm : The URL ( or URL pattern ) that identifies your web site to the user when she is authorizing it . @ type realm : str @ param return _ to : The UR...
if return_to : return_to = oidutil . appendArgs ( return_to , self . return_to_args ) elif immediate : raise ValueError ( '"return_to" is mandatory when using "checkid_immediate"' ) elif self . message . isOpenID1 ( ) : raise ValueError ( '"return_to" is mandatory for OpenID 1 requests' ) elif self . return...
def _assemble_corpus_string ( self , corpus ) : """Takes a list of filepaths , returns a string containing contents of all files ."""
if corpus == 'phi5' : filepaths = assemble_phi5_author_filepaths ( ) file_cleaner = phi5_plaintext_cleanup elif corpus == 'tlg' : filepaths = assemble_tlg_author_filepaths ( ) file_cleaner = tlg_plaintext_cleanup for filepath in filepaths : with open ( filepath ) as file_open : file_read = f...
def delete_module ( modname ) : """Delete module and sub - modules from ` sys . module `"""
try : _ = sys . modules [ modname ] except KeyError : raise ValueError ( "Module not found in sys.modules: '{}'" . format ( modname ) ) for module in list ( sys . modules . keys ( ) ) : if module and module . startswith ( modname ) : del sys . modules [ module ]
def imshow_z ( data , name ) : """2D color plot of the quasiparticle weight as a function of interaction and doping"""
zmes = pick_flat_z ( data ) plt . figure ( ) plt . imshow ( zmes . T , origin = 'lower' , extent = [ data [ 'doping' ] . min ( ) , data [ 'doping' ] . max ( ) , 0 , data [ 'u_int' ] . max ( ) ] , aspect = .16 ) plt . colorbar ( ) plt . xlabel ( '$n$' , fontsize = 20 ) plt . ylabel ( '$U/D$' , fontsize = 20 ) plt . save...
def reducer_init_output ( self ) : """establish connection to MongoDB"""
try : self . mongo = MongoGeo ( db = DB , collection = COLLECTION , timeout = MONGO_TIMEOUT ) except ServerSelectionTimeoutError : # failed to connect to running MongoDB instance self . mongo = None
def dot ( self , other_tf ) : """Compose this simliarity transform with another . This transform is on the left - hand side of the composition . Parameters other _ tf : : obj : ` SimilarityTransform ` The other SimilarityTransform to compose with this one . Returns : obj : ` SimilarityTransform ` A Si...
if other_tf . to_frame != self . from_frame : raise ValueError ( 'To frame of right hand side ({0}) must match from frame of left hand side ({1})' . format ( other_tf . to_frame , self . from_frame ) ) if not isinstance ( other_tf , RigidTransform ) : raise ValueError ( 'Can only compose with other RigidTransfo...
def port_channel_redundancy_group_activate ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) port_channel_redundancy_group = ET . SubElement ( config , "port-channel-redundancy-group" , xmlns = "urn:brocade.com:mgmt:brocade-lag" ) group_id_key = ET . SubElement ( port_channel_redundancy_group , "group-id" ) group_id_key . text = kwargs . pop ( 'group_id' ) activate = ET . Sub...
def parse_field ( cls : Type [ DocumentType ] , field_name : str , line : str ) -> Any : """Parse a document field with regular expression and return the value : param field _ name : Name of the field : param line : Line string to parse : return :"""
try : match = cls . fields_parsers [ field_name ] . match ( line ) if match is None : raise AttributeError value = match . group ( 1 ) except AttributeError : raise MalformedDocumentError ( field_name ) return value
def add_update_user ( self , user , capacity = None ) : # type : ( Union [ hdx . data . user . User , Dict , str ] , Optional [ str ] ) - > None """Add new or update existing user in organization with new metadata . Capacity eg . member , admin must be supplied either within the User object or dictionary or using...
if isinstance ( user , str ) : user = hdx . data . user . User . read_from_hdx ( user , configuration = self . configuration ) elif isinstance ( user , dict ) : user = hdx . data . user . User ( user , configuration = self . configuration ) if isinstance ( user , hdx . data . user . User ) : users = self . ...
def element_should_not_exist ( self , json_string , expr ) : """Check that one or more elements , matching [ http : / / jsonselect . org / | JSONSelect ] expression , don ' t exist . * DEPRECATED * JSON Select query language is outdated and not supported any more . Use other keywords of this library to query JS...
value = self . select_elements ( json_string , expr ) if value is not None : raise JsonValidatorError ( 'Elements %s exist but should not' % expr )
def configure_installation_source ( source_plus_key ) : """Configure an installation source . The functionality is provided by charmhelpers . fetch . add _ source ( ) The difference between the two functions is that add _ source ( ) signature requires the key to be passed directly , whereas this function pass...
if source_plus_key . startswith ( 'snap' ) : # Do nothing for snap installs return # extract the key if there is one , denoted by a ' | ' in the rel source , key = get_source_and_pgp_key ( source_plus_key ) # handle the ordinary sources via add _ source try : fetch_add_source ( source , key , fail_invalid = Tru...
def mad ( a ) : '''Calculate the median absolute deviation of a sample a - a numpy array - like collection of values returns the median of the deviation of a from its median .'''
a = np . asfarray ( a ) . flatten ( ) return np . median ( np . abs ( a - np . median ( a ) ) )
def _get ( url , use_kerberos = None , debug = False ) : """Perform a GET query against the CIS"""
from ligo . org import request # perform query try : response = request ( url , debug = debug , use_kerberos = use_kerberos ) except HTTPError : raise ValueError ( "Channel not found at URL %s " "Information System. Please double check the " "name and try again." % url ) if isinstance ( response , bytes ) : ...
def _container_manipulation_allowed ( self ) : # type : ( StorageAccount ) - > bool """Check if container manipulation is allowed : param StorageAccount self : this : rtype : bool : return : if container manipulation is allowed"""
if self . is_sas : # search for account sas " c " resource sasparts = self . key . split ( '&' ) for part in sasparts : tmp = part . split ( '=' ) if tmp [ 0 ] == 'srt' : return 'c' in tmp [ 1 ] # this is a sas without the srt parameter , so this must be # a service - level s...
def profiles ( ) : """List of all the connection profile files , ordered by preference . : returns : list of all Koji client config files . Example : [ ' / home / kdreyer / . koji / config . d / kojidev . conf ' , ' / etc / koji . conf . d / stg . conf ' , ' / etc / koji . conf . d / fedora . conf ' ]"""
paths = [ ] for pattern in PROFILES : pattern = os . path . expanduser ( pattern ) paths += glob ( pattern ) return paths
def mean ( self ) : """Return the sample mean ."""
if len ( self ) == 0 : return float ( 'NaN' ) arr = self . samples ( ) return sum ( arr ) / float ( len ( arr ) )
def determine_indent ( str ) : """Figure out the character ( s ) used for indents in a given source code fragement . Parameters str : string source code starting at an indent of 0 and containing at least one indented block . Returns string The character ( s ) used for indenting . Example code = " de...
indent = None reg = r""" ^(?P<previous_indent>\s*)\S.+?:\n # line starting a block, i. e. ' for i in x:\n' ((\s*)\n)* # empty lines (?P=previous_indent)(?P<indent>\s+)\S # first indented line of the new block, i. e. ' d'(..oStuff()) """ matches = re . com...
def list_ebs ( region , filter_by_kwargs ) : """List running ebs volumes ."""
conn = boto . ec2 . connect_to_region ( region ) instances = conn . get_all_volumes ( ) return lookup ( instances , filter_by = filter_by_kwargs )
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : WorkerStatisticsContext for this WorkerStatisticsInstance : rtype : twilio . rest . taskrouter . v1 . workspace . worker ....
if self . _context is None : self . _context = WorkerStatisticsContext ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , worker_sid = self . _solution [ 'worker_sid' ] , ) return self . _context
def _screen_size_cb ( self , w , tf ) : """This function is called when the user clicks the ' Screen size ' checkbox . ` tf ` is True if checked , False otherwise ."""
self . _screen_size = tf self . w . width . set_enabled ( not tf ) self . w . height . set_enabled ( not tf ) self . w . lock_aspect . set_enabled ( not tf ) if self . _screen_size : wd , ht = self . fitsimage . get_window_size ( ) self . _configure_cb ( self . fitsimage , wd , ht )
def parse_input_samples ( job , inputs ) : """Parses config file to pull sample information . Stores samples as tuples of ( uuid , URL ) : param JobFunctionWrappingJob job : passed by Toil automatically : param Namespace inputs : Stores input arguments ( see main )"""
job . fileStore . logToMaster ( 'Parsing input samples and batching jobs' ) samples = [ ] if inputs . config : with open ( inputs . config , 'r' ) as f : for line in f . readlines ( ) : if not line . isspace ( ) : sample = line . strip ( ) . split ( ',' ) assert l...
def _run ( name , ** kwargs ) : '''. . deprecated : : 2017.7.0 Function name stays the same , behaviour will change . Run a single module function ` ` name ` ` The module function to execute ` ` returner ` ` Specify the returner to send the return of the module execution to ` ` kwargs ` ` Pass any a...
ret = { 'name' : name , 'changes' : { } , 'comment' : '' , 'result' : None } if name not in __salt__ : ret [ 'comment' ] = 'Module function {0} is not available' . format ( name ) ret [ 'result' ] = False return ret if __opts__ [ 'test' ] : ret [ 'comment' ] = 'Module function {0} is set to execute' . f...
def pprint_value ( self , value ) : """Applies the applicable formatter to the value . Args : value : Dimension value to format Returns : Formatted dimension value"""
own_type = type ( value ) if self . type is None else self . type formatter = ( self . value_format if self . value_format else self . type_formatters . get ( own_type ) ) if formatter : if callable ( formatter ) : return formatter ( value ) elif isinstance ( formatter , basestring ) : if isinst...
def set_refresh_cookies ( response , encoded_refresh_token , max_age = None ) : """Takes a flask response object , and an encoded refresh token , and configures the response to set in the refresh token in a cookie . If ` JWT _ CSRF _ IN _ COOKIES ` is ` True ` ( see : ref : ` Configuration Options ` ) , this wi...
if not config . jwt_in_cookies : raise RuntimeWarning ( "set_refresh_cookies() called without " "'JWT_TOKEN_LOCATION' configured to use cookies" ) # Set the refresh JWT in the cookie response . set_cookie ( config . refresh_cookie_name , value = encoded_refresh_token , max_age = max_age or config . cookie_max_age ,...
def _get_arguments_for_execution ( self , function_name , serialized_args ) : """Retrieve the arguments for the remote function . This retrieves the values for the arguments to the remote function that were passed in as object IDs . Arguments that were passed by value are not changed . This is called by the w...
arguments = [ ] for ( i , arg ) in enumerate ( serialized_args ) : if isinstance ( arg , ObjectID ) : # get the object from the local object store argument = self . get_object ( [ arg ] ) [ 0 ] if isinstance ( argument , RayError ) : raise argument else : # pass the argument by value...
def machine ( self , machine_id , credentials = False ) : """GET / : login / machines / : id : param machine _ id : unique identifier for a machine to be found in the datacenter : type machine _ id : : py : class : ` basestring ` : rtype : : py : class : ` smartdc . machine . Machine `"""
if isinstance ( machine_id , dict ) : machine_id = machine_id [ 'id' ] elif isinstance ( machine_id , Machine ) : machine_id = machine_id . id return Machine ( datacenter = self , machine_id = machine_id , credentials = credentials )
def count_called ( self , axis = None ) : """Count called genotypes . Parameters axis : int , optional Axis over which to count , or None to perform overall count ."""
b = self . is_called ( ) return np . sum ( b , axis = axis )
def do_action ( self , names , kwargs ) : '''Perform an action on a VM which may be specific to this cloud provider'''
ret = { } invalid_functions = { } names = set ( names ) for alias , drivers in six . iteritems ( self . map_providers_parallel ( ) ) : if not names : break for driver , vms in six . iteritems ( drivers ) : if not names : break valid_function = True fun = '{0}.{1}' . f...
def get_subdomains_count ( self , accepted = True , cur = None ) : """Fetch subdomain names"""
if accepted : accepted_filter = 'WHERE accepted=1' else : accepted_filter = '' get_cmd = "SELECT COUNT(DISTINCT fully_qualified_subdomain) as count FROM {} {};" . format ( self . subdomain_table , accepted_filter ) cursor = cur if cursor is None : cursor = self . conn . cursor ( ) db_query_execute ( cursor ...
def get_movielens_iter ( filename , batch_size ) : """Not particularly fast code to parse the text file and load into NDArrays . return two data iters , one for train , the other for validation ."""
logging . info ( "Preparing data iterators for " + filename + " ... " ) user = [ ] item = [ ] score = [ ] with open ( filename , 'r' ) as f : num_samples = 0 for line in f : tks = line . strip ( ) . split ( '::' ) if len ( tks ) != 4 : continue num_samples += 1 user ....
def learn ( self ) : """Learn on the current dataset , either for many timesteps and even episodes ( batchMode = True ) or for a single timestep ( batchMode = False ) . Batch mode is possible , because Q - Learning is an off - policy method . In batchMode , the algorithm goes through all the samples in the ...
if self . batchMode : samples = self . dataset else : samples = [ [ self . dataset . getSample ( ) ] ] for seq in samples : for lastState , lastAction , reward in seq : self . _updatePropensities ( int ( lastState ) , int ( lastAction ) , reward )
def _must_decode ( value ) : """Copied from pkginfo 1.4.1 , _ compat module ."""
if type ( value ) is bytes : try : return value . decode ( 'utf-8' ) except UnicodeDecodeError : return value . decode ( 'latin1' ) return value
def _create_task_problem ( self , problemid , problem_content , task_problem_types ) : """Creates a new instance of the right class for a given problem ."""
# Basic checks if not id_checker ( problemid ) : raise Exception ( "Invalid problem _id: " + problemid ) if problem_content . get ( 'type' , "" ) not in task_problem_types : raise Exception ( "Invalid type for problem " + problemid ) return task_problem_types . get ( problem_content . get ( 'type' , "" ) ) ( se...
def moves_in_direction ( self , direction , position ) : """Finds moves in a given direction : type : direction : lambda : type : position : Board : rtype : list"""
current_square = self . location while True : try : current_square = direction ( current_square ) except IndexError : return if self . contains_opposite_color_piece ( current_square , position ) : yield self . create_move ( current_square , notation_const . CAPTURE ) if not posit...
def from_json_dict ( cls , json_dict # type : Dict [ str , Any ] ) : # type : ( . . . ) - > DateSpec """Make a DateSpec object from a dictionary containing its properties . : param dict json _ dict : This dictionary must contain a ` ' format ' ` key . In addition , it must contain a ` ' hashing ' ` key , wh...
# noinspection PyCompatibility result = cast ( DateSpec , # For Mypy . super ( ) . from_json_dict ( json_dict ) ) format_ = json_dict [ 'format' ] result . format = format_ [ 'format' ] return result
def where ( cls , where_clause = "" , start_position = "" , max_results = "" , qb = None ) : """: param where _ clause : QBO SQL where clause ( DO NOT include ' WHERE ' ) : param start _ position : : param max _ results : : param qb : : return : Returns list filtered by input where _ clause"""
if where_clause : where_clause = "WHERE " + where_clause if start_position : start_position = " STARTPOSITION " + str ( start_position ) if max_results : max_results = " MAXRESULTS " + str ( max_results ) select = "SELECT * FROM {0} {1}{2}{3}" . format ( cls . qbo_object_name , where_clause , start_position...
def optimize_images ( pelican ) : """Optimized jpg and png images : param pelican : The Pelican instance"""
for dirpath , _ , filenames in os . walk ( pelican . settings [ 'OUTPUT_PATH' ] ) : for name in filenames : if os . path . splitext ( name ) [ 1 ] in COMMANDS . keys ( ) : optimize ( dirpath , name )
def normalize_name ( name ) : """When looking up a language - code component by name , we would rather ignore distinctions of case and certain punctuation . " Chinese ( Traditional ) " should be matched by " Chinese Traditional " and " chinese traditional " ."""
name = name . casefold ( ) name = name . replace ( "’" , "'" ) name = name . replace ( "-" , " " ) name = name . replace ( "(" , "" ) name = name . replace ( ")" , "" ) name = name . replace ( "," , "" ) return name . strip ( )
def check ( state_engine , token_op , block_id , checked_ops ) : """Verify that a token transfer operation is permitted . * the token feature must exist * the sender must be unlocked - - - i . e . able to send at this point * the sender must have enough balance of the given token to send the amount requested ...
epoch_features = get_epoch_features ( block_id ) if EPOCH_FEATURE_TOKEN_TRANSFER not in epoch_features : log . warning ( "Token transfers are not enabled in this epoch" ) return False consensus_hash = token_op [ 'consensus_hash' ] address = token_op [ 'address' ] recipient_address = token_op [ 'recipient_addres...
def p_label_line_co ( p ) : """label _ line _ co : LABEL statements _ co | LABEL co _ statements _ co | LABEL"""
lbl = make_label ( p [ 1 ] , p . lineno ( 1 ) ) p [ 0 ] = make_block ( lbl , p [ 2 ] ) if len ( p ) == 3 else lbl
def section_bif_radial_distances ( neurites , neurite_type = NeuriteType . all , origin = None ) : '''Get the radial distances of the bifurcation sections for a collection of neurites'''
return section_radial_distances ( neurites , neurite_type = neurite_type , origin = origin , iterator_type = Tree . ibifurcation_point )
def get_place_tags ( index_page , domain ) : # : TODO geoip to docstring """Return list of ` place ` tags parsed from ` meta ` and ` whois ` . Args : index _ page ( str ) : HTML content of the page you wisht to analyze . domain ( str ) : Domain of the web , without ` ` http : / / ` ` or other parts . Return...
ip_address = get_ip_address ( domain ) dom = dhtmlparser . parseString ( index_page ) place_tags = [ get_html_geo_place_tags ( dom ) , get_whois_tags ( ip_address ) , # [ _ get _ geo _ place _ tag ( ip _ address ) ] , # TODO : implement geoip ] return sum ( place_tags , [ ] )
def _unflatten_beam_dim ( tensor , batch_size , beam_size ) : """Reshapes first dimension back to [ batch _ size , beam _ size ] . Args : tensor : Tensor to reshape of shape [ batch _ size * beam _ size , . . . ] batch _ size : Tensor , original batch size . beam _ size : int , original beam size . Return...
shape = _shape_list ( tensor ) new_shape = [ batch_size , beam_size ] + shape [ 1 : ] return tf . reshape ( tensor , new_shape )
def _search_body ( self , search_type , search_term , start , max_items ) : """Return the search XML body . : param search _ type : The search type : type search _ type : str : param search _ term : The search term e . g . ' Jon Bon Jovi ' : type search _ term : str : param start : The start index of the ...
xml = self . _base_body ( ) # Add the Body part XML . SubElement ( xml , 's:Body' ) item_attrib = { 'xmlns' : 'http://www.sonos.com/Services/1.1' } search = XML . SubElement ( xml [ 1 ] , 'search' , item_attrib ) XML . SubElement ( search , 'id' ) . text = search_type XML . SubElement ( search , 'term' ) . text = searc...
def network_show ( self , name ) : '''Show network information'''
nt_ks = self . compute_conn net_list = nt_ks . networks . list ( ) return self . _network_show ( name , net_list )
def _normalize ( self , key , value ) : """Use normalize _ < key > methods to normalize user input . Any user input will be normalized at the moment it is used as filter , or entered as a value of Task attribute ."""
# None value should not be converted by normalizer if value is None : return None normalize_func = getattr ( self , 'normalize_{0}' . format ( key ) , lambda x : x ) return normalize_func ( value )
def _get_best_merge ( routing_table , aliases ) : """Inspect all possible merges for the routing table and return the merge which would combine the greatest number of entries . Returns : py : class : ` ~ . Merge `"""
# Create an empty merge to start with best_merge = _Merge ( routing_table ) best_goodness = 0 # Look through every merge , discarding those that are no better than the # best we currently know about . for merge in _get_all_merges ( routing_table ) : # If the merge isn ' t sufficiently good ignore it and move on if ...
def load ( cls , filename ) : """Load from stored files"""
filename = cls . correct_file_extension ( filename ) with open ( filename , 'rb' ) as f : return pickle . load ( f )
def from_scf_input ( cls , workdir , scf_input , ph_ngqpt , with_becs = True , manager = None , allocate = True ) : """Create a ` PhononFlow ` for phonon calculations from an ` AbinitInput ` defining a ground - state run . Args : workdir : Working directory of the flow . scf _ input : : class : ` AbinitInput ...
flow = cls ( workdir , manager = manager ) # Register the SCF task flow . register_scf_task ( scf_input ) scf_task = flow [ 0 ] [ 0 ] # Make sure k - mesh and q - mesh are compatible . scf_ngkpt , ph_ngqpt = np . array ( scf_input [ "ngkpt" ] ) , np . array ( ph_ngqpt ) if any ( scf_ngkpt % ph_ngqpt != 0 ) : raise ...