idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
233,900
def _clean_empty ( d ) : if not isinstance ( d , ( dict , list ) ) : return d if isinstance ( d , list ) : return [ v for v in ( _clean_empty ( v ) for v in d ) if v is not None ] return { k : v for k , v in ( ( k , _clean_empty ( v ) ) for k , v in d . items ( ) ) if v is not None }
Remove None values from a dict .
233,901
def create_cells ( headers , schema_fields , values = None , row_number = None ) : fillvalue = '_fillvalue' is_header_row = ( values is None ) cells = [ ] iterator = zip_longest ( headers , schema_fields , values or [ ] , fillvalue = fillvalue ) for column_number , ( header , field , value ) in enumerate ( iterator , s...
Create list of cells from headers fields and values .
233,902
def __impl_read_chain ( self , start , read_sector_f , read_fat_f ) : sector = start check = [ sector ] buffer = StringIO ( ) while sector != ENDOFCHAIN : buffer . write ( read_sector_f ( sector ) ) next = read_fat_f ( sector ) if next in check : logging . error ( 'infinite loop detected at {0} to {1} starting at {2}' ...
Returns the entire contents of a chain starting at the given sector .
233,903
def get_charm_url ( self ) : if self . rank_id <= 4 : return self . RANK_CHARMS [ 0 ] if self . rank_id <= 8 : return self . RANK_CHARMS [ 1 ] if self . rank_id <= 12 : return self . RANK_CHARMS [ 2 ] if self . rank_id <= 16 : return self . RANK_CHARMS [ 3 ] if self . rank_id <= 19 : return self . RANK_CHARMS [ 4 ] ret...
Get charm URL for the bracket this rank is in
233,904
def load_rank ( self , region , season = - 1 ) : data = yield from self . auth . get ( "https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/r6karma/players?board_id=pvp_ranked&profile_ids=%s&region_id=%s&season_id=%s" % ( self . spaceid , self . platform_url , self . id , region , season ) ) if "players" in da...
|coro| Loads the players rank for this region and season
233,905
def libdmtx_function ( fname , restype , * args ) : prototype = CFUNCTYPE ( restype , * args ) return prototype ( ( fname , load_libdmtx ( ) ) )
Returns a foreign function exported by libdmtx .
233,906
def _image ( pixels , width , height , pack ) : image = dmtxImageCreate ( pixels , width , height , pack ) if not image : raise PyLibDMTXError ( 'Could not create image' ) else : try : yield image finally : dmtxImageDestroy ( byref ( image ) )
A context manager for DmtxImage created and destroyed by dmtxImageCreate and dmtxImageDestroy .
233,907
def _decoder ( image , shrink ) : decoder = dmtxDecodeCreate ( image , shrink ) if not decoder : raise PyLibDMTXError ( 'Could not create decoder' ) else : try : yield decoder finally : dmtxDecodeDestroy ( byref ( decoder ) )
A context manager for DmtxDecode created and destroyed by dmtxDecodeCreate and dmtxDecodeDestroy .
233,908
def _region ( decoder , timeout ) : region = dmtxRegionFindNext ( decoder , timeout ) try : yield region finally : if region : dmtxRegionDestroy ( byref ( region ) )
A context manager for DmtxRegion created and destroyed by dmtxRegionFindNext and dmtxRegionDestroy .
233,909
def _decoded_matrix_region ( decoder , region , corrections ) : message = dmtxDecodeMatrixRegion ( decoder , region , corrections ) try : yield message finally : if message : dmtxMessageDestroy ( byref ( message ) )
A context manager for DmtxMessage created and destoyed by dmtxDecodeMatrixRegion and dmtxMessageDestroy .
233,910
def _decode_region ( decoder , region , corrections , shrink ) : with _decoded_matrix_region ( decoder , region , corrections ) as msg : if msg : p00 = DmtxVector2 ( ) p11 = DmtxVector2 ( 1.0 , 1.0 ) dmtxMatrix3VMultiplyBy ( p00 , region . contents . fit2raw ) dmtxMatrix3VMultiplyBy ( p11 , region . contents . fit2raw ...
Decodes and returns the value in a region .
233,911
def encode ( data , scheme = None , size = None ) : size = size if size else 'ShapeAuto' size_name = '{0}{1}' . format ( ENCODING_SIZE_PREFIX , size ) if not hasattr ( DmtxSymbolSize , size_name ) : raise PyLibDMTXError ( 'Invalid size [{0}]: should be one of {1}' . format ( size , ENCODING_SIZE_NAMES ) ) size = getatt...
Encodes data in a DataMatrix image .
233,912
def add_edge ( edges , edge_points , coords , i , j ) : if ( i , j ) in edges or ( j , i ) in edges : return ( edges . add ( ( i , j ) ) , edge_points . append ( coords [ [ i , j ] ] ) )
Add a line between the i - th and j - th points if not in the list already
233,913
def sequence ( self ) : if ( len ( self . Points [ 0 ] ) == 2 ) : if ( self . Sort == 'X' or self . Sort == 'x' ) : self . Points . sort ( key = lambda x : x [ 0 ] ) self . order ( self . Points ) elif ( self . Sort == 'Y' or self . Sort == 'y' ) : self . Points . sort ( key = lambda x : x [ 1 ] ) self . order ( self ....
sort the points in the line with given option
233,914
def resample ( df , rule , time_index , groupby = None , aggregation = 'mean' ) : if groupby : df = df . groupby ( groupby ) df = df . resample ( rule , on = time_index ) df = getattr ( df , aggregation ) ( ) for column in groupby : del df [ column ] return df
pd . DataFrame . resample adapter .
233,915
def _join_names ( names ) : levels = ( str ( name ) for name in names if name != '' ) return '_' . join ( levels )
Join the names of a multi - level index with an underscore .
233,916
def unstack ( df , level = - 1 , reset_index = True ) : df = df . unstack ( level = level ) if reset_index : df = df . reset_index ( ) df . columns = df . columns . map ( _join_names ) return df
pd . DataFrame . unstack adapter .
233,917
def load_boston_multitask ( ) : dataset = datasets . load_boston ( ) y = dataset . target target = np . column_stack ( [ y , 2 * y + 5 ] ) return Dataset ( load_boston . __doc__ , dataset . data , target , r2_score )
Boston House Prices Dataset with a synthetic multitask output .
233,918
def energy ( data ) : data = np . mean ( data , axis = 1 ) return np . sum ( data ** 2 ) / np . float64 ( len ( data ) )
Computes signal energy of data
233,919
def zcr ( data ) : data = np . mean ( data , axis = 1 ) count = len ( data ) countZ = np . sum ( np . abs ( np . diff ( np . sign ( data ) ) ) ) / 2 return ( np . float64 ( countZ ) / np . float64 ( count - 1.0 ) )
Computes zero crossing rate of segment
233,920
def spectral_flux ( d0 , d1 ) : d0 = np . mean ( d0 , axis = 1 ) d1 = np . mean ( d1 , axis = 1 ) nFFT = min ( len ( d0 ) // 2 , len ( d1 ) // 2 ) X = FFT ( d0 , nFFT ) Xprev = FFT ( d1 , nFFT ) sumX = np . sum ( X + EPSILON ) sumPrevX = np . sum ( Xprev + EPSILON ) return np . sum ( ( X / sumX - Xprev / sumPrevX ) ** ...
Computes the spectral flux feature of the current frame
233,921
def rolling_window_sequences ( X , index , window_size , target_size , target_column ) : out_X = list ( ) out_y = list ( ) X_index = list ( ) y_index = list ( ) target = X [ : , target_column ] for start in range ( len ( X ) - window_size - target_size + 1 ) : end = start + window_size out_X . append ( X [ start : end ...
Create rolling window sequences out of timeseries data .
233,922
def time_segments_average ( X , interval , time_column ) : warnings . warn ( _TIME_SEGMENTS_AVERAGE_DEPRECATION_WARNING , DeprecationWarning ) if isinstance ( X , np . ndarray ) : X = pd . DataFrame ( X ) X = X . sort_values ( time_column ) . set_index ( time_column ) start_ts = X . index . values [ 0 ] max_ts = X . in...
Compute average of values over fixed length time segments .
233,923
def time_segments_aggregate ( X , interval , time_column , method = [ 'mean' ] ) : if isinstance ( X , np . ndarray ) : X = pd . DataFrame ( X ) X = X . sort_values ( time_column ) . set_index ( time_column ) if isinstance ( method , str ) : method = [ method ] start_ts = X . index . values [ 0 ] max_ts = X . index . v...
Aggregate values over fixed length time segments .
233,924
def image_transform ( X , function , reshape_before = False , reshape_after = False , width = None , height = None , ** kwargs ) : if not callable ( function ) : function = import_object ( function ) elif not callable ( function ) : raise ValueError ( "function must be a str or a callable" ) flat_image = len ( X [ 0 ] ...
Apply a function image by image .
233,925
def regression_errors ( y , y_hat , smoothing_window = 0.01 , smooth = True ) : errors = np . abs ( y - y_hat ) [ : , 0 ] if not smooth : return errors smoothing_window = int ( smoothing_window * len ( y ) ) return pd . Series ( errors ) . ewm ( span = smoothing_window ) . mean ( ) . values
Compute an array of absolute errors comparing predictions and expected output .
233,926
def deltas ( errors , epsilon , mean , std ) : below = errors [ errors <= epsilon ] if not len ( below ) : return 0 , 0 return mean - below . mean ( ) , std - below . std ( )
Compute mean and std deltas .
233,927
def count_above ( errors , epsilon ) : above = errors > epsilon total_above = len ( errors [ above ] ) above = pd . Series ( above ) shift = above . shift ( 1 ) change = above != shift total_consecutive = sum ( above & change ) return total_above , total_consecutive
Count number of errors and continuous sequences above epsilon .
233,928
def z_cost ( z , errors , mean , std ) : epsilon = mean + z * std delta_mean , delta_std = deltas ( errors , epsilon , mean , std ) above , consecutive = count_above ( errors , epsilon ) numerator = - ( delta_mean / mean + delta_std / std ) denominator = above + consecutive ** 2 if denominator == 0 : return np . inf re...
Compute how bad a z value is .
233,929
def find_threshold ( errors , z_range = ( 0 , 10 ) ) : mean = errors . mean ( ) std = errors . std ( ) min_z , max_z = z_range best_z = min_z best_cost = np . inf for z in range ( min_z , max_z ) : best = fmin ( z_cost , z , args = ( errors , mean , std ) , full_output = True , disp = False ) z , cost = best [ 0 : 2 ] ...
Find the ideal threshold .
233,930
def find_sequences ( errors , epsilon ) : above = pd . Series ( errors > epsilon ) shift = above . shift ( 1 ) . fillna ( False ) change = above != shift index = above . index starts = index [ above & change ] . tolist ( ) ends = ( index [ ~ above & change ] - 1 ) . tolist ( ) if len ( ends ) == len ( starts ) - 1 : en...
Find sequences of values that are above epsilon .
233,931
def find_anomalies ( errors , index , z_range = ( 0 , 10 ) ) : threshold = find_threshold ( errors , z_range ) sequences = find_sequences ( errors , threshold ) anomalies = list ( ) denominator = errors . mean ( ) + errors . std ( ) for start , stop in sequences : max_error = errors [ start : stop + 1 ] . max ( ) score...
Find sequences of values that are anomalous .
233,932
def GaussianBlur ( X , ksize_width , ksize_height , sigma_x , sigma_y ) : return image_transform ( X , cv2 . GaussianBlur , ksize = ( ksize_width , ksize_height ) , sigmaX = sigma_x , sigmaY = sigma_y )
Apply Gaussian blur to the given data .
233,933
def get_anomalies ( smoothed_errors , y_true , z , window , all_anomalies , error_buffer ) : mu = np . mean ( smoothed_errors ) sigma = np . std ( smoothed_errors ) epsilon = mu + ( z * sigma ) errors_seq , anomaly_indices , max_error_below_e = group_consecutive_anomalies ( smoothed_errors , epsilon , y_true , error_bu...
Helper method to get anomalies .
233,934
def prune_anomalies ( e_seq , smoothed_errors , max_error_below_e , anomaly_indices ) : MIN_PERCENT_DECREASE = 0.05 e_seq_max , smoothed_errors_max = [ ] , [ ] for error_seq in e_seq : if len ( smoothed_errors [ error_seq [ 0 ] : error_seq [ 1 ] ] ) > 0 : sliced_errors = smoothed_errors [ error_seq [ 0 ] : error_seq [ ...
Helper method that removes anomalies which don t meet a minimum separation from next anomaly .
233,935
def _configure_nodes ( self , nodes ) : if isinstance ( nodes , str ) : nodes = [ nodes ] elif not isinstance ( nodes , ( dict , list ) ) : raise ValueError ( 'nodes configuration should be a list or a dict,' ' got {}' . format ( type ( nodes ) ) ) conf_changed = False for node in nodes : conf = { 'hostname' : node , '...
Parse and set up the given nodes .
233,936
def _get_pos ( self , key ) : p = bisect ( self . runtime . _keys , self . hashi ( key ) ) if p == len ( self . runtime . _keys ) : return 0 else : return p
Get the index of the given key in the sorted key list .
233,937
def _get ( self , key , what ) : if not self . runtime . _ring : return None pos = self . _get_pos ( key ) if what == 'pos' : return pos nodename = self . runtime . _ring [ self . runtime . _keys [ pos ] ] if what in [ 'hostname' , 'instance' , 'port' , 'weight' ] : return self . runtime . _nodes [ nodename ] [ what ] ...
Generic getter magic method .
233,938
def get_instances ( self ) : return [ c . get ( 'instance' ) for c in self . runtime . _nodes . values ( ) if c . get ( 'instance' ) ]
Returns a list of the instances of all the configured nodes .
233,939
def iterate_nodes ( self , key , distinct = True ) : if not self . runtime . _ring : yield None else : for node in self . range ( key , unique = distinct ) : yield node [ 'nodename' ]
hash_ring compatibility implementation .
233,940
def print_continuum ( self ) : numpoints = len ( self . runtime . _keys ) if numpoints : print ( 'Numpoints in continuum: {}' . format ( numpoints ) ) else : print ( 'Continuum empty' ) for p in self . get_points ( ) : point , node = p print ( '{} ({})' . format ( node , point ) )
Prints a ketama compatible continuum report .
233,941
def patch_memcache ( ) : def _init ( self , servers , * k , ** kw ) : self . _old_init ( servers , * k , ** kw ) nodes = { } for server in self . servers : conf = { 'hostname' : server . ip , 'instance' : server , 'port' : server . port , 'weight' : server . weight } nodes [ server . ip ] = conf self . uhashring = Hash...
Monkey patch python - memcached to implement our consistent hashring in its node selection and operations .
233,942
def hashi ( self , key , replica = 0 ) : dh = self . _listbytes ( md5 ( str ( key ) . encode ( 'utf-8' ) ) . digest ( ) ) rd = replica * 4 return ( ( dh [ 3 + rd ] << 24 ) | ( dh [ 2 + rd ] << 16 ) | ( dh [ 1 + rd ] << 8 ) | dh [ 0 + rd ] )
Returns a ketama compatible hash from the given key .
233,943
def _hashi_weight_generator ( self , node_name , node_conf ) : ks = ( node_conf [ 'vnodes' ] * len ( self . _nodes ) * node_conf [ 'weight' ] ) // self . _weight_sum for w in range ( 0 , ks ) : w_node_name = '%s-%s' % ( node_name , w ) for i in range ( 0 , self . _replicas ) : yield self . hashi ( w_node_name , replica...
Calculate the weight factor of the given node and yield its hash key for every configured replica .
233,944
def lapmod ( n , cc , ii , kk , fast = True , return_cost = True , fp_version = FP_DYNAMIC ) : check_cost ( n , cc , ii , kk ) if fast is True : x , y = _lapmod ( n , cc , ii , kk , fp_version = fp_version ) else : cc = np . ascontiguousarray ( cc , dtype = np . float64 ) ii = np . ascontiguousarray ( ii , dtype = np ....
Solve sparse linear assignment problem using Jonker - Volgenant algorithm .
233,945
def register_provider ( cls , provider ) : def decorator ( subclass ) : cls . _providers [ provider ] = subclass subclass . name = provider return subclass return decorator
Register method to keep list of providers .
233,946
def tar_to_bigfile ( self , fname , outfile ) : fnames = [ ] tmpdir = mkdtemp ( ) with tarfile . open ( fname ) as tar : tar . extractall ( path = tmpdir ) for root , _ , files in os . walk ( tmpdir ) : fnames += [ os . path . join ( root , fname ) for fname in files ] with open ( outfile , "w" ) as out : for infile in...
Convert tar of multiple FASTAs to one file .
233,947
def find_plugins ( ) : plugin_dir = os . path . dirname ( os . path . realpath ( __file__ ) ) plugin_dir = os . path . join ( plugin_dir , "plugins" ) plugin_files = [ x [ : - 3 ] for x in os . listdir ( plugin_dir ) if x . endswith ( ".py" ) ] sys . path . insert ( 0 , plugin_dir ) for plugin in plugin_files : __impor...
Locate and initialize all available plugins .
233,948
def convert ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
Convert CamelCase to underscore
233,949
def init_plugins ( ) : find_plugins ( ) d = { } for c in Plugin . __subclasses__ ( ) : ins = c ( ) if ins . name ( ) in config . get ( "plugin" , [ ] ) : ins . activate ( ) d [ ins . name ( ) ] = ins return d
Return dictionary of available plugins
233,950
def activate ( name ) : if name in plugins : plugins [ name ] . activate ( ) else : raise Exception ( "plugin {} not found" . format ( name ) )
Activate plugin .
233,951
def deactivate ( name ) : if name in plugins : plugins [ name ] . deactivate ( ) else : raise Exception ( "plugin {} not found" . format ( name ) )
Deactivate plugin .
233,952
def manage_config ( cmd , * args ) : if cmd == "file" : print ( config . config_file ) elif cmd == "show" : with open ( config . config_file ) as f : print ( f . read ( ) ) elif cmd == "generate" : fname = os . path . join ( user_config_dir ( "genomepy" ) , "{}.yaml" . format ( "genomepy" ) ) if not os . path . exists ...
Manage genomepy config file .
233,953
def search ( term , provider = None ) : if provider : providers = [ ProviderBase . create ( provider ) ] else : providers = [ ProviderBase . create ( p ) for p in ProviderBase . list_providers ( ) ] for p in providers : for row in p . search ( term ) : yield [ x . encode ( 'latin-1' ) for x in [ p . name ] + list ( row...
Search for a genome .
233,954
def install_genome ( name , provider , version = None , genome_dir = None , localname = None , mask = "soft" , regex = None , invert_match = False , annotation = False ) : if not genome_dir : genome_dir = config . get ( "genome_dir" , None ) if not genome_dir : raise norns . exceptions . ConfigError ( "Please provide o...
Install a genome .
233,955
def generate_exports ( ) : env = [ ] for name in list_installed_genomes ( ) : try : g = Genome ( name ) env_name = re . sub ( r'[^\w]+' , "_" , name ) . upper ( ) env . append ( "export {}={}" . format ( env_name , g . filename ) ) except : pass return env
Print export commands for setting environment variables .
233,956
def generate_env ( fname = None ) : config_dir = user_config_dir ( "genomepy" ) if os . path . exists ( config_dir ) : fname = os . path . join ( config_dir , "exports.txt" ) with open ( fname , "w" ) as fout : for env in generate_exports ( ) : fout . write ( "{}\n" . format ( env ) )
Generate file with exports .
233,957
def manage_plugins ( command , plugin_names = None ) : if plugin_names is None : plugin_names = [ ] active_plugins = config . get ( "plugin" , [ ] ) plugins = init_plugins ( ) if command == "enable" : for name in plugin_names : if name not in plugins : raise ValueError ( "Unknown plugin: {}" . format ( name ) ) if name...
Enable or disable plugins .
233,958
def get_random_sequences ( self , n = 10 , length = 200 , chroms = None , max_n = 0.1 ) : retries = 100 cutoff = length * max_n if not chroms : chroms = self . keys ( ) try : gap_sizes = self . gap_sizes ( ) except : gap_sizes = { } sizes = dict ( [ ( chrom , len ( self [ chrom ] ) - gap_sizes . get ( chrom , 0 ) ) for...
Return random genomic sequences .
233,959
def search ( term , provider = None ) : for row in genomepy . search ( term , provider ) : print ( "\t" . join ( [ x . decode ( 'utf-8' , 'ignore' ) for x in row ] ) )
Search for genomes that contain TERM in their name or description .
233,960
def install ( name , provider , genome_dir , localname , mask , regex , match , annotation ) : genomepy . install_genome ( name , provider , genome_dir = genome_dir , localname = localname , mask = mask , regex = regex , invert_match = not ( match ) , annotation = annotation )
Install genome NAME from provider PROVIDER in directory GENOME_DIR .
233,961
def generate_gap_bed ( fname , outname ) : f = Fasta ( fname ) with open ( outname , "w" ) as bed : for chrom in f . keys ( ) : for m in re . finditer ( r'N+' , f [ chrom ] [ : ] . seq ) : bed . write ( "{}\t{}\t{}\n" . format ( chrom , m . start ( 0 ) , m . end ( 0 ) ) )
Generate a BED file with gap locations .
233,962
def generate_sizes ( name , genome_dir ) : fa = os . path . join ( genome_dir , name , "{}.fa" . format ( name ) ) sizes = fa + ".sizes" g = Fasta ( fa ) with open ( sizes , "w" ) as f : for seqname in g . keys ( ) : f . write ( "{}\t{}\n" . format ( seqname , len ( g [ seqname ] ) ) )
Generate a sizes file with length of sequences in FASTA file .
233,963
def filter_fasta ( infa , outfa , regex = ".*" , v = False , force = False ) : if infa == outfa : raise ValueError ( "Input and output FASTA are the same file." ) if os . path . exists ( outfa ) : if force : os . unlink ( outfa ) if os . path . exists ( outfa + ".fai" ) : os . unlink ( outfa + ".fai" ) else : raise Val...
Filter fasta file based on regex .
233,964
def cmd_ok ( cmd ) : try : sp . check_call ( cmd , stderr = sp . PIPE , stdout = sp . PIPE ) except sp . CalledProcessError : pass except : sys . stderr . write ( "{} not found, skipping\n" . format ( cmd ) ) return False return True
Returns True if cmd can be run .
233,965
def run_index_cmd ( name , cmd ) : sys . stderr . write ( "Creating {} index...\n" . format ( name ) ) p = sp . Popen ( cmd , shell = True , stdout = sp . PIPE , stderr = sp . PIPE ) stdout , stderr = p . communicate ( ) if p . returncode != 0 : sys . stderr . write ( "Index for {} failed\n" . format ( name ) ) sys . s...
Run command show errors if the returncode is non - zero .
233,966
def scan_cgroups ( subsys_name , filters = list ( ) ) : status = SubsystemStatus ( ) if subsys_name not in status . get_all ( ) : raise NoSuchSubsystemError ( "No such subsystem found: " + subsys_name ) if subsys_name not in status . get_available ( ) : raise EnvironmentError ( "Disabled in the kernel: " + subsys_name ...
It returns a control group hierarchy which belong to the subsys_name . When collecting cgroups filters are applied to the cgroups . See pydoc of apply_filters method of CGroup for more information about the filters .
233,967
def walk_cgroups ( cgroup , action , opaque ) : action ( cgroup , opaque ) for child in cgroup . childs : walk_cgroups ( child , action , opaque )
The function applies the action function with the opaque object to each control group under the cgroup recursively .
233,968
def get_cgroup ( fullpath ) : fullpath = os . path . realpath ( fullpath ) status = SubsystemStatus ( ) name = None for name , path in status . paths . items ( ) : if path in fullpath : break else : raise Exception ( 'Invalid path: ' + fullpath ) subsys = _get_subsystem ( name ) return CGroup ( subsys , fullpath )
It returns a CGroup object which is pointed by the fullpath .
233,969
def parse ( content ) : ret = { } lines = content . split ( '\n' ) for line in lines : m = RdmaStat . _RE . match ( line ) if m is None : continue name = m . group ( 'name' ) hca_handle = long ( m . group ( 'hca_handle' ) ) hca_object = m . group ( 'hca_object' ) if hca_object != "max" : hca_object = long ( hca_object ...
Parse rdma . curren and rdma . max
233,970
def apply_filters ( self , filters ) : _configs = self . configs _stats = self . stats self . configs = { } self . stats = { } for f in filters : if f in _configs : self . configs [ f ] = _configs [ f ] elif f in _stats : self . stats [ f ] = _stats [ f ] else : raise NoSuchControlFileError ( "%s for %s" % ( f , self ....
It applies a specified filters . The filters are used to reduce the control groups which are accessed by get_confgs get_stats and get_defaults methods .
233,971
def get_configs ( self ) : configs = { } for name , default in self . configs . items ( ) : cls = default . __class__ path = self . paths [ name ] if os . path . exists ( path ) : try : configs [ name ] = self . _PARSERS [ cls ] ( fileops . read ( path ) ) except IOError as e : if e . errno == errno . EOPNOTSUPP : pass...
It returns a name and a current value pairs of control files which are categorised in the configs group .
233,972
def get_stats ( self ) : stats = { } for name , cls in self . stats . items ( ) : path = self . paths [ name ] if os . path . exists ( path ) : try : stats [ name ] = self . _PARSERS [ cls ] ( fileops . read ( path ) ) except IOError as e : if e . errno == errno . EOPNOTSUPP : pass if e . errno == errno . EIO : pass el...
It returns a name and a value pairs of control files which are categorised in the stats group .
233,973
def update ( self ) : pids = fileops . readlines ( self . paths [ 'cgroup.procs' ] ) self . pids = [ int ( pid ) for pid in pids if pid != '' ] self . n_procs = len ( pids )
It updates process information of the cgroup .
233,974
def wait ( self ) : ret = os . read ( self . event_fd , 64 / 8 ) return struct . unpack ( 'Q' , ret )
It returns when an event which we have configured by set_threshold happens . Note that it blocks until then .
233,975
def dumpf ( obj , path ) : with open ( path , 'w' ) as f : dump ( obj , f ) return path
Write an nginx configuration to file .
233,976
def as_strings ( self ) : ret = [ ] for x in self . children : if isinstance ( x , ( Key , Comment ) ) : ret . append ( x . as_strings ) else : for y in x . as_strings : ret . append ( y ) if ret : ret [ - 1 ] = re . sub ( '}\n+$' , '}\n' , ret [ - 1 ] ) return ret
Return the entire Conf as nginx config strings .
233,977
def as_list ( self ) : return [ self . name , self . value , [ x . as_list for x in self . children ] ]
Return all child objects in nested lists of strings .
233,978
def as_dict ( self ) : dicts = [ x . as_dict for x in self . children ] return { '{0} {1}' . format ( self . name , self . value ) : dicts }
Return all child objects in nested dict .
233,979
def as_strings ( self ) : ret = [ ] container_title = ( INDENT * self . _depth ) container_title += '{0}{1} {{\n' . format ( self . name , ( ' {0}' . format ( self . value ) if self . value else '' ) ) ret . append ( container_title ) for x in self . children : if isinstance ( x , Key ) : ret . append ( INDENT + x . as...
Return the entire Container as nginx config strings .
233,980
def as_strings ( self ) : if self . value == '' or self . value is None : return '{0};\n' . format ( self . name ) if '"' not in self . value and ( ';' in self . value or '#' in self . value ) : return '{0} "{1}";\n' . format ( self . name , self . value ) return '{0} {1};\n' . format ( self . name , self . value )
Return key as nginx config string .
233,981
def convert_aws_args ( aws_args ) : if not isinstance ( aws_args , dict ) : raise errors . InvalidConfiguration ( 'Elastic DocManager config option "aws" must be a dict' ) old_session_kwargs = dict ( region = "region_name" , access_id = "aws_access_key_id" , secret_key = "aws_secret_access_key" , ) new_kwargs = { } for...
Convert old style options into arguments to boto3 . session . Session .
233,982
def _index_and_mapping ( self , namespace ) : index , doc_type = namespace . split ( "." , 1 ) return index . lower ( ) , doc_type
Helper method for getting the index and type from a namespace .
233,983
def _stream_search ( self , * args , ** kwargs ) : for hit in scan ( self . elastic , query = kwargs . pop ( "body" , None ) , scroll = "10m" , ** kwargs ) : hit [ "_source" ] [ "_id" ] = hit [ "_id" ] yield hit [ "_source" ]
Helper method for iterating over ES search results .
233,984
def search ( self , start_ts , end_ts ) : return self . _stream_search ( index = self . meta_index_name , body = { "query" : { "range" : { "_ts" : { "gte" : start_ts , "lte" : end_ts } } } } , )
Query Elasticsearch for documents in a time range .
233,985
def commit ( self ) : self . send_buffered_operations ( ) retry_until_ok ( self . elastic . indices . refresh , index = "" )
Send buffered requests and refresh all indexes .
233,986
def add_upsert ( self , action , meta_action , doc_source , update_spec ) : if update_spec : self . bulk_index ( action , meta_action ) self . add_doc_to_update ( action , update_spec , len ( self . action_buffer ) - 2 ) else : if doc_source : self . add_to_sources ( action , doc_source ) self . bulk_index ( action , m...
Function which stores sources for insert actions and decide if for update action has to add docs to get source buffer
233,987
def add_doc_to_update ( self , action , update_spec , action_buffer_index ) : doc = { "_index" : action [ "_index" ] , "_type" : action [ "_type" ] , "_id" : action [ "_id" ] , } get_from_ES = self . should_get_id ( action ) self . doc_to_update . append ( ( doc , update_spec , action_buffer_index , get_from_ES ) )
Prepare document for update based on Elasticsearch response . Set flag if document needs to be retrieved from Elasticsearch
233,988
def get_docs_sources_from_ES ( self ) : docs = [ doc for doc , _ , _ , get_from_ES in self . doc_to_update if get_from_ES ] if docs : documents = self . docman . elastic . mget ( body = { "docs" : docs } , realtime = True ) return iter ( documents [ "docs" ] ) else : return iter ( [ ] )
Get document sources using MGET elasticsearch API
233,989
def update_sources ( self ) : ES_documents = self . get_docs_sources_from_ES ( ) for doc , update_spec , action_buffer_index , get_from_ES in self . doc_to_update : if get_from_ES : ES_doc = next ( ES_documents ) if ES_doc [ "found" ] : source = ES_doc [ "_source" ] else : LOG . error ( "mGET: Document id: %s has not b...
Update local sources based on response from Elasticsearch
233,990
def add_to_sources ( self , action , doc_source ) : mapping = self . sources . setdefault ( action [ "_index" ] , { } ) . setdefault ( action [ "_type" ] , { } ) mapping [ action [ "_id" ] ] = doc_source
Store sources locally
233,991
def get_from_sources ( self , index , doc_type , document_id ) : return self . sources . get ( index , { } ) . get ( doc_type , { } ) . get ( document_id , { } )
Get source stored locally
233,992
def clean_up ( self ) : self . action_buffer = [ ] self . sources = { } self . doc_to_get = { } self . doc_to_update = [ ]
Do clean - up before returning buffer
233,993
def get_buffer ( self ) : if self . doc_to_update : self . update_sources ( ) ES_buffer = self . action_buffer self . clean_up ( ) return ES_buffer
Get buffer which needs to be bulked to elasticsearch
233,994
def run ( self ) : self . socket = self . bluez . hci_open_dev ( self . bt_device_id ) filtr = self . bluez . hci_filter_new ( ) self . bluez . hci_filter_all_events ( filtr ) self . bluez . hci_filter_set_ptype ( filtr , self . bluez . HCI_EVENT_PKT ) self . socket . setsockopt ( self . bluez . SOL_HCI , self . bluez ...
Continously scan for BLE advertisements .
233,995
def set_scan_parameters ( self , scan_type = ScanType . ACTIVE , interval_ms = 10 , window_ms = 10 , address_type = BluetoothAddressType . RANDOM , filter_type = ScanFilter . ALL ) : interval_fractions = interval_ms / MS_FRACTION_DIVIDER if interval_fractions < 0x0004 or interval_fractions > 0x4000 : raise ValueError (...
sets the le scan parameters
233,996
def toggle_scan ( self , enable , filter_duplicates = False ) : command = struct . pack ( ">BB" , enable , filter_duplicates ) self . bluez . hci_send_cmd ( self . socket , OGF_LE_CTL , OCF_LE_SET_SCAN_ENABLE , command )
Enables or disables BLE scanning
233,997
def process_packet ( self , pkt ) : if not ( ( ( self . mode & ScannerMode . MODE_IBEACON ) and ( pkt [ 19 : 23 ] == b"\x4c\x00\x02\x15" ) ) or ( ( self . mode & ScannerMode . MODE_EDDYSTONE ) and ( pkt [ 19 : 21 ] == b"\xaa\xfe" ) ) or ( ( self . mode & ScannerMode . MODE_ESTIMOTE ) and ( pkt [ 19 : 21 ] == b"\x9a\xfe...
Parse the packet and call callback if one of the filters matches .
233,998
def save_bt_addr ( self , packet , bt_addr ) : if isinstance ( packet , EddystoneUIDFrame ) : new_mappings = [ m for m in self . eddystone_mappings if m [ 0 ] != bt_addr ] new_mappings . append ( ( bt_addr , packet . properties ) ) self . eddystone_mappings = new_mappings
Add to the list of mappings .
233,999
def get_properties ( self , packet , bt_addr ) : if is_one_of ( packet , [ EddystoneTLMFrame , EddystoneURLFrame , EddystoneEncryptedTLMFrame , EddystoneEIDFrame ] ) : return self . properties_from_mapping ( bt_addr ) else : return packet . properties
Get properties of beacon depending on type .