code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def filter_keys(cls, data): keys = list(data.keys()) for pattern in cls.EXCLUDE_PATTERNS: for key in keys: if re.match(pattern, key): keys.remove(key) return dict(filter(lambda x: x[0] in keys, data.items()))
Filter GELF record keys using exclude_patterns :param dict data: Log record has dict :return: the filtered log record :rtype: dict
def write_config(self): json.dump( self.config, open(CONFIG_FILE, 'w'), indent=4, separators=(',', ': ') ) return True
Write the configuration to a local file. :return: Boolean if successful
def load_config(self, **kwargs): virgin_config = False if not os.path.exists(CONFIG_PATH): virgin_config = True os.makedirs(CONFIG_PATH) if not os.path.exists(CONFIG_FILE): virgin_config = True if not virgin_config: self.config = json.load(open(CONFIG_FILE)) else: self.logger.info('[!] Processing whitelists, this may take a few minutes...') process_whitelists() if kwargs: self.config.update(kwargs) if virgin_config or kwargs: self.write_config() if 'api_key' not in self.config: sys.stderr.write('configuration missing API key\n') if 'email' not in self.config: sys.stderr.write('configuration missing email\n') if not ('api_key' in self.config and 'email' in self.config): sys.stderr.write('Errors have been reported. Run blockade-cfg ' 'to fix these warnings.\n') try: last_update = datetime.strptime(self.config['whitelist_date'], "%Y-%m-%d") current = datetime.now() delta = (current - last_update).days if delta > 14: self.logger.info('[!] Refreshing whitelists, this may take a few minutes...') process_whitelists() self.config['whitelist_date'] = datetime.now().strftime("%Y-%m-%d") self.write_config() except Exception as e: self.logger.error(str(e)) self.logger.info('[!] Processing whitelists, this may take a few minutes...') process_whitelists() self.config['whitelist_date'] = datetime.now().strftime("%Y-%m-%d") self.write_config() return True
Load the configuration for the user or seed it with defaults. :return: Boolean if successful
def create_table_rate_rule(cls, table_rate_rule, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_table_rate_rule_with_http_info(table_rate_rule, **kwargs) else: (data) = cls._create_table_rate_rule_with_http_info(table_rate_rule, **kwargs) return data
Create TableRateRule Create a new TableRateRule This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_table_rate_rule(table_rate_rule, async=True) >>> result = thread.get() :param async bool :param TableRateRule table_rate_rule: Attributes of tableRateRule to create (required) :return: TableRateRule If the method is called asynchronously, returns the request thread.
def delete_table_rate_rule_by_id(cls, table_rate_rule_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_table_rate_rule_by_id_with_http_info(table_rate_rule_id, **kwargs) else: (data) = cls._delete_table_rate_rule_by_id_with_http_info(table_rate_rule_id, **kwargs) return data
Delete TableRateRule Delete an instance of TableRateRule by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_table_rate_rule_by_id(table_rate_rule_id, async=True) >>> result = thread.get() :param async bool :param str table_rate_rule_id: ID of tableRateRule to delete. (required) :return: None If the method is called asynchronously, returns the request thread.
def get_table_rate_rule_by_id(cls, table_rate_rule_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_table_rate_rule_by_id_with_http_info(table_rate_rule_id, **kwargs) else: (data) = cls._get_table_rate_rule_by_id_with_http_info(table_rate_rule_id, **kwargs) return data
Find TableRateRule Return single instance of TableRateRule by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_table_rate_rule_by_id(table_rate_rule_id, async=True) >>> result = thread.get() :param async bool :param str table_rate_rule_id: ID of tableRateRule to return (required) :return: TableRateRule If the method is called asynchronously, returns the request thread.
def list_all_table_rate_rules(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_table_rate_rules_with_http_info(**kwargs) else: (data) = cls._list_all_table_rate_rules_with_http_info(**kwargs) return data
List TableRateRules Return a list of TableRateRules This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_table_rate_rules(async=True) >>> result = thread.get() :param async bool :param int page: page number :param int size: page size :param str sort: page order :return: page[TableRateRule] If the method is called asynchronously, returns the request thread.
def replace_table_rate_rule_by_id(cls, table_rate_rule_id, table_rate_rule, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_table_rate_rule_by_id_with_http_info(table_rate_rule_id, table_rate_rule, **kwargs) else: (data) = cls._replace_table_rate_rule_by_id_with_http_info(table_rate_rule_id, table_rate_rule, **kwargs) return data
Replace TableRateRule Replace all attributes of TableRateRule This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_table_rate_rule_by_id(table_rate_rule_id, table_rate_rule, async=True) >>> result = thread.get() :param async bool :param str table_rate_rule_id: ID of tableRateRule to replace (required) :param TableRateRule table_rate_rule: Attributes of tableRateRule to replace (required) :return: TableRateRule If the method is called asynchronously, returns the request thread.
def update_table_rate_rule_by_id(cls, table_rate_rule_id, table_rate_rule, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_table_rate_rule_by_id_with_http_info(table_rate_rule_id, table_rate_rule, **kwargs) else: (data) = cls._update_table_rate_rule_by_id_with_http_info(table_rate_rule_id, table_rate_rule, **kwargs) return data
Update TableRateRule Update attributes of TableRateRule This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_table_rate_rule_by_id(table_rate_rule_id, table_rate_rule, async=True) >>> result = thread.get() :param async bool :param str table_rate_rule_id: ID of tableRateRule to update. (required) :param TableRateRule table_rate_rule: Attributes of tableRateRule to update. (required) :return: TableRateRule If the method is called asynchronously, returns the request thread.
def _update_fobj(self): # print("PPPPPPPPPPPPPPPPPPPRINTANDO O STACK") # traceback.print_stack() emsg, flag_error = "", False fieldname = None try: self._before_update_fobj() for item in self._map: self._f.obj[item.fieldname] = item.get_value() self._after_update_fobj() except Exception as E: flag_error = True if fieldname is not None: emsg = "Field '{}': {}".format(fieldname, str(E)) else: emsg = str(E) self.add_log_error(emsg) self._flag_valid = not flag_error if not flag_error: self.status("")
Updates fobj from GUI. Opposite of _update_gui().
def colname_gen(df,col_name = 'unnamed_col'): if col_name not in df.keys(): yield col_name id_number = 0 while True: col_name = col_name + str(id_number) if col_name in df.keys(): id_number+=1 else: return col_name
Returns a column name that isn't in the specified DataFrame Parameters: df - DataFrame DataFrame to analyze col_name - string, default 'unnamed_col' Column name to use as the base value for the generated column name
def clean_colnames(df): col_list = [] for index in range(_dutils.cols(df)): col_list.append(df.columns[index].strip().lower().replace(' ','_')) df.columns = col_list
Cleans the column names on a DataFrame Parameters: df - DataFrame The DataFrame to clean
def col_strip(df,col_name,dest = False): if dest: df[col_name] = df[col_name].str.strip() else: return df[col_name].str.strip()
Performs str.strip() a column of a DataFrame Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to strip dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
def col_scrubf(df,col_name,which,count = 1,dest = False): if dest: df.loc[which,col_name] = df.loc[which,col_name].str[count:] else: new_col = df[col_name].copy() new_col[which] = df.loc[which,col_name].str[count:] return new_col
Removes characters from the front of the entries in DataFrame for a column Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to scrub which - boolean array Boolean array that determines which elements to scrub, where True means scrub count - integer, default 1 amount of characters to scrub dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
def col_to_numeric(df,col_name, dest = False): new_col = _pd.to_numeric(df[col_name], errors = 'coerce') if dest: set_col(df,col_name,new_col) else: return new_col
Coerces a column in a DataFrame to numeric Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to coerce dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
def col_to_dt(df,col_name,set_format = None,infer_format = True, dest = False): new_col = _pd.to_datetime(df[col_name],errors = 'coerce', format = set_format,infer_datetime_format = infer_format) if dest: set_col(df,col_name,new_col) else: return new_col
Coerces a column in a DataFrame to datetime Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to coerce dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
def col_to_cat(df,col_name, dest = False): new_col = df[col_name].astype('category') if dest: set_col(df,col_name,new_col) else: return new_col
Coerces a column in a DataFrame to categorical Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to coerce dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
def col_rename(df,col_name,new_col_name): col_list = list(df.columns) for index,value in enumerate(col_list): if value == col_name: col_list[index] = new_col_name break df.columns = col_list
Changes a column name in a DataFrame Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to change new_col_name - string New name of column
def col_mod(df,col_name,func,*args,**kwargs): backup = df[col_name].copy() try: return_val = func(df,col_name,*args,**kwargs) if return_val is not None: set_col(df,col_name,return_val) except: df[col_name] = backup
Changes a column of a DataFrame according to a given function Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to modify func - function The function to use to modify the column
def cols_strip(df,col_list, dest = False): if not dest: return _pd.DataFrame({col_name:col_strip(df,col_name) for col_name in col_list}) for col_name in col_list: col_strip(df,col_name,dest)
Performs str.strip() a column of a DataFrame Parameters: df - DataFrame DataFrame to operate on col_list - list of strings names of columns to strip dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
def cols_to_numeric(df, col_list,dest = False): if not dest: return _pd.DataFrame({col_name:col_to_numeric(df,col_name) for col_name in col_list}) for col_name in col_list: col_to_numeric(df,col_name,dest)
Coerces a list of columns to numeric Parameters: df - DataFrame DataFrame to operate on col_list - list of strings names of columns to coerce dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
def cols_to_dt(df, col_list,set_format = None,infer_format = True,dest = False): if not dest: return _pd.DataFrame({col_name:col_to_dt(df,col_name,set_format,infer_format) for col_name in col_list}) for col_name in col_list: col_to_dt(df,col_name,set_format,infer_format,dest)
Coerces a list of columns to datetime Parameters: df - DataFrame DataFrame to operate on col_list - list of strings names of columns to coerce dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
def cols_to_cat(df, col_list,dest = False): # Convert a list of columns to categorical if not dest: return _pd.DataFrame({col_name:col_to_cat(df,col_name) for col_name in col_list}) for col_name in col_list: col_to_cat(df,col_name,dest)
Coerces a list of columns to categorical Parameters: df - DataFrame DataFrame to operate on col_list - list of strings names of columns to coerce dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
def cols_(df,col_list,func,*args,**kwargs): return _pd.DataFrame({col_name:func(df,col_name,*args,**kwargs) for col_name in col_list})
Do a function over a list of columns and return the result Parameters: df - DataFrame DataFrame to operate on col_list - list of strings names of columns to coerce func - function function to use
def cols_rename(df,col_names, new_col_names): assert len(col_names) == len(new_col_names) for old_name,new_name in zip(col_names,new_col_names): col_rename(df,old_name,new_name)
Rename a set of columns in a DataFrame Parameters: df - DataFrame DataFrame to operate on col_names - list of strings names of columns to change new_col_names - list of strings new names for old columns (order should be same as col_names)
def col_dtypes(df): # Does some work to reduce possibility of errors and stuff test_list = [col_isobj,col_isnum,col_isbool,col_isdt,col_iscat,col_istdelt,col_isdtz] deque_list = [(deque(col_method(df)),name) \ for col_method,name in zip(test_list,_globals.__dtype_names) if len(col_method(df))] type_dict = {} for que, name in deque_list: while len(que): type_dict[que.popleft()] = name return type_dict
Returns dictionary of datatypes in a DataFrame (uses string representation) Parameters: df - DataFrame The DataFrame to return the object types of Pandas datatypes are as follows: object,number,bool,datetime,category,timedelta,datetimetz This method uses queues and iterates over the columns in linear time. It does extra steps to ensure that no further work with numpy datatypes needs to be done.
def col_isobj(df, col_name = None): col_list = df.select_dtypes(include = 'object').columns if col_name is None: return col_list else: return col_name in col_list
Returns a list of columns that are of type object. If col_name is specified, returns whether the column in the DataFrame is of type 'object' instead. Parameters: df - DataFrame DataFrame to check col_name - string, default None If specified, this function will True if df[col_name] is of type 'object'
def col_isnum(df,col_name = None): col_list = df.select_dtypes(include = 'number').columns if col_name is None: return col_list else: return col_name in col_list
Returns a list of columns that are of type 'number'. If col_name is specified, returns whether the column in the DataFrame is of type 'number' instead. Parameters: df - DataFrame DataFrame to check col_name - string, default None If specified, this function will True if df[col_name] is of type 'number'
def col_isbool(df,col_name = None): col_list = df.select_dtypes(include = 'bool').columns if col_name is None: return col_list else: return col_name in col_list
Returns a list of columns that are of type 'bool'. If col_name is specified, returns whether the column in the DataFrame is of type 'bool' instead. Parameters: df - DataFrame DataFrame to check col_name - string, default None If specified, this function will True if df[col_name] is of type 'bool'
def col_isdt(df,col_name = None): col_list = df.select_dtypes(include = 'datetime').columns if col_name is None: return col_list else: return col_name in col_list
Returns a list of columns that are of type 'datetime'. If col_name is specified, returns whether the column in the DataFrame is of type 'datetime' instead. Parameters: df - DataFrame DataFrame to check col_name - string, default None If specified, this function will True if df[col_name] is of type 'datetime'
def col_iscat(df,col_name = None): col_list = df.select_dtypes(include = 'category').columns if col_name is None: return col_list else: return col_name in col_list
Returns a list of columns that are of type 'category'. If col_name is specified, returns whether the column in the DataFrame is of type 'category' instead. Parameters: df - DataFrame DataFrame to check col_name - string, default None If specified, this function will True if df[col_name] is of type 'category'
def col_istdelt(df,col_name = None): col_list = df.select_dtypes(include = 'timedelta').columns if col_name is None: return col_list else: return col_name in col_list
Returns a list of columns that are of type 'timedelta'. If col_name is specified, returns whether the column in the DataFrame is of type 'timedelta' instead. Parameters: df - DataFrame DataFrame to check col_name - string, default None If specified, this function will True if df[col_name] is of type 'timedelta'
def col_isdtz(df,col_name = None): col_list = df.select_dtypes(include = 'datetimetz').columns if col_name is None: return col_list else: return col_name in col_list
Returns a list of columns that are of type 'datetimetz'. If col_name is specified, returns whether the column in the DataFrame is of type 'datetimetz' instead. Parameters: df - DataFrame DataFrame to check col_name - string, default None If specified, this function will True if df[col_name] is of type 'datetimetz'
def set_query_on_table_metaclass(model: object, session: Session): if not hasattr(model, "query"): model.query = session.query(model)
Ensures that the given database model (`DeclarativeMeta`) has a `query` property through which the user can easily query the corresponding database table. Database object models derived from Flask-SQLAlchemy's `database.Model` have this property set up by default, but when using SQLAlchemy, this may not be the case. In this method this problem we fix. Argumentss: model (DeclarativeMeta): The database model object whose `query` property should be set up if it's not set up already. session (Session): The session to use to set up the `query` property on `model`.
def get_feature_model(): try: return apps.get_model(flipper_settings.FEATURE_FLIPPER_MODEL) except ValueError: raise ImproperlyConfigured( "FEATURE_FLIPPER_MODEL must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "FEATURE_FLIPPER_MODEL refers to model '{}' that has not been" " installed".format(flipper_settings.FEATURE_FLIPPER_MODEL))
Return the FeatureFlipper model defined in settings.py
def show_feature(self, user, feature): user_filter = { self.model.USER_FEATURE_FIELD: user, } return self.get_feature(feature).filter( models.Q(**user_filter) | models.Q(everyone=True)).exists()
Return True or False for the given feature.
def solve_loop(slsp, u_span, j_coup): zet, lam, eps, hlog, mean_f = [], [], [], [], [None] for u in u_span: print(u, j_coup) hlog.append(slsp.selfconsistency(u, j_coup, mean_f[-1])) mean_f.append(slsp.mean_field()) zet.append(slsp.quasiparticle_weight()) lam.append(slsp.param['lambda']) eps.append(orbital_energies(slsp.param, zet[-1])) return np.asarray([zet, lam, eps]), hlog, mean_f
Calculates the quasiparticle for the input loop of: @param slsp: Slave spin Object @param Uspan: local Couloumb interation @param J_coup: Fraction of Uspan of Hund coupling strength
def calc_z(bands, filling, interaction, hund_cu, name): while True: try: data = np.load(name+'.npz') break except IOError: dopout = [] for dop in filling: slsp = Spinon(slaves=2*bands, orbitals=bands, \ hopping=[0.5]*2*bands, populations=[dop]*2*bands) dopout.append(solve_loop(slsp, interaction, hund_cu)[0][0]) np.savez(name, zeta=dopout, u_int=interaction, doping=filling, hund=hund_cu) return data
Calculates the quasiparticle weight of degenerate system of N-bands at a given filling within an interaction range and saves the file
def label_saves(name): plt.legend(loc=0) plt.ylim([0, 1.025]) plt.xlabel('$U/D$', fontsize=20) plt.ylabel('$Z$', fontsize=20) plt.savefig(name, dpi=300, format='png', transparent=False, bbox_inches='tight', pad_inches=0.05)
Labels plots and saves file
def plot_curves_z(data, name, title=None): plt.figure() for zet, c in zip(data['zeta'], data['doping']): plt.plot(data['u_int'], zet[:, 0], label='$n={}$'.format(str(c))) if title != None: plt.title(title) label_saves(name+'.png')
Generates a simple plot of the quasiparticle weight decay curves given data object with doping setup
def pick_flat_z(data): zmes = [] for i in data['zeta']: zmes.append(i[:, 0]) return np.asarray(zmes)
Generate a 2D array of the quasiparticle weight by only selecting the first particle data
def imshow_z(data, name): zmes = pick_flat_z(data) plt.figure() plt.imshow(zmes.T, origin='lower', \ extent=[data['doping'].min(), data['doping'].max(), \ 0, data['u_int'].max()], aspect=.16) plt.colorbar() plt.xlabel('$n$', fontsize=20) plt.ylabel('$U/D$', fontsize=20) plt.savefig(name+'_imshow.png', dpi=300, format='png', transparent=False, bbox_inches='tight', pad_inches=0.05)
2D color plot of the quasiparticle weight as a function of interaction and doping
def surf_z(data, name): from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter fig = plt.figure() ax = fig.gca(projection='3d') dop, u_int = np.meshgrid(data['doping'], data['u_int']) zmes = pick_flat_z(data) ax.plot_surface(u_int, dop, zmes.T, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.contourf(u_int, dop, zmes.T, zdir='z', offset=0, cmap=cm.coolwarm) ax.set_zlim(0, 1) ax.view_init(elev=11, azim=-34) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) ax.set_xlabel('$U/D$', fontsize=20) ax.set_ylabel('$n$', fontsize=20) ax.set_zlabel('$Z$', fontsize=20) plt.savefig(name+'_surf.png', dpi=300, format='png', transparent=False, bbox_inches='tight', pad_inches=0.05)
Surface plot of the quasiparticle weight as fuction of U/D and dop
def plot_mean_field_conv(N=1, n=0.5, Uspan=np.arange(0, 3.6, 0.5)): sl = Spinon(slaves=2*N, orbitals=N, avg_particles=2*n, hopping=[0.5]*2*N, orbital_e=[0]*2*N) hlog = solve_loop(sl, Uspan, [0.])[1] f, (ax1, ax2) = plt.subplots(2, sharex=True) for field in hlog: field = np.asarray(field) ax1.semilogy(abs(field[1:]-field[:-1])) ax2.plot(field)#, label = 'h, U = {}'.format(Uint)) plt.title('Convergence of selfconsintent mean field') ax1.set_ylabel('$\\Delta h$') ax2.set_ylabel('mean field $h$') plt.xlabel('iterations') return hlog
Generates the plot on the convergenge of the mean field in single site spin hamiltonian under with N degenerate half-filled orbitals
def assign(self, value, termenc): if self._termenc != termenc: self._decoder = codecs.getincrementaldecoder(termenc)(errors='replace') self._termenc = termenc self._data = self._decoder.decode(value)
>>> scanner = DefaultScanner() >>> scanner.assign("01234", "ascii") >>> scanner._data u'01234'
def dtypes_summary(df): output_df = pd.DataFrame([]) row_count = df.shape[0] row_indexes = ['rows_numerical','rows_string','rows_date_time','category_count','largest_category','rows_na','rows_total'] for colname in df: data = df[colname] # data is the pandas series associated with this column # number of numerical values in the column rows_numerical = pd.to_numeric(data,errors = 'coerce').count() # number of values that can't be coerced to a numerical rows_string = row_count - rows_numerical # number of values that can be coerced to a date-time object rows_date_time = pd.to_datetime(data,errors = 'coerce',infer_datetime_format = True).count() # categories in column value_counts = data.value_counts().reset_index() # number of different values in the dataframe categories = len(value_counts) # largest category largest_category = value_counts.iloc[0,1] # number of null/missing values rows_na = data.isnull().sum() # build the output list output_data = [rows_numerical, rows_string, rows_date_time, categories, largest_category,rows_na,row_count] # add to dataframe output_df.loc[:,colname] = pd.Series(output_data) # row names output_df.index = row_indexes return output_df
Takes in a dataframe and returns a dataframe with information on the data-types present in each column. Parameters: df - DataFrame Dataframe to summarize
def df_outliers(df,sensitivity = 1.5): outlier_df = df.copy() dtypes = _basics.col_dtypes(df) for col_name in df.columns: outlier_df.loc[~outliers(df[col_name],'bool',dtypes[col_name],sensitivity),col_name] = np.nan outlier_df = outlier_df.dropna(how = 'all') return outlier_df
Finds outliers in the dataframe. Parameters: df - DataFrame The DataFrame to analyze. sensitivity - number, default 1.5 The value to multipy by the iter-quartile range when determining outliers. This number is used for categorical data as well.
def outliers(df,output_type = 'values',dtype = 'number',sensitivity = 1.5):# can output boolean array or values if dtype in ('number','datetime','timedelt','datetimetz'): if not dtype == 'number': df = pd.to_numeric(df,errors = 'coerce') quart25, quart75 = percentiles(df,q = [.25,.75]) out_range= sensitivity * (quart75 - quart25) lower_bound,upper_bound = quart25-out_range, quart75+out_range bool_array = (df < lower_bound)|(df > upper_bound) else: value_counts = df.value_counts() # Trying to find categorical outliers. quart25 = cum_percentile(value_counts,.25) quart75 = cum_percentile(value_counts,.75) out_values = int(sensitivity * (quart75 - quart25) + quart75 + 1) if out_values >= len(value_counts): bool_array = _utils.bc_vec(df,value = False) else: outlier_values = value_counts[value_counts <= value_counts.iloc[out_values]].index bool_array = df.isin(outlier_values) if output_type == 'values': return df[bool_array] return bool_array
Returns potential outliers as either a boolean array or a subset of the original. Parameters: df - array_like Series or dataframe to check output_type - string, default 'values' if 'values' is specified, then will output the values in the series that are suspected outliers. Else, a boolean array will be outputted, where True means the value is an outlier dtype - string, default 'number' the way to treat the object. Possible values are 'number','datetime', 'timedelt','datetimetz','category',or 'object' sensitivity - number, default 1.5 The value to multipy by the iter-quartile range when determining outliers. This number is used for categorical data as well.
def cum_percentile(series,q): total = series.sum() cum_sum = series.cumsum() return sum(cum_sum < total*q)
Takes a series of ordered frequencies and returns the value at a specified quantile Parameters: series - Series The series to analyze q - number Quantile to get the value of
def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Payment, dict): for key, value in self.items(): result[key] = value return result
Returns the model properties as a dict
def list_all_payments(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_payments_with_http_info(**kwargs) else: (data) = cls._list_all_payments_with_http_info(**kwargs) return data
List Payments Return a list of Payments This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_payments(async=True) >>> result = thread.get() :param async bool :param int page: page number :param int size: page size :param str sort: page order :return: page[Payment] If the method is called asynchronously, returns the request thread.
def from_config(cls): config = Config() client = cls( email=config.get('email'), api_key=config.get('api_key'), server=config.get('api_server'), http_proxy=config.get('http_proxy'), https_proxy=config.get('https_proxy'), ) return client
Method to return back a loaded instance.
def set_debug(self, status): if status: self.logger.setLevel('DEBUG') else: self.logger.setLevel('INFO')
Control the logging state.
def _endpoint(self, endpoint, action, *url_args): args = (self.api_base, endpoint, action) if action == '': args = (self.api_base, endpoint) api_url = "/".join(args) if url_args: if len(url_args) == 1: api_url += "/" + url_args[0] else: api_url += "/".join(url_args) return api_url
Return the URL for the action. :param str endpoint: The controller :param str action: The action provided by the controller :param url_args: Additional endpoints(for endpoints that take part of the url as option) :return: Full URL for the requested action
def _json(self, response): if response.status_code == 204: return None try: return response.json() except ValueError as e: raise ValueError( 'Exception: %s\n' 'request: %s, response code: %s, response: %s' % ( str(e), response.request.url, response.status_code, response.content, ) )
JSON response from server. :param response: Response from the server :throws ValueError: from requests' response.json() error :return: response deserialized from JSON
def _get(self, endpoint, action, *url_args, **url_params): api_url = self._endpoint(endpoint, action, *url_args) kwargs = {'headers': self.headers, 'params': url_params, 'timeout': Client.TIMEOUT, 'verify': self.verify} if self.proxies: kwargs['proxies'] = self.proxies self.logger.debug("Requesting: %s, %s" % (api_url, str(kwargs))) response = requests.get(api_url, **kwargs) return self._json(response)
Request API Endpoint - for GET methods. :param str endpoint: Endpoint :param str action: Endpoint Action :param url_args: Additional endpoints(for endpoints that take part of the url as option) :param url_params: Parameters to pass to url, typically query string :return: response deserialized from JSON
def _send_data(self, method, endpoint, action, data, *url_args, **url_params): api_url = self._endpoint(endpoint, action, *url_args) data.update({'email': self.email, 'api_key': self.api_key}) data = json.dumps(data) kwargs = {'headers': self.headers, 'params': url_params, 'verify': self.verify, 'data': data} if self.proxies: kwargs['proxies'] = self.proxies self.logger.debug("Requesting: %s %s, %s" % (method, api_url, str(kwargs))) response = requests.request(method, api_url, **kwargs) self.logger.debug("Response: %d, %s" % (response.status_code, response.content)) return self._json(response)
Submit to API Endpoint - for DELETE, PUT, POST methods. :param str method: Method to use for the request :param str endpoint: Endpoint :param str action: Endpoint Action :param url_args: Additional endpoints(for endpoints that take part of the url as option) :param url_params: Parameters to pass to url, typically query string :return: response deserialized from JSON
def create_free_item_coupon(cls, free_item_coupon, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_free_item_coupon_with_http_info(free_item_coupon, **kwargs) else: (data) = cls._create_free_item_coupon_with_http_info(free_item_coupon, **kwargs) return data
Create FreeItemCoupon Create a new FreeItemCoupon This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_free_item_coupon(free_item_coupon, async=True) >>> result = thread.get() :param async bool :param FreeItemCoupon free_item_coupon: Attributes of freeItemCoupon to create (required) :return: FreeItemCoupon If the method is called asynchronously, returns the request thread.
def delete_free_item_coupon_by_id(cls, free_item_coupon_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_free_item_coupon_by_id_with_http_info(free_item_coupon_id, **kwargs) else: (data) = cls._delete_free_item_coupon_by_id_with_http_info(free_item_coupon_id, **kwargs) return data
Delete FreeItemCoupon Delete an instance of FreeItemCoupon by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_free_item_coupon_by_id(free_item_coupon_id, async=True) >>> result = thread.get() :param async bool :param str free_item_coupon_id: ID of freeItemCoupon to delete. (required) :return: None If the method is called asynchronously, returns the request thread.
def get_free_item_coupon_by_id(cls, free_item_coupon_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_free_item_coupon_by_id_with_http_info(free_item_coupon_id, **kwargs) else: (data) = cls._get_free_item_coupon_by_id_with_http_info(free_item_coupon_id, **kwargs) return data
Find FreeItemCoupon Return single instance of FreeItemCoupon by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_free_item_coupon_by_id(free_item_coupon_id, async=True) >>> result = thread.get() :param async bool :param str free_item_coupon_id: ID of freeItemCoupon to return (required) :return: FreeItemCoupon If the method is called asynchronously, returns the request thread.
def list_all_free_item_coupons(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_free_item_coupons_with_http_info(**kwargs) else: (data) = cls._list_all_free_item_coupons_with_http_info(**kwargs) return data
List FreeItemCoupons Return a list of FreeItemCoupons This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_free_item_coupons(async=True) >>> result = thread.get() :param async bool :param int page: page number :param int size: page size :param str sort: page order :return: page[FreeItemCoupon] If the method is called asynchronously, returns the request thread.
def replace_free_item_coupon_by_id(cls, free_item_coupon_id, free_item_coupon, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_free_item_coupon_by_id_with_http_info(free_item_coupon_id, free_item_coupon, **kwargs) else: (data) = cls._replace_free_item_coupon_by_id_with_http_info(free_item_coupon_id, free_item_coupon, **kwargs) return data
Replace FreeItemCoupon Replace all attributes of FreeItemCoupon This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_free_item_coupon_by_id(free_item_coupon_id, free_item_coupon, async=True) >>> result = thread.get() :param async bool :param str free_item_coupon_id: ID of freeItemCoupon to replace (required) :param FreeItemCoupon free_item_coupon: Attributes of freeItemCoupon to replace (required) :return: FreeItemCoupon If the method is called asynchronously, returns the request thread.
def update_free_item_coupon_by_id(cls, free_item_coupon_id, free_item_coupon, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_free_item_coupon_by_id_with_http_info(free_item_coupon_id, free_item_coupon, **kwargs) else: (data) = cls._update_free_item_coupon_by_id_with_http_info(free_item_coupon_id, free_item_coupon, **kwargs) return data
Update FreeItemCoupon Update attributes of FreeItemCoupon This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_free_item_coupon_by_id(free_item_coupon_id, free_item_coupon, async=True) >>> result = thread.get() :param async bool :param str free_item_coupon_id: ID of freeItemCoupon to update. (required) :param FreeItemCoupon free_item_coupon: Attributes of freeItemCoupon to update. (required) :return: FreeItemCoupon If the method is called asynchronously, returns the request thread.
def process_events(events, source_ip): s3 = boto3.resource('s3') table = boto3.resource("dynamodb").Table(os.environ['database']) with table.batch_writer() as batch: for idx, event in enumerate(events): event = convert_keys_to_string(event) event['sourceIp'] = source_ip event['event'] = hashlib.sha256(str(event)).hexdigest() metadata = event['metadata'] timestamp = str(event['metadata']['timeStamp']) event['metadata']['timeStamp'] = timestamp kwargs = {'match': event['indicatorMatch'], 'type': metadata['type'], 'method': metadata['method'].lower(), 'time': event['analysisTime'], 'ip': source_ip} file_struct = '{match}_{type}_{method}_{ip}_{time}.json' file_name = file_struct.format(**kwargs) key_path = '/tmp/%s' % file_name output = json.dumps(event, indent=4, sort_keys=True) open(key_path, "w").write(output) data = open(key_path, 'rb') s3.Bucket(os.environ['s3_bucket']).put_object(Key=file_name, Body=data) logger.info("EVENT: %s" % str(event)) batch.put_item(Item=event) return True
Process all the events for logging and S3.
def lambda_handler(event, context): body = event.get('body', dict()) events = body.get('events', list()) source_ip = str(event.get('source_ip', '')) if len(events) == 0: return {'success': False, 'message': "No events sent in"} status = process_events(events, source_ip) msg = "Wrote {} events to the cloud".format(len(events)) return {'success': True, 'message': msg}
Run the script.
def cost_type(self, cost_type): allowed_values = ["orderSubtotal", "weight"] if cost_type is not None and cost_type not in allowed_values: raise ValueError( "Invalid value for `cost_type` ({0}), must be one of {1}" .format(cost_type, allowed_values) ) self._cost_type = cost_type
Sets the cost_type of this TableRateShipping. :param cost_type: The cost_type of this TableRateShipping. :type: str
def create_table_rate_shipping(cls, table_rate_shipping, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_table_rate_shipping_with_http_info(table_rate_shipping, **kwargs) else: (data) = cls._create_table_rate_shipping_with_http_info(table_rate_shipping, **kwargs) return data
Create TableRateShipping Create a new TableRateShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_table_rate_shipping(table_rate_shipping, async=True) >>> result = thread.get() :param async bool :param TableRateShipping table_rate_shipping: Attributes of tableRateShipping to create (required) :return: TableRateShipping If the method is called asynchronously, returns the request thread.
def delete_table_rate_shipping_by_id(cls, table_rate_shipping_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, **kwargs) else: (data) = cls._delete_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, **kwargs) return data
Delete TableRateShipping Delete an instance of TableRateShipping by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_table_rate_shipping_by_id(table_rate_shipping_id, async=True) >>> result = thread.get() :param async bool :param str table_rate_shipping_id: ID of tableRateShipping to delete. (required) :return: None If the method is called asynchronously, returns the request thread.
def get_table_rate_shipping_by_id(cls, table_rate_shipping_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, **kwargs) else: (data) = cls._get_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, **kwargs) return data
Find TableRateShipping Return single instance of TableRateShipping by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_table_rate_shipping_by_id(table_rate_shipping_id, async=True) >>> result = thread.get() :param async bool :param str table_rate_shipping_id: ID of tableRateShipping to return (required) :return: TableRateShipping If the method is called asynchronously, returns the request thread.
def list_all_table_rate_shippings(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_table_rate_shippings_with_http_info(**kwargs) else: (data) = cls._list_all_table_rate_shippings_with_http_info(**kwargs) return data
List TableRateShippings Return a list of TableRateShippings This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_table_rate_shippings(async=True) >>> result = thread.get() :param async bool :param int page: page number :param int size: page size :param str sort: page order :return: page[TableRateShipping] If the method is called asynchronously, returns the request thread.
def replace_table_rate_shipping_by_id(cls, table_rate_shipping_id, table_rate_shipping, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, table_rate_shipping, **kwargs) else: (data) = cls._replace_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, table_rate_shipping, **kwargs) return data
Replace TableRateShipping Replace all attributes of TableRateShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_table_rate_shipping_by_id(table_rate_shipping_id, table_rate_shipping, async=True) >>> result = thread.get() :param async bool :param str table_rate_shipping_id: ID of tableRateShipping to replace (required) :param TableRateShipping table_rate_shipping: Attributes of tableRateShipping to replace (required) :return: TableRateShipping If the method is called asynchronously, returns the request thread.
def update_table_rate_shipping_by_id(cls, table_rate_shipping_id, table_rate_shipping, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, table_rate_shipping, **kwargs) else: (data) = cls._update_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, table_rate_shipping, **kwargs) return data
Update TableRateShipping Update attributes of TableRateShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_table_rate_shipping_by_id(table_rate_shipping_id, table_rate_shipping, async=True) >>> result = thread.get() :param async bool :param str table_rate_shipping_id: ID of tableRateShipping to update. (required) :param TableRateShipping table_rate_shipping: Attributes of tableRateShipping to update. (required) :return: TableRateShipping If the method is called asynchronously, returns the request thread.
def next_formatted_pair(self): key = self.key_gen.next() token = self.token_gen.create_token(key) fkey = self.formatter.format_key(key) ftoken = self.formatter.format_token(token) return FormattedPair(key, token, fkey, ftoken)
\ Returns a :class:`FormattedPair <shorten.store.FormattedPair>` containing attributes `key`, `token`, `formatted_key` and `formatted_token`. Calling this method will always consume a key and token.
def get_source(path): ''' yields all non-empty lines in a file ''' for line in read(path): if 'import' in line or len(line.strip()) == 0 or line.startswith('#'): continue if '__name__' in line and '__main__' in line: break else: yield linf get_source(path): ''' yields all non-empty lines in a file ''' for line in read(path): if 'import' in line or len(line.strip()) == 0 or line.startswith('#'): continue if '__name__' in line and '__main__' in line: break else: yield line
yields all non-empty lines in a file
def create_option_value(cls, option_value, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_option_value_with_http_info(option_value, **kwargs) else: (data) = cls._create_option_value_with_http_info(option_value, **kwargs) return data
Create OptionValue Create a new OptionValue This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_option_value(option_value, async=True) >>> result = thread.get() :param async bool :param OptionValue option_value: Attributes of optionValue to create (required) :return: OptionValue If the method is called asynchronously, returns the request thread.
def delete_option_value_by_id(cls, option_value_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_option_value_by_id_with_http_info(option_value_id, **kwargs) else: (data) = cls._delete_option_value_by_id_with_http_info(option_value_id, **kwargs) return data
Delete OptionValue Delete an instance of OptionValue by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_option_value_by_id(option_value_id, async=True) >>> result = thread.get() :param async bool :param str option_value_id: ID of optionValue to delete. (required) :return: None If the method is called asynchronously, returns the request thread.
def get_option_value_by_id(cls, option_value_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_option_value_by_id_with_http_info(option_value_id, **kwargs) else: (data) = cls._get_option_value_by_id_with_http_info(option_value_id, **kwargs) return data
Find OptionValue Return single instance of OptionValue by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_option_value_by_id(option_value_id, async=True) >>> result = thread.get() :param async bool :param str option_value_id: ID of optionValue to return (required) :return: OptionValue If the method is called asynchronously, returns the request thread.
def list_all_option_values(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_option_values_with_http_info(**kwargs) else: (data) = cls._list_all_option_values_with_http_info(**kwargs) return data
List OptionValues Return a list of OptionValues This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_option_values(async=True) >>> result = thread.get() :param async bool :param int page: page number :param int size: page size :param str sort: page order :return: page[OptionValue] If the method is called asynchronously, returns the request thread.
def replace_option_value_by_id(cls, option_value_id, option_value, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_option_value_by_id_with_http_info(option_value_id, option_value, **kwargs) else: (data) = cls._replace_option_value_by_id_with_http_info(option_value_id, option_value, **kwargs) return data
Replace OptionValue Replace all attributes of OptionValue This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_option_value_by_id(option_value_id, option_value, async=True) >>> result = thread.get() :param async bool :param str option_value_id: ID of optionValue to replace (required) :param OptionValue option_value: Attributes of optionValue to replace (required) :return: OptionValue If the method is called asynchronously, returns the request thread.
def update_option_value_by_id(cls, option_value_id, option_value, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_option_value_by_id_with_http_info(option_value_id, option_value, **kwargs) else: (data) = cls._update_option_value_by_id_with_http_info(option_value_id, option_value, **kwargs) return data
Update OptionValue Update attributes of OptionValue This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_option_value_by_id(option_value_id, option_value, async=True) >>> result = thread.get() :param async bool :param str option_value_id: ID of optionValue to update. (required) :param OptionValue option_value: Attributes of optionValue to update. (required) :return: OptionValue If the method is called asynchronously, returns the request thread.
def bool_set(operation,*sets): '''combine ``sets`` with ``operation`` :and: combine sets with AND :or: combine sets with OR :not: NOT sets versus the last given set''' if len(sets)<=1: return sets if operation=='and': return and_sets(*sets) if operation=='or': return or_sets(*sets) if operation=='not': return not_sets(*setsf bool_set(operation,*sets): '''combine ``sets`` with ``operation`` :and: combine sets with AND :or: combine sets with OR :not: NOT sets versus the last given set''' if len(sets)<=1: return sets if operation=='and': return and_sets(*sets) if operation=='or': return or_sets(*sets) if operation=='not': return not_sets(*sets)
combine ``sets`` with ``operation`` :and: combine sets with AND :or: combine sets with OR :not: NOT sets versus the last given set
def datetime_to_ns(then): if then == datetime(1970, 1, 1, 0, 0): return 'Antiquity' now = datetime.utcnow() delta = now - then seconds = delta.total_seconds() # There's gotta be a better way to do this... years, seconds = divmod(seconds, 60*60*24*365) days, seconds = divmod(seconds, 60*60*24) hours, seconds = divmod(seconds, 60*60) minutes, seconds = divmod(seconds, 60) years = int(years) days = int(days) hours = int(hours) minutes = int(minutes) seconds = round(seconds) if years > 1: if days > 1: return f'{years} years {days} days ago' elif days == 1: return '{years} years 1 day ago' return '{years} years ago' if years == 1: if days > 1: return f'1 year {days} days ago' elif days == 1: return '1 year 1 day ago' return '1 year ago' if days > 3: return f'{days} days ago' if days > 1: if hours > 1: return f'{days} days {hours} hours ago' elif hours == 1: return f'{days} days 1 hour ago' return f'{days} days ago' if days == 1: if hours > 1: return f'1 day {hours} hours ago' elif hours == 1: return '1 day 1 hour ago' return '1 day ago' if hours > 1: return f'{hours} hours ago' if hours == 1: return f'{minutes + 60} minutes ago' if minutes > 1: return f'{minutes} minutes ago' if minutes == 1: return '1 minute ago' return 'Seconds ago'
Transform a :any:`datetime.datetime` into a NationStates-style string. For example "6 days ago", "105 minutes ago", etc.
def authenticate(self, request): # todo: can we trust that request.user variable is even defined? if request.user and request.user.is_authenticated(): return request.user if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 2: if auth[0].lower() == "basic": uname, passwd = base64.b64decode(auth[1]).split(':') user = authenticate(username=uname, password=passwd) if user is not None: if user.is_active: request.user = user return user else: raise Forbidden() # either no auth header or using some other auth protocol, # we'll return a challenge for the user anyway raise Unauthorized()
Authenticate request using HTTP Basic authentication protocl. If the user is successfully identified, the corresponding user object is stored in `request.user`. If the request has already been authenticated (i.e. `request.user` has authenticated user object), this function does nothing. Raises Forbidden or Unauthorized if the user authentication fails. If no exception is thrown, the `request.user` will contain authenticated user object.
def clean(): os.chdir(os.path.join(project_root, 'docs')) sh("make clean") os.chdir(project_root) sh("rm -rf pyoauth2.egg-info")
Clean up previous garbage
def _is_unit(rule): # type: (Type[Rule]) -> bool return len(rule.left) == 1 and len(rule.right) == 1 and \ isclass(rule.fromSymbol) and isclass(rule.toSymbol) and \ issubclass(rule.fromSymbol, Nonterminal) and issubclass(rule.toSymbol, Nonterminal)
Check if parameter is unit rule. :param rule: Object to check. :return: True if is parameter unit rule, false otherwise.
def _create_rule(rule, index, backtrack): # type: (Rule, int, Dict[Type[Nonterminal], Type[Rule]]) -> Type[EpsilonRemovedRule] # remove old rules from the dictionary old_dict = rule.__dict__.copy() if 'rules' in old_dict: del old_dict['rules'] if 'rule' in old_dict: del old_dict['rule'] if 'left' in old_dict: del old_dict['left'] if 'right' in old_dict: del old_dict['right'] if 'fromSymbol' in old_dict: del old_dict['fromSymbol'] if 'toSymbol' in old_dict: del old_dict['toSymbol'] # create type created = type('NoEps[' + rule.__name__ + ']', (EpsilonRemovedRule,), old_dict) # type: Type[EpsilonRemovedRule] # add from_rule and index created.from_rule = rule created.replace_index = index created.backtrack = backtrack # attach rule created.fromSymbol = rule.fromSymbol created.right = [rule.right[i] for i in range(len(rule.right)) if i != index] # ff the right side is empty if len(created.right) == 0: created.right = [EPSILON] return created
Create EpsilonRemovedRule. This rule will skip symbol at the `index`. :param rule: Original rule. :param index: Index of symbol that is rewritable to epsilon. :param backtrack: Dictionary where key is nonterminal and value is rule which is next to generate epsilon. :return: EpsilonRemovedRule class without symbol rewritable to epsilon.
def remove_rules_with_epsilon(grammar, inplace=False): # type: (Grammar, bool) -> Grammar # copy if required if inplace is False: grammar = copy(grammar) # find nonterminals rewritable to epsilon rewritable = find_nonterminals_rewritable_to_epsilon(grammar) # type: Dict[Type[Nonterminal], Type[Rule]] # create queue from rules to iterate over rules = Queue() for r in grammar.rules: rules.put(r) # iterate thought rules while not rules.empty(): rule = rules.get() right = rule.right # if the rule rewrite to epsilon we can safely delete it if right == [EPSILON]: # unless it rewrites from the start symbol if rule.fromSymbol != grammar.start: grammar.rules.discard(rule) # continue IS executed, but due optimization line is marked as missed. continue # pragma: no cover # iterate over the right side for rule_index in range(len(right)): symbol = right[rule_index] # if symbol is rewritable, generate new rule without that symbol if symbol in rewritable: new_rule = _create_rule(rule, rule_index, rewritable) grammar.rules.add(new_rule) rules.put(new_rule) # in case there are more rewritable symbols return grammar
Remove epsilon rules. :param grammar: Grammar where rules remove :param inplace: True if transformation should be performed in place, false otherwise. False by default. :return: Grammar without epsilon rules.
def average(): count = 0 total = total() i=0 while 1: i = yield ((total.send(i)*1.0)/count if count else 0) count += 1
generator that holds a rolling average
def args(self): if self._args is None: parser = self._build_parser() self._args = parser.parse_args() return self._args
Parsed command-line arguments.
def build_pypackage_basename(self, pytree, base): dirname = os.path.dirname(pytree) parsed_package_name = base.replace(dirname, '').strip('/') return parsed_package_name
Build the string representing the parsed package basename. :param str pytree: The pytree absolute path. :param str pytree: The absolute path of the pytree sub-package of which determine the parsed name. :rtype: str
def _build_parser(self): parser = argparse.ArgumentParser() parser.add_argument('--pytree', required=True, type=self._valid_directory, help='This is the path, absolute or relative, of the Python package ' 'that is to be parsed.') parser.add_argument('--doctree', required=True, type=self._valid_directory, help='This is the path, absolute or relative, of the documentation ' 'package that is to be parsed.') parser.add_argument('--no-fail', action='store_true', help='Using this option will cause this program to return an exit ' 'code of 0 even when the given trees do not match.') parser.add_argument('--doc-ignores', action=AddDocIgnores, help='A comma separated list of additional doc files to ignore') return parser
Build the needed command-line parser.
def build_pyfile_path_from_docname(self, docfile): name, ext = os.path.splitext(docfile) expected_py_name = name.replace('.', '/') + '.py' return expected_py_name
Build the expected Python file name based on the given documentation file name. :param str docfile: The documentation file name from which to build the Python file name. :rtype: str
def calculate_tree_differences(self, pytree, doctree): pykeys = set(pytree.keys()) dockeys = set(doctree.keys()) # Calculate the missing documentation files, if any. missing_doc_keys = pykeys - dockeys missing_docs = {pytree[pyfile] for pyfile in missing_doc_keys} # Calculate the missing Python files, if any. missing_py_keys = dockeys - pykeys missing_pys = {docfile for docfile in missing_py_keys} return missing_pys, missing_docs
Calculate the differences between the given trees. :param dict pytree: The dictionary of the parsed Python tree. :param dict doctree: The dictionary of the parsed documentation tree. :rtype: tuple :returns: A two-tuple of sets, where the first is the missing Python files, and the second is the missing documentation files.
def compare_trees(self, parsed_pytree, parsed_doctree): if parsed_pytree == parsed_doctree: return 0 missing_pys, missing_docs = self.calculate_tree_differences(pytree=parsed_pytree, doctree=parsed_doctree) self.pprint_tree_differences(missing_pys=missing_pys, missing_docs=missing_docs) return 0 if self.args.no_fail else 1
Compare the given parsed trees. :param dict parsed_pytree: A dictionary representing the parsed Python tree where each key is a parsed Python file and its key is its expected rst file name.
def parse_doc_tree(self, doctree, pypackages): parsed_doctree = {} for filename in os.listdir(doctree): if self._ignore_docfile(filename): continue expected_pyfile = self.build_pyfile_path_from_docname(filename) parsed_doctree[expected_pyfile] = filename pypackages = {name + '.py' for name in pypackages} return {elem: parsed_doctree[elem] for elem in parsed_doctree if elem not in pypackages}
Parse the given documentation tree. :param str doctree: The absolute path to the documentation tree which is to be parsed. :param set pypackages: A set of all Python packages found in the pytree. :rtype: dict :returns: A dict where each key is the path of an expected Python module and its value is the parsed rst module name (relative to the documentation tree).
def parse_py_tree(self, pytree): parsed_pytree = {} pypackages = set() for base, dirs, files in os.walk(pytree): if self._ignore_pydir(os.path.basename(base)): continue # TODO(Anthony): If this is being run against a Python 3 package, this needs to be # adapted to account for namespace packages. elif '__init__.py' not in files: continue package_basename = self.build_pypackage_basename(pytree=pytree, base=base) pypackages.add(package_basename) for filename in files: if self._ignore_pyfile(filename): continue parsed_path = os.path.join(package_basename, filename) parsed_pytree[parsed_path] = self.build_rst_name_from_pypath(parsed_path) return parsed_pytree, pypackages
Parse the given Python package tree. :param str pytree: The absolute path to the Python tree which is to be parsed. :rtype: dict :returns: A two-tuple. The first element is a dict where each key is the path of a parsed Python module (relative to the Python tree) and its value is the expected rst module name. The second element is a set where each element is a Python package or sub-package. :rtype: tuple
def pprint_tree_differences(self, missing_pys, missing_docs): if missing_pys: print('The following Python files appear to be missing:') for pyfile in missing_pys: print(pyfile) print('\n') if missing_docs: print('The following documentation files appear to be missing:') for docfiile in missing_docs: print(docfiile) print('\n')
Pprint the missing files of each given set. :param set missing_pys: The set of missing Python files. :param set missing_docs: The set of missing documentation files. :rtype: None
def _valid_directory(self, path): abspath = os.path.abspath(path) if not os.path.isdir(abspath): raise argparse.ArgumentTypeError('Not a valid directory: {}'.format(abspath)) return abspath
Ensure that the given path is valid. :param str path: A valid directory path. :raises: :py:class:`argparse.ArgumentTypeError` :returns: An absolute directory path.
def main(self): args = self.args parsed_pytree, pypackages = self.parse_py_tree(pytree=args.pytree) parsed_doctree = self.parse_doc_tree(doctree=args.doctree, pypackages=pypackages) return self.compare_trees(parsed_pytree=parsed_pytree, parsed_doctree=parsed_doctree)
Parse package trees and report on any discrepancies.
def initialize(self, grid, num_of_paths, seed): for p in self.producers: p.initialize(grid, num_of_paths, seed) self.grid = grid self.num_of_paths = num_of_paths self.seed = seed
inits producer for a simulation run