signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def connect ( self ) : """Overrides HTTPSConnection . connect to specify TLS version"""
# Standard implementation from HTTPSConnection , which is not # designed for extension , unfortunately sock = socket . create_connection ( ( self . host , self . port ) , self . timeout , self . source_address ) if getattr ( self , '_tunnel_host' , None ) : self . sock = sock # pragma : no cover self . _tun...
def open ( self , tid , flags ) : """File open . ` ` YTStor ` ` object associated with this file is initialised and written to ` ` self . fds ` ` . Parameters tid : str Path to file . Original ` path ` argument is converted to tuple identifier by ` ` _ pathdec ` ` decorator . flags : int File open mode . ...
pt = self . PathType . get ( tid ) if pt is not self . PathType . file and pt is not self . PathType . ctrl : raise FuseOSError ( errno . EINVAL ) if pt is not self . PathType . ctrl and ( flags & os . O_WRONLY or flags & os . O_RDWR ) : raise FuseOSError ( errno . EPERM ) if not self . __exists ( tid ) : r...
def create_lexicon ( self , data_set_reader , n_grams , min_total_occurrences , min_sentiment_value , filters ) : """Generates sentiment lexicon using PMI on words and classification of context they are in . : param : dataSetReader Dataset containing tweets and their sentiment classification : param : nGrams n ...
counter = self . count_n_grams_py_polarity ( data_set_reader , n_grams , filters ) lexicon = { } pos = sum ( map ( lambda i : i . num_positive , counter . values ( ) ) ) neg = sum ( map ( lambda i : i . num_negative , counter . values ( ) ) ) ratio = neg / float ( pos ) for key , value in counter . items ( ) : if v...
def clean_core ( self , config_file , region = None , profile_name = None ) : """Clean all Core related provisioned artifacts from both the local file and the AWS Greengrass service . : param config _ file : config file containing the core to clean : param region : the region in which the core should be clean...
config = GroupConfigFile ( config_file = config_file ) if region is None : region = self . _region # delete the Core ' s Certificate core_cert_id = config [ 'core' ] [ 'cert_id' ] core_cert_arn = config [ 'core' ] [ 'cert_arn' ] core_thing_name = config [ 'core' ] [ 'thing_name' ] policy_name = config [ 'misc' ] [ ...
def get_port_channel_detail_output_lacp_aggr_member_interface_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_port_channel_detail = ET . Element ( "get_port_channel_detail" ) config = get_port_channel_detail output = ET . SubElement ( get_port_channel_detail , "output" ) lacp = ET . SubElement ( output , "lacp" ) aggr_member = ET . SubElement ( lacp , "aggr-member" ) interface_name = ET ....
def create_invoices ( account_id : str , due_date : date ) -> Sequence [ Invoice ] : """Creates the invoices for any due positive charges in the account . If there are due positive charges in different currencies , one invoice is created for each currency . : param account _ id : The account to invoice . : pa...
invoices = [ ] with transaction . atomic ( ) : due_charges = Charge . objects . uninvoiced ( account_id = account_id ) . charges ( ) total = total_amount ( due_charges ) for amount_due in total . monies ( ) : if amount_due . amount > 0 : invoice = Invoice . objects . create ( account_id ...
def limit_update ( db , key , limits ) : """Safely updates the list of limits in the database . : param db : The database handle . : param key : The key the limits are stored under . : param limits : A list or sequence of limit objects , each understanding the dehydrate ( ) method . The limits list curren...
# Start by dehydrating all the limits desired = [ msgpack . dumps ( l . dehydrate ( ) ) for l in limits ] desired_set = set ( desired ) # Now , let ' s update the limits with db . pipeline ( ) as pipe : while True : try : # Watch for changes to the key pipe . watch ( key ) # Look up ...
def uninstall_plugin ( pkgpath , force ) : """Uninstall a plugin . : param pkgpath : Path to package to uninstall ( delete ) : param force : Force uninstall without asking"""
pkgname = os . path . basename ( pkgpath ) if os . path . exists ( pkgpath ) : if not force : click . confirm ( "[?] Are you sure you want to delete `{}` from honeycomb?" . format ( pkgname ) , abort = True ) try : shutil . rmtree ( pkgpath ) logger . debug ( "successfully uninstalled {}...
def _column_resized ( self , col , old_width , new_width ) : """Update the column width ."""
self . dataTable . setColumnWidth ( col , new_width ) self . _update_layout ( )
def from_moment_relative_to_crystal_axes ( cls , moment , lattice ) : """Obtaining a Magmom object from a magnetic moment provided relative to crystal axes . Used for obtaining moments from magCIF file . : param magmom : list of floats specifying vector magmom : param lattice : Lattice : return : Magmom""...
# get matrix representing unit lattice vectors unit_m = lattice . matrix / np . linalg . norm ( lattice . matrix , axis = 1 ) [ : , None ] moment = np . matmul ( list ( moment ) , unit_m ) # round small values to zero moment [ np . abs ( moment ) < 1e-8 ] = 0 return cls ( moment )
def get_environment ( self , fUnicode = None ) : """Retrieves the environment with wich the program is running . @ note : Duplicated keys are joined using null characters . To avoid this behavior , call L { get _ environment _ variables } instead and convert the results to a dictionary directly , like this : ...
# Get the environment variables . variables = self . get_environment_variables ( ) # Convert the strings to ANSI if requested . if fUnicode is None : gst = win32 . GuessStringType fUnicode = gst . t_default == gst . t_unicode if not fUnicode : variables = [ ( key . encode ( 'cp1252' ) , value . encode ( 'cp...
def parse_arguments ( args , config ) : """Parse specified arguments via config Parameters args : list Command line arguments config : object ConfigParser instance which values are used as default values of options Returns list : arguments , options options indicate the return value of ArgumentPar...
import notify from conf import config_to_options opts = config_to_options ( config ) usage = ( "%(prog)s " "[-h] [-t TO_ADDR] [-f FROM_ADDR] [-e ENCODING] [-s SUBJECT]\n" " " "[-o HOST] [-p PORT] [--username USERNAME] [--password PASSWORD]\n" " " "[--setup] [--check] COMMAND ARGUMENTS" ) % { '...
def axes ( self ) : """Returns all the axes that have been defined for this chart . : return [ < projexui . widgets . xchart . XChartAxis > , . . ]"""
out = self . _axes [ : ] if self . _horizontalAxis : out . append ( self . _horizontalAxis ) if self . _verticalAxis : out . append ( self . _verticalAxis ) return out
def tag ( self , tag , child = '' , enclose = 0 , newline = True , ** kwargs ) : """enclose : 0 = > < tag > 1 = > < tag / > 2 = > < tag > < / tag >"""
kw = kwargs . copy ( ) _class = '' if '_class' in kw : _class = kw . pop ( '_class' ) if 'class' in kw : _class += ' ' + kw . pop ( 'class' ) tag_class = self . tag_class . get ( tag , '' ) if tag_class : # if tag _ class definition starts with ' + ' , and combine it with original value if tag_class . start...
def move_to ( self , r ) : '''Translate the molecule to a new position * r * .'''
dx = r - self . r_array [ 0 ] self . r_array += dx
def find_objects ( uid = None ) : """Find the object by its UID 1 . get the object from the given uid 2 . fetch objects specified in the request parameters 3 . fetch objects located in the request body : param uid : The UID of the object to find : type uid : string : returns : List of found objects : ...
# The objects to cut objects = [ ] # get the object by the given uid or try to find it by the request # parameters obj = get_object_by_uid ( uid ) or get_object_by_request ( ) if obj : objects . append ( obj ) else : # no uid - > go through the record items records = req . get_request_data ( ) for record in...
def volume_absent ( name , volume_name = None , volume_id = None , instance_name = None , instance_id = None , device = None , region = None , key = None , keyid = None , profile = None ) : '''Ensure the EC2 volume is detached and absent . . . versionadded : : 2016.11.0 name State definition name . volume _...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } filters = { } running_states = ( 'pending' , 'rebooting' , 'running' , 'stopping' , 'stopped' ) if not salt . utils . data . exactly_one ( ( volume_name , volume_id , instance_name , instance_id ) ) : raise SaltInvocationError ( "Exactly o...
def __get_oauth_url ( self , url , method , ** kwargs ) : """Generate oAuth1.0a URL"""
oauth = OAuth ( url = url , consumer_key = self . consumer_key , consumer_secret = self . consumer_secret , version = self . version , method = method , oauth_timestamp = kwargs . get ( "oauth_timestamp" , int ( time ( ) ) ) ) return oauth . get_oauth_url ( )
def to_snake_case ( name ) : """Given a name in camelCase return in snake _ case"""
s1 = FIRST_CAP_REGEX . sub ( r'\1_\2' , name ) return ALL_CAP_REGEX . sub ( r'\1_\2' , s1 ) . lower ( )
def AckFlowProcessingRequests ( self , requests ) : """Deletes a list of flow processing requests from the database ."""
for r in requests : key = ( r . client_id , r . flow_id ) if key in self . flow_processing_requests : del self . flow_processing_requests [ key ]
def generate_key ( block_size = 32 ) : """Generate random key for ope cipher . Parameters block _ size : int , optional Length of random bytes . Returns random _ key : str A random key for encryption . Notes : Implementation follows https : / / github . com / pyca / cryptography"""
random_seq = os . urandom ( block_size ) random_key = base64 . b64encode ( random_seq ) return random_key
def clean ( self , * args , ** kwargs ) : """validation"""
self . _validate_backend ( ) self . _validate_config ( ) self . _validate_netengine ( ) self . _validate_duplicates ( )
def MergeOrAddUser ( self , kb_user ) : """Merge a user into existing users or add new if it doesn ' t exist . Args : kb _ user : A User rdfvalue . Returns : A list of strings with the set attribute names , e . g . [ " users . sid " ]"""
user = self . GetUser ( sid = kb_user . sid , uid = kb_user . uid , username = kb_user . username ) new_attrs = [ ] merge_conflicts = [ ] # Record when we overwrite a value . if not user : new_attrs = self . _CreateNewUser ( kb_user ) else : for key , val in iteritems ( kb_user . AsDict ( ) ) : if user ...
def make_gears_cache_registry ( args ) : """create a new gears registry cache on Ariane Server : param args : the cache parameters - look to the tests to know more : return : remote procedure call return - look to the tests to know more"""
LOGGER . debug ( "InjectorCachedRegistryFactoryService.make_gears_cache_registry" ) if args is None : err_msg = 'InjectorCachedRegistryFactoryService.make_gears_cache_registry - not args defined !' LOGGER . debug ( err_msg ) return None if 'registry.name' not in args or args [ 'registry.name' ] is None or n...
def setcover_greedy ( candidate_sets_dict , items = None , set_weights = None , item_values = None , max_weight = None ) : r"""Greedy algorithm for various covering problems . approximation gaurentees depending on specifications like set _ weights and item values Set Cover : log ( len ( items ) + 1 ) approximat...
import utool as ut solution_cover = { } # If candset _ weights or item _ values not given use the length as defaults if items is None : items = ut . flatten ( candidate_sets_dict . values ( ) ) if set_weights is None : get_weight = len else : def get_weight ( solution_cover ) : sum ( [ set_weights [...
def DbGetHostServersInfo ( self , argin ) : """Get info about all servers running on specified host , name , mode and level : param argin : Host name : type : tango . DevString : return : Server info for all servers running on specified host : rtype : tango . DevVarStringArray"""
self . _log . debug ( "In DbGetHostServersInfo()" ) argin = replace_wildcard ( argin ) return self . db . get_host_servers_info ( argin )
def _add_element ( self , cls , ** kwargs ) : """Add an element ."""
# Convert stylename strings to actual style elements . kwargs = self . _replace_stylename ( kwargs ) el = cls ( ** kwargs ) self . _doc . text . addElement ( el )
def find_ui_tree_entity ( entity_id = None , entity_value = None , entity_ca = None ) : """find the Ariane UI tree menu entity depending on its id ( priority ) , value or context address : param entity _ id : the Ariane UI tree menu ID to search : param entity _ value : the Ariane UI tree menu Value to search ...
LOGGER . debug ( "InjectorUITreeService.find_ui_tree_entity" ) operation = None search_criteria = None criteria_value = None if entity_id is not None : operation = 'GET_TREE_MENU_ENTITY_I' search_criteria = 'id' criteria_value = entity_id if operation is None and entity_value is not None : operation = '...
def get_params_from_func ( func : Callable , signature : Signature = None ) -> Params : """Gets all parameters from a function signature . : param func : The function to inspect . : param signature : An inspect . Signature instance . : returns : A named tuple containing information about all , optional , re...
if signature is None : # Check if the function already parsed the signature signature = getattr ( func , '_doctor_signature' , None ) # Otherwise parse the signature if signature is None : signature = inspect . signature ( func ) # Check if a ` req _ obj _ type ` was provided for the function . If s...
def isolines ( obj , prop , val , outliers = None , data_range = None , clipped = np . inf , weights = None , weight_min = 0 , weight_transform = Ellipsis , mask = None , valid_range = None , transform = None , smooth = False , yield_addresses = False ) : '''isolines ( mesh , prop , val ) yields a 2 x D x N array o...
import scipy . sparse as sps from neuropythy import ( is_subject , is_list , is_tuple , is_topo , is_mesh , is_tess ) from neuropythy . util import flattest if is_subject ( obj ) : kw = dict ( outliers = outliers , data_range = data_range , clipped = clipped , weights = weights , weight_min = weight_min , weight_tr...
def update ( self , dt ) : """Tasks that occur over time should be handled here"""
self . group . update ( dt ) # check if the sprite ' s feet are colliding with wall # sprite must have a rect called feet , and move _ back method , # otherwise this will fail for sprite in self . group . sprites ( ) : if sprite . feet . collidelist ( self . walls ) > - 1 : sprite . move_back ( dt )
def download ( url , dest ) : """Download the image to disk ."""
path = os . path . join ( dest , url . split ( '/' ) [ - 1 ] ) r = requests . get ( url , stream = True ) r . raise_for_status ( ) with open ( path , 'wb' ) as f : for chunk in r . iter_content ( chunk_size = 1024 ) : if chunk : f . write ( chunk ) return path
def run ( self , data_portal = None ) : """Run the algorithm ."""
# HACK : I don ' t think we really want to support passing a data portal # this late in the long term , but this is needed for now for backwards # compat downstream . if data_portal is not None : self . data_portal = data_portal self . asset_finder = data_portal . asset_finder elif self . data_portal is None : ...
def msg_curse ( self , args = None , max_width = None ) : """Return the dict to display in the curse interface ."""
# Init the return message ret = [ ] # Only process if stats exist and display plugin enable . . . if not self . stats or self . is_disable ( ) : return ret # Max size for the interface name name_max_width = max_width - 7 # Header msg = '{:{width}}' . format ( 'FOLDERS' , width = name_max_width ) ret . append ( self...
def log_time ( func : Callable [ ... , Any ] ) -> Callable [ ... , Any ] : """Log the time it takes to run a function . It ' s sort of like timeit , but prettier ."""
def wrapper ( * args , ** kwargs ) : start_time = time . time ( ) log . info ( "%s starting..." , func . __name__ . title ( ) ) ret = func ( * args , ** kwargs ) log . info ( "%s finished (%s)" , func . __name__ . title ( ) , datetime . timedelta ( seconds = int ( time . time ( ) - start_time ) ) , ) ...
def list_blocks_of_type ( self , blocktype , size ) : """This function returns the AG list of a specified block type ."""
blocktype = snap7 . snap7types . block_types . get ( blocktype ) if not blocktype : raise Snap7Exception ( "The blocktype parameter was invalid" ) logger . debug ( "listing blocks of type: %s size: %s" % ( blocktype , size ) ) if ( size == 0 ) : return 0 data = ( c_uint16 * size ) ( ) count = c_int ( size ) res...
def get_version ( self , layer_id , version_id , expand = [ ] ) : """Get a specific version of a layer ."""
target_url = self . client . get_url ( 'VERSION' , 'GET' , 'single' , { 'layer_id' : layer_id , 'version_id' : version_id } ) return self . _get ( target_url , expand = expand )
def volumes ( self ) : """Returns a list of the volumes attached to the instance Returns : ` list ` of ` EBSVolume `"""
return [ EBSVolume ( res ) for res in db . Resource . join ( ResourceProperty , Resource . resource_id == ResourceProperty . resource_id ) . filter ( Resource . resource_type_id == ResourceType . get ( 'aws_ebs_volume' ) . resource_type_id , ResourceProperty . name == 'attachments' , func . JSON_CONTAINS ( ResourceProp...
def __read_config ( self , file_path : str ) : """Read the config file"""
if not os . path . exists ( file_path ) : raise FileNotFoundError ( "File path not found: %s" , file_path ) # check if file exists if not os . path . isfile ( file_path ) : log ( ERROR , "file not found: %s" , file_path ) raise FileNotFoundError ( "configuration file not found %s" , file_path ) self . confi...
def reanimate ( self , _time = None ) : """Move dead proxies to unchecked if a backoff timeout passes"""
n_reanimated = 0 now = _time or time . time ( ) for proxy in list ( self . dead ) : state = self . proxies [ proxy ] assert state . next_check is not None if state . next_check <= now : self . dead . remove ( proxy ) self . unchecked . add ( proxy ) n_reanimated += 1 return n_reanima...
def reset_threads ( old_function ) : """Resets original threading . _ get _ ident ( ) function ."""
with _waitforthreads_lock : if hasattr ( threading , 'get_ident' ) : threading . get_ident = old_function else : threading . _get_ident = old_function
def configure ( self , ** kwargs ) : '''Configure what assertion logging is done . Settings configured with this method are overridden by environment variables . Parameters logfile : str or bytes or file object If a string or bytes object , we write to that filename . If an open file object , we just wr...
if 'logfile' in kwargs : # Note that kwargs [ ' logfile ' ] might be an open file # object , not a string . We deal with this in # _ open _ if _ needed , but refactoring it so that in that case # it gets set on another attribute would be tricky to # handle the lazy opening semantics that let us override # it with MARBL...
def assign_item ( self , item , origin ) : """Assigns an item from a given cluster to the closest located cluster . : param item : the item to be moved . : param origin : the originating cluster ."""
closest_cluster = origin for cluster in self . __clusters : if self . distance ( item , centroid ( cluster ) ) < self . distance ( item , centroid ( closest_cluster ) ) : closest_cluster = cluster if id ( closest_cluster ) != id ( origin ) : self . move_item ( item , origin , closest_cluster ) retur...
def lb_to_radec ( l , b , degree = False , epoch = 2000.0 ) : """NAME : lb _ to _ radec PURPOSE : transform from Galactic coordinates to equatorial coordinates INPUT : l - Galactic longitude b - Galactic lattitude degree - ( Bool ) if True , l and b are given in degree and ra and dec will be as well ...
if _APY_COORDS : epoch , frame = _parse_epoch_frame_apy ( epoch ) c = apycoords . SkyCoord ( l * units . rad , b * units . rad , frame = 'galactic' ) if not epoch is None and 'J' in epoch : c = c . transform_to ( apycoords . FK5 ( equinox = epoch ) ) elif not epoch is None and 'B' in epoch : ...
def _set_queue_size ( self , v , load = False ) : """Setter method for queue _ size , mapped from YANG variable / interface / ethernet / qos / rx _ queue / multicast / queue _ size ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ queue _ size is considered as a ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "traffic_class" , queue_size . queue_size , yang_name = "queue-size" , rest_name = "queue-size" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = '...
def is_conformal ( self ) : """True if the transform is conformal , i . e . , if angles between points are preserved after applying the transform , within rounding limits . This implies that the transform has no effective shear ."""
a , b , c , d , e , f , g , h , i = self return abs ( a * b + d * e ) < EPSILON
def groups_remove_owner ( self , room_id , user_id , ** kwargs ) : """Removes the role of owner from a user in the current Group ."""
return self . __call_api_post ( 'groups.removeOwner' , roomId = room_id , userId = user_id , kwargs = kwargs )
def run_dev_cmd ( cmd_list , auth , url , devid = None , devip = None ) : """Function takes devid of target device and a sequential list of strings which define the specific commands to be run on the target device and returns a str object containing the output of the commands . : param devid : int devid of th...
if devip is not None : devid = get_dev_details ( devip , auth , url ) [ 'id' ] run_dev_cmd_url = '/imcrs/icc/confFile/executeCmd' f_url = url + run_dev_cmd_url cmd_list = _make_cmd_list ( cmd_list ) payload = '''{ "deviceId" : "''' + str ( devid ) + '''", "cmdlist" : { "cmd" : ...
def _asym_transform_deriv_shape ( systematic_utilities , alt_IDs , rows_to_alts , eta , ref_position = None , dh_dc_array = None , fill_dc_d_eta = None , output_array = None , * args , ** kwargs ) : """Parameters systematic _ utilities : 1D ndarray . Contains the systematic utilities for each each available alt...
# Convert the reduced shape parameters to the natural shape parameters natural_shape_params = _convert_eta_to_c ( eta , ref_position ) # Calculate the derivative of the transformed utilities with respect to # the vector of natural shape parameters , c # Create a vector which contains the appropriate shape for each row ...
def code_block ( self , node , entering ) : '''Output Pygments if required else use default html5 output'''
if self . use_pygments : self . cr ( ) info_words = node . info . split ( ) if node . info else [ ] if len ( info_words ) > 0 and len ( info_words [ 0 ] ) > 0 : try : lexer = get_lexer_by_name ( info_words [ 0 ] ) except ValueError : # no lexer found - use the text one instead of...
def discrete ( cats , name = 'discrete' ) : """Return a class category that shows the encoding"""
import json ks = list ( cats ) for key in ks : if isinstance ( key , bytes ) : cats [ key . decode ( 'utf-8' ) ] = cats . pop ( key ) return 'discrete(' + json . dumps ( [ cats , name ] ) + ')'
def grab_next ( self , timeout : float = None ) -> typing . List [ DataAndMetadata . DataAndMetadata ] : """Grab the next data to finish from the buffer , blocking until one is available ."""
with self . __buffer_lock : self . __buffer = list ( ) return self . grab_latest ( timeout )
def parse_url ( self , url_string ) : """Parse the URL string with the url map of this app instance . : param url _ string : the origin URL string . : returns : the tuple as ` ( url , url _ adapter , query _ args ) ` , the url is parsed by the standard library ` urlparse ` , the url _ adapter is from the we...
url = urllib . parse . urlparse ( url_string ) url = self . validate_url ( url ) url_adapter = self . url_map . bind ( server_name = url . hostname , url_scheme = url . scheme , path_info = url . path ) query_args = url_decode ( url . query ) return url , url_adapter , query_args
def delete_cookie ( self , key : str , path : str = '/' , domain : Optional [ str ] = None ) -> None : """Delete a cookie ( set to expire immediately ) ."""
self . set_cookie ( key , expires = datetime . utcnow ( ) , max_age = 0 , path = path , domain = domain )
def getLogLevelNo ( level ) : """Return numerical log level or raise ValueError . A valid level is either an integer or a string such as WARNING etc ."""
if isinstance ( level , ( int , long ) ) : return level try : return ( int ( logging . getLevelName ( level . upper ( ) ) ) ) except : raise ValueError ( 'illegal loglevel %s' % level )
def to_dict ( self ) : """Encode the name , the status of all checks , and the current overall status ."""
if not isinstance ( self . graph . loader , PartitioningLoader ) : return dict ( msg = "Config sharing disabled for non-partioned loader" ) if not hasattr ( self . graph . loader , "secrets" ) : return dict ( msg = "Config sharing disabled if no secrets are labelled" ) def remove_nulls ( dct ) : return { ke...
def _ser_script_to_sh_address ( script_bytes , witness = False , cashaddr = True ) : '''makes an p2sh address from a serialized script'''
if witness : script_hash = utils . sha256 ( script_bytes ) else : script_hash = utils . hash160 ( script_bytes ) return _hash_to_sh_address ( script_hash = script_hash , witness = witness , cashaddr = cashaddr )
def resolve_mode ( self , name ) : """From given mode name , return mode file path from ` ` settings . CODEMIRROR _ MODES ` ` map . Arguments : name ( string ) : Mode name . Raises : KeyError : When given name does not exist in ` ` settings . CODEMIRROR _ MODES ` ` . Returns : string : Mode file pat...
if name not in settings . CODEMIRROR_MODES : msg = ( "Given config name '{}' does not exists in " "'settings.CODEMIRROR_MODES'." ) raise UnknowModeError ( msg . format ( name ) ) return settings . CODEMIRROR_MODES . get ( name )
def barrier ( ) : """Works as a temporary distributed barrier , currently pytorch doesn ' t implement barrier for NCCL backend . Calls all _ reduce on dummy tensor and synchronizes with GPU ."""
if torch . distributed . is_available ( ) and torch . distributed . is_initialized ( ) : torch . distributed . all_reduce ( torch . cuda . FloatTensor ( 1 ) ) torch . cuda . synchronize ( )
def _iter_tokens ( self ) : """Iterate through all tokens in the input string ."""
reobj , actions , nextstates = self . _rules [ self . states [ - 1 ] ] mobj = reobj . match ( self . string , self . pos ) while mobj is not None : text = mobj . group ( 0 ) idx = mobj . lastindex - 1 nextstate = nextstates [ idx ] # Take action actions [ idx ] ( self , text ) while self . token...
def set_params ( self , ** params ) : """Set the parameters of this estimator . Modification of the sklearn method to allow unknown kwargs . This allows using the full range of xgboost parameters that are not defined as member variables in sklearn grid search . Returns self"""
if not params : # Simple optimization to gain speed ( inspect is slow ) return self for key , value in params . items ( ) : if hasattr ( self , key ) : setattr ( self , key , value ) else : self . kwargs [ key ] = value return self
def tags ( self ) : # type : ( ) - > Set [ str ] """Tags applied to operation ."""
tags = set ( ) if self . _tags : tags . update ( self . _tags ) if self . binding : binding_tags = getattr ( self . binding , 'tags' , None ) if binding_tags : tags . update ( binding_tags ) return tags
def _get_instance_state ( self ) : """Attempt to retrieve the state of the instance . Raises : EC2CloudException : If the instance cannot be found ."""
instance = self . _get_instance ( ) state = None try : state = instance . state [ 'Name' ] except Exception : raise EC2CloudException ( 'Instance with id: {instance_id}, ' 'cannot be found.' . format ( instance_id = self . running_instance_id ) ) return state
def load_plugins_dir ( path , category = None , overwrite = False ) : """load plugins from a directory Parameters path : str or path _ like category : None or str if str , apply for single plugin category overwrite : bool if True , allow existing plugins to be overwritten"""
# get potential plugin python files if hasattr ( path , 'glob' ) : pypaths = path . glob ( '*.py' ) else : pypaths = glob . glob ( os . path . join ( path , '*.py' ) ) load_errors = [ ] for pypath in pypaths : # use uuid to ensure no conflicts in name space mod_name = str ( uuid . uuid4 ( ) ) try : ...
def get_success_url ( self ) : """Ensure the user - originating redirection URL is safe ."""
redirect_to = self . request . POST . get ( self . redirect_field_name , self . request . GET . get ( self . redirect_field_name , '' ) ) url_is_safe = is_safe_url ( url = redirect_to , # allowed _ hosts = self . get _ success _ url _ allowed _ hosts ( ) , # require _ https = self . request . is _ secure ( ) , ) if not...
def _c3_mro ( cls , abcs = None ) : """Computes the method resolution order using extended C3 linearization . If no * abcs * are given , the algorithm works exactly like the built - in C3 linearization used for method resolution . If given , * abcs * is a list of abstract base classes that should be inserted ...
for i , base in enumerate ( reversed ( cls . __bases__ ) ) : if hasattr ( base , '__abstractmethods__' ) : boundary = len ( cls . __bases__ ) - i break # Bases up to the last explicit ABC are considered first . else : boundary = 0 abcs = list ( abcs ) if abcs else [ ] explicit_bases = li...
def posterior ( self , x ) : """Model is X _ 1 , . . . , X _ n ~ N ( 0 , 1 / theta ) , theta ~ Gamma ( a , b )"""
return Gamma ( a = self . a + 0.5 * x . size , b = self . b + 0.5 * np . sum ( x ** 2 ) )
def listen_fds ( unset_environment = True ) : """Return a list of socket activated descriptors Example : : ( in primary window ) $ systemd - activate - l 2000 python3 - c \ ' from systemd . daemon import listen _ fds ; print ( listen _ fds ( ) ) ' ( in another window ) $ telnet localhost 2000 ( in prima...
num = _listen_fds ( unset_environment ) return list ( range ( LISTEN_FDS_START , LISTEN_FDS_START + num ) )
def download_document ( self , document : Document , overwrite = True , path = None ) : """Download a document to the given path . if no path is provided the path is constructed frome the base _ url + stud . ip path + filename . If overwrite is set the local version will be overwritten if the file was changed on ...
if not path : path = os . path . join ( os . path . expanduser ( c [ "base_path" ] ) , document . path ) if ( self . modified ( document ) and overwrite ) or not os . path . exists ( join ( path , document . title ) ) : log . info ( "Downloading %s" % join ( path , document . title ) ) file = self . _get ( ...
def run_pipeline_steps ( steps , context ) : """Run the run _ step ( context ) method of each step in steps . Args : steps : list . Sequence of Steps to execute context : pypyr . context . Context . The pypyr context . Will mutate ."""
logger . debug ( "starting" ) assert isinstance ( context , dict ) , "context must be a dictionary, even if empty {}." if steps is None : logger . debug ( "No steps found to execute." ) else : step_count = 0 for step in steps : step_instance = Step ( step ) step_instance . run_step ( context...
def validate ( self ) : """Validate the contents of the object . This calls ` ` setattr ` ` for each of the class ' s grammar properties . It will catch ` ` ValueError ` ` s raised by the grammar property ' s setters and re - raise them as : class : ` ValidationError ` ."""
for key , val in self . grammar . items ( ) : try : setattr ( self , key , val ) except ValueError as e : raise ValidationError ( 'invalid contents: ' + e . args [ 0 ] )
def is_deprecated ( cls , label , datacenter = None ) : """Check if image if flagged as deprecated ."""
images = cls . list ( datacenter , label ) images_visibility = dict ( [ ( image [ 'label' ] , image [ 'visibility' ] ) for image in images ] ) return images_visibility . get ( label , 'all' ) == 'deprecated'
def geometricBar ( weights , alldistribT ) : """return the weighted geometric mean of distributions"""
assert ( len ( weights ) == alldistribT . shape [ 1 ] ) return np . exp ( np . dot ( np . log ( alldistribT ) , weights . T ) )
def GetService ( self , service_name , version = sorted ( _SERVICE_MAP . keys ( ) ) [ - 1 ] , server = None ) : """Creates a service client for the given service . Args : service _ name : A string identifying which Ad Manager service to create a service client for . [ optional ] version : A string identif...
if not server : server = DEFAULT_ENDPOINT server = server [ : - 1 ] if server [ - 1 ] == '/' else server try : service = googleads . common . GetServiceClassForLibrary ( self . soap_impl ) ( self . _SOAP_SERVICE_FORMAT % ( server , version , service_name ) , self . _header_handler , _AdManagerPacker , self . pr...
def upload_entities ( namespace , workspace , entity_data ) : """Upload entities from tab - delimited string . Args : namespace ( str ) : project to which workspace belongs workspace ( str ) : Workspace name entity _ data ( str ) : TSV string describing entites Swagger : https : / / api . firecloud . or...
body = urlencode ( { "entities" : entity_data } ) headers = _fiss_agent_header ( { 'Content-type' : "application/x-www-form-urlencoded" } ) uri = "workspaces/{0}/{1}/importEntities" . format ( namespace , workspace ) return __post ( uri , headers = headers , data = body )
def _string_width ( string , * , _IS_ASCII = _IS_ASCII ) : """Returns string ' s width ."""
match = _IS_ASCII . match ( string ) if match : return match . endpos UNICODE_WIDE_CHAR_TYPE = 'WFA' width = 0 func = unicodedata . east_asian_width for char in string : width += 2 if func ( char ) in UNICODE_WIDE_CHAR_TYPE else 1 return width
def separate_fields ( fields ) : """Non - foreign key fields can be mapped to new article instances directly . Foreign key fields require a bit more work . This method returns a tuple , of the same format : ( flat fields , nested fields )"""
flat_fields = { } nested_fields = { } # exclude " id " and " meta " elements for k , v in fields . items ( ) : # TODO : remove dependence on KEYS _ TO _ INCLUDE if k not in KEYS_TO_EXCLUDE : if type ( v ) not in [ type ( { } ) , type ( [ ] ) ] : flat_fields . update ( { k : v } ) else : ...
def import_image ( self , name , stream_import , tags = None ) : """Import image tags from a Docker registry into an ImageStream : return : bool , whether tags were imported"""
# Get the JSON for the ImageStream imagestream_json = self . get_image_stream ( name ) . json ( ) logger . debug ( "imagestream: %r" , imagestream_json ) if 'dockerImageRepository' in imagestream_json . get ( 'spec' , { } ) : logger . debug ( "Removing 'dockerImageRepository' from ImageStream %s" , name ) sourc...
def post ( self , request , * args , ** kwargs ) : """Validates subscription data before creating Outbound message"""
# Look up subscriber subscription_id = kwargs [ "subscription_id" ] if Subscription . objects . filter ( id = subscription_id ) . exists ( ) : status = 202 accepted = { "accepted" : True } store_resend_request . apply_async ( args = [ subscription_id ] ) else : status = 400 accepted = { "accepted" :...
def toSparse ( self ) : """Convert to SparseMatrix"""
if self . isTransposed : values = np . ravel ( self . toArray ( ) , order = 'F' ) else : values = self . values indices = np . nonzero ( values ) [ 0 ] colCounts = np . bincount ( indices // self . numRows ) colPtrs = np . cumsum ( np . hstack ( ( 0 , colCounts , np . zeros ( self . numCols - colCounts . size )...
def match_global_phase ( a : np . ndarray , b : np . ndarray ) -> Tuple [ np . ndarray , np . ndarray ] : """Phases the given matrices so that they agree on the phase of one entry . To maximize precision , the position with the largest entry from one of the matrices is used when attempting to compute the phase ...
# Not much point when they have different shapes . if a . shape != b . shape : return a , b # Find the entry with the largest magnitude in one of the matrices . k = max ( np . ndindex ( * a . shape ) , key = lambda t : abs ( b [ t ] ) ) def dephase ( v ) : r = np . real ( v ) i = np . imag ( v ) # Avoid...
def set_soup ( self ) : """Sets soup and strips items"""
self . soup = BeautifulSoup ( self . feed_content , "html.parser" ) for item in self . soup . findAll ( 'item' ) : item . decompose ( ) for image in self . soup . findAll ( 'image' ) : image . decompose ( )
def listen_many ( * rooms ) : """Listen for changes in all registered listeners in all specified rooms"""
rooms = set ( r . conn for r in rooms ) for room in rooms : room . validate_listeners ( ) with ARBITRATOR . condition : while any ( r . connected for r in rooms ) : ARBITRATOR . condition . wait ( ) rooms = [ r for r in rooms if r . run_queues ( ) ] if not rooms : return
def _match_registers ( self , query ) : """Tries to match in status registers : param query : message tuple : type query : Tuple [ bytes ] : return : response if found or None : rtype : Tuple [ bytes ] | None"""
if query in self . _status_registers : register = self . _status_registers [ query ] response = register . value logger . debug ( 'Found response in status register: %s' , repr ( response ) ) register . clear ( ) return response
def is_same_key ( key_1 , key_2 ) : """Extract the key from two host entries and compare them . : param key _ 1 : Host key : type key _ 1 : str : param key _ 2 : Host key : type key _ 2 : str"""
# The key format get will be like ' | 1 | 2rUumCavEXWVaVyB5uMl6m85pZo = | Cp ' # ' EL6l7VTY37T / fg / ihhNb / GPgs = ssh - rsa AAAAB ' , we only need to compare # the part start with ' ssh - rsa ' followed with ' = ' , because the hash # value in the beginning will change each time . k_1 = key_1 . split ( '= ' ) [ 1 ] ...
def loadSenderKey ( self , senderKeyName ) : """: type senderKeyName : SenderKeyName"""
q = "SELECT record FROM sender_keys WHERE group_id = ? and sender_id = ?" cursor = self . dbConn . cursor ( ) cursor . execute ( q , ( senderKeyName . getGroupId ( ) , senderKeyName . getSender ( ) . getName ( ) ) ) result = cursor . fetchone ( ) if not result : return SenderKeyRecord ( ) return SenderKeyRecord ( s...
def playlist_song_delete ( self , playlist_song ) : """Delete song from playlist . Parameters : playlist _ song ( str ) : A playlist song dict . Returns : dict : Playlist dict including songs ."""
self . playlist_songs_delete ( [ playlist_song ] ) return self . playlist ( playlist_song [ 'playlistId' ] , include_songs = True )
def init_cmu ( filehandle = None ) : """Initialize the module ' s pronunciation data . This function is called automatically the first time you attempt to use another function in the library that requires loading the pronunciation data from disk . You can call this function manually to control when and how ...
global pronunciations , lookup , rhyme_lookup if pronunciations is None : if filehandle is None : filehandle = cmudict . dict_stream ( ) pronunciations = parse_cmu ( filehandle ) filehandle . close ( ) lookup = collections . defaultdict ( list ) for word , phones in pronunciations : ...
def get_threshold_values ( self , application_id ) : """Requires : account ID , list of application ID Method : Get Endpoint : api . newrelic . com Restrictions : ? ? ? Errors : 403 Invalid API key , 422 Invalid Parameters Returns : A list of threshold _ value objects , each will have information about ...
endpoint = "https://rpm.newrelic.com" remote_file = "threshold_values.xml" uri = "{endpoint}/accounts/{account_id}/applications/{app_id}/{xml}" . format ( endpoint = endpoint , account_id = self . account_id , app_id = application_id , xml = remote_file ) response = self . _make_get_request ( uri ) thresholds = [ ] for...
def convert ( self , string ) : """Returns : a converted tagged string param : string ( contains html tags ) Don ' t replace characters inside tags"""
( string , tags ) = self . detag_string ( string ) string = self . inner_convert_string ( string ) string = self . retag_string ( string , tags ) return string
def cmdmap ( xdot ) : """Generates a command map"""
# TODO : Integrate the output into documentation from copy import copy def print_commands ( command , map_output , groups = None , depth = 0 ) : if groups is None : groups = [ ] if 'commands' in command . __dict__ : if len ( groups ) > 0 : if xdot : line = " %s -> ...
def transformation_matrix ( self ) : """Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation . Returns : A 4x4 homogeneous transformation matrix as a 4x4 Numpy array Note : This feature only makes sense when referring to a unit quaternion . Calling this method will implicitly ...
t = np . array ( [ [ 0.0 ] , [ 0.0 ] , [ 0.0 ] ] ) Rt = np . hstack ( [ self . rotation_matrix , t ] ) return np . vstack ( [ Rt , np . array ( [ 0.0 , 0.0 , 0.0 , 1.0 ] ) ] )
def _set_last_rcvd_interface ( self , v , load = False ) : """Setter method for last _ rcvd _ interface , mapped from YANG variable / brocade _ interface _ ext _ rpc / get _ interface _ detail / input / last _ rcvd _ interface ( container ) If this variable is read - only ( config : false ) in the source YANG f...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = last_rcvd_interface . last_rcvd_interface , is_container = 'container' , presence = False , yang_name = "last-rcvd-interface" , rest_name = "last-rcvd-interface" , parent = self , choice = ( u'request-type' , u'get-next-reque...
def log ( self , message , level = logging . INFO , * args , ** kwargs ) : """Send log entry : param str message : log message : param int level : ` Logging level < https : / / docs . python . org / 3 / library / logging . html # levels > ` _ : param list args : log record arguments : param dict kwargs : lo...
msg = "{}.{}: {}[{}]: {}" . format ( self . __class__ . __name__ , self . status , self . __class__ . path , self . uuid , message ) extra = kwargs . pop ( "extra" , dict ( ) ) extra . update ( dict ( kmsg = Message ( self . uuid , entrypoint = self . __class__ . path , params = self . params , metadata = self . metada...
def getPluginVersion ( ) : """The version must be updated in the . cdmp file"""
desc_file = os . path . join ( 'cdmplugins' , 'gc' , plugin_desc_file ) if not os . path . exists ( desc_file ) : print ( 'Cannot find the plugin description file. Expected here: ' + desc_file , file = sys . stderr ) sys . exit ( 1 ) with open ( desc_file ) as dec_file : for line in dec_file : line ...
def write ( self , f ) : """Write an SBOL file from current document contents"""
rdf = ET . Element ( NS ( 'rdf' , 'RDF' ) , nsmap = XML_NS ) # TODO : TopLevel Annotations sequence_values = sorted ( self . _sequences . values ( ) , key = lambda x : x . identity ) self . _add_to_root ( rdf , sequence_values ) component_values = sorted ( self . _components . values ( ) , key = lambda x : x . identity...
def populateWidget ( self ) : """Populate the widget using data stored in the state object . The order in which the individual widgets are populated follows their arrangment . The models are recreated every time the function is called . This might seem to be an overkill , but in practice it is very fast . ...
self . elementComboBox . setItems ( self . state . _elements , self . state . element ) self . chargeComboBox . setItems ( self . state . _charges , self . state . charge ) self . symmetryComboBox . setItems ( self . state . _symmetries , self . state . symmetry ) self . experimentComboBox . setItems ( self . state . _...
def conditions_met ( self , instance , state ) : """Check if all conditions have been met"""
transition = self . get_transition ( state ) if transition is None : return False elif transition . conditions is None : return True else : return all ( map ( lambda condition : condition ( instance ) , transition . conditions ) )
def build_graph ( path , term_depth = 1000 , skim_depth = 10 , d_weights = False , ** kwargs ) : """Tokenize a text , index a term matrix , and build out a graph . Args : path ( str ) : The file path . term _ depth ( int ) : Consider the N most frequent terms . skim _ depth ( int ) : Connect each word to th...
# Tokenize text . click . echo ( '\nTokenizing text...' ) t = Text . from_file ( path ) click . echo ( 'Extracted %d tokens' % len ( t . tokens ) ) m = Matrix ( ) # Index the term matrix . click . echo ( '\nIndexing terms:' ) m . index ( t , t . most_frequent_terms ( term_depth ) , ** kwargs ) g = Skimmer ( ) # Constru...
def check_config ( self ) : """called after config was modified to sanity check raises on error"""
# sanity checks - no config access past here if not getattr ( self , 'stages' , None ) : raise NotImplementedError ( "member variable 'stages' must be defined" ) # start at stage if self . __start : self . __stage_start = self . find_stage ( self . __start ) else : self . __stage_start = 0 # end at stage if...