signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def examine_rootdir ( self , on_new_doc , on_doc_modified , on_doc_deleted , on_doc_unchanged , progress_cb = dummy_progress_cb ) : """Examine the rootdir . Calls on _ new _ doc ( doc ) , on _ doc _ modified ( doc ) , on _ doc _ deleted ( docid ) every time a new , modified , or deleted document is found"""
count = self . docsearch . index . start_examine_rootdir ( ) progress = 0 while True : ( status , doc ) = self . docsearch . index . continue_examine_rootdir ( ) if status == 'end' : break elif status == 'modified' : on_doc_modified ( doc ) elif status == 'unchanged' : on_doc_unc...
def _dbsetup ( self ) : """Create / open local SQLite database"""
self . _dbconn = sqlite3 . connect ( self . _db_file ) # Create table for multiplicons sql = '''CREATE TABLE multiplicons (id, genome_x, list_x, parent, genome_y, list_y, level, number_of_anchorpoints, profile_length, begin_x, end_x, begin_y, end_y, is_redundant)''' ...
def formatException ( self , ei ) : '''Indent traceback info for better readability'''
out = super ( CliFormatter , self ) . formatException ( ei ) return b'│' + format_multiline ( out )
def add_button ( self , name , button_class = wtf_fields . SubmitField , ** options ) : """Adds a button to the form ."""
self . _buttons [ name ] = button_class ( ** options )
def replace ( pretty , old_str , new_str ) : """Replace strings giving some info on where the replacement was done"""
out_str = '' line_number = 1 changes = 0 for line in pretty . splitlines ( keepends = True ) : new_line = line . replace ( old_str , new_str ) if line . find ( old_str ) != - 1 : logging . debug ( '%s' , line_number ) logging . debug ( '< %s' , line ) logging . debug ( '> %s' , new_line ...
def rest_put ( url , data , timeout ) : '''Call rest put method'''
try : response = requests . put ( url , headers = { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' } , data = data , timeout = timeout ) return response except Exception as e : print ( 'Get exception {0} when sending http put to url {1}' . format ( str ( e ) , url ) ) return None
def get_cloud_masks ( self , X ) : """Runs the cloud detection on the input images ( dimension n _ images x n x m x 10 or n _ images x n x m x 13 ) and returns the raster cloud mask ( dimension n _ images x n x m ) . Pixel values equal to 0 indicate pixels classified as clear - sky , while values equal to 1 i...
cloud_probs = self . get_cloud_probability_maps ( X ) return self . get_mask_from_prob ( cloud_probs )
def login ( self , email , password ) : """Login to Todoist . : param email : The user ' s email address . : type email : str : param password : The user ' s password . : type password : str : return : The HTTP response to the request . : rtype : : class : ` requests . Response ` > > > from pytodoist ...
params = { 'email' : email , 'password' : password } return self . _get ( 'login' , params )
def plot_ossos_discoveries ( ax , discoveries , plot_discoveries , plot_colossos = False , split_plutinos = False ) : """plotted at their discovery locations , provided by the Version Releases in decimal degrees ."""
fc = [ 'b' , '#E47833' , 'k' ] alpha = [ 0.85 , 0.6 , 1. ] marker = [ 'o' , 'd' ] size = [ 7 , 25 ] plottable = [ ] # Which blocks ' discoveries to include ? for d in discoveries : for n in plot_discoveries : if d [ 'object' ] . startswith ( n ) : # can for sure be better , but this hack works . Need to get...
def float_to_decimal ( f ) : """Convert a float to a 38 - precision Decimal"""
n , d = f . as_integer_ratio ( ) numerator , denominator = Decimal ( n ) , Decimal ( d ) return DECIMAL_CONTEXT . divide ( numerator , denominator )
def get_file_chunk_count ( file_path : str , chunk_size : int = DEFAULT_CHUNK_SIZE ) -> int : """Determines the number of chunks necessary to send the file for the given chunk size : param file _ path : The absolute path to the file that will be synchronized in chunks : param chunk _ size : The maximum si...
if not os . path . exists ( file_path ) : return 0 file_size = os . path . getsize ( file_path ) return max ( 1 , int ( math . ceil ( file_size / chunk_size ) ) )
def list_tags ( tags ) : """Print tags in dict so they allign with listing above ."""
tags_sorted = sorted ( list ( tags . items ( ) ) , key = operator . itemgetter ( 0 ) ) tag_sec_spacer = "" c = 1 ignored_keys = [ "Name" , "aws:ec2spot:fleet-request-id" ] pad_col = { 1 : 38 , 2 : 49 } for k , v in tags_sorted : # if k ! = " Name " : if k not in ignored_keys : if c < 3 : padamt ...
def main ( ) : """Starting point of the executable ."""
try : # A bit of a hack : We want to load the plugins ( specified via the mode # and health parameter ) in order to add their arguments to the argument # parser . But this means we first need to look into the CLI arguments # to find them . . . before looking at the arguments . So we first perform # a manual search thro...
def road_closed ( self ) : """Retrieves the road closed information for the incident / incidents from the output response Returns : road _ closed ( namedtuple ) : List of named tuples of road closed information for the incident / incidents"""
resource_list = self . traffic_incident ( ) road_closed = namedtuple ( 'road_closed' , 'road_closed' ) if len ( resource_list ) == 1 and resource_list [ 0 ] is None : return None else : try : return [ road_closed ( resource [ 'roadClosed' ] ) for resource in resource_list ] except ( KeyError , TypeE...
def _broadcast_compat_variables ( * variables ) : """Create broadcast compatible variables , with the same dimensions . Unlike the result of broadcast _ variables ( ) , some variables may have dimensions of size 1 instead of the the size of the broadcast dimension ."""
dims = tuple ( _unified_dims ( variables ) ) return tuple ( var . set_dims ( dims ) if var . dims != dims else var for var in variables )
def sessions ( status , access_key , id_only , all ) : '''List and manage compute sessions .'''
fields = [ ( 'Session ID' , 'sess_id' ) , ] with Session ( ) as session : if is_admin ( session ) : fields . append ( ( 'Owner' , 'access_key' ) ) if not id_only : fields . extend ( [ ( 'Image' , 'image' ) , ( 'Tag' , 'tag' ) , ( 'Created At' , 'created_at' , ) , ( 'Terminated At' , 'terminated_at' ) , ...
def readDataSet ( dataSet , noise = 0 ) : """: param dataSet : dataset name : param noise : amount of noise added to the dataset : return :"""
filePath = 'data/' + dataSet + '.csv' if dataSet == 'nyc_taxi' or dataSet == 'nyc_taxi_perturb' or dataSet == 'nyc_taxi_perturb_baseline' : seq = pd . read_csv ( filePath , header = 0 , skiprows = [ 1 , 2 ] , names = [ 'time' , 'data' , 'timeofday' , 'dayofweek' ] ) seq [ 'time' ] = pd . to_datetime ( seq [ 'ti...
def config_present ( name , value ) : '''Ensure configuration property is set to value in / usbkey / config name : string name of property value : string value of property'''
name = name . lower ( ) ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } # load confiration config = _load_config ( ) # handle bool and None value if isinstance ( value , ( bool ) ) : value = 'true' if value else 'false' if not value : value = "" if name in config : if six . text...
def apt_sources ( attrs = None , where = None ) : '''Return apt _ sources information from osquery CLI Example : . . code - block : : bash salt ' * ' osquery . apt _ sources'''
if __grains__ [ 'os_family' ] == 'Debian' : return _osquery_cmd ( table = 'apt_sources' , attrs = attrs , where = where ) return { 'result' : False , 'comment' : 'Only available on Debian based systems.' }
def lookups ( self , request , model_admin ) : """Returns a list of tuples . The first element in each tuple is the coded value for the option that will appear in the URL query . The second element is the human - readable name for the option that will appear in the right sidebar ."""
types = models . EventType . objects . filter ( is_public = True ) . order_by ( 'slug' ) types = [ ( t . id , t . swatch ( ) ) for t in types ] return types
def discard_elements_of_type ( input_tuple , target_type ) : """Creates a new list by removing the elements of a specific type from a given tuple . Examples : discard _ elements _ of _ type ( ( 4 , 5 , 4 , 7.7 , 1.2 ) , int ) - > [ 7.7 , 1.2] discard _ elements _ of _ type ( ( 7 , 8 , 9 , ' SR ' ) , str ) - >...
result = [ element for element in input_tuple if not isinstance ( element , target_type ) ] return result
def rnn ( name , input , state , kernel , bias , new_state , number_of_gates = 2 ) : '''- Ht = f ( Xt * Wi + Ht _ 1 * Ri + Wbi + Rbi )'''
nn = Build ( name ) nn . tanh ( nn . mad ( kernel = kernel , bias = bias , x = nn . concat ( input , state ) ) , out = new_state ) ; return nn . layers ;
def to_mesh ( obj ) : '''to _ mesh ( obj ) yields a Mesh object that is equivalent to obj or identical to obj if obj is itself a mesh object . The following objects can be converted into meshes : * a mesh object * a tuple ( coords , faces ) where coords is a coordinate matrix and faces is a matrix of coor...
if is_mesh ( obj ) : return obj elif pimms . is_vector ( obj ) and len ( obj ) == 2 : ( a , b ) = obj if pimms . is_matrix ( a , 'int' ) and pimms . is_matrix ( b , 'real' ) : return mesh ( a , b ) elif pimms . is_matrix ( b , 'int' ) and pimms . is_matrix ( a , 'real' ) : return mesh ( ...
def delete ( self , key , cache = None ) : """Query the server to delete the key specified from the cache specified . Keyword arguments : key - - the key the item is stored under . Required . cache - - the cache to delete the item from . Defaults to None , which uses self . name . If no name is set , rais...
if cache is None : cache = self . name if cache is None : raise ValueError ( "Cache name must be set" ) cache = quote_plus ( cache ) key = quote_plus ( key ) self . client . delete ( "caches/%s/items/%s" % ( cache , key ) ) return True
def get_members ( self , show = True , proxy = None , timeout = 0 ) : """GET Mediawiki : API ( action = query ) category members https : / / www . mediawiki . org / wiki / API : Categorymembers Required { params } : title OR pageid - title : < str > article title - pageid : < int > Wikipedia database ID O...
title = self . params . get ( 'title' ) pageid = self . params . get ( 'pageid' ) if not title and not pageid : raise LookupError ( "needs category title or pageid" ) self . _get ( 'category' , show , proxy , timeout ) while self . data . get ( 'continue' ) : self . _get ( 'category' , show , proxy , timeout ) ...
def instances ( exp = ".*" ) : "Filter list of machines matching an expression"
expression = re . compile ( exp ) instances = [ ] for node in ec2_instances ( ) : if node . tags and ip ( node ) : try : if expression . match ( node . tags . get ( "Name" ) ) : instances . append ( node ) except TypeError : pass return instances
def GetResults ( self ) : """Retrieves the hashing results . Returns : list [ AnalyzerResult ] : results ."""
results = [ ] for hasher in self . _hashers : logger . debug ( 'Processing results for hasher {0:s}' . format ( hasher . NAME ) ) result = analyzer_result . AnalyzerResult ( ) result . analyzer_name = self . NAME result . attribute_name = '{0:s}_hash' . format ( hasher . NAME ) result . attribute_va...
def service ( self ) : """Returns a Splunk service object for this command invocation or None . The service object is created from the Splunkd URI and authentication token passed to the command invocation in the search results info file . This data is not passed to a command invocation by default . You must ...
if self . _service is not None : return self . _service info = self . search_results_info if info is None : return None splunkd = urlsplit ( info . splunkd_uri , info . splunkd_protocol , allow_fragments = False ) self . _service = Service ( scheme = splunkd . scheme , host = splunkd . hostname , port = splunkd...
def content_remove ( self , key , model , contentid ) : """Deletes the information for the given contentid under the given model . This method maps to https : / / github . com / exosite / docs / tree / master / provision # delete - - - delete - content Args : key : The CIK or Token for the device model :"...
path = PROVISION_MANAGE_CONTENT + model + '/' + contentid return self . _request ( path , key , '' , 'DELETE' , self . _manage_by_cik )
def cleanall ( self , str , cleanslash = 0 ) : """Deals with things like : 1 . / accents with a slashes and converts them to entities . Example : \' , \ ` , \ ^ 2 . / Some ' missed ' incomplete entities or & # x00b4 ; ( floating apostroph ) and the like . Example : Milos & caron ; evic - - > Milo & scaron...
retstr = self . re_accent . sub ( self . __sub_accent , str ) retstr = self . re_missent . sub ( self . __sub_missent , retstr ) # retstr = self . re _ missent _ space . sub ( ' ' , retstr ) retstr = self . re_morenum . sub ( self . __sub_morenum , retstr ) # 11/5/02 AA - add translation of & rsquo ; and & rsquor ; int...
def update_get_params ( self ) : """Update HTTP GET params with the given fields that user wants to fetch ."""
if isinstance ( self . _fields , ( tuple , list ) ) : # tuples & lists > x , y , z self . get_params [ "fields" ] = "," . join ( [ str ( _ ) for _ in self . _fields ] ) elif isinstance ( self . _fields , str ) : self . get_params [ "fields" ] = self . _fields
def update_jsonb ( uid , extinfo ) : '''Update the json .'''
cur_extinfo = MPost . get_by_uid ( uid ) . extinfo for key in extinfo : cur_extinfo [ key ] = extinfo [ key ] entry = TabPost . update ( extinfo = cur_extinfo , ) . where ( TabPost . uid == uid ) entry . execute ( ) return uid
def push_account_task ( obj_id ) : """Async : push _ account _ task . delay ( Account . id )"""
lock_id = "%s-push-account-%s" % ( settings . ENV_PREFIX , obj_id ) acquire_lock = lambda : cache . add ( lock_id , "true" , LOCK_EXPIRE ) # noqa : E731 release_lock = lambda : cache . delete ( lock_id ) # noqa : E731 if acquire_lock ( ) : UserModel = get_user_model ( ) try : upload_intercom_user ( obj_...
def check_coin_a_phrase_from ( text ) : """Check the text ."""
err = "misc.illogic.coin" msg = "You can't coin an existing phrase. Did you mean 'borrow'?" regex = "to coin a phrase from" return existence_check ( text , [ regex ] , err , msg , offset = 1 )
def setColumnHidden ( self , column , state ) : """Sets the hidden state for the inputed column . : param column | < int > state | < bool >"""
super ( XTreeWidget , self ) . setColumnHidden ( column , state ) if ( not self . signalsBlocked ( ) ) : self . columnHiddenChanged . emit ( column , state ) self . executeDelayedItemsLayout ( )
def get_user_groups ( name , sid = False ) : '''Get the groups to which a user belongs Args : name ( str ) : The user name to query sid ( bool ) : True will return a list of SIDs , False will return a list of group names Returns : list : A list of group names or sids'''
if name == 'SYSTEM' : # ' win32net . NetUserGetLocalGroups ' will fail if you pass in ' SYSTEM ' . groups = [ name ] else : groups = win32net . NetUserGetLocalGroups ( None , name ) if not sid : return groups ret_groups = set ( ) for group in groups : ret_groups . add ( get_sid_from_name ( group ) ) ret...
def is_list_of_list ( item ) : """check whether the item is list ( tuple ) and consist of list ( tuple ) elements"""
if ( type ( item ) in ( list , tuple ) and len ( item ) and isinstance ( item [ 0 ] , ( list , tuple ) ) ) : return True return False
def add_rule_to_model ( model , rule , annotations = None ) : """Add a Rule to a PySB model and handle duplicate component errors ."""
try : model . add_component ( rule ) # If the rule was actually added , also add the annotations if annotations : model . annotations += annotations # If this rule is already in the model , issue a warning and continue except ComponentDuplicateNameError : msg = "Rule %s already in model! Skippin...
def from_image ( cls , image , filename ) : """Filename is 1-8 alphanumeric characters to identify the GRF in ZPL ."""
source = Image . open ( BytesIO ( image ) ) source = source . convert ( '1' ) width = int ( math . ceil ( source . size [ 0 ] / 8.0 ) ) data = [ ] for line in _chunked ( list ( source . getdata ( ) ) , source . size [ 0 ] ) : row = '' . join ( [ '0' if p else '1' for p in line ] ) row = row . ljust ( width * 8 ...
def load_file_to_string ( self ) : """load a file to a string"""
try : with open ( self . fullname , 'r' ) as f : txt = f . read ( ) return txt except IOError : return ''
def alpha3 ( self , code ) : """Return the ISO 3166-1 three letter country code matching the provided country code . If no match is found , returns an empty string ."""
code = self . alpha2 ( code ) try : return self . alt_codes [ code ] [ 0 ] except KeyError : return ""
def bookmark_present ( name , snapshot ) : '''ensure bookmark exists name : string name of bookmark snapshot : string name of snapshot'''
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } # # log configuration log . debug ( 'zfs.bookmark_present::%s::config::snapshot = %s' , name , snapshot ) # # check we have valid snapshot / bookmark name if not __utils__ [ 'zfs.is_snapshot' ] ( snapshot ) : ret [ 'result' ] = False r...
def get_config ( ini_path = None , rootdir = None ) : """Load configuration from INI . : return Namespace :"""
config = Namespace ( ) config . default_section = 'pylama' if not ini_path : path = get_default_config_file ( rootdir ) if path : config . read ( path ) else : config . read ( ini_path ) return config
def _GetSanitizedEventValues ( self , event ) : """Sanitizes the event for use in Elasticsearch . The event values need to be sanitized to prevent certain values from causing problems when indexing with Elasticsearch . For example the path specification is a nested dictionary which will cause problems for E...
event_values = { } for attribute_name , attribute_value in event . GetAttributes ( ) : # Ignore the regvalue attribute as it cause issues when indexing . if attribute_name == 'regvalue' : continue if attribute_name == 'pathspec' : try : attribute_value = JsonPathSpecSerializer . Writ...
def get_SSE ( a , b , r , x , y ) : """input : a , b , r , x , y . circle center , radius , xpts , ypts output : SSE"""
SSE = 0 X = numpy . array ( x ) Y = numpy . array ( y ) for i in range ( len ( X ) ) : x = X [ i ] y = Y [ i ] v = ( numpy . sqrt ( ( x - a ) ** 2 + ( y - b ) ** 2 ) - r ) ** 2 SSE += v return SSE
def create_onvif_service ( self , name , from_template = True , portType = None ) : '''Create ONVIF service client'''
name = name . lower ( ) xaddr , wsdl_file = self . get_definition ( name ) with self . services_lock : svt = self . services_template . get ( name ) # Has a template , clone from it . Faster . if svt and from_template and self . use_services_template . get ( name ) : service = ONVIFService . clone (...
async def set_start_date ( self , date : str , time : str , check_in_duration : int = None ) : """set the tournament start date ( and check in duration ) | methcoro | Args : date : fomatted date as YYYY / MM / DD ( 2017/02/14) time : fromatted time as HH : MM ( 20:15) check _ in _ duration ( optional ) : ...
date_time = datetime . strptime ( date + ' ' + time , '%Y/%m/%d %H:%M' ) res = await self . connection ( 'PUT' , 'tournaments/{}' . format ( self . _id ) , 'tournament' , start_at = date_time , check_in_duration = check_in_duration or 0 ) self . _refresh_from_json ( res )
def ajax_required ( func ) : # taken from djangosnippets . org """AJAX request required decorator use it in your views : @ ajax _ required def my _ view ( request ) :"""
def wrap ( request , * args , ** kwargs ) : if not request . is_ajax ( ) : return HttpResponseBadRequest return func ( request , * args , ** kwargs ) wrap . __doc__ = func . __doc__ wrap . __name__ = func . __name__ return wrap
def load_alerts ( self ) : """NOTE : use refresh ( ) instead of this , if you are just needing to refresh the alerts list Gets raw xml ( cap ) from the Alerts feed , throws it into the parser and ends up with a list of alerts object , which it stores to self . _ alerts"""
self . _feed = AlertsFeed ( state = self . scope , maxage = self . cachetime ) parser = CapParser ( self . _feed . raw_cap ( ) , geo = self . geo ) self . _alerts = parser . get_alerts ( )
def apply_trans_rot ( ampal , translation , angle , axis , point , radians = False ) : """Applies a translation and rotation to an AMPAL object ."""
if not numpy . isclose ( angle , 0.0 ) : ampal . rotate ( angle = angle , axis = axis , point = point , radians = radians ) ampal . translate ( vector = translation ) return
def _get_id ( self , player ) : """Parse the player ID . Given a PyQuery object representing a single player on the team roster , parse the player ID and return it as a string . Parameters player : PyQuery object A PyQuery object representing the player information from the roster table . Returns st...
name_tag = player ( 'td[data-stat="player"] a' ) name = re . sub ( r'.*/players/./' , '' , str ( name_tag ) ) return re . sub ( r'\.shtml.*' , '' , name )
def add_aux_param ( self , param_name , layer_index , blob_index ) : """Add an aux param to . params file . Example : moving _ mean in BatchNorm layer"""
self . add_param ( 'aux:%s' % param_name , layer_index , blob_index )
def load ( cls , fp , ** kwargs ) : """wrapper for : py : func : ` json . load `"""
json_obj = json . load ( fp , ** kwargs ) return parse ( cls , json_obj )
def formatted ( text , * args , ** kwargs ) : """Args : text ( str | unicode ) : Text to format * args : Objects to extract values from ( as attributes ) * * kwargs : Optional values provided as named args Returns : ( str ) : Attributes from this class are expanded if mentioned"""
if not text or "{" not in text : return text strict = kwargs . pop ( "strict" , True ) max_depth = kwargs . pop ( "max_depth" , 3 ) objects = list ( args ) + [ kwargs ] if kwargs else args [ 0 ] if len ( args ) == 1 else args if not objects : return text definitions = { } markers = RE_FORMAT_MARKERS . findall (...
def is_fp_arg ( self , arg ) : """This should take a SimFunctionArgument instance and return whether or not that argument is a floating - point argument . Returns True for MUST be a floating point arg , False for MUST NOT be a floating point arg , None for when it can be either ."""
if arg in self . int_args : return False if arg in self . fp_args or arg == self . FP_RETURN_VAL : return True return None
def remove_lcr_regions ( orig_bed , items ) : """If configured and available , update a BED file to remove low complexity regions ."""
lcr_bed = tz . get_in ( [ "genome_resources" , "variation" , "lcr" ] , items [ 0 ] ) if lcr_bed and os . path . exists ( lcr_bed ) and "lcr" in get_exclude_regions ( items ) : return _remove_regions ( orig_bed , [ lcr_bed ] , "nolcr" , items [ 0 ] ) else : return orig_bed
def read_fei_metadata ( fh , byteorder , dtype , count , offsetsize ) : """Read FEI SFEG / HELIOS headers and return as dict ."""
result = { } section = { } data = bytes2str ( stripnull ( fh . read ( count ) ) ) for line in data . splitlines ( ) : line = line . strip ( ) if line . startswith ( '[' ) : section = { } result [ line [ 1 : - 1 ] ] = section continue try : key , value = line . split ( '=' ) ...
def delete ( filename , retry_params = None , _account_id = None ) : """Delete a Google Cloud Storage file . Args : filename : A Google Cloud Storage filename of form ' / bucket / filename ' . retry _ params : An api _ utils . RetryParams for this call to GCS . If None , the default one is used . _ accoun...
api = storage_api . _get_storage_api ( retry_params = retry_params , account_id = _account_id ) common . validate_file_path ( filename ) filename = api_utils . _quote_filename ( filename ) status , resp_headers , content = api . delete_object ( filename ) errors . check_status ( status , [ 204 ] , filename , resp_heade...
def parse_uptime ( uptime_str ) : """Extract the uptime string from the given Cisco IOS Device . Return the uptime in seconds as an integer"""
# Initialize to zero ( years , weeks , days , hours , minutes ) = ( 0 , 0 , 0 , 0 , 0 ) uptime_str = uptime_str . strip ( ) time_list = uptime_str . split ( "," ) for element in time_list : if re . search ( "year" , element ) : years = int ( element . split ( ) [ 0 ] ) elif re . search ( "week" , elemen...
def close ( self ) : """Close the connection ."""
if self . sock : self . sock . close ( ) self . sock = 0 self . eof = 1
def dr ( self , r1 , r2 , cutoff = None ) : """Calculate the distance between two fractional coordinates in the cell . Args : r1 ( np . array ) : fractional coordinates for position 1. r2 ( np . array ) : fractional coordinates for position 2. cutoff ( optional : Bool ) : If set , returns None for distances...
delta_r_cartesian = ( r1 - r2 ) . dot ( self . matrix ) delta_r_squared = sum ( delta_r_cartesian ** 2 ) if cutoff != None : cutoff_squared = cutoff ** 2 if delta_r_squared > cutoff_squared : return None return ( math . sqrt ( delta_r_squared ) )
def millis_to_human_readable ( time_millis ) : """Calculates the equivalent time of the given milliseconds into a human readable string from seconds to weeks . : param time _ millis : Time in milliseconds using python time library . : return : Human readable time string . Example : 2 min 3 s ."""
weeks = 0 days = 0 hours = 0 minutes = 0 seconds = round ( time_millis / 1000 ) while seconds > 59 : seconds -= 60 minutes += 1 while minutes > 59 : minutes -= 60 hours += 1 while hours > 23 : hours -= 24 days += 1 while days > 6 : hours -= 7 weeks += 1 if weeks > 0 : output = '{} w ...
def change_custom_host_var ( self , host , varname , varvalue ) : """Change custom host variable Format of the line that triggers function call : : CHANGE _ CUSTOM _ HOST _ VAR ; < host _ name > ; < varname > ; < varvalue > : param host : host to edit : type host : alignak . objects . host . Host : param ...
if varname . upper ( ) in host . customs : host . modified_attributes |= DICT_MODATTR [ "MODATTR_CUSTOM_VARIABLE" ] . value host . customs [ varname . upper ( ) ] = varvalue self . send_an_element ( host . get_update_status_brok ( ) )
def to_file ( self , path ) : """Write metadata to an image , video or XMP sidecar file . : param str path : The image / video file path name ."""
xmp_path = path + '.xmp' # remove any existing XMP file if os . path . exists ( xmp_path ) : os . unlink ( xmp_path ) # attempt to open image / video file for metadata md_path = path md = GExiv2 . Metadata ( ) try : md . open_path ( md_path ) except GLib . GError : # file type does not support metadata so use X...
def _bind ( l , bind = None ) : '''Bind helper .'''
if bind is None : return method = bind . get ( 'method' , 'simple' ) if method is None : return elif method == 'simple' : l . simple_bind_s ( bind . get ( 'dn' , '' ) , bind . get ( 'password' , '' ) ) elif method == 'sasl' : sasl_class = getattr ( ldap . sasl , bind . get ( 'mechanism' , 'EXTERNAL' ) ....
def execute ( self , sources , target ) : """: type sources : list [ DFAdapter ] : type target : DFAdapter"""
existing_ml_fields = self . _get_fields_list_from_eps ( sources ) dup_ml_fields = [ f . copy ( ) for f in self . fields ] if self . is_append : src = list ( [ copy . deepcopy ( f ) for f in existing_ml_fields [ 0 ] ] ) src . extend ( dup_ml_fields ) target . _ml_fields = src else : target . _ml_fields =...
def search ( self , buf ) : """Search the provided buffer for matching text . Search the provided buffer for matching text . If the * match * is found , returns a : class : ` SequenceMatch ` object , otherwise returns ` ` None ` ` . : param buf : Buffer to search for a match . : return : : class : ` Sequenc...
self . _check_type ( buf ) normalized = unicodedata . normalize ( self . FORM , buf ) idx = normalized . find ( self . _text ) if idx < 0 : return None start = idx end = idx + len ( self . _text ) return SequenceMatch ( self , normalized [ start : end ] , start , end )
def execute ( self , identity_records : 'RDD' , old_state_rdd : Optional [ 'RDD' ] = None ) -> 'RDD' : """Executes Blurr BTS with the given records . old _ state _ rdd can be provided to load an older state from a previous run . : param identity _ records : RDD of the form Tuple [ Identity , List [ TimeAndRecor...
identity_records_with_state = identity_records if old_state_rdd : identity_records_with_state = identity_records . fullOuterJoin ( old_state_rdd ) return identity_records_with_state . map ( lambda x : self . _execute_per_identity_records ( x ) )
async def create_proof ( self , proof_req : dict , creds : dict , requested_creds : dict ) -> str : """Create proof as HolderProver . Raise : * AbsentLinkSecret if link secret not set * CredentialFocus on attempt to create proof on no creds or multiple creds for a credential definition * AbsentTails if miss...
LOGGER . debug ( 'HolderProver.create_proof >>> proof_req: %s, creds: %s, requested_creds: %s' , proof_req , creds , requested_creds ) self . _assert_link_secret ( 'create_proof' ) x_uuids = [ attr_uuid for attr_uuid in creds [ 'attrs' ] if len ( creds [ 'attrs' ] [ attr_uuid ] ) != 1 ] if x_uuids : LOGGER . debug ...
def frustum_height_at_distance ( vfov_deg , distance ) : """Calculate the frustum height ( in world units ) at a given distance ( in world units ) from the camera ."""
height = 2.0 * distance * np . tan ( np . radians ( vfov_deg * 0.5 ) ) return height
def cloneNode ( self ) : '''cloneNode - Clone this node ( tag name and attributes ) . Does not clone children . Tags will be equal according to isTagEqual method , but will contain a different internal unique id such tag origTag ! = origTag . cloneNode ( ) , as is the case in JS DOM .'''
return self . __class__ ( self . tagName , self . getAttributesList ( ) , self . isSelfClosing )
def left_to_right ( self ) : """This is for text that flows Left to Right"""
self . _entry_mode |= Command . MODE_INCREMENT self . command ( self . _entry_mode )
def compute_feature_weights ( pres_list , rec_list , feature_list , distances ) : """Compute clustering scores along a set of feature dimensions Parameters pres _ list : list list of presented words rec _ list : list list of recalled words feature _ list : list list of feature dicts for presented word...
# initialize the weights object for just this list weights = { } for feature in feature_list [ 0 ] : weights [ feature ] = [ ] # return default list if there is not enough data to compute the fingerprint if len ( rec_list ) <= 2 : print ( 'Not enough recalls to compute fingerprint, returning default' 'fingerpri...
def from_xml ( cls , data , api = None , parser = None ) : """Create a new instance and load data from xml data or object . . . note : : If parser is set to None , the functions tries to find the best parse . By default the SAX parser is chosen if a string is provided as data . The parser is set to DOM if a...
if parser is None : if isinstance ( data , str ) : parser = XML_PARSER_SAX else : parser = XML_PARSER_DOM result = cls ( api = api ) if parser == XML_PARSER_DOM : import xml . etree . ElementTree as ET if isinstance ( data , str ) : root = ET . fromstring ( data ) elif isinst...
def js_output ( self , attrs = None ) : """Return a string suitable for JavaScript ."""
result = [ ] items = sorted ( self . items ( ) ) for key , value in items : result . append ( value . js_output ( attrs ) ) return _nulljoin ( result )
def move_camera ( action , action_space , minimap ) : """Move the camera ."""
minimap . assign_to ( spatial ( action , action_space ) . camera_move . center_minimap )
def xreadgroup ( self , groupname , consumername , streams , count = None , block = None , noack = False ) : """Read from a stream via a consumer group . groupname : name of the consumer group . consumername : name of the requesting consumer . streams : a dict of stream names to stream IDs , where IDs indic...
pieces = [ Token . get_token ( 'GROUP' ) , groupname , consumername ] if count is not None : if not isinstance ( count , ( int , long ) ) or count < 1 : raise DataError ( "XREADGROUP count must be a positive integer" ) pieces . append ( Token . get_token ( "COUNT" ) ) pieces . append ( str ( count )...
def RGB_to_HSV ( cobj , * args , ** kwargs ) : """Converts from RGB to HSV . H values are in degrees and are 0 to 360. S values are a percentage , 0.0 to 1.0. V values are a percentage , 0.0 to 1.0."""
var_R = cobj . rgb_r var_G = cobj . rgb_g var_B = cobj . rgb_b var_max = max ( var_R , var_G , var_B ) var_min = min ( var_R , var_G , var_B ) var_H = __RGB_to_Hue ( var_R , var_G , var_B , var_min , var_max ) if var_max == 0 : var_S = 0 else : var_S = 1.0 - ( var_min / var_max ) var_V = var_max return HSVColor...
def save_profile ( self , profile ) : """Save the current minimum needs into a new profile . : param profile : The profile ' s name : type profile : basestring , str"""
profile = profile . replace ( '.json' , '' ) profile_path = os . path . join ( self . root_directory , 'minimum_needs' , profile + '.json' ) self . write_to_file ( profile_path )
def url_path_replace ( url , old , new , count = None ) : """Return a copy of url with replaced path . Return a copy of url with all occurrences of old replaced by new in the url path . If the optional argument count is given , only the first count occurrences are replaced ."""
args = [ ] scheme , netloc , path , query , fragment = urlparse . urlsplit ( url ) if count is not None : args . append ( count ) return urlparse . urlunsplit ( ( scheme , netloc , path . replace ( old , new , * args ) , query , fragment ) )
def save_state_machine ( delete_old_state_machine = False , recent_opened_notification = False , as_copy = False , copy_path = None ) : """Save selected state machine The function checks if states of the state machine has not stored script data abd triggers dialog windows to take user input how to continue ( ig...
state_machine_manager_model = rafcon . gui . singleton . state_machine_manager_model states_editor_ctrl = rafcon . gui . singleton . main_window_controller . get_controller ( 'states_editor_ctrl' ) state_machine_m = state_machine_manager_model . get_selected_state_machine_model ( ) if state_machine_m is None : logg...
def post ( self , title , body , permlink , tags ) : '''Used for creating a main post to an account ' s blog . Waits 20 seconds after posting as that is the required amount of time between posting .'''
for num_of_retries in range ( default . max_retry ) : try : self . msg . message ( "Attempting to post " + permlink ) self . steem_instance ( ) . post ( title , body , self . mainaccount , permlink , None , None , None , None , tags , None , False ) except Exception as e : self . util . ...
def send_to_splunk ( session = None , url = None , data = None , headers = None , verify = False , ssl_options = None , timeout = 10.0 ) : """send _ to _ splunk Send formatted msgs to Splunk . This will throw exceptions for any errors . It is decoupled from the publishers to make testing easier with mocks . ...
r = session . post ( url = url , data = data , headers = headers , verify = verify , timeout = timeout ) r . raise_for_status ( ) # Throws exception for 4xx / 5xx status return r
def expand_zip ( zip_fname , cwd = None ) : "expand a zip"
unzip_path = '/usr/bin/unzip' if not os . path . exists ( unzip_path ) : log . error ( 'ERROR: {} does not exist' . format ( unzip_path ) ) sys . exit ( 1 ) args = [ unzip_path , zip_fname ] # Does it have a top dir res = subprocess . Popen ( [ args [ 0 ] , '-l' , args [ 1 ] ] , cwd = cwd , stdout = subprocess ...
def result_report_class_wise_average ( self ) : """Report class - wise averages Returns str result report in string format"""
results = self . results_class_wise_average_metrics ( ) output = self . ui . section_header ( 'Class-wise average metrics (macro-average)' , indent = 2 ) + '\n' if results [ 'f_measure' ] : output += self . ui . line ( 'F-measure' , indent = 2 ) + '\n' output += self . ui . data ( field = 'F-measure (F1)' , val...
def current_heart_rate ( self ) : """Return current heart rate for in - progress session ."""
try : rates = self . intervals [ 0 ] [ 'timeseries' ] [ 'heartRate' ] num_rates = len ( rates ) if num_rates == 0 : return None rate = rates [ num_rates - 1 ] [ 1 ] except KeyError : rate = None return rate
def explode_host_groups_into_hosts ( self , item , hosts , hostgroups ) : """Get all hosts of hostgroups and add all in host _ name container : param item : the item object : type item : alignak . objects . item . Item : param hosts : hosts object : type hosts : alignak . objects . host . Hosts : param ho...
hnames_list = [ ] # Gets item ' s hostgroup _ name hgnames = getattr ( item , "hostgroup_name" , '' ) or '' # Defines if hostgroup is a complex expression # Expands hostgroups if is_complex_expr ( hgnames ) : hnames_list . extend ( self . evaluate_hostgroup_expression ( item . hostgroup_name , hosts , hostgroups ) ...
def _construct_target_list ( targets ) : """Create a list of TargetEntry items from a list of tuples in the form ( target , flags , info ) The list can also contain existing TargetEntry items in which case the existing entry is re - used in the return list ."""
target_entries = [ ] for entry in targets : if not isinstance ( entry , Gtk . TargetEntry ) : entry = Gtk . TargetEntry . new ( * entry ) target_entries . append ( entry ) return target_entries
def flatten ( struct ) : """Creates a flat list of all all items in structured output ( dicts , lists , items ) : . . code - block : : python > > > sorted ( flatten ( { ' a ' : ' foo ' , ' b ' : ' bar ' } ) ) [ ' bar ' , ' foo ' ] > > > sorted ( flatten ( [ ' foo ' , [ ' bar ' , ' troll ' ] ] ) ) [ ' bar ...
if struct is None : return [ ] flat = [ ] if isinstance ( struct , dict ) : for _ , result in six . iteritems ( struct ) : flat += flatten ( result ) return flat if isinstance ( struct , six . string_types ) : return [ struct ] try : # if iterable iterator = iter ( struct ) except TypeError ...
def delete ( obj , key = None ) : """Delete a single key if specified , or all env if key is none : param obj : settings object : param key : key to delete from store location : return : None"""
client = StrictRedis ( ** obj . REDIS_FOR_DYNACONF ) holder = obj . get ( "ENVVAR_PREFIX_FOR_DYNACONF" ) if key : client . hdel ( holder . upper ( ) , key . upper ( ) ) obj . unset ( key ) else : keys = client . hkeys ( holder . upper ( ) ) client . delete ( holder . upper ( ) ) obj . unset_all ( ke...
def force_auto ( service , _type ) : """Helper for forcing autoserialization of a datatype with already registered explicit storable instance . Arguments : service ( StorableService ) : active storable service . _ type ( type ) : type to be autoserialized . * * Not tested * *"""
storable = service . byPythonType ( _type , istype = True ) version = max ( handler . version [ 0 ] for handler in storable . handlers ) + 1 _storable = default_storable ( _type , version = ( version , ) ) storable . handlers . append ( _storable . handlers [ 0 ] )
def _exists_with_etag ( self , name , content ) : """Checks whether a file with a name and a content is already uploaded to Cloudinary . Uses ETAG header and MD5 hash for the content comparison ."""
url = self . _get_url ( name ) response = requests . head ( url ) if response . status_code == 404 : return False etag = response . headers [ 'ETAG' ] . split ( '"' ) [ 1 ] hash = self . file_hash ( name , content ) return etag . startswith ( hash )
def _validate_schema_and_ast ( schema , ast ) : """Validate the supplied graphql schema and ast . This method wraps around graphql - core ' s validation to enforce a stricter requirement of the schema - - all directives supported by the compiler must be declared by the schema , regardless of whether each dire...
core_graphql_errors = validate ( schema , ast ) # The following directives appear in the core - graphql library , but are not supported by the # graphql compiler . unsupported_default_directives = frozenset ( [ frozenset ( [ 'include' , frozenset ( [ 'FIELD' , 'FRAGMENT_SPREAD' , 'INLINE_FRAGMENT' ] ) , frozenset ( [ '...
def log_initial_states ( self ) : """Raise hosts and services initial status logs First , raise hosts status and then services . This to allow the events log to be a little sorted . : return : None"""
# Raise hosts initial status broks for elt in self . hosts : elt . raise_initial_state ( ) # And then services initial status broks for elt in self . services : elt . raise_initial_state ( )
def from_string ( cls , token_string ) : """` token _ string ` should be the string representation from the server ."""
# unhexlify works fine with unicode input in everythin but pypy3 , where it Raises " TypeError : ' str ' does not support the buffer interface " if isinstance ( token_string , six . text_type ) : token_string = token_string . encode ( 'ascii' ) # The BOP stores a hex string return cls ( unhexlify ( token_string ) )
def islink ( self , path = None , header = None ) : """Returns True if object is a symbolic link . Args : path ( str ) : File path or URL . header ( dict ) : Object header . Returns : bool : True if object is Symlink ."""
if header is None : header = self . _head ( self . get_client_kwargs ( path ) ) for key in ( 'x-oss-object-type' , 'type' ) : try : return header . pop ( key ) == 'Symlink' except KeyError : continue return False
def drive_rotational_speed_rpm ( self ) : """Gets set of rotational speed of the disks"""
drv_rot_speed_rpm = set ( ) for member in self . _drives_list ( ) : if member . rotation_speed_rpm is not None : drv_rot_speed_rpm . add ( member . rotation_speed_rpm ) return drv_rot_speed_rpm
def _ParseLogLine ( self , parser_mediator , structure , key ) : """Parse a single log line and produce an event object . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . structure ( pyparsing . ParseResults ) : structure ...
time_elements_tuple = self . _GetTimeElementsTuple ( structure ) try : date_time = dfdatetime_time_elements . TimeElements ( time_elements_tuple = time_elements_tuple ) except ValueError : parser_mediator . ProduceExtractionWarning ( 'invalid date time value: {0!s}' . format ( structure . date_time ) ) retu...
async def seen ( self , tick , source = None ) : '''Update the . seen interval and optionally a source specific seen node .'''
await self . set ( '.seen' , tick ) if source is not None : seen = await self . snap . addNode ( 'meta:seen' , ( source , self . ndef ) ) await seen . set ( '.seen' , tick )
def list_concat ( input , ** params ) : """Concatenates two or more lists and put result into dest field : param input : : param params : : return :"""
PARAM_SOURCE_FIELDS = 'src.fields' PARAM_DEST_FIELD = 'dest.field' field_list = params . get ( PARAM_SOURCE_FIELDS ) for row in input : res = [ ] for field in field_list : res += row [ field ] row [ params . get ( PARAM_DEST_FIELD ) ] = res return input