idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
234,900
def generateImplicitParameters ( obj ) : try : obj . action except AttributeError : obj . add ( 'action' ) . value = 'AUDIO' try : obj . trigger except AttributeError : obj . add ( 'trigger' ) . value = datetime . timedelta ( 0 )
Create default ACTION and TRIGGER if they re not set .
234,901
def transformToNative ( obj ) : if obj . isNative : return obj obj . isNative = True obj . value = obj . value if obj . value == '' : return obj else : deltalist = stringToDurations ( obj . value ) if len ( deltalist ) == 1 : obj . value = deltalist [ 0 ] return obj else : raise ParseError ( "DURATION must have a singl...
Turn obj . value into a datetime . timedelta .
234,902
def transformFromNative ( obj ) : if not obj . isNative : return obj obj . isNative = False obj . value = timedeltaToString ( obj . value ) return obj
Replace the datetime . timedelta in obj . value with an RFC2445 string .
234,903
def transformToNative ( obj ) : if obj . isNative : return obj value = getattr ( obj , 'value_param' , 'DURATION' ) . upper ( ) if hasattr ( obj , 'value_param' ) : del obj . value_param if obj . value == '' : obj . isNative = True return obj elif value == 'DURATION' : try : return Duration . transformToNative ( obj ) ...
Turn obj . value into a timedelta or datetime .
234,904
def transformToNative ( obj ) : if obj . isNative : return obj obj . isNative = True if obj . value == '' : obj . value = [ ] return obj tzinfo = getTzid ( getattr ( obj , 'tzid_param' , None ) ) obj . value = [ stringToPeriod ( x , tzinfo ) for x in obj . value . split ( "," ) ] return obj
Convert comma separated periods into tuples .
234,905
def transformFromNative ( cls , obj ) : if obj . isNative : obj . isNative = False transformed = [ ] for tup in obj . value : transformed . append ( periodToString ( tup , cls . forceUTC ) ) if len ( transformed ) > 0 : tzid = TimezoneComponent . registerTzinfo ( tup [ 0 ] . tzinfo ) if not cls . forceUTC and tzid is n...
Convert the list of tuples in obj . value to strings .
234,906
def serializeFields ( obj , order = None ) : fields = [ ] if order is None : fields = [ backslashEscape ( val ) for val in obj ] else : for field in order : escapedValueList = [ backslashEscape ( val ) for val in toList ( getattr ( obj , field ) ) ] fields . append ( ',' . join ( escapedValueList ) ) return ';' . join ...
Turn an object s fields into a ; and seperated string .
234,907
def toString ( val , join_char = '\n' ) : if type ( val ) in ( list , tuple ) : return join_char . join ( val ) return val
Turn a string or array value into a string .
234,908
def transformToNative ( obj ) : if obj . isNative : return obj obj . isNative = True obj . value = Name ( ** dict ( zip ( NAME_ORDER , splitFields ( obj . value ) ) ) ) return obj
Turn obj . value into a Name .
234,909
def transformFromNative ( obj ) : obj . isNative = False obj . value = serializeFields ( obj . value , NAME_ORDER ) return obj
Replace the Name in obj . value with a string .
234,910
def transformToNative ( obj ) : if obj . isNative : return obj obj . isNative = True obj . value = Address ( ** dict ( zip ( ADDRESS_ORDER , splitFields ( obj . value ) ) ) ) return obj
Turn obj . value into an Address .
234,911
def transformToNative ( obj ) : if obj . isNative : return obj obj . isNative = True obj . value = splitFields ( obj . value ) return obj
Turn obj . value into a list .
234,912
def decode ( cls , line ) : if line . encoded : if 'BASE64' in line . singletonparams : line . singletonparams . remove ( 'BASE64' ) line . encoding_param = cls . base64string encoding = getattr ( line , 'encoding_param' , None ) if encoding : line . value = codecs . decode ( line . value . encode ( "utf-8" ) , "base64...
Remove backslash escaping from line . valueDecode line either to remove backslash espacing or to decode base64 encoding . The content line should contain a ENCODING = b for base64 encoding but Apple Addressbook seems to export a singleton parameter of BASE64 which does not match the 3 . 0 vCard spec . If we encouter th...
234,913
def validate ( cls , obj , raiseException = False , complainUnrecognized = False ) : if not cls . allowGroup and obj . group is not None : err = "{0} has a group, but this object doesn't support groups" . format ( obj ) raise base . VObjectError ( err ) if isinstance ( obj , base . ContentLine ) : return cls . lineVali...
Check if the object satisfies this behavior s requirements .
234,914
def pickNthWeekday ( year , month , dayofweek , hour , minute , whichweek ) : first = datetime . datetime ( year = year , month = month , hour = hour , minute = minute , day = 1 ) weekdayone = first . replace ( day = ( ( dayofweek - first . isoweekday ( ) ) % 7 + 1 ) ) for n in xrange ( whichweek - 1 , - 1 , - 1 ) : dt...
dayofweek == 0 means Sunday whichweek > 4 means last instance
234,915
def deleteExtraneous ( component , ignore_dtstamp = False ) : for comp in component . components ( ) : deleteExtraneous ( comp , ignore_dtstamp ) for line in component . lines ( ) : if 'X-VOBJ-ORIGINAL-TZID' in line . params : del line . params [ 'X-VOBJ-ORIGINAL-TZID' ] if ignore_dtstamp and hasattr ( component , 'dts...
Recursively walk the component s children deleting extraneous details like X - VOBJ - ORIGINAL - TZID .
234,916
def fillPelicanHole ( site , username , password , tstat_name , start_time , end_time ) : start = datetime . strptime ( start_time , _INPUT_TIME_FORMAT ) . replace ( tzinfo = pytz . utc ) . astimezone ( _pelican_time ) end = datetime . strptime ( end_time , _INPUT_TIME_FORMAT ) . replace ( tzinfo = pytz . utc ) . astim...
Fill a hole in a Pelican thermostat s data stream .
234,917
def add_degree_days ( self , col = 'OAT' , hdh_cpoint = 65 , cdh_cpoint = 65 ) : if self . preprocessed_data . empty : data = self . original_data else : data = self . preprocessed_data data [ 'hdh' ] = data [ col ] over_hdh = data . loc [ : , col ] > hdh_cpoint data . loc [ over_hdh , 'hdh' ] = 0 data . loc [ ~ over_h...
Adds Heating & Cooling Degree Hours .
234,918
def add_col_features ( self , col = None , degree = None ) : if not col and not degree : return else : if isinstance ( col , list ) and isinstance ( degree , list ) : if len ( col ) != len ( degree ) : print ( 'col len: ' , len ( col ) ) print ( 'degree len: ' , len ( degree ) ) raise ValueError ( 'col and degree shoul...
Exponentiate columns of dataframe .
234,919
def standardize ( self ) : if self . preprocessed_data . empty : data = self . original_data else : data = self . preprocessed_data scaler = preprocessing . StandardScaler ( ) data = pd . DataFrame ( scaler . fit_transform ( data ) , columns = data . columns , index = data . index ) self . preprocessed_data = data
Standardize data .
234,920
def normalize ( self ) : if self . preprocessed_data . empty : data = self . original_data else : data = self . preprocessed_data data = pd . DataFrame ( preprocessing . normalize ( data ) , columns = data . columns , index = data . index ) self . preprocessed_data = data
Normalize data .
234,921
def add_time_features ( self , year = False , month = False , week = True , tod = True , dow = True ) : var_to_expand = [ ] if self . preprocessed_data . empty : data = self . original_data else : data = self . preprocessed_data if year : data [ "year" ] = data . index . year var_to_expand . append ( "year" ) if month ...
Add time features to dataframe .
234,922
def split_data ( self ) : try : time_period1 = ( slice ( self . baseline_period [ 0 ] , self . baseline_period [ 1 ] ) ) self . baseline_in = self . original_data . loc [ time_period1 , self . input_col ] self . baseline_out = self . original_data . loc [ time_period1 , self . output_col ] if self . exclude_time_period...
Split data according to baseline and projection time period values .
234,923
def linear_regression ( self ) : model = LinearRegression ( ) scores = [ ] kfold = KFold ( n_splits = self . cv , shuffle = True , random_state = 42 ) for i , ( train , test ) in enumerate ( kfold . split ( self . baseline_in , self . baseline_out ) ) : model . fit ( self . baseline_in . iloc [ train ] , self . baselin...
Linear Regression .
234,924
def lasso_regression ( self ) : score_list = [ ] max_score = float ( '-inf' ) best_alpha = None for alpha in self . alphas : model = Lasso ( alpha = alpha , max_iter = 5000 ) model . fit ( self . baseline_in , self . baseline_out . values . ravel ( ) ) scores = [ ] kfold = KFold ( n_splits = self . cv , shuffle = True ...
Lasso Regression .
234,925
def random_forest ( self ) : model = RandomForestRegressor ( random_state = 42 ) scores = [ ] kfold = KFold ( n_splits = self . cv , shuffle = True , random_state = 42 ) for i , ( train , test ) in enumerate ( kfold . split ( self . baseline_in , self . baseline_out ) ) : model . fit ( self . baseline_in . iloc [ train...
Random Forest .
234,926
def run_models ( self ) : self . linear_regression ( ) self . lasso_regression ( ) self . ridge_regression ( ) self . elastic_net_regression ( ) self . random_forest ( ) self . ann ( ) best_model_index = self . max_scores . index ( max ( self . max_scores ) ) self . best_model_name = self . model_names [ best_model_ind...
Run all models .
234,927
def custom_model ( self , func ) : y_pred = func ( self . baseline_in , self . baseline_out ) self . custom_metrics = { } self . custom_metrics [ 'r2' ] = r2_score ( self . baseline_out , y_pred ) self . custom_metrics [ 'mse' ] = mean_squared_error ( self . baseline_out , y_pred ) self . custom_metrics [ 'rmse' ] = ma...
Run custom model provided by user .
234,928
def best_model_fit ( self ) : self . best_model . fit ( self . baseline_in , self . baseline_out ) self . y_true = self . baseline_out self . y_pred = self . best_model . predict ( self . baseline_in ) self . y_pred [ self . y_pred < 0 ] = 0 self . n_test = self . baseline_in . shape [ 0 ] self . k_test = self . baseli...
Fit data to optimal model and return its metrics .
234,929
def correlation_plot ( self , data ) : fig = plt . figure ( Plot_Data . count ) corr = data . corr ( ) ax = sns . heatmap ( corr ) Plot_Data . count += 1 return fig
Create heatmap of Pearson s correlation coefficient .
234,930
def baseline_projection_plot ( self , y_true , y_pred , baseline_period , projection_period , model_name , adj_r2 , data , input_col , output_col , model , site ) : fig = plt . figure ( Plot_Data . count ) if projection_period : nrows = len ( baseline_period ) + len ( projection_period ) / 2 else : nrows = len ( baseli...
Create baseline and projection plots .
234,931
def get_thermostat_meter_data ( zone ) : meter_uri = zone2meter . get ( zone , "None" ) data = [ ] def cb ( msg ) : for po in msg . payload_objects : if po . type_dotted == ( 2 , 0 , 9 , 1 ) : m = msgpack . unpackb ( po . content ) data . append ( m [ 'current_demand' ] ) handle = c . subscribe ( meter_uri + "/signal/m...
This method subscribes to the output of the meter for the given zone . It returns a handler to call when you want to stop subscribing data which returns a list of the data readins over that time period
234,932
def call_heat ( tstat ) : current_hsp , current_csp = tstat . heating_setpoint , tstat . cooling_setpoint current_temp = tstat . temperature tstat . write ( { 'heating_setpoint' : current_temp + 10 , 'cooling_setpoint' : current_temp + 20 , 'mode' : HEAT , } ) def restore ( ) : tstat . write ( { 'heating_setpoint' : cu...
Adjusts the temperature setpoints in order to call for heating . Returns a handler to call when you want to reset the thermostat
234,933
def call_cool ( tstat ) : current_hsp , current_csp = tstat . heating_setpoint , tstat . cooling_setpoint current_temp = tstat . temperature tstat . write ( { 'heating_setpoint' : current_temp - 20 , 'cooling_setpoint' : current_temp - 10 , 'mode' : COOL , } ) def restore ( ) : tstat . write ( { 'heating_setpoint' : cu...
Adjusts the temperature setpoints in order to call for cooling . Returns a handler to call when you want to reset the thermostat
234,934
def call_fan ( tstat ) : old_fan = tstat . fan tstat . write ( { 'fan' : not old_fan , } ) def restore ( ) : tstat . write ( { 'fan' : old_fan , } ) return restore
Toggles the fan
234,935
def _load_csv ( self , file_name , folder_name , head_row , index_col , convert_col , concat_files ) : if file_name == "*" : if not os . path . isdir ( folder_name ) : raise OSError ( 'Folder does not exist.' ) else : file_name_list = sorted ( glob . glob ( folder_name + '*.csv' ) ) if not file_name_list : raise OSErro...
Load single csv file .
234,936
def convert_to_utc ( time ) : if 'Z' in time : return time else : time_formatted = time [ : - 3 ] + time [ - 2 : ] dt = datetime . strptime ( time_formatted , '%Y-%m-%dT%H:%M:%S%z' ) dt = dt . astimezone ( timezone ( 'UTC' ) ) return dt . strftime ( '%Y-%m-%dT%H:%M:%SZ' )
Convert time to UTC
234,937
def get_meter ( self , site , start , end , point_type = 'Green_Button_Meter' , var = "meter" , agg = 'MEAN' , window = '24h' , aligned = True , return_names = True ) : start = self . convert_to_utc ( start ) end = self . convert_to_utc ( end ) request = self . compose_MDAL_dic ( point_type = point_type , site = site ,...
Get meter data from MDAL .
234,938
def get_tstat ( self , site , start , end , var = "tstat_temp" , agg = 'MEAN' , window = '24h' , aligned = True , return_names = True ) : start = self . convert_to_utc ( start ) end = self . convert_to_utc ( end ) point_map = { "tstat_state" : "Thermostat_Status" , "tstat_hsp" : "Supply_Air_Temperature_Heating_Setpoint...
Get thermostat data from MDAL .
234,939
def compose_MDAL_dic ( self , site , point_type , start , end , var , agg , window , aligned , points = None , return_names = False ) : start = self . convert_to_utc ( start ) end = self . convert_to_utc ( end ) request = { } request [ 'Time' ] = { 'Start' : start , 'End' : end , 'Window' : window , 'Aligned' : aligned...
Create dictionary for MDAL request .
234,940
def get_point_name ( self , context ) : metadata_table = self . parse_context ( context ) return metadata_table . apply ( self . strip_point_name , axis = 1 )
Get point name .
234,941
def replace_uuid_w_names ( self , resp ) : col_mapper = self . get_point_name ( resp . context ) [ "?point" ] . to_dict ( ) resp . df . rename ( columns = col_mapper , inplace = True ) return resp
Replace the uuid s with names .
234,942
def resample_data ( self , data , freq , resampler = 'mean' ) : if resampler == 'mean' : data = data . resample ( freq ) . mean ( ) elif resampler == 'max' : data = data . resample ( freq ) . max ( ) else : raise ValueError ( 'Resampler can be \'mean\' or \'max\' only.' ) return data
Resample dataframe .
234,943
def interpolate_data ( self , data , limit , method ) : data = data . interpolate ( how = "index" , limit = limit , method = method ) return data
Interpolate dataframe .
234,944
def remove_na ( self , data , remove_na_how ) : data = data . dropna ( how = remove_na_how ) return data
Remove NAs from dataframe .
234,945
def remove_outlier ( self , data , sd_val ) : data = data . dropna ( ) data = data [ ( np . abs ( stats . zscore ( data ) ) < float ( sd_val ) ) . all ( axis = 1 ) ] return data
Remove outliers from dataframe .
234,946
def remove_out_of_bounds ( self , data , low_bound , high_bound ) : data = data . dropna ( ) data = data [ ( data > low_bound ) . all ( axis = 1 ) & ( data < high_bound ) . all ( axis = 1 ) ] return data
Remove out of bound datapoints from dataframe .
234,947
def _set_TS_index ( self , data ) : data . index = pd . to_datetime ( data . index , error = "ignore" ) for col in data . columns : data [ col ] = pd . to_numeric ( data [ col ] , errors = "coerce" ) return data
Convert index to datetime and all other columns to numeric
234,948
def _utc_to_local ( self , data , local_zone = "America/Los_Angeles" ) : data . index = data . index . tz_localize ( pytz . utc ) . tz_convert ( local_zone ) data . index = data . index . tz_localize ( None ) return data
Adjust index of dataframe according to timezone that is requested by user .
234,949
def _local_to_utc ( self , timestamp , local_zone = "America/Los_Angeles" ) : timestamp_new = pd . to_datetime ( timestamp , infer_datetime_format = True , errors = 'coerce' ) timestamp_new = timestamp_new . tz_localize ( local_zone ) . tz_convert ( pytz . utc ) timestamp_new = timestamp_new . strftime ( '%Y-%m-%d %H:%...
Convert local timestamp to UTC .
234,950
def find_uuid ( self , obj , column_name ) : keys = obj . context . keys ( ) for i in keys : if column_name in obj . context [ i ] [ '?point' ] : uuid = i return i
Find uuid .
234,951
def identify_missing ( self , df , check_start = True ) : data_missing = df . isnull ( ) * 1 col_name = str ( data_missing . columns [ 0 ] ) if check_start & data_missing [ col_name ] [ 0 ] == 1 : data_missing [ col_name ] [ 0 ] = 0 return data_missing , col_name
Identify missing data .
234,952
def diff_boolean ( self , df , column_name = None , uuid = None , duration = True , min_event_filter = '3 hours' ) : if uuid == None : uuid = 'End' data_gaps = df [ ( df . diff ( ) == 1 ) | ( df . diff ( ) == - 1 ) ] . dropna ( ) data_gaps [ "duration" ] = abs ( data_gaps . index . to_series ( ) . diff ( periods = - 1 ...
takes the dataframe of missing values and returns a dataframe that indicates the length of each event where data was continuously missing
234,953
def analyze_quality_table ( self , obj , low_bound = None , high_bound = None ) : data = obj . df N_rows = 3 N_cols = data . shape [ 1 ] d = pd . DataFrame ( np . zeros ( ( N_rows , N_cols ) ) , index = [ '% Missing' , 'AVG Length Missing' , 'Std dev. Missing' ] , columns = [ data . columns ] ) if low_bound : data = da...
Takes in an the object returned by the MDAL query and analyzes the quality of the data for each column in the df . Returns a df of data quality metrics
234,954
def analyze_quality_graph ( self , obj ) : data = obj . df for i in range ( data . shape [ 1 ] ) : data_per_meter = data . iloc [ : , [ i ] ] data_missing , meter = self . identify_missing ( data_per_meter ) percentage = data_missing . sum ( ) / ( data . shape [ 0 ] ) * 100 print ( 'Percentage Missing of ' + meter + ' ...
Takes in an the object returned by the MDAL query and analyzes the quality of the data for each column in the df in the form of graphs . The Graphs returned show missing data events over time and missing data frequency during each hour of the day
234,955
def clean_data ( self , resample = True , freq = 'h' , resampler = 'mean' , interpolate = True , limit = 1 , method = 'linear' , remove_na = True , remove_na_how = 'any' , remove_outliers = True , sd_val = 3 , remove_out_of_bounds = True , low_bound = 0 , high_bound = 9998 ) : data = self . original_data if resample : ...
Clean dataframe .
234,956
def write_json ( self ) : with open ( self . results_folder_name + '/results-' + str ( self . get_global_count ( ) ) + '.json' , 'a' ) as f : json . dump ( self . result , f )
Dump data into json file .
234,957
def site_analysis ( self , folder_name , site_install_mapping , end_date ) : def count_number_of_days ( site , end_date ) : start_date = site_install_mapping [ site ] start_date = start_date . split ( '-' ) start = date ( int ( start_date [ 0 ] ) , int ( start_date [ 1 ] ) , int ( start_date [ 2 ] ) ) end_date = end_da...
Summarize site data into a single table .
234,958
def search ( self , file_name , imported_data = None ) : resample_freq = [ '15T' , 'h' , 'd' ] time_freq = { 'year' : [ True , False , False , False , False ] , 'month' : [ False , True , False , False , False ] , 'week' : [ False , False , True , False , False ] , 'tod' : [ False , False , False , True , False ] , 'do...
Run models on different data configurations .
234,959
def clean_data ( self , data , rename_col = None , drop_col = None , resample = True , freq = 'h' , resampler = 'mean' , interpolate = True , limit = 1 , method = 'linear' , remove_na = True , remove_na_how = 'any' , remove_outliers = True , sd_val = 3 , remove_out_of_bounds = True , low_bound = 0 , high_bound = float ...
Cleans dataframe according to user specifications and stores result in self . cleaned_data .
234,960
def prevmonday ( num ) : today = get_today ( ) lastmonday = today - timedelta ( days = today . weekday ( ) , weeks = num ) return lastmonday
Return unix SECOND timestamp of num mondays ago
234,961
def med_filt ( x , k = 201 ) : if x . ndim > 1 : x = np . squeeze ( x ) med = np . median ( x ) assert k % 2 == 1 , "Median filter length must be odd." assert x . ndim == 1 , "Input must be one-dimensional." k2 = ( k - 1 ) // 2 y = np . zeros ( ( len ( x ) , k ) , dtype = x . dtype ) y [ : , k2 ] = x for i in range ( k...
Apply a length - k median filter to a 1D array x . Boundaries are extended by repeating endpoints .
234,962
def preprocess_data ( self , data , hdh_cpoint = 65 , cdh_cpoint = 65 , col_hdh_cdh = None , col_degree = None , degree = None , standardize = False , normalize = False , year = False , month = False , week = False , tod = False , dow = False , save_file = True ) : if not isinstance ( data , pd . DataFrame ) : raise Sy...
Preprocesses dataframe according to user specifications and stores result in self . preprocessed_data .
234,963
def model ( self , data , ind_col = None , dep_col = None , project_ind_col = None , baseline_period = [ None , None ] , projection_period = None , exclude_time_period = None , alphas = np . logspace ( - 4 , 1 , 30 ) , cv = 3 , plot = True , figsize = None , custom_model_func = None ) : if not isinstance ( data , pd . ...
Split data into baseline and projection periods run models on them and display metrics & plots .
234,964
def make_dataframe ( result ) : import pandas as pd ret = { } if isinstance ( result , dict ) : if 'timeseries' in result : result = result [ 'timeseries' ] for uuid , data in result . items ( ) : df = pd . DataFrame ( data ) if len ( df . columns ) == 5 : df . columns = [ 'time' , 'min' , 'mean' , 'max' , 'count' ] el...
Turns the results of one of the data API calls into a pandas dataframe
234,965
def query ( self , query , archiver = "" , timeout = DEFAULT_TIMEOUT ) : if archiver == "" : archiver = self . archivers [ 0 ] nonce = random . randint ( 0 , 2 ** 32 ) ev = threading . Event ( ) response = { } def _handleresult ( msg ) : got_response = False error = getError ( nonce , msg ) if error is not None : got_r...
Runs the given pundat query and returns the results as a Python object .
234,966
def uuids ( self , where , archiver = "" , timeout = DEFAULT_TIMEOUT ) : resp = self . query ( "select uuid where {0}" . format ( where ) , archiver , timeout ) uuids = [ ] for r in resp [ "metadata" ] : uuids . append ( r [ "uuid" ] ) return uuids
Using the given where - clause finds all UUIDs that match
234,967
def tags ( self , where , archiver = "" , timeout = DEFAULT_TIMEOUT ) : return self . query ( "select * where {0}" . format ( where ) , archiver , timeout ) . get ( 'metadata' , { } )
Retrieves tags for all streams matching the given WHERE clause
234,968
def tags_uuids ( self , uuids , archiver = "" , timeout = DEFAULT_TIMEOUT ) : if not isinstance ( uuids , list ) : uuids = [ uuids ] where = " or " . join ( [ 'uuid = "{0}"' . format ( uuid ) for uuid in uuids ] ) return self . query ( "select * where {0}" . format ( where ) , archiver , timeout ) . get ( 'metadata' , ...
Retrieves tags for all streams with the provided UUIDs
234,969
def data ( self , where , start , end , archiver = "" , timeout = DEFAULT_TIMEOUT ) : return self . query ( "select data in ({0}, {1}) where {2}" . format ( start , end , where ) , archiver , timeout ) . get ( 'timeseries' , { } )
With the given WHERE clause retrieves all RAW data between the 2 given timestamps
234,970
def data_uuids ( self , uuids , start , end , archiver = "" , timeout = DEFAULT_TIMEOUT ) : if not isinstance ( uuids , list ) : uuids = [ uuids ] where = " or " . join ( [ 'uuid = "{0}"' . format ( uuid ) for uuid in uuids ] ) return self . query ( "select data in ({0}, {1}) where {2}" . format ( start , end , where )...
With the given list of UUIDs retrieves all RAW data between the 2 given timestamps
234,971
def stats ( self , where , start , end , pw , archiver = "" , timeout = DEFAULT_TIMEOUT ) : return self . query ( "select statistical({3}) data in ({0}, {1}) where {2}" . format ( start , end , where , pw ) , archiver , timeout ) . get ( 'timeseries' , { } )
With the given WHERE clause retrieves all statistical data between the 2 given timestamps using the given pointwidth
234,972
def window ( self , where , start , end , width , archiver = "" , timeout = DEFAULT_TIMEOUT ) : return self . query ( "select window({3}) data in ({0}, {1}) where {2}" . format ( start , end , where , width ) , archiver , timeout ) . get ( 'timeseries' , { } )
With the given WHERE clause retrieves all statistical data between the 2 given timestamps using the given window size
234,973
def brightness ( self ) : if self . mode == "ww" : return int ( self . raw_state [ 9 ] ) else : _ , _ , v = colorsys . rgb_to_hsv ( * self . getRgb ( ) ) return v
Return current brightness 0 - 255 .
234,974
def decode ( var , encoding ) : if PY2 : if isinstance ( var , unicode ) : ret = var elif isinstance ( var , str ) : if encoding : ret = var . decode ( encoding ) else : ret = unicode ( var ) else : ret = unicode ( var ) else : ret = str ( var ) return ret
If not already unicode decode it .
234,975
def cfitsio_version ( asfloat = False ) : ver = '%0.3f' % _fitsio_wrap . cfitsio_version ( ) if asfloat : return float ( ver ) else : return ver
Return the cfitsio version as a string .
234,976
def is_little_endian ( array ) : if numpy . little_endian : machine_little = True else : machine_little = False byteorder = array . dtype . base . byteorder return ( byteorder == '<' ) or ( machine_little and byteorder == '=' )
Return True if array is little endian False otherwise .
234,977
def array_to_native ( array , inplace = False ) : if numpy . little_endian : machine_little = True else : machine_little = False data_little = False if array . dtype . names is None : if array . dtype . base . byteorder == '|' : return array data_little = is_little_endian ( array ) else : for fname in array . dtype . n...
Convert an array to the native byte order .
234,978
def mks ( val ) : if sys . version_info > ( 3 , 0 , 0 ) : if isinstance ( val , bytes ) : sval = str ( val , 'utf-8' ) else : sval = str ( val ) else : sval = str ( val ) return sval
make sure the value is a string paying mind to python3 vs 2
234,979
def _get_col_dimstr ( tdim , is_string = False ) : dimstr = '' if tdim is None : dimstr = 'array[bad TDIM]' else : if is_string : if len ( tdim ) > 1 : dimstr = [ str ( d ) for d in tdim [ 1 : ] ] else : if len ( tdim ) > 1 or tdim [ 0 ] > 1 : dimstr = [ str ( d ) for d in tdim ] if dimstr != '' : dimstr = ',' . join (...
not for variable length
234,980
def get_colname ( self , colnum ) : if colnum < 0 or colnum > ( len ( self . _colnames ) - 1 ) : raise ValueError ( "colnum out of range [0,%s-1]" % ( 0 , len ( self . _colnames ) ) ) return self . _colnames [ colnum ]
Get the name associated with the given column number
234,981
def write_column ( self , column , data , ** keys ) : firstrow = keys . get ( 'firstrow' , 0 ) colnum = self . _extract_colnum ( column ) if not data . flags [ 'C_CONTIGUOUS' ] : data_send = numpy . ascontiguousarray ( data ) array_to_native ( data_send , inplace = True ) else : data_send = array_to_native ( data , inp...
Write data to a column in this HDU
234,982
def _verify_column_data ( self , colnum , data ) : this_dt = data . dtype . descr [ 0 ] if len ( data . shape ) > 2 : this_shape = data . shape [ 1 : ] elif len ( data . shape ) == 2 and data . shape [ 1 ] > 1 : this_shape = data . shape [ 1 : ] else : this_shape = ( ) this_npy_type = this_dt [ 1 ] [ 1 : ] npy_type , i...
verify the input data is of the correct type and shape
234,983
def write_var_column ( self , column , data , firstrow = 0 , ** keys ) : if not is_object ( data ) : raise ValueError ( "Only object fields can be written to " "variable-length arrays" ) colnum = self . _extract_colnum ( column ) self . _FITS . write_var_column ( self . _ext + 1 , colnum + 1 , data , firstrow = firstro...
Write data to a variable - length column in this HDU
234,984
def insert_column ( self , name , data , colnum = None ) : if name in self . _colnames : raise ValueError ( "column '%s' already exists" % name ) if IS_PY3 and data . dtype . char == 'U' : descr = numpy . empty ( 1 ) . astype ( data . dtype ) . astype ( 'S' ) . dtype . descr else : descr = data . dtype . descr if len (...
Insert a new column .
234,985
def append ( self , data , ** keys ) : firstrow = self . _info [ 'nrows' ] keys [ 'firstrow' ] = firstrow self . write ( data , ** keys )
Append new rows to a table HDU
234,986
def delete_rows ( self , rows ) : if rows is None : return if isinstance ( rows , slice ) : rows = self . _process_slice ( rows ) if rows . step is not None and rows . step != 1 : rows = numpy . arange ( rows . start + 1 , rows . stop + 1 , rows . step , ) else : rows = slice ( rows . start + 1 , rows . stop + 1 ) else...
Delete rows from the table
234,987
def resize ( self , nrows , front = False ) : nrows_current = self . get_nrows ( ) if nrows == nrows_current : return if nrows < nrows_current : rowdiff = nrows_current - nrows if front : start = 0 stop = rowdiff else : start = nrows stop = nrows_current self . delete_rows ( slice ( start , stop ) ) else : rowdiff = nr...
Resize the table to the given size removing or adding rows as necessary . Note if expanding the table at the end it is more efficient to use the append function than resizing and then writing .
234,988
def read ( self , ** keys ) : columns = keys . get ( 'columns' , None ) rows = keys . get ( 'rows' , None ) if columns is not None : if 'columns' in keys : del keys [ 'columns' ] data = self . read_columns ( columns , ** keys ) elif rows is not None : if 'rows' in keys : del keys [ 'rows' ] data = self . read_rows ( ro...
read data from this HDU
234,989
def _read_all ( self , ** keys ) : dtype , offsets , isvar = self . get_rec_dtype ( ** keys ) w , = numpy . where ( isvar == True ) has_tbit = self . _check_tbit ( ) if w . size > 0 : vstorage = keys . get ( 'vstorage' , self . _vstorage ) colnums = self . _extract_colnums ( ) rows = None array = self . _read_rec_with_...
Read all data in the HDU .
234,990
def read_column ( self , col , ** keys ) : res = self . read_columns ( [ col ] , ** keys ) colname = res . dtype . names [ 0 ] data = res [ colname ] self . _maybe_trim_strings ( data , ** keys ) return data
Read the specified column
234,991
def read_rows ( self , rows , ** keys ) : if rows is None : return self . _read_all ( ) if self . _info [ 'hdutype' ] == ASCII_TBL : keys [ 'rows' ] = rows return self . read ( ** keys ) rows = self . _extract_rows ( rows ) dtype , offsets , isvar = self . get_rec_dtype ( ** keys ) w , = numpy . where ( isvar == True )...
Read the specified rows .
234,992
def read_columns ( self , columns , ** keys ) : if self . _info [ 'hdutype' ] == ASCII_TBL : keys [ 'columns' ] = columns return self . read ( ** keys ) rows = keys . get ( 'rows' , None ) colnums = self . _extract_colnums ( columns ) if isinstance ( colnums , int ) : return self . read_column ( columns , ** keys ) row...
read a subset of columns from this binary table HDU
234,993
def read_slice ( self , firstrow , lastrow , step = 1 , ** keys ) : if self . _info [ 'hdutype' ] == ASCII_TBL : rows = numpy . arange ( firstrow , lastrow , step , dtype = 'i8' ) keys [ 'rows' ] = rows return self . read_ascii ( ** keys ) step = keys . get ( 'step' , 1 ) if self . _info [ 'hdutype' ] == IMAGE_HDU : ra...
Read the specified row slice from a table .
234,994
def get_rec_dtype ( self , ** keys ) : colnums = keys . get ( 'colnums' , None ) vstorage = keys . get ( 'vstorage' , self . _vstorage ) if colnums is None : colnums = self . _extract_colnums ( ) descr = [ ] isvararray = numpy . zeros ( len ( colnums ) , dtype = numpy . bool ) for i , colnum in enumerate ( colnums ) : ...
Get the dtype for the specified columns
234,995
def _check_tbit ( self , ** keys ) : colnums = keys . get ( 'colnums' , None ) if colnums is None : colnums = self . _extract_colnums ( ) has_tbit = False for i , colnum in enumerate ( colnums ) : npy_type , isvar , istbit = self . _get_tbl_numpy_dtype ( colnum ) if ( istbit ) : has_tbit = True break return has_tbit
Check if one of the columns is a TBIT column
234,996
def _fix_tbit_dtype ( self , array , colnums ) : descr = array . dtype . descr for i , colnum in enumerate ( colnums ) : npy_type , isvar , istbit = self . _get_tbl_numpy_dtype ( colnum ) if ( istbit ) : coldescr = list ( descr [ i ] ) coldescr [ 1 ] = '?' descr [ i ] = tuple ( coldescr ) return array . view ( descr )
If necessary patch up the TBIT to convert to bool array
234,997
def _get_simple_dtype_and_shape ( self , colnum , rows = None ) : npy_type , isvar , istbit = self . _get_tbl_numpy_dtype ( colnum ) info = self . _info [ 'colinfo' ] [ colnum ] name = info [ 'name' ] if rows is None : nrows = self . _info [ 'nrows' ] else : nrows = rows . size shape = None tdim = info [ 'tdim' ] shape...
When reading a single column we want the basic data type and the shape of the array .
234,998
def get_rec_column_descr ( self , colnum , vstorage ) : npy_type , isvar , istbit = self . _get_tbl_numpy_dtype ( colnum ) name = self . _info [ 'colinfo' ] [ colnum ] [ 'name' ] if isvar : if vstorage == 'object' : descr = ( name , 'O' ) else : tform = self . _info [ 'colinfo' ] [ colnum ] [ 'tform' ] max_size = _extr...
Get a descriptor entry for the specified column .
234,999
def _read_rec_with_var ( self , colnums , rows , dtype , offsets , isvar , vstorage ) : colnumsp = colnums + 1 if rows is None : nrows = self . _info [ 'nrows' ] else : nrows = rows . size array = numpy . zeros ( nrows , dtype = dtype ) wnotvar , = numpy . where ( isvar == False ) if wnotvar . size > 0 : thesecol = col...
Read columns from a table into a rec array including variable length columns . This is special because for efficiency it involves reading from the main table as normal but skipping the columns in the array that are variable . Then reading the variable length columns with accounting for strides appropriately .