signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _get_new_connection ( self , conn_params ) : """Opens a connection to the database ."""
self . __connection_string = conn_params . get ( 'connection_string' , '' ) conn = self . Database . connect ( ** conn_params ) return conn
def set ( self , value ) : '''set a setting'''
if value == 'None' and self . default is None : value = None if value is not None : if self . type == bool : if str ( value ) . lower ( ) in [ '1' , 'true' , 'yes' ] : value = True elif str ( value ) . lower ( ) in [ '0' , 'false' , 'no' ] : value = False else : ...
def _get_py_loglevel ( lvl ) : """Map log levels to strings"""
if not lvl : lvl = 'INFO' return LOG_LEVEL_MAP . get ( lvl . upper ( ) , logging . DEBUG )
def index_synonym ( self , syn , ont ) : """Index a synonym Typically not called from outside this object ; called by ` index _ ontology `"""
if not syn . val : if syn . pred == 'label' : if not self . _is_meaningful_ids ( ) : if not ont . is_obsolete ( syn . class_id ) : pass # logging . error ( ' Use meaningful ids if label not present : { } ' . format ( syn ) ) else : logging . warning ( ...
def add_userids_for_address ( self , address : Address , user_ids : Iterable [ str ] ) : """Add multiple ` ` user _ ids ` ` for the given ` ` address ` ` . Implicitly adds any addresses if they were unknown before ."""
self . _address_to_userids [ address ] . update ( user_ids )
def add ( self , files , items ) : """Add a list of files with a reference to a list of objects ."""
if isinstance ( files , ( str , bytes ) ) : files = iter ( [ files ] ) for pathname in files : try : values = self . _filemap [ pathname ] except KeyError : self . _filemap [ pathname ] = items else : values . extend ( items )
def get_dict ( self ) : """Convert all rules to dict and return them ."""
out = { property_name : getattr ( self , property_name ) for property_name in self . _property_names } if "frequency" in out : out [ "frequency" ] = int ( out [ "frequency" ] ) return out
def offer ( self , item , timeout = 0 ) : """Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions . Returns ` ` true ` ` upon success . If there is no space currently available : * If a timeout is provided , it waits until this timeout elap...
check_not_none ( item , "Value can't be None" ) element_data = self . _to_data ( item ) return self . _encode_invoke ( queue_offer_codec , value = element_data , timeout_millis = to_millis ( timeout ) )
def extract_feature_base ( dbpath , folder_path , set_object , extractor , force_extraction = False , verbose = 0 , add_args = None , custom_name = None ) : """Generic function which extracts a feature and stores it in the database Parameters dbpath : string , path to SQLite database file folder _ path : stri...
if custom_name is None : extractor_name = extractor . __name__ else : extractor_name = custom_name engine = create_engine ( 'sqlite:////' + dbpath ) session_cl = sessionmaker ( bind = engine ) session = session_cl ( ) a = 0 tmp_object = session . query ( set_object ) . get ( 1 ) if tmp_object . features is None...
def _recv_ff ( self , data ) : """Process a received ' First Frame ' frame"""
self . rx_timer . cancel ( ) if self . rx_state != ISOTP_IDLE : warning ( "RX state was reset because first frame was received" ) self . rx_state = ISOTP_IDLE if len ( data ) < 7 : return 1 self . rx_ll_dl = len ( data ) # get the FF _ DL self . rx_len = ( six . indexbytes ( data , 0 ) & 0x0f ) * 256 + six ...
def remove_stream_handlers ( logger = None ) : """Remove only stream handlers from the specified logger : param logger : logging name or object to modify , defaults to root logger"""
if not isinstance ( logger , logging . Logger ) : logger = logging . getLogger ( logger ) new_handlers = [ ] for handler in logger . handlers : # FileHandler is a subclass of StreamHandler so # ' if not a StreamHandler ' does not work if ( isinstance ( handler , logging . FileHandler ) or isinstance ( handler ,...
def run_std_simulate ( ns_run , estimator_list , n_simulate = None ) : """Uses the ' simulated weights ' method to calculate an estimate of the standard deviation of the distribution of sampling errors ( the uncertainty on the calculation ) for a single nested sampling run . Note that the simulated weights me...
assert n_simulate is not None , 'run_std_simulate: must specify n_simulate' all_values = np . zeros ( ( len ( estimator_list ) , n_simulate ) ) for i in range ( n_simulate ) : all_values [ : , i ] = nestcheck . ns_run_utils . run_estimators ( ns_run , estimator_list , simulate = True ) stds = np . zeros ( all_value...
def url_to_filename ( url : str , etag : str = None ) -> str : """Convert ` url ` into a hashed filename in a repeatable way . If ` etag ` is specified , append its hash to the url ' s , delimited by a period ."""
url_bytes = url . encode ( 'utf-8' ) url_hash = sha256 ( url_bytes ) filename = url_hash . hexdigest ( ) if etag : etag_bytes = etag . encode ( 'utf-8' ) etag_hash = sha256 ( etag_bytes ) filename += '.' + etag_hash . hexdigest ( ) return filename
def create ( cls , community , record , user = None , expires_at = None , notify = True ) : """Create a record inclusion request to a community . : param community : Community object . : param record : Record API object . : param expires _ at : Time after which the request expires and shouldn ' t be resolve...
if expires_at and expires_at < datetime . utcnow ( ) : raise InclusionRequestExpiryTimeError ( community = community , record = record ) if community . has_record ( record ) : raise InclusionRequestObsoleteError ( community = community , record = record ) try : # Create inclusion request with db . session ....
def create_table ( self , data , table_name , error_if_exists = False , ** kwargs ) : 'Create a table based on the data , but don \' t insert anything .'
converted_data = convert ( data ) if len ( converted_data ) == 0 or converted_data [ 0 ] == [ ] : raise ValueError ( u'You passed no sample values, or all the values you passed were null.' ) else : startdata = OrderedDict ( converted_data [ 0 ] ) # Select a non - null item for k , v in startdata . items ( ) : ...
def _dist_version_url ( self , dist ) : """Get version and homepage for a pkg _ resources . Distribution : param dist : the pkg _ resources . Distribution to get information for : returns : 2 - tuple of ( version , homepage URL ) : rtype : tuple"""
ver = str ( dist . version ) url = None for line in dist . get_metadata_lines ( dist . PKG_INFO ) : line = line . strip ( ) if ':' not in line : continue ( k , v ) = line . split ( ':' , 1 ) if k == 'Home-page' : url = v . strip ( ) return ( ver , url )
def genderize ( name , api_token = None ) : """Fetch gender from genderize . io"""
GENDERIZE_API_URL = "https://api.genderize.io/" TOTAL_RETRIES = 10 MAX_RETRIES = 5 SLEEP_TIME = 0.25 STATUS_FORCELIST = [ 502 ] params = { 'name' : name } if api_token : params [ 'apikey' ] = api_token session = requests . Session ( ) retries = urllib3 . util . Retry ( total = TOTAL_RETRIES , connect = MAX_RETRIES ...
def make_tb2rad_lut ( self , filepath , normalized = True ) : """Generate a Tb to radiance look - up table"""
tb_ = np . arange ( TB_MIN , TB_MAX , self . tb_resolution ) retv = self . tb2radiance ( tb_ , normalized = normalized ) rad = retv [ 'radiance' ] np . savez ( filepath , tb = tb_ , radiance = rad )
def inserir ( self , id_equipamento , fqdn , user , password , id_tipo_acesso , enable_pass ) : """Add new relationship between equipment and access type and returns its id . : param id _ equipamento : Equipment identifier . : param fqdn : Equipment FQDN . : param user : User . : param password : Password ....
equipamento_acesso_map = dict ( ) equipamento_acesso_map [ 'id_equipamento' ] = id_equipamento equipamento_acesso_map [ 'fqdn' ] = fqdn equipamento_acesso_map [ 'user' ] = user equipamento_acesso_map [ 'pass' ] = password equipamento_acesso_map [ 'id_tipo_acesso' ] = id_tipo_acesso equipamento_acesso_map [ 'enable_pass...
def __get_img ( self ) : """Returns an image object corresponding to the page"""
with self . fs . open ( self . __img_path , 'rb' ) as fd : img = PIL . Image . open ( fd ) img . load ( ) return img
def backend_config_to_configparser ( config ) : """Return a ConfigParser instance representing a given backend config dictionary . Args : config ( dict ) : Dictionary of config key / value pairs . Returns : SafeConfigParser : SafeConfigParser instance representing config . Note : We do not provide * any...
def get_store ( ) : return config . get ( 'store' ) def get_day_start ( ) : day_start = config . get ( 'day_start' ) if day_start : day_start = day_start . strftime ( '%H:%M:%S' ) return day_start def get_fact_min_delta ( ) : return text_type ( config . get ( 'fact_min_delta' ) ) def get_tmp...
def older_message ( m , lastm ) : '''return true if m is older than lastm by timestamp'''
atts = { 'time_boot_ms' : 1.0e-3 , 'time_unix_usec' : 1.0e-6 , 'time_usec' : 1.0e-6 } for a in atts . keys ( ) : if hasattr ( m , a ) : mul = atts [ a ] t1 = m . getattr ( a ) * mul t2 = lastm . getattr ( a ) * mul if t2 >= t1 and t2 - t1 < 60 : return True return False
def action_create ( self , courseid , taskid , path ) : """Delete a file or a directory"""
# the path is given by the user . Let ' s normalize it path = path . strip ( ) if not path . startswith ( "/" ) : path = "/" + path want_directory = path . endswith ( "/" ) wanted_path = self . verify_path ( courseid , taskid , path , True ) if wanted_path is None : return self . show_tab_file ( courseid , task...
def call_env_check_consistency ( cls , kb_app , builder : StandaloneHTMLBuilder , sphinx_env : BuildEnvironment ) : """On env - check - consistency , do callbacks"""
for callback in EventAction . get_callbacks ( kb_app , SphinxEvent . ECC ) : callback ( kb_app , builder , sphinx_env )
def Kill ( self ) : """Send death pill to Gdb and forcefully kill it if that doesn ' t work ."""
try : if self . is_running : self . Detach ( ) if self . _Execute ( '__kill__' ) == '__kill_ack__' : # acknowledged , let ' s give it some time to die in peace time . sleep ( 0.1 ) except ( TimeoutError , ProxyError ) : logging . debug ( 'Termination request not acknowledged, killing gdb.' )...
def reserve ( self , max = None , timeout = None , wait = None , delete = None ) : """Retrieves Messages from the queue and reserves it . Arguments : max - - The maximum number of messages to reserve . Defaults to 1. timeout - - Timeout in seconds . wait - - Time to long poll for messages , in seconds . Max...
url = "queues/%s/reservations" % self . name qitems = { } if max is not None : qitems [ 'n' ] = max if timeout is not None : qitems [ 'timeout' ] = timeout if wait is not None : qitems [ 'wait' ] = wait if delete is not None : qitems [ 'delete' ] = delete body = json . dumps ( qitems ) response = self ....
def run_tm_noise_experiment ( dim = 2048 , cellsPerColumn = 1 , num_active = 40 , activationThreshold = 16 , initialPermanence = 0.8 , connectedPermanence = 0.50 , minThreshold = 16 , maxNewSynapseCount = 20 , permanenceIncrement = 0.05 , permanenceDecrement = 0.00 , predictedSegmentDecrement = 0.000 , maxSegmentsPerCe...
if automatic_threshold : activationThreshold = min ( num_active / 2 , maxNewSynapseCount / 2 ) minThreshold = min ( num_active / 2 , maxNewSynapseCount / 2 ) for noise in noise_range : print noise for trial in range ( num_trials ) : tm = TM ( columnDimensions = ( dim , ) , cellsPerColumn = cells...
def simxEraseFile ( clientID , fileName_serverSide , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
if ( sys . version_info [ 0 ] == 3 ) and ( type ( fileName_serverSide ) is str ) : fileName_serverSide = fileName_serverSide . encode ( 'utf-8' ) return c_EraseFile ( clientID , fileName_serverSide , operationMode )
def value_left ( self , other ) : """Returns the value of the other type instance to use in an operator method , namely when the method ' s instance is on the left side of the expression ."""
return other . value if isinstance ( other , self . __class__ ) else other
def trigger_event ( self , module_name , event ) : """Trigger an event on a named module ."""
if module_name : self . _py3_wrapper . events_thread . process_event ( module_name , event )
def _get_home ( ) : """Find user ' s home directory if possible . Otherwise , returns None . : see : http : / / mail . python . org / pipermail / python - list / 2005 - February / 325395 . html This function is copied from matplotlib version 1.4.3 , Jan 2016"""
try : if six . PY2 and sys . platform == 'win32' : path = os . path . expanduser ( b"~" ) . decode ( sys . getfilesystemencoding ( ) ) else : path = os . path . expanduser ( "~" ) except ImportError : # This happens on Google App Engine ( pwd module is not present ) . pass else : if os ....
def _fix_perms ( perm_obj ) : """: param perm _ obj : A permissions object , as given by os . stat ( ) : type perm _ obj : integer : returns : A permissions object that is the result of " chmod a + rX " on the given permission object . This is defined to be the permission object bitwise or - ed with all sta...
ret_perm = perm_obj | stat . S_IROTH | stat . S_IRGRP | stat . S_IRUSR if ret_perm & stat . S_IXUSR : ret_perm = ret_perm | stat . S_IXGRP | stat . S_IXOTH return ret_perm
def build_command ( chunks ) : """Create a command from various parts . The parts provided may include a base , flags , option - bound arguments , and positional arguments . Each element must be either a string or a two - tuple . Raw strings are interpreted as either the command base , a pre - joined pair (...
if not chunks : raise ValueError ( "No command parts: {} ({})" . format ( chunks , type ( chunks ) ) ) if isinstance ( chunks , str ) : return chunks parsed_pieces = [ ] for cmd_part in chunks : if cmd_part is None : continue try : # Trim just space , not all whitespace . # This prevents dam...
def kill ( pid_file ) : """Attempts to shut down a previously started daemon ."""
try : with open ( pid_file ) as f : os . kill ( int ( f . read ( ) ) , 9 ) os . remove ( pid_file ) except ( IOError , OSError ) : return False return True
def convert_dt_time ( duration , return_iter = False ) : """Summary : convert timedelta objects to human readable output Args : : duration ( datetime . timedelta ) : time duration to convert : return _ iter ( tuple ) : tuple containing time sequence Returns : days , hours , minutes , seconds | TYPE : tu...
try : days , hours , minutes , seconds = convert_timedelta ( duration ) if return_iter : return days , hours , minutes , seconds # string format conversions if days > 0 : format_string = ( '{} day{}, {} hour{}' . format ( days , 's' if days != 1 else '' , hours , 's' if hours != 1 else '...
def create_with_netlinks ( cls , name , netlinks , ** kwargs ) : """Create a multilink with a list of StaticNetlinks . To properly create the multilink using this method , pass a list of netlinks with the following dict structure : : netlinks = [ { ' netlink ' : StaticNetlink , ' ip _ range ' : 1.1.1.1-1.1....
multilink_members = [ ] for member in netlinks : m = { 'ip_range' : member . get ( 'ip_range' , '0.0.0.0' ) , 'netlink_role' : member . get ( 'netlink_role' , 'active' ) } netlink = member . get ( 'netlink' ) m . update ( netlink_ref = netlink . href ) if netlink . typeof == 'netlink' : m . upda...
def _maybe_repeat ( self , x ) : """Utility function for processing arguments that are singletons or lists . Args : x : either a list of self . n elements , or not a list . Returns : a list of self . n elements ."""
if isinstance ( x , list ) : assert len ( x ) == self . n return x else : return [ x ] * self . n
def language ( fname , is_ext = False ) : """Return an instance of the language class that fname is suited for . Searches through the module langs for the class that matches up with fname . If is _ ext is True then fname will be taken to be the extension for a language ."""
global _langmapping # Normalize the fname so that it looks like an extension . if is_ext : fname = '.' + fname _ , ext = os . path . splitext ( fname ) return _langmapping [ ext ] ( )
def prior_sediment_rate ( * args , ** kwargs ) : """Get the prior density of sediment rates Returns y : ndarray Array giving the density . x : ndarray Array of sediment accumulation values ( yr / cm ) over which the density was evaluated ."""
# PlotAccPrior @ Bacon . R ln 113 - > ln 1097-1115 # alpha = acc _ shape , beta = acc _ shape / acc _ mean # TODO ( brews ) : Check that these stats are correctly translated to scipy . stats distribs . acc_mean = kwargs [ 'acc_mean' ] acc_shape = kwargs [ 'acc_shape' ] x = np . linspace ( 0 , 6 * np . max ( acc_mean ) ...
def Compile ( self , filter_implemention ) : """Returns the data _ store filter implementation from the attribute ."""
return self . operator_method ( self . attribute_obj , filter_implemention , * self . args )
def display ( self ) : """Pretty - prints the ParsedResponse to the screen ."""
table_list = [ ] table_list . append ( ( "Text" , "Orig. Text" , "Start time" , "End time" , "Phonetic" ) ) for unit in self . unit_list : table_list . append ( ( unit . text , "/" . join ( unit . original_text ) , unit . start_time , unit . end_time , unit . phonetic_representation ) ) print_table ( table_list )
def get_metadata_new ( self , series_number ) : """Return series metadata . Output condatin information about voxelsize _ mm , series _ number and modality . If it is possible , the ImageComment , AcquisitionDate and few other dicom tags are also in output dict . : param series _ number : : return : metadat...
# TODO implement simplier metadata function # automatic test is prepared files , files_with_info = self . get_sorted_series_files ( series_number = series_number , return_files_with_info = True ) metadata = { # ' voxelsize _ mm ' : voxelsize _ mm , # ' Modality ' : data1 . Modality , # ' SeriesNumber ' : series _ numbe...
def close ( self ) : """Flush the buffer and finalize the file . When this returns the new file is available for reading ."""
if not self . closed : self . closed = True self . _flush ( finish = True ) self . _buffer = None
def _LogProgressUpdateIfReasonable ( self ) : """Prints a progress update if enough time has passed ."""
next_log_time = ( self . _time_of_last_status_log + self . SECONDS_BETWEEN_STATUS_LOG_MESSAGES ) current_time = time . time ( ) if current_time < next_log_time : return completion_time = time . ctime ( current_time + self . EstimateTimeRemaining ( ) ) log_message = ( '{0:s} hash analysis plugin running. {1:d} hashe...
def run ( self , ** export_params ) : """Make the actual request to the Import API ( exporting is part of the Import API ) . : param export _ params : Any additional parameters to be sent to the Import API : type export _ params : kwargs : return : . . note : : The export is asynchronous , so you should...
export_params [ "visualization_id" ] = self . visualization_id return super ( ExportJob , self ) . run ( params = export_params )
def calc_z0_and_conv_factor_from_ratio_of_harmonics ( z , z2 , NA = 0.999 ) : """Calculates the Conversion Factor and physical amplitude of motion in nms by comparison of the ratio of the heights of the z signal and second harmonic of z . Parameters z : ndarray array containing z signal in volts z2 : nd...
V1 = calc_mean_amp ( z ) V2 = calc_mean_amp ( z2 ) ratio = V2 / V1 beta = 4 * ratio laserWavelength = 1550e-9 # in m k0 = ( 2 * pi ) / ( laserWavelength ) WaistSize = laserWavelength / ( pi * NA ) Zr = pi * WaistSize ** 2 / laserWavelength z0 = beta / ( k0 - 1 / Zr ) ConvFactor = V1 / z0 T0 = 300 return z0 , ConvFactor
def google_trends ( query_terms = [ 'big data' , 'machine learning' , 'data science' ] , data_set = 'google_trends' , refresh_data = False ) : """Data downloaded from Google trends for given query terms . Warning , if you use this function multiple times in a row you get blocked due to terms of service violatio...
query_terms . sort ( ) import pandas as pd # Create directory name for data dir_path = os . path . join ( data_path , 'google_trends' ) if not os . path . isdir ( dir_path ) : os . makedirs ( dir_path ) dir_name = '-' . join ( query_terms ) dir_name = dir_name . replace ( ' ' , '_' ) dir_path = os . path . join ( d...
def new_file ( self ) : """Creates a new file into a new * * Script _ Editor _ tabWidget * * Widget tab . : return : Method success . : rtype : bool"""
language = self . __languages_model . get_language ( self . __default_script_language ) editor = Editor ( parent = self , language = language ) file = editor . new_file ( ) if not file : return False LOGGER . info ( "{0} | Creating '{1}' file!" . format ( self . __class__ . __name__ , file ) ) if self . __model . s...
def url ( self , name , * , base = None , query = None , ** match ) : """Construct an url for the given parameters . . . seealso : : Proxy : : meth : ` . Router . url `"""
return self . __router . url ( name , base = base , query = query , ** match )
def get_and_write_raw ( self , url : str , filename : str ) -> None : """Downloads and writes anonymously - requested raw data into a file . : raises QueryReturnedNotFoundException : When the server responds with a 404. : raises QueryReturnedForbiddenException : When the server responds with a 403. : raises C...
self . write_raw ( self . get_raw ( url ) , filename )
def get_project_pod_spec ( volume_mounts , volumes , image , command , args , ports , env_vars = None , env_from = None , container_name = None , resources = None , node_selector = None , affinity = None , tolerations = None , image_pull_policy = None , restart_policy = None , service_account_name = None ) : """Pod...
volume_mounts = to_list ( volume_mounts , check_none = True ) volumes = to_list ( volumes , check_none = True ) gpu_volume_mounts , gpu_volumes = get_gpu_volumes_def ( resources ) volume_mounts += gpu_volume_mounts volumes += gpu_volumes ports = [ client . V1ContainerPort ( container_port = port ) for port in ports ] p...
def getFriends ( self , user_id = "astronauta.mecanico" , write = True ) : """Returns user _ ids ( that you have access ) of the friends of your friend with user _ ids"""
while user_id not in self . browser . url : self . browser . visit ( "http://www.facebook.com/{}/friends" . format ( user_id ) , wait_time = 3 ) # self . go ( " http : / / www . facebook . com / { } / friends " . format ( user _ id ) ) T = time . time ( ) while 1 : h1 = self . browser . evaluate_script ( "docum...
def calculate_sunrise_sunset ( locator , calc_date = datetime . utcnow ( ) ) : """calculates the next sunset and sunrise for a Maidenhead locator at a give date & time Args : locator1 ( string ) : Maidenhead Locator , either 4 or 6 characters calc _ date ( datetime , optional ) : Starting datetime for the cal...
morning_dawn = None sunrise = None evening_dawn = None sunset = None latitude , longitude = locator_to_latlong ( locator ) if type ( calc_date ) != datetime : raise ValueError sun = ephem . Sun ( ) home = ephem . Observer ( ) home . lat = str ( latitude ) home . long = str ( longitude ) home . date = calc_date sun ...
def _check_release_done_processing ( release ) : """Moves a release candidate to reviewing if all runs are done ."""
if release . status != models . Release . PROCESSING : # NOTE : This statement also guards for situations where the user has # prematurely specified that the release is good or bad . Once the user # has done that , the system will not automatically move the release # back into the ' reviewing ' state or send the email ...
def delete ( self , subnet_id ) : """This is bad delete function because one vpc can have more than one subnet . It is Ok if user only use CAL for manage cloud resource We will update ASAP ."""
# 1 : show subnet subnet = self . client . describe_subnets ( SubnetIds = [ subnet_id ] ) . get ( 'Subnets' ) [ 0 ] vpc_id = subnet . get ( 'VpcId' ) # 2 : delete subnet self . client . delete_subnet ( SubnetId = subnet_id ) # 3 : delete vpc return self . client . delete_vpc ( VpcId = vpc_id )
def xpath ( self , path , namespaces = None , regexp = False , smart_strings = True , single_use = False , ) : u"""Executes XPath query on the ` ` lxml ` ` object and returns a correct object . : param str path : XPath string e . g . , ' cars ' / ' car ' : param str / dict namespaces : e . g . , ' exslt ' , ' r...
if ( namespaces in [ 'exslt' , 're' ] or ( regexp and not namespaces ) ) : namespaces = { 're' : "http://exslt.org/regular-expressions" } if single_use : node = self . _xml . xpath ( path ) else : xpe = self . xpath_evaluator ( namespaces = namespaces , regexp = regexp , smart_strings = smart_strings ) ...
def _loadDB ( self ) : """Connect to the database to load myself"""
if not self . _validID ( ) : raise NotFound , self . _getID ( ) ( sql , fields ) = self . _prepareSQL ( "SELECT" ) curs = self . cursor ( ) curs . execute ( sql , self . _getID ( ) ) result = curs . fetchone ( ) if not result : curs . close ( ) raise NotFound , self . _getID ( ) self . _loadFromRow ( result...
def sum ( self ) : """Add up the elements in this RDD . > > > sc . parallelize ( [ 1.0 , 2.0 , 3.0 ] ) . sum ( ) 6.0"""
return self . mapPartitions ( lambda x : [ sum ( x ) ] ) . fold ( 0 , operator . add )
def rerun ( client , revision , roots , siblings , inputs , paths ) : """Recreate files generated by a sequence of ` ` run ` ` commands ."""
graph = Graph ( client ) outputs = graph . build ( paths = paths , revision = revision ) # Check or extend siblings of outputs . outputs = siblings ( graph , outputs ) output_paths = { node . path for node in outputs } # Normalize and check all starting paths . roots = { graph . normalize_path ( root ) for root in root...
def requested_intervals ( self , intervals ) : """Set the requested intervals ( to the database ) : param intervals : The intervals : type intervals : TimeIntervals : return : None"""
with switch_db ( WorkflowStatusModel , db_alias = 'hyperstream' ) : workflow_statuses = WorkflowStatusModel . objects ( workflow_id = self . workflow_id ) if len ( workflow_statuses ) != 1 : workflow_status = WorkflowStatusModel ( workflow_id = self . workflow_id , requested_intervals = [ ] ) else :...
def upload_ssh_key ( rollback = False ) : """Upload your ssh key for passwordless logins"""
auth_keys = '/home/%s/.ssh/authorized_keys' % env . user if not rollback : local_user = getpass . getuser ( ) host = socket . gethostname ( ) u = '@' . join ( [ local_user , host ] ) u = 'ssh-key-uploaded-%s' % u if not env . overwrite and server_state ( u ) : return if not exists ( '.ss...
def create ( self , data , ** kwargs ) : """Create a new object . Args : data ( dict ) : parameters to send to the server to create the resource * * kwargs : Extra options to send to the server ( e . g . sudo ) Returns : RESTObject , RESTObject : The source and target issues Raises : GitlabAuthentic...
self . _check_missing_create_attrs ( data ) server_data = self . gitlab . http_post ( self . path , post_data = data , ** kwargs ) source_issue = ProjectIssue ( self . _parent . manager , server_data [ 'source_issue' ] ) target_issue = ProjectIssue ( self . _parent . manager , server_data [ 'target_issue' ] ) return so...
def saml_name_id_format_to_hash_type ( name_format ) : """Translate pySAML2 name format to satosa format : type name _ format : str : rtype : satosa . internal _ data . UserIdHashType : param name _ format : SAML2 name format : return : satosa format"""
msg = "saml_name_id_format_to_hash_type is deprecated and will be removed." _warnings . warn ( msg , DeprecationWarning ) name_id_format_to_hash_type = { NAMEID_FORMAT_TRANSIENT : UserIdHashType . transient , NAMEID_FORMAT_PERSISTENT : UserIdHashType . persistent , NAMEID_FORMAT_EMAILADDRESS : UserIdHashType . emailadd...
def get_resource_by_uri ( self , uri ) : """Return resource described by MediaFire URI . uri - - MediaFire URI Examples : Folder ( using folderkey ) : mf : r5g3p2z0sqs3j mf : r5g3p2z0sqs3j / folder / file . ext File ( using quickkey ) : mf : xkr43dadqa3o2p2 Path : mf : / / / Documents / file . ext...
location = self . _parse_uri ( uri ) if location . startswith ( "/" ) : # Use path lookup only , root = myfiles result = self . get_resource_by_path ( location ) elif "/" in location : # mf : abcdefjhijklm / name resource_key , path = location . split ( '/' , 2 ) parent_folder = self . get_resource_by_key (...
def _generate_data_key ( self , algorithm : AlgorithmSuite , encryption_context : Dict [ Text , Text ] ) -> DataKey : """Perform the provider - specific data key generation task . : param algorithm : Algorithm on which to base data key : type algorithm : aws _ encryption _ sdk . identifiers . Algorithm : para...
data_key = b"" . join ( [ chr ( i ) . encode ( "utf-8" ) for i in range ( 1 , algorithm . data_key_len + 1 ) ] ) return DataKey ( key_provider = self . key_provider , data_key = data_key , encrypted_data_key = self . _encrypted_data_key )
def set_stack_index ( self , index , instance ) : """Set the index of the current notebook ."""
if instance == self : self . tabwidget . setCurrentIndex ( index )
def parse_form_data ( environ , charset = 'utf8' , strict = False , ** kw ) : '''Parse form data from an environ dict and return a ( forms , files ) tuple . Both tuple values are dictionaries with the form - field name as a key ( unicode ) and lists as values ( multiple values per key are possible ) . The for...
forms , files = MultiDict ( ) , MultiDict ( ) try : if environ . get ( 'REQUEST_METHOD' , 'GET' ) . upper ( ) not in ( 'POST' , 'PUT' ) : raise MultipartError ( "Request method other than POST or PUT." ) content_length = int ( environ . get ( 'CONTENT_LENGTH' , '-1' ) ) content_type = environ . get ...
def export ( app , local , no_scrub ) : """Export the data ."""
log ( header , chevrons = False ) data . export ( str ( app ) , local = local , scrub_pii = ( not no_scrub ) )
def shannon_entropy ( p ) : """Calculates shannon entropy in bits . Parameters p : np . array array of probabilities Returns shannon entropy in bits"""
return - np . sum ( np . where ( p != 0 , p * np . log2 ( p ) , 0 ) )
def urls ( self ) : """The decoded URL list for this MIME : : Type . The special URL value IANA will be translated into : http : / / www . iana . org / assignments / media - types / < mediatype > / < subtype > The special URL value RFC # # # will be translated into : http : / / www . rfc - editor . org / rf...
def _url ( el ) : if el == 'IANA' : return IANA_URL % ( self . media_type , self . sub_type ) elif el == 'LTSW' : return LTSW_URL % self . media_type match = re . compile ( '^\{([^=]+)=([^\}]+)\}' ) . match ( el ) if match : return match . group ( 1 , 2 ) match = re . compile...
def dispatch ( self , command ) : """Pass a command along with its params to a suitable handler If the command is blank , succeed silently If the command has no handler , succeed silently If the handler raises an exception , fail with the exception message"""
log . info ( "Dispatch on %s" , command ) if not command : return "OK" action , params = self . parse_command ( command ) log . debug ( "Action = %s, Params = %s" , action , params ) try : function = getattr ( self , "do_" + action , None ) if function : function ( * params ) return "OK" except ...
def CalculateWaitForRetry ( retry_attempt , max_wait = 60 ) : """Calculates amount of time to wait before a retry attempt . Wait time grows exponentially with the number of attempts . A random amount of jitter is added to spread out retry attempts from different clients . Args : retry _ attempt : Retry at...
wait_time = 2 ** retry_attempt max_jitter = wait_time / 4.0 wait_time += random . uniform ( - max_jitter , max_jitter ) return max ( 1 , min ( wait_time , max_wait ) )
def collectFilterTerms ( self , columns = None , ignore = None ) : """Returns a collection of filter terms for this tree widget based on \ the results in the tree items . If the optional columns or ignore \ values are supplied then the specific columns will be used to generate \ the search terms , and the col...
if ( columns == None ) : columns = self . columns ( ) if ( ignore ) : columns = [ column for column in columns if not column in ignore ] # this will return an int / set pairing which we will change to a str / list terms = { } for column in columns : index = self . column ( column ) if ( index == - 1 ) :...
def batch_get_item ( self , request_items , object_hook = None ) : """Return a set of attributes for a multiple items in multiple tables using their primary keys . : type request _ items : dict : param request _ items : A Python version of the RequestItems data structure defined by DynamoDB ."""
data = { 'RequestItems' : request_items } json_input = json . dumps ( data ) return self . make_request ( 'BatchGetItem' , json_input , object_hook = object_hook )
def revoke_security_group ( self , group_name = None , src_security_group_name = None , src_security_group_owner_id = None , ip_protocol = None , from_port = None , to_port = None , cidr_ip = None , group_id = None , src_security_group_group_id = None ) : """Remove an existing rule from an existing security group ....
if src_security_group_name : if from_port is None and to_port is None and ip_protocol is None : return self . revoke_security_group_deprecated ( group_name , src_security_group_name , src_security_group_owner_id ) params = { } if group_name is not None : params [ 'GroupName' ] = group_name if group_id i...
def bake ( self , P , key = 'curr' , closed = False , itemsize = None ) : """Given a path P , return the baked vertices as they should be copied in the collection if the path has already been appended . Example : paths . append ( P ) P * = 2 paths [ ' prev ' ] [ 0 ] = bake ( P , ' prev ' ) paths [ ' cur...
itemsize = itemsize or len ( P ) itemcount = len ( P ) / itemsize # noqa n = itemsize if closed : I = np . arange ( n + 3 ) if key == 'prev' : I -= 2 I [ 0 ] , I [ 1 ] , I [ - 1 ] = n - 1 , n - 1 , n - 1 elif key == 'next' : I [ 0 ] , I [ - 3 ] , I [ - 2 ] , I [ - 1 ] = 1 , 0 , 1 , 1...
def getAmountOfHostsConnected ( self , lanInterfaceId = 1 , timeout = 1 ) : """Execute NewHostNumberOfEntries action to get the amount of known hosts . : param int lanInterfaceId : the id of the LAN interface : param float timeout : the timeout to wait for the action to be executed : return : the amount of kn...
namespace = Lan . getServiceType ( "getAmountOfHostsConnected" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetHostNumberOfEntries" , timeout = timeout ) return int ( results [ "NewHostNumberOfEntries" ] )
def create_replica ( self , clone_member ) : """create the replica according to the replica _ method defined by the user . this is a list , so we need to loop through all methods the user supplies"""
self . set_state ( 'creating replica' ) self . _sysid = None is_remote_master = isinstance ( clone_member , RemoteMember ) create_replica_methods = is_remote_master and clone_member . create_replica_methods # get list of replica methods either from clone member or from # the config . If there is no configuration key , ...
def locate_key ( self , chrom , pos = None ) : """Get index location for the requested key . Parameters chrom : object Chromosome or contig . pos : int , optional Position within chromosome or contig . Returns loc : int or slice Location of requested key ( will be slice if there are duplicate entr...
if pos is None : # we just want the region for a chromosome if chrom in self . chrom_ranges : # return previously cached result return self . chrom_ranges [ chrom ] else : loc_chrom = np . nonzero ( self . chrom == chrom ) [ 0 ] if len ( loc_chrom ) == 0 : raise KeyError ( ch...
def _run_once ( runner_list , extra_tick , use_poll ) : """: return True - success ; False - extra _ tick failure ; runner object - the runner who tick failure"""
if len ( runner_list ) > 0 : asyncore . loop ( 0 , use_poll , None , 1 ) for runner in runner_list : if not runner . tick ( ) : return runner if extra_tick is not None : code = extra_tick ( ) if code is False : return False return True
def expand ( self , url ) : """Expand implementation for Bit . ly Args : url : the URL you want to shorten Returns : A string containing the expanded URL Raises : ExpandingErrorException : If the API Returns an error as response"""
expand_url = f'{self.api_url}v3/expand' params = { 'shortUrl' : url , 'access_token' : self . api_key , 'format' : 'txt' , } response = self . _get ( expand_url , params = params ) if response . ok : return response . text . strip ( ) raise ExpandingErrorException ( response . content )
def _pixelsize ( self , p ) : """Calculate line width necessary to cover at least one pixel on all axes ."""
xpixelsize = 1. / float ( p . xdensity ) ypixelsize = 1. / float ( p . ydensity ) return max ( [ xpixelsize , ypixelsize ] )
def cmd ( name , func = None , arg = ( ) , ** kwargs ) : '''Execute a runner asynchronous : USAGE : . . code - block : : yaml run _ cloud : runner . cmd : - func : cloud . create - arg : - my - ec2 - config - myinstance run _ cloud : runner . cmd : - func : cloud . create - kwargs : provid...
ret = { 'name' : name , 'changes' : { } , 'comment' : '' , 'result' : True } if func is None : func = name local_opts = { } local_opts . update ( __opts__ ) local_opts [ 'async' ] = True # ensure this will be run asynchronous local_opts . update ( { 'fun' : func , 'arg' : arg , 'kwarg' : kwargs } ) runner = salt . ...
def write ( self , path ) : """Output the log to file . : param string path : the path of the log file to be written"""
with io . open ( path , "w" , encoding = "utf-8" ) as log_file : log_file . write ( self . pretty_print ( ) )
def rm_rf ( name ) : """Remove a file or a directory similarly to running ` rm - rf < name > ` in a UNIX shell . : param str name : the name of the file or directory to remove . : raises : OSError on error ."""
if not os . path . exists ( name ) : return try : # Avoid using safe _ rmtree so we can detect failures . shutil . rmtree ( name ) except OSError as e : if e . errno == errno . ENOTDIR : # ' Not a directory ' , but a file . Attempt to os . unlink the file , raising OSError on failure . safe_delete (...
def start ( self , timeout = None ) : """Start the client in a new thread . Parameters timeout : float in seconds Seconds to wait for client thread to start . Do not specify a timeout if start ( ) is being called from the same ioloop that this client will be installed on , since it will block the ioloop w...
if self . _running . isSet ( ) : raise RuntimeError ( "Device client already started." ) # Make sure we have an ioloop self . ioloop = self . _ioloop_manager . get_ioloop ( ) if timeout : t0 = self . ioloop . time ( ) self . _ioloop_manager . start ( timeout ) self . ioloop . add_callback ( self . _install ) if...
def apply_connectivity_changes ( request , add_vlan_action , remove_vlan_action , logger = None ) : """Standard implementation for the apply _ connectivity _ changes operation This function will accept as an input the actions to perform for add / remove vlan . It implements the basic flow of decoding the JSON c...
if not logger : logger = logging . getLogger ( "apply_connectivity_changes" ) if request is None or request == '' : raise Exception ( 'ConnectivityOperations' , 'request is None or empty' ) holder = connectivity_request_from_json ( request ) driver_response = DriverResponse ( ) results = [ ] driver_response_roo...
def getBitcoinAddressDetails ( address = None ) : '''Method that checks the presence of a Bitcoin Address in blockchain . info : " total _ sent " : 41301084, " total _ received " : 52195147, " final _ balance " : 10894063, " address " : " 1APKyS2TEdFMjXjJfMCgavFtoWuv2QNXTw " , " hash160 " : " 66f21efc754a...
try : apiURL = "https://blockchain.info/rawaddr/" + str ( address ) # Accessing the HIBP API data = urllib2 . urlopen ( apiURL ) . read ( ) # Reading the text data onto python structures jsonData = json . loads ( data ) return jsonData except : # No information was found , then we return a null ...
def _get_tax ( self , order_book_id , _ , cost_money ) : """港交所收费项目繁多 , 按照如下逻辑计算税费 : 1 . 税费比例为 0.11 % , 不足 1 元按 1 元记 , 四舍五入保留两位小数 ( 包括印花税 、 交易征费 、 交易系统使用费 ) 。 2 , 五元固定费用 ( 包括卖方收取的转手纸印花税 、 买方收取的过户费用 ) 。"""
instrument = Environment . get_instance ( ) . get_instrument ( order_book_id ) if instrument . type != 'CS' : return 0 tax = cost_money * self . tax_rate if tax < 1 : tax = 1 else : tax = round ( tax , 2 ) return tax + 5
def execute_console_command ( frame , thread_id , frame_id , line , buffer_output = True ) : """fetch an interactive console instance from the cache and push the received command to the console . create and return an instance of console _ message"""
console_message = ConsoleMessage ( ) interpreter = get_interactive_console ( thread_id , frame_id , frame , console_message ) more , output_messages , error_messages = interpreter . push ( line , frame , buffer_output ) console_message . update_more ( more ) for message in output_messages : console_message . add_co...
def get_sequence_properties ( self , clean_seq = False , representatives_only = True ) : """Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of all protein sequences . Results are stored in the protein ' s respective SeqProp objects at ` ` . annotations ` ` Args : representative...
for g in tqdm ( self . genes ) : g . protein . get_sequence_properties ( clean_seq = clean_seq , representative_only = representatives_only )
def ask ( question , default = None ) : """@ question : str @ default : Any value which can be converted to string . Asks a user for a input . If default parameter is passed it will be appended to the end of the message in square brackets ."""
question = str ( question ) if default : question += ' [' + str ( default ) + ']' question += ': ' reply = raw_input ( question ) return reply if reply else default
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 : ParticipantContext for this ParticipantInstance : rtype : twilio . rest . proxy . v1 . service . session . participant . P...
if self . _context is None : self . _context = ParticipantContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , session_sid = self . _solution [ 'session_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def find ( self , path ) : """Return the node for a path , or None ."""
path = path . split ( '.' ) node = self while node . _parent : node = node . _parent for name in path : node = node . _tree . get ( name , None ) if node is None or type ( node ) is float : return None return node
def read_until_close ( self , timeout_ms = None ) : """Yield data until this stream is closed . Args : timeout _ ms : Timeout in milliseconds to keep reading ( or a PolledTimeout object ) . Yields : Data read from a single call to self . read ( ) , until the stream is closed or timeout is reached . Ra...
while True : try : yield self . read ( timeout_ms = timeout_ms ) except usb_exceptions . AdbStreamClosedError : break
def make_view ( self , context , data , child_name ) : # type : ( Context , Model , str ) - > Any """Make a child View of data [ child _ name ]"""
with self . _lock : child = data [ child_name ] child_view = make_view ( self , context , child ) return child_view
def unzoom_all ( self , event = None , panel = None ) : """zoom out full data range"""
if panel is None : panel = self . current_panel self . panels [ panel ] . unzoom_all ( event = event )
def stops ( self ) : """Return all stops visited by trips for this agency ."""
stops = set ( ) for stop_time in self . stop_times ( ) : stops |= stop_time . stops ( ) return stops
def bool_check ( * args , func = None ) : """Check if arguments are bytes type ."""
func = func or inspect . stack ( ) [ 2 ] [ 3 ] for var in args : if not isinstance ( var , bool ) : name = type ( var ) . __name__ raise BoolError ( f'Function {func} expected bool, {name} got instead.' )
def _rest_make_phenotypes ( ) : # phenotype sources neuroner = Path ( devconfig . git_local_base , 'neuroNER/resources/bluima/neuroner/hbp_morphology_ontology.obo' ) . as_posix ( ) neuroner1 = Path ( devconfig . git_local_base , 'neuroNER/resources/bluima/neuroner/hbp_electrophysiology_ontology.obo' ) . as_posi...
desired_nif_terms = set ( ) # ' NIFQUAL : sao1959705051 ' , # dendrite # ' NIFQUAL : sao2088691397 ' , # axon # ' NIFQUAL : sao1057800815 ' , # morphological # ' NIFQUAL : sao - 1126011106 ' , # soma # ' NIFQUAL : ' , # ' NIFQUAL : ' , starts = [ # " NIFQUAL : sao2088691397 " , # " NIFQUAL : sao1278200674 " , # " NIFQU...