max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
app/schemas/cost.py
code-lab-org/ise-design
0
6625051
<filename>app/schemas/cost.py<gh_stars>0 from fastapi_utils.api_model import APIModel from pydantic import Field from typing import List, Dict class BillOfMaterialsLine(APIModel): name: str = Field( ..., description="Material name." ) cost: float = Field( ..., description="Unit cost ($)." ) quantity: int = Field( ..., description="Quantity used." ) class AssemblyCostAnalysis(APIModel): components: float = Field( ..., description="Cost of assembling individual components ($)." ) integration: float = Field( ..., description="Cost of integrating components ($)." ) total: float = Field( ..., description="Total assembly cost ($)." ) class OverheadCostAnalysis(APIModel): engineering: float = Field( ..., description="Cost of engineering staff ($)." ) marketing: float = Field( ..., description="Cost of marketing staff ($)." ) administration: float = Field( ..., description="Cost of administration staff ($)." ) facilities: float = Field( ..., description="Cost of facilities ($)." ) total: float = Field( ..., description="Total overhead cost ($)." ) class CostAnalysis(APIModel): version: str = Field( ..., description="Version number." ) materials: float = Field( ..., description="Cost of the materials ($)." ) bom: Dict[str, BillOfMaterialsLine] = Field( ..., description="Bill of materials." ) assembly: AssemblyCostAnalysis = Field( ..., description="Assembly cost analysis." ) overhead: OverheadCostAnalysis = Field( ..., description="Overhead cost analysis." ) total: float = Field( ..., description="Total cost ($)." )
<filename>app/schemas/cost.py<gh_stars>0 from fastapi_utils.api_model import APIModel from pydantic import Field from typing import List, Dict class BillOfMaterialsLine(APIModel): name: str = Field( ..., description="Material name." ) cost: float = Field( ..., description="Unit cost ($)." ) quantity: int = Field( ..., description="Quantity used." ) class AssemblyCostAnalysis(APIModel): components: float = Field( ..., description="Cost of assembling individual components ($)." ) integration: float = Field( ..., description="Cost of integrating components ($)." ) total: float = Field( ..., description="Total assembly cost ($)." ) class OverheadCostAnalysis(APIModel): engineering: float = Field( ..., description="Cost of engineering staff ($)." ) marketing: float = Field( ..., description="Cost of marketing staff ($)." ) administration: float = Field( ..., description="Cost of administration staff ($)." ) facilities: float = Field( ..., description="Cost of facilities ($)." ) total: float = Field( ..., description="Total overhead cost ($)." ) class CostAnalysis(APIModel): version: str = Field( ..., description="Version number." ) materials: float = Field( ..., description="Cost of the materials ($)." ) bom: Dict[str, BillOfMaterialsLine] = Field( ..., description="Bill of materials." ) assembly: AssemblyCostAnalysis = Field( ..., description="Assembly cost analysis." ) overhead: OverheadCostAnalysis = Field( ..., description="Overhead cost analysis." ) total: float = Field( ..., description="Total cost ($)." )
none
1
2.217964
2
fin dashboard/fin_dash.py
queeniekwan/Seaquake
0
6625052
<reponame>queeniekwan/Seaquake<filename>fin dashboard/fin_dash.py<gh_stars>0 import pandas as pd import json from datetime import datetime, timedelta def clean_data(df): ''' filter and edit raw data into clean data ''' # filter out rows where entry_trade_size_asset != exit_trade_size_asset; entry_trade_size_dollar = 0; exit_trade_size_dollar = 0 df = df[df.entry_trade_size_asset == df.exit_trade_size_asset] df = df[df.entry_trade_size_dollar != 0] df = df[df.exit_trade_size_dollar != 0] # convert time columns to datetime object df['entry_trade_time_iso8601'] = pd.to_datetime(df['entry_trade_time_iso8601']) df['exit_trade_time_iso8601'] = pd.to_datetime(df['exit_trade_time_iso8601']) # add market_made_type df['market_made_type'] = df.apply(mm_condition, axis='columns') # add hold time (seconds) df['hold_time'] = df.exit_trade_time_unix - df.entry_trade_time_unix return df def mm_condition(df): ''' apply condition for market_made_type ''' if df.entry_trade_maker == True: if df.exit_trade_maker == True: return 'both sides maker' else: return 'entry maker' else: if df.exit_trade_maker == True: return 'exit maker' else: return 'both sides taker' def create_fin_dash(df): ''' create and return the fin dashboard table with data from df ''' # create table frame dash = pd.DataFrame(columns=['metric', 'value_type', 'total', 'today', 'yesterday', 'day-3', 'day-4', 'day-5', 'day-6', 'day-7', 'this_week', 'last_week', 'week-3', 'week-4', 'this_month', 'last_month']) dash.metric = ['trades', 'trade volume asset', 'trade volume dollar', 'spread profit', 'fee rebate', 'fee paid', 'net profit', 'profitable trades', 'profitable trades', 'unprofitable trades', 'unprofitable trades', 'both sides maker', 'both sides maker', 'entry maker only', 'entry maker only', 'exit maker only', 'exit maker only', 'both sides taker', 'both sides taker', 'maker trade', 'maker trade', 'taker trade', 'taker trade', 'maker order', 'maker order', 'maker order volume', 'taker order', 'taker order', 'taker order volume', 'long trade', 'long trade', 'short trade', 'short trade', 'entry limit order', 'entry limit order', 'entry market order', 'entry market order', 'exit limit order', 'exit limit order', 'exit market order', 'exit market order', 'avg order size asset', 'avg order size dollar', 'win trades avg hold time', 'lose trades avg hold time', 'timeframe', 'weekday'] dash.value_type = ['value', 'value', 'value', 'value', 'value', 'value', 'value', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'value', 'percentage', 'value', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'value', 'value', 'value', 'str', 'str'] # fill table columns # get utc today 00:00 now = datetime.utcnow().strftime('%Y-%m-%d') today_start = datetime.strptime(now+' 00:00:00', '%Y-%m-%d %H:%M:%S') # total dash.total = fill_findash_column(df) # loop fill today to day-7 start = today_start end = None for column in dash[['today', 'yesterday', 'day-3', 'day-4', 'day-5', 'day-6', 'day-7']]: dash[column] = fill_findash_column(df, start_date=start, end_date=end, col_type='day') end = start start -= timedelta(days=1) # loop fill this week to week-4 wd_today = today_start.weekday() #weekday today (int, 0=Mon, 7=Sun) start = today_start - timedelta(days=wd_today) end = None for column in dash[['this_week', 'last_week', 'week-3', 'week-4']]: dash[column] = fill_findash_column(df, start_date=start, end_date=end, col_type='week') end = start start -= timedelta(weeks=1) # loop fill this month to last month start = today_start.replace(day=1) end = None for column in dash[['this_month', 'last_month']]: dash[column] = fill_findash_column(df, start_date=start, end_date=end, col_type='month') end = start last_day_prev_month = start - timedelta(days=1) start = last_day_prev_month.replace(day=1) return dash def fill_findash_column(df, start_date=None, end_date=None, col_type=None): ''' return a list of data for a specific column in the fin_dash Dataframe from the df Dataframe df is the source data Dataframe, start_date and end_date filter data within this date range (default is None), col_type is type of this column (str: day, week, or month) ''' # create a subset of data within the time range if start_date and end_date: data = df[(df.entry_trade_time_iso8601 >= start_date) & (df.entry_trade_time_iso8601 < end_date)] elif start_date: data = df[(df.entry_trade_time_iso8601 >= start_date)] else: data = df.copy() # date range and day of week if col_type == 'day': timeframe = start_date.strftime('%Y/%m/%d') wd = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] weekday = wd[start_date.weekday()] elif col_type == 'week': timeframe = start_date.strftime('%Y/%m/%d') + ' - ' + (start_date + timedelta(days=6)).strftime('%Y/%m/%d') weekday = 'N/A' elif col_type == 'month': timeframe = start_date.strftime('%Y/%m') weekday = 'N/A' else: timeframe = (data['entry_trade_time_iso8601'].min()).strftime('%Y/%m/%d') + ' - ' + (data['entry_trade_time_iso8601'].max()).strftime('%Y/%m/%d') weekday = 'N/A' # calculate value for each metric trades = data['id'].count() if trades == 0: column = ['N/A'] * 41 + [timeframe, weekday] + ['N/A'] * 4 else: total_volume_asset = data['total_volume_asset'].sum() total_volume_dollar = data['total_volume_dollar'].sum() spread_profit = data['profit_dollar'].sum() fee_rebate = data['fee_rebate'].sum() fee_paid = data['fee_paid'].sum() net_profit = data['total_revenue'].sum() profitable = data[data['total_revenue']>0].count()['id'] profitable_percent = profitable / trades unprofitable = data[data['total_revenue']<0].count()['id'] unprofitable_percent = unprofitable / trades both_sides_maker = data[data['market_made_type']=='both sides maker'].count()['id'] both_sides_maker_percent = both_sides_maker / trades entry_maker = data[data['market_made_type']=='entry maker'].count()['id'] entry_maker_percent = entry_maker / trades exit_maker = data[data['market_made_type']=='exit maker'].count()['id'] exit_maker_percent = exit_maker / trades both_sides_taker = data[data['market_made_type']=='both sides taker'].count()['id'] both_sides_taker_percent = both_sides_taker / trades maker_trade = data[data['market_made_type']!='both sides taker'].count()['id'] maker_trade_percent = maker_trade / trades taker_trade = both_sides_taker taker_trade_percent = both_sides_taker_percent maker_order = data[data['entry_trade_maker']==True].count()['id'] + data[data['exit_trade_maker']==True].count()['id'] maker_order_percent = maker_order / (trades * 2) maker_order_volume = data[data['entry_trade_maker']==True].sum()['entry_trade_size_dollar'] + data[data['exit_trade_maker']==True].sum()['exit_trade_size_dollar'] taker_order = data[data['entry_trade_maker']==False].count()['id'] + data[data['exit_trade_maker']==False].count()['id'] taker_order_percent = taker_order / (trades * 2) taker_order_volume = data[data['entry_trade_maker']==False].sum()['entry_trade_size_dollar'] + data[data['exit_trade_maker']==False].sum()['exit_trade_size_dollar'] long_trade = data[data['long']==True].count()['id'] long_trade_percent = long_trade / trades short_trade = data[data['long']==False].count()['id'] short_trade_percent = short_trade / trades entry_limit_order = data[data['entry_trade_order_type']=='LIMIT'].count()['id'] entry_limit_order_percent = entry_limit_order / trades entry_market_order = data[data['entry_trade_order_type']=='MARKET'].count()['id'] entry_market_order_percent = entry_market_order / trades exit_limit_order = data[data['exit_trade_order_type']=='LIMIT'].count()['id'] exit_limit_order_percent = exit_limit_order / trades exit_market_order = data[data['exit_trade_order_type']=='MARKET'].count()['id'] exit_market_order_percent = exit_market_order / trades avg_order_size_asset = data['entry_trade_size_asset'].mean() avg_order_size_dollar = data['total_volume_dollar'].mean() / 2 win_trades_avg_hold_time = data[data['profit_dollar']>0].mean()['hold_time'] lose_trades_avg_hold_time = data[data['profit_dollar']<0].mean()['hold_time'] # put all values in a list column = [trades, total_volume_asset, total_volume_dollar, spread_profit, fee_rebate, fee_paid, net_profit, profitable, profitable_percent, unprofitable, unprofitable_percent, both_sides_maker, both_sides_maker_percent, entry_maker, entry_maker_percent, exit_maker, exit_maker_percent, both_sides_taker, both_sides_taker_percent, maker_trade, maker_trade_percent, taker_trade, taker_trade_percent, maker_order, maker_order_percent, maker_order_volume, taker_order, taker_order_percent, taker_order_volume, long_trade, long_trade_percent, short_trade, short_trade_percent, entry_limit_order, entry_limit_order_percent, entry_market_order, entry_market_order_percent, exit_limit_order, exit_limit_order_percent, exit_market_order, exit_market_order_percent, avg_order_size_asset, avg_order_size_dollar, win_trades_avg_hold_time, lose_trades_avg_hold_time, timeframe, weekday] return column def creat_mmlevel_dash(df): ''' create and return the mmlevel dashboard table with data from df ''' dash = pd.DataFrame(columns=['position', 'mm_level', 'total_trades', 'win_trades', 'win_rate', 'both_sides_maker', 'spread','rebate','fee_paid', 'revenue_per_level', 'win_trades_avg_holdtime_per_level', 'lose_trades_avg_holdtime_per_level', 'win_trades_avg_holdtime_per_side', 'lose_trades_avg_holdtime_per_side', 'revenue_per_side', 'total_revenue']) dash.position = ['long'] * 5 + ['short'] * 5 dash.mm_level = [4, 3, 2, 1, 0, 0, 1, 2, 3, 4] # loop fill per level values for i in range(10): dash.loc[i] = fill_mmlevel_row(df, dash.loc[i].position, dash.loc[i].mm_level) # print(dash.loc[i]) # calculate and fill per side value dash.win_trades_avg_holdtime_per_side.loc[dash.position == 'long'] = dash[dash.position == 'long'].mean()['win_trades_avg_holdtime_per_level'] dash.win_trades_avg_holdtime_per_side.loc[dash.position == 'short'] = dash[dash.position == 'short'].mean()['win_trades_avg_holdtime_per_level'] dash.lose_trades_avg_holdtime_per_side.loc[dash.position == 'long'] = dash[dash.position == 'long'].mean()['lose_trades_avg_holdtime_per_level'] dash.lose_trades_avg_holdtime_per_side.loc[dash.position == 'short'] = dash[dash.position == 'short'].mean()['lose_trades_avg_holdtime_per_level'] dash.revenue_per_side.loc[dash.position == 'long'] = dash[dash.position == 'long'].sum()['revenue_per_level'] dash.revenue_per_side.loc[dash.position == 'short'] = dash[dash.position == 'short'].sum()['revenue_per_level'] # calculate total revenue dash.total_revenue = dash['revenue_per_level'].sum() return dash def fill_mmlevel_row(df, position, level): ''' return a list of data for a specific row in the mmlevel_dash Dataframe from the df Dataframe df is the source data Dataframe, position is str ('long' or 'short'), level is int (0 - 4) ''' # create a subset of data with specific position and level if position == 'long': data = df[(df.long == True) & (df.market_making_level == level)] else: data = df[(df.long == False) & (df.market_making_level == level)] # calculate value for each metric (column) total_trades = data.count()['id'] if total_trades == 0: row = [0] * 10 + [''] * 4 else: win_trades = data[data.total_revenue > 0].count()['id'] win_rate = win_trades / total_trades both_sides_maker = data[data.market_made_type == 'both sides maker'].count()['id'] spread = data.profit_dollar.sum() rebates = data.fee_rebate.sum() fee_paid = data.fee_paid.sum() revenue_per_level = data.total_revenue.sum() win_trades_avg_holdtime_per_level = data[data.total_revenue > 0].mean()['hold_time'] lose_trades_avg_holdtime_per_level = data[data.total_revenue < 0].mean()['hold_time'] # put all values in a list row = [position, level, total_trades, win_trades, win_rate, both_sides_maker, spread, rebates, fee_paid, revenue_per_level, win_trades_avg_holdtime_per_level, lose_trades_avg_holdtime_per_level] + [''] * 4 return row def flip_position(df): ''' return df with flipped trades position (opposite 'long' and 'profit_dollar') ''' for i, r in df.iterrows(): df['long'][i] = not r['long'] df['profit_dollar'][i] = - (r['profit_dollar']) return df def trade_limit_analysis(df, parameter): ''' ''' # create a subset of data with the specific parameter data = df[df.parameters == parameter] # calculate time range timerange = data.entry_trade_time_unix.max() - data.entry_trade_time_unix.min() period = timerange % 180 # calculate metrics for each 3 min period start = data.entry_trade_time_unix.min() end = start + 180 trade_limit = [] for i in range(period): trade_count = data[(data['entry_trade_time_unix'] >= start) & (data['entry_trade_time_unix'] < end)].count()['id'] start = end end += 180 print(trade_count) trade_limit.append(trade_count) def main(): ''' open json input file and convert to df ''' with open('fin dashboard/data.json') as f: data = json.load(f) df = pd.read_json(data) ''' process file and export dash to json ''' df = clean_data(df) # df.to_csv('fin dashboard/clean_data.csv') # print(df.parameters.unique()) # fin_dash = create_fin_dash(df) # dash.to_json('fin dashboard/fin_dash_data.json') # print(fin_dash) # mm_dash = creat_mmlevel_dash(df) # mm_dash.to_json('fin dashboard/mm_dash.json') # print(mm_dash) # flip = flip_position(df) # print(flip.long) trade_limit_analysis(df, 'bid-3-1-0.01-300-0.0003-5.0-0.0005-15-True') if __name__ == "__main__": main()
dashboard/fin_dash.py<gh_stars>0 import pandas as pd import json from datetime import datetime, timedelta def clean_data(df): ''' filter and edit raw data into clean data ''' # filter out rows where entry_trade_size_asset != exit_trade_size_asset; entry_trade_size_dollar = 0; exit_trade_size_dollar = 0 df = df[df.entry_trade_size_asset == df.exit_trade_size_asset] df = df[df.entry_trade_size_dollar != 0] df = df[df.exit_trade_size_dollar != 0] # convert time columns to datetime object df['entry_trade_time_iso8601'] = pd.to_datetime(df['entry_trade_time_iso8601']) df['exit_trade_time_iso8601'] = pd.to_datetime(df['exit_trade_time_iso8601']) # add market_made_type df['market_made_type'] = df.apply(mm_condition, axis='columns') # add hold time (seconds) df['hold_time'] = df.exit_trade_time_unix - df.entry_trade_time_unix return df def mm_condition(df): ''' apply condition for market_made_type ''' if df.entry_trade_maker == True: if df.exit_trade_maker == True: return 'both sides maker' else: return 'entry maker' else: if df.exit_trade_maker == True: return 'exit maker' else: return 'both sides taker' def create_fin_dash(df): ''' create and return the fin dashboard table with data from df ''' # create table frame dash = pd.DataFrame(columns=['metric', 'value_type', 'total', 'today', 'yesterday', 'day-3', 'day-4', 'day-5', 'day-6', 'day-7', 'this_week', 'last_week', 'week-3', 'week-4', 'this_month', 'last_month']) dash.metric = ['trades', 'trade volume asset', 'trade volume dollar', 'spread profit', 'fee rebate', 'fee paid', 'net profit', 'profitable trades', 'profitable trades', 'unprofitable trades', 'unprofitable trades', 'both sides maker', 'both sides maker', 'entry maker only', 'entry maker only', 'exit maker only', 'exit maker only', 'both sides taker', 'both sides taker', 'maker trade', 'maker trade', 'taker trade', 'taker trade', 'maker order', 'maker order', 'maker order volume', 'taker order', 'taker order', 'taker order volume', 'long trade', 'long trade', 'short trade', 'short trade', 'entry limit order', 'entry limit order', 'entry market order', 'entry market order', 'exit limit order', 'exit limit order', 'exit market order', 'exit market order', 'avg order size asset', 'avg order size dollar', 'win trades avg hold time', 'lose trades avg hold time', 'timeframe', 'weekday'] dash.value_type = ['value', 'value', 'value', 'value', 'value', 'value', 'value', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'value', 'percentage', 'value', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'percentage', 'value', 'value', 'value', 'value', 'str', 'str'] # fill table columns # get utc today 00:00 now = datetime.utcnow().strftime('%Y-%m-%d') today_start = datetime.strptime(now+' 00:00:00', '%Y-%m-%d %H:%M:%S') # total dash.total = fill_findash_column(df) # loop fill today to day-7 start = today_start end = None for column in dash[['today', 'yesterday', 'day-3', 'day-4', 'day-5', 'day-6', 'day-7']]: dash[column] = fill_findash_column(df, start_date=start, end_date=end, col_type='day') end = start start -= timedelta(days=1) # loop fill this week to week-4 wd_today = today_start.weekday() #weekday today (int, 0=Mon, 7=Sun) start = today_start - timedelta(days=wd_today) end = None for column in dash[['this_week', 'last_week', 'week-3', 'week-4']]: dash[column] = fill_findash_column(df, start_date=start, end_date=end, col_type='week') end = start start -= timedelta(weeks=1) # loop fill this month to last month start = today_start.replace(day=1) end = None for column in dash[['this_month', 'last_month']]: dash[column] = fill_findash_column(df, start_date=start, end_date=end, col_type='month') end = start last_day_prev_month = start - timedelta(days=1) start = last_day_prev_month.replace(day=1) return dash def fill_findash_column(df, start_date=None, end_date=None, col_type=None): ''' return a list of data for a specific column in the fin_dash Dataframe from the df Dataframe df is the source data Dataframe, start_date and end_date filter data within this date range (default is None), col_type is type of this column (str: day, week, or month) ''' # create a subset of data within the time range if start_date and end_date: data = df[(df.entry_trade_time_iso8601 >= start_date) & (df.entry_trade_time_iso8601 < end_date)] elif start_date: data = df[(df.entry_trade_time_iso8601 >= start_date)] else: data = df.copy() # date range and day of week if col_type == 'day': timeframe = start_date.strftime('%Y/%m/%d') wd = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] weekday = wd[start_date.weekday()] elif col_type == 'week': timeframe = start_date.strftime('%Y/%m/%d') + ' - ' + (start_date + timedelta(days=6)).strftime('%Y/%m/%d') weekday = 'N/A' elif col_type == 'month': timeframe = start_date.strftime('%Y/%m') weekday = 'N/A' else: timeframe = (data['entry_trade_time_iso8601'].min()).strftime('%Y/%m/%d') + ' - ' + (data['entry_trade_time_iso8601'].max()).strftime('%Y/%m/%d') weekday = 'N/A' # calculate value for each metric trades = data['id'].count() if trades == 0: column = ['N/A'] * 41 + [timeframe, weekday] + ['N/A'] * 4 else: total_volume_asset = data['total_volume_asset'].sum() total_volume_dollar = data['total_volume_dollar'].sum() spread_profit = data['profit_dollar'].sum() fee_rebate = data['fee_rebate'].sum() fee_paid = data['fee_paid'].sum() net_profit = data['total_revenue'].sum() profitable = data[data['total_revenue']>0].count()['id'] profitable_percent = profitable / trades unprofitable = data[data['total_revenue']<0].count()['id'] unprofitable_percent = unprofitable / trades both_sides_maker = data[data['market_made_type']=='both sides maker'].count()['id'] both_sides_maker_percent = both_sides_maker / trades entry_maker = data[data['market_made_type']=='entry maker'].count()['id'] entry_maker_percent = entry_maker / trades exit_maker = data[data['market_made_type']=='exit maker'].count()['id'] exit_maker_percent = exit_maker / trades both_sides_taker = data[data['market_made_type']=='both sides taker'].count()['id'] both_sides_taker_percent = both_sides_taker / trades maker_trade = data[data['market_made_type']!='both sides taker'].count()['id'] maker_trade_percent = maker_trade / trades taker_trade = both_sides_taker taker_trade_percent = both_sides_taker_percent maker_order = data[data['entry_trade_maker']==True].count()['id'] + data[data['exit_trade_maker']==True].count()['id'] maker_order_percent = maker_order / (trades * 2) maker_order_volume = data[data['entry_trade_maker']==True].sum()['entry_trade_size_dollar'] + data[data['exit_trade_maker']==True].sum()['exit_trade_size_dollar'] taker_order = data[data['entry_trade_maker']==False].count()['id'] + data[data['exit_trade_maker']==False].count()['id'] taker_order_percent = taker_order / (trades * 2) taker_order_volume = data[data['entry_trade_maker']==False].sum()['entry_trade_size_dollar'] + data[data['exit_trade_maker']==False].sum()['exit_trade_size_dollar'] long_trade = data[data['long']==True].count()['id'] long_trade_percent = long_trade / trades short_trade = data[data['long']==False].count()['id'] short_trade_percent = short_trade / trades entry_limit_order = data[data['entry_trade_order_type']=='LIMIT'].count()['id'] entry_limit_order_percent = entry_limit_order / trades entry_market_order = data[data['entry_trade_order_type']=='MARKET'].count()['id'] entry_market_order_percent = entry_market_order / trades exit_limit_order = data[data['exit_trade_order_type']=='LIMIT'].count()['id'] exit_limit_order_percent = exit_limit_order / trades exit_market_order = data[data['exit_trade_order_type']=='MARKET'].count()['id'] exit_market_order_percent = exit_market_order / trades avg_order_size_asset = data['entry_trade_size_asset'].mean() avg_order_size_dollar = data['total_volume_dollar'].mean() / 2 win_trades_avg_hold_time = data[data['profit_dollar']>0].mean()['hold_time'] lose_trades_avg_hold_time = data[data['profit_dollar']<0].mean()['hold_time'] # put all values in a list column = [trades, total_volume_asset, total_volume_dollar, spread_profit, fee_rebate, fee_paid, net_profit, profitable, profitable_percent, unprofitable, unprofitable_percent, both_sides_maker, both_sides_maker_percent, entry_maker, entry_maker_percent, exit_maker, exit_maker_percent, both_sides_taker, both_sides_taker_percent, maker_trade, maker_trade_percent, taker_trade, taker_trade_percent, maker_order, maker_order_percent, maker_order_volume, taker_order, taker_order_percent, taker_order_volume, long_trade, long_trade_percent, short_trade, short_trade_percent, entry_limit_order, entry_limit_order_percent, entry_market_order, entry_market_order_percent, exit_limit_order, exit_limit_order_percent, exit_market_order, exit_market_order_percent, avg_order_size_asset, avg_order_size_dollar, win_trades_avg_hold_time, lose_trades_avg_hold_time, timeframe, weekday] return column def creat_mmlevel_dash(df): ''' create and return the mmlevel dashboard table with data from df ''' dash = pd.DataFrame(columns=['position', 'mm_level', 'total_trades', 'win_trades', 'win_rate', 'both_sides_maker', 'spread','rebate','fee_paid', 'revenue_per_level', 'win_trades_avg_holdtime_per_level', 'lose_trades_avg_holdtime_per_level', 'win_trades_avg_holdtime_per_side', 'lose_trades_avg_holdtime_per_side', 'revenue_per_side', 'total_revenue']) dash.position = ['long'] * 5 + ['short'] * 5 dash.mm_level = [4, 3, 2, 1, 0, 0, 1, 2, 3, 4] # loop fill per level values for i in range(10): dash.loc[i] = fill_mmlevel_row(df, dash.loc[i].position, dash.loc[i].mm_level) # print(dash.loc[i]) # calculate and fill per side value dash.win_trades_avg_holdtime_per_side.loc[dash.position == 'long'] = dash[dash.position == 'long'].mean()['win_trades_avg_holdtime_per_level'] dash.win_trades_avg_holdtime_per_side.loc[dash.position == 'short'] = dash[dash.position == 'short'].mean()['win_trades_avg_holdtime_per_level'] dash.lose_trades_avg_holdtime_per_side.loc[dash.position == 'long'] = dash[dash.position == 'long'].mean()['lose_trades_avg_holdtime_per_level'] dash.lose_trades_avg_holdtime_per_side.loc[dash.position == 'short'] = dash[dash.position == 'short'].mean()['lose_trades_avg_holdtime_per_level'] dash.revenue_per_side.loc[dash.position == 'long'] = dash[dash.position == 'long'].sum()['revenue_per_level'] dash.revenue_per_side.loc[dash.position == 'short'] = dash[dash.position == 'short'].sum()['revenue_per_level'] # calculate total revenue dash.total_revenue = dash['revenue_per_level'].sum() return dash def fill_mmlevel_row(df, position, level): ''' return a list of data for a specific row in the mmlevel_dash Dataframe from the df Dataframe df is the source data Dataframe, position is str ('long' or 'short'), level is int (0 - 4) ''' # create a subset of data with specific position and level if position == 'long': data = df[(df.long == True) & (df.market_making_level == level)] else: data = df[(df.long == False) & (df.market_making_level == level)] # calculate value for each metric (column) total_trades = data.count()['id'] if total_trades == 0: row = [0] * 10 + [''] * 4 else: win_trades = data[data.total_revenue > 0].count()['id'] win_rate = win_trades / total_trades both_sides_maker = data[data.market_made_type == 'both sides maker'].count()['id'] spread = data.profit_dollar.sum() rebates = data.fee_rebate.sum() fee_paid = data.fee_paid.sum() revenue_per_level = data.total_revenue.sum() win_trades_avg_holdtime_per_level = data[data.total_revenue > 0].mean()['hold_time'] lose_trades_avg_holdtime_per_level = data[data.total_revenue < 0].mean()['hold_time'] # put all values in a list row = [position, level, total_trades, win_trades, win_rate, both_sides_maker, spread, rebates, fee_paid, revenue_per_level, win_trades_avg_holdtime_per_level, lose_trades_avg_holdtime_per_level] + [''] * 4 return row def flip_position(df): ''' return df with flipped trades position (opposite 'long' and 'profit_dollar') ''' for i, r in df.iterrows(): df['long'][i] = not r['long'] df['profit_dollar'][i] = - (r['profit_dollar']) return df def trade_limit_analysis(df, parameter): ''' ''' # create a subset of data with the specific parameter data = df[df.parameters == parameter] # calculate time range timerange = data.entry_trade_time_unix.max() - data.entry_trade_time_unix.min() period = timerange % 180 # calculate metrics for each 3 min period start = data.entry_trade_time_unix.min() end = start + 180 trade_limit = [] for i in range(period): trade_count = data[(data['entry_trade_time_unix'] >= start) & (data['entry_trade_time_unix'] < end)].count()['id'] start = end end += 180 print(trade_count) trade_limit.append(trade_count) def main(): ''' open json input file and convert to df ''' with open('fin dashboard/data.json') as f: data = json.load(f) df = pd.read_json(data) ''' process file and export dash to json ''' df = clean_data(df) # df.to_csv('fin dashboard/clean_data.csv') # print(df.parameters.unique()) # fin_dash = create_fin_dash(df) # dash.to_json('fin dashboard/fin_dash_data.json') # print(fin_dash) # mm_dash = creat_mmlevel_dash(df) # mm_dash.to_json('fin dashboard/mm_dash.json') # print(mm_dash) # flip = flip_position(df) # print(flip.long) trade_limit_analysis(df, 'bid-3-1-0.01-300-0.0003-5.0-0.0005-15-True') if __name__ == "__main__": main()
en
0.524126
filter and edit raw data into clean data # filter out rows where entry_trade_size_asset != exit_trade_size_asset; entry_trade_size_dollar = 0; exit_trade_size_dollar = 0 # convert time columns to datetime object # add market_made_type # add hold time (seconds) apply condition for market_made_type create and return the fin dashboard table with data from df # create table frame # fill table columns # get utc today 00:00 # total # loop fill today to day-7 # loop fill this week to week-4 #weekday today (int, 0=Mon, 7=Sun) # loop fill this month to last month return a list of data for a specific column in the fin_dash Dataframe from the df Dataframe df is the source data Dataframe, start_date and end_date filter data within this date range (default is None), col_type is type of this column (str: day, week, or month) # create a subset of data within the time range # date range and day of week # calculate value for each metric # put all values in a list create and return the mmlevel dashboard table with data from df # loop fill per level values # print(dash.loc[i]) # calculate and fill per side value # calculate total revenue return a list of data for a specific row in the mmlevel_dash Dataframe from the df Dataframe df is the source data Dataframe, position is str ('long' or 'short'), level is int (0 - 4) # create a subset of data with specific position and level # calculate value for each metric (column) # put all values in a list return df with flipped trades position (opposite 'long' and 'profit_dollar') # create a subset of data with the specific parameter # calculate time range # calculate metrics for each 3 min period open json input file and convert to df process file and export dash to json # df.to_csv('fin dashboard/clean_data.csv') # print(df.parameters.unique()) # fin_dash = create_fin_dash(df) # dash.to_json('fin dashboard/fin_dash_data.json') # print(fin_dash) # mm_dash = creat_mmlevel_dash(df) # mm_dash.to_json('fin dashboard/mm_dash.json') # print(mm_dash) # flip = flip_position(df) # print(flip.long)
2.902232
3
NLP/Text/topic_modeler.py
KzlvA/STT-TTS-LM-Toolkit
1
6625053
from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer from gensim import models, corpora # Load input data def load_data(input_file): data = [] with open(input_file, 'r') as f: for line in f.readlines(): data.append(line[:-1]) return data # Processor function for tokenizing, removing stop # words, and stemming def process(input_text): # Create a regular expression tokenizer tokenizer = RegexpTokenizer(r'\w+') # Create a Snowball stemmer stemmer = SnowballStemmer('english') # Get the list of stop words stop_words = stopwords.words('english') # Tokenize the input string tokens = tokenizer.tokenize(input_text.lower()) # Remove the stop words tokens = [x for x in tokens if not x in stop_words] # Perform stemming on the tokenized words tokens_stemmed = [stemmer.stem(x) for x in tokens] return tokens_stemmed if __name__=='__main__': # Load input data data = load_data('data.txt') # Create a list for sentence tokens tokens = [process(x) for x in data] # Create a dictionary based on the sentence tokens dict_tokens = corpora.Dictionary(tokens) # Create a document-term matrix doc_term_mat = [dict_tokens.doc2bow(token) for token in tokens] # Define the number of topics for the LDA model num_topics = 2 # Generate the LDA model ldamodel = models.ldamodel.LdaModel(doc_term_mat, num_topics=num_topics, id2word=dict_tokens, passes=25) num_words = 5 print('\nTop ' + str(num_words) + ' contributing words to each topic:') for item in ldamodel.print_topics(num_topics=num_topics, num_words=num_words): print('\nTopic', item[0]) # Print the contributing words along with their relative contributions list_of_strings = item[1].split(' + ') for text in list_of_strings: weight = text.split('*')[0] word = text.split('*')[1] print(word, '==>', str(round(float(weight) * 100, 2)) + '%')
from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer from gensim import models, corpora # Load input data def load_data(input_file): data = [] with open(input_file, 'r') as f: for line in f.readlines(): data.append(line[:-1]) return data # Processor function for tokenizing, removing stop # words, and stemming def process(input_text): # Create a regular expression tokenizer tokenizer = RegexpTokenizer(r'\w+') # Create a Snowball stemmer stemmer = SnowballStemmer('english') # Get the list of stop words stop_words = stopwords.words('english') # Tokenize the input string tokens = tokenizer.tokenize(input_text.lower()) # Remove the stop words tokens = [x for x in tokens if not x in stop_words] # Perform stemming on the tokenized words tokens_stemmed = [stemmer.stem(x) for x in tokens] return tokens_stemmed if __name__=='__main__': # Load input data data = load_data('data.txt') # Create a list for sentence tokens tokens = [process(x) for x in data] # Create a dictionary based on the sentence tokens dict_tokens = corpora.Dictionary(tokens) # Create a document-term matrix doc_term_mat = [dict_tokens.doc2bow(token) for token in tokens] # Define the number of topics for the LDA model num_topics = 2 # Generate the LDA model ldamodel = models.ldamodel.LdaModel(doc_term_mat, num_topics=num_topics, id2word=dict_tokens, passes=25) num_words = 5 print('\nTop ' + str(num_words) + ' contributing words to each topic:') for item in ldamodel.print_topics(num_topics=num_topics, num_words=num_words): print('\nTopic', item[0]) # Print the contributing words along with their relative contributions list_of_strings = item[1].split(' + ') for text in list_of_strings: weight = text.split('*')[0] word = text.split('*')[1] print(word, '==>', str(round(float(weight) * 100, 2)) + '%')
en
0.711009
# Load input data # Processor function for tokenizing, removing stop # words, and stemming # Create a regular expression tokenizer # Create a Snowball stemmer # Get the list of stop words # Tokenize the input string # Remove the stop words # Perform stemming on the tokenized words # Load input data # Create a list for sentence tokens # Create a dictionary based on the sentence tokens # Create a document-term matrix # Define the number of topics for the LDA model # Generate the LDA model # Print the contributing words along with their relative contributions
3.297028
3
src/foremast/utils/banners.py
dnava013/foremast
157
6625054
<gh_stars>100-1000 # Foremast - Pipeline Tooling # # Copyright 2018 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Prints a banner. Example: ================================================================================ Create Security Group ================================================================================ """ import logging LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) def banner(text, border='=', width=80): """Center _text_ in a banner _width_ wide with _border_ characters. Args: text (str): What to write in the banner border (str): Border character width (int): How long the border should be """ text_padding = '{0:^%d}' % (width) LOG.info(border * width) LOG.info(text_padding.format(text)) LOG.info(border * width)
# Foremast - Pipeline Tooling # # Copyright 2018 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Prints a banner. Example: ================================================================================ Create Security Group ================================================================================ """ import logging LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) def banner(text, border='=', width=80): """Center _text_ in a banner _width_ wide with _border_ characters. Args: text (str): What to write in the banner border (str): Border character width (int): How long the border should be """ text_padding = '{0:^%d}' % (width) LOG.info(border * width) LOG.info(text_padding.format(text)) LOG.info(border * width)
en
0.752494
# Foremast - Pipeline Tooling # # Copyright 2018 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Prints a banner. Example: ================================================================================ Create Security Group ================================================================================ Center _text_ in a banner _width_ wide with _border_ characters. Args: text (str): What to write in the banner border (str): Border character width (int): How long the border should be
2.411733
2
eqcharinfo/controllers/charfile_ingest.py
Preocts/eqcharinfo
0
6625055
"""Controller for ingest and parsing of character files""" import logging import re from configparser import ConfigParser from pathlib import Path class CharfileIngest: HEADER_PATTERN = r"\bLocation\sName\sID\sCount\sSlots\b" ROW_PATTERN = r"^.*?\s.*?\s[0-9]*?\s[0-9]*?\s[0-9]*?$" def __init__(self, config: ConfigParser) -> None: self.log = logging.getLogger(__name__) self.config = config self.filepath = Path(config["CHARACTERS"]["file_path"]).absolute() self._charfile: dict[str, str] = {"filename": "", "content": ""} def process_webform(self, webform_content: str) -> dict[str, str]: """Returns filename:content on success, empty dict on failure""" filename = self.extract_filename(webform_content) content = self.extract_content(webform_content) charfile = {"filename": filename, "content": content} self._charfile = charfile return self._charfile.copy() if filename and content else {"error": "Invalid"} def extract_filename(self, webform_content: str) -> str: """Extract filename from webform, returns empty string on failure""" result = re.search(r'filename="(.*?)"', webform_content) return self._rpl_spaces(result.group(1)) if result is not None else "" def extract_content(self, webform_content: str) -> str: """Extract file body from webform, returns empty string on failure""" headers = re.findall(self.HEADER_PATTERN, webform_content) rows: list[str] = [] for line in webform_content.split("\n"): if re.match(self.ROW_PATTERN, line): rows.append(line) if not headers or not rows: return "" rows.insert(0, headers[0]) return "\n".join(rows) def save_to_file(self) -> bool: """Saves loaded charfile(s) to disk""" try: with open(self.filepath / self._charfile["filename"], "w") as outfile: outfile.write(self._charfile["content"]) except OSError as err: self.log.error("Failed to save '%s' : %s", self._charfile["filename"], err) return False return True @staticmethod def _rpl_spaces(string: str) -> str: """Replaces spaces with underscores""" string = re.sub(r"\s", "_", string.strip()) return re.sub(r"_-_", "-", string)
"""Controller for ingest and parsing of character files""" import logging import re from configparser import ConfigParser from pathlib import Path class CharfileIngest: HEADER_PATTERN = r"\bLocation\sName\sID\sCount\sSlots\b" ROW_PATTERN = r"^.*?\s.*?\s[0-9]*?\s[0-9]*?\s[0-9]*?$" def __init__(self, config: ConfigParser) -> None: self.log = logging.getLogger(__name__) self.config = config self.filepath = Path(config["CHARACTERS"]["file_path"]).absolute() self._charfile: dict[str, str] = {"filename": "", "content": ""} def process_webform(self, webform_content: str) -> dict[str, str]: """Returns filename:content on success, empty dict on failure""" filename = self.extract_filename(webform_content) content = self.extract_content(webform_content) charfile = {"filename": filename, "content": content} self._charfile = charfile return self._charfile.copy() if filename and content else {"error": "Invalid"} def extract_filename(self, webform_content: str) -> str: """Extract filename from webform, returns empty string on failure""" result = re.search(r'filename="(.*?)"', webform_content) return self._rpl_spaces(result.group(1)) if result is not None else "" def extract_content(self, webform_content: str) -> str: """Extract file body from webform, returns empty string on failure""" headers = re.findall(self.HEADER_PATTERN, webform_content) rows: list[str] = [] for line in webform_content.split("\n"): if re.match(self.ROW_PATTERN, line): rows.append(line) if not headers or not rows: return "" rows.insert(0, headers[0]) return "\n".join(rows) def save_to_file(self) -> bool: """Saves loaded charfile(s) to disk""" try: with open(self.filepath / self._charfile["filename"], "w") as outfile: outfile.write(self._charfile["content"]) except OSError as err: self.log.error("Failed to save '%s' : %s", self._charfile["filename"], err) return False return True @staticmethod def _rpl_spaces(string: str) -> str: """Replaces spaces with underscores""" string = re.sub(r"\s", "_", string.strip()) return re.sub(r"_-_", "-", string)
en
0.670484
Controller for ingest and parsing of character files Returns filename:content on success, empty dict on failure Extract filename from webform, returns empty string on failure Extract file body from webform, returns empty string on failure Saves loaded charfile(s) to disk Replaces spaces with underscores
2.975686
3
custom_components/kia_uvo/config_flow.py
ManCaveMedia/kia_uvo
0
6625056
<filename>custom_components/kia_uvo/config_flow.py import logging import voluptuous as vol import uuid import requests from urllib.parse import parse_qs, urlparse from homeassistant import config_entries from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, CONF_UNIT_OF_MEASUREMENT, CONF_UNIT_SYSTEM from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from .const import * from .Token import Token from .KiaUvoApi import KiaUvoApi _LOGGER = logging.getLogger(__name__) class KiaUvoOptionFlowHandler(config_entries.OptionsFlow): def __init__(self, config_entry): self.config_entry = config_entry self.schema = vol.Schema( { vol.Optional(CONF_UNIT_OF_MEASUREMENT, default = self.config_entry.options.get(CONF_UNIT_OF_MEASUREMENT, DEFAULT_DISTANCE_UNIT)): vol.In(DISTANCE_UNITS), vol.Optional(CONF_SCAN_INTERVAL, default = self.config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)): vol.All(vol.Coerce(int), vol.Range(min=1, max=999)), vol.Optional(CONF_FORCE_SCAN_INTERVAL, default = self.config_entry.options.get(CONF_FORCE_SCAN_INTERVAL, DEFAULT_FORCE_SCAN_INTERVAL)): vol.All(vol.Coerce(int), vol.Range(min=1, max=999)), vol.Optional(CONF_NO_FORCE_SCAN_HOUR_START, default = self.config_entry.options.get(CONF_NO_FORCE_SCAN_HOUR_START, DEFAULT_NO_FORCE_SCAN_HOUR_START)): vol.All(vol.Coerce(int), vol.Range(min=1, max=23)), vol.Optional(CONF_NO_FORCE_SCAN_HOUR_FINISH, default = self.config_entry.options.get(CONF_NO_FORCE_SCAN_HOUR_FINISH, DEFAULT_NO_FORCE_SCAN_HOUR_FINISH)): vol.All(vol.Coerce(int), vol.Range(min=1, max=23)), } ) async def async_step_init(self, user_input = None): if user_input is not None: _LOGGER.debug(f"{DOMAIN} user input in option flow : %s", user_input) return self.async_create_entry(title = "", data = user_input) return self.async_show_form(step_id = "init", data_schema = self.schema) class KiaUvoConfigFlowHandler(config_entries.ConfigFlow, domain = DOMAIN): VERSION = CONFIG_FLOW_VERSION CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL @staticmethod @callback def async_get_options_flow(config_entry): return KiaUvoOptionFlowHandler(config_entry) def __init__(self): self.schema = vol.Schema( { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str } ) self.kia_uvo_api = None self.token = None async def async_step_user(self, user_input = None): await self.async_set_unique_id(DOMAIN) self._abort_if_unique_id_configured() errors = None if user_input is not None: username = user_input[CONF_USERNAME] password = user_input[CONF_PASSWORD] self.kia_uvo_api = KiaUvoApi(username, password) try: self.token = await self.hass.async_add_executor_job(self.kia_uvo_api.login) return self.async_create_entry( title = username, data = { CONF_USERNAME: username, CONF_PASSWORD: password, CONF_STORED_CREDENTIALS: vars(self.token), } ) except Exception as ex: _LOGGER.error(f"{DOMAIN} Exception in kia_uvo login : %s", str(ex)) errors = {"base": "auth"} return self.async_show_form(step_id = "user", data_schema = self.schema, errors = errors)
<filename>custom_components/kia_uvo/config_flow.py import logging import voluptuous as vol import uuid import requests from urllib.parse import parse_qs, urlparse from homeassistant import config_entries from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, CONF_UNIT_OF_MEASUREMENT, CONF_UNIT_SYSTEM from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from .const import * from .Token import Token from .KiaUvoApi import KiaUvoApi _LOGGER = logging.getLogger(__name__) class KiaUvoOptionFlowHandler(config_entries.OptionsFlow): def __init__(self, config_entry): self.config_entry = config_entry self.schema = vol.Schema( { vol.Optional(CONF_UNIT_OF_MEASUREMENT, default = self.config_entry.options.get(CONF_UNIT_OF_MEASUREMENT, DEFAULT_DISTANCE_UNIT)): vol.In(DISTANCE_UNITS), vol.Optional(CONF_SCAN_INTERVAL, default = self.config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)): vol.All(vol.Coerce(int), vol.Range(min=1, max=999)), vol.Optional(CONF_FORCE_SCAN_INTERVAL, default = self.config_entry.options.get(CONF_FORCE_SCAN_INTERVAL, DEFAULT_FORCE_SCAN_INTERVAL)): vol.All(vol.Coerce(int), vol.Range(min=1, max=999)), vol.Optional(CONF_NO_FORCE_SCAN_HOUR_START, default = self.config_entry.options.get(CONF_NO_FORCE_SCAN_HOUR_START, DEFAULT_NO_FORCE_SCAN_HOUR_START)): vol.All(vol.Coerce(int), vol.Range(min=1, max=23)), vol.Optional(CONF_NO_FORCE_SCAN_HOUR_FINISH, default = self.config_entry.options.get(CONF_NO_FORCE_SCAN_HOUR_FINISH, DEFAULT_NO_FORCE_SCAN_HOUR_FINISH)): vol.All(vol.Coerce(int), vol.Range(min=1, max=23)), } ) async def async_step_init(self, user_input = None): if user_input is not None: _LOGGER.debug(f"{DOMAIN} user input in option flow : %s", user_input) return self.async_create_entry(title = "", data = user_input) return self.async_show_form(step_id = "init", data_schema = self.schema) class KiaUvoConfigFlowHandler(config_entries.ConfigFlow, domain = DOMAIN): VERSION = CONFIG_FLOW_VERSION CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL @staticmethod @callback def async_get_options_flow(config_entry): return KiaUvoOptionFlowHandler(config_entry) def __init__(self): self.schema = vol.Schema( { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str } ) self.kia_uvo_api = None self.token = None async def async_step_user(self, user_input = None): await self.async_set_unique_id(DOMAIN) self._abort_if_unique_id_configured() errors = None if user_input is not None: username = user_input[CONF_USERNAME] password = user_input[CONF_PASSWORD] self.kia_uvo_api = KiaUvoApi(username, password) try: self.token = await self.hass.async_add_executor_job(self.kia_uvo_api.login) return self.async_create_entry( title = username, data = { CONF_USERNAME: username, CONF_PASSWORD: password, CONF_STORED_CREDENTIALS: vars(self.token), } ) except Exception as ex: _LOGGER.error(f"{DOMAIN} Exception in kia_uvo login : %s", str(ex)) errors = {"base": "auth"} return self.async_show_form(step_id = "user", data_schema = self.schema, errors = errors)
none
1
2.022416
2
MyExpenses/myexpenses/admin.py
mainyanim/MyExpenses
0
6625057
from django.contrib import admin from .models import * admin.site.register(Expense) admin.site.register(Note)
from django.contrib import admin from .models import * admin.site.register(Expense) admin.site.register(Note)
none
1
1.184669
1
core/views.py
dudonwai/dota_stats_py
0
6625058
from django.shortcuts import render from django.views.generic.base import TemplateView from django.views.generic.list import ListView from django.views.generic.detail import DetailView import core.models as coremodels # Landing Page for Index class LandingView(TemplateView): template_name = "blog/index.html" # Template for About, Archive, Contact class BasicView(TemplateView): template_name = "themes/basic.html"
from django.shortcuts import render from django.views.generic.base import TemplateView from django.views.generic.list import ListView from django.views.generic.detail import DetailView import core.models as coremodels # Landing Page for Index class LandingView(TemplateView): template_name = "blog/index.html" # Template for About, Archive, Contact class BasicView(TemplateView): template_name = "themes/basic.html"
en
0.701073
# Landing Page for Index # Template for About, Archive, Contact
1.589244
2
MMMaker/app/memes/migrations/0003_auto_20200616_1316.py
C4Ution/MMMaker
9
6625059
# Generated by Django 2.2.12 on 2020-06-16 13:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('memes', '0002_auto_20200616_1314'), ] operations = [ migrations.RenameField( model_name='taskresource', old_name='url', new_name='access_key', ), ]
# Generated by Django 2.2.12 on 2020-06-16 13:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('memes', '0002_auto_20200616_1314'), ] operations = [ migrations.RenameField( model_name='taskresource', old_name='url', new_name='access_key', ), ]
en
0.725987
# Generated by Django 2.2.12 on 2020-06-16 13:16
1.532401
2
timestack/base.py
acomphealth/timestack
0
6625060
def math_func(x): return x + 1
def math_func(x): return x + 1
none
1
1.373162
1
version.py
NickBayard/MLH
0
6625061
__version__ = '1.1' if __name__ == '__main__': print('Version: {}'.format(__version__))
__version__ = '1.1' if __name__ == '__main__': print('Version: {}'.format(__version__))
none
1
1.565319
2
setup.py
joferkington/seismic_plotting
20
6625062
<reponame>joferkington/seismic_plotting from setuptools import setup setup( name = 'seismic_plotting', version = '0.1', description = "Cross Section Plotting with Geoprobe Datasets", author = '<NAME>', author_email = '<EMAIL>', license = 'LICENSE', install_requires = [ 'matplotlib >= 0.98', 'numpy >= 1.1', 'shapely >= 1.2', 'scipy >= 0.7', ] )
from setuptools import setup setup( name = 'seismic_plotting', version = '0.1', description = "Cross Section Plotting with Geoprobe Datasets", author = '<NAME>', author_email = '<EMAIL>', license = 'LICENSE', install_requires = [ 'matplotlib >= 0.98', 'numpy >= 1.1', 'shapely >= 1.2', 'scipy >= 0.7', ] )
none
1
1.15787
1
surl/helpers/log.py
LarryPavanery/surl
0
6625063
<reponame>LarryPavanery/surl # -*- encoding: utf-8 -*- ''' __author__ = "Larry_Pavanery ''' from datetime import datetime as dt import surl.helpers.shared as util class Log(object): def __init__(self, class_name): self.log_enable = util.log_enable() self.class_name = class_name def _print(self, level, content): if self.log_enable: print('[!][{}] [{}] {} - {}'.format(dt.now(), self.class_name.upper(), level, content)) def info(self, content): self._print('INFO', content) def warn(self, content): self._print('WARN', content) def debug(self, content): self._print('DEBUG', content)
# -*- encoding: utf-8 -*- ''' __author__ = "Larry_Pavanery ''' from datetime import datetime as dt import surl.helpers.shared as util class Log(object): def __init__(self, class_name): self.log_enable = util.log_enable() self.class_name = class_name def _print(self, level, content): if self.log_enable: print('[!][{}] [{}] {} - {}'.format(dt.now(), self.class_name.upper(), level, content)) def info(self, content): self._print('INFO', content) def warn(self, content): self._print('WARN', content) def debug(self, content): self._print('DEBUG', content)
en
0.661129
# -*- encoding: utf-8 -*- __author__ = "Larry_Pavanery
2.450597
2
neural_networks/get_new_weight_inc.py
Yao-Shao/Maching-Learning-only-with-Numpy
1
6625064
import numpy as np def get_new_weight_inc(weight_inc, weight, momW, wc, lr, weight_grad): ''' Get new increment weight, the update weight policy. inputs: weight_inc: old increment weights weight: old weights momW: weight momentum wc: weight decay lr: learning rate weight_grad: weight gradient outputs: weight_inc: new increment weights ''' weight_inc = momW * weight_inc - wc * lr * weight - lr * weight_grad return weight_inc
import numpy as np def get_new_weight_inc(weight_inc, weight, momW, wc, lr, weight_grad): ''' Get new increment weight, the update weight policy. inputs: weight_inc: old increment weights weight: old weights momW: weight momentum wc: weight decay lr: learning rate weight_grad: weight gradient outputs: weight_inc: new increment weights ''' weight_inc = momW * weight_inc - wc * lr * weight - lr * weight_grad return weight_inc
en
0.742485
Get new increment weight, the update weight policy. inputs: weight_inc: old increment weights weight: old weights momW: weight momentum wc: weight decay lr: learning rate weight_grad: weight gradient outputs: weight_inc: new increment weights
2.832914
3
neutron/agent/ovsdb/native/helpers.py
ISCAS-VDI/neutron-base
1
6625065
# Copyright (c) 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from neutron.agent.common import utils def _connection_to_manager_uri(conn_uri): proto, addr = conn_uri.split(':', 1) if ':' in addr: ip, port = addr.split(':', 1) return 'p%s:%s:%s' % (proto, port, ip) else: return 'p%s:%s' % (proto, addr) def enable_connection_uri(conn_uri): manager_uri = _connection_to_manager_uri(conn_uri) utils.execute(['ovs-vsctl', 'set-manager', manager_uri], run_as_root=True)
# Copyright (c) 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from neutron.agent.common import utils def _connection_to_manager_uri(conn_uri): proto, addr = conn_uri.split(':', 1) if ':' in addr: ip, port = addr.split(':', 1) return 'p%s:%s:%s' % (proto, port, ip) else: return 'p%s:%s' % (proto, addr) def enable_connection_uri(conn_uri): manager_uri = _connection_to_manager_uri(conn_uri) utils.execute(['ovs-vsctl', 'set-manager', manager_uri], run_as_root=True)
en
0.854798
# Copyright (c) 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License.
1.480494
1
userbot/modules/filemanager.py
tiararosebiezetta/WeebProject-fork
0
6625066
# Credits to Userge for Remove and Rename import io import os import os.path import shutil import time from datetime import datetime from os.path import basename, dirname, exists, isdir, isfile, join, relpath, splitext from shutil import rmtree from tarfile import TarFile, is_tarfile from zipfile import BadZipFile, ZipFile, is_zipfile from natsort import os_sorted from py7zr import Bad7zFile, SevenZipFile, is_7zfile from rarfile import BadRarFile, RarFile, is_rarfile from userbot import CMD_HELP, TEMP_DOWNLOAD_DIRECTORY from userbot.events import register from userbot.utils import humanbytes MAX_MESSAGE_SIZE_LIMIT = 4095 @register(outgoing=True, pattern=r"^\.ls(?: |$)(.*)") async def lst(event): if event.fwd_from: return cat = event.pattern_match.group(1) path = cat if cat else os.getcwd() if not exists(path): await event.edit( f"There is no such directory or file with the name `{cat}` check again!" ) return if isdir(path): if cat: msg = f"**Folders and Files in `{path}`** :\n\n" else: msg = "**Folders and Files in Current Directory** :\n\n" lists = os.listdir(path) files = "" folders = "" for contents in os_sorted(lists): catpath = path + "/" + contents if not isdir(catpath): size = os.stat(catpath).st_size if contents.endswith((".mp3", ".flac", ".wav", ".m4a")): files += "🎵 " elif contents.endswith(".opus"): files += "🎙 " elif contents.endswith( (".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv") ): files += "🎞 " elif contents.endswith( (".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz") ): files += "🗜 " elif contents.endswith( (".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp") ): files += "🖼 " elif contents.endswith((".exe", ".deb")): files += "⚙️ " elif contents.endswith((".iso", ".img")): files += "💿 " elif contents.endswith((".apk", ".xapk")): files += "📱 " elif contents.endswith(".py"): files += "🐍 " else: files += "📄 " files += f"`{contents}` (__{humanbytes(size)}__)\n" else: folders += f"📁 `{contents}`\n" msg = msg + folders + files if files or folders else msg + "__empty path__" else: size = os.stat(path).st_size msg = "The details of given file :\n\n" if path.endswith((".mp3", ".flac", ".wav", ".m4a")): mode = "🎵 " elif path.endswith(".opus"): mode = "🎙 " elif path.endswith((".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv")): mode = "🎞 " elif path.endswith((".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz")): mode = "🗜 " elif path.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp")): mode = "🖼 " elif path.endswith((".exe", ".deb")): mode = "⚙️ " elif path.endswith((".iso", ".img")): mode = "💿 " elif path.endswith((".apk", ".xapk")): mode = "📱 " elif path.endswith(".py"): mode = "🐍 " else: mode = "📄 " time.ctime(os.path.getctime(path)) time2 = time.ctime(os.path.getmtime(path)) time3 = time.ctime(os.path.getatime(path)) msg += f"**Location :** `{path}`\n" msg += f"**Icon :** `{mode}`\n" msg += f"**Size :** `{humanbytes(size)}`\n" msg += f"**Last Modified Time:** `{time2}`\n" msg += f"**Last Accessed Time:** `{time3}`" if len(msg) > MAX_MESSAGE_SIZE_LIMIT: with io.BytesIO(str.encode(msg)) as out_file: out_file.name = "ls.txt" await event.client.send_file( event.chat_id, out_file, force_document=True, allow_cache=False, caption=path, ) await event.delete() else: await event.edit(msg) @register(outgoing=True, pattern=r"^\.rm(?: |$)(.*)") async def rmove(event): """Removing Directory/File""" cat = event.pattern_match.group(1) if not cat: await event.edit("`Missing file path!`") return if not exists(cat): await event.edit("`File path not exists!`") return if isfile(cat): os.remove(cat) else: rmtree(cat) await event.edit(f"Removed `{cat}`") @register(outgoing=True, pattern=r"^\.rn ([^|]+)\|([^|]+)") async def rname(event): """Renaming Directory/File""" cat = str(event.pattern_match.group(1)).strip() new_name = str(event.pattern_match.group(2)).strip() if not exists(cat): await event.edit(f"file path : {cat} not exists!") return new_path = join(dirname(cat), new_name) shutil.move(cat, new_path) await event.edit(f"Renamed `{cat}` to `{new_path}`") @register(outgoing=True, pattern=r"^\.zip (.*)") async def zip_file(event): if event.fwd_from: return if not exists(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) input_str = event.pattern_match.group(1) path = input_str zip_name = "" if "|" in input_str: path, zip_name = path.split("|") path = path.strip() zip_name = zip_name.strip() if exists(path): await event.edit("`Zipping...`") start_time = datetime.now() if isdir(path): dir_path = path.split("/")[-1] if path.endswith("/"): dir_path = path.split("/")[-2] zip_path = join(TEMP_DOWNLOAD_DIRECTORY, dir_path) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w") as zip_obj: for roots, _, files in os.walk(path): for file in files: files_path = join(roots, file) arc_path = join(dir_path, relpath(files_path, path)) zip_obj.write(files_path, arc_path) end_time = (datetime.now() - start_time).seconds await event.edit( f"Zipped `{path}` into `{zip_path}` in `{end_time}` seconds." ) elif isfile(path): file_name = basename(path) zip_path = join(TEMP_DOWNLOAD_DIRECTORY, file_name) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj: zip_obj.write(path, file_name) await event.edit(f"Zipped `{path}` into `{zip_path}`") else: await event.edit("`404: Not Found`") @register(outgoing=True, pattern=r"^\.unzip (.*)") async def unzip_file(event): if event.fwd_from: return if not exists(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) input_str = event.pattern_match.group(1) output_path = TEMP_DOWNLOAD_DIRECTORY + basename(splitext(input_str)[0]) if exists(input_str): start_time = datetime.now() await event.edit("`Unzipping...`") if is_zipfile(input_str): zip_type = ZipFile elif is_rarfile(input_str): zip_type = RarFile elif is_tarfile(input_str): zip_type = TarFile elif is_7zfile(input_str): zip_type = SevenZipFile else: return await event.edit( "`Unsupported file types!`\n`ZIP, TAR, 7z, and RAR only`" ) try: with zip_type(input_str, "r") as zip_obj: zip_obj.extractall(output_path) except BadRarFile: return await event.edit("**Error:** `Corrupted RAR File`") except BadZipFile: return await event.edit("**Error:** `Corrupted ZIP File`") except Bad7zFile: return await event.edit("**Error:** `Corrupted 7z File`") except BaseException as err: return await event.edit(f"**Error:** `{err}`") end_time = (datetime.now() - start_time).seconds await event.edit( f"Unzipped `{input_str}` into `{output_path}` in `{end_time}` seconds." ) else: await event.edit("`404: Not Found`") CMD_HELP.update( { "file": ">`.ls` <directory>" "\nUsage: Get list file inside directory." "\n\n>`.rm` <directory/file>" "\nUsage: Remove file or directory" "\n\n>`.rn` <directory/file> | <new name>" "\nUsage: Rename file or directory" "\n\n>`.zip` <file/folder path> | <zip name> (optional)" "\nUsage: For zipping file or folder." "\n\n>`.unzip` <path to zip file>" "\nUsage: For extracting archive file" "\nOnly support ZIP, TAR, 7z, and RAR file!" } )
# Credits to Userge for Remove and Rename import io import os import os.path import shutil import time from datetime import datetime from os.path import basename, dirname, exists, isdir, isfile, join, relpath, splitext from shutil import rmtree from tarfile import TarFile, is_tarfile from zipfile import BadZipFile, ZipFile, is_zipfile from natsort import os_sorted from py7zr import Bad7zFile, SevenZipFile, is_7zfile from rarfile import BadRarFile, RarFile, is_rarfile from userbot import CMD_HELP, TEMP_DOWNLOAD_DIRECTORY from userbot.events import register from userbot.utils import humanbytes MAX_MESSAGE_SIZE_LIMIT = 4095 @register(outgoing=True, pattern=r"^\.ls(?: |$)(.*)") async def lst(event): if event.fwd_from: return cat = event.pattern_match.group(1) path = cat if cat else os.getcwd() if not exists(path): await event.edit( f"There is no such directory or file with the name `{cat}` check again!" ) return if isdir(path): if cat: msg = f"**Folders and Files in `{path}`** :\n\n" else: msg = "**Folders and Files in Current Directory** :\n\n" lists = os.listdir(path) files = "" folders = "" for contents in os_sorted(lists): catpath = path + "/" + contents if not isdir(catpath): size = os.stat(catpath).st_size if contents.endswith((".mp3", ".flac", ".wav", ".m4a")): files += "🎵 " elif contents.endswith(".opus"): files += "🎙 " elif contents.endswith( (".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv") ): files += "🎞 " elif contents.endswith( (".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz") ): files += "🗜 " elif contents.endswith( (".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp") ): files += "🖼 " elif contents.endswith((".exe", ".deb")): files += "⚙️ " elif contents.endswith((".iso", ".img")): files += "💿 " elif contents.endswith((".apk", ".xapk")): files += "📱 " elif contents.endswith(".py"): files += "🐍 " else: files += "📄 " files += f"`{contents}` (__{humanbytes(size)}__)\n" else: folders += f"📁 `{contents}`\n" msg = msg + folders + files if files or folders else msg + "__empty path__" else: size = os.stat(path).st_size msg = "The details of given file :\n\n" if path.endswith((".mp3", ".flac", ".wav", ".m4a")): mode = "🎵 " elif path.endswith(".opus"): mode = "🎙 " elif path.endswith((".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv")): mode = "🎞 " elif path.endswith((".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz")): mode = "🗜 " elif path.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp")): mode = "🖼 " elif path.endswith((".exe", ".deb")): mode = "⚙️ " elif path.endswith((".iso", ".img")): mode = "💿 " elif path.endswith((".apk", ".xapk")): mode = "📱 " elif path.endswith(".py"): mode = "🐍 " else: mode = "📄 " time.ctime(os.path.getctime(path)) time2 = time.ctime(os.path.getmtime(path)) time3 = time.ctime(os.path.getatime(path)) msg += f"**Location :** `{path}`\n" msg += f"**Icon :** `{mode}`\n" msg += f"**Size :** `{humanbytes(size)}`\n" msg += f"**Last Modified Time:** `{time2}`\n" msg += f"**Last Accessed Time:** `{time3}`" if len(msg) > MAX_MESSAGE_SIZE_LIMIT: with io.BytesIO(str.encode(msg)) as out_file: out_file.name = "ls.txt" await event.client.send_file( event.chat_id, out_file, force_document=True, allow_cache=False, caption=path, ) await event.delete() else: await event.edit(msg) @register(outgoing=True, pattern=r"^\.rm(?: |$)(.*)") async def rmove(event): """Removing Directory/File""" cat = event.pattern_match.group(1) if not cat: await event.edit("`Missing file path!`") return if not exists(cat): await event.edit("`File path not exists!`") return if isfile(cat): os.remove(cat) else: rmtree(cat) await event.edit(f"Removed `{cat}`") @register(outgoing=True, pattern=r"^\.rn ([^|]+)\|([^|]+)") async def rname(event): """Renaming Directory/File""" cat = str(event.pattern_match.group(1)).strip() new_name = str(event.pattern_match.group(2)).strip() if not exists(cat): await event.edit(f"file path : {cat} not exists!") return new_path = join(dirname(cat), new_name) shutil.move(cat, new_path) await event.edit(f"Renamed `{cat}` to `{new_path}`") @register(outgoing=True, pattern=r"^\.zip (.*)") async def zip_file(event): if event.fwd_from: return if not exists(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) input_str = event.pattern_match.group(1) path = input_str zip_name = "" if "|" in input_str: path, zip_name = path.split("|") path = path.strip() zip_name = zip_name.strip() if exists(path): await event.edit("`Zipping...`") start_time = datetime.now() if isdir(path): dir_path = path.split("/")[-1] if path.endswith("/"): dir_path = path.split("/")[-2] zip_path = join(TEMP_DOWNLOAD_DIRECTORY, dir_path) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w") as zip_obj: for roots, _, files in os.walk(path): for file in files: files_path = join(roots, file) arc_path = join(dir_path, relpath(files_path, path)) zip_obj.write(files_path, arc_path) end_time = (datetime.now() - start_time).seconds await event.edit( f"Zipped `{path}` into `{zip_path}` in `{end_time}` seconds." ) elif isfile(path): file_name = basename(path) zip_path = join(TEMP_DOWNLOAD_DIRECTORY, file_name) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj: zip_obj.write(path, file_name) await event.edit(f"Zipped `{path}` into `{zip_path}`") else: await event.edit("`404: Not Found`") @register(outgoing=True, pattern=r"^\.unzip (.*)") async def unzip_file(event): if event.fwd_from: return if not exists(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) input_str = event.pattern_match.group(1) output_path = TEMP_DOWNLOAD_DIRECTORY + basename(splitext(input_str)[0]) if exists(input_str): start_time = datetime.now() await event.edit("`Unzipping...`") if is_zipfile(input_str): zip_type = ZipFile elif is_rarfile(input_str): zip_type = RarFile elif is_tarfile(input_str): zip_type = TarFile elif is_7zfile(input_str): zip_type = SevenZipFile else: return await event.edit( "`Unsupported file types!`\n`ZIP, TAR, 7z, and RAR only`" ) try: with zip_type(input_str, "r") as zip_obj: zip_obj.extractall(output_path) except BadRarFile: return await event.edit("**Error:** `Corrupted RAR File`") except BadZipFile: return await event.edit("**Error:** `Corrupted ZIP File`") except Bad7zFile: return await event.edit("**Error:** `Corrupted 7z File`") except BaseException as err: return await event.edit(f"**Error:** `{err}`") end_time = (datetime.now() - start_time).seconds await event.edit( f"Unzipped `{input_str}` into `{output_path}` in `{end_time}` seconds." ) else: await event.edit("`404: Not Found`") CMD_HELP.update( { "file": ">`.ls` <directory>" "\nUsage: Get list file inside directory." "\n\n>`.rm` <directory/file>" "\nUsage: Remove file or directory" "\n\n>`.rn` <directory/file> | <new name>" "\nUsage: Rename file or directory" "\n\n>`.zip` <file/folder path> | <zip name> (optional)" "\nUsage: For zipping file or folder." "\n\n>`.unzip` <path to zip file>" "\nUsage: For extracting archive file" "\nOnly support ZIP, TAR, 7z, and RAR file!" } )
en
0.931091
# Credits to Userge for Remove and Rename Removing Directory/File Renaming Directory/File
2.308216
2
dependencies/src/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/gkh_20000804.py
aleasims/Peach
0
6625067
#G. <NAME>'s <<EMAIL>> node-set intersection and difference example from Xml.Xslt import test_harness sheet_and_source = """<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:data="ken" version="1.0"> <xsl:output method="text"/> <data:data> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> </data:data> <xsl:template match="/"> <!--root rule--> <xsl:variable name="ns1" select="document('')//data:data/item[position()>1]"/> <xsl:variable name="ns2" select="document('')//data:data/item[position()&lt;5]"/> <xsl:for-each select="$ns1[count(.|$ns2)=count($ns2)]"> Intersection: <xsl:value-of select="."/> </xsl:for-each> <xsl:for-each select="( $ns1[count(.|$ns2)!=count($ns2)] | $ns2[count(.|$ns1)!=count($ns1)] )"> Difference: <xsl:value-of select="."/> </xsl:for-each> </xsl:template> </xsl:stylesheet>""" expected = """ Intersection: 2 Intersection: 3 Intersection: 4 Difference: 1 Difference: 5""" def Test(tester): source = test_harness.FileInfo(string=sheet_and_source) sheet = test_harness.FileInfo(string=sheet_and_source) test_harness.XsltTest(tester, source, [sheet], expected) return
#G. <NAME>'s <<EMAIL>> node-set intersection and difference example from Xml.Xslt import test_harness sheet_and_source = """<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:data="ken" version="1.0"> <xsl:output method="text"/> <data:data> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> </data:data> <xsl:template match="/"> <!--root rule--> <xsl:variable name="ns1" select="document('')//data:data/item[position()>1]"/> <xsl:variable name="ns2" select="document('')//data:data/item[position()&lt;5]"/> <xsl:for-each select="$ns1[count(.|$ns2)=count($ns2)]"> Intersection: <xsl:value-of select="."/> </xsl:for-each> <xsl:for-each select="( $ns1[count(.|$ns2)!=count($ns2)] | $ns2[count(.|$ns1)!=count($ns1)] )"> Difference: <xsl:value-of select="."/> </xsl:for-each> </xsl:template> </xsl:stylesheet>""" expected = """ Intersection: 2 Intersection: 3 Intersection: 4 Difference: 1 Difference: 5""" def Test(tester): source = test_harness.FileInfo(string=sheet_and_source) sheet = test_harness.FileInfo(string=sheet_and_source) test_harness.XsltTest(tester, source, [sheet], expected) return
en
0.16465
#G. <NAME>'s <<EMAIL>> node-set intersection and difference example <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:data="ken" version="1.0"> <xsl:output method="text"/> <data:data> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> </data:data> <xsl:template match="/"> <!--root rule--> <xsl:variable name="ns1" select="document('')//data:data/item[position()>1]"/> <xsl:variable name="ns2" select="document('')//data:data/item[position()&lt;5]"/> <xsl:for-each select="$ns1[count(.|$ns2)=count($ns2)]"> Intersection: <xsl:value-of select="."/> </xsl:for-each> <xsl:for-each select="( $ns1[count(.|$ns2)!=count($ns2)] | $ns2[count(.|$ns1)!=count($ns1)] )"> Difference: <xsl:value-of select="."/> </xsl:for-each> </xsl:template> </xsl:stylesheet> Intersection: 2 Intersection: 3 Intersection: 4 Difference: 1 Difference: 5
2.914747
3
docassemble_base/docassemble/base/__init__.py
foxbat123/docassemble
1
6625068
try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__) __version__ = "1.3.9"
try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__) __version__ = "1.3.9"
none
1
1.406548
1
sympy/physics/units/tests/test_quantities.py
ripper479/sympy
0
6625069
<reponame>ripper479/sympy<gh_stars>0 from sympy import (Abs, Add, Basic, Function, Number, Rational, S, Symbol, diff, exp, integrate, log, sin, sqrt, symbols, Matrix) from sympy.physics.units import (amount_of_substance, convert_to, find_unit, volume, kilometer) from sympy.physics.units.definitions import (amu, au, centimeter, coulomb, day, foot, grams, hour, inch, kg, km, m, meter, mile, millimeter, minute, quart, s, second, speed_of_light, bit, byte, kibibyte, mebibyte, gibibyte, tebibyte, pebibyte, exbibyte, kilogram, gravitational_constant) from sympy.physics.units.definitions.dimension_definitions import ( Dimension, charge, length, time, temperature, pressure, energy ) from sympy.physics.units.prefixes import PREFIXES, kilo from sympy.physics.units.quantities import Quantity from sympy.physics.units.systems import SI from sympy.utilities.pytest import XFAIL, raises, warns_deprecated_sympy k = PREFIXES["k"] def test_str_repr(): assert str(kg) == "kilogram" def test_eq(): # simple test assert 10*m == 10*m assert 10*m != 10*s def test_convert_to(): q = Quantity("q1") q.set_global_relative_scale_factor(S(5000), meter) assert q.convert_to(m) == 5000*m assert speed_of_light.convert_to(m / s) == 299792458 * m / s # TODO: eventually support this kind of conversion: # assert (2*speed_of_light).convert_to(m / s) == 2 * 299792458 * m / s assert day.convert_to(s) == 86400*s # Wrong dimension to convert: assert q.convert_to(s) == q assert speed_of_light.convert_to(m) == speed_of_light def test_Quantity_definition(): q = Quantity("s10", abbrev="sabbr") q.set_global_relative_scale_factor(10, second) u = Quantity("u", abbrev="dam") u.set_global_relative_scale_factor(10, meter) km = Quantity("km") km.set_global_relative_scale_factor(kilo, meter) v = Quantity("u") v.set_global_relative_scale_factor(5*kilo, meter) assert q.scale_factor == 10 assert q.dimension == time assert q.abbrev == Symbol("sabbr") assert u.dimension == length assert u.scale_factor == 10 assert u.abbrev == Symbol("dam") assert km.scale_factor == 1000 assert km.func(*km.args) == km assert km.func(*km.args).args == km.args assert v.dimension == length assert v.scale_factor == 5000 with warns_deprecated_sympy(): Quantity('invalid', 'dimension', 1) with warns_deprecated_sympy(): Quantity('mismatch', dimension=length, scale_factor=kg) def test_abbrev(): u = Quantity("u") u.set_global_relative_scale_factor(S.One, meter) assert u.name == Symbol("u") assert u.abbrev == Symbol("u") u = Quantity("u", abbrev="om") u.set_global_relative_scale_factor(S(2), meter) assert u.name == Symbol("u") assert u.abbrev == Symbol("om") assert u.scale_factor == 2 assert isinstance(u.scale_factor, Number) u = Quantity("u", abbrev="ikm") u.set_global_relative_scale_factor(3*kilo, meter) assert u.abbrev == Symbol("ikm") assert u.scale_factor == 3000 def test_print(): u = Quantity("unitname", abbrev="dam") assert repr(u) == "unitname" assert str(u) == "unitname" def test_Quantity_eq(): u = Quantity("u", abbrev="dam") v = Quantity("v1") assert u != v v = Quantity("v2", abbrev="ds") assert u != v v = Quantity("v3", abbrev="dm") assert u != v def test_add_sub(): u = Quantity("u") v = Quantity("v") w = Quantity("w") u.set_global_relative_scale_factor(S(10), meter) v.set_global_relative_scale_factor(S(5), meter) w.set_global_relative_scale_factor(S(2), second) assert isinstance(u + v, Add) assert (u + v.convert_to(u)) == (1 + S.Half)*u # TODO: eventually add this: # assert (u + v).convert_to(u) == (1 + S.Half)*u assert isinstance(u - v, Add) assert (u - v.convert_to(u)) == S.Half*u # TODO: eventually add this: # assert (u - v).convert_to(u) == S.Half*u def test_quantity_abs(): v_w1 = Quantity('v_w1') v_w2 = Quantity('v_w2') v_w3 = Quantity('v_w3') v_w1.set_global_relative_scale_factor(1, meter/second) v_w2.set_global_relative_scale_factor(1, meter/second) v_w3.set_global_relative_scale_factor(1, meter/second) expr = v_w3 - Abs(v_w1 - v_w2) assert SI.get_dimensional_expr(v_w1) == (length/time).name Dq = Dimension(SI.get_dimensional_expr(expr)) with warns_deprecated_sympy(): Dq1 = Dimension(Quantity.get_dimensional_expr(expr)) assert Dq == Dq1 assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == { 'length': 1, 'time': -1, } assert meter == sqrt(meter**2) def test_check_unit_consistency(): u = Quantity("u") v = Quantity("v") w = Quantity("w") u.set_global_relative_scale_factor(S(10), meter) v.set_global_relative_scale_factor(S(5), meter) w.set_global_relative_scale_factor(S(2), second) def check_unit_consistency(expr): SI._collect_factor_and_dimension(expr) raises(ValueError, lambda: check_unit_consistency(u + w)) raises(ValueError, lambda: check_unit_consistency(u - w)) raises(ValueError, lambda: check_unit_consistency(u + 1)) raises(ValueError, lambda: check_unit_consistency(u - 1)) raises(ValueError, lambda: check_unit_consistency(1 - exp(u / w))) def test_mul_div(): u = Quantity("u") v = Quantity("v") t = Quantity("t") ut = Quantity("ut") v2 = Quantity("v") u.set_global_relative_scale_factor(S(10), meter) v.set_global_relative_scale_factor(S(5), meter) t.set_global_relative_scale_factor(S(2), second) ut.set_global_relative_scale_factor(S(20), meter*second) v2.set_global_relative_scale_factor(S(5), meter/second) assert 1 / u == u**(-1) assert u / 1 == u v1 = u / t v2 = v # Pow only supports structural equality: assert v1 != v2 assert v1 == v2.convert_to(v1) # TODO: decide whether to allow such expression in the future # (requires somehow manipulating the core). # assert u / Quantity('l2', dimension=length, scale_factor=2) == 5 assert u * 1 == u ut1 = u * t ut2 = ut # Mul only supports structural equality: assert ut1 != ut2 assert ut1 == ut2.convert_to(ut1) # Mul only supports structural equality: lp1 = Quantity("lp1") lp1.set_global_relative_scale_factor(S(2), 1/meter) assert u * lp1 != 20 assert u**0 == 1 assert u**1 == u # TODO: Pow only support structural equality: u2 = Quantity("u2") u3 = Quantity("u3") u2.set_global_relative_scale_factor(S(100), meter**2) u3.set_global_relative_scale_factor(Rational(1, 10), 1/meter) assert u ** 2 != u2 assert u ** -1 != u3 assert u ** 2 == u2.convert_to(u) assert u ** -1 == u3.convert_to(u) def test_units(): assert convert_to((5*m/s * day) / km, 1) == 432 assert convert_to(foot / meter, meter) == Rational(3048, 10000) # amu is a pure mass so mass/mass gives a number, not an amount (mol) # TODO: need better simplification routine: assert str(convert_to(grams/amu, grams).n(2)) == '6.0e+23' # Light from the sun needs about 8.3 minutes to reach earth t = (1*au / speed_of_light) / minute # TODO: need a better way to simplify expressions containing units: t = convert_to(convert_to(t, meter / minute), meter) assert t == Rational(49865956897, 5995849160) # TODO: fix this, it should give `m` without `Abs` assert sqrt(m**2) == Abs(m) assert (sqrt(m))**2 == m t = Symbol('t') assert integrate(t*m/s, (t, 1*s, 5*s)) == 12*m*s assert (t * m/s).integrate((t, 1*s, 5*s)) == 12*m*s def test_issue_quart(): assert convert_to(4 * quart / inch ** 3, meter) == 231 assert convert_to(4 * quart / inch ** 3, millimeter) == 231 def test_issue_5565(): assert (m < s).is_Relational def test_find_unit(): assert find_unit('coulomb') == ['coulomb', 'coulombs', 'coulomb_constant'] assert find_unit(coulomb) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge'] assert find_unit(charge) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge'] assert find_unit(inch) == [ 'm', 'au', 'cm', 'dm', 'ft', 'km', 'ly', 'mi', 'mm', 'nm', 'pm', 'um', 'yd', 'nmi', 'feet', 'foot', 'inch', 'mile', 'yard', 'meter', 'miles', 'yards', 'inches', 'meters', 'micron', 'microns', 'decimeter', 'kilometer', 'lightyear', 'nanometer', 'picometer', 'centimeter', 'decimeters', 'kilometers', 'lightyears', 'micrometer', 'millimeter', 'nanometers', 'picometers', 'centimeters', 'micrometers', 'millimeters', 'nautical_mile', 'planck_length', 'nautical_miles', 'astronomical_unit', 'astronomical_units'] assert find_unit(inch**-1) == ['D', 'dioptre', 'optical_power'] assert find_unit(length**-1) == ['D', 'dioptre', 'optical_power'] assert find_unit(inch ** 3) == [ 'l', 'cl', 'dl', 'ml', 'liter', 'quart', 'liters', 'quarts', 'deciliter', 'centiliter', 'deciliters', 'milliliter', 'centiliters', 'milliliters', 'planck_volume'] assert find_unit('voltage') == ['V', 'v', 'volt', 'volts', 'planck_voltage'] def test_Quantity_derivative(): x = symbols("x") assert diff(x*meter, x) == meter assert diff(x**3*meter**2, x) == 3*x**2*meter**2 assert diff(meter, meter) == 1 assert diff(meter**2, meter) == 2*meter def test_quantity_postprocessing(): q1 = Quantity('q1') q2 = Quantity('q2') SI.set_quantity_dimension(q1, length*pressure**2*temperature/time) SI.set_quantity_dimension(q2, energy*pressure*temperature/(length**2*time)) assert q1 + q2 q = q1 + q2 Dq = Dimension(SI.get_dimensional_expr(q)) assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == { 'length': -1, 'mass': 2, 'temperature': 1, 'time': -5, } def test_factor_and_dimension(): assert (3000, Dimension(1)) == SI._collect_factor_and_dimension(3000) assert (1001, length) == SI._collect_factor_and_dimension(meter + km) assert (2, length/time) == SI._collect_factor_and_dimension( meter/second + 36*km/(10*hour)) x, y = symbols('x y') assert (x + y/100, length) == SI._collect_factor_and_dimension( x*m + y*centimeter) cH = Quantity('cH') SI.set_quantity_dimension(cH, amount_of_substance/volume) pH = -log(cH) assert (1, volume/amount_of_substance) == SI._collect_factor_and_dimension( exp(pH)) v_w1 = Quantity('v_w1') v_w2 = Quantity('v_w2') v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second) v_w2.set_global_relative_scale_factor(2, meter/second) expr = Abs(v_w1/2 - v_w2) assert (Rational(5, 4), length/time) == \ SI._collect_factor_and_dimension(expr) expr = Rational(5, 2)*second/meter*v_w1 - 3000 assert (-(2996 + Rational(1, 4)), Dimension(1)) == \ SI._collect_factor_and_dimension(expr) expr = v_w1**(v_w2/v_w1) assert ((Rational(3, 2))**Rational(4, 3), (length/time)**Rational(4, 3)) == \ SI._collect_factor_and_dimension(expr) with warns_deprecated_sympy(): assert (3000, Dimension(1)) == Quantity._collect_factor_and_dimension(3000) @XFAIL def test_factor_and_dimension_with_Abs(): with warns_deprecated_sympy(): v_w1 = Quantity('v_w1', length/time, Rational(3, 2)*meter/second) v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second) expr = v_w1 - Abs(v_w1) assert (0, length/time) == Quantity._collect_factor_and_dimension(expr) def test_dimensional_expr_of_derivative(): l = Quantity('l') t = Quantity('t') t1 = Quantity('t1') l.set_global_relative_scale_factor(36, km) t.set_global_relative_scale_factor(1, hour) t1.set_global_relative_scale_factor(1, second) x = Symbol('x') y = Symbol('y') f = Function('f') dfdx = f(x, y).diff(x, y) dl_dt = dfdx.subs({f(x, y): l, x: t, y: t1}) assert SI.get_dimensional_expr(dl_dt) ==\ SI.get_dimensional_expr(l / t / t1) ==\ Symbol("length")/Symbol("time")**2 assert SI._collect_factor_and_dimension(dl_dt) ==\ SI._collect_factor_and_dimension(l / t / t1) ==\ (10, length/time**2) def test_get_dimensional_expr_with_function(): v_w1 = Quantity('v_w1') v_w2 = Quantity('v_w2') v_w1.set_global_relative_scale_factor(1, meter/second) v_w2.set_global_relative_scale_factor(1, meter/second) assert SI.get_dimensional_expr(sin(v_w1)) == \ sin(SI.get_dimensional_expr(v_w1)) assert SI.get_dimensional_expr(sin(v_w1/v_w2)) == 1 def test_binary_information(): assert convert_to(kibibyte, byte) == 1024*byte assert convert_to(mebibyte, byte) == 1024**2*byte assert convert_to(gibibyte, byte) == 1024**3*byte assert convert_to(tebibyte, byte) == 1024**4*byte assert convert_to(pebibyte, byte) == 1024**5*byte assert convert_to(exbibyte, byte) == 1024**6*byte assert kibibyte.convert_to(bit) == 8*1024*bit assert byte.convert_to(bit) == 8*bit a = 10*kibibyte*hour assert convert_to(a, byte) == 10240*byte*hour assert convert_to(a, minute) == 600*kibibyte*minute assert convert_to(a, [byte, minute]) == 614400*byte*minute def test_conversion_with_2_nonstandard_dimensions(): smartness = Dimension("smartness") generousness = Dimension("generousness") good_grade = Quantity("good_grade") kilo_good_grade = Quantity("kilo_good_grade") centi_good_grade = Quantity("centi_good_grade") kilo_good_grade.set_global_relative_scale_factor(1000, good_grade) centi_good_grade.set_global_relative_scale_factor(S.One/10**5, kilo_good_grade) charity_points = Quantity("charity_points") milli_charity_points = Quantity("milli_charity_points") missions = Quantity("missions") milli_charity_points.set_global_relative_scale_factor(S.One/1000, charity_points) missions.set_global_relative_scale_factor(251, charity_points) assert convert_to( kilo_good_grade*milli_charity_points*millimeter, [centi_good_grade, missions, centimeter] ) == S.One * 10**5 / (251*1000) / 10 * centi_good_grade*missions*centimeter def test_eval_subs(): energy, mass, force = symbols('energy mass force') expr1 = energy/mass units = {energy: kilogram*meter**2/second**2, mass: kilogram} assert expr1.subs(units) == meter**2/second**2 expr2 = force/mass units = {force:gravitational_constant*kilogram**2/meter**2, mass:kilogram} assert expr2.subs(units) == gravitational_constant*kilogram/meter**2 def test_issue_14932(): assert (log(inch) - log(2)).simplify() == log(inch/2) assert (log(inch) - log(foot)).simplify() == -log(12) p = symbols('p', positive=True) assert (log(inch) - log(p)).simplify() == log(inch/p) def test_issue_14547(): # the root issue is that an argument with dimensions should # not raise an error when the the `arg - 1` calculation is # performed in the assumptions system from sympy.physics.units import foot, inch from sympy import Eq assert log(foot).is_zero is None assert log(foot).is_positive is None assert log(foot).is_nonnegative is None assert log(foot).is_negative is None assert log(foot).is_algebraic is None assert log(foot).is_rational is None # doesn't raise error assert Eq(log(foot), log(inch)) is not None # might be False or unevaluated x = Symbol('x') e = foot + x assert e.is_Add and set(e.args) == {foot, x} e = foot + 1 assert e.is_Add and set(e.args) == {foot, 1} def test_deprecated_quantity_methods(): step = Quantity("step") with warns_deprecated_sympy(): step.set_dimension(length) step.set_scale_factor(2*meter) assert convert_to(step, centimeter) == 200*centimeter assert convert_to(1000*step/second, kilometer/second) == 2*kilometer/second
from sympy import (Abs, Add, Basic, Function, Number, Rational, S, Symbol, diff, exp, integrate, log, sin, sqrt, symbols, Matrix) from sympy.physics.units import (amount_of_substance, convert_to, find_unit, volume, kilometer) from sympy.physics.units.definitions import (amu, au, centimeter, coulomb, day, foot, grams, hour, inch, kg, km, m, meter, mile, millimeter, minute, quart, s, second, speed_of_light, bit, byte, kibibyte, mebibyte, gibibyte, tebibyte, pebibyte, exbibyte, kilogram, gravitational_constant) from sympy.physics.units.definitions.dimension_definitions import ( Dimension, charge, length, time, temperature, pressure, energy ) from sympy.physics.units.prefixes import PREFIXES, kilo from sympy.physics.units.quantities import Quantity from sympy.physics.units.systems import SI from sympy.utilities.pytest import XFAIL, raises, warns_deprecated_sympy k = PREFIXES["k"] def test_str_repr(): assert str(kg) == "kilogram" def test_eq(): # simple test assert 10*m == 10*m assert 10*m != 10*s def test_convert_to(): q = Quantity("q1") q.set_global_relative_scale_factor(S(5000), meter) assert q.convert_to(m) == 5000*m assert speed_of_light.convert_to(m / s) == 299792458 * m / s # TODO: eventually support this kind of conversion: # assert (2*speed_of_light).convert_to(m / s) == 2 * 299792458 * m / s assert day.convert_to(s) == 86400*s # Wrong dimension to convert: assert q.convert_to(s) == q assert speed_of_light.convert_to(m) == speed_of_light def test_Quantity_definition(): q = Quantity("s10", abbrev="sabbr") q.set_global_relative_scale_factor(10, second) u = Quantity("u", abbrev="dam") u.set_global_relative_scale_factor(10, meter) km = Quantity("km") km.set_global_relative_scale_factor(kilo, meter) v = Quantity("u") v.set_global_relative_scale_factor(5*kilo, meter) assert q.scale_factor == 10 assert q.dimension == time assert q.abbrev == Symbol("sabbr") assert u.dimension == length assert u.scale_factor == 10 assert u.abbrev == Symbol("dam") assert km.scale_factor == 1000 assert km.func(*km.args) == km assert km.func(*km.args).args == km.args assert v.dimension == length assert v.scale_factor == 5000 with warns_deprecated_sympy(): Quantity('invalid', 'dimension', 1) with warns_deprecated_sympy(): Quantity('mismatch', dimension=length, scale_factor=kg) def test_abbrev(): u = Quantity("u") u.set_global_relative_scale_factor(S.One, meter) assert u.name == Symbol("u") assert u.abbrev == Symbol("u") u = Quantity("u", abbrev="om") u.set_global_relative_scale_factor(S(2), meter) assert u.name == Symbol("u") assert u.abbrev == Symbol("om") assert u.scale_factor == 2 assert isinstance(u.scale_factor, Number) u = Quantity("u", abbrev="ikm") u.set_global_relative_scale_factor(3*kilo, meter) assert u.abbrev == Symbol("ikm") assert u.scale_factor == 3000 def test_print(): u = Quantity("unitname", abbrev="dam") assert repr(u) == "unitname" assert str(u) == "unitname" def test_Quantity_eq(): u = Quantity("u", abbrev="dam") v = Quantity("v1") assert u != v v = Quantity("v2", abbrev="ds") assert u != v v = Quantity("v3", abbrev="dm") assert u != v def test_add_sub(): u = Quantity("u") v = Quantity("v") w = Quantity("w") u.set_global_relative_scale_factor(S(10), meter) v.set_global_relative_scale_factor(S(5), meter) w.set_global_relative_scale_factor(S(2), second) assert isinstance(u + v, Add) assert (u + v.convert_to(u)) == (1 + S.Half)*u # TODO: eventually add this: # assert (u + v).convert_to(u) == (1 + S.Half)*u assert isinstance(u - v, Add) assert (u - v.convert_to(u)) == S.Half*u # TODO: eventually add this: # assert (u - v).convert_to(u) == S.Half*u def test_quantity_abs(): v_w1 = Quantity('v_w1') v_w2 = Quantity('v_w2') v_w3 = Quantity('v_w3') v_w1.set_global_relative_scale_factor(1, meter/second) v_w2.set_global_relative_scale_factor(1, meter/second) v_w3.set_global_relative_scale_factor(1, meter/second) expr = v_w3 - Abs(v_w1 - v_w2) assert SI.get_dimensional_expr(v_w1) == (length/time).name Dq = Dimension(SI.get_dimensional_expr(expr)) with warns_deprecated_sympy(): Dq1 = Dimension(Quantity.get_dimensional_expr(expr)) assert Dq == Dq1 assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == { 'length': 1, 'time': -1, } assert meter == sqrt(meter**2) def test_check_unit_consistency(): u = Quantity("u") v = Quantity("v") w = Quantity("w") u.set_global_relative_scale_factor(S(10), meter) v.set_global_relative_scale_factor(S(5), meter) w.set_global_relative_scale_factor(S(2), second) def check_unit_consistency(expr): SI._collect_factor_and_dimension(expr) raises(ValueError, lambda: check_unit_consistency(u + w)) raises(ValueError, lambda: check_unit_consistency(u - w)) raises(ValueError, lambda: check_unit_consistency(u + 1)) raises(ValueError, lambda: check_unit_consistency(u - 1)) raises(ValueError, lambda: check_unit_consistency(1 - exp(u / w))) def test_mul_div(): u = Quantity("u") v = Quantity("v") t = Quantity("t") ut = Quantity("ut") v2 = Quantity("v") u.set_global_relative_scale_factor(S(10), meter) v.set_global_relative_scale_factor(S(5), meter) t.set_global_relative_scale_factor(S(2), second) ut.set_global_relative_scale_factor(S(20), meter*second) v2.set_global_relative_scale_factor(S(5), meter/second) assert 1 / u == u**(-1) assert u / 1 == u v1 = u / t v2 = v # Pow only supports structural equality: assert v1 != v2 assert v1 == v2.convert_to(v1) # TODO: decide whether to allow such expression in the future # (requires somehow manipulating the core). # assert u / Quantity('l2', dimension=length, scale_factor=2) == 5 assert u * 1 == u ut1 = u * t ut2 = ut # Mul only supports structural equality: assert ut1 != ut2 assert ut1 == ut2.convert_to(ut1) # Mul only supports structural equality: lp1 = Quantity("lp1") lp1.set_global_relative_scale_factor(S(2), 1/meter) assert u * lp1 != 20 assert u**0 == 1 assert u**1 == u # TODO: Pow only support structural equality: u2 = Quantity("u2") u3 = Quantity("u3") u2.set_global_relative_scale_factor(S(100), meter**2) u3.set_global_relative_scale_factor(Rational(1, 10), 1/meter) assert u ** 2 != u2 assert u ** -1 != u3 assert u ** 2 == u2.convert_to(u) assert u ** -1 == u3.convert_to(u) def test_units(): assert convert_to((5*m/s * day) / km, 1) == 432 assert convert_to(foot / meter, meter) == Rational(3048, 10000) # amu is a pure mass so mass/mass gives a number, not an amount (mol) # TODO: need better simplification routine: assert str(convert_to(grams/amu, grams).n(2)) == '6.0e+23' # Light from the sun needs about 8.3 minutes to reach earth t = (1*au / speed_of_light) / minute # TODO: need a better way to simplify expressions containing units: t = convert_to(convert_to(t, meter / minute), meter) assert t == Rational(49865956897, 5995849160) # TODO: fix this, it should give `m` without `Abs` assert sqrt(m**2) == Abs(m) assert (sqrt(m))**2 == m t = Symbol('t') assert integrate(t*m/s, (t, 1*s, 5*s)) == 12*m*s assert (t * m/s).integrate((t, 1*s, 5*s)) == 12*m*s def test_issue_quart(): assert convert_to(4 * quart / inch ** 3, meter) == 231 assert convert_to(4 * quart / inch ** 3, millimeter) == 231 def test_issue_5565(): assert (m < s).is_Relational def test_find_unit(): assert find_unit('coulomb') == ['coulomb', 'coulombs', 'coulomb_constant'] assert find_unit(coulomb) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge'] assert find_unit(charge) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge'] assert find_unit(inch) == [ 'm', 'au', 'cm', 'dm', 'ft', 'km', 'ly', 'mi', 'mm', 'nm', 'pm', 'um', 'yd', 'nmi', 'feet', 'foot', 'inch', 'mile', 'yard', 'meter', 'miles', 'yards', 'inches', 'meters', 'micron', 'microns', 'decimeter', 'kilometer', 'lightyear', 'nanometer', 'picometer', 'centimeter', 'decimeters', 'kilometers', 'lightyears', 'micrometer', 'millimeter', 'nanometers', 'picometers', 'centimeters', 'micrometers', 'millimeters', 'nautical_mile', 'planck_length', 'nautical_miles', 'astronomical_unit', 'astronomical_units'] assert find_unit(inch**-1) == ['D', 'dioptre', 'optical_power'] assert find_unit(length**-1) == ['D', 'dioptre', 'optical_power'] assert find_unit(inch ** 3) == [ 'l', 'cl', 'dl', 'ml', 'liter', 'quart', 'liters', 'quarts', 'deciliter', 'centiliter', 'deciliters', 'milliliter', 'centiliters', 'milliliters', 'planck_volume'] assert find_unit('voltage') == ['V', 'v', 'volt', 'volts', 'planck_voltage'] def test_Quantity_derivative(): x = symbols("x") assert diff(x*meter, x) == meter assert diff(x**3*meter**2, x) == 3*x**2*meter**2 assert diff(meter, meter) == 1 assert diff(meter**2, meter) == 2*meter def test_quantity_postprocessing(): q1 = Quantity('q1') q2 = Quantity('q2') SI.set_quantity_dimension(q1, length*pressure**2*temperature/time) SI.set_quantity_dimension(q2, energy*pressure*temperature/(length**2*time)) assert q1 + q2 q = q1 + q2 Dq = Dimension(SI.get_dimensional_expr(q)) assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == { 'length': -1, 'mass': 2, 'temperature': 1, 'time': -5, } def test_factor_and_dimension(): assert (3000, Dimension(1)) == SI._collect_factor_and_dimension(3000) assert (1001, length) == SI._collect_factor_and_dimension(meter + km) assert (2, length/time) == SI._collect_factor_and_dimension( meter/second + 36*km/(10*hour)) x, y = symbols('x y') assert (x + y/100, length) == SI._collect_factor_and_dimension( x*m + y*centimeter) cH = Quantity('cH') SI.set_quantity_dimension(cH, amount_of_substance/volume) pH = -log(cH) assert (1, volume/amount_of_substance) == SI._collect_factor_and_dimension( exp(pH)) v_w1 = Quantity('v_w1') v_w2 = Quantity('v_w2') v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second) v_w2.set_global_relative_scale_factor(2, meter/second) expr = Abs(v_w1/2 - v_w2) assert (Rational(5, 4), length/time) == \ SI._collect_factor_and_dimension(expr) expr = Rational(5, 2)*second/meter*v_w1 - 3000 assert (-(2996 + Rational(1, 4)), Dimension(1)) == \ SI._collect_factor_and_dimension(expr) expr = v_w1**(v_w2/v_w1) assert ((Rational(3, 2))**Rational(4, 3), (length/time)**Rational(4, 3)) == \ SI._collect_factor_and_dimension(expr) with warns_deprecated_sympy(): assert (3000, Dimension(1)) == Quantity._collect_factor_and_dimension(3000) @XFAIL def test_factor_and_dimension_with_Abs(): with warns_deprecated_sympy(): v_w1 = Quantity('v_w1', length/time, Rational(3, 2)*meter/second) v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second) expr = v_w1 - Abs(v_w1) assert (0, length/time) == Quantity._collect_factor_and_dimension(expr) def test_dimensional_expr_of_derivative(): l = Quantity('l') t = Quantity('t') t1 = Quantity('t1') l.set_global_relative_scale_factor(36, km) t.set_global_relative_scale_factor(1, hour) t1.set_global_relative_scale_factor(1, second) x = Symbol('x') y = Symbol('y') f = Function('f') dfdx = f(x, y).diff(x, y) dl_dt = dfdx.subs({f(x, y): l, x: t, y: t1}) assert SI.get_dimensional_expr(dl_dt) ==\ SI.get_dimensional_expr(l / t / t1) ==\ Symbol("length")/Symbol("time")**2 assert SI._collect_factor_and_dimension(dl_dt) ==\ SI._collect_factor_and_dimension(l / t / t1) ==\ (10, length/time**2) def test_get_dimensional_expr_with_function(): v_w1 = Quantity('v_w1') v_w2 = Quantity('v_w2') v_w1.set_global_relative_scale_factor(1, meter/second) v_w2.set_global_relative_scale_factor(1, meter/second) assert SI.get_dimensional_expr(sin(v_w1)) == \ sin(SI.get_dimensional_expr(v_w1)) assert SI.get_dimensional_expr(sin(v_w1/v_w2)) == 1 def test_binary_information(): assert convert_to(kibibyte, byte) == 1024*byte assert convert_to(mebibyte, byte) == 1024**2*byte assert convert_to(gibibyte, byte) == 1024**3*byte assert convert_to(tebibyte, byte) == 1024**4*byte assert convert_to(pebibyte, byte) == 1024**5*byte assert convert_to(exbibyte, byte) == 1024**6*byte assert kibibyte.convert_to(bit) == 8*1024*bit assert byte.convert_to(bit) == 8*bit a = 10*kibibyte*hour assert convert_to(a, byte) == 10240*byte*hour assert convert_to(a, minute) == 600*kibibyte*minute assert convert_to(a, [byte, minute]) == 614400*byte*minute def test_conversion_with_2_nonstandard_dimensions(): smartness = Dimension("smartness") generousness = Dimension("generousness") good_grade = Quantity("good_grade") kilo_good_grade = Quantity("kilo_good_grade") centi_good_grade = Quantity("centi_good_grade") kilo_good_grade.set_global_relative_scale_factor(1000, good_grade) centi_good_grade.set_global_relative_scale_factor(S.One/10**5, kilo_good_grade) charity_points = Quantity("charity_points") milli_charity_points = Quantity("milli_charity_points") missions = Quantity("missions") milli_charity_points.set_global_relative_scale_factor(S.One/1000, charity_points) missions.set_global_relative_scale_factor(251, charity_points) assert convert_to( kilo_good_grade*milli_charity_points*millimeter, [centi_good_grade, missions, centimeter] ) == S.One * 10**5 / (251*1000) / 10 * centi_good_grade*missions*centimeter def test_eval_subs(): energy, mass, force = symbols('energy mass force') expr1 = energy/mass units = {energy: kilogram*meter**2/second**2, mass: kilogram} assert expr1.subs(units) == meter**2/second**2 expr2 = force/mass units = {force:gravitational_constant*kilogram**2/meter**2, mass:kilogram} assert expr2.subs(units) == gravitational_constant*kilogram/meter**2 def test_issue_14932(): assert (log(inch) - log(2)).simplify() == log(inch/2) assert (log(inch) - log(foot)).simplify() == -log(12) p = symbols('p', positive=True) assert (log(inch) - log(p)).simplify() == log(inch/p) def test_issue_14547(): # the root issue is that an argument with dimensions should # not raise an error when the the `arg - 1` calculation is # performed in the assumptions system from sympy.physics.units import foot, inch from sympy import Eq assert log(foot).is_zero is None assert log(foot).is_positive is None assert log(foot).is_nonnegative is None assert log(foot).is_negative is None assert log(foot).is_algebraic is None assert log(foot).is_rational is None # doesn't raise error assert Eq(log(foot), log(inch)) is not None # might be False or unevaluated x = Symbol('x') e = foot + x assert e.is_Add and set(e.args) == {foot, x} e = foot + 1 assert e.is_Add and set(e.args) == {foot, 1} def test_deprecated_quantity_methods(): step = Quantity("step") with warns_deprecated_sympy(): step.set_dimension(length) step.set_scale_factor(2*meter) assert convert_to(step, centimeter) == 200*centimeter assert convert_to(1000*step/second, kilometer/second) == 2*kilometer/second
en
0.731869
# simple test # TODO: eventually support this kind of conversion: # assert (2*speed_of_light).convert_to(m / s) == 2 * 299792458 * m / s # Wrong dimension to convert: # TODO: eventually add this: # assert (u + v).convert_to(u) == (1 + S.Half)*u # TODO: eventually add this: # assert (u - v).convert_to(u) == S.Half*u # Pow only supports structural equality: # TODO: decide whether to allow such expression in the future # (requires somehow manipulating the core). # assert u / Quantity('l2', dimension=length, scale_factor=2) == 5 # Mul only supports structural equality: # Mul only supports structural equality: # TODO: Pow only support structural equality: # amu is a pure mass so mass/mass gives a number, not an amount (mol) # TODO: need better simplification routine: # Light from the sun needs about 8.3 minutes to reach earth # TODO: need a better way to simplify expressions containing units: # TODO: fix this, it should give `m` without `Abs` # the root issue is that an argument with dimensions should # not raise an error when the the `arg - 1` calculation is # performed in the assumptions system # doesn't raise error # might be False or unevaluated
2.787044
3
tests/conftest.py
zosocanuck/connaisseur
0
6625070
<gh_stars>0 import re import json import pytest import requests from aioresponses import CallbackResult import connaisseur.kube_api import connaisseur.config as co import connaisseur.admission_request as admreq import connaisseur.alert as alert import connaisseur.validators.notaryv1.trust_data as td import connaisseur.validators.notaryv1.key_store as ks import connaisseur.validators.notaryv1.notary as no import connaisseur.validators.notaryv1.notaryv1_validator as nv1 import connaisseur.util as util from contextlib import contextmanager """ This file is used for sharing fixtures across all other test files. https://docs.pytest.org/en/stable/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session """ @contextmanager def no_exc(): yield def get_json(path): with open(path, "r") as file: return json.load(file) def get_admreq(adm_type): try: return get_json( f"tests/data/sample_admission_requests/ad_request_{adm_type}.json" ) except FileNotFoundError: return None def get_td(path): return get_json(f"tests/data/trust_data/{path}.json") def get_k8s_res(path): return get_json(f"tests/data/sample_kube_resources/{path}.json") def get_cosign_err_msg(path): with open(f"tests/data/cosign/{path}.txt") as file: return file.read() @pytest.fixture def m_request(monkeypatch): monkeypatch.setattr(requests, "get", mock_get_request) monkeypatch.setattr(requests, "post", mock_post_request) monkeypatch.setattr(connaisseur.kube_api, "__get_token", kube_token) class MockResponse: content: dict headers: dict status_code: int = 200 def __init__(self, content: dict, headers: dict = None, status_code: int = 200): self.content = content self.headers = headers self.status_code = status_code def raise_for_status(self): if self.status_code != 200: raise requests.exceptions.HTTPError def json(self): return self.content def async_callback(url, **kwargs): mock_rsp = mock_get_request(str(url), **kwargs) return CallbackResult( status=mock_rsp.status_code, payload=mock_rsp.content, headers=mock_rsp.headers, reason="irrelevant", ) def mock_get_request(url, **kwargs): notary_regex = [ ( r"https:\/\/([^\/]+)\/v2\/([^\/]+)\/([^\/]+\/)?" r"([^\/]+)\/_trust\/tuf\/(.+)\.json" ), mock_request_notary, ] kube_regex = [ ( r"https:\/\/[^\/]+\/apis?\/(apps\/v1|v1|batch\/v1beta1)" r"\/namespaces\/([^\/]+)\/([^\/]+)\/([^\/]+)" ), mock_request_kube, ] notary_health_regex = [ (r"https:\/\/([^\/]+)\/_notary_server\/health"), mock_request_notary_health, ] notary_token_regex = [ (r"https:\/\/([^\/]+)\/token\?((service=[^&]+)|(scope=[^&]+)|&)*"), mock_request_notary_token, ] kube_namespace_less_regex = [ ( r"https:\/\/[^\/]+\/apis?\/(admissionregistration" r"\.k8s\.io\/v1beta1)\/[^\/]+\/([^\/]+)" ), mock_request_kube_namespace_less, ] for reg in ( notary_regex, kube_regex, notary_health_regex, notary_token_regex, kube_namespace_less_regex, ): match = re.search(reg[0], url) if match: return reg[1](match, **kwargs) return MockResponse({}, status_code=500) def mock_request_notary(match: re.Match, **kwargs): host, registry, repo, image, role = ( match.group(1), match.group(2), match.group(3), match.group(4), match.group(5), ) if registry == "auth.io" and not kwargs.get("headers"): return MockResponse( {}, headers={ "Www-authenticate": ( 'Bearer realm="https://sample.notary.io/token,"' 'service="notary",scope="repository:sample-image:pull"' ) }, status_code=401, ) if registry == "empty.io": return MockResponse({}, status_code=404) return MockResponse(get_td(f"{image}/{role}")) def mock_request_kube(match: re.Match, **kwargs): version, namespace, kind, name = ( match.group(1), match.group(2), match.group(3), match.group(4), ) try: return MockResponse(get_k8s_res(kind)) except FileNotFoundError as err: return MockResponse({}, status_code=500) def mock_request_notary_health(match: re.Match, **kwargs): host = match.group(1) if "unhealthy" in host: return MockResponse({}, status_code=500) elif "exceptional" in host: raise Exception else: return MockResponse({}) def kube_token(path: str): return "" def mock_request_notary_token(match: re.Match, **kwargs): host, scope, service = match.group(1), match.group(2), match.group(3) auth = kwargs.get("auth") if host == "notary.acr.io": return MockResponse({"access_token": "a.valid.token"}) if host == "empty.io": return MockResponse({}, status_code=500) if host == "notary.hans.io": if ( getattr(auth, "login", None) == "hans" and getattr(auth, "password", None) == "<PASSWORD>" ): return MockResponse({"access_token": "a.valid.token"}) return MockResponse({}, status_code=401) if "wrong_token" in scope: return MockResponse({"tocken": "a.valid.token"}) if "invalid_token" in scope: return MockResponse({"token": "invalidtoken"}) return MockResponse({"token": "a.valid.token"}) def mock_request_kube_namespace_less(match: re.Match, **kwargs): name = match.group(2) return MockResponse(get_k8s_res(name)) def mock_post_request(url, **kwargs): opsgenie_regex = [ (r"https:\/\/api\.eu\.opsgenie\.com\/v2\/alerts"), mock_opsgenie_request, ] for reg in [opsgenie_regex]: match = re.search(reg[0], url) if match: return reg[1](match, **kwargs) return MockResponse({}, status_code=500) def mock_opsgenie_request(match: re.Match, **kwargs): if kwargs.get("headers", {}).get("Authorization"): return MockResponse( { "result": "Request will be processed", "took": 0.302, "requestId": "43a29c5c-3dbf-4fa4-9c26-f4f71023e120", } ) return MockResponse({}, status_code=401) @pytest.fixture def m_trust_data(): connaisseur.validators.notaryv1.trust_data.RootData._TrustData__SCHEMA_PATH = ( "connaisseur/res/root_schema.json" ) connaisseur.validators.notaryv1.trust_data.TargetsData._TrustData__SCHEMA_PATH = ( "connaisseur/res/targets_schema.json" ) connaisseur.validators.notaryv1.trust_data.SnapshotData._TrustData__SCHEMA_PATH = ( "connaisseur/res/snapshot_schema.json" ) connaisseur.validators.notaryv1.trust_data.TimestampData._TrustData__SCHEMA_PATH = ( "connaisseur/res/timestamp_schema.json" ) @pytest.fixture def m_expiry(monkeypatch): def mock_expiry(self): pass monkeypatch.setattr(td.TrustData, "validate_expiry", mock_expiry) @pytest.fixture def sample_key_store(m_trust_data): sample_key = ( "<KEY>" "<KEY>" "<KEY> ) k = ks.KeyStore(sample_key) for role in ("root", "targets", "snapshot", "timestamp"): k.update(td.TrustData(get_td(f"sample_{role}"), role)) return k @pytest.fixture def alice_key_store(m_trust_data): sample_key = ( "<KEY>" "<KEY>" "<KEY> ) k = ks.KeyStore(sample_key) for role in ("root", "targets", "snapshot", "timestamp"): k.update(td.TrustData(get_td(f"alice-image/{role}"), role)) return k @pytest.fixture def m_notary(monkeypatch): def mock_healthy(self): return True monkeypatch.setattr(no.Notary, "healthy", mock_healthy) @pytest.fixture def sample_nv1(m_notary): sample_notary = { "name": "dockerhub", "host": "notary.docker.io", "trust_roots": [ { "name": "default", "key": ( "<KEY>" "S2PWacRcBN/VQdVK4PVk1w4pMWlz9AHQthDGl+W2k3elHkPbR+gNkK2PCA==" ), }, { "name": "charlie", "key": ( "<KEY>" "aUWM7eZ19L2WPJfjt105PPieCM1CZybSZ2h3O4+E4hPz1X5RfmojpXKePg==" ), }, {"name": "missingkey", "key": ""}, ], "is_acr": False, "auth": {"username": "bert", "password": "<PASSWORD>"}, "cert": None, } return nv1.NotaryV1Validator(**sample_notary) @pytest.fixture() def m_ad_schema_path(): admreq.AdmissionRequest._AdmissionRequest__SCHEMA_PATH = ( "connaisseur/res/ad_request_schema.json" ) @pytest.fixture def adm_req_samples(m_ad_schema_path): return [ get_admreq(t) for t in ( "deployments", "pods", "replicasets", "cronjob", "err", "invalid_image", "auto_approval", ) ] @pytest.fixture() def m_safe_path_func(monkeypatch): side_effect = lambda callback, base_dir, path, *args, **kwargs: callback( path, *args, **kwargs ) monkeypatch.setattr(connaisseur.util, "safe_path_func", side_effect) @pytest.fixture def m_alerting(monkeypatch, m_safe_path_func): monkeypatch.setenv("DETECTION_MODE", "0") monkeypatch.setenv("POD_NAME", "connaisseur-pod-123") monkeypatch.setenv("CLUSTER_NAME", "minikube") connaisseur.alert.AlertingConfiguration._AlertingConfiguration__PATH = ( "tests/data/alerting/alertconfig.json" ) connaisseur.alert.AlertingConfiguration._AlertingConfiguration__SCHEMA_PATH = ( "connaisseur/res/alertconfig_schema.json" ) connaisseur.alert.Alert._Alert__TEMPLATE_PATH = "tests/data/alerting/templates"
import re import json import pytest import requests from aioresponses import CallbackResult import connaisseur.kube_api import connaisseur.config as co import connaisseur.admission_request as admreq import connaisseur.alert as alert import connaisseur.validators.notaryv1.trust_data as td import connaisseur.validators.notaryv1.key_store as ks import connaisseur.validators.notaryv1.notary as no import connaisseur.validators.notaryv1.notaryv1_validator as nv1 import connaisseur.util as util from contextlib import contextmanager """ This file is used for sharing fixtures across all other test files. https://docs.pytest.org/en/stable/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session """ @contextmanager def no_exc(): yield def get_json(path): with open(path, "r") as file: return json.load(file) def get_admreq(adm_type): try: return get_json( f"tests/data/sample_admission_requests/ad_request_{adm_type}.json" ) except FileNotFoundError: return None def get_td(path): return get_json(f"tests/data/trust_data/{path}.json") def get_k8s_res(path): return get_json(f"tests/data/sample_kube_resources/{path}.json") def get_cosign_err_msg(path): with open(f"tests/data/cosign/{path}.txt") as file: return file.read() @pytest.fixture def m_request(monkeypatch): monkeypatch.setattr(requests, "get", mock_get_request) monkeypatch.setattr(requests, "post", mock_post_request) monkeypatch.setattr(connaisseur.kube_api, "__get_token", kube_token) class MockResponse: content: dict headers: dict status_code: int = 200 def __init__(self, content: dict, headers: dict = None, status_code: int = 200): self.content = content self.headers = headers self.status_code = status_code def raise_for_status(self): if self.status_code != 200: raise requests.exceptions.HTTPError def json(self): return self.content def async_callback(url, **kwargs): mock_rsp = mock_get_request(str(url), **kwargs) return CallbackResult( status=mock_rsp.status_code, payload=mock_rsp.content, headers=mock_rsp.headers, reason="irrelevant", ) def mock_get_request(url, **kwargs): notary_regex = [ ( r"https:\/\/([^\/]+)\/v2\/([^\/]+)\/([^\/]+\/)?" r"([^\/]+)\/_trust\/tuf\/(.+)\.json" ), mock_request_notary, ] kube_regex = [ ( r"https:\/\/[^\/]+\/apis?\/(apps\/v1|v1|batch\/v1beta1)" r"\/namespaces\/([^\/]+)\/([^\/]+)\/([^\/]+)" ), mock_request_kube, ] notary_health_regex = [ (r"https:\/\/([^\/]+)\/_notary_server\/health"), mock_request_notary_health, ] notary_token_regex = [ (r"https:\/\/([^\/]+)\/token\?((service=[^&]+)|(scope=[^&]+)|&)*"), mock_request_notary_token, ] kube_namespace_less_regex = [ ( r"https:\/\/[^\/]+\/apis?\/(admissionregistration" r"\.k8s\.io\/v1beta1)\/[^\/]+\/([^\/]+)" ), mock_request_kube_namespace_less, ] for reg in ( notary_regex, kube_regex, notary_health_regex, notary_token_regex, kube_namespace_less_regex, ): match = re.search(reg[0], url) if match: return reg[1](match, **kwargs) return MockResponse({}, status_code=500) def mock_request_notary(match: re.Match, **kwargs): host, registry, repo, image, role = ( match.group(1), match.group(2), match.group(3), match.group(4), match.group(5), ) if registry == "auth.io" and not kwargs.get("headers"): return MockResponse( {}, headers={ "Www-authenticate": ( 'Bearer realm="https://sample.notary.io/token,"' 'service="notary",scope="repository:sample-image:pull"' ) }, status_code=401, ) if registry == "empty.io": return MockResponse({}, status_code=404) return MockResponse(get_td(f"{image}/{role}")) def mock_request_kube(match: re.Match, **kwargs): version, namespace, kind, name = ( match.group(1), match.group(2), match.group(3), match.group(4), ) try: return MockResponse(get_k8s_res(kind)) except FileNotFoundError as err: return MockResponse({}, status_code=500) def mock_request_notary_health(match: re.Match, **kwargs): host = match.group(1) if "unhealthy" in host: return MockResponse({}, status_code=500) elif "exceptional" in host: raise Exception else: return MockResponse({}) def kube_token(path: str): return "" def mock_request_notary_token(match: re.Match, **kwargs): host, scope, service = match.group(1), match.group(2), match.group(3) auth = kwargs.get("auth") if host == "notary.acr.io": return MockResponse({"access_token": "a.valid.token"}) if host == "empty.io": return MockResponse({}, status_code=500) if host == "notary.hans.io": if ( getattr(auth, "login", None) == "hans" and getattr(auth, "password", None) == "<PASSWORD>" ): return MockResponse({"access_token": "a.valid.token"}) return MockResponse({}, status_code=401) if "wrong_token" in scope: return MockResponse({"tocken": "a.valid.token"}) if "invalid_token" in scope: return MockResponse({"token": "invalidtoken"}) return MockResponse({"token": "a.valid.token"}) def mock_request_kube_namespace_less(match: re.Match, **kwargs): name = match.group(2) return MockResponse(get_k8s_res(name)) def mock_post_request(url, **kwargs): opsgenie_regex = [ (r"https:\/\/api\.eu\.opsgenie\.com\/v2\/alerts"), mock_opsgenie_request, ] for reg in [opsgenie_regex]: match = re.search(reg[0], url) if match: return reg[1](match, **kwargs) return MockResponse({}, status_code=500) def mock_opsgenie_request(match: re.Match, **kwargs): if kwargs.get("headers", {}).get("Authorization"): return MockResponse( { "result": "Request will be processed", "took": 0.302, "requestId": "43a29c5c-3dbf-4fa4-9c26-f4f71023e120", } ) return MockResponse({}, status_code=401) @pytest.fixture def m_trust_data(): connaisseur.validators.notaryv1.trust_data.RootData._TrustData__SCHEMA_PATH = ( "connaisseur/res/root_schema.json" ) connaisseur.validators.notaryv1.trust_data.TargetsData._TrustData__SCHEMA_PATH = ( "connaisseur/res/targets_schema.json" ) connaisseur.validators.notaryv1.trust_data.SnapshotData._TrustData__SCHEMA_PATH = ( "connaisseur/res/snapshot_schema.json" ) connaisseur.validators.notaryv1.trust_data.TimestampData._TrustData__SCHEMA_PATH = ( "connaisseur/res/timestamp_schema.json" ) @pytest.fixture def m_expiry(monkeypatch): def mock_expiry(self): pass monkeypatch.setattr(td.TrustData, "validate_expiry", mock_expiry) @pytest.fixture def sample_key_store(m_trust_data): sample_key = ( "<KEY>" "<KEY>" "<KEY> ) k = ks.KeyStore(sample_key) for role in ("root", "targets", "snapshot", "timestamp"): k.update(td.TrustData(get_td(f"sample_{role}"), role)) return k @pytest.fixture def alice_key_store(m_trust_data): sample_key = ( "<KEY>" "<KEY>" "<KEY> ) k = ks.KeyStore(sample_key) for role in ("root", "targets", "snapshot", "timestamp"): k.update(td.TrustData(get_td(f"alice-image/{role}"), role)) return k @pytest.fixture def m_notary(monkeypatch): def mock_healthy(self): return True monkeypatch.setattr(no.Notary, "healthy", mock_healthy) @pytest.fixture def sample_nv1(m_notary): sample_notary = { "name": "dockerhub", "host": "notary.docker.io", "trust_roots": [ { "name": "default", "key": ( "<KEY>" "S2PWacRcBN/VQdVK4PVk1w4pMWlz9AHQthDGl+W2k3elHkPbR+gNkK2PCA==" ), }, { "name": "charlie", "key": ( "<KEY>" "aUWM7eZ19L2WPJfjt105PPieCM1CZybSZ2h3O4+E4hPz1X5RfmojpXKePg==" ), }, {"name": "missingkey", "key": ""}, ], "is_acr": False, "auth": {"username": "bert", "password": "<PASSWORD>"}, "cert": None, } return nv1.NotaryV1Validator(**sample_notary) @pytest.fixture() def m_ad_schema_path(): admreq.AdmissionRequest._AdmissionRequest__SCHEMA_PATH = ( "connaisseur/res/ad_request_schema.json" ) @pytest.fixture def adm_req_samples(m_ad_schema_path): return [ get_admreq(t) for t in ( "deployments", "pods", "replicasets", "cronjob", "err", "invalid_image", "auto_approval", ) ] @pytest.fixture() def m_safe_path_func(monkeypatch): side_effect = lambda callback, base_dir, path, *args, **kwargs: callback( path, *args, **kwargs ) monkeypatch.setattr(connaisseur.util, "safe_path_func", side_effect) @pytest.fixture def m_alerting(monkeypatch, m_safe_path_func): monkeypatch.setenv("DETECTION_MODE", "0") monkeypatch.setenv("POD_NAME", "connaisseur-pod-123") monkeypatch.setenv("CLUSTER_NAME", "minikube") connaisseur.alert.AlertingConfiguration._AlertingConfiguration__PATH = ( "tests/data/alerting/alertconfig.json" ) connaisseur.alert.AlertingConfiguration._AlertingConfiguration__SCHEMA_PATH = ( "connaisseur/res/alertconfig_schema.json" ) connaisseur.alert.Alert._Alert__TEMPLATE_PATH = "tests/data/alerting/templates"
en
0.733761
This file is used for sharing fixtures across all other test files. https://docs.pytest.org/en/stable/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session
1.944878
2
docassemble_base/docassemble/base/filter.py
Hamudss/docassemble
0
6625071
<filename>docassemble_base/docassemble/base/filter.py # -*- coding: utf-8 -*- import sys from six import string_types, text_type, PY2 import re import os import markdown import mimetypes import codecs import json import qrcode import qrcode.image.svg from io import BytesIO import tempfile import types import time import stat import PyPDF2 from docassemble.base.functions import server, word import docassemble.base.functions from docassemble.base.pandoc import MyPandoc from bs4 import BeautifulSoup import docassemble.base.file_docx from pylatex.utils import escape_latex from io import open from pathlib import Path NoneType = type(None) from docassemble.base.logger import logmessage from docassemble.base.rtfng.object.picture import Image import PIL DEFAULT_PAGE_WIDTH = '6.5in' term_start = re.compile(r'\[\[') term_match = re.compile(r'\[\[([^\]]*)\]\]') noquote_match = re.compile(r'"') lt_match = re.compile(r'<') gt_match = re.compile(r'>') amp_match = re.compile(r'&') emoji_match = re.compile(r':([A-Za-z][A-Za-z0-9\_\-]+):') extension_match = re.compile(r'\.[a-z]+$') map_match = re.compile(r'\[MAP ([^\]]+)\]', flags=re.DOTALL) code_match = re.compile(r'<code>') def set_default_page_width(width): global DEFAULT_PAGE_WIDTH DEFAULT_PAGE_WIDTH = text_type(width) return def get_default_page_width(): return(DEFAULT_PAGE_WIDTH) DEFAULT_IMAGE_WIDTH = '4in' def set_default_image_width(width): global DEFAULT_IMAGE_WIDTH DEFAULT_IMAGE_WIDTH = text_type(width) return def get_default_image_width(): return(DEFAULT_IMAGE_WIDTH) MAX_HEIGHT_POINTS = 10 * 72 def set_max_height_points(points): global MAX_HEIGHT_POINTS MAX_HEIGHT_POINTS = points return def get_max_height_points(): return(MAX_HEIGHT_POINTS) MAX_WIDTH_POINTS = 6.5 * 72.0 def set_max_width_points(points): global MAX_WIDTH_POINTS MAX_WIDTH_POINTS = points return def get_max_width_points(): return(MAX_WIDTH_POINTS) # def blank_da_send_mail(*args, **kwargs): # logmessage("da_send_mail: no mail agent configured!") # return(None) # da_send_mail = blank_da_send_mail # def set_da_send_mail(func): # global da_send_mail # da_send_mail = func # return # def blank_file_finder(*args, **kwargs): # return(dict(filename="invalid")) # file_finder = blank_file_finder # def set_file_finder(func): # global file_finder # #sys.stderr.write("set the file finder to " + text_type(func) + "\n") # file_finder = func # return # def blank_url_finder(*args, **kwargs): # return('about:blank') # url_finder = blank_url_finder # def set_url_finder(func): # global url_finder # url_finder = func # return # def blank_url_for(*args, **kwargs): # return('about:blank') # url_for = blank_url_for # def set_url_for(func): # global url_for # url_for = func # return rtf_spacing = {'tight': r'\\sl0 ', 'single': r'\\sl0 ', 'oneandahalf': r'\\sl360\\slmult1 ', 'double': r'\\sl480\\slmult1 ', 'triple': r'\\sl720\\slmult1 '} rtf_after_space = {'tight': 0, 'single': 1, 'oneandahalf': 0, 'double': 0, 'triplespacing': 0, 'triple': 0} def rtf_prefilter(text, metadata=dict()): text = re.sub(r'^# ', '[HEADING1] ', text, flags=re.MULTILINE) text = re.sub(r'^## ', '[HEADING2] ', text, flags=re.MULTILINE) text = re.sub(r'^### ', '[HEADING3] ', text, flags=re.MULTILINE) text = re.sub(r'^#### ', '[HEADING4] ', text, flags=re.MULTILINE) text = re.sub(r'^##### ', '[HEADING5] ', text, flags=re.MULTILINE) text = re.sub(r'^###### ', '[HEADING6] ', text, flags=re.MULTILINE) text = re.sub(r'^####### ', '[HEADING7] ', text, flags=re.MULTILINE) text = re.sub(r'^######## ', '[HEADING8] ', text, flags=re.MULTILINE) text = re.sub(r'^######### ', '[HEADING9] ', text, flags=re.MULTILINE) text = re.sub(r'\s*\[VERTICAL_LINE\]\s*', '\n\n[VERTICAL_LINE]\n\n', text) text = re.sub(r'\s*\[BREAK\]\s*', '\n\n[BREAK]\n\n', text) text = re.sub(r'\s+\[END_TWOCOL\]', '\n\n[END_TWOCOL]', text) text = re.sub(r'\s+\[END_CAPTION\]', '\n\n[END_CAPTION]', text) text = re.sub(r'\[BEGIN_TWOCOL\]\s+', '[BEGIN_TWOCOL]\n\n', text) text = re.sub(r'\[BEGIN_CAPTION\]\s+', '[BEGIN_CAPTION]\n\n', text) return(text) def repeat_along(chars, match): output = chars * len(match.group(1)) #logmessage("Output is " + repr(output)) return output def rtf_filter(text, metadata=None, styles=None, question=None): if metadata is None: metadata = dict() if styles is None: styles = dict() #sys.stderr.write(text + "\n") if 'fontsize' in metadata: text = re.sub(r'{\\pard', r'\\fs' + text_type(convert_length(metadata['fontsize'], 'hp')) + r' {\\pard', text, count=1) after_space_multiplier = text_type(convert_length(metadata['fontsize'], 'twips')) else: after_space_multiplier = 240 if 'IndentationAmount' in metadata: indentation_amount = text_type(convert_length(metadata['IndentationAmount'], 'twips')) else: indentation_amount = '720' if 'Indentation' in metadata: if metadata['Indentation']: default_indentation = True else: default_indentation = False else: default_indentation = True if 'SingleSpacing' in metadata and metadata['SingleSpacing']: #logmessage("Gi there!") default_spacing = 'single' if 'Indentation' not in metadata: default_indentation = False elif 'OneAndAHalfSpacing' in metadata and metadata['OneAndAHalfSpacing']: default_spacing = 'oneandahalf' elif 'DoubleSpacing' in metadata and metadata['DoubleSpacing']: default_spacing = 'double' elif 'TripleSpacing' in metadata and metadata['TripleSpacing']: default_spacing = 'triple' else: default_spacing = 'double' after_space = after_space_multiplier * rtf_after_space[default_spacing] text = re.sub(r'{\\pard \\ql \\f0 \\sa180 \\li0 \\fi0 \[HEADING([0-9]+)\] *', (lambda x: '{\\pard ' + styles.get(x.group(1), '\\ql \\f0 \\sa180 \\li0 \\fi0 ')), text) text = re.sub(r'{\\pard \\ql \\f0 \\sa180 \\li0 \\fi0 \[(BEGIN_TWOCOL|BREAK|END_TWOCOL|BEGIN_CAPTION|VERTICAL_LINE|END_CAPTION|TIGHTSPACING|SINGLESPACING|DOUBLESPACING|START_INDENTATION|STOP_INDENTATION|PAGEBREAK|SKIPLINE|NOINDENT|FLUSHLEFT|FLUSHRIGHT|CENTER|BOLDCENTER|INDENTBY[^\]]*)\] *', r'[\1]{\\pard \\ql \\f0 \\sa180 \\li0 \\fi0 ', text) text = re.sub(r'{\\pard \\ql \\f0 \\sa180 \\li0 \\fi0 *\\par}', r'', text) text = re.sub(r'\[\[([^\]]*)\]\]', r'\1', text) # with open('/tmp/asdf.rtf', 'w') as deb_file: # deb_file.write(text) text = re.sub(r'\\par}\s*\[(END_TWOCOL|END_CAPTION|BREAK|VERTICAL_LINE)\]', r'}[\1]', text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\s*\[BREAK\]\s*(.+?)\[END_TWOCOL\]', rtf_two_col, text, flags=re.DOTALL) text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_as_rtf(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_as_rtf(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_as_rtf(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_as_rtf(x, question=question), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_as_rtf, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_as_rtf, text) text = re.sub(r'\[QR ([^\]]+)\]', qr_as_rtf, text) text = re.sub(r'\[MAP ([^\]]+)\]', '', text) text = replace_fields(text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) text = re.sub(r'\[TARGET ([^\]]+)\]', '', text) text = re.sub(r'\[YOUTUBE[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[VIMEO[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\s*\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', rtf_caption_table, text, flags=re.DOTALL) text = re.sub(r'\[NBSP\]', r'\\~ ', text) text = re.sub(r'\[REDACTION_SPACE\]', r'\\u9608\\zwbo', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along('\\u9608', x), text) text = re.sub(r'\[ENDASH\]', r'{\\endash}', text) text = re.sub(r'\[EMDASH\]', r'{\\emdash}', text) text = re.sub(r'\[HYPHEN\]', r'-', text) text = re.sub(r'\[CHECKBOX\]', r'____', text) text = re.sub(r'\[BLANK\]', r'________________', text) text = re.sub(r'\[BLANKFILL\]', r'________________', text) text = re.sub(r'\[PAGEBREAK\] *', r'\\page ', text) text = re.sub(r'\[PAGENUM\]', r'{\\chpgn}', text) text = re.sub(r'\[TOTALPAGES\]', r'{\\field{\\*\\fldinst NUMPAGES } {\\fldrslt 1}}', text) text = re.sub(r'\[SECTIONNUM\]', r'{\\sectnum}', text) text = re.sub(r' *\[SKIPLINE\] *', r'\\line ', text) text = re.sub(r' *\[NEWLINE\] *', r'\\line ', text) text = re.sub(r' *\[NEWPAR\] *', r'\\par ', text) text = re.sub(r' *\[BR\] *', r'\\line ', text) text = re.sub(r' *\[TAB\] *', r'\\tab ', text) text = re.sub(r' *\[END\] *', r'\n', text) text = re.sub(r'\\sa180\\sa180\\par', r'\\par', text) text = re.sub(r'\\sa180', r'\\sa0', text) text = re.sub(r'(\\trowd \\trgaph[0-9]+)', r'\1\\trqc', text) text = re.sub(r'\\intbl\\row}\s*{\\pard', r'\\intbl\\row}\n\\line\n{\\pard', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\s*\[(SAVE|RESTORE|TIGHTSPACING|SINGLESPACING|DOUBLESPACING|TRIPLESPACING|ONEANDAHALFSPACING|START_INDENTATION|STOP_INDENTATION)\]\s*', r'\n[\1]\n', text) lines = text.split('\n') spacing_command = rtf_spacing[default_spacing] if default_indentation: indentation_command = r'\\fi' + text_type(indentation_amount) + " " else: indentation_command = r'\\fi0 ' text = '' formatting_stack = list() for line in lines: if re.search(r'\[SAVE\]', line): formatting_stack.append(dict(spacing_command=spacing_command, after_space=after_space, default_indentation=default_indentation, indentation_command=indentation_command)) elif re.search(r'\[RESTORE\]', line): if len(formatting_stack): prior_values = formatting_stack.pop() spacing_command = prior_values['spacing_command'] after_space = prior_values['after_space'] default_indentation = prior_values['default_indentation'] indentation_command = prior_values['indentation_command'] elif re.search(r'\[TIGHTSPACING\]', line): spacing_command = rtf_spacing['tight'] default_spacing = 'tight' after_space = after_space_multiplier * rtf_after_space[default_spacing] default_indentation = False elif re.search(r'\[SINGLESPACING\]', line): spacing_command = rtf_spacing['single'] default_spacing = 'single' after_space = after_space_multiplier * rtf_after_space[default_spacing] default_indentation = False elif re.search(r'\[ONEANDAHALFSPACING\]', line): spacing_command = rtf_spacing['oneandahalf'] default_spacing = 'oneandahalf' after_space = after_space_multiplier * rtf_after_space[default_spacing] elif re.search(r'\[DOUBLESPACING\]', line): spacing_command = rtf_spacing['double'] default_spacing = 'double' after_space = after_space_multiplier * rtf_after_space[default_spacing] elif re.search(r'\[TRIPLESPACING\]', line): spacing_command = rtf_spacing['triple'] default_spacing = 'triple' after_space = after_space_multiplier * rtf_after_space[default_spacing] elif re.search(r'\[START_INDENTATION\]', line): indentation_command = r'\\fi' + text_type(indentation_amount) + " " elif re.search(r'\[STOP_INDENTATION\]', line): indentation_command = r'\\fi0 ' elif line != '': special_after_space = None special_spacing = None if re.search(r'\[BORDER\]', line): line = re.sub(r' *\[BORDER\] *', r'', line) border_text = r'\\box \\brdrhair \\brdrw1 \\brdrcf1 \\brsp29 ' else: border_text = r'' line = re.sub(r'{(\\pard\\intbl \\q[lrc] \\f[0-9]+ \\sa[0-9]+ \\li[0-9]+ \\fi[0-9]+.*?)\\par}', r'\1', line) if re.search(r'\[NOPAR\]', line): line = re.sub(r'{\\pard \\ql \\f[0-9]+ \\sa[0-9]+ \\li[0-9]+ \\fi-?[0-9]* *(.*?)\\par}', r'\1', line) line = re.sub(r' *\[NOPAR\] *', r'', line) n = re.search(r'\[INDENTBY *([0-9\.]+ *[A-Za-z]+) *([0-9\.]+ *[A-Za-z]+)\]', line) m = re.search(r'\[INDENTBY *([0-9\.]+ *[A-Za-z]+)\]', line) if n: line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\ri-?[0-9]+ ', r'', line) line = re.sub(r'\\li-?[0-9]+ ', r'\\li' + text_type(convert_length(n.group(1), 'twips')) + r' \\ri' + text_type(convert_length(n.group(2), 'twips')) + ' ', line) line = re.sub(r'\[INDENTBY[^\]]*\]', '', line) elif m: line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\li-?[0-9]+ ', r'\\li' + text_type(convert_length(m.group(1), 'twips')) + ' ', line) line = re.sub(r' *\[INDENTBY[^\]]*\] *', '', line) elif re.search(r'\[NOINDENT\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r' *\[NOINDENT\] *', '', line) elif re.search(r'\[FLUSHLEFT\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r' *\[FLUSHLEFT\] *', '', line) special_after_space = after_space_multiplier * 1 special_spacing = rtf_spacing['single'] elif re.search(r'\[FLUSHRIGHT\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\ql', r'\\qr', line) line = re.sub(r' *\[FLUSHRIGHT\] *', '', line) special_after_space = after_space_multiplier * 1 special_spacing = rtf_spacing['single'] elif re.search(r'\[CENTER\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\ql', r'\\qc', line) line = re.sub(r' *\[CENTER\] *', '', line) elif re.search(r'\[BOLDCENTER\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\ql', r'\\qc \\b', line) line = re.sub(r' *\[BOLDCENTER\] *', '', line) elif indentation_command != '' and not re.search(r'\\widctlpar', line): line = re.sub(r'\\fi-?[0-9]+ ', indentation_command, line) if not re.search(r'\\s[0-9]', line): if special_spacing: spacing_command_to_use = special_spacing else: spacing_command_to_use = spacing_command line = re.sub(r'\\pard ', r'\\pard ' + text_type(spacing_command_to_use) + text_type(border_text), line) line = re.sub(r'\\pard\\intbl ', r'\\pard\\intbl ' + text_type(spacing_command_to_use) + text_type(border_text), line) if not (re.search(r'\\fi0\\(endash|bullet)', line) or re.search(r'\\s[0-9]', line) or re.search(r'\\intbl', line)): if special_after_space: after_space_to_use = special_after_space else: after_space_to_use = after_space if after_space_to_use > 0: line = re.sub(r'\\sa[0-9]+ ', r'\\sa' + text_type(after_space_to_use) + ' ', line) else: line = re.sub(r'\\sa[0-9]+ ', r'\\sa0 ', line) text += line + '\n' text = re.sub(r'{\\pard \\sl[0-9]+\\slmult[0-9]+ \\ql \\f[0-9]+ \\sa[0-9]+ \\li[0-9]+ \\fi-?[0-9]*\s*\\par}', r'', text) text = re.sub(r'\[MANUALSKIP\]', r'{\\pard \\sl0 \\ql \\f0 \\sa0 \\li0 \\fi0 \\par}', text) return(text) def docx_filter(text, metadata=None, question=None): if metadata is None: metadata = dict() text = text + "\n\n" text = re.sub(r'\[\[([^\]]*)\]\]', r'\1', text) text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_include_docx, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_include_docx, text) text = re.sub(r'\[QR ([^\]]+)\]', qr_include_docx, text) text = re.sub(r'\[MAP ([^\]]+)\]', '', text) text = replace_fields(text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) text = re.sub(r'\[TARGET ([^\]]+)\]', '', text) text = re.sub(r'\[YOUTUBE[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[VIMEO[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\\clearpage *\\clearpage', '', text) text = re.sub(r'\[START_INDENTATION\]', '', text) text = re.sub(r'\[STOP_INDENTATION\]', '', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', '', text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\[BREAK\]\s*(.+?)\[END_TWOCOL\]', '', text, flags=re.DOTALL) text = re.sub(r'\[TIGHTSPACING\] *', '', text) text = re.sub(r'\[SINGLESPACING\] *', '', text) text = re.sub(r'\[DOUBLESPACING\] *', '', text) text = re.sub(r'\[ONEANDAHALFSPACING\] *', '', text) text = re.sub(r'\[TRIPLESPACING\] *', '', text) text = re.sub(r'\[NBSP\]', ' ', text) text = re.sub(r'\[REDACTION_SPACE\]', u'█​', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along(u'█', x), text) text = re.sub(r'\[ENDASH\]', '--', text) text = re.sub(r'\[EMDASH\]', '---', text) text = re.sub(r'\[HYPHEN\]', '-', text) text = re.sub(r'\[CHECKBOX\]', '____', text) text = re.sub(r'\[BLANK\]', r'__________________', text) text = re.sub(r'\[BLANKFILL\]', r'__________________', text) text = re.sub(r'\[PAGEBREAK\] *', '', text) text = re.sub(r'\[PAGENUM\] *', '', text) text = re.sub(r'\[TOTALPAGES\] *', '', text) text = re.sub(r'\[SECTIONNUM\] *', '', text) text = re.sub(r'\[SKIPLINE\] *', '\n\n', text) text = re.sub(r'\[VERTICALSPACE\] *', '\n\n', text) text = re.sub(r'\[NEWLINE\] *', '\n\n', text) text = re.sub(r'\[NEWPAR\] *', '\n\n', text) text = re.sub(r'\[BR\] *', '\n\n', text) text = re.sub(r'\[TAB\] *', '', text) text = re.sub(r' *\[END\] *', r'\n', text) text = re.sub(r'\[BORDER\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[NOINDENT\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHLEFT\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHRIGHT\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[CENTER\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BOLDCENTER\] *(.+?)\n *\n', r'**\1**\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', r'\2', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+) *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', r'\3', text, flags=re.MULTILINE | re.DOTALL) return(text) def docx_template_filter(text, question=None): #logmessage('docx_template_filter') if text == 'True': return True elif text == 'False': return False elif text == 'None': return None text = re.sub(r'\[\[([^\]]*)\]\]', r'\1', text) text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_include_docx_template, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_include_docx_template, text) text = re.sub(r'\[QR ([^\]]+)\]', qr_include_docx_template, text) text = re.sub(r'\[MAP ([^\]]+)\]', '', text) text = replace_fields(text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) text = re.sub(r'\[TARGET ([^\]]+)\]', '', text) text = re.sub(r'\[YOUTUBE[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[VIMEO[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\\clearpage *\\clearpage', '', text) text = re.sub(r'\[START_INDENTATION\]', '', text) text = re.sub(r'\[STOP_INDENTATION\]', '', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', '', text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\[BREAK\]\s*(.+?)\[END_TWOCOL\]', '', text, flags=re.DOTALL) text = re.sub(r'\[TIGHTSPACING\] *', '', text) text = re.sub(r'\[SINGLESPACING\] *', '', text) text = re.sub(r'\[DOUBLESPACING\] *', '', text) text = re.sub(r'\[ONEANDAHALFSPACING\] *', '', text) text = re.sub(r'\[TRIPLESPACING\] *', '', text) text = re.sub(r'\[NBSP\]', ' ', text) text = re.sub(r'\[REDACTION_SPACE\]', r'█​', text) #text = re.sub(r'\[REDACTION_SPACE\]', r'', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along('█', x), text) #text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along('X', x), text) text = re.sub(r'\[ENDASH\]', '--', text) text = re.sub(r'\[EMDASH\]', '---', text) text = re.sub(r'\[HYPHEN\]', '-', text) text = re.sub(r'\\', '', text) text = re.sub(r'\[CHECKBOX\]', '____', text) text = re.sub(r'\[BLANK\]', r'__________________', text) text = re.sub(r'\[BLANKFILL\]', r'__________________', text) text = re.sub(r'\[PAGEBREAK\] *', '', text) text = re.sub(r'\[PAGENUM\] *', '', text) text = re.sub(r'\[TOTALPAGES\] *', '', text) text = re.sub(r'\[SECTIONNUM\] *', '', text) text = re.sub(r'\[SKIPLINE\] *', '</w:t><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[VERTICALSPACE\] *', '</w:t><w:br/><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[NEWLINE\] *', '</w:t><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\n *\n', '[NEWPAR]', text) text = re.sub(r'\n', ' ', text) text = re.sub(r'\[NEWPAR\] *', '</w:t><w:br/><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[TAB\] *', '\t', text) text = re.sub(r'\[NEWPAR\]', '</w:t><w:br/><w:br/><w:t xml:space="preserve">', text) text = re.sub(r' *\[END\] *', r'</w:t><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[BORDER\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[NOINDENT\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHLEFT\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHRIGHT\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[CENTER\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BOLDCENTER\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', r'\2', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+) *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', r'\3', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BR\]', '</w:t><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[SKIPLINE\]', '</w:t><w:br/><w:t xml:space="preserve">', text) return(text) def metadata_filter(text, doc_format): if doc_format == 'pdf': text = re.sub(r'\*\*([^\*]+?)\*\*', r'\\begingroup\\bfseries \1\\endgroup {}', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\*([^\*]+?)\*', r'\\begingroup\\itshape \1\\endgroup {}', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\_\_([^\_]+?)\_\_', r'\\begingroup\\bfseries \1\\endgroup {}', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\_([^\_]+?)\_*', r'\\begingroup\\itshape \1\\endgroup {}', text, flags=re.MULTILINE | re.DOTALL) return text def redact_latex(match): return u'\\redactword{' + text_type(escape_latex(match.group(1))) + u'}' def pdf_filter(text, metadata=None, question=None): if metadata is None: metadata = dict() #if len(metadata): # text = yaml.dump(metadata) + "\n---\n" + text text = text + "\n\n" text = re.sub(r'\[\[([^\]]*)\]\]', r'\1', text) text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_string(x, emoji=True, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_include_string(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_string(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_include_string(x, question=question), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_include_string, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_include_string, text) text = re.sub(r'\[QR ([^\]]+)\]', qr_include_string, text) text = re.sub(r'\[MAP ([^\]]+)\]', '', text) text = replace_fields(text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) text = re.sub(r'\[TARGET ([^\]]+)\]', '', text) text = re.sub(r'\[YOUTUBE[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[VIMEO[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\$\$+', '$', text) text = re.sub(r'\\clearpage *\\clearpage', r'\\clearpage', text) text = re.sub(r'\[BORDER\]\s*\[(BEGIN_TWOCOL|BEGIN_CAPTION|TIGHTSPACING|SINGLESPACING|DOUBLESPACING|START_INDENTATION|STOP_INDENTATION|NOINDENT|FLUSHLEFT|FLUSHRIGHT|CENTER|BOLDCENTER|INDENTBY[^\]]*)\]', r'[\1] [BORDER]', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[START_INDENTATION\]', r'\\setlength{\\parindent}{\\myindentamount}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[STOP_INDENTATION\]', r'\\setlength{\\parindent}{0in}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', pdf_caption, text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\[BREAK\]\s*(.+?)\[END_TWOCOL\]', pdf_two_col, text, flags=re.DOTALL) text = re.sub(r'\[TIGHTSPACING\]\s*', r'\\singlespacing\\setlength{\\parskip}{0pt}\\setlength{\\parindent}{0pt}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[SINGLESPACING\]\s*', r'\\singlespacing\\setlength{\\parskip}{\\myfontsize}\\setlength{\\parindent}{0pt}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[DOUBLESPACING\]\s*', r'\\doublespacing\\setlength{\\parindent}{\\myindentamount}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[ONEANDAHALFSPACING\]\s*', r'\\onehalfspacing\\setlength{\\parindent}{\\myindentamount}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[TRIPLESPACING\]\s*', r'\\setlength{\\parindent}{\\myindentamount}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[NBSP\]', r'\\myshow{\\nonbreakingspace}', text) text = re.sub(r'\[REDACTION_SPACE\]', r'\\redactword{~}\\hspace{0pt}', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', redact_latex, text) text = re.sub(r'\[ENDASH\]', r'\\myshow{\\myendash}', text) text = re.sub(r'\[EMDASH\]', r'\\myshow{\\myemdash}', text) text = re.sub(r'\[HYPHEN\]', r'\\myshow{\\myhyphen}', text) text = re.sub(r'\[CHECKBOX\]', r'{\\rule{0.3in}{0.4pt}}', text) text = re.sub(r'\[BLANK\]', r'\\leavevmode{\\xrfill[-2pt]{0.4pt}}', text) text = re.sub(r'\[BLANKFILL\]', r'\\leavevmode{\\xrfill[-2pt]{0.4pt}}', text) text = re.sub(r'\[PAGEBREAK\]\s*', r'\\clearpage ', text) text = re.sub(r'\[PAGENUM\]', r'\\myshow{\\thepage\\xspace}', text) text = re.sub(r'\[TOTALPAGES\]', r'\\myshow{\\pageref*{LastPage}\\xspace}', text) text = re.sub(r'\[SECTIONNUM\]', r'\\myshow{\\thesection\\xspace}', text) text = re.sub(r'\s*\[SKIPLINE\]\s*', r'\\par\\myskipline ', text) text = re.sub(r'\[VERTICALSPACE\] *', r'\\rule[-24pt]{0pt}{0pt}', text) text = re.sub(r'\[NEWLINE\] *', r'\\newline ', text) text = re.sub(r'\[NEWPAR\] *', r'\\par ', text) text = re.sub(r'\[BR\] *', r'\\manuallinebreak ', text) text = re.sub(r'\[TAB\] *', r'\\manualindent ', text) text = re.sub(r' *\[END\] *', r'\n', text) text = re.sub(r'\[NOINDENT\] *', r'\\noindent ', text) text = re.sub(r'\[FLUSHLEFT\] *(.+?)\n *\n', flushleft_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHRIGHT\] *(.+?)\n *\n', flushright_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[CENTER\] *(.+?)\n *\n', center_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BOLDCENTER\] *(.+?)\n *\n', boldcenter_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', indentby_left_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+) *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', indentby_both_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BORDER\] *(.+?)\n *\n', border_pdf, text, flags=re.MULTILINE | re.DOTALL) return(text) def html_filter(text, status=None, question=None, embedder=None, default_image_width=None): if question is None and status is not None: question = status.question text = text + "\n\n" text = re.sub(r'^[|] (.*)$', r'\1<br>', text, flags=re.MULTILINE) text = replace_fields(text, status=status, embedder=embedder) # if embedder is not None: # text = re.sub(r'\[FIELD ([^\]]+)\]', lambda x: embedder(status, x.group(1)), text) # else: # text = re.sub(r'\[FIELD ([^\]]+)\]', 'ERROR: FIELD cannot be used here', text) text = re.sub(r'\[TARGET ([^\]]+)\]', target_html, text) if docassemble.base.functions.this_thread.evaluation_context != 'docx': text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_url_string(x, emoji=True, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_url_string(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_url_string(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_url_string(x, question=question, default_image_width=default_image_width), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_url_string, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_url_string, text) text = re.sub(r'\[QR ([^,\]]+)\]', qr_url_string, text) if map_match.search(text): text = map_match.sub((lambda x: map_string(x.group(1), status)), text) # width="420" height="315" text = re.sub(r'\[YOUTUBE ([^\]]+)\]', r'<div class="davideo davideo169"><iframe src="https://www.youtube.com/embed/\1?rel=0" frameborder="0" allowfullscreen></iframe></div>', text) text = re.sub(r'\[YOUTUBE4:3 ([^\]]+)\]', r'<div class="davideo davideo43"><iframe src="https://www.youtube.com/embed/\1?rel=0" frameborder="0" allowfullscreen></iframe></div>', text) text = re.sub(r'\[YOUTUBE16:9 ([^\]]+)\]', r'<div class="davideo davideo169"><iframe src="https://www.youtube.com/embed/\1?rel=0" frameborder="0" allowfullscreen></iframe></div>', text) # width="500" height="281" text = re.sub(r'\[VIMEO ([^\]]+)\]', r'<div class="davideo davideo169"><iframe src="https://player.vimeo.com/video/\1?byline=0&portrait=0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>', text) text = re.sub(r'\[VIMEO4:3 ([^\]]+)\]', r'<div class="davideo davideo43"><iframe src="https://player.vimeo.com/video/\1?byline=0&portrait=0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>', text) text = re.sub(r'\[VIMEO16:9 ([^\]]+)\]', r'<div class="davideo davideo169"><iframe src="https://player.vimeo.com/video/\1?byline=0&portrait=0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', html_caption, text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\[BREAK\]\s*(.+?)\[END_TWOCOL\]', html_two_col, text, flags=re.DOTALL) text = re.sub(r'\[TIGHTSPACING\] *', r'', text) text = re.sub(r'\[SINGLESPACING\] *', r'', text) text = re.sub(r'\[DOUBLESPACING\] *', r'', text) text = re.sub(r'\[ONEANDAHALFSPACING\] *', '', text) text = re.sub(r'\[TRIPLESPACING\] *', '', text) text = re.sub(r'\[START_INDENTATION\] *', r'', text) text = re.sub(r'\[STOP_INDENTATION\] *', r'', text) text = re.sub(r'\[NBSP\]', r'&nbsp;', text) text = re.sub(r'\[REDACTION_SPACE\]', '&#9608;&#8203;', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along('&#9608;', x), text) text = re.sub(r'\[ENDASH\]', r'&ndash;', text) text = re.sub(r'\[EMDASH\]', r'&mdash;', text) text = re.sub(r'\[HYPHEN\]', r'-', text) text = re.sub(r'\[CHECKBOX\]', r'<span style="text-decoration: underline">&nbsp;&nbsp;&nbsp;&nbsp;</span>', text) text = re.sub(r'\[BLANK\]', r'<span style="text-decoration: underline">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>', text) text = re.sub(r'\[BLANKFILL\]', r'<span style="text-decoration: underline">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>', text) text = re.sub(r'\[PAGEBREAK\] *', r'', text) text = re.sub(r'\[PAGENUM\] *', r'', text) text = re.sub(r'\[SECTIONNUM\] *', r'', text) text = re.sub(r'\[SKIPLINE\] *', r'<br />', text) text = re.sub(r'\[NEWLINE\] *', r'<br />', text) text = re.sub(r'\[NEWPAR\] *', r'<br /><br />', text) text = re.sub(r'\[BR\] *', r'<br />', text) text = re.sub(r'\[TAB\] *', '<span class="datab"></span>', text) text = re.sub(r' *\[END\] *', r'\n', text) lines = re.split(r'\n *\n', text) text = '' for line in lines: classes = set() styles = dict() if re.search(r'\[BORDER\]', line): classes.add('daborder') if re.search(r'\[NOINDENT\]', line): classes.add('daflushleft') if re.search(r'\[FLUSHLEFT\]', line): classes.add('daflushleft') if re.search(r'\[FLUSHRIGHT\]', line): classes.add('daflushright') if re.search(r'\[CENTER\]', line): classes.add('dacenter') if re.search(r'\[BOLDCENTER\]', line): classes.add('dacenter') classes.add('dabold') m = re.search(r'\[INDENTBY *([0-9]+ *[A-Za-z]+)\]', line) if m: styles["padding-left"] = text_type(convert_length(m.group(1), 'px')) + 'px' m = re.search(r'\[INDENTBY *([0-9]+ *[A-Za-z]+) *([0-9]+ *[A-Za-z]+)\]', line) if m: styles["margin-left"] = text_type(convert_length(m.group(1), 'px')) + 'px' styles["margin-right"] = text_type(convert_length(m.group(2), 'px')) + 'px' line = re.sub(r'\[(BORDER|NOINDENT|FLUSHLEFT|FLUSHRIGHT|BOLDCENTER|CENTER)\] *', r'', line) line = re.sub(r'\[INDENTBY[^\]]*\]', r'', line) if len(classes) or len(styles): text += "<p" if len(classes): text += ' class="' + " ".join(classes) + '"' if len(styles): text += ' style="' + "".join(map(lambda x: text_type(x) + ":" + styles[x] + ';', styles.keys())) + '"' text += ">" + line + '</p>\n\n' else: text += line + '\n\n' text = re.sub(r'\\_', r'__', text) text = re.sub(r'\n+$', r'', text) return(text) def clean_markdown_to_latex(string): string = re.sub(r'\s*\[SKIPLINE\]\s*', r'\\par\\myskipline ', string) string = re.sub(r'^[\n ]+', '', string) string = re.sub(r'[\n ]+$', '', string) string = re.sub(r' *\n *$', '\n', string) string = re.sub(r'\n{2,}', '[NEWLINE]', string) string = re.sub(r'\[BR\]', '[NEWLINE]', string) string = re.sub(r'\[(NOINDENT|FLUSHLEFT|FLUSHRIGHT|CENTER|BOLDCENTER|TIGHTSPACING|SINGLESPACING|DOUBLESPACING|START_INDENTATION|STOP_INDENTATION|PAGEBREAK)\]\s*', '', string) string = re.sub(r'\*\*([^\*]+?)\*\*', r'\\textbf{\1}', string) string = re.sub(r'\*([^\*]+?)\*', r'\\emph{\1}', string) string = re.sub(r'(?<!\\)_([^_]+?)_', r'\\emph{\1}', string) string = re.sub(r'\[([^\]]+?)\]\(([^\)]+?)\)', r'\\href{\2}{\1}', string) return string; def map_string(encoded_text, status): if status is None: return '' map_number = len(status.maps) status.maps.append(codecs.decode(bytearray(encoded_text, 'utf-8'), 'base64').decode()) return '<div id="map' + text_type(map_number) + '" class="dagoogleMap"></div>' def target_html(match): target = match.group(1) target = re.sub(r'[^A-Za-z0-9\_]', r'', text_type(target)) return '<span id="datarget' + target + '"></span>' def pdf_two_col(match, add_line=False): firstcol = clean_markdown_to_latex(match.group(1)) secondcol = clean_markdown_to_latex(match.group(2)) if add_line: return '\\noindent\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\mynoindent\\begin{tabular}{@{}m{0.49\\textwidth}|@{\\hspace{1em}}m{0.49\\textwidth}@{}}{' + firstcol + '} & {' + secondcol + '} \\\\ \\end{tabular}\\endgroup\\myskipline' else: return '\\noindent\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\mynoindent\\begin{tabular}{@{}m{0.49\\textwidth}@{\\hspace{1em}}m{0.49\\textwidth}@{}}{' + firstcol + '} & {' + secondcol + '} \\\\ \\end{tabular}\\endgroup\\myskipline' def html_caption(match): firstcol = match.group(1) secondcol = match.group(2) firstcol = re.sub(r'^\s+', '', firstcol) firstcol = re.sub(r'\s+$', '', firstcol) secondcol = re.sub(r'^\s+', '', secondcol) secondcol = re.sub(r'\s+$', '', secondcol) firstcol = re.sub(r'\n{2,}', '<br>', firstcol) secondcol = re.sub(r'\n{2,}', '<br>', secondcol) return '<table style="width: 100%"><tr><td style="width: 50%; border-style: solid; border-right-width: 1px; padding-right: 1em; border-left-width: 0px; border-top-width: 0px; border-bottom-width: 0px">' + firstcol + '</td><td style="padding-left: 1em; width: 50%;">' + secondcol + '</td></tr></table>' def html_two_col(match): firstcol = markdown_to_html(match.group(1)) secondcol = markdown_to_html(match.group(2)) return '<table style="width: 100%"><tr><td style="width: 50%; vertical-align: top; border-style: none; padding-right: 1em;">' + firstcol + '</td><td style="padding-left: 1em; vertical-align: top; width: 50%;">' + secondcol + '</td></tr></table>' def pdf_caption(match): return pdf_two_col(match, add_line=False) def add_newlines(string): string = re.sub(r'\[(BR)\]', r'[NEWLINE]', string) string = re.sub(r' *\n', r'\n', string) string = re.sub(r'(?<!\[NEWLINE\])\n', r' [NEWLINE]\n', string) return string def border_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return('\\mdframed\\setlength{\\parindent}{0pt} ' + text_type(string) + '\n\n\\endmdframed' + "\n\n") def flushleft_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return borderify('\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\setlength{\\parindent}{0pt}\\noindent ' + text_type(string) + '\\par\\endgroup') + "\n\n" def flushright_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return borderify('\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\setlength{\\parindent}{0pt}\\RaggedLeft ' + text_type(string) + '\\par\\endgroup') + "\n\n" def center_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return borderify('\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\Centering\\noindent ' + text_type(string) + '\\par\\endgroup') + "\n\n" def boldcenter_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return borderify('\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\Centering\\bfseries\\noindent ' + text_type(string) + '\\par\\endgroup') + "\n\n" def indentby_left_pdf(match): string = match.group(2) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) if re.search(r'\[BORDER\]', string): string = re.sub(r' *\[BORDER\] *', r'', string) return '\\mdframed[leftmargin=' + text_type(convert_length(match.group(1), 'pt')) + 'pt]\n\\noindent ' + text_type(string) + '\n\n\\endmdframed' + "\n\n" return '\\begingroup\\setlength{\\leftskip}{' + text_type(convert_length(match.group(1), 'pt')) + 'pt}\\noindent ' + text_type(string) + '\\par\\endgroup' + "\n\n" def indentby_both_pdf(match): string = match.group(3) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) if re.search(r'\[BORDER\]', string): string = re.sub(r' *\[BORDER\] *', r'', string) return '\\mdframed[leftmargin=' + text_type(convert_length(match.group(1), 'pt')) + 'pt,rightmargin=' + text_type(convert_length(match.group(2), 'pt')) + 'pt]\n\\noindent ' + text_type(string) + '\n\n\\endmdframed' + "\n\n" return '\\begingroup\\setlength{\\leftskip}{' + text_type(convert_length(match.group(1), 'pt')) + 'pt}\\setlength{\\rightskip}{' + text_type(convert_length(match.group(2), 'pt')) + 'pt}\\noindent ' + text_type(string) + '\\par\\endgroup' + "\n\n" def borderify(string): if not re.search(r'\[BORDER\]', string): return string string = re.sub(r'\[BORDER\] *', r'', string) return('\\mdframed ' + text_type(string) + '\\endmdframed') def image_as_rtf(match, question=None): width_supplied = False try: width = match.group(2) assert width != 'None' width_supplied = True except: width = DEFAULT_IMAGE_WIDTH if width == 'full': width_supplied = False file_reference = match.group(1) file_info = server.file_finder(file_reference, convert={'svg': 'png', 'gif': 'png'}, question=question) if 'path' not in file_info: return '' #logmessage('image_as_rtf: path is ' + file_info['path']) if 'mimetype' in file_info: if re.search(r'^(audio|video)', file_info['mimetype']): return '[reference to file type that cannot be displayed]' if 'width' in file_info: try: return rtf_image(file_info, width, False) except: return '[graphic could not be inserted]' elif file_info['extension'] in ('pdf', 'docx', 'rtf', 'doc', 'odt'): output = '' if not width_supplied: #logmessage("image_as_rtf: Adding page break\n") width = DEFAULT_PAGE_WIDTH #output += '\\page ' #logmessage("image_as_rtf: maxpage is " + text_type(int(file_info['pages'])) + "\n") if not os.path.isfile(file_info['path'] + '.pdf'): if file_info['extension'] in ('docx', 'rtf', 'doc', 'odt') and not os.path.isfile(file_info['path'] + '.pdf'): server.fg_make_pdf_for_word_path(file_info['path'], file_info['extension']) if 'pages' not in file_info: try: reader = PyPDF2.PdfFileReader(open(file_info['path'] + '.pdf', 'rb')) file_info['pages'] = reader.getNumPages() except: file_info['pages'] = 1 max_pages = 1 + int(file_info['pages']) formatter = '%0' + text_type(len(text_type(max_pages))) + 'd' for page in range(1, max_pages): #logmessage("image_as_rtf: doing page " + text_type(page) + "\n") page_file = dict() test_path = file_info['path'] + 'page-in-progress' #logmessage("Test path is " + test_path) if os.path.isfile(test_path): #logmessage("image_as_rtf: test path " + test_path + " exists") while (os.path.isfile(test_path) and time.time() - os.stat(test_path)[stat.ST_MTIME]) < 30: #logmessage("Waiting for test path to go away") if not os.path.isfile(test_path): break time.sleep(1) page_file['extension'] = 'png' page_file['path'] = file_info['path'] + 'page-' + formatter % page page_file['fullpath'] = page_file['path'] + '.png' if not os.path.isfile(page_file['fullpath']): server.fg_make_png_for_pdf_path(file_info['path'] + '.pdf', 'page') if os.path.isfile(page_file['fullpath']): im = PIL.Image.open(page_file['fullpath']) page_file['width'], page_file['height'] = im.size output += rtf_image(page_file, width, False) else: output += "[Error including page image]" # if not width_supplied: # #logmessage("Adding page break\n") # output += '\\page ' # else: output += ' ' #logmessage("Returning output\n") return(output) else: return('') def qr_as_rtf(match): width_supplied = False try: width = match.group(2) assert width != 'None' width_supplied = True except: width = DEFAULT_IMAGE_WIDTH if width == 'full': width_supplied = False string = match.group(1) output = '' if not width_supplied: #logmessage("Adding page break\n") width = DEFAULT_PAGE_WIDTH output += '\\page ' im = qrcode.make(string) the_image = tempfile.NamedTemporaryFile(suffix=".png") im.save(the_image.name) page_file = dict() page_file['extension'] = 'png' page_file['fullpath'] = the_image.name page_file['width'], page_file['height'] = im.size output += rtf_image(page_file, width, False) if not width_supplied: #logmessage("Adding page break\n") output += '\\page ' else: output += ' ' #logmessage("Returning output\n") return(output) def rtf_image(file_info, width, insert_page_breaks): pixels = pixels_in(width) if pixels > 0 and file_info['width'] > 0: scale = float(pixels)/float(file_info['width']) #logmessage("scale is " + text_type(scale) + "\n") if scale*float(file_info['height']) > float(MAX_HEIGHT_POINTS): scale = float(MAX_HEIGHT_POINTS)/float(file_info['height']) #logmessage("scale is " + text_type(scale) + "\n") if scale*float(file_info['width']) > float(MAX_WIDTH_POINTS): scale = float(MAX_WIDTH_POINTS)/float(file_info['width']) #logmessage("scale is " + text_type(scale) + "\n") #scale *= 100.0 #logmessage("scale is " + text_type(scale) + "\n") #scale = int(scale) #logmessage("scale is " + text_type(scale) + "\n") wtwips = int(scale*float(file_info['width'])*20.0) htwips = int(scale*float(file_info['height'])*20.0) image = Image( file_info['fullpath'] ) image.Data = re.sub(r'\\picwgoal([0-9]+)', r'\\picwgoal' + text_type(wtwips), image.Data) image.Data = re.sub(r'\\pichgoal([0-9]+)', r'\\pichgoal' + text_type(htwips), image.Data) else: image = Image( file_info['fullpath'] ) if insert_page_breaks: content = '\\page ' else: content = '' #logmessage(content + image.Data) return(content + image.Data) unit_multipliers = {'twips': 0.0500, 'hp': 0.5, 'in': 72, 'pt': 1, 'px': 1, 'em': 12, 'cm': 28.346472} def convert_length(length, unit): value = pixels_in(length) if unit in unit_multipliers: size = float(value)/float(unit_multipliers[unit]) return(int(size)) else: logmessage("Unit " + text_type(unit) + " is not a valid unit\n") return(300) def pixels_in(length): m = re.search(r"([0-9.]+) *([a-z]+)", text_type(length).lower()) if m: value = float(m.group(1)) unit = m.group(2) #logmessage("value is " + text_type(value) + " and unit is " + unit + "\n") if unit in unit_multipliers: size = float(unit_multipliers[unit]) * value #logmessage("size is " + text_type(size) + "\n") return(int(size)) logmessage("Could not read " + text_type(length) + "\n") return(300) def image_url_string(match, emoji=False, question=None, playground=False, default_image_width=None): file_reference = match.group(1) try: width = match.group(2) assert width != 'None' except: if default_image_width is not None: width = default_image_width else: width = "300px" if width == "full": width = "300px" if match.lastindex == 3: if match.group(3) != 'None': alt_text = 'alt=' + json.dumps(match.group(3)) + ' ' else: alt_text = '' else: alt_text = '' file_info = server.file_finder(file_reference, question=question) if 'mimetype' in file_info and file_info['mimetype'] is not None: if re.search(r'^audio', file_info['mimetype']): urls = get_audio_urls([{'text': "[FILE " + file_reference + "]", 'package': None, 'type': 'audio'}], question=question) if len(urls): return audio_control(urls) return '' if re.search(r'^video', file_info['mimetype']): urls = get_video_urls([{'text': "[FILE " + file_reference + "]", 'package': None, 'type': 'video'}], question=question) if len(urls): return video_control(urls) return '' if 'extension' in file_info and file_info['extension'] is not None: if re.match(r'.*%$', width): width_string = "width:" + width else: width_string = "max-width:" + width if emoji: width_string += ';vertical-align: middle' alt_text = 'alt="" ' the_url = server.url_finder(file_reference, _question=question, display_filename=file_info['filename']) if the_url is None: return ('[ERROR: File reference ' + text_type(file_reference) + ' cannot be displayed]') if width_string == 'width:100%': extra_class = ' dawideimage' else: extra_class = '' if file_info.get('extension', '') in ['png', 'jpg', 'gif', 'svg', 'jpe', 'jpeg']: return('<img ' + alt_text + 'class="daicon daimageref' + extra_class + '" style="' + width_string + '" src="' + the_url + '"/>') elif file_info['extension'] in ('pdf', 'docx', 'rtf', 'doc', 'odt'): if file_info['extension'] in ('docx', 'rtf', 'doc', 'odt') and not os.path.isfile(file_info['path'] + '.pdf'): server.fg_make_pdf_for_word_path(file_info['path'], file_info['extension']) server.fg_make_png_for_pdf_path(file_info['path'] + ".pdf", 'screen', page=1) if 'pages' not in file_info: try: reader = PyPDF2.PdfFileReader(open(file_info['path'] + '.pdf', 'rb')) file_info['pages'] = reader.getNumPages() except: file_info['pages'] = 1 image_url = server.url_finder(file_reference, size="screen", page=1, _question=question) if image_url is None: return ('[ERROR: File reference ' + text_type(file_reference) + ' cannot be displayed]') if 'filename' in file_info: title = ' title="' + file_info['filename'] + '"' else: title = '' if alt_text == '': the_alt_text = 'alt=' + json.dumps(word("Thumbnail image of document")) + ' ' else: the_alt_text = alt_text output = '<a target="_blank"' + title + ' class="daimageref" href="' + the_url + '"><img ' + the_alt_text + 'class="daicon dapdfscreen' + extra_class + '" style="' + width_string + '" src="' + image_url + '"/></a>' if 'pages' in file_info and file_info['pages'] > 1: output += " (" + text_type(file_info['pages']) + " " + word('pages') + ")" return(output) else: return('<a target="_blank" class="daimageref" href="' + the_url + '">' + file_info['filename'] + '</a>') else: return('[Invalid image reference; reference=' + text_type(file_reference) + ', width=' + text_type(width) + ', filename=' + file_info.get('filename', 'unknown') + ']') def qr_url_string(match): string = match.group(1) try: width = match.group(2) assert width != 'None' except: width = "300px" if width == "full": width = "300px" if match.lastindex == 3: if match.group(3) != 'None': alt_text = text_type(match.group(3)) else: alt_text = word("A QR code") else: alt_text = word("A QR code") width_string = "width:" + width im = qrcode.make(string, image_factory=qrcode.image.svg.SvgPathImage) output = BytesIO() im.save(output) the_image = output.getvalue().decode() the_image = re.sub("<\?xml version='1.0' encoding='UTF-8'\?>\n", '', the_image) the_image = re.sub(r'height="[0-9]+mm" ', '', the_image) the_image = re.sub(r'width="[0-9]+mm" ', '', the_image) m = re.search(r'(viewBox="[^"]+")', the_image) if m: viewbox = m.group(1) else: viewbox = "" return('<svg style="' + width_string + '" ' + viewbox + '><g transform="scale(1.0)">' + the_image + '</g><title>' + alt_text + '</title></svg>') def convert_pixels(match): pixels = match.group(1) return (text_type(int(pixels)/72.0) + "in") def image_include_string(match, emoji=False, question=None): file_reference = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '\\textwidth' except: width = DEFAULT_IMAGE_WIDTH file_info = server.file_finder(file_reference, convert={'svg': 'eps', 'gif': 'png'}, question=question) if 'mimetype' in file_info: if re.search(r'^(audio|video)', file_info['mimetype']): return '[reference to file type that cannot be displayed]' if 'path' in file_info: if 'extension' in file_info: if file_info['extension'] in ['png', 'jpg', 'pdf', 'eps', 'jpe', 'jpeg', 'docx', 'rtf', 'doc', 'odt']: if file_info['extension'] == 'pdf': output = '\\includepdf[pages={-}]{' + file_info['path'] + '.pdf}' elif file_info['extension'] in ('docx', 'rtf', 'doc', 'odt'): if not os.path.isfile(file_info['path'] + '.pdf'): server.fg_make_pdf_for_word_path(file_info['path'], file_info['extension']) output = '\\includepdf[pages={-}]{' + file_info['path'] + '.pdf}' else: if emoji: output = '\\raisebox{-.6\\dp\\strutbox}{\\mbox{\\includegraphics[width=' + width + ']{' + file_info['path'] + '}}}' else: output = '\\mbox{\\includegraphics[width=' + width + ']{' + file_info['path'] + '}}' if width == '\\textwidth': output = '\\clearpage ' + output + '\\clearpage ' return(output) return('[invalid graphics reference]') def image_include_docx(match, question=None): file_reference = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '100%' except: width = DEFAULT_IMAGE_WIDTH file_info = server.file_finder(file_reference, convert={'svg': 'eps'}, question=question) if 'mimetype' in file_info: if re.search(r'^(audio|video)', file_info['mimetype']): return '[reference to file type that cannot be displayed]' if 'path' in file_info: if 'extension' in file_info: if file_info['extension'] in ('docx', 'rtf', 'doc', 'odt'): if not os.path.isfile(file_info['path'] + '.pdf'): server.fg_make_pdf_for_word_path(file_info['path'], file_info['extension']) output = '![](' + file_info['path'] + '.pdf){width=' + width + '}' return(output) if file_info['extension'] in ['png', 'jpg', 'gif', 'pdf', 'eps', 'jpe', 'jpeg']: output = '![](' + file_info['path'] + '){width=' + width + '}' return(output) return('[invalid graphics reference]') def qr_include_string(match): string = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '\\textwidth' except: width = DEFAULT_IMAGE_WIDTH im = qrcode.make(string) the_image = tempfile.NamedTemporaryFile(prefix="datemp", suffix=".png", delete=False) #docassemble.base.functions.this_thread.temporary_resources.add(the_image.name) im.save(the_image.name) output = '\\mbox{\\includegraphics[width=' + width + ']{' + the_image.name + '}}' if width == '\\textwidth': output = '\\clearpage ' + output + '\\clearpage ' #logmessage("Output is " + output) return(output) def qr_include_docx(match): string = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '100%' except: width = DEFAULT_IMAGE_WIDTH im = qrcode.make(string) the_image = tempfile.NamedTemporaryFile(prefix="datemp", suffix=".png", delete=False) #docassemble.base.functions.this_thread.temporary_resources.add(the_image.name) im.save(the_image.name) output = '![](' + the_image.name + '){width=' + width + '}' return(output) def rtf_caption_table(match): table_text = """\\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrs\\brdrw10 \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrs\\brdrw10 \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\pararsid1508006\\yts24 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs22\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 { [SAVE][TIGHTSPACING][STOP_INDENTATION]""" + match.group(1) + """}{\\cell}{""" + match.group(2) + """[RESTORE]}{\\cell}\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\sa200\\sl276\\slmult1\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs24\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid10753242 \\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrs\\brdrw10 \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrs\\brdrw10 \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\row }""" table_text += """\\pard \\ltrpar \\qc \\li0\\ri0\\sb0\\sl240\\slmult1\\widctlpar\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\itap0\\pararsid10753242""" table_text = re.sub(r'\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0', r'\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\sl240 \\slmult1', table_text) return table_text + '[MANUALSKIP]' def rtf_two_col(match): table_text = """\\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\pararsid1508006\\yts24 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs22\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid2427490 [SAVE][TIGHTSPACING][STOP_INDENTATION]""" + match.group(1) + """}{\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid10753242\\charrsid2427490 \\cell}{""" + match.group(2) + """[RESTORE]}{\\cell}\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\sa200\\sl276\\slmult1\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs24\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid10753242 \\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\row }""" table_text += """\\pard \\ltrpar \\qc \\li0\\ri0\\sb0\\sl240\\slmult1\\widctlpar\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\itap0\\pararsid10753242""" table_text = re.sub(r'\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0', r'\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\sl240 \\slmult1', table_text) return table_text + '[MANUALSKIP]' def emoji_html(text, status=None, question=None, images=None): #logmessage("Got to emoji_html") if status is not None and question is None: question = status.question if images is None: images = question.interview.images if text in images: if status is not None and images[text].attribution is not None: status.attributions.add(images[text].attribution) return("[EMOJI " + images[text].get_reference() + ', 1em]') icons_setting = docassemble.base.functions.get_config('default icons', None) if icons_setting == 'font awesome': m = re.search(r'^(fa[a-z])-fa-(.*)', text) if m: the_prefix = m.group(1) text = m.group(2) else: the_prefix = docassemble.base.functions.get_config('font awesome prefix', 'fas') return('<i class="' + the_prefix + ' fa-' + text_type(text) + '"></i>') elif icons_setting == 'material icons': return('<i class="da-material-icons">' + text_type(text) + '</i>') return(":" + text_type(text) + ":") def emoji_insert(text, status=None, images=None): if images is None: images = status.question.interview.images if text in images: if status is not None and images[text].attribution is not None: status.attributions.add(images[text].attribution) return("[EMOJI " + images[text].get_reference() + ', 1.2em]') else: return(":" + text_type(text) + ":") def link_rewriter(m, status): if re.search(r'^(\?|javascript:)', m.group(1)): target = '' else: target = 'target="_blank" ' action_search = re.search(r'^\?action=([^\&]+)', m.group(1)) if action_search: action_data = 'data-embaction="' + action_search.group(1) + '" ' else: action_data = '' js_search = re.search(r'^javascript:(.*)', m.group(1)) if js_search: js_data = 'data-js="' + js_search.group(1) + '" ' else: js_data = '' if status is None: return '<a ' + action_data + target + js_data + 'href="' + m.group(1) + '"' status.linkcounter += 1 return '<a data-linknum="' + text_type(status.linkcounter) + '" ' + action_data + target + js_data + 'href="' + m.group(1) + '"' def markdown_to_html(a, trim=False, pclass=None, status=None, question=None, use_pandoc=False, escape=False, do_terms=True, indent=None, strip_newlines=None, divclass=None, embedder=None, default_image_width=None): a = text_type(a) if question is None and status is not None: question = status.question if question is not None: if do_terms: if status is not None: if len(question.terms): lang = docassemble.base.functions.get_language() for term in question.terms: if lang in question.terms[term]['re']: a = question.terms[term]['re'][lang].sub(r'[[\1]]', a) else: a = question.terms[term]['re'][question.language].sub(r'[[\1]]', a) if len(question.autoterms): lang = docassemble.base.functions.get_language() for term in question.autoterms: if lang in question.autoterms[term]['re']: a = question.autoterms[term]['re'][lang].sub(r'[[\1]]', a) else: a = question.autoterms[term]['re'][question.language].sub(r'[[\1]]', a) if len(question.interview.terms): lang = docassemble.base.functions.get_language() if lang in question.interview.terms and len(question.interview.terms[lang]) > 0: for term in question.interview.terms[lang]: #logmessage("Searching for term " + term + " in " + a + "\n") a = question.interview.terms[lang][term]['re'].sub(r'[[\1]]', a) #logmessage("string is now " + text_type(a) + "\n") elif question.language in question.interview.terms and len(question.interview.terms[question.language]) > 0: for term in question.interview.terms[question.language]: #logmessage("Searching for term " + term + " in " + a + "\n") a = question.interview.terms[question.language][term]['re'].sub(r'[[\1]]', a) #logmessage("string is now " + text_type(a) + "\n") if len(question.interview.autoterms): lang = docassemble.base.functions.get_language() if lang in question.interview.autoterms and len(question.interview.autoterms[lang]) > 0: for term in question.interview.autoterms[lang]: #logmessage("Searching for term " + term + " in " + a + "\n") a = question.interview.autoterms[lang][term]['re'].sub(r'[[\1]]', a) #logmessage("string is now " + text_type(a) + "\n") elif question.language in question.interview.autoterms and len(question.interview.autoterms[question.language]) > 0: for term in question.interview.autoterms[question.language]: #logmessage("Searching for term " + term + " in " + a + "\n") a = question.interview.autoterms[question.language][term]['re'].sub(r'[[\1]]', a) #logmessage("string is now " + text_type(a) + "\n") if status is not None and question.interview.scan_for_emojis: a = emoji_match.sub((lambda x: emoji_html(x.group(1), status=status, question=question)), a) a = html_filter(text_type(a), status=status, question=question, embedder=embedder, default_image_width=default_image_width) #logmessage("before: " + a) if use_pandoc: converter = MyPandoc() converter.output_format = 'html' converter.input_content = text_type(a) converter.convert(question) result = converter.output_content else: try: result = docassemble.base.functions.this_thread.markdown.reset().convert(a) except: # Try again because sometimes it fails randomly and maybe trying again will work. result = docassemble.base.functions.this_thread.markdown.reset().convert(a) result = re.sub(r'<table>', r'<table class="table table-striped">', result) result = re.sub(r'<blockquote>', r'<blockquote class="blockquote">', result) #result = re.sub(r'<table>', r'<table class="datable">', result) result = re.sub(r'<a href="(.*?)"', lambda x: link_rewriter(x, status), result) if do_terms and question is not None and term_start.search(result): lang = docassemble.base.functions.get_language() if status is not None: if len(question.terms): result = term_match.sub((lambda x: add_terms(x.group(1), status.extras['terms'], status=status, question=question)), result) if len(question.autoterms): result = term_match.sub((lambda x: add_terms(x.group(1), status.extras['autoterms'], status=status, question=question)), result) if lang in question.interview.terms and len(question.interview.terms[lang]): result = term_match.sub((lambda x: add_terms(x.group(1), question.interview.terms[lang], status=status, question=question)), result) elif question.language in question.interview.terms and len(question.interview.terms[question.language]): result = term_match.sub((lambda x: add_terms(x.group(1), question.interview.terms[question.language], status=status, question=question)), result) if lang in question.interview.autoterms and len(question.interview.autoterms[lang]): result = term_match.sub((lambda x: add_terms(x.group(1), question.interview.autoterms[lang], status=status, question=question)), result) elif question.language in question.interview.autoterms and len(question.interview.autoterms[question.language]): result = term_match.sub((lambda x: add_terms(x.group(1), question.interview.autoterms[question.language], status=status, question=question)), result) if trim: if result.startswith('<p>') and result.endswith('</p>'): result = result[3:-4] elif pclass: result = re.sub('<p>', '<p class="' + pclass + '">', result) if escape: result = noquote_match.sub('&quot;', result) result = lt_match.sub('&lt;', result) result = gt_match.sub('&gt;', result) result = amp_match.sub('&amp;', result) #logmessage("after: " + result) #result = result.replace('\n', ' ') if result: if strip_newlines: result = result.replace('\n', ' ') if divclass is not None: result = '<div class="' + text_type(divclass) + '">' + result + '</div>' if indent and not code_match.search(result): return (" " * indent) + re.sub(r'\n', "\n" + (" " * indent), result).rstrip() + "\n" return(result) def my_escape(result): result = noquote_match.sub('&quot;', result) result = lt_match.sub('&lt;', result) result = gt_match.sub('&gt;', result) result = amp_match.sub('&amp;', result) return(result) def noquote(string): #return json.dumps(string.replace('\n', ' ').rstrip()) return '"' + string.replace('\n', ' ').replace('"', '&quot;').rstrip() + '"' def add_terms_mako(termname, terms, status=None, question=None): lower_termname = termname.lower() if lower_termname in terms: return('<a tabindex="0" class="daterm" data-toggle="popover" data-placement="bottom" data-content=' + noquote(markdown_to_html(terms[lower_termname]['definition'].text(dict()), trim=True, default_image_width='100%', do_terms=False, status=status, question=question)) + '>' + text_type(termname) + '</a>') #logmessage(lower_termname + " is not in terms dictionary\n") return '[[' + termname + ']]' def add_terms(termname, terms, status=None, question=None): lower_termname = termname.lower() if lower_termname in terms: return('<a tabindex="0" class="daterm" data-toggle="popover" data-placement="bottom" data-content=' + noquote(markdown_to_html(terms[lower_termname]['definition'], trim=True, default_image_width='100%', do_terms=False, status=status, question=question)) + '>' + text_type(termname) + '</a>') #logmessage(lower_termname + " is not in terms dictionary\n") return '[[' + termname + ']]' def audio_control(files, preload="metadata", title_text=None): for d in files: if isinstance(d, string_types): return d if title_text is None: title_text = '' else: title_text = " title=" + json.dumps(title_text) output = '<audio' + title_text + ' class="daaudio-control" controls="controls" preload="' + preload + '">' + "\n" for d in files: if type(d) is list: output += ' <source src="' + d[0] + '"' if d[1] is not None: output += ' type="' + d[1] + '"/>' output += "\n" output += ' <a target="_blank" href="' + files[-1][0] + '">' + word('Listen') + '</a>\n' output += "</audio>\n" return output def video_control(files): for d in files: if isinstance(d, (string_types, NoneType)): return text_type(d) output = '<video class="dawidevideo" controls="controls">' + "\n" for d in files: if type(d) is list: if d[0] is None: continue output += ' <source src="' + d[0] + '"' if d[1] is not None: output += ' type="' + d[1] + '"/>' output += "\n" output += ' <a target="_blank" href="' + files[-1][0] + '">' + word('Listen') + '</a>\n' output += "</video>\n" return output def get_audio_urls(the_audio, question=None): output = list() the_list = list() to_try = dict() for audio_item in the_audio: if audio_item['type'] != 'audio': continue found_upload = False pattern = re.compile(r'^\[FILE ([^,\]]+)') for (file_ref) in re.findall(pattern, audio_item['text']): found_upload = True m = re.match(r'[0-9]+', file_ref) if m: file_info = server.file_finder(file_ref, question=question) if 'path' in file_info: if file_info['mimetype'] == 'audio/ogg': output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) elif os.path.isfile(file_info['path'] + '.ogg'): output.append([server.url_finder(file_ref, ext='ogg', _question=question), 'audio/ogg']) if file_info['mimetype'] == 'audio/mpeg': output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) elif os.path.isfile(file_info['path'] + '.mp3'): output.append([server.url_finder(file_ref, ext='mp3', _question=question), 'audio/mpeg']) if file_info['mimetype'] not in ['audio/mpeg', 'audio/ogg']: output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) else: the_list.append({'text': file_ref, 'package': audio_item['package']}) if not found_upload: the_list.append(audio_item) for audio_item in the_list: mimetype, encoding = mimetypes.guess_type(audio_item['text']) if re.search(r'^http', audio_item['text']): output.append([audio_item['text'], mimetype]) continue basename = os.path.splitext(audio_item['text'])[0] ext = os.path.splitext(audio_item['text'])[1] if not mimetype in to_try: to_try[mimetype] = list(); to_try[mimetype].append({'basename': basename, 'filename': audio_item['text'], 'ext': ext, 'package': audio_item['package']}) if 'audio/mpeg' in to_try and 'audio/ogg' not in to_try: to_try['audio/ogg'] = list() for attempt in to_try['audio/mpeg']: if attempt['ext'] == '.MP3': to_try['audio/ogg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.OGG', 'ext': '.OGG', 'package': attempt['package']}) else: to_try['audio/ogg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.ogg', 'ext': '.ogg', 'package': attempt['package']}) if 'audio/ogg' in to_try and 'audio/mpeg' not in to_try: to_try['audio/mpeg'] = list() for attempt in to_try['audio/ogg']: if attempt['ext'] == '.OGG': to_try['audio/mpeg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.MP3', 'ext': '.MP3', 'package': attempt['package']}) else: to_try['audio/mpeg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.mp3', 'ext': '.mp3', 'package': attempt['package']}) for mimetype in reversed(sorted(to_try.keys())): for attempt in to_try[mimetype]: parts = attempt['filename'].split(':') if len(parts) < 2: parts = [attempt['package'], attempt['filename']] if parts[0] is None: parts[0] = 'None' parts[1] = re.sub(r'^data/static/', '', parts[1]) full_file = parts[0] + ':data/static/' + parts[1] file_info = server.file_finder(full_file, question=question) if 'fullpath' in file_info: url = server.url_finder(full_file, _question=question) output.append([url, mimetype]) return output def get_video_urls(the_video, question=None): output = list() the_list = list() to_try = dict() for video_item in the_video: if video_item['type'] != 'video': continue found_upload = False if re.search(r'^\[(YOUTUBE|VIMEO)[0-9\:]* ', video_item['text']): output.append(html_filter(video_item['text'])) continue pattern = re.compile(r'^\[FILE ([^,\]]+)') for (file_ref) in re.findall(pattern, video_item['text']): found_upload = True m = re.match(r'[0-9]+', file_ref) if m: file_info = server.file_finder(file_ref, question=question) if 'path' in file_info: if file_info['mimetype'] == 'video/ogg': output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) elif os.path.isfile(file_info['path'] + '.ogv'): output.append([server.url_finder(file_ref, ext='ogv', _question=question), 'video/ogg']) if file_info['mimetype'] == 'video/mp4': output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) elif os.path.isfile(file_info['path'] + '.mp4'): output.append([server.url_finder(file_ref, ext='mp4', _question=question), 'video/mp4']) if file_info['mimetype'] not in ['video/mp4', 'video/ogg']: output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) else: the_list.append({'text': file_ref, 'package': video_item['package']}) if not found_upload: the_list.append(video_item) for video_item in the_list: mimetype, encoding = mimetypes.guess_type(video_item['text']) if re.search(r'^http', video_item['text']): output.append([video_item['text'], mimetype]) continue basename = os.path.splitext(video_item['text'])[0] ext = os.path.splitext(video_item['text'])[1] if not mimetype in to_try: to_try[mimetype] = list(); to_try[mimetype].append({'basename': basename, 'filename': video_item['text'], 'ext': ext, 'package': video_item['package']}) if 'video/mp4' in to_try and 'video/ogg' not in to_try: to_try['video/ogg'] = list() for attempt in to_try['video/mp4']: if attempt['ext'] == '.MP4': to_try['video/ogg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.OGV', 'ext': '.OGV', 'package': attempt['package']}) else: to_try['video/ogg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.ogv', 'ext': '.ogv', 'package': attempt['package']}) if 'video/ogg' in to_try and 'video/mp4' not in to_try: to_try['video/mp4'] = list() for attempt in to_try['video/ogg']: if attempt['ext'] == '.OGV': to_try['video/mp4'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.MP4', 'ext': '.MP4', 'package': attempt['package']}) else: to_try['audio/mpeg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.mp4', 'ext': '.mp4', 'package': attempt['package']}) for mimetype in reversed(sorted(to_try.keys())): for attempt in to_try[mimetype]: parts = attempt['filename'].split(':') if len(parts) < 2: parts = [attempt['package'], attempt['filename']] if parts[0] is None: parts[0] = 'None' parts[1] = re.sub(r'^data/static/', '', parts[1]) full_file = parts[0] + ':data/static/' + parts[1] file_info = server.file_finder(full_file, question=question) if 'fullpath' in file_info: url = server.url_finder(full_file, _question=question) if url is not None: output.append([url, mimetype]) return output def to_text(html_doc, terms, links, status): output = "" #logmessage("to_text: html doc is " + text_type(html_doc)) soup = BeautifulSoup(html_doc, 'html.parser') [s.extract() for s in soup(['style', 'script', '[document]', 'head', 'title', 'audio', 'video', 'pre', 'attribution'])] [s.extract() for s in soup.find_all(hidden)] [s.extract() for s in soup.find_all('div', {'class': 'dainvisible'})] for s in soup.find_all(do_show): if s.name in ['input', 'textarea', 'img'] and s.has_attr('alt'): words = s.attrs['alt'] if s.has_attr('placeholder'): words += ", " + s.attrs['placeholder'] else: words = s.get_text() words = re.sub(r'\n\s*', ' ', words, flags=re.DOTALL) output += words + "\n" for s in soup.find_all('a'): if s.has_attr('class') and s.attrs['class'][0] == 'daterm' and s.has_attr('data-content'): terms[s.string] = s.attrs['data-content'] elif s.has_attr('href'):# and (s.attrs['href'].startswith(url) or s.attrs['href'].startswith('?')): #logmessage("Adding a link: " + s.attrs['href']) links.append((s.attrs['href'], s.get_text())) output = re.sub(br'\u201c'.decode('raw_unicode_escape'), '"', output) output = re.sub(br'\u201d'.decode('raw_unicode_escape'), '"', output) output = re.sub(br'\u2018'.decode('raw_unicode_escape'), "'", output) output = re.sub(br'\u2019'.decode('raw_unicode_escape'), "'", output) output = re.sub(br'\u201b'.decode('raw_unicode_escape'), "'", output) output = re.sub(r'&amp;gt;', '>', output) output = re.sub(r'&amp;lt;', '<', output) output = re.sub(r'&gt;', '>', output) output = re.sub(r'&lt;', '<', output) output = re.sub(r'<[^>]+>', '', output) output = re.sub(r'\n$', '', output) output = re.sub(r' +', ' ', output) return output bad_list = ['div', 'option'] good_list = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'button', 'textarea', 'note'] def do_show(element): if re.match('<!--.*-->', text_type(element), re.DOTALL): return False if element.name in ['option'] and element.has_attr('selected'): return True if element.name in bad_list: return False if element.name in ['img', 'input'] and element.has_attr('alt'): return True if element.name in good_list: return True if element.parent and element.parent.name in good_list: return False if element.string: return True if re.match(r'\s+', element.get_text()): return False return False def hidden(element): if element.name == 'input': if element.has_attr('type'): if element.attrs['type'] == 'hidden': return True return False def replace_fields(string, status=None, embedder=None): if not re.search(r'\[FIELD ', string): return string matches = list() in_match = False start_match = None depth = 0 i = 0 while i < len(string): if string[i:i+7] == '[FIELD ': in_match = True start_match = i i += 7 continue if in_match: if string[i] == '[': depth += 1 elif string[i] == ']': if depth == 0: i += 1 matches.append((start_match, i)) in_match = False continue else: depth -= 1 i += 1 field_strings = list() for (start, end) in matches: field_strings.append(string[start:end]) #logmessage(repr(field_strings)) for field_string in field_strings: if embedder is None: string = string.replace(field_string, 'ERROR: FIELD cannot be used here') else: string = string.replace(field_string, embedder(status, field_string)) return string def image_include_docx_template(match, question=None): file_reference = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '100%' except: width = DEFAULT_IMAGE_WIDTH file_info = server.file_finder(file_reference, convert={'svg': 'eps'}, question=question) if 'mimetype' in file_info: if re.search(r'^(audio|video)', file_info['mimetype']): return '[reference to file type that cannot be displayed]' if 'path' in file_info: if 'mimetype' in file_info: if file_info['mimetype'] in ('text/markdown', 'text/plain'): with open(file_info['fullpath'], 'rU', encoding='utf-8') as f: contents = f.read() if file_info['mimetype'] == 'text/plain': return contents else: return docassemble.base.file_docx.markdown_to_docx(contents, docassemble.base.functions.this_thread.misc.get('docx_template', None)) if file_info['mimetype'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': return text_type(docassemble.base.file_docx.include_docx_template(docassemble.base.functions.DALocalFile(file_info['fullpath']))) else: return text_type(docassemble.base.file_docx.image_for_docx(file_reference, question, docassemble.base.functions.this_thread.misc.get('docx_template', None), width=width)) return '[reference to file that could not be found]' def qr_include_docx_template(match): string = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '100%' except: width = DEFAULT_IMAGE_WIDTH im = qrcode.make(string) the_image = tempfile.NamedTemporaryFile(prefix="datemp", suffix=".png", delete=False) im.save(the_image.name) return text_type(docassemble.base.file_docx.image_for_docx(docassemble.base.functions.DALocalFile(the_image.name), None, docassemble.base.functions.this_thread.misc.get('docx_template', None), width=width)) def ensure_valid_filename(filename): m = re.search(r'[\\/\&\`:;,~\'\"\*\?\<\>\|]', filename) if m: raise Exception("Filename contained invalid character " + repr(m.group(1))) for char in filename: if ord(char) < 32 or ord(char) >= 127: raise Exception("Filename contained invalid character " + repr(char)) return True
<filename>docassemble_base/docassemble/base/filter.py # -*- coding: utf-8 -*- import sys from six import string_types, text_type, PY2 import re import os import markdown import mimetypes import codecs import json import qrcode import qrcode.image.svg from io import BytesIO import tempfile import types import time import stat import PyPDF2 from docassemble.base.functions import server, word import docassemble.base.functions from docassemble.base.pandoc import MyPandoc from bs4 import BeautifulSoup import docassemble.base.file_docx from pylatex.utils import escape_latex from io import open from pathlib import Path NoneType = type(None) from docassemble.base.logger import logmessage from docassemble.base.rtfng.object.picture import Image import PIL DEFAULT_PAGE_WIDTH = '6.5in' term_start = re.compile(r'\[\[') term_match = re.compile(r'\[\[([^\]]*)\]\]') noquote_match = re.compile(r'"') lt_match = re.compile(r'<') gt_match = re.compile(r'>') amp_match = re.compile(r'&') emoji_match = re.compile(r':([A-Za-z][A-Za-z0-9\_\-]+):') extension_match = re.compile(r'\.[a-z]+$') map_match = re.compile(r'\[MAP ([^\]]+)\]', flags=re.DOTALL) code_match = re.compile(r'<code>') def set_default_page_width(width): global DEFAULT_PAGE_WIDTH DEFAULT_PAGE_WIDTH = text_type(width) return def get_default_page_width(): return(DEFAULT_PAGE_WIDTH) DEFAULT_IMAGE_WIDTH = '4in' def set_default_image_width(width): global DEFAULT_IMAGE_WIDTH DEFAULT_IMAGE_WIDTH = text_type(width) return def get_default_image_width(): return(DEFAULT_IMAGE_WIDTH) MAX_HEIGHT_POINTS = 10 * 72 def set_max_height_points(points): global MAX_HEIGHT_POINTS MAX_HEIGHT_POINTS = points return def get_max_height_points(): return(MAX_HEIGHT_POINTS) MAX_WIDTH_POINTS = 6.5 * 72.0 def set_max_width_points(points): global MAX_WIDTH_POINTS MAX_WIDTH_POINTS = points return def get_max_width_points(): return(MAX_WIDTH_POINTS) # def blank_da_send_mail(*args, **kwargs): # logmessage("da_send_mail: no mail agent configured!") # return(None) # da_send_mail = blank_da_send_mail # def set_da_send_mail(func): # global da_send_mail # da_send_mail = func # return # def blank_file_finder(*args, **kwargs): # return(dict(filename="invalid")) # file_finder = blank_file_finder # def set_file_finder(func): # global file_finder # #sys.stderr.write("set the file finder to " + text_type(func) + "\n") # file_finder = func # return # def blank_url_finder(*args, **kwargs): # return('about:blank') # url_finder = blank_url_finder # def set_url_finder(func): # global url_finder # url_finder = func # return # def blank_url_for(*args, **kwargs): # return('about:blank') # url_for = blank_url_for # def set_url_for(func): # global url_for # url_for = func # return rtf_spacing = {'tight': r'\\sl0 ', 'single': r'\\sl0 ', 'oneandahalf': r'\\sl360\\slmult1 ', 'double': r'\\sl480\\slmult1 ', 'triple': r'\\sl720\\slmult1 '} rtf_after_space = {'tight': 0, 'single': 1, 'oneandahalf': 0, 'double': 0, 'triplespacing': 0, 'triple': 0} def rtf_prefilter(text, metadata=dict()): text = re.sub(r'^# ', '[HEADING1] ', text, flags=re.MULTILINE) text = re.sub(r'^## ', '[HEADING2] ', text, flags=re.MULTILINE) text = re.sub(r'^### ', '[HEADING3] ', text, flags=re.MULTILINE) text = re.sub(r'^#### ', '[HEADING4] ', text, flags=re.MULTILINE) text = re.sub(r'^##### ', '[HEADING5] ', text, flags=re.MULTILINE) text = re.sub(r'^###### ', '[HEADING6] ', text, flags=re.MULTILINE) text = re.sub(r'^####### ', '[HEADING7] ', text, flags=re.MULTILINE) text = re.sub(r'^######## ', '[HEADING8] ', text, flags=re.MULTILINE) text = re.sub(r'^######### ', '[HEADING9] ', text, flags=re.MULTILINE) text = re.sub(r'\s*\[VERTICAL_LINE\]\s*', '\n\n[VERTICAL_LINE]\n\n', text) text = re.sub(r'\s*\[BREAK\]\s*', '\n\n[BREAK]\n\n', text) text = re.sub(r'\s+\[END_TWOCOL\]', '\n\n[END_TWOCOL]', text) text = re.sub(r'\s+\[END_CAPTION\]', '\n\n[END_CAPTION]', text) text = re.sub(r'\[BEGIN_TWOCOL\]\s+', '[BEGIN_TWOCOL]\n\n', text) text = re.sub(r'\[BEGIN_CAPTION\]\s+', '[BEGIN_CAPTION]\n\n', text) return(text) def repeat_along(chars, match): output = chars * len(match.group(1)) #logmessage("Output is " + repr(output)) return output def rtf_filter(text, metadata=None, styles=None, question=None): if metadata is None: metadata = dict() if styles is None: styles = dict() #sys.stderr.write(text + "\n") if 'fontsize' in metadata: text = re.sub(r'{\\pard', r'\\fs' + text_type(convert_length(metadata['fontsize'], 'hp')) + r' {\\pard', text, count=1) after_space_multiplier = text_type(convert_length(metadata['fontsize'], 'twips')) else: after_space_multiplier = 240 if 'IndentationAmount' in metadata: indentation_amount = text_type(convert_length(metadata['IndentationAmount'], 'twips')) else: indentation_amount = '720' if 'Indentation' in metadata: if metadata['Indentation']: default_indentation = True else: default_indentation = False else: default_indentation = True if 'SingleSpacing' in metadata and metadata['SingleSpacing']: #logmessage("Gi there!") default_spacing = 'single' if 'Indentation' not in metadata: default_indentation = False elif 'OneAndAHalfSpacing' in metadata and metadata['OneAndAHalfSpacing']: default_spacing = 'oneandahalf' elif 'DoubleSpacing' in metadata and metadata['DoubleSpacing']: default_spacing = 'double' elif 'TripleSpacing' in metadata and metadata['TripleSpacing']: default_spacing = 'triple' else: default_spacing = 'double' after_space = after_space_multiplier * rtf_after_space[default_spacing] text = re.sub(r'{\\pard \\ql \\f0 \\sa180 \\li0 \\fi0 \[HEADING([0-9]+)\] *', (lambda x: '{\\pard ' + styles.get(x.group(1), '\\ql \\f0 \\sa180 \\li0 \\fi0 ')), text) text = re.sub(r'{\\pard \\ql \\f0 \\sa180 \\li0 \\fi0 \[(BEGIN_TWOCOL|BREAK|END_TWOCOL|BEGIN_CAPTION|VERTICAL_LINE|END_CAPTION|TIGHTSPACING|SINGLESPACING|DOUBLESPACING|START_INDENTATION|STOP_INDENTATION|PAGEBREAK|SKIPLINE|NOINDENT|FLUSHLEFT|FLUSHRIGHT|CENTER|BOLDCENTER|INDENTBY[^\]]*)\] *', r'[\1]{\\pard \\ql \\f0 \\sa180 \\li0 \\fi0 ', text) text = re.sub(r'{\\pard \\ql \\f0 \\sa180 \\li0 \\fi0 *\\par}', r'', text) text = re.sub(r'\[\[([^\]]*)\]\]', r'\1', text) # with open('/tmp/asdf.rtf', 'w') as deb_file: # deb_file.write(text) text = re.sub(r'\\par}\s*\[(END_TWOCOL|END_CAPTION|BREAK|VERTICAL_LINE)\]', r'}[\1]', text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\s*\[BREAK\]\s*(.+?)\[END_TWOCOL\]', rtf_two_col, text, flags=re.DOTALL) text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_as_rtf(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_as_rtf(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_as_rtf(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_as_rtf(x, question=question), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_as_rtf, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_as_rtf, text) text = re.sub(r'\[QR ([^\]]+)\]', qr_as_rtf, text) text = re.sub(r'\[MAP ([^\]]+)\]', '', text) text = replace_fields(text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) text = re.sub(r'\[TARGET ([^\]]+)\]', '', text) text = re.sub(r'\[YOUTUBE[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[VIMEO[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\s*\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', rtf_caption_table, text, flags=re.DOTALL) text = re.sub(r'\[NBSP\]', r'\\~ ', text) text = re.sub(r'\[REDACTION_SPACE\]', r'\\u9608\\zwbo', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along('\\u9608', x), text) text = re.sub(r'\[ENDASH\]', r'{\\endash}', text) text = re.sub(r'\[EMDASH\]', r'{\\emdash}', text) text = re.sub(r'\[HYPHEN\]', r'-', text) text = re.sub(r'\[CHECKBOX\]', r'____', text) text = re.sub(r'\[BLANK\]', r'________________', text) text = re.sub(r'\[BLANKFILL\]', r'________________', text) text = re.sub(r'\[PAGEBREAK\] *', r'\\page ', text) text = re.sub(r'\[PAGENUM\]', r'{\\chpgn}', text) text = re.sub(r'\[TOTALPAGES\]', r'{\\field{\\*\\fldinst NUMPAGES } {\\fldrslt 1}}', text) text = re.sub(r'\[SECTIONNUM\]', r'{\\sectnum}', text) text = re.sub(r' *\[SKIPLINE\] *', r'\\line ', text) text = re.sub(r' *\[NEWLINE\] *', r'\\line ', text) text = re.sub(r' *\[NEWPAR\] *', r'\\par ', text) text = re.sub(r' *\[BR\] *', r'\\line ', text) text = re.sub(r' *\[TAB\] *', r'\\tab ', text) text = re.sub(r' *\[END\] *', r'\n', text) text = re.sub(r'\\sa180\\sa180\\par', r'\\par', text) text = re.sub(r'\\sa180', r'\\sa0', text) text = re.sub(r'(\\trowd \\trgaph[0-9]+)', r'\1\\trqc', text) text = re.sub(r'\\intbl\\row}\s*{\\pard', r'\\intbl\\row}\n\\line\n{\\pard', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\s*\[(SAVE|RESTORE|TIGHTSPACING|SINGLESPACING|DOUBLESPACING|TRIPLESPACING|ONEANDAHALFSPACING|START_INDENTATION|STOP_INDENTATION)\]\s*', r'\n[\1]\n', text) lines = text.split('\n') spacing_command = rtf_spacing[default_spacing] if default_indentation: indentation_command = r'\\fi' + text_type(indentation_amount) + " " else: indentation_command = r'\\fi0 ' text = '' formatting_stack = list() for line in lines: if re.search(r'\[SAVE\]', line): formatting_stack.append(dict(spacing_command=spacing_command, after_space=after_space, default_indentation=default_indentation, indentation_command=indentation_command)) elif re.search(r'\[RESTORE\]', line): if len(formatting_stack): prior_values = formatting_stack.pop() spacing_command = prior_values['spacing_command'] after_space = prior_values['after_space'] default_indentation = prior_values['default_indentation'] indentation_command = prior_values['indentation_command'] elif re.search(r'\[TIGHTSPACING\]', line): spacing_command = rtf_spacing['tight'] default_spacing = 'tight' after_space = after_space_multiplier * rtf_after_space[default_spacing] default_indentation = False elif re.search(r'\[SINGLESPACING\]', line): spacing_command = rtf_spacing['single'] default_spacing = 'single' after_space = after_space_multiplier * rtf_after_space[default_spacing] default_indentation = False elif re.search(r'\[ONEANDAHALFSPACING\]', line): spacing_command = rtf_spacing['oneandahalf'] default_spacing = 'oneandahalf' after_space = after_space_multiplier * rtf_after_space[default_spacing] elif re.search(r'\[DOUBLESPACING\]', line): spacing_command = rtf_spacing['double'] default_spacing = 'double' after_space = after_space_multiplier * rtf_after_space[default_spacing] elif re.search(r'\[TRIPLESPACING\]', line): spacing_command = rtf_spacing['triple'] default_spacing = 'triple' after_space = after_space_multiplier * rtf_after_space[default_spacing] elif re.search(r'\[START_INDENTATION\]', line): indentation_command = r'\\fi' + text_type(indentation_amount) + " " elif re.search(r'\[STOP_INDENTATION\]', line): indentation_command = r'\\fi0 ' elif line != '': special_after_space = None special_spacing = None if re.search(r'\[BORDER\]', line): line = re.sub(r' *\[BORDER\] *', r'', line) border_text = r'\\box \\brdrhair \\brdrw1 \\brdrcf1 \\brsp29 ' else: border_text = r'' line = re.sub(r'{(\\pard\\intbl \\q[lrc] \\f[0-9]+ \\sa[0-9]+ \\li[0-9]+ \\fi[0-9]+.*?)\\par}', r'\1', line) if re.search(r'\[NOPAR\]', line): line = re.sub(r'{\\pard \\ql \\f[0-9]+ \\sa[0-9]+ \\li[0-9]+ \\fi-?[0-9]* *(.*?)\\par}', r'\1', line) line = re.sub(r' *\[NOPAR\] *', r'', line) n = re.search(r'\[INDENTBY *([0-9\.]+ *[A-Za-z]+) *([0-9\.]+ *[A-Za-z]+)\]', line) m = re.search(r'\[INDENTBY *([0-9\.]+ *[A-Za-z]+)\]', line) if n: line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\ri-?[0-9]+ ', r'', line) line = re.sub(r'\\li-?[0-9]+ ', r'\\li' + text_type(convert_length(n.group(1), 'twips')) + r' \\ri' + text_type(convert_length(n.group(2), 'twips')) + ' ', line) line = re.sub(r'\[INDENTBY[^\]]*\]', '', line) elif m: line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\li-?[0-9]+ ', r'\\li' + text_type(convert_length(m.group(1), 'twips')) + ' ', line) line = re.sub(r' *\[INDENTBY[^\]]*\] *', '', line) elif re.search(r'\[NOINDENT\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r' *\[NOINDENT\] *', '', line) elif re.search(r'\[FLUSHLEFT\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r' *\[FLUSHLEFT\] *', '', line) special_after_space = after_space_multiplier * 1 special_spacing = rtf_spacing['single'] elif re.search(r'\[FLUSHRIGHT\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\ql', r'\\qr', line) line = re.sub(r' *\[FLUSHRIGHT\] *', '', line) special_after_space = after_space_multiplier * 1 special_spacing = rtf_spacing['single'] elif re.search(r'\[CENTER\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\ql', r'\\qc', line) line = re.sub(r' *\[CENTER\] *', '', line) elif re.search(r'\[BOLDCENTER\]', line): line = re.sub(r'\\fi-?[0-9]+ ', r'\\fi0 ', line) line = re.sub(r'\\ql', r'\\qc \\b', line) line = re.sub(r' *\[BOLDCENTER\] *', '', line) elif indentation_command != '' and not re.search(r'\\widctlpar', line): line = re.sub(r'\\fi-?[0-9]+ ', indentation_command, line) if not re.search(r'\\s[0-9]', line): if special_spacing: spacing_command_to_use = special_spacing else: spacing_command_to_use = spacing_command line = re.sub(r'\\pard ', r'\\pard ' + text_type(spacing_command_to_use) + text_type(border_text), line) line = re.sub(r'\\pard\\intbl ', r'\\pard\\intbl ' + text_type(spacing_command_to_use) + text_type(border_text), line) if not (re.search(r'\\fi0\\(endash|bullet)', line) or re.search(r'\\s[0-9]', line) or re.search(r'\\intbl', line)): if special_after_space: after_space_to_use = special_after_space else: after_space_to_use = after_space if after_space_to_use > 0: line = re.sub(r'\\sa[0-9]+ ', r'\\sa' + text_type(after_space_to_use) + ' ', line) else: line = re.sub(r'\\sa[0-9]+ ', r'\\sa0 ', line) text += line + '\n' text = re.sub(r'{\\pard \\sl[0-9]+\\slmult[0-9]+ \\ql \\f[0-9]+ \\sa[0-9]+ \\li[0-9]+ \\fi-?[0-9]*\s*\\par}', r'', text) text = re.sub(r'\[MANUALSKIP\]', r'{\\pard \\sl0 \\ql \\f0 \\sa0 \\li0 \\fi0 \\par}', text) return(text) def docx_filter(text, metadata=None, question=None): if metadata is None: metadata = dict() text = text + "\n\n" text = re.sub(r'\[\[([^\]]*)\]\]', r'\1', text) text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_include_docx, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_include_docx, text) text = re.sub(r'\[QR ([^\]]+)\]', qr_include_docx, text) text = re.sub(r'\[MAP ([^\]]+)\]', '', text) text = replace_fields(text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) text = re.sub(r'\[TARGET ([^\]]+)\]', '', text) text = re.sub(r'\[YOUTUBE[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[VIMEO[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\\clearpage *\\clearpage', '', text) text = re.sub(r'\[START_INDENTATION\]', '', text) text = re.sub(r'\[STOP_INDENTATION\]', '', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', '', text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\[BREAK\]\s*(.+?)\[END_TWOCOL\]', '', text, flags=re.DOTALL) text = re.sub(r'\[TIGHTSPACING\] *', '', text) text = re.sub(r'\[SINGLESPACING\] *', '', text) text = re.sub(r'\[DOUBLESPACING\] *', '', text) text = re.sub(r'\[ONEANDAHALFSPACING\] *', '', text) text = re.sub(r'\[TRIPLESPACING\] *', '', text) text = re.sub(r'\[NBSP\]', ' ', text) text = re.sub(r'\[REDACTION_SPACE\]', u'█​', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along(u'█', x), text) text = re.sub(r'\[ENDASH\]', '--', text) text = re.sub(r'\[EMDASH\]', '---', text) text = re.sub(r'\[HYPHEN\]', '-', text) text = re.sub(r'\[CHECKBOX\]', '____', text) text = re.sub(r'\[BLANK\]', r'__________________', text) text = re.sub(r'\[BLANKFILL\]', r'__________________', text) text = re.sub(r'\[PAGEBREAK\] *', '', text) text = re.sub(r'\[PAGENUM\] *', '', text) text = re.sub(r'\[TOTALPAGES\] *', '', text) text = re.sub(r'\[SECTIONNUM\] *', '', text) text = re.sub(r'\[SKIPLINE\] *', '\n\n', text) text = re.sub(r'\[VERTICALSPACE\] *', '\n\n', text) text = re.sub(r'\[NEWLINE\] *', '\n\n', text) text = re.sub(r'\[NEWPAR\] *', '\n\n', text) text = re.sub(r'\[BR\] *', '\n\n', text) text = re.sub(r'\[TAB\] *', '', text) text = re.sub(r' *\[END\] *', r'\n', text) text = re.sub(r'\[BORDER\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[NOINDENT\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHLEFT\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHRIGHT\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[CENTER\] *(.+?)\n *\n', r'\1\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BOLDCENTER\] *(.+?)\n *\n', r'**\1**\n\n', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', r'\2', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+) *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', r'\3', text, flags=re.MULTILINE | re.DOTALL) return(text) def docx_template_filter(text, question=None): #logmessage('docx_template_filter') if text == 'True': return True elif text == 'False': return False elif text == 'None': return None text = re.sub(r'\[\[([^\]]*)\]\]', r'\1', text) text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_include_docx(x, question=question), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_include_docx_template, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_include_docx_template, text) text = re.sub(r'\[QR ([^\]]+)\]', qr_include_docx_template, text) text = re.sub(r'\[MAP ([^\]]+)\]', '', text) text = replace_fields(text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) text = re.sub(r'\[TARGET ([^\]]+)\]', '', text) text = re.sub(r'\[YOUTUBE[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[VIMEO[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\\clearpage *\\clearpage', '', text) text = re.sub(r'\[START_INDENTATION\]', '', text) text = re.sub(r'\[STOP_INDENTATION\]', '', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', '', text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\[BREAK\]\s*(.+?)\[END_TWOCOL\]', '', text, flags=re.DOTALL) text = re.sub(r'\[TIGHTSPACING\] *', '', text) text = re.sub(r'\[SINGLESPACING\] *', '', text) text = re.sub(r'\[DOUBLESPACING\] *', '', text) text = re.sub(r'\[ONEANDAHALFSPACING\] *', '', text) text = re.sub(r'\[TRIPLESPACING\] *', '', text) text = re.sub(r'\[NBSP\]', ' ', text) text = re.sub(r'\[REDACTION_SPACE\]', r'█​', text) #text = re.sub(r'\[REDACTION_SPACE\]', r'', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along('█', x), text) #text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along('X', x), text) text = re.sub(r'\[ENDASH\]', '--', text) text = re.sub(r'\[EMDASH\]', '---', text) text = re.sub(r'\[HYPHEN\]', '-', text) text = re.sub(r'\\', '', text) text = re.sub(r'\[CHECKBOX\]', '____', text) text = re.sub(r'\[BLANK\]', r'__________________', text) text = re.sub(r'\[BLANKFILL\]', r'__________________', text) text = re.sub(r'\[PAGEBREAK\] *', '', text) text = re.sub(r'\[PAGENUM\] *', '', text) text = re.sub(r'\[TOTALPAGES\] *', '', text) text = re.sub(r'\[SECTIONNUM\] *', '', text) text = re.sub(r'\[SKIPLINE\] *', '</w:t><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[VERTICALSPACE\] *', '</w:t><w:br/><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[NEWLINE\] *', '</w:t><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\n *\n', '[NEWPAR]', text) text = re.sub(r'\n', ' ', text) text = re.sub(r'\[NEWPAR\] *', '</w:t><w:br/><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[TAB\] *', '\t', text) text = re.sub(r'\[NEWPAR\]', '</w:t><w:br/><w:br/><w:t xml:space="preserve">', text) text = re.sub(r' *\[END\] *', r'</w:t><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[BORDER\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[NOINDENT\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHLEFT\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHRIGHT\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[CENTER\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BOLDCENTER\] *', r'', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', r'\2', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+) *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', r'\3', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BR\]', '</w:t><w:br/><w:t xml:space="preserve">', text) text = re.sub(r'\[SKIPLINE\]', '</w:t><w:br/><w:t xml:space="preserve">', text) return(text) def metadata_filter(text, doc_format): if doc_format == 'pdf': text = re.sub(r'\*\*([^\*]+?)\*\*', r'\\begingroup\\bfseries \1\\endgroup {}', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\*([^\*]+?)\*', r'\\begingroup\\itshape \1\\endgroup {}', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\_\_([^\_]+?)\_\_', r'\\begingroup\\bfseries \1\\endgroup {}', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\_([^\_]+?)\_*', r'\\begingroup\\itshape \1\\endgroup {}', text, flags=re.MULTILINE | re.DOTALL) return text def redact_latex(match): return u'\\redactword{' + text_type(escape_latex(match.group(1))) + u'}' def pdf_filter(text, metadata=None, question=None): if metadata is None: metadata = dict() #if len(metadata): # text = yaml.dump(metadata) + "\n---\n" + text text = text + "\n\n" text = re.sub(r'\[\[([^\]]*)\]\]', r'\1', text) text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_string(x, emoji=True, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_include_string(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_include_string(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_include_string(x, question=question), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_include_string, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_include_string, text) text = re.sub(r'\[QR ([^\]]+)\]', qr_include_string, text) text = re.sub(r'\[MAP ([^\]]+)\]', '', text) text = replace_fields(text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) text = re.sub(r'\[TARGET ([^\]]+)\]', '', text) text = re.sub(r'\[YOUTUBE[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\[VIMEO[^ ]* ([^\]]+)\]', '', text) text = re.sub(r'\$\$+', '$', text) text = re.sub(r'\\clearpage *\\clearpage', r'\\clearpage', text) text = re.sub(r'\[BORDER\]\s*\[(BEGIN_TWOCOL|BEGIN_CAPTION|TIGHTSPACING|SINGLESPACING|DOUBLESPACING|START_INDENTATION|STOP_INDENTATION|NOINDENT|FLUSHLEFT|FLUSHRIGHT|CENTER|BOLDCENTER|INDENTBY[^\]]*)\]', r'[\1] [BORDER]', text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[START_INDENTATION\]', r'\\setlength{\\parindent}{\\myindentamount}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[STOP_INDENTATION\]', r'\\setlength{\\parindent}{0in}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', pdf_caption, text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\[BREAK\]\s*(.+?)\[END_TWOCOL\]', pdf_two_col, text, flags=re.DOTALL) text = re.sub(r'\[TIGHTSPACING\]\s*', r'\\singlespacing\\setlength{\\parskip}{0pt}\\setlength{\\parindent}{0pt}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[SINGLESPACING\]\s*', r'\\singlespacing\\setlength{\\parskip}{\\myfontsize}\\setlength{\\parindent}{0pt}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[DOUBLESPACING\]\s*', r'\\doublespacing\\setlength{\\parindent}{\\myindentamount}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[ONEANDAHALFSPACING\]\s*', r'\\onehalfspacing\\setlength{\\parindent}{\\myindentamount}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[TRIPLESPACING\]\s*', r'\\setlength{\\parindent}{\\myindentamount}\\setlength{\\RaggedRightParindent}{\\parindent}', text) text = re.sub(r'\[NBSP\]', r'\\myshow{\\nonbreakingspace}', text) text = re.sub(r'\[REDACTION_SPACE\]', r'\\redactword{~}\\hspace{0pt}', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', redact_latex, text) text = re.sub(r'\[ENDASH\]', r'\\myshow{\\myendash}', text) text = re.sub(r'\[EMDASH\]', r'\\myshow{\\myemdash}', text) text = re.sub(r'\[HYPHEN\]', r'\\myshow{\\myhyphen}', text) text = re.sub(r'\[CHECKBOX\]', r'{\\rule{0.3in}{0.4pt}}', text) text = re.sub(r'\[BLANK\]', r'\\leavevmode{\\xrfill[-2pt]{0.4pt}}', text) text = re.sub(r'\[BLANKFILL\]', r'\\leavevmode{\\xrfill[-2pt]{0.4pt}}', text) text = re.sub(r'\[PAGEBREAK\]\s*', r'\\clearpage ', text) text = re.sub(r'\[PAGENUM\]', r'\\myshow{\\thepage\\xspace}', text) text = re.sub(r'\[TOTALPAGES\]', r'\\myshow{\\pageref*{LastPage}\\xspace}', text) text = re.sub(r'\[SECTIONNUM\]', r'\\myshow{\\thesection\\xspace}', text) text = re.sub(r'\s*\[SKIPLINE\]\s*', r'\\par\\myskipline ', text) text = re.sub(r'\[VERTICALSPACE\] *', r'\\rule[-24pt]{0pt}{0pt}', text) text = re.sub(r'\[NEWLINE\] *', r'\\newline ', text) text = re.sub(r'\[NEWPAR\] *', r'\\par ', text) text = re.sub(r'\[BR\] *', r'\\manuallinebreak ', text) text = re.sub(r'\[TAB\] *', r'\\manualindent ', text) text = re.sub(r' *\[END\] *', r'\n', text) text = re.sub(r'\[NOINDENT\] *', r'\\noindent ', text) text = re.sub(r'\[FLUSHLEFT\] *(.+?)\n *\n', flushleft_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[FLUSHRIGHT\] *(.+?)\n *\n', flushright_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[CENTER\] *(.+?)\n *\n', center_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BOLDCENTER\] *(.+?)\n *\n', boldcenter_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', indentby_left_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[INDENTBY *([0-9]+ *[A-Za-z]+) *([0-9]+ *[A-Za-z]+)\] *(.+?)\n *\n', indentby_both_pdf, text, flags=re.MULTILINE | re.DOTALL) text = re.sub(r'\[BORDER\] *(.+?)\n *\n', border_pdf, text, flags=re.MULTILINE | re.DOTALL) return(text) def html_filter(text, status=None, question=None, embedder=None, default_image_width=None): if question is None and status is not None: question = status.question text = text + "\n\n" text = re.sub(r'^[|] (.*)$', r'\1<br>', text, flags=re.MULTILINE) text = replace_fields(text, status=status, embedder=embedder) # if embedder is not None: # text = re.sub(r'\[FIELD ([^\]]+)\]', lambda x: embedder(status, x.group(1)), text) # else: # text = re.sub(r'\[FIELD ([^\]]+)\]', 'ERROR: FIELD cannot be used here', text) text = re.sub(r'\[TARGET ([^\]]+)\]', target_html, text) if docassemble.base.functions.this_thread.evaluation_context != 'docx': text = re.sub(r'\[EMOJI ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_url_string(x, emoji=True, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', lambda x: image_url_string(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+), *([0-9A-Za-z.%]+)\]', lambda x: image_url_string(x, question=question), text) text = re.sub(r'\[FILE ([^,\]]+)\]', lambda x: image_url_string(x, question=question, default_image_width=default_image_width), text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+), *([^\]]*)\]', qr_url_string, text) text = re.sub(r'\[QR ([^,\]]+), *([0-9A-Za-z.%]+)\]', qr_url_string, text) text = re.sub(r'\[QR ([^,\]]+)\]', qr_url_string, text) if map_match.search(text): text = map_match.sub((lambda x: map_string(x.group(1), status)), text) # width="420" height="315" text = re.sub(r'\[YOUTUBE ([^\]]+)\]', r'<div class="davideo davideo169"><iframe src="https://www.youtube.com/embed/\1?rel=0" frameborder="0" allowfullscreen></iframe></div>', text) text = re.sub(r'\[YOUTUBE4:3 ([^\]]+)\]', r'<div class="davideo davideo43"><iframe src="https://www.youtube.com/embed/\1?rel=0" frameborder="0" allowfullscreen></iframe></div>', text) text = re.sub(r'\[YOUTUBE16:9 ([^\]]+)\]', r'<div class="davideo davideo169"><iframe src="https://www.youtube.com/embed/\1?rel=0" frameborder="0" allowfullscreen></iframe></div>', text) # width="500" height="281" text = re.sub(r'\[VIMEO ([^\]]+)\]', r'<div class="davideo davideo169"><iframe src="https://player.vimeo.com/video/\1?byline=0&portrait=0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>', text) text = re.sub(r'\[VIMEO4:3 ([^\]]+)\]', r'<div class="davideo davideo43"><iframe src="https://player.vimeo.com/video/\1?byline=0&portrait=0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>', text) text = re.sub(r'\[VIMEO16:9 ([^\]]+)\]', r'<div class="davideo davideo169"><iframe src="https://player.vimeo.com/video/\1?byline=0&portrait=0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>', text) text = re.sub(r'\[BEGIN_CAPTION\](.+?)\[VERTICAL_LINE\]\s*(.+?)\[END_CAPTION\]', html_caption, text, flags=re.DOTALL) text = re.sub(r'\[BEGIN_TWOCOL\](.+?)\[BREAK\]\s*(.+?)\[END_TWOCOL\]', html_two_col, text, flags=re.DOTALL) text = re.sub(r'\[TIGHTSPACING\] *', r'', text) text = re.sub(r'\[SINGLESPACING\] *', r'', text) text = re.sub(r'\[DOUBLESPACING\] *', r'', text) text = re.sub(r'\[ONEANDAHALFSPACING\] *', '', text) text = re.sub(r'\[TRIPLESPACING\] *', '', text) text = re.sub(r'\[START_INDENTATION\] *', r'', text) text = re.sub(r'\[STOP_INDENTATION\] *', r'', text) text = re.sub(r'\[NBSP\]', r'&nbsp;', text) text = re.sub(r'\[REDACTION_SPACE\]', '&#9608;&#8203;', text) text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along('&#9608;', x), text) text = re.sub(r'\[ENDASH\]', r'&ndash;', text) text = re.sub(r'\[EMDASH\]', r'&mdash;', text) text = re.sub(r'\[HYPHEN\]', r'-', text) text = re.sub(r'\[CHECKBOX\]', r'<span style="text-decoration: underline">&nbsp;&nbsp;&nbsp;&nbsp;</span>', text) text = re.sub(r'\[BLANK\]', r'<span style="text-decoration: underline">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>', text) text = re.sub(r'\[BLANKFILL\]', r'<span style="text-decoration: underline">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>', text) text = re.sub(r'\[PAGEBREAK\] *', r'', text) text = re.sub(r'\[PAGENUM\] *', r'', text) text = re.sub(r'\[SECTIONNUM\] *', r'', text) text = re.sub(r'\[SKIPLINE\] *', r'<br />', text) text = re.sub(r'\[NEWLINE\] *', r'<br />', text) text = re.sub(r'\[NEWPAR\] *', r'<br /><br />', text) text = re.sub(r'\[BR\] *', r'<br />', text) text = re.sub(r'\[TAB\] *', '<span class="datab"></span>', text) text = re.sub(r' *\[END\] *', r'\n', text) lines = re.split(r'\n *\n', text) text = '' for line in lines: classes = set() styles = dict() if re.search(r'\[BORDER\]', line): classes.add('daborder') if re.search(r'\[NOINDENT\]', line): classes.add('daflushleft') if re.search(r'\[FLUSHLEFT\]', line): classes.add('daflushleft') if re.search(r'\[FLUSHRIGHT\]', line): classes.add('daflushright') if re.search(r'\[CENTER\]', line): classes.add('dacenter') if re.search(r'\[BOLDCENTER\]', line): classes.add('dacenter') classes.add('dabold') m = re.search(r'\[INDENTBY *([0-9]+ *[A-Za-z]+)\]', line) if m: styles["padding-left"] = text_type(convert_length(m.group(1), 'px')) + 'px' m = re.search(r'\[INDENTBY *([0-9]+ *[A-Za-z]+) *([0-9]+ *[A-Za-z]+)\]', line) if m: styles["margin-left"] = text_type(convert_length(m.group(1), 'px')) + 'px' styles["margin-right"] = text_type(convert_length(m.group(2), 'px')) + 'px' line = re.sub(r'\[(BORDER|NOINDENT|FLUSHLEFT|FLUSHRIGHT|BOLDCENTER|CENTER)\] *', r'', line) line = re.sub(r'\[INDENTBY[^\]]*\]', r'', line) if len(classes) or len(styles): text += "<p" if len(classes): text += ' class="' + " ".join(classes) + '"' if len(styles): text += ' style="' + "".join(map(lambda x: text_type(x) + ":" + styles[x] + ';', styles.keys())) + '"' text += ">" + line + '</p>\n\n' else: text += line + '\n\n' text = re.sub(r'\\_', r'__', text) text = re.sub(r'\n+$', r'', text) return(text) def clean_markdown_to_latex(string): string = re.sub(r'\s*\[SKIPLINE\]\s*', r'\\par\\myskipline ', string) string = re.sub(r'^[\n ]+', '', string) string = re.sub(r'[\n ]+$', '', string) string = re.sub(r' *\n *$', '\n', string) string = re.sub(r'\n{2,}', '[NEWLINE]', string) string = re.sub(r'\[BR\]', '[NEWLINE]', string) string = re.sub(r'\[(NOINDENT|FLUSHLEFT|FLUSHRIGHT|CENTER|BOLDCENTER|TIGHTSPACING|SINGLESPACING|DOUBLESPACING|START_INDENTATION|STOP_INDENTATION|PAGEBREAK)\]\s*', '', string) string = re.sub(r'\*\*([^\*]+?)\*\*', r'\\textbf{\1}', string) string = re.sub(r'\*([^\*]+?)\*', r'\\emph{\1}', string) string = re.sub(r'(?<!\\)_([^_]+?)_', r'\\emph{\1}', string) string = re.sub(r'\[([^\]]+?)\]\(([^\)]+?)\)', r'\\href{\2}{\1}', string) return string; def map_string(encoded_text, status): if status is None: return '' map_number = len(status.maps) status.maps.append(codecs.decode(bytearray(encoded_text, 'utf-8'), 'base64').decode()) return '<div id="map' + text_type(map_number) + '" class="dagoogleMap"></div>' def target_html(match): target = match.group(1) target = re.sub(r'[^A-Za-z0-9\_]', r'', text_type(target)) return '<span id="datarget' + target + '"></span>' def pdf_two_col(match, add_line=False): firstcol = clean_markdown_to_latex(match.group(1)) secondcol = clean_markdown_to_latex(match.group(2)) if add_line: return '\\noindent\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\mynoindent\\begin{tabular}{@{}m{0.49\\textwidth}|@{\\hspace{1em}}m{0.49\\textwidth}@{}}{' + firstcol + '} & {' + secondcol + '} \\\\ \\end{tabular}\\endgroup\\myskipline' else: return '\\noindent\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\mynoindent\\begin{tabular}{@{}m{0.49\\textwidth}@{\\hspace{1em}}m{0.49\\textwidth}@{}}{' + firstcol + '} & {' + secondcol + '} \\\\ \\end{tabular}\\endgroup\\myskipline' def html_caption(match): firstcol = match.group(1) secondcol = match.group(2) firstcol = re.sub(r'^\s+', '', firstcol) firstcol = re.sub(r'\s+$', '', firstcol) secondcol = re.sub(r'^\s+', '', secondcol) secondcol = re.sub(r'\s+$', '', secondcol) firstcol = re.sub(r'\n{2,}', '<br>', firstcol) secondcol = re.sub(r'\n{2,}', '<br>', secondcol) return '<table style="width: 100%"><tr><td style="width: 50%; border-style: solid; border-right-width: 1px; padding-right: 1em; border-left-width: 0px; border-top-width: 0px; border-bottom-width: 0px">' + firstcol + '</td><td style="padding-left: 1em; width: 50%;">' + secondcol + '</td></tr></table>' def html_two_col(match): firstcol = markdown_to_html(match.group(1)) secondcol = markdown_to_html(match.group(2)) return '<table style="width: 100%"><tr><td style="width: 50%; vertical-align: top; border-style: none; padding-right: 1em;">' + firstcol + '</td><td style="padding-left: 1em; vertical-align: top; width: 50%;">' + secondcol + '</td></tr></table>' def pdf_caption(match): return pdf_two_col(match, add_line=False) def add_newlines(string): string = re.sub(r'\[(BR)\]', r'[NEWLINE]', string) string = re.sub(r' *\n', r'\n', string) string = re.sub(r'(?<!\[NEWLINE\])\n', r' [NEWLINE]\n', string) return string def border_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return('\\mdframed\\setlength{\\parindent}{0pt} ' + text_type(string) + '\n\n\\endmdframed' + "\n\n") def flushleft_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return borderify('\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\setlength{\\parindent}{0pt}\\noindent ' + text_type(string) + '\\par\\endgroup') + "\n\n" def flushright_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return borderify('\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\setlength{\\parindent}{0pt}\\RaggedLeft ' + text_type(string) + '\\par\\endgroup') + "\n\n" def center_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return borderify('\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\Centering\\noindent ' + text_type(string) + '\\par\\endgroup') + "\n\n" def boldcenter_pdf(match): string = match.group(1) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) return borderify('\\begingroup\\singlespacing\\setlength{\\parskip}{0pt}\\Centering\\bfseries\\noindent ' + text_type(string) + '\\par\\endgroup') + "\n\n" def indentby_left_pdf(match): string = match.group(2) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) if re.search(r'\[BORDER\]', string): string = re.sub(r' *\[BORDER\] *', r'', string) return '\\mdframed[leftmargin=' + text_type(convert_length(match.group(1), 'pt')) + 'pt]\n\\noindent ' + text_type(string) + '\n\n\\endmdframed' + "\n\n" return '\\begingroup\\setlength{\\leftskip}{' + text_type(convert_length(match.group(1), 'pt')) + 'pt}\\noindent ' + text_type(string) + '\\par\\endgroup' + "\n\n" def indentby_both_pdf(match): string = match.group(3) string = re.sub(r'\[NEWLINE\] *', r'\\newline ', string) if re.search(r'\[BORDER\]', string): string = re.sub(r' *\[BORDER\] *', r'', string) return '\\mdframed[leftmargin=' + text_type(convert_length(match.group(1), 'pt')) + 'pt,rightmargin=' + text_type(convert_length(match.group(2), 'pt')) + 'pt]\n\\noindent ' + text_type(string) + '\n\n\\endmdframed' + "\n\n" return '\\begingroup\\setlength{\\leftskip}{' + text_type(convert_length(match.group(1), 'pt')) + 'pt}\\setlength{\\rightskip}{' + text_type(convert_length(match.group(2), 'pt')) + 'pt}\\noindent ' + text_type(string) + '\\par\\endgroup' + "\n\n" def borderify(string): if not re.search(r'\[BORDER\]', string): return string string = re.sub(r'\[BORDER\] *', r'', string) return('\\mdframed ' + text_type(string) + '\\endmdframed') def image_as_rtf(match, question=None): width_supplied = False try: width = match.group(2) assert width != 'None' width_supplied = True except: width = DEFAULT_IMAGE_WIDTH if width == 'full': width_supplied = False file_reference = match.group(1) file_info = server.file_finder(file_reference, convert={'svg': 'png', 'gif': 'png'}, question=question) if 'path' not in file_info: return '' #logmessage('image_as_rtf: path is ' + file_info['path']) if 'mimetype' in file_info: if re.search(r'^(audio|video)', file_info['mimetype']): return '[reference to file type that cannot be displayed]' if 'width' in file_info: try: return rtf_image(file_info, width, False) except: return '[graphic could not be inserted]' elif file_info['extension'] in ('pdf', 'docx', 'rtf', 'doc', 'odt'): output = '' if not width_supplied: #logmessage("image_as_rtf: Adding page break\n") width = DEFAULT_PAGE_WIDTH #output += '\\page ' #logmessage("image_as_rtf: maxpage is " + text_type(int(file_info['pages'])) + "\n") if not os.path.isfile(file_info['path'] + '.pdf'): if file_info['extension'] in ('docx', 'rtf', 'doc', 'odt') and not os.path.isfile(file_info['path'] + '.pdf'): server.fg_make_pdf_for_word_path(file_info['path'], file_info['extension']) if 'pages' not in file_info: try: reader = PyPDF2.PdfFileReader(open(file_info['path'] + '.pdf', 'rb')) file_info['pages'] = reader.getNumPages() except: file_info['pages'] = 1 max_pages = 1 + int(file_info['pages']) formatter = '%0' + text_type(len(text_type(max_pages))) + 'd' for page in range(1, max_pages): #logmessage("image_as_rtf: doing page " + text_type(page) + "\n") page_file = dict() test_path = file_info['path'] + 'page-in-progress' #logmessage("Test path is " + test_path) if os.path.isfile(test_path): #logmessage("image_as_rtf: test path " + test_path + " exists") while (os.path.isfile(test_path) and time.time() - os.stat(test_path)[stat.ST_MTIME]) < 30: #logmessage("Waiting for test path to go away") if not os.path.isfile(test_path): break time.sleep(1) page_file['extension'] = 'png' page_file['path'] = file_info['path'] + 'page-' + formatter % page page_file['fullpath'] = page_file['path'] + '.png' if not os.path.isfile(page_file['fullpath']): server.fg_make_png_for_pdf_path(file_info['path'] + '.pdf', 'page') if os.path.isfile(page_file['fullpath']): im = PIL.Image.open(page_file['fullpath']) page_file['width'], page_file['height'] = im.size output += rtf_image(page_file, width, False) else: output += "[Error including page image]" # if not width_supplied: # #logmessage("Adding page break\n") # output += '\\page ' # else: output += ' ' #logmessage("Returning output\n") return(output) else: return('') def qr_as_rtf(match): width_supplied = False try: width = match.group(2) assert width != 'None' width_supplied = True except: width = DEFAULT_IMAGE_WIDTH if width == 'full': width_supplied = False string = match.group(1) output = '' if not width_supplied: #logmessage("Adding page break\n") width = DEFAULT_PAGE_WIDTH output += '\\page ' im = qrcode.make(string) the_image = tempfile.NamedTemporaryFile(suffix=".png") im.save(the_image.name) page_file = dict() page_file['extension'] = 'png' page_file['fullpath'] = the_image.name page_file['width'], page_file['height'] = im.size output += rtf_image(page_file, width, False) if not width_supplied: #logmessage("Adding page break\n") output += '\\page ' else: output += ' ' #logmessage("Returning output\n") return(output) def rtf_image(file_info, width, insert_page_breaks): pixels = pixels_in(width) if pixels > 0 and file_info['width'] > 0: scale = float(pixels)/float(file_info['width']) #logmessage("scale is " + text_type(scale) + "\n") if scale*float(file_info['height']) > float(MAX_HEIGHT_POINTS): scale = float(MAX_HEIGHT_POINTS)/float(file_info['height']) #logmessage("scale is " + text_type(scale) + "\n") if scale*float(file_info['width']) > float(MAX_WIDTH_POINTS): scale = float(MAX_WIDTH_POINTS)/float(file_info['width']) #logmessage("scale is " + text_type(scale) + "\n") #scale *= 100.0 #logmessage("scale is " + text_type(scale) + "\n") #scale = int(scale) #logmessage("scale is " + text_type(scale) + "\n") wtwips = int(scale*float(file_info['width'])*20.0) htwips = int(scale*float(file_info['height'])*20.0) image = Image( file_info['fullpath'] ) image.Data = re.sub(r'\\picwgoal([0-9]+)', r'\\picwgoal' + text_type(wtwips), image.Data) image.Data = re.sub(r'\\pichgoal([0-9]+)', r'\\pichgoal' + text_type(htwips), image.Data) else: image = Image( file_info['fullpath'] ) if insert_page_breaks: content = '\\page ' else: content = '' #logmessage(content + image.Data) return(content + image.Data) unit_multipliers = {'twips': 0.0500, 'hp': 0.5, 'in': 72, 'pt': 1, 'px': 1, 'em': 12, 'cm': 28.346472} def convert_length(length, unit): value = pixels_in(length) if unit in unit_multipliers: size = float(value)/float(unit_multipliers[unit]) return(int(size)) else: logmessage("Unit " + text_type(unit) + " is not a valid unit\n") return(300) def pixels_in(length): m = re.search(r"([0-9.]+) *([a-z]+)", text_type(length).lower()) if m: value = float(m.group(1)) unit = m.group(2) #logmessage("value is " + text_type(value) + " and unit is " + unit + "\n") if unit in unit_multipliers: size = float(unit_multipliers[unit]) * value #logmessage("size is " + text_type(size) + "\n") return(int(size)) logmessage("Could not read " + text_type(length) + "\n") return(300) def image_url_string(match, emoji=False, question=None, playground=False, default_image_width=None): file_reference = match.group(1) try: width = match.group(2) assert width != 'None' except: if default_image_width is not None: width = default_image_width else: width = "300px" if width == "full": width = "300px" if match.lastindex == 3: if match.group(3) != 'None': alt_text = 'alt=' + json.dumps(match.group(3)) + ' ' else: alt_text = '' else: alt_text = '' file_info = server.file_finder(file_reference, question=question) if 'mimetype' in file_info and file_info['mimetype'] is not None: if re.search(r'^audio', file_info['mimetype']): urls = get_audio_urls([{'text': "[FILE " + file_reference + "]", 'package': None, 'type': 'audio'}], question=question) if len(urls): return audio_control(urls) return '' if re.search(r'^video', file_info['mimetype']): urls = get_video_urls([{'text': "[FILE " + file_reference + "]", 'package': None, 'type': 'video'}], question=question) if len(urls): return video_control(urls) return '' if 'extension' in file_info and file_info['extension'] is not None: if re.match(r'.*%$', width): width_string = "width:" + width else: width_string = "max-width:" + width if emoji: width_string += ';vertical-align: middle' alt_text = 'alt="" ' the_url = server.url_finder(file_reference, _question=question, display_filename=file_info['filename']) if the_url is None: return ('[ERROR: File reference ' + text_type(file_reference) + ' cannot be displayed]') if width_string == 'width:100%': extra_class = ' dawideimage' else: extra_class = '' if file_info.get('extension', '') in ['png', 'jpg', 'gif', 'svg', 'jpe', 'jpeg']: return('<img ' + alt_text + 'class="daicon daimageref' + extra_class + '" style="' + width_string + '" src="' + the_url + '"/>') elif file_info['extension'] in ('pdf', 'docx', 'rtf', 'doc', 'odt'): if file_info['extension'] in ('docx', 'rtf', 'doc', 'odt') and not os.path.isfile(file_info['path'] + '.pdf'): server.fg_make_pdf_for_word_path(file_info['path'], file_info['extension']) server.fg_make_png_for_pdf_path(file_info['path'] + ".pdf", 'screen', page=1) if 'pages' not in file_info: try: reader = PyPDF2.PdfFileReader(open(file_info['path'] + '.pdf', 'rb')) file_info['pages'] = reader.getNumPages() except: file_info['pages'] = 1 image_url = server.url_finder(file_reference, size="screen", page=1, _question=question) if image_url is None: return ('[ERROR: File reference ' + text_type(file_reference) + ' cannot be displayed]') if 'filename' in file_info: title = ' title="' + file_info['filename'] + '"' else: title = '' if alt_text == '': the_alt_text = 'alt=' + json.dumps(word("Thumbnail image of document")) + ' ' else: the_alt_text = alt_text output = '<a target="_blank"' + title + ' class="daimageref" href="' + the_url + '"><img ' + the_alt_text + 'class="daicon dapdfscreen' + extra_class + '" style="' + width_string + '" src="' + image_url + '"/></a>' if 'pages' in file_info and file_info['pages'] > 1: output += " (" + text_type(file_info['pages']) + " " + word('pages') + ")" return(output) else: return('<a target="_blank" class="daimageref" href="' + the_url + '">' + file_info['filename'] + '</a>') else: return('[Invalid image reference; reference=' + text_type(file_reference) + ', width=' + text_type(width) + ', filename=' + file_info.get('filename', 'unknown') + ']') def qr_url_string(match): string = match.group(1) try: width = match.group(2) assert width != 'None' except: width = "300px" if width == "full": width = "300px" if match.lastindex == 3: if match.group(3) != 'None': alt_text = text_type(match.group(3)) else: alt_text = word("A QR code") else: alt_text = word("A QR code") width_string = "width:" + width im = qrcode.make(string, image_factory=qrcode.image.svg.SvgPathImage) output = BytesIO() im.save(output) the_image = output.getvalue().decode() the_image = re.sub("<\?xml version='1.0' encoding='UTF-8'\?>\n", '', the_image) the_image = re.sub(r'height="[0-9]+mm" ', '', the_image) the_image = re.sub(r'width="[0-9]+mm" ', '', the_image) m = re.search(r'(viewBox="[^"]+")', the_image) if m: viewbox = m.group(1) else: viewbox = "" return('<svg style="' + width_string + '" ' + viewbox + '><g transform="scale(1.0)">' + the_image + '</g><title>' + alt_text + '</title></svg>') def convert_pixels(match): pixels = match.group(1) return (text_type(int(pixels)/72.0) + "in") def image_include_string(match, emoji=False, question=None): file_reference = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '\\textwidth' except: width = DEFAULT_IMAGE_WIDTH file_info = server.file_finder(file_reference, convert={'svg': 'eps', 'gif': 'png'}, question=question) if 'mimetype' in file_info: if re.search(r'^(audio|video)', file_info['mimetype']): return '[reference to file type that cannot be displayed]' if 'path' in file_info: if 'extension' in file_info: if file_info['extension'] in ['png', 'jpg', 'pdf', 'eps', 'jpe', 'jpeg', 'docx', 'rtf', 'doc', 'odt']: if file_info['extension'] == 'pdf': output = '\\includepdf[pages={-}]{' + file_info['path'] + '.pdf}' elif file_info['extension'] in ('docx', 'rtf', 'doc', 'odt'): if not os.path.isfile(file_info['path'] + '.pdf'): server.fg_make_pdf_for_word_path(file_info['path'], file_info['extension']) output = '\\includepdf[pages={-}]{' + file_info['path'] + '.pdf}' else: if emoji: output = '\\raisebox{-.6\\dp\\strutbox}{\\mbox{\\includegraphics[width=' + width + ']{' + file_info['path'] + '}}}' else: output = '\\mbox{\\includegraphics[width=' + width + ']{' + file_info['path'] + '}}' if width == '\\textwidth': output = '\\clearpage ' + output + '\\clearpage ' return(output) return('[invalid graphics reference]') def image_include_docx(match, question=None): file_reference = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '100%' except: width = DEFAULT_IMAGE_WIDTH file_info = server.file_finder(file_reference, convert={'svg': 'eps'}, question=question) if 'mimetype' in file_info: if re.search(r'^(audio|video)', file_info['mimetype']): return '[reference to file type that cannot be displayed]' if 'path' in file_info: if 'extension' in file_info: if file_info['extension'] in ('docx', 'rtf', 'doc', 'odt'): if not os.path.isfile(file_info['path'] + '.pdf'): server.fg_make_pdf_for_word_path(file_info['path'], file_info['extension']) output = '![](' + file_info['path'] + '.pdf){width=' + width + '}' return(output) if file_info['extension'] in ['png', 'jpg', 'gif', 'pdf', 'eps', 'jpe', 'jpeg']: output = '![](' + file_info['path'] + '){width=' + width + '}' return(output) return('[invalid graphics reference]') def qr_include_string(match): string = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '\\textwidth' except: width = DEFAULT_IMAGE_WIDTH im = qrcode.make(string) the_image = tempfile.NamedTemporaryFile(prefix="datemp", suffix=".png", delete=False) #docassemble.base.functions.this_thread.temporary_resources.add(the_image.name) im.save(the_image.name) output = '\\mbox{\\includegraphics[width=' + width + ']{' + the_image.name + '}}' if width == '\\textwidth': output = '\\clearpage ' + output + '\\clearpage ' #logmessage("Output is " + output) return(output) def qr_include_docx(match): string = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '100%' except: width = DEFAULT_IMAGE_WIDTH im = qrcode.make(string) the_image = tempfile.NamedTemporaryFile(prefix="datemp", suffix=".png", delete=False) #docassemble.base.functions.this_thread.temporary_resources.add(the_image.name) im.save(the_image.name) output = '![](' + the_image.name + '){width=' + width + '}' return(output) def rtf_caption_table(match): table_text = """\\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrs\\brdrw10 \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrs\\brdrw10 \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\pararsid1508006\\yts24 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs22\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 { [SAVE][TIGHTSPACING][STOP_INDENTATION]""" + match.group(1) + """}{\\cell}{""" + match.group(2) + """[RESTORE]}{\\cell}\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\sa200\\sl276\\slmult1\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs24\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid10753242 \\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrs\\brdrw10 \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrs\\brdrw10 \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\row }""" table_text += """\\pard \\ltrpar \\qc \\li0\\ri0\\sb0\\sl240\\slmult1\\widctlpar\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\itap0\\pararsid10753242""" table_text = re.sub(r'\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0', r'\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\sl240 \\slmult1', table_text) return table_text + '[MANUALSKIP]' def rtf_two_col(match): table_text = """\\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\pararsid1508006\\yts24 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs22\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid2427490 [SAVE][TIGHTSPACING][STOP_INDENTATION]""" + match.group(1) + """}{\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid10753242\\charrsid2427490 \\cell}{""" + match.group(2) + """[RESTORE]}{\\cell}\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\sa200\\sl276\\slmult1\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs24\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid10753242 \\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\row }""" table_text += """\\pard \\ltrpar \\qc \\li0\\ri0\\sb0\\sl240\\slmult1\\widctlpar\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\itap0\\pararsid10753242""" table_text = re.sub(r'\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0', r'\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\sl240 \\slmult1', table_text) return table_text + '[MANUALSKIP]' def emoji_html(text, status=None, question=None, images=None): #logmessage("Got to emoji_html") if status is not None and question is None: question = status.question if images is None: images = question.interview.images if text in images: if status is not None and images[text].attribution is not None: status.attributions.add(images[text].attribution) return("[EMOJI " + images[text].get_reference() + ', 1em]') icons_setting = docassemble.base.functions.get_config('default icons', None) if icons_setting == 'font awesome': m = re.search(r'^(fa[a-z])-fa-(.*)', text) if m: the_prefix = m.group(1) text = m.group(2) else: the_prefix = docassemble.base.functions.get_config('font awesome prefix', 'fas') return('<i class="' + the_prefix + ' fa-' + text_type(text) + '"></i>') elif icons_setting == 'material icons': return('<i class="da-material-icons">' + text_type(text) + '</i>') return(":" + text_type(text) + ":") def emoji_insert(text, status=None, images=None): if images is None: images = status.question.interview.images if text in images: if status is not None and images[text].attribution is not None: status.attributions.add(images[text].attribution) return("[EMOJI " + images[text].get_reference() + ', 1.2em]') else: return(":" + text_type(text) + ":") def link_rewriter(m, status): if re.search(r'^(\?|javascript:)', m.group(1)): target = '' else: target = 'target="_blank" ' action_search = re.search(r'^\?action=([^\&]+)', m.group(1)) if action_search: action_data = 'data-embaction="' + action_search.group(1) + '" ' else: action_data = '' js_search = re.search(r'^javascript:(.*)', m.group(1)) if js_search: js_data = 'data-js="' + js_search.group(1) + '" ' else: js_data = '' if status is None: return '<a ' + action_data + target + js_data + 'href="' + m.group(1) + '"' status.linkcounter += 1 return '<a data-linknum="' + text_type(status.linkcounter) + '" ' + action_data + target + js_data + 'href="' + m.group(1) + '"' def markdown_to_html(a, trim=False, pclass=None, status=None, question=None, use_pandoc=False, escape=False, do_terms=True, indent=None, strip_newlines=None, divclass=None, embedder=None, default_image_width=None): a = text_type(a) if question is None and status is not None: question = status.question if question is not None: if do_terms: if status is not None: if len(question.terms): lang = docassemble.base.functions.get_language() for term in question.terms: if lang in question.terms[term]['re']: a = question.terms[term]['re'][lang].sub(r'[[\1]]', a) else: a = question.terms[term]['re'][question.language].sub(r'[[\1]]', a) if len(question.autoterms): lang = docassemble.base.functions.get_language() for term in question.autoterms: if lang in question.autoterms[term]['re']: a = question.autoterms[term]['re'][lang].sub(r'[[\1]]', a) else: a = question.autoterms[term]['re'][question.language].sub(r'[[\1]]', a) if len(question.interview.terms): lang = docassemble.base.functions.get_language() if lang in question.interview.terms and len(question.interview.terms[lang]) > 0: for term in question.interview.terms[lang]: #logmessage("Searching for term " + term + " in " + a + "\n") a = question.interview.terms[lang][term]['re'].sub(r'[[\1]]', a) #logmessage("string is now " + text_type(a) + "\n") elif question.language in question.interview.terms and len(question.interview.terms[question.language]) > 0: for term in question.interview.terms[question.language]: #logmessage("Searching for term " + term + " in " + a + "\n") a = question.interview.terms[question.language][term]['re'].sub(r'[[\1]]', a) #logmessage("string is now " + text_type(a) + "\n") if len(question.interview.autoterms): lang = docassemble.base.functions.get_language() if lang in question.interview.autoterms and len(question.interview.autoterms[lang]) > 0: for term in question.interview.autoterms[lang]: #logmessage("Searching for term " + term + " in " + a + "\n") a = question.interview.autoterms[lang][term]['re'].sub(r'[[\1]]', a) #logmessage("string is now " + text_type(a) + "\n") elif question.language in question.interview.autoterms and len(question.interview.autoterms[question.language]) > 0: for term in question.interview.autoterms[question.language]: #logmessage("Searching for term " + term + " in " + a + "\n") a = question.interview.autoterms[question.language][term]['re'].sub(r'[[\1]]', a) #logmessage("string is now " + text_type(a) + "\n") if status is not None and question.interview.scan_for_emojis: a = emoji_match.sub((lambda x: emoji_html(x.group(1), status=status, question=question)), a) a = html_filter(text_type(a), status=status, question=question, embedder=embedder, default_image_width=default_image_width) #logmessage("before: " + a) if use_pandoc: converter = MyPandoc() converter.output_format = 'html' converter.input_content = text_type(a) converter.convert(question) result = converter.output_content else: try: result = docassemble.base.functions.this_thread.markdown.reset().convert(a) except: # Try again because sometimes it fails randomly and maybe trying again will work. result = docassemble.base.functions.this_thread.markdown.reset().convert(a) result = re.sub(r'<table>', r'<table class="table table-striped">', result) result = re.sub(r'<blockquote>', r'<blockquote class="blockquote">', result) #result = re.sub(r'<table>', r'<table class="datable">', result) result = re.sub(r'<a href="(.*?)"', lambda x: link_rewriter(x, status), result) if do_terms and question is not None and term_start.search(result): lang = docassemble.base.functions.get_language() if status is not None: if len(question.terms): result = term_match.sub((lambda x: add_terms(x.group(1), status.extras['terms'], status=status, question=question)), result) if len(question.autoterms): result = term_match.sub((lambda x: add_terms(x.group(1), status.extras['autoterms'], status=status, question=question)), result) if lang in question.interview.terms and len(question.interview.terms[lang]): result = term_match.sub((lambda x: add_terms(x.group(1), question.interview.terms[lang], status=status, question=question)), result) elif question.language in question.interview.terms and len(question.interview.terms[question.language]): result = term_match.sub((lambda x: add_terms(x.group(1), question.interview.terms[question.language], status=status, question=question)), result) if lang in question.interview.autoterms and len(question.interview.autoterms[lang]): result = term_match.sub((lambda x: add_terms(x.group(1), question.interview.autoterms[lang], status=status, question=question)), result) elif question.language in question.interview.autoterms and len(question.interview.autoterms[question.language]): result = term_match.sub((lambda x: add_terms(x.group(1), question.interview.autoterms[question.language], status=status, question=question)), result) if trim: if result.startswith('<p>') and result.endswith('</p>'): result = result[3:-4] elif pclass: result = re.sub('<p>', '<p class="' + pclass + '">', result) if escape: result = noquote_match.sub('&quot;', result) result = lt_match.sub('&lt;', result) result = gt_match.sub('&gt;', result) result = amp_match.sub('&amp;', result) #logmessage("after: " + result) #result = result.replace('\n', ' ') if result: if strip_newlines: result = result.replace('\n', ' ') if divclass is not None: result = '<div class="' + text_type(divclass) + '">' + result + '</div>' if indent and not code_match.search(result): return (" " * indent) + re.sub(r'\n', "\n" + (" " * indent), result).rstrip() + "\n" return(result) def my_escape(result): result = noquote_match.sub('&quot;', result) result = lt_match.sub('&lt;', result) result = gt_match.sub('&gt;', result) result = amp_match.sub('&amp;', result) return(result) def noquote(string): #return json.dumps(string.replace('\n', ' ').rstrip()) return '"' + string.replace('\n', ' ').replace('"', '&quot;').rstrip() + '"' def add_terms_mako(termname, terms, status=None, question=None): lower_termname = termname.lower() if lower_termname in terms: return('<a tabindex="0" class="daterm" data-toggle="popover" data-placement="bottom" data-content=' + noquote(markdown_to_html(terms[lower_termname]['definition'].text(dict()), trim=True, default_image_width='100%', do_terms=False, status=status, question=question)) + '>' + text_type(termname) + '</a>') #logmessage(lower_termname + " is not in terms dictionary\n") return '[[' + termname + ']]' def add_terms(termname, terms, status=None, question=None): lower_termname = termname.lower() if lower_termname in terms: return('<a tabindex="0" class="daterm" data-toggle="popover" data-placement="bottom" data-content=' + noquote(markdown_to_html(terms[lower_termname]['definition'], trim=True, default_image_width='100%', do_terms=False, status=status, question=question)) + '>' + text_type(termname) + '</a>') #logmessage(lower_termname + " is not in terms dictionary\n") return '[[' + termname + ']]' def audio_control(files, preload="metadata", title_text=None): for d in files: if isinstance(d, string_types): return d if title_text is None: title_text = '' else: title_text = " title=" + json.dumps(title_text) output = '<audio' + title_text + ' class="daaudio-control" controls="controls" preload="' + preload + '">' + "\n" for d in files: if type(d) is list: output += ' <source src="' + d[0] + '"' if d[1] is not None: output += ' type="' + d[1] + '"/>' output += "\n" output += ' <a target="_blank" href="' + files[-1][0] + '">' + word('Listen') + '</a>\n' output += "</audio>\n" return output def video_control(files): for d in files: if isinstance(d, (string_types, NoneType)): return text_type(d) output = '<video class="dawidevideo" controls="controls">' + "\n" for d in files: if type(d) is list: if d[0] is None: continue output += ' <source src="' + d[0] + '"' if d[1] is not None: output += ' type="' + d[1] + '"/>' output += "\n" output += ' <a target="_blank" href="' + files[-1][0] + '">' + word('Listen') + '</a>\n' output += "</video>\n" return output def get_audio_urls(the_audio, question=None): output = list() the_list = list() to_try = dict() for audio_item in the_audio: if audio_item['type'] != 'audio': continue found_upload = False pattern = re.compile(r'^\[FILE ([^,\]]+)') for (file_ref) in re.findall(pattern, audio_item['text']): found_upload = True m = re.match(r'[0-9]+', file_ref) if m: file_info = server.file_finder(file_ref, question=question) if 'path' in file_info: if file_info['mimetype'] == 'audio/ogg': output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) elif os.path.isfile(file_info['path'] + '.ogg'): output.append([server.url_finder(file_ref, ext='ogg', _question=question), 'audio/ogg']) if file_info['mimetype'] == 'audio/mpeg': output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) elif os.path.isfile(file_info['path'] + '.mp3'): output.append([server.url_finder(file_ref, ext='mp3', _question=question), 'audio/mpeg']) if file_info['mimetype'] not in ['audio/mpeg', 'audio/ogg']: output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) else: the_list.append({'text': file_ref, 'package': audio_item['package']}) if not found_upload: the_list.append(audio_item) for audio_item in the_list: mimetype, encoding = mimetypes.guess_type(audio_item['text']) if re.search(r'^http', audio_item['text']): output.append([audio_item['text'], mimetype]) continue basename = os.path.splitext(audio_item['text'])[0] ext = os.path.splitext(audio_item['text'])[1] if not mimetype in to_try: to_try[mimetype] = list(); to_try[mimetype].append({'basename': basename, 'filename': audio_item['text'], 'ext': ext, 'package': audio_item['package']}) if 'audio/mpeg' in to_try and 'audio/ogg' not in to_try: to_try['audio/ogg'] = list() for attempt in to_try['audio/mpeg']: if attempt['ext'] == '.MP3': to_try['audio/ogg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.OGG', 'ext': '.OGG', 'package': attempt['package']}) else: to_try['audio/ogg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.ogg', 'ext': '.ogg', 'package': attempt['package']}) if 'audio/ogg' in to_try and 'audio/mpeg' not in to_try: to_try['audio/mpeg'] = list() for attempt in to_try['audio/ogg']: if attempt['ext'] == '.OGG': to_try['audio/mpeg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.MP3', 'ext': '.MP3', 'package': attempt['package']}) else: to_try['audio/mpeg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.mp3', 'ext': '.mp3', 'package': attempt['package']}) for mimetype in reversed(sorted(to_try.keys())): for attempt in to_try[mimetype]: parts = attempt['filename'].split(':') if len(parts) < 2: parts = [attempt['package'], attempt['filename']] if parts[0] is None: parts[0] = 'None' parts[1] = re.sub(r'^data/static/', '', parts[1]) full_file = parts[0] + ':data/static/' + parts[1] file_info = server.file_finder(full_file, question=question) if 'fullpath' in file_info: url = server.url_finder(full_file, _question=question) output.append([url, mimetype]) return output def get_video_urls(the_video, question=None): output = list() the_list = list() to_try = dict() for video_item in the_video: if video_item['type'] != 'video': continue found_upload = False if re.search(r'^\[(YOUTUBE|VIMEO)[0-9\:]* ', video_item['text']): output.append(html_filter(video_item['text'])) continue pattern = re.compile(r'^\[FILE ([^,\]]+)') for (file_ref) in re.findall(pattern, video_item['text']): found_upload = True m = re.match(r'[0-9]+', file_ref) if m: file_info = server.file_finder(file_ref, question=question) if 'path' in file_info: if file_info['mimetype'] == 'video/ogg': output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) elif os.path.isfile(file_info['path'] + '.ogv'): output.append([server.url_finder(file_ref, ext='ogv', _question=question), 'video/ogg']) if file_info['mimetype'] == 'video/mp4': output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) elif os.path.isfile(file_info['path'] + '.mp4'): output.append([server.url_finder(file_ref, ext='mp4', _question=question), 'video/mp4']) if file_info['mimetype'] not in ['video/mp4', 'video/ogg']: output.append([server.url_finder(file_ref, _question=question), file_info['mimetype']]) else: the_list.append({'text': file_ref, 'package': video_item['package']}) if not found_upload: the_list.append(video_item) for video_item in the_list: mimetype, encoding = mimetypes.guess_type(video_item['text']) if re.search(r'^http', video_item['text']): output.append([video_item['text'], mimetype]) continue basename = os.path.splitext(video_item['text'])[0] ext = os.path.splitext(video_item['text'])[1] if not mimetype in to_try: to_try[mimetype] = list(); to_try[mimetype].append({'basename': basename, 'filename': video_item['text'], 'ext': ext, 'package': video_item['package']}) if 'video/mp4' in to_try and 'video/ogg' not in to_try: to_try['video/ogg'] = list() for attempt in to_try['video/mp4']: if attempt['ext'] == '.MP4': to_try['video/ogg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.OGV', 'ext': '.OGV', 'package': attempt['package']}) else: to_try['video/ogg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.ogv', 'ext': '.ogv', 'package': attempt['package']}) if 'video/ogg' in to_try and 'video/mp4' not in to_try: to_try['video/mp4'] = list() for attempt in to_try['video/ogg']: if attempt['ext'] == '.OGV': to_try['video/mp4'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.MP4', 'ext': '.MP4', 'package': attempt['package']}) else: to_try['audio/mpeg'].append({'basename': attempt['basename'], 'filename': attempt['basename'] + '.mp4', 'ext': '.mp4', 'package': attempt['package']}) for mimetype in reversed(sorted(to_try.keys())): for attempt in to_try[mimetype]: parts = attempt['filename'].split(':') if len(parts) < 2: parts = [attempt['package'], attempt['filename']] if parts[0] is None: parts[0] = 'None' parts[1] = re.sub(r'^data/static/', '', parts[1]) full_file = parts[0] + ':data/static/' + parts[1] file_info = server.file_finder(full_file, question=question) if 'fullpath' in file_info: url = server.url_finder(full_file, _question=question) if url is not None: output.append([url, mimetype]) return output def to_text(html_doc, terms, links, status): output = "" #logmessage("to_text: html doc is " + text_type(html_doc)) soup = BeautifulSoup(html_doc, 'html.parser') [s.extract() for s in soup(['style', 'script', '[document]', 'head', 'title', 'audio', 'video', 'pre', 'attribution'])] [s.extract() for s in soup.find_all(hidden)] [s.extract() for s in soup.find_all('div', {'class': 'dainvisible'})] for s in soup.find_all(do_show): if s.name in ['input', 'textarea', 'img'] and s.has_attr('alt'): words = s.attrs['alt'] if s.has_attr('placeholder'): words += ", " + s.attrs['placeholder'] else: words = s.get_text() words = re.sub(r'\n\s*', ' ', words, flags=re.DOTALL) output += words + "\n" for s in soup.find_all('a'): if s.has_attr('class') and s.attrs['class'][0] == 'daterm' and s.has_attr('data-content'): terms[s.string] = s.attrs['data-content'] elif s.has_attr('href'):# and (s.attrs['href'].startswith(url) or s.attrs['href'].startswith('?')): #logmessage("Adding a link: " + s.attrs['href']) links.append((s.attrs['href'], s.get_text())) output = re.sub(br'\u201c'.decode('raw_unicode_escape'), '"', output) output = re.sub(br'\u201d'.decode('raw_unicode_escape'), '"', output) output = re.sub(br'\u2018'.decode('raw_unicode_escape'), "'", output) output = re.sub(br'\u2019'.decode('raw_unicode_escape'), "'", output) output = re.sub(br'\u201b'.decode('raw_unicode_escape'), "'", output) output = re.sub(r'&amp;gt;', '>', output) output = re.sub(r'&amp;lt;', '<', output) output = re.sub(r'&gt;', '>', output) output = re.sub(r'&lt;', '<', output) output = re.sub(r'<[^>]+>', '', output) output = re.sub(r'\n$', '', output) output = re.sub(r' +', ' ', output) return output bad_list = ['div', 'option'] good_list = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'button', 'textarea', 'note'] def do_show(element): if re.match('<!--.*-->', text_type(element), re.DOTALL): return False if element.name in ['option'] and element.has_attr('selected'): return True if element.name in bad_list: return False if element.name in ['img', 'input'] and element.has_attr('alt'): return True if element.name in good_list: return True if element.parent and element.parent.name in good_list: return False if element.string: return True if re.match(r'\s+', element.get_text()): return False return False def hidden(element): if element.name == 'input': if element.has_attr('type'): if element.attrs['type'] == 'hidden': return True return False def replace_fields(string, status=None, embedder=None): if not re.search(r'\[FIELD ', string): return string matches = list() in_match = False start_match = None depth = 0 i = 0 while i < len(string): if string[i:i+7] == '[FIELD ': in_match = True start_match = i i += 7 continue if in_match: if string[i] == '[': depth += 1 elif string[i] == ']': if depth == 0: i += 1 matches.append((start_match, i)) in_match = False continue else: depth -= 1 i += 1 field_strings = list() for (start, end) in matches: field_strings.append(string[start:end]) #logmessage(repr(field_strings)) for field_string in field_strings: if embedder is None: string = string.replace(field_string, 'ERROR: FIELD cannot be used here') else: string = string.replace(field_string, embedder(status, field_string)) return string def image_include_docx_template(match, question=None): file_reference = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '100%' except: width = DEFAULT_IMAGE_WIDTH file_info = server.file_finder(file_reference, convert={'svg': 'eps'}, question=question) if 'mimetype' in file_info: if re.search(r'^(audio|video)', file_info['mimetype']): return '[reference to file type that cannot be displayed]' if 'path' in file_info: if 'mimetype' in file_info: if file_info['mimetype'] in ('text/markdown', 'text/plain'): with open(file_info['fullpath'], 'rU', encoding='utf-8') as f: contents = f.read() if file_info['mimetype'] == 'text/plain': return contents else: return docassemble.base.file_docx.markdown_to_docx(contents, docassemble.base.functions.this_thread.misc.get('docx_template', None)) if file_info['mimetype'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': return text_type(docassemble.base.file_docx.include_docx_template(docassemble.base.functions.DALocalFile(file_info['fullpath']))) else: return text_type(docassemble.base.file_docx.image_for_docx(file_reference, question, docassemble.base.functions.this_thread.misc.get('docx_template', None), width=width)) return '[reference to file that could not be found]' def qr_include_docx_template(match): string = match.group(1) try: width = match.group(2) assert width != 'None' width = re.sub(r'^(.*)px', convert_pixels, width) if width == "full": width = '100%' except: width = DEFAULT_IMAGE_WIDTH im = qrcode.make(string) the_image = tempfile.NamedTemporaryFile(prefix="datemp", suffix=".png", delete=False) im.save(the_image.name) return text_type(docassemble.base.file_docx.image_for_docx(docassemble.base.functions.DALocalFile(the_image.name), None, docassemble.base.functions.this_thread.misc.get('docx_template', None), width=width)) def ensure_valid_filename(filename): m = re.search(r'[\\/\&\`:;,~\'\"\*\?\<\>\|]', filename) if m: raise Exception("Filename contained invalid character " + repr(m.group(1))) for char in filename: if ord(char) < 32 or ord(char) >= 127: raise Exception("Filename contained invalid character " + repr(char)) return True
en
0.195609
# -*- coding: utf-8 -*- # def blank_da_send_mail(*args, **kwargs): # logmessage("da_send_mail: no mail agent configured!") # return(None) # da_send_mail = blank_da_send_mail # def set_da_send_mail(func): # global da_send_mail # da_send_mail = func # return # def blank_file_finder(*args, **kwargs): # return(dict(filename="invalid")) # file_finder = blank_file_finder # def set_file_finder(func): # global file_finder # #sys.stderr.write("set the file finder to " + text_type(func) + "\n") # file_finder = func # return # def blank_url_finder(*args, **kwargs): # return('about:blank') # url_finder = blank_url_finder # def set_url_finder(func): # global url_finder # url_finder = func # return # def blank_url_for(*args, **kwargs): # return('about:blank') # url_for = blank_url_for # def set_url_for(func): # global url_for # url_for = func # return # ', '[HEADING1] ', text, flags=re.MULTILINE) ## ', '[HEADING2] ', text, flags=re.MULTILINE) ### ', '[HEADING3] ', text, flags=re.MULTILINE) #### ', '[HEADING4] ', text, flags=re.MULTILINE) ##### ', '[HEADING5] ', text, flags=re.MULTILINE) ###### ', '[HEADING6] ', text, flags=re.MULTILINE) ####### ', '[HEADING7] ', text, flags=re.MULTILINE) ######## ', '[HEADING8] ', text, flags=re.MULTILINE) ######### ', '[HEADING9] ', text, flags=re.MULTILINE) #logmessage("Output is " + repr(output)) #sys.stderr.write(text + "\n") #logmessage("Gi there!") # with open('/tmp/asdf.rtf', 'w') as deb_file: # deb_file.write(text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) #logmessage('docx_template_filter') # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) #text = re.sub(r'\[REDACTION_SPACE\]', r'', text) #text = re.sub(r'\[REDACTION_WORD ([^\]]+)\]', lambda x: repeat_along('X', x), text) #if len(metadata): # text = yaml.dump(metadata) + "\n---\n" + text # text = re.sub(r'\[FIELD ([^\]]+)\]', '', text) # if embedder is not None: # text = re.sub(r'\[FIELD ([^\]]+)\]', lambda x: embedder(status, x.group(1)), text) # else: # text = re.sub(r'\[FIELD ([^\]]+)\]', 'ERROR: FIELD cannot be used here', text) # width="420" height="315" # width="500" height="281" #9608;&#8203;', text) #9608;', x), text) #logmessage('image_as_rtf: path is ' + file_info['path']) #logmessage("image_as_rtf: Adding page break\n") #output += '\\page ' #logmessage("image_as_rtf: maxpage is " + text_type(int(file_info['pages'])) + "\n") #logmessage("image_as_rtf: doing page " + text_type(page) + "\n") #logmessage("Test path is " + test_path) #logmessage("image_as_rtf: test path " + test_path + " exists") #logmessage("Waiting for test path to go away") # if not width_supplied: # #logmessage("Adding page break\n") # output += '\\page ' # else: #logmessage("Returning output\n") #logmessage("Adding page break\n") #logmessage("Adding page break\n") #logmessage("Returning output\n") #logmessage("scale is " + text_type(scale) + "\n") #logmessage("scale is " + text_type(scale) + "\n") #logmessage("scale is " + text_type(scale) + "\n") #scale *= 100.0 #logmessage("scale is " + text_type(scale) + "\n") #scale = int(scale) #logmessage("scale is " + text_type(scale) + "\n") #logmessage(content + image.Data) #logmessage("value is " + text_type(value) + " and unit is " + unit + "\n") #logmessage("size is " + text_type(size) + "\n") #docassemble.base.functions.this_thread.temporary_resources.add(the_image.name) #logmessage("Output is " + output) #docassemble.base.functions.this_thread.temporary_resources.add(the_image.name) \\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrs\\brdrw10 \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrs\\brdrw10 \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\pararsid1508006\\yts24 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs22\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 { [SAVE][TIGHTSPACING][STOP_INDENTATION] }{\\cell}{ [RESTORE]}{\\cell}\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\sa200\\sl276\\slmult1\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs24\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid10753242 \\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrs\\brdrw10 \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrs\\brdrw10 \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\row } \\pard \\ltrpar \\qc \\li0\\ri0\\sb0\\sl240\\slmult1\\widctlpar\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\itap0\\pararsid10753242 \\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\pararsid1508006\\yts24 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs22\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid2427490 [SAVE][TIGHTSPACING][STOP_INDENTATION] }{\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid10753242\\charrsid2427490 \\cell}{ [RESTORE]}{\\cell}\\pard\\plain \\ltrpar \\ql \\li0\\ri0\\sa200\\sl276\\slmult1\\widctlpar\\intbl\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0 \\rtlch\\fcs1 \\af0\\afs22\\alang1025 \\ltrch\\fcs0 \\fs24\\lang1033\\langfe1033\\cgrid\\langnp1033\\langfenp1033 {\\rtlch\\fcs1 \\af0 \\ltrch\\fcs0 \\insrsid10753242 \\trowd \\irow0\\irowband0\\lastrow \\ltrrow\\ts24\\trgaph108\\trleft0\\trbrdrt\\brdrs\\brdrw10 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrh\\brdrs\\brdrw10 \\trbrdrv\\brdrs\\brdrw10 \\trftsWidth1\\trftsWidthB3\\trftsWidthA3\\trautofit1\\trpaddl108\\trpaddr108\\trpaddfl3\\trpaddft3\\trpaddfb3\\trpaddfr3\\trcbpat1\\trcfpat1\\tblrsid1508006\\tbllkhdrrows\\tbllkhdrcols\\tbllknocolband\\tblind0\\tblindtype3 \\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx4680\\clvertalc\\clbrdrt\\brdrnone \\clbrdrl\\brdrnone \\clbrdrb\\brdrnone \\clbrdrr\\clshdng0\\brdrnone \\cltxlrtb\\clftsWidth3\\clwWidth4732 \\cellx9468\\row } \\pard \\ltrpar \\qc \\li0\\ri0\\sb0\\sl240\\slmult1\\widctlpar\\wrapdefault\\aspalpha\\aspnum\\faauto\\adjustright\\rin0\\lin0\\itap0\\pararsid10753242 #logmessage("Got to emoji_html") #logmessage("Searching for term " + term + " in " + a + "\n") #logmessage("string is now " + text_type(a) + "\n") #logmessage("Searching for term " + term + " in " + a + "\n") #logmessage("string is now " + text_type(a) + "\n") #logmessage("Searching for term " + term + " in " + a + "\n") #logmessage("string is now " + text_type(a) + "\n") #logmessage("Searching for term " + term + " in " + a + "\n") #logmessage("string is now " + text_type(a) + "\n") #logmessage("before: " + a) # Try again because sometimes it fails randomly and maybe trying again will work. #result = re.sub(r'<table>', r'<table class="datable">', result) #logmessage("after: " + result) #result = result.replace('\n', ' ') #return json.dumps(string.replace('\n', ' ').rstrip()) #logmessage(lower_termname + " is not in terms dictionary\n") #logmessage(lower_termname + " is not in terms dictionary\n") #logmessage("to_text: html doc is " + text_type(html_doc)) # and (s.attrs['href'].startswith(url) or s.attrs['href'].startswith('?')): #logmessage("Adding a link: " + s.attrs['href']) #logmessage(repr(field_strings))
2.030011
2
face_recognition_final_year/user_manager_app/views.py
chiragsaraswat/automated_authentication_system_using_face_recognition
0
6625072
from django.shortcuts import render, redirect from .forms import NewUserForm from django.contrib.auth import login, authenticate, logout from django.contrib import messages from django.contrib.auth.forms import AuthenticationForm from .models import Attendance from django.http import HttpResponse # Create your views here. def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user,backend='django.contrib.auth.backends.ModelBackend') messages.info(request, f"You are now logged in as {username}.") return redirect("face_recognizer_app:index") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="user_manager_app/login.html", context={"login_form":form}) def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user,backend='django.contrib.auth.backends.ModelBackend') messages.success(request, "Registration successful." ) return redirect("face_recognizer_app:add_photos") messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm return render (request=request, template_name="user_manager_app/register.html", context={"register_form":form}) def logout_request(request): logout(request) messages.info(request, "You have successfully logged out.") return redirect("face_recognizer_app:index")
from django.shortcuts import render, redirect from .forms import NewUserForm from django.contrib.auth import login, authenticate, logout from django.contrib import messages from django.contrib.auth.forms import AuthenticationForm from .models import Attendance from django.http import HttpResponse # Create your views here. def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user,backend='django.contrib.auth.backends.ModelBackend') messages.info(request, f"You are now logged in as {username}.") return redirect("face_recognizer_app:index") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="user_manager_app/login.html", context={"login_form":form}) def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user,backend='django.contrib.auth.backends.ModelBackend') messages.success(request, "Registration successful." ) return redirect("face_recognizer_app:add_photos") messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm return render (request=request, template_name="user_manager_app/register.html", context={"register_form":form}) def logout_request(request): logout(request) messages.info(request, "You have successfully logged out.") return redirect("face_recognizer_app:index")
en
0.968116
# Create your views here.
2.295524
2
boofuzz/boofuzz/sex.py
youngcraft/boofuzz-modbus
23
6625073
<reponame>youngcraft/boofuzz-modbus import attr # Sulley EXception Class class BoofuzzError(Exception): pass class BoofuzzRestartFailedError(BoofuzzError): pass class BoofuzzTargetConnectionFailedError(BoofuzzError): pass class BoofuzzTargetConnectionReset(BoofuzzError): pass @attr.s class BoofuzzTargetConnectionAborted(BoofuzzError): """ Raised on `errno.ECONNABORTED`. """ socket_errno = attr.ib() socket_errmsg = attr.ib() class SullyRuntimeError(Exception): pass class SizerNotUtilizedError(Exception): pass class MustImplementException(Exception): pass
import attr # Sulley EXception Class class BoofuzzError(Exception): pass class BoofuzzRestartFailedError(BoofuzzError): pass class BoofuzzTargetConnectionFailedError(BoofuzzError): pass class BoofuzzTargetConnectionReset(BoofuzzError): pass @attr.s class BoofuzzTargetConnectionAborted(BoofuzzError): """ Raised on `errno.ECONNABORTED`. """ socket_errno = attr.ib() socket_errmsg = attr.ib() class SullyRuntimeError(Exception): pass class SizerNotUtilizedError(Exception): pass class MustImplementException(Exception): pass
en
0.573579
# Sulley EXception Class Raised on `errno.ECONNABORTED`.
2.369984
2
hackerrank/data-structures/stacks/simple-text-editor/simple-text-editor.py
EliahKagan/practice
0
6625074
#!/usr/bin/env python3 """ HackerRank - Simple Text Editor https://www.hackerrank.com/challenges/simple-text-editor naive approach, storing full snapshots """ class Editor: """ Text buffer supporting appending and truncation, with undo capability. """ __slots__ = ('_buffers',) def __init__(self): """Creates a new editor with an initially empty buffer.""" self._buffers = [""] def append(self, text): """Saves a checkpoint and appends text to the buffer.""" self._buffers.append(self._buffers[-1] + text) def delete(self, count): """Saves a checkpoint and truncates the buffer.""" self._buffers.append(self._buffers[-1][:-count]) def print(self, index): """Prints a (1-based) indexed character.""" print(self._buffers[-1][index - 1]) def undo(self): """Reverts the last append or delete.""" del self._buffers[-1] if __name__ == '__main__': editor = Editor() for _ in range(int(input())): tokens = input().split() opcode = int(tokens[0]) if opcode == 1: editor.append(tokens[1]) elif opcode == 2: editor.delete(int(tokens[1])) elif opcode == 3: editor.print(int(tokens[1])) elif opcode == 4: editor.undo()
#!/usr/bin/env python3 """ HackerRank - Simple Text Editor https://www.hackerrank.com/challenges/simple-text-editor naive approach, storing full snapshots """ class Editor: """ Text buffer supporting appending and truncation, with undo capability. """ __slots__ = ('_buffers',) def __init__(self): """Creates a new editor with an initially empty buffer.""" self._buffers = [""] def append(self, text): """Saves a checkpoint and appends text to the buffer.""" self._buffers.append(self._buffers[-1] + text) def delete(self, count): """Saves a checkpoint and truncates the buffer.""" self._buffers.append(self._buffers[-1][:-count]) def print(self, index): """Prints a (1-based) indexed character.""" print(self._buffers[-1][index - 1]) def undo(self): """Reverts the last append or delete.""" del self._buffers[-1] if __name__ == '__main__': editor = Editor() for _ in range(int(input())): tokens = input().split() opcode = int(tokens[0]) if opcode == 1: editor.append(tokens[1]) elif opcode == 2: editor.delete(int(tokens[1])) elif opcode == 3: editor.print(int(tokens[1])) elif opcode == 4: editor.undo()
en
0.772627
#!/usr/bin/env python3 HackerRank - Simple Text Editor https://www.hackerrank.com/challenges/simple-text-editor naive approach, storing full snapshots Text buffer supporting appending and truncation, with undo capability. Creates a new editor with an initially empty buffer. Saves a checkpoint and appends text to the buffer. Saves a checkpoint and truncates the buffer. Prints a (1-based) indexed character. Reverts the last append or delete.
3.659637
4
main/views/public/common/common_decorator.py
tiberiucorbu/av-website
0
6625075
from . import * def decorate_page_response_model(resp_model): decorate_navbar_model(resp_model) decorate_page_meta(resp_model) decorate_view_reduced_switcher(resp_model) decorate_footer_model(resp_model)
from . import * def decorate_page_response_model(resp_model): decorate_navbar_model(resp_model) decorate_page_meta(resp_model) decorate_view_reduced_switcher(resp_model) decorate_footer_model(resp_model)
none
1
1.192042
1
sfepy/linalg/extmods/setup.py
vondrejc/sfepy
0
6625076
<gh_stars>0 #!/usr/bin/env python def configuration(parent_package='', top_path=None): import os.path as op from numpy.distutils.misc_util import Configuration from sfepy import Config site_config = Config() os_flag = {'posix' : 0, 'windows' : 1} auto_dir = op.dirname(__file__) auto_name = op.split(auto_dir)[-1] config = Configuration(auto_name, parent_package, top_path) defines = [('__SDIR__', "'\"%s\"'" % auto_dir), ('SFEPY_PLATFORM', os_flag[site_config.system()])] if '-DDEBUG_FMF' in site_config.debug_flags(): defines.append(('DEBUG_FMF', None)) common_path = '../../discrete/fem/extmods' fem_src = ['common_python.c'] fem_src = [op.join(common_path, ii) for ii in fem_src] src = ['crcm.pyx', 'rcm.c'] config.add_extension('crcm', sources=src + fem_src, extra_compile_args=site_config.compile_flags(), extra_link_args=site_config.link_flags(), include_dirs=[auto_dir, common_path], define_macros=defines) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
#!/usr/bin/env python def configuration(parent_package='', top_path=None): import os.path as op from numpy.distutils.misc_util import Configuration from sfepy import Config site_config = Config() os_flag = {'posix' : 0, 'windows' : 1} auto_dir = op.dirname(__file__) auto_name = op.split(auto_dir)[-1] config = Configuration(auto_name, parent_package, top_path) defines = [('__SDIR__', "'\"%s\"'" % auto_dir), ('SFEPY_PLATFORM', os_flag[site_config.system()])] if '-DDEBUG_FMF' in site_config.debug_flags(): defines.append(('DEBUG_FMF', None)) common_path = '../../discrete/fem/extmods' fem_src = ['common_python.c'] fem_src = [op.join(common_path, ii) for ii in fem_src] src = ['crcm.pyx', 'rcm.c'] config.add_extension('crcm', sources=src + fem_src, extra_compile_args=site_config.compile_flags(), extra_link_args=site_config.link_flags(), include_dirs=[auto_dir, common_path], define_macros=defines) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
ru
0.26433
#!/usr/bin/env python
1.858936
2
ch6/decomposable_att_model/decomp_att.py
thundercrawl/book-of-qna-code
121
6625077
# -*- encoding:utf8 -*- import tensorflow as tf import numpy as np import os import sys from copy import deepcopy stdout = sys.stdout reload(sys) sys.stdout = stdout os.environ["CUDA_VISIBLE_DEVICES"] = "0" import cPickle as pkl from utils import * from models import DecompAtt class DecompAttConfig(object): def __init__(self, vocab_size, embeddings=None): # 输入问题(句子)长度 self.max_q_length = 200 # 输入答案长度 self.max_a_length = 200 # 循环数 self.num_epochs = 100 # batch大小 self.batch_size = 128 # 词表大小 self.vocab_size = vocab_size # 词向量大小 self.embeddings = embeddings self.embedding_size = 100 if self.embeddings is not None: self.embedding_size = embeddings.shape[1] # RNN单元类型和大小与堆叠层数 self.cell_type = 'GRU' self.rnn_size = 128 self.layer_size = 1 # 隐层大小 self.hidden_size = 128 self.output_size = 128 # keep_prob=1-dropout self.keep_prob = 0.6 # 学习率 self.lr = 0.0003 self.grad_clip = 1. self.cf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) self.cf.gpu_options.per_process_gpu_memory_fraction = 0.2 def train(train_corpus, config, val_corpus, eval_train_corpus=None): iterator = Iterator(train_corpus) if not os.path.exists(model_path): os.mkdir(model_path) with tf.Session(config=config.cf) as sess: model = DecompAtt(config) saver = tf.train.Saver() sess.run(tf.initialize_all_variables()) for epoch in xrange(config.num_epochs): count = 0 for batch_x in iterator.next(config.batch_size, shuffle=True): batch_qids, batch_q, batch_aids, batch_ap, labels = zip(*batch_x) batch_q = np.asarray(batch_q) batch_ap = np.asarray(batch_ap) labels = np.asarray(labels).astype(np.int32) _, loss = sess.run([model.train_op, model.total_loss], feed_dict={model.q:batch_q, model.a:batch_ap, model.y:labels, model.keep_prob:config.keep_prob}) count += 1 if count % 10 == 0: print('[epoch {}, batch {}]Loss:{}'.format(epoch, count, loss)) saver.save(sess,'{}/my_model'.format(model_path), global_step=epoch) if eval_train_corpus is not None: train_res = evaluate(sess, model, eval_train_corpus, config) print('[train] ' + train_res) if val_corpus is not None: val_res = evaluate(sess, model, val_corpus, config) print('[eval] ' + val_res) def evaluate(sess, model, corpus, config): iterator = Iterator(corpus) count = 0 total_qids = [] total_aids = [] total_pred = [] total_labels = [] total_loss = 0. for batch_x in iterator.next(config.batch_size, shuffle=False): batch_qids, batch_q, batch_aids, batch_ap, labels = zip(*batch_x) batch_q = np.asarray(batch_q) batch_ap = np.asarray(batch_ap) y_hat, loss = sess.run([model.y_hat, model.total_loss], feed_dict={model.q:batch_q, model.a:batch_ap, model.y:labels, model.keep_prob:1.}) y_hat = np.argmax(y_hat, axis=-1) total_loss += loss count += 1 total_qids.append(batch_qids) total_aids.append(batch_aids) total_pred.append(y_hat) total_labels.append(labels) # print(batch_qids[0], [id2word[_] for _ in batch_q[0]], # batch_aids[0], [id2word[_] for _ in batch_ap[0]]) total_qids = np.concatenate(total_qids, axis=0) total_aids = np.concatenate(total_aids, axis=0) total_pred = np.concatenate(total_pred, axis=0) total_labels = np.concatenate(total_labels, axis=0) MAP, MRR = eval_map_mrr(total_qids, total_aids, total_pred, total_labels) # print('Eval loss:{}'.format(total_loss / count)) return 'MAP:{}, MRR:{}'.format(MAP, MRR) def test(corpus, config): with tf.Session(config=config.cf) as sess: model = DecompAtt(config) saver = tf.train.Saver() saver.restore(sess, tf.train.latest_checkpoint(model_path)) print('[test] ' + evaluate(sess, model, corpus, config)) def main(args): max_q_length = 25 max_a_length = 90 with open(os.path.join(processed_data_path, 'pointwise_corpus.pkl'), 'r') as fr: train_corpus, val_corpus, test_corpus = pkl.load(fr) embeddings = build_embedding(embedding_path, word2id) train_qids, train_q, train_aids, train_ap, train_labels = zip(*train_corpus) train_q = padding(train_q, max_q_length) train_ap = padding(train_ap, max_a_length) train_corpus = zip(train_qids, train_q, train_aids, train_ap, train_labels) val_qids, val_q, val_aids, val_ap, labels = zip(*val_corpus) val_q = padding(val_q, max_q_length) val_ap = padding(val_ap, max_a_length) val_corpus = zip(val_qids, val_q, val_aids, val_ap, labels) test_qids, test_q, test_aids, test_ap, labels = zip(*test_corpus) test_q = padding(test_q, max_q_length) test_ap = padding(test_ap, max_a_length) test_corpus = zip(test_qids, test_q, test_aids, test_ap, labels) config = DecompAttConfig(max(word2id.values()) + 1, embeddings=embeddings) config.max_q_length = max_q_length config.max_a_length = max_a_length if args.train: train(deepcopy(train_corpus), config, val_corpus, deepcopy(train_corpus)) elif args.test: test(test_corpus, config) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument("--train", help="whether to train", action='store_true') parser.add_argument("--test", help="whether to test", action='store_true') args = parser.parse_args() raw_data_path = '../data/WikiQA/raw' processed_data_path = '../data/WikiQA/processed' embedding_path = '../data/embedding/glove.6B.300d.txt' model_path = 'models' with open(os.path.join(processed_data_path, 'vocab.pkl'), 'r') as fr: word2id, id2word = pkl.load(fr) main(args)
# -*- encoding:utf8 -*- import tensorflow as tf import numpy as np import os import sys from copy import deepcopy stdout = sys.stdout reload(sys) sys.stdout = stdout os.environ["CUDA_VISIBLE_DEVICES"] = "0" import cPickle as pkl from utils import * from models import DecompAtt class DecompAttConfig(object): def __init__(self, vocab_size, embeddings=None): # 输入问题(句子)长度 self.max_q_length = 200 # 输入答案长度 self.max_a_length = 200 # 循环数 self.num_epochs = 100 # batch大小 self.batch_size = 128 # 词表大小 self.vocab_size = vocab_size # 词向量大小 self.embeddings = embeddings self.embedding_size = 100 if self.embeddings is not None: self.embedding_size = embeddings.shape[1] # RNN单元类型和大小与堆叠层数 self.cell_type = 'GRU' self.rnn_size = 128 self.layer_size = 1 # 隐层大小 self.hidden_size = 128 self.output_size = 128 # keep_prob=1-dropout self.keep_prob = 0.6 # 学习率 self.lr = 0.0003 self.grad_clip = 1. self.cf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) self.cf.gpu_options.per_process_gpu_memory_fraction = 0.2 def train(train_corpus, config, val_corpus, eval_train_corpus=None): iterator = Iterator(train_corpus) if not os.path.exists(model_path): os.mkdir(model_path) with tf.Session(config=config.cf) as sess: model = DecompAtt(config) saver = tf.train.Saver() sess.run(tf.initialize_all_variables()) for epoch in xrange(config.num_epochs): count = 0 for batch_x in iterator.next(config.batch_size, shuffle=True): batch_qids, batch_q, batch_aids, batch_ap, labels = zip(*batch_x) batch_q = np.asarray(batch_q) batch_ap = np.asarray(batch_ap) labels = np.asarray(labels).astype(np.int32) _, loss = sess.run([model.train_op, model.total_loss], feed_dict={model.q:batch_q, model.a:batch_ap, model.y:labels, model.keep_prob:config.keep_prob}) count += 1 if count % 10 == 0: print('[epoch {}, batch {}]Loss:{}'.format(epoch, count, loss)) saver.save(sess,'{}/my_model'.format(model_path), global_step=epoch) if eval_train_corpus is not None: train_res = evaluate(sess, model, eval_train_corpus, config) print('[train] ' + train_res) if val_corpus is not None: val_res = evaluate(sess, model, val_corpus, config) print('[eval] ' + val_res) def evaluate(sess, model, corpus, config): iterator = Iterator(corpus) count = 0 total_qids = [] total_aids = [] total_pred = [] total_labels = [] total_loss = 0. for batch_x in iterator.next(config.batch_size, shuffle=False): batch_qids, batch_q, batch_aids, batch_ap, labels = zip(*batch_x) batch_q = np.asarray(batch_q) batch_ap = np.asarray(batch_ap) y_hat, loss = sess.run([model.y_hat, model.total_loss], feed_dict={model.q:batch_q, model.a:batch_ap, model.y:labels, model.keep_prob:1.}) y_hat = np.argmax(y_hat, axis=-1) total_loss += loss count += 1 total_qids.append(batch_qids) total_aids.append(batch_aids) total_pred.append(y_hat) total_labels.append(labels) # print(batch_qids[0], [id2word[_] for _ in batch_q[0]], # batch_aids[0], [id2word[_] for _ in batch_ap[0]]) total_qids = np.concatenate(total_qids, axis=0) total_aids = np.concatenate(total_aids, axis=0) total_pred = np.concatenate(total_pred, axis=0) total_labels = np.concatenate(total_labels, axis=0) MAP, MRR = eval_map_mrr(total_qids, total_aids, total_pred, total_labels) # print('Eval loss:{}'.format(total_loss / count)) return 'MAP:{}, MRR:{}'.format(MAP, MRR) def test(corpus, config): with tf.Session(config=config.cf) as sess: model = DecompAtt(config) saver = tf.train.Saver() saver.restore(sess, tf.train.latest_checkpoint(model_path)) print('[test] ' + evaluate(sess, model, corpus, config)) def main(args): max_q_length = 25 max_a_length = 90 with open(os.path.join(processed_data_path, 'pointwise_corpus.pkl'), 'r') as fr: train_corpus, val_corpus, test_corpus = pkl.load(fr) embeddings = build_embedding(embedding_path, word2id) train_qids, train_q, train_aids, train_ap, train_labels = zip(*train_corpus) train_q = padding(train_q, max_q_length) train_ap = padding(train_ap, max_a_length) train_corpus = zip(train_qids, train_q, train_aids, train_ap, train_labels) val_qids, val_q, val_aids, val_ap, labels = zip(*val_corpus) val_q = padding(val_q, max_q_length) val_ap = padding(val_ap, max_a_length) val_corpus = zip(val_qids, val_q, val_aids, val_ap, labels) test_qids, test_q, test_aids, test_ap, labels = zip(*test_corpus) test_q = padding(test_q, max_q_length) test_ap = padding(test_ap, max_a_length) test_corpus = zip(test_qids, test_q, test_aids, test_ap, labels) config = DecompAttConfig(max(word2id.values()) + 1, embeddings=embeddings) config.max_q_length = max_q_length config.max_a_length = max_a_length if args.train: train(deepcopy(train_corpus), config, val_corpus, deepcopy(train_corpus)) elif args.test: test(test_corpus, config) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument("--train", help="whether to train", action='store_true') parser.add_argument("--test", help="whether to test", action='store_true') args = parser.parse_args() raw_data_path = '../data/WikiQA/raw' processed_data_path = '../data/WikiQA/processed' embedding_path = '../data/embedding/glove.6B.300d.txt' model_path = 'models' with open(os.path.join(processed_data_path, 'vocab.pkl'), 'r') as fr: word2id, id2word = pkl.load(fr) main(args)
en
0.353128
# -*- encoding:utf8 -*- # 输入问题(句子)长度 # 输入答案长度 # 循环数 # batch大小 # 词表大小 # 词向量大小 # RNN单元类型和大小与堆叠层数 # 隐层大小 # keep_prob=1-dropout # 学习率 # print(batch_qids[0], [id2word[_] for _ in batch_q[0]], # batch_aids[0], [id2word[_] for _ in batch_ap[0]]) # print('Eval loss:{}'.format(total_loss / count))
1.970018
2
bids/layout/layout.py
miykael/pybids
1
6625078
import os import re import json import warnings from io import open from .validation import BIDSValidator from .. import config as cf from grabbit import Layout, File from grabbit.external import six, inflect from grabbit.utils import listify from collections import defaultdict from functools import reduce, partial from itertools import chain from bids.config import get_option try: from os.path import commonpath except ImportError: def commonpath(paths): prefix = os.path.commonprefix(paths) if not os.path.isdir(prefix): prefix = os.path.dirname(prefix) return prefix __all__ = ['BIDSLayout'] def add_config_paths(**kwargs): """ Add to the pool of available configuration files for BIDSLayout. Args: kwargs: each kwarg should be a pair of config key name, and path Example: bids.layout.add_config_paths(my_config='/path/to/config') """ for k, path in kwargs.items(): if not os.path.exists(path): raise ValueError( 'Configuration file "{}" does not exist'.format(k)) if k in cf.get_option('config_paths'): raise ValueError('Configuration {!r} already exists'.format(k)) kwargs.update(**cf.get_option('config_paths')) cf.set_option('config_paths', kwargs) class BIDSFile(File): """ Represents a single BIDS file. """ def __init__(self, filename, layout): super(BIDSFile, self).__init__(filename) self.layout = layout def __getattr__(self, attr): # Ensures backwards compatibility with old File_ namedtuple, which is # deprecated as of 0.7. if attr in self.entities: warnings.warn("Accessing entities as attributes is deprecated as " "of 0.7. Please use the .entities dictionary instead" " (i.e., .entities['%s'] instead of .%s." % (attr, attr)) return self.entities[attr] raise AttributeError("%s object has no attribute named %r" % (self.__class__.__name__, attr)) def __repr__(self): source = '' if self.layout.sources: source = ", root='{}'".format(os.path.basename(self.layout.root)) return "<BIDSFile filename='{}'{}>".format( os.path.relpath(self.path, start=self.layout.root), source) @property def image(self): """ Return the associated image file (if it exists) as a NiBabel object. """ try: import nibabel as nb return nb.load(self.path) except Exception: return None @property def metadata(self): """ Return all associated metadata. """ return self.layout.get_metadata(self.path) class BIDSLayout(Layout): """ Layout class representing an entire BIDS dataset. Args: root (str): The root directory of the BIDS dataset. validate (bool): If True, all files are checked for BIDS compliance when first indexed, and non-compliant files are ignored. This provides a convenient way to restrict file indexing to only those files defined in the "core" BIDS spec, as setting validate=True will lead files in supplementary folders like derivatives/, code/, etc. to be ignored. index_associated (bool): Argument passed onto the BIDSValidator; ignored if validate = False. include (str, list): String or list of strings specifying which of the directories that are by default excluded from indexing should be included. The default exclusion list is ['code', 'stimuli', 'sourcedata', 'models']. absolute_paths (bool): If True, queries always return absolute paths. If False, queries return relative paths, unless the root argument was left empty (in which case the root defaults to the file system root). derivatives (bool, str, list): Specificies whether and/or which derivatives to to index. If True, all pipelines found in the derivatives/ subdirectory will be indexed. If a str or list, gives the paths to one or more derivatives directories to index. If False or None, the derivatives/ directory is ignored during indexing, and derivatives will have to be added manually via add_derivatives(). config (str, list): Optional name(s) of configuration file(s) to use. By default (None), uses 'bids'. sources (BIDLayout, list): Optional BIDSLayout(s) from which the current BIDSLayout is derived. kwargs: Optional keyword arguments to pass onto the Layout initializer in grabbit. """ def __init__(self, root, validate=True, index_associated=True, include=None, absolute_paths=True, derivatives=False, config=None, sources=None, **kwargs): self.validator = BIDSValidator(index_associated=index_associated) self.validate = validate self.metadata_index = MetadataIndex(self) self.derivatives = {} self.sources = listify(sources) # Validate arguments if not isinstance(root, six.string_types): raise ValueError("root argument must be a string specifying the" " directory containing the BIDS dataset.") if not os.path.exists(root): raise ValueError("BIDS root does not exist: %s" % root) self.root = root target = os.path.join(self.root, 'dataset_description.json') if not os.path.exists(target): if validate is True: raise ValueError( "'dataset_description.json' is missing from project root." " Every valid BIDS dataset must have this file.") else: self.description = None else: with open(target, 'r', encoding='utf-8') as desc_fd: self.description = json.load(desc_fd) if validate is True: for k in ['Name', 'BIDSVersion']: if k not in self.description: raise ValueError("Mandatory '%s' field missing from " "dataset_description.json." % k) # Determine which subdirectories to exclude from indexing excludes = {"code", "stimuli", "sourcedata", "models", "derivatives"} if include is not None: include = listify(include) if "derivatives" in include: raise ValueError("Do not pass 'derivatives' in the include " "list. To index derivatives, either set " "derivatives=True, or use add_derivatives().") excludes -= set([d.strip(os.path.sep) for d in include]) self._exclude_dirs = list(excludes) # Set up path and config for grabbit if config is None: config = 'bids' config_paths = get_option('config_paths') path = (root, [config_paths[c] for c in listify(config)]) # Initialize grabbit Layout super(BIDSLayout, self).__init__(path, root=self.root, dynamic_getters=True, absolute_paths=absolute_paths, **kwargs) # Add derivatives if any are found self.derivatives = {} if derivatives: if derivatives is True: derivatives = os.path.join(root, 'derivatives') self.add_derivatives( derivatives, validate=validate, index_associated=index_associated, include=include, absolute_paths=absolute_paths, derivatives=None, config=None, sources=self, **kwargs) def add_derivatives(self, path, **kwargs): ''' Add BIDS-Derivatives datasets to tracking. Args: path (str, list): One or more paths to BIDS-Derivatives datasets. Each path can point to either a derivatives/ directory containing one more more pipeline directories, or to a single pipeline directory (e.g., derivatives/fmriprep). kwargs (dict): Optional keyword arguments to pass on to BIDSLayout() when initializing each of the derivative datasets. ''' paths = listify(path) deriv_dirs = [] # Collect all paths that contain a dataset_description.json def check_for_description(dir): dd = os.path.join(dir, 'dataset_description.json') return os.path.exists(dd) for p in paths: p = os.path.abspath(p) if os.path.exists(p): if check_for_description(p): deriv_dirs.append(p) else: subdirs = [d for d in os.listdir(p) if os.path.isdir(os.path.join(p, d))] for sd in subdirs: sd = os.path.join(p, sd) if check_for_description(sd): deriv_dirs.append(sd) local_entities = set(ent.name for ent in self.entities.values()) for deriv in deriv_dirs: dd = os.path.join(deriv, 'dataset_description.json') with open(dd, 'r', encoding='utf-8') as ddfd: description = json.load(ddfd) pipeline_name = description.get( 'PipelineDescription', {}).get('Name', None) if pipeline_name is None: raise ValueError("Every valid BIDS-derivatives dataset must " "have a PipelineDescription.Name field set " "inside dataset_description.json.") if pipeline_name in self.derivatives: raise ValueError("Pipeline name '%s' has already been added " "to this BIDSLayout. Every added pipeline " "must have a unique name!") # Default config and sources values kwargs['config'] = kwargs.get('config') or ['bids', 'derivatives'] kwargs['sources'] = kwargs.get('sources') or self self.derivatives[pipeline_name] = BIDSLayout(deriv, **kwargs) # Propagate derivative entities into top-level dynamic getters deriv_entities = set( ent.name for ent in self.derivatives[pipeline_name].entities.values()) for deriv_ent in deriv_entities - local_entities: local_entities.add(deriv_ent) getter = 'get_' + inflect.engine().plural(deriv_ent) if not hasattr(self, getter): func = partial( self.get, target=deriv_ent, return_type='id') setattr(self, getter, func) def to_df(self, **kwargs): """ Return information for all Files tracked in the Layout as a pandas DataFrame. Args: kwargs: Optional keyword arguments passed on to get(). This allows one to easily select only a subset of files for export. Returns: A pandas DataFrame, where each row is a file, and each column is a tracked entity. NaNs are injected whenever a file has no value for a given attribute. """ return self.as_data_frame(**kwargs) def __repr__(self): n_sessions = len([session for isub in self.get_subjects() for session in self.get_sessions(subject=isub)]) n_runs = len([run for isub in self.get_subjects() for run in self.get_runs(subject=isub)]) n_subjects = len(self.get_subjects()) root = self.root[-30:] s = ("BIDS Layout: ...{} | Subjects: {} | Sessions: {} | " "Runs: {}".format(root, n_subjects, n_sessions, n_runs)) return s def _validate_dir(self, d): # Callback from grabbit. Exclude special directories like derivatives/ # and code/ from indexing unless they were explicitly included at # initialization. no_root = os.path.relpath(d, self.root).split(os.path.sep)[0] if no_root in self._exclude_dirs: check_paths = set(self._paths_to_index) - {self.root} if not any([d.startswith(p) for p in check_paths]): return False return True def _validate_file(self, f): # Callback from grabbit. Files are excluded from indexing if validation # is enabled and fails (i.e., file is not a valid BIDS file). if not self.validate: return True # For derivatives, we need to cheat a bit and construct a fake # derivatives path--prepend 'derivatives' and the pipeline name to_check = os.path.relpath(f, self.root) if 'derivatives' in self.domains: to_check = os.path.join( 'derivatives', self.description['PipelineDescription']['Name'], to_check) sep = os.path.sep if to_check[:len(sep)] != sep: to_check = sep + to_check return self.validator.is_bids(to_check) def _get_nearest_helper(self, path, extension, suffix=None, **kwargs): """ Helper function for grabbit get_nearest """ path = os.path.abspath(path) if not suffix: f = self.get_file(path) if 'suffix' not in f.entities: raise ValueError( "File '%s' does not have a valid suffix, most " "likely because it is not a valid BIDS file." % path ) suffix = f.entities['suffix'] tmp = self.get_nearest( path, extensions=extension, all_=True, suffix=suffix, ignore_strict_entities=['suffix'], **kwargs) if len(tmp): return tmp else: return None def get(self, return_type='object', target=None, extensions=None, derivatives=True, regex_search=None, defined_fields=None, domains=None, **kwargs): """ Retrieve files and/or metadata from the current Layout. Args: return_type (str): Type of result to return. Valid values: 'object' (default): return a list of matching BIDSFile objects. 'file': return a list of matching filenames. 'dir': return a list of directories. 'id': return a list of unique IDs. Must be used together with a valid target. target (str): Optional name of the target entity to get results for (only used if return_type is 'dir' or 'id'). extensions (str, list): One or more file extensions to filter on. Files with any other extensions will be excluded. derivatives (bool, str, list): Whether/how to search associated BIDS-Derivatives datasets. If True (default), all available derivatives are searched. If a str or list, must be the name(s) of the derivatives to search (as defined in the PipelineDescription.Name field in dataset_description.json). regex_search (bool or None): Whether to require exact matching (False) or regex search (True) when comparing the query string to each entity. If None (default), uses the value found in self. defined_fields (list): Optional list of names of metadata fields that must be defined in JSON sidecars in order to consider the file a match, but which don't need to match any particular value. domains (str, list): Domain(s) to search in. Valid values are 'bids' and 'derivatives'. kwargs (dict): Any optional key/values to filter the entities on. Keys are entity names, values are regexes to filter on. For example, passing filter={ 'subject': 'sub-[12]'} would return only files that match the first two subjects. Returns: A list of BIDSFile (default) or other objects (see return_type for details). """ # Warn users still expecting 0.6 behavior if 'type' in kwargs: raise ValueError("As of pybids 0.7.0, the 'type' argument has been" " replaced with 'suffix'.") if derivatives is True: derivatives = list(self.derivatives.keys()) elif derivatives: derivatives = listify(derivatives) # Separate entity kwargs from metadata kwargs ent_kwargs, md_kwargs = {}, {} all_ents = self.get_domain_entities() if derivatives: for deriv in derivatives: deriv_ents = self.derivatives[deriv].get_domain_entities() all_ents.update(deriv_ents) for k, v in kwargs.items(): if k in all_ents: ent_kwargs[k] = v else: md_kwargs[k] = v # Provide some suggestions if target is specified and invalid. if target is not None and target not in all_ents: import difflib potential = list(all_ents.keys()) suggestions = difflib.get_close_matches(target, potential) if suggestions: message = "Did you mean one of: {}?".format(suggestions) else: message = "Valid targets are: {}".format(potential) raise ValueError(("Unknown target '{}'. " + message) .format(target)) all_results = [] # Get entity-based search results using the superclass's get() result = [] result = super( BIDSLayout, self).get(return_type, target=target, extensions=extensions, domains=None, regex_search=regex_search, **ent_kwargs) # Search the metadata if needed if return_type not in {'dir', 'id'}: if md_kwargs: if return_type.startswith('obj'): result = [f.path for f in result] result = self.metadata_index.search(result, defined_fields, **md_kwargs) if return_type.startswith('obj'): result = [self.files[f] for f in result] all_results.append(result) # Add results from derivatives if derivatives: for deriv in derivatives: deriv = self.derivatives[deriv] deriv_res = deriv.get(return_type, target, extensions, None, regex_search, **ent_kwargs) all_results.append(deriv_res) # Flatten results result = list(chain(*all_results)) if return_type in ['dir', 'id']: result = list(set(result)) return result def get_metadata(self, path, include_entities=False, **kwargs): """Return metadata found in JSON sidecars for the specified file. Args: path (str): Path to the file to get metadata for. include_entities (bool): If True, all available entities extracted from the filename (rather than JSON sidecars) are included in the returned metadata dictionary. kwargs (dict): Optional keyword arguments to pass onto get_nearest(). Returns: A dictionary of key/value pairs extracted from all of the target file's associated JSON sidecars. Notes: A dictionary containing metadata extracted from all matching .json files is returned. In cases where the same key is found in multiple files, the values in files closer to the input filename will take precedence, per the inheritance rules in the BIDS specification. """ # For querying efficiency, store metadata in the MetadataIndex cache self.metadata_index.index_file(path) if include_entities: f = self.get_file(os.path.abspath(path)) entities = f.entities results = entities else: results = {} results.update(self.metadata_index.file_index[path]) return results def get_bvec(self, path, **kwargs): """Get bvec file for passed path.""" tmp = self._get_nearest_helper(path, 'bvec', suffix='dwi', **kwargs)[0] if isinstance(tmp, list): return tmp[0] else: return tmp def get_bval(self, path, **kwargs): """Get bval file for passed path.""" tmp = self._get_nearest_helper(path, 'bval', suffix='dwi', **kwargs)[0] if isinstance(tmp, list): return tmp[0] else: return tmp def get_fieldmap(self, path, return_list=False): """Get fieldmap(s) for specified path.""" fieldmaps = self._get_fieldmaps(path) if return_list: return fieldmaps else: if len(fieldmaps) == 1: return fieldmaps[0] elif len(fieldmaps) > 1: raise ValueError("More than one fieldmap found, but the " "'return_list' argument was set to False. " "Either ensure that there is only one " "fieldmap for this image, or set the " "'return_list' argument to True and handle " "the result as a list.") else: # len(fieldmaps) == 0 return None def _get_fieldmaps(self, path): sub = os.path.split(path)[1].split("_")[0].split("sub-")[1] fieldmap_set = [] suffix = '(phase1|phasediff|epi|fieldmap)' files = self.get(subject=sub, suffix=suffix, extensions=['nii.gz', 'nii']) for file in files: metadata = self.get_metadata(file.path) if metadata and "IntendedFor" in metadata.keys(): intended_for = listify(metadata["IntendedFor"]) if any([path.endswith(_suff) for _suff in intended_for]): cur_fieldmap = {} if file.suffix == "phasediff": cur_fieldmap = {"phasediff": file.path, "magnitude1": file.path.replace( "phasediff", "magnitude1"), "suffix": "phasediff"} magnitude2 = file.path.replace( "phasediff", "magnitude2") if os.path.isfile(magnitude2): cur_fieldmap['magnitude2'] = magnitude2 elif file.suffix == "phase1": cur_fieldmap["phase1"] = file.path cur_fieldmap["magnitude1"] = \ file.path.replace("phase1", "magnitude1") cur_fieldmap["phase2"] = \ file.path.replace("phase1", "phase2") cur_fieldmap["magnitude2"] = \ file.path.replace("phase1", "magnitude2") cur_fieldmap["suffix"] = "phase" elif file.suffix == "epi": cur_fieldmap["epi"] = file.path cur_fieldmap["suffix"] = "epi" elif file.suffix == "fieldmap": cur_fieldmap["fieldmap"] = file.path cur_fieldmap["magnitude"] = \ file.path.replace("fieldmap", "magnitude") cur_fieldmap["suffix"] = "fieldmap" fieldmap_set.append(cur_fieldmap) return fieldmap_set def get_tr(self, derivatives=False, **selectors): """ Returns the scanning repetition time (TR) for one or more runs. Args: derivatives (bool): If True, also checks derivatives images. selectors: Optional keywords used to constrain the selected runs. Can be any arguments valid for a .get call (e.g., BIDS entities or JSON sidecar keys). Returns: A single float. Notes: Raises an exception if more than one unique TR is found. """ # Constrain search to functional images selectors['suffix'] = 'bold' selectors['datatype'] = 'func' images = self.get(extensions=['.nii', '.nii.gz'], derivatives=derivatives, **selectors) if not images: raise ValueError("No functional images that match criteria found.") all_trs = set() for img in images: md = self.get_metadata(img.path, suffix='bold', full_search=True) all_trs.add(round(float(md['RepetitionTime']), 5)) if len(all_trs) > 1: raise ValueError("Unique TR cannot be found given selectors {!r}" .format(selectors)) return all_trs.pop() def get_collections(self, level, types=None, variables=None, merge=False, sampling_rate=None, skip_empty=False, **kwargs): """Return one or more variable Collections in the BIDS project. Args: level (str): The level of analysis to return variables for. Must be one of 'run', 'session', 'subject', or 'dataset'. types (str, list): Types of variables to retrieve. All valid values reflect the filename stipulated in the BIDS spec for each kind of variable. Valid values include: 'events', 'physio', 'stim', 'scans', 'participants', 'sessions', and 'regressors'. variables (list): Optional list of variables names to return. If None, all available variables are returned. merge (bool): If True, variables are merged across all observations of the current level. E.g., if level='subject', variables from all subjects will be merged into a single collection. If False, each observation is handled separately, and the result is returned as a list. sampling_rate (int, str): If level='run', the sampling rate to pass onto the returned BIDSRunVariableCollection. skip_empty (bool): Whether or not to skip empty Variables (i.e., where there are no rows/records in a file after applying any filtering operations like dropping NaNs). kwargs: Optional additional arguments to pass onto load_variables. """ from bids.variables import load_variables index = load_variables(self, types=types, levels=level, skip_empty=skip_empty, **kwargs) return index.get_collections(level, variables, merge, sampling_rate=sampling_rate) def _make_file_object(self, root, f): # Override grabbit's File with a BIDSFile. return BIDSFile(os.path.join(root, f), self) def get_file(self, filename, derivatives=True): ''' Returns the BIDSFile object with the specified path. Args: filename (str): The path of the file to retrieve. derivatives (bool: If True, checks all associated derivative datasets as well. Returns: A BIDSFile. ''' layouts = [self] if derivatives: layouts += self.derivatives.values() for ly in layouts: if filename in ly.files: return ly.files[filename] return None class MetadataIndex(object): """A simple dict-based index for key/value pairs in JSON metadata. Args: layout (BIDSLayout): The BIDSLayout instance to index. """ def __init__(self, layout): self.layout = layout self.key_index = {} self.file_index = defaultdict(dict) def index_file(self, f, overwrite=False): """Index metadata for the specified file. Args: f (BIDSFile, str): A BIDSFile or path to an indexed file. overwrite (bool): If True, forces reindexing of the file even if an entry already exists. """ if isinstance(f, six.string_types): f = self.layout.get_file(f) if f.path in self.file_index and not overwrite: return if 'suffix' not in f.entities: # Skip files without suffixes return md = self._get_metadata(f.path) for md_key, md_val in md.items(): if md_key not in self.key_index: self.key_index[md_key] = {} self.key_index[md_key][f.path] = md_val self.file_index[f.path][md_key] = md_val def _get_metadata(self, path, **kwargs): potential_jsons = self.layout._get_nearest_helper(path, '.json', **kwargs) if potential_jsons is None: return {} results = {} for json_file_path in reversed(potential_jsons): if os.path.exists(json_file_path): with open(json_file_path, 'r', encoding='utf-8') as fd: param_dict = json.load(fd) results.update(param_dict) return results def search(self, files=None, defined_fields=None, **kwargs): """Search files in the layout by metadata fields. Args: files (list): Optional list of names of files to search. If None, all files in the layout are scanned. defined_fields (list): Optional list of names of fields that must be defined in the JSON sidecar in order to consider the file a match, but which don't need to match any particular value. kwargs: Optional keyword arguments defining search constraints; keys are names of metadata fields, and values are the values to match those fields against (e.g., SliceTiming=0.017) would return all files that have a SliceTiming value of 0.071 in metadata. Returns: A list of filenames that match all constraints. """ if defined_fields is None: defined_fields = [] all_keys = set(defined_fields) | set(kwargs.keys()) if not all_keys: raise ValueError("At least one field to search on must be passed.") # If no list of files is passed, use all files in layout if files is None: files = set(self.layout.files.keys()) # Index metadata for any previously unseen files for f in files: self.index_file(f) # Get file intersection of all kwargs keys--this is fast filesets = [set(self.key_index.get(k, [])) for k in all_keys] matches = reduce(lambda x, y: x & y, filesets) if files is not None: matches &= set(files) if not matches: return [] def check_matches(f, key, val): if isinstance(val, six.string_types) and '*' in val: val = ('^%s$' % val).replace('*', ".*") return re.search(str(self.file_index[f][key]), val) is not None else: return val == self.file_index[f][key] # Serially check matches against each pattern, with early termination for k, val in kwargs.items(): matches = list(filter(lambda x: check_matches(x, k, val), matches)) if not matches: return [] return matches
import os import re import json import warnings from io import open from .validation import BIDSValidator from .. import config as cf from grabbit import Layout, File from grabbit.external import six, inflect from grabbit.utils import listify from collections import defaultdict from functools import reduce, partial from itertools import chain from bids.config import get_option try: from os.path import commonpath except ImportError: def commonpath(paths): prefix = os.path.commonprefix(paths) if not os.path.isdir(prefix): prefix = os.path.dirname(prefix) return prefix __all__ = ['BIDSLayout'] def add_config_paths(**kwargs): """ Add to the pool of available configuration files for BIDSLayout. Args: kwargs: each kwarg should be a pair of config key name, and path Example: bids.layout.add_config_paths(my_config='/path/to/config') """ for k, path in kwargs.items(): if not os.path.exists(path): raise ValueError( 'Configuration file "{}" does not exist'.format(k)) if k in cf.get_option('config_paths'): raise ValueError('Configuration {!r} already exists'.format(k)) kwargs.update(**cf.get_option('config_paths')) cf.set_option('config_paths', kwargs) class BIDSFile(File): """ Represents a single BIDS file. """ def __init__(self, filename, layout): super(BIDSFile, self).__init__(filename) self.layout = layout def __getattr__(self, attr): # Ensures backwards compatibility with old File_ namedtuple, which is # deprecated as of 0.7. if attr in self.entities: warnings.warn("Accessing entities as attributes is deprecated as " "of 0.7. Please use the .entities dictionary instead" " (i.e., .entities['%s'] instead of .%s." % (attr, attr)) return self.entities[attr] raise AttributeError("%s object has no attribute named %r" % (self.__class__.__name__, attr)) def __repr__(self): source = '' if self.layout.sources: source = ", root='{}'".format(os.path.basename(self.layout.root)) return "<BIDSFile filename='{}'{}>".format( os.path.relpath(self.path, start=self.layout.root), source) @property def image(self): """ Return the associated image file (if it exists) as a NiBabel object. """ try: import nibabel as nb return nb.load(self.path) except Exception: return None @property def metadata(self): """ Return all associated metadata. """ return self.layout.get_metadata(self.path) class BIDSLayout(Layout): """ Layout class representing an entire BIDS dataset. Args: root (str): The root directory of the BIDS dataset. validate (bool): If True, all files are checked for BIDS compliance when first indexed, and non-compliant files are ignored. This provides a convenient way to restrict file indexing to only those files defined in the "core" BIDS spec, as setting validate=True will lead files in supplementary folders like derivatives/, code/, etc. to be ignored. index_associated (bool): Argument passed onto the BIDSValidator; ignored if validate = False. include (str, list): String or list of strings specifying which of the directories that are by default excluded from indexing should be included. The default exclusion list is ['code', 'stimuli', 'sourcedata', 'models']. absolute_paths (bool): If True, queries always return absolute paths. If False, queries return relative paths, unless the root argument was left empty (in which case the root defaults to the file system root). derivatives (bool, str, list): Specificies whether and/or which derivatives to to index. If True, all pipelines found in the derivatives/ subdirectory will be indexed. If a str or list, gives the paths to one or more derivatives directories to index. If False or None, the derivatives/ directory is ignored during indexing, and derivatives will have to be added manually via add_derivatives(). config (str, list): Optional name(s) of configuration file(s) to use. By default (None), uses 'bids'. sources (BIDLayout, list): Optional BIDSLayout(s) from which the current BIDSLayout is derived. kwargs: Optional keyword arguments to pass onto the Layout initializer in grabbit. """ def __init__(self, root, validate=True, index_associated=True, include=None, absolute_paths=True, derivatives=False, config=None, sources=None, **kwargs): self.validator = BIDSValidator(index_associated=index_associated) self.validate = validate self.metadata_index = MetadataIndex(self) self.derivatives = {} self.sources = listify(sources) # Validate arguments if not isinstance(root, six.string_types): raise ValueError("root argument must be a string specifying the" " directory containing the BIDS dataset.") if not os.path.exists(root): raise ValueError("BIDS root does not exist: %s" % root) self.root = root target = os.path.join(self.root, 'dataset_description.json') if not os.path.exists(target): if validate is True: raise ValueError( "'dataset_description.json' is missing from project root." " Every valid BIDS dataset must have this file.") else: self.description = None else: with open(target, 'r', encoding='utf-8') as desc_fd: self.description = json.load(desc_fd) if validate is True: for k in ['Name', 'BIDSVersion']: if k not in self.description: raise ValueError("Mandatory '%s' field missing from " "dataset_description.json." % k) # Determine which subdirectories to exclude from indexing excludes = {"code", "stimuli", "sourcedata", "models", "derivatives"} if include is not None: include = listify(include) if "derivatives" in include: raise ValueError("Do not pass 'derivatives' in the include " "list. To index derivatives, either set " "derivatives=True, or use add_derivatives().") excludes -= set([d.strip(os.path.sep) for d in include]) self._exclude_dirs = list(excludes) # Set up path and config for grabbit if config is None: config = 'bids' config_paths = get_option('config_paths') path = (root, [config_paths[c] for c in listify(config)]) # Initialize grabbit Layout super(BIDSLayout, self).__init__(path, root=self.root, dynamic_getters=True, absolute_paths=absolute_paths, **kwargs) # Add derivatives if any are found self.derivatives = {} if derivatives: if derivatives is True: derivatives = os.path.join(root, 'derivatives') self.add_derivatives( derivatives, validate=validate, index_associated=index_associated, include=include, absolute_paths=absolute_paths, derivatives=None, config=None, sources=self, **kwargs) def add_derivatives(self, path, **kwargs): ''' Add BIDS-Derivatives datasets to tracking. Args: path (str, list): One or more paths to BIDS-Derivatives datasets. Each path can point to either a derivatives/ directory containing one more more pipeline directories, or to a single pipeline directory (e.g., derivatives/fmriprep). kwargs (dict): Optional keyword arguments to pass on to BIDSLayout() when initializing each of the derivative datasets. ''' paths = listify(path) deriv_dirs = [] # Collect all paths that contain a dataset_description.json def check_for_description(dir): dd = os.path.join(dir, 'dataset_description.json') return os.path.exists(dd) for p in paths: p = os.path.abspath(p) if os.path.exists(p): if check_for_description(p): deriv_dirs.append(p) else: subdirs = [d for d in os.listdir(p) if os.path.isdir(os.path.join(p, d))] for sd in subdirs: sd = os.path.join(p, sd) if check_for_description(sd): deriv_dirs.append(sd) local_entities = set(ent.name for ent in self.entities.values()) for deriv in deriv_dirs: dd = os.path.join(deriv, 'dataset_description.json') with open(dd, 'r', encoding='utf-8') as ddfd: description = json.load(ddfd) pipeline_name = description.get( 'PipelineDescription', {}).get('Name', None) if pipeline_name is None: raise ValueError("Every valid BIDS-derivatives dataset must " "have a PipelineDescription.Name field set " "inside dataset_description.json.") if pipeline_name in self.derivatives: raise ValueError("Pipeline name '%s' has already been added " "to this BIDSLayout. Every added pipeline " "must have a unique name!") # Default config and sources values kwargs['config'] = kwargs.get('config') or ['bids', 'derivatives'] kwargs['sources'] = kwargs.get('sources') or self self.derivatives[pipeline_name] = BIDSLayout(deriv, **kwargs) # Propagate derivative entities into top-level dynamic getters deriv_entities = set( ent.name for ent in self.derivatives[pipeline_name].entities.values()) for deriv_ent in deriv_entities - local_entities: local_entities.add(deriv_ent) getter = 'get_' + inflect.engine().plural(deriv_ent) if not hasattr(self, getter): func = partial( self.get, target=deriv_ent, return_type='id') setattr(self, getter, func) def to_df(self, **kwargs): """ Return information for all Files tracked in the Layout as a pandas DataFrame. Args: kwargs: Optional keyword arguments passed on to get(). This allows one to easily select only a subset of files for export. Returns: A pandas DataFrame, where each row is a file, and each column is a tracked entity. NaNs are injected whenever a file has no value for a given attribute. """ return self.as_data_frame(**kwargs) def __repr__(self): n_sessions = len([session for isub in self.get_subjects() for session in self.get_sessions(subject=isub)]) n_runs = len([run for isub in self.get_subjects() for run in self.get_runs(subject=isub)]) n_subjects = len(self.get_subjects()) root = self.root[-30:] s = ("BIDS Layout: ...{} | Subjects: {} | Sessions: {} | " "Runs: {}".format(root, n_subjects, n_sessions, n_runs)) return s def _validate_dir(self, d): # Callback from grabbit. Exclude special directories like derivatives/ # and code/ from indexing unless they were explicitly included at # initialization. no_root = os.path.relpath(d, self.root).split(os.path.sep)[0] if no_root in self._exclude_dirs: check_paths = set(self._paths_to_index) - {self.root} if not any([d.startswith(p) for p in check_paths]): return False return True def _validate_file(self, f): # Callback from grabbit. Files are excluded from indexing if validation # is enabled and fails (i.e., file is not a valid BIDS file). if not self.validate: return True # For derivatives, we need to cheat a bit and construct a fake # derivatives path--prepend 'derivatives' and the pipeline name to_check = os.path.relpath(f, self.root) if 'derivatives' in self.domains: to_check = os.path.join( 'derivatives', self.description['PipelineDescription']['Name'], to_check) sep = os.path.sep if to_check[:len(sep)] != sep: to_check = sep + to_check return self.validator.is_bids(to_check) def _get_nearest_helper(self, path, extension, suffix=None, **kwargs): """ Helper function for grabbit get_nearest """ path = os.path.abspath(path) if not suffix: f = self.get_file(path) if 'suffix' not in f.entities: raise ValueError( "File '%s' does not have a valid suffix, most " "likely because it is not a valid BIDS file." % path ) suffix = f.entities['suffix'] tmp = self.get_nearest( path, extensions=extension, all_=True, suffix=suffix, ignore_strict_entities=['suffix'], **kwargs) if len(tmp): return tmp else: return None def get(self, return_type='object', target=None, extensions=None, derivatives=True, regex_search=None, defined_fields=None, domains=None, **kwargs): """ Retrieve files and/or metadata from the current Layout. Args: return_type (str): Type of result to return. Valid values: 'object' (default): return a list of matching BIDSFile objects. 'file': return a list of matching filenames. 'dir': return a list of directories. 'id': return a list of unique IDs. Must be used together with a valid target. target (str): Optional name of the target entity to get results for (only used if return_type is 'dir' or 'id'). extensions (str, list): One or more file extensions to filter on. Files with any other extensions will be excluded. derivatives (bool, str, list): Whether/how to search associated BIDS-Derivatives datasets. If True (default), all available derivatives are searched. If a str or list, must be the name(s) of the derivatives to search (as defined in the PipelineDescription.Name field in dataset_description.json). regex_search (bool or None): Whether to require exact matching (False) or regex search (True) when comparing the query string to each entity. If None (default), uses the value found in self. defined_fields (list): Optional list of names of metadata fields that must be defined in JSON sidecars in order to consider the file a match, but which don't need to match any particular value. domains (str, list): Domain(s) to search in. Valid values are 'bids' and 'derivatives'. kwargs (dict): Any optional key/values to filter the entities on. Keys are entity names, values are regexes to filter on. For example, passing filter={ 'subject': 'sub-[12]'} would return only files that match the first two subjects. Returns: A list of BIDSFile (default) or other objects (see return_type for details). """ # Warn users still expecting 0.6 behavior if 'type' in kwargs: raise ValueError("As of pybids 0.7.0, the 'type' argument has been" " replaced with 'suffix'.") if derivatives is True: derivatives = list(self.derivatives.keys()) elif derivatives: derivatives = listify(derivatives) # Separate entity kwargs from metadata kwargs ent_kwargs, md_kwargs = {}, {} all_ents = self.get_domain_entities() if derivatives: for deriv in derivatives: deriv_ents = self.derivatives[deriv].get_domain_entities() all_ents.update(deriv_ents) for k, v in kwargs.items(): if k in all_ents: ent_kwargs[k] = v else: md_kwargs[k] = v # Provide some suggestions if target is specified and invalid. if target is not None and target not in all_ents: import difflib potential = list(all_ents.keys()) suggestions = difflib.get_close_matches(target, potential) if suggestions: message = "Did you mean one of: {}?".format(suggestions) else: message = "Valid targets are: {}".format(potential) raise ValueError(("Unknown target '{}'. " + message) .format(target)) all_results = [] # Get entity-based search results using the superclass's get() result = [] result = super( BIDSLayout, self).get(return_type, target=target, extensions=extensions, domains=None, regex_search=regex_search, **ent_kwargs) # Search the metadata if needed if return_type not in {'dir', 'id'}: if md_kwargs: if return_type.startswith('obj'): result = [f.path for f in result] result = self.metadata_index.search(result, defined_fields, **md_kwargs) if return_type.startswith('obj'): result = [self.files[f] for f in result] all_results.append(result) # Add results from derivatives if derivatives: for deriv in derivatives: deriv = self.derivatives[deriv] deriv_res = deriv.get(return_type, target, extensions, None, regex_search, **ent_kwargs) all_results.append(deriv_res) # Flatten results result = list(chain(*all_results)) if return_type in ['dir', 'id']: result = list(set(result)) return result def get_metadata(self, path, include_entities=False, **kwargs): """Return metadata found in JSON sidecars for the specified file. Args: path (str): Path to the file to get metadata for. include_entities (bool): If True, all available entities extracted from the filename (rather than JSON sidecars) are included in the returned metadata dictionary. kwargs (dict): Optional keyword arguments to pass onto get_nearest(). Returns: A dictionary of key/value pairs extracted from all of the target file's associated JSON sidecars. Notes: A dictionary containing metadata extracted from all matching .json files is returned. In cases where the same key is found in multiple files, the values in files closer to the input filename will take precedence, per the inheritance rules in the BIDS specification. """ # For querying efficiency, store metadata in the MetadataIndex cache self.metadata_index.index_file(path) if include_entities: f = self.get_file(os.path.abspath(path)) entities = f.entities results = entities else: results = {} results.update(self.metadata_index.file_index[path]) return results def get_bvec(self, path, **kwargs): """Get bvec file for passed path.""" tmp = self._get_nearest_helper(path, 'bvec', suffix='dwi', **kwargs)[0] if isinstance(tmp, list): return tmp[0] else: return tmp def get_bval(self, path, **kwargs): """Get bval file for passed path.""" tmp = self._get_nearest_helper(path, 'bval', suffix='dwi', **kwargs)[0] if isinstance(tmp, list): return tmp[0] else: return tmp def get_fieldmap(self, path, return_list=False): """Get fieldmap(s) for specified path.""" fieldmaps = self._get_fieldmaps(path) if return_list: return fieldmaps else: if len(fieldmaps) == 1: return fieldmaps[0] elif len(fieldmaps) > 1: raise ValueError("More than one fieldmap found, but the " "'return_list' argument was set to False. " "Either ensure that there is only one " "fieldmap for this image, or set the " "'return_list' argument to True and handle " "the result as a list.") else: # len(fieldmaps) == 0 return None def _get_fieldmaps(self, path): sub = os.path.split(path)[1].split("_")[0].split("sub-")[1] fieldmap_set = [] suffix = '(phase1|phasediff|epi|fieldmap)' files = self.get(subject=sub, suffix=suffix, extensions=['nii.gz', 'nii']) for file in files: metadata = self.get_metadata(file.path) if metadata and "IntendedFor" in metadata.keys(): intended_for = listify(metadata["IntendedFor"]) if any([path.endswith(_suff) for _suff in intended_for]): cur_fieldmap = {} if file.suffix == "phasediff": cur_fieldmap = {"phasediff": file.path, "magnitude1": file.path.replace( "phasediff", "magnitude1"), "suffix": "phasediff"} magnitude2 = file.path.replace( "phasediff", "magnitude2") if os.path.isfile(magnitude2): cur_fieldmap['magnitude2'] = magnitude2 elif file.suffix == "phase1": cur_fieldmap["phase1"] = file.path cur_fieldmap["magnitude1"] = \ file.path.replace("phase1", "magnitude1") cur_fieldmap["phase2"] = \ file.path.replace("phase1", "phase2") cur_fieldmap["magnitude2"] = \ file.path.replace("phase1", "magnitude2") cur_fieldmap["suffix"] = "phase" elif file.suffix == "epi": cur_fieldmap["epi"] = file.path cur_fieldmap["suffix"] = "epi" elif file.suffix == "fieldmap": cur_fieldmap["fieldmap"] = file.path cur_fieldmap["magnitude"] = \ file.path.replace("fieldmap", "magnitude") cur_fieldmap["suffix"] = "fieldmap" fieldmap_set.append(cur_fieldmap) return fieldmap_set def get_tr(self, derivatives=False, **selectors): """ Returns the scanning repetition time (TR) for one or more runs. Args: derivatives (bool): If True, also checks derivatives images. selectors: Optional keywords used to constrain the selected runs. Can be any arguments valid for a .get call (e.g., BIDS entities or JSON sidecar keys). Returns: A single float. Notes: Raises an exception if more than one unique TR is found. """ # Constrain search to functional images selectors['suffix'] = 'bold' selectors['datatype'] = 'func' images = self.get(extensions=['.nii', '.nii.gz'], derivatives=derivatives, **selectors) if not images: raise ValueError("No functional images that match criteria found.") all_trs = set() for img in images: md = self.get_metadata(img.path, suffix='bold', full_search=True) all_trs.add(round(float(md['RepetitionTime']), 5)) if len(all_trs) > 1: raise ValueError("Unique TR cannot be found given selectors {!r}" .format(selectors)) return all_trs.pop() def get_collections(self, level, types=None, variables=None, merge=False, sampling_rate=None, skip_empty=False, **kwargs): """Return one or more variable Collections in the BIDS project. Args: level (str): The level of analysis to return variables for. Must be one of 'run', 'session', 'subject', or 'dataset'. types (str, list): Types of variables to retrieve. All valid values reflect the filename stipulated in the BIDS spec for each kind of variable. Valid values include: 'events', 'physio', 'stim', 'scans', 'participants', 'sessions', and 'regressors'. variables (list): Optional list of variables names to return. If None, all available variables are returned. merge (bool): If True, variables are merged across all observations of the current level. E.g., if level='subject', variables from all subjects will be merged into a single collection. If False, each observation is handled separately, and the result is returned as a list. sampling_rate (int, str): If level='run', the sampling rate to pass onto the returned BIDSRunVariableCollection. skip_empty (bool): Whether or not to skip empty Variables (i.e., where there are no rows/records in a file after applying any filtering operations like dropping NaNs). kwargs: Optional additional arguments to pass onto load_variables. """ from bids.variables import load_variables index = load_variables(self, types=types, levels=level, skip_empty=skip_empty, **kwargs) return index.get_collections(level, variables, merge, sampling_rate=sampling_rate) def _make_file_object(self, root, f): # Override grabbit's File with a BIDSFile. return BIDSFile(os.path.join(root, f), self) def get_file(self, filename, derivatives=True): ''' Returns the BIDSFile object with the specified path. Args: filename (str): The path of the file to retrieve. derivatives (bool: If True, checks all associated derivative datasets as well. Returns: A BIDSFile. ''' layouts = [self] if derivatives: layouts += self.derivatives.values() for ly in layouts: if filename in ly.files: return ly.files[filename] return None class MetadataIndex(object): """A simple dict-based index for key/value pairs in JSON metadata. Args: layout (BIDSLayout): The BIDSLayout instance to index. """ def __init__(self, layout): self.layout = layout self.key_index = {} self.file_index = defaultdict(dict) def index_file(self, f, overwrite=False): """Index metadata for the specified file. Args: f (BIDSFile, str): A BIDSFile or path to an indexed file. overwrite (bool): If True, forces reindexing of the file even if an entry already exists. """ if isinstance(f, six.string_types): f = self.layout.get_file(f) if f.path in self.file_index and not overwrite: return if 'suffix' not in f.entities: # Skip files without suffixes return md = self._get_metadata(f.path) for md_key, md_val in md.items(): if md_key not in self.key_index: self.key_index[md_key] = {} self.key_index[md_key][f.path] = md_val self.file_index[f.path][md_key] = md_val def _get_metadata(self, path, **kwargs): potential_jsons = self.layout._get_nearest_helper(path, '.json', **kwargs) if potential_jsons is None: return {} results = {} for json_file_path in reversed(potential_jsons): if os.path.exists(json_file_path): with open(json_file_path, 'r', encoding='utf-8') as fd: param_dict = json.load(fd) results.update(param_dict) return results def search(self, files=None, defined_fields=None, **kwargs): """Search files in the layout by metadata fields. Args: files (list): Optional list of names of files to search. If None, all files in the layout are scanned. defined_fields (list): Optional list of names of fields that must be defined in the JSON sidecar in order to consider the file a match, but which don't need to match any particular value. kwargs: Optional keyword arguments defining search constraints; keys are names of metadata fields, and values are the values to match those fields against (e.g., SliceTiming=0.017) would return all files that have a SliceTiming value of 0.071 in metadata. Returns: A list of filenames that match all constraints. """ if defined_fields is None: defined_fields = [] all_keys = set(defined_fields) | set(kwargs.keys()) if not all_keys: raise ValueError("At least one field to search on must be passed.") # If no list of files is passed, use all files in layout if files is None: files = set(self.layout.files.keys()) # Index metadata for any previously unseen files for f in files: self.index_file(f) # Get file intersection of all kwargs keys--this is fast filesets = [set(self.key_index.get(k, [])) for k in all_keys] matches = reduce(lambda x, y: x & y, filesets) if files is not None: matches &= set(files) if not matches: return [] def check_matches(f, key, val): if isinstance(val, six.string_types) and '*' in val: val = ('^%s$' % val).replace('*', ".*") return re.search(str(self.file_index[f][key]), val) is not None else: return val == self.file_index[f][key] # Serially check matches against each pattern, with early termination for k, val in kwargs.items(): matches = list(filter(lambda x: check_matches(x, k, val), matches)) if not matches: return [] return matches
en
0.773844
Add to the pool of available configuration files for BIDSLayout. Args: kwargs: each kwarg should be a pair of config key name, and path Example: bids.layout.add_config_paths(my_config='/path/to/config') Represents a single BIDS file. # Ensures backwards compatibility with old File_ namedtuple, which is # deprecated as of 0.7. Return the associated image file (if it exists) as a NiBabel object. Return all associated metadata. Layout class representing an entire BIDS dataset. Args: root (str): The root directory of the BIDS dataset. validate (bool): If True, all files are checked for BIDS compliance when first indexed, and non-compliant files are ignored. This provides a convenient way to restrict file indexing to only those files defined in the "core" BIDS spec, as setting validate=True will lead files in supplementary folders like derivatives/, code/, etc. to be ignored. index_associated (bool): Argument passed onto the BIDSValidator; ignored if validate = False. include (str, list): String or list of strings specifying which of the directories that are by default excluded from indexing should be included. The default exclusion list is ['code', 'stimuli', 'sourcedata', 'models']. absolute_paths (bool): If True, queries always return absolute paths. If False, queries return relative paths, unless the root argument was left empty (in which case the root defaults to the file system root). derivatives (bool, str, list): Specificies whether and/or which derivatives to to index. If True, all pipelines found in the derivatives/ subdirectory will be indexed. If a str or list, gives the paths to one or more derivatives directories to index. If False or None, the derivatives/ directory is ignored during indexing, and derivatives will have to be added manually via add_derivatives(). config (str, list): Optional name(s) of configuration file(s) to use. By default (None), uses 'bids'. sources (BIDLayout, list): Optional BIDSLayout(s) from which the current BIDSLayout is derived. kwargs: Optional keyword arguments to pass onto the Layout initializer in grabbit. # Validate arguments # Determine which subdirectories to exclude from indexing # Set up path and config for grabbit # Initialize grabbit Layout # Add derivatives if any are found Add BIDS-Derivatives datasets to tracking. Args: path (str, list): One or more paths to BIDS-Derivatives datasets. Each path can point to either a derivatives/ directory containing one more more pipeline directories, or to a single pipeline directory (e.g., derivatives/fmriprep). kwargs (dict): Optional keyword arguments to pass on to BIDSLayout() when initializing each of the derivative datasets. # Collect all paths that contain a dataset_description.json # Default config and sources values # Propagate derivative entities into top-level dynamic getters Return information for all Files tracked in the Layout as a pandas DataFrame. Args: kwargs: Optional keyword arguments passed on to get(). This allows one to easily select only a subset of files for export. Returns: A pandas DataFrame, where each row is a file, and each column is a tracked entity. NaNs are injected whenever a file has no value for a given attribute. # Callback from grabbit. Exclude special directories like derivatives/ # and code/ from indexing unless they were explicitly included at # initialization. # Callback from grabbit. Files are excluded from indexing if validation # is enabled and fails (i.e., file is not a valid BIDS file). # For derivatives, we need to cheat a bit and construct a fake # derivatives path--prepend 'derivatives' and the pipeline name Helper function for grabbit get_nearest Retrieve files and/or metadata from the current Layout. Args: return_type (str): Type of result to return. Valid values: 'object' (default): return a list of matching BIDSFile objects. 'file': return a list of matching filenames. 'dir': return a list of directories. 'id': return a list of unique IDs. Must be used together with a valid target. target (str): Optional name of the target entity to get results for (only used if return_type is 'dir' or 'id'). extensions (str, list): One or more file extensions to filter on. Files with any other extensions will be excluded. derivatives (bool, str, list): Whether/how to search associated BIDS-Derivatives datasets. If True (default), all available derivatives are searched. If a str or list, must be the name(s) of the derivatives to search (as defined in the PipelineDescription.Name field in dataset_description.json). regex_search (bool or None): Whether to require exact matching (False) or regex search (True) when comparing the query string to each entity. If None (default), uses the value found in self. defined_fields (list): Optional list of names of metadata fields that must be defined in JSON sidecars in order to consider the file a match, but which don't need to match any particular value. domains (str, list): Domain(s) to search in. Valid values are 'bids' and 'derivatives'. kwargs (dict): Any optional key/values to filter the entities on. Keys are entity names, values are regexes to filter on. For example, passing filter={ 'subject': 'sub-[12]'} would return only files that match the first two subjects. Returns: A list of BIDSFile (default) or other objects (see return_type for details). # Warn users still expecting 0.6 behavior # Separate entity kwargs from metadata kwargs # Provide some suggestions if target is specified and invalid. # Get entity-based search results using the superclass's get() # Search the metadata if needed # Add results from derivatives # Flatten results Return metadata found in JSON sidecars for the specified file. Args: path (str): Path to the file to get metadata for. include_entities (bool): If True, all available entities extracted from the filename (rather than JSON sidecars) are included in the returned metadata dictionary. kwargs (dict): Optional keyword arguments to pass onto get_nearest(). Returns: A dictionary of key/value pairs extracted from all of the target file's associated JSON sidecars. Notes: A dictionary containing metadata extracted from all matching .json files is returned. In cases where the same key is found in multiple files, the values in files closer to the input filename will take precedence, per the inheritance rules in the BIDS specification. # For querying efficiency, store metadata in the MetadataIndex cache Get bvec file for passed path. Get bval file for passed path. Get fieldmap(s) for specified path. # len(fieldmaps) == 0 Returns the scanning repetition time (TR) for one or more runs. Args: derivatives (bool): If True, also checks derivatives images. selectors: Optional keywords used to constrain the selected runs. Can be any arguments valid for a .get call (e.g., BIDS entities or JSON sidecar keys). Returns: A single float. Notes: Raises an exception if more than one unique TR is found. # Constrain search to functional images Return one or more variable Collections in the BIDS project. Args: level (str): The level of analysis to return variables for. Must be one of 'run', 'session', 'subject', or 'dataset'. types (str, list): Types of variables to retrieve. All valid values reflect the filename stipulated in the BIDS spec for each kind of variable. Valid values include: 'events', 'physio', 'stim', 'scans', 'participants', 'sessions', and 'regressors'. variables (list): Optional list of variables names to return. If None, all available variables are returned. merge (bool): If True, variables are merged across all observations of the current level. E.g., if level='subject', variables from all subjects will be merged into a single collection. If False, each observation is handled separately, and the result is returned as a list. sampling_rate (int, str): If level='run', the sampling rate to pass onto the returned BIDSRunVariableCollection. skip_empty (bool): Whether or not to skip empty Variables (i.e., where there are no rows/records in a file after applying any filtering operations like dropping NaNs). kwargs: Optional additional arguments to pass onto load_variables. # Override grabbit's File with a BIDSFile. Returns the BIDSFile object with the specified path. Args: filename (str): The path of the file to retrieve. derivatives (bool: If True, checks all associated derivative datasets as well. Returns: A BIDSFile. A simple dict-based index for key/value pairs in JSON metadata. Args: layout (BIDSLayout): The BIDSLayout instance to index. Index metadata for the specified file. Args: f (BIDSFile, str): A BIDSFile or path to an indexed file. overwrite (bool): If True, forces reindexing of the file even if an entry already exists. # Skip files without suffixes Search files in the layout by metadata fields. Args: files (list): Optional list of names of files to search. If None, all files in the layout are scanned. defined_fields (list): Optional list of names of fields that must be defined in the JSON sidecar in order to consider the file a match, but which don't need to match any particular value. kwargs: Optional keyword arguments defining search constraints; keys are names of metadata fields, and values are the values to match those fields against (e.g., SliceTiming=0.017) would return all files that have a SliceTiming value of 0.071 in metadata. Returns: A list of filenames that match all constraints. # If no list of files is passed, use all files in layout # Index metadata for any previously unseen files # Get file intersection of all kwargs keys--this is fast # Serially check matches against each pattern, with early termination
2.101585
2
PastaPhase/energy_and_pressure.py
ppgaluzio/PastaPhase
0
6625079
# -*- coding: utf-8 -*- import numpy as np from scipy.integrate import quad def _int_e(k, m, gs, sigma): return np.sqrt(k**2 + (m - gs * sigma)**2) * k**2 def _int_p(k, m, gs, sigma): return k**4 / np.sqrt(k**2 + (m - gs * sigma)**2) def pressure(ms, mRho, rho, sigma, mw, w0, k, gs, m): """ pressure -------- calculate pressurey, eq. 4.160 from compact stars book parameters: ms: m_sigma sigma: scalar field mw: m_omega w0: omega_0 k: fermi energy gs: g_sigma m: mass """ p = - 0.5 * ms**2 * sigma**2 \ + 0.5 * mw**2 * w0**2 \ + 0.5 * mRho**2 * rho**2 \ + (1/3) * (2/np.pi**2) \ * quad(_int_p, 0, k, args=(m, gs, sigma))[0] return p def energy(ms, mRho, rho, sigma, mw, w0, k, gs, m): """ energy ------ calculate energy density, eq. 4.160 from compact stars book parameters: ms: m_sigma sigma: scalar field mw: m_omega w0: omega_0 k: fermi energy gs: g_sigma m: mass """ e = + 0.5 * ms**2 * sigma**2 \ + 0.5 * mw**2 * w0**2 \ + 0.5 * mRho**2 * rho**2 \ + (2 / np.pi**2) \ * quad(_int_e, 0, k, args=(m, gs, sigma))[0] return e
# -*- coding: utf-8 -*- import numpy as np from scipy.integrate import quad def _int_e(k, m, gs, sigma): return np.sqrt(k**2 + (m - gs * sigma)**2) * k**2 def _int_p(k, m, gs, sigma): return k**4 / np.sqrt(k**2 + (m - gs * sigma)**2) def pressure(ms, mRho, rho, sigma, mw, w0, k, gs, m): """ pressure -------- calculate pressurey, eq. 4.160 from compact stars book parameters: ms: m_sigma sigma: scalar field mw: m_omega w0: omega_0 k: fermi energy gs: g_sigma m: mass """ p = - 0.5 * ms**2 * sigma**2 \ + 0.5 * mw**2 * w0**2 \ + 0.5 * mRho**2 * rho**2 \ + (1/3) * (2/np.pi**2) \ * quad(_int_p, 0, k, args=(m, gs, sigma))[0] return p def energy(ms, mRho, rho, sigma, mw, w0, k, gs, m): """ energy ------ calculate energy density, eq. 4.160 from compact stars book parameters: ms: m_sigma sigma: scalar field mw: m_omega w0: omega_0 k: fermi energy gs: g_sigma m: mass """ e = + 0.5 * ms**2 * sigma**2 \ + 0.5 * mw**2 * w0**2 \ + 0.5 * mRho**2 * rho**2 \ + (2 / np.pi**2) \ * quad(_int_e, 0, k, args=(m, gs, sigma))[0] return e
en
0.472951
# -*- coding: utf-8 -*- pressure -------- calculate pressurey, eq. 4.160 from compact stars book parameters: ms: m_sigma sigma: scalar field mw: m_omega w0: omega_0 k: fermi energy gs: g_sigma m: mass energy ------ calculate energy density, eq. 4.160 from compact stars book parameters: ms: m_sigma sigma: scalar field mw: m_omega w0: omega_0 k: fermi energy gs: g_sigma m: mass
3.153405
3
lib/JumpScale/baselib/mercurial/HgLibFactory.py
rudecs/jumpscale_core7
1
6625080
<gh_stars>1-10 from HgLibClient import HgLibClient from JumpScale import j class HgLibFactory: def __init__(self): j.logger.consolelogCategories.append("bitbucket") def getClient(self, hgbasedir, remoteUrl="", branchname=None, cleandir=False): """ return a mercurial tool which you can help to manipulate a hg repository @param base dir where local hgrepository will be stored @branchname "" means is the tip, None means will try to fetch the branchname from the basedir @param remote url of hg repository, e.g. https://login:passwd@bitbucket.org/despiegk/ssospecs/ #DO NOT FORGET LOGIN PASSWD """ if not isinstance(cleandir, bool): raise ValueError("cleandir needs to be boolean") return HgLibClient(hgbasedir, remoteUrl, branchname=branchname, cleandir=cleandir) def log(self,msg,category="",level=5): category="mercurial.%s"%category category=category.rstrip(".") j.logger.log(msg,category=category,level=level)
from HgLibClient import HgLibClient from JumpScale import j class HgLibFactory: def __init__(self): j.logger.consolelogCategories.append("bitbucket") def getClient(self, hgbasedir, remoteUrl="", branchname=None, cleandir=False): """ return a mercurial tool which you can help to manipulate a hg repository @param base dir where local hgrepository will be stored @branchname "" means is the tip, None means will try to fetch the branchname from the basedir @param remote url of hg repository, e.g. https://login:passwd@bitbucket.org/despiegk/ssospecs/ #DO NOT FORGET LOGIN PASSWD """ if not isinstance(cleandir, bool): raise ValueError("cleandir needs to be boolean") return HgLibClient(hgbasedir, remoteUrl, branchname=branchname, cleandir=cleandir) def log(self,msg,category="",level=5): category="mercurial.%s"%category category=category.rstrip(".") j.logger.log(msg,category=category,level=level)
en
0.711372
return a mercurial tool which you can help to manipulate a hg repository @param base dir where local hgrepository will be stored @branchname "" means is the tip, None means will try to fetch the branchname from the basedir @param remote url of hg repository, e.g. https://login:passwd@bitbucket.org/despiegk/ssospecs/ #DO NOT FORGET LOGIN PASSWD
2.655421
3
cairis/test/test_PersonaCharacteristicAPI.py
RAIJ95/https-github.com-failys-cairis
0
6625081
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from urllib import quote from StringIO import StringIO import os import jsonpickle from cairis.core.PersonaCharacteristic import PersonaCharacteristic from cairis.test.CairisDaemonTestCase import CairisDaemonTestCase from cairis.mio.ModelImport import importModelFile from cairis.tools.JsonConverter import json_deserialize from cairis.tools.PseudoClasses import PersonaCharacteristicReference import os __author__ = '<NAME>' class PersonaCharacteristicAPITests(CairisDaemonTestCase): @classmethod def setUpClass(cls): importModelFile(os.environ['CAIRIS_SRC'] + '/../examples/exemplars/ACME_Water/ACME_Water.xml',1,'test') def setUp(self): self.logger = logging.getLogger(__name__) self.new_pc = PersonaCharacteristic( pcId = -1, pName = 'Rick', modQual = 'Maybe', vName = 'Activities', cDesc = 'This is a test characteristic', pcGrounds = [{"theReferenceName": "Line manager site authorisation", "theDimensionName": "document", "theCharacteristicType": "grounds", "__python_obj__": "cairis.tools.PseudoClasses.PersonaCharacteristicReference", "theReferenceDescription": "Can only access sites they have been authorised to; permission for authorisation changes need to be sought from the line manager."}], pcWarrant = [{"theReferenceDescription": "Work reports are filed and sent to ACME monthly.", "theDimensionName": "document", "theCharacteristicType": "warrant", "__python_obj__": "cairis.tools.PseudoClasses.PersonaCharacteristicReference", "theReferenceName": "Work reports are filed"}], pcRebuttal = [{"theReferenceDescription": "Everything that happens is logged.", "theDimensionName": "document", "theCharacteristicType": "rebuttal", "__python_obj__": "cairis.tools.PseudoClasses.PersonaCharacteristicReference", "theReferenceName": "Everything is logged"}], pcBacking = ['Business compliance GT concept']) self.new_pc_dict = { 'session_id' : 'test', 'object': self.new_pc } self.existing_pc_name = 'Personal safety is an infosec hygiene factor' def test_get_all(self): method = 'test_get_persona_characteristics' url = '/api/persona_characteristics?session_id=test' self.logger.info('[%s] URL: %s', method, url) rv = self.app.get(url) pcs = jsonpickle.decode(rv.data) self.assertIsNotNone(pcs, 'No results after deserialization') self.assertIsInstance(pcs, dict, 'The result is not a dictionary as expected') self.assertGreater(len(pcs), 0, 'No persona characteristics in the dictionary') self.logger.info('[%s] Persona characteristics found: %d', method, len(pcs)) pc = pcs.values()[0] self.logger.info('[%s] First persona characteristic: %s [%d]\n', method, pc['theCharacteristic'], pc['theId']) def test_get_by_name(self): method = 'test_get_by_name' url = '/api/persona_characteristics/name/%s?session_id=test' % quote(self.existing_pc_name) rv = self.app.get(url) self.assertIsNotNone(rv.data, 'No response') self.logger.debug('[%s] Response data: %s', method, rv.data) pc = jsonpickle.decode(rv.data) self.assertIsNotNone(pc, 'No results after deserialization') self.logger.info('[%s] Persona characteristic: %s [%d]\n', method, pc['theCharacteristic'], pc['theId']) def test_post(self): method = 'test_post_new' rv = self.app.post('/api/persona_characteristics', content_type='application/json', data=jsonpickle.encode(self.new_pc_dict)) self.logger.debug('[%s] Response data: %s', method, rv.data) json_resp = json_deserialize(rv.data) self.assertIsNotNone(json_resp, 'No results after deserialization') ackMsg = json_resp.get('message', None) self.assertEqual(ackMsg, 'Persona Characteristic successfully added') def test_put(self): method = 'test_put' self.new_pc_dict['object'].theExcerpt = 'Updated text segment' url = '/api/persona_characteristics/name/%s?session_id=test' % quote(self.new_pc.theCharacteristic) rv = self.app.put(url, content_type='application/json', data=jsonpickle.encode(self.new_pc_dict)) self.logger.debug('[%s] Response data: %s', method, rv.data) json_resp = json_deserialize(rv.data) self.assertIsNotNone(json_resp, 'No results after deserialization') ackMsg = json_resp.get('message', None) self.assertEqual(ackMsg, 'Persona Characteristic successfully updated') def test_delete(self): method = 'test_delete' rv = self.app.post('/api/persona_characteristics', content_type='application/json', data=jsonpickle.encode(self.new_pc_dict)) self.logger.debug('[%s] Response data: %s', method, rv.data) json_resp = json_deserialize(rv.data) url = '/api/persona_characteristics/name/%s?session_id=test' % quote(self.new_pc.theCharacteristic) rv = self.app.delete(url) self.logger.debug('[%s] Response data: %s', method, rv.data) json_resp = json_deserialize(rv.data) self.assertIsNotNone(json_resp, 'No results after deserialization') ackMsg = json_resp.get('message', None) self.assertEqual(ackMsg, 'Persona Characteristic successfully deleted')
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from urllib import quote from StringIO import StringIO import os import jsonpickle from cairis.core.PersonaCharacteristic import PersonaCharacteristic from cairis.test.CairisDaemonTestCase import CairisDaemonTestCase from cairis.mio.ModelImport import importModelFile from cairis.tools.JsonConverter import json_deserialize from cairis.tools.PseudoClasses import PersonaCharacteristicReference import os __author__ = '<NAME>' class PersonaCharacteristicAPITests(CairisDaemonTestCase): @classmethod def setUpClass(cls): importModelFile(os.environ['CAIRIS_SRC'] + '/../examples/exemplars/ACME_Water/ACME_Water.xml',1,'test') def setUp(self): self.logger = logging.getLogger(__name__) self.new_pc = PersonaCharacteristic( pcId = -1, pName = 'Rick', modQual = 'Maybe', vName = 'Activities', cDesc = 'This is a test characteristic', pcGrounds = [{"theReferenceName": "Line manager site authorisation", "theDimensionName": "document", "theCharacteristicType": "grounds", "__python_obj__": "cairis.tools.PseudoClasses.PersonaCharacteristicReference", "theReferenceDescription": "Can only access sites they have been authorised to; permission for authorisation changes need to be sought from the line manager."}], pcWarrant = [{"theReferenceDescription": "Work reports are filed and sent to ACME monthly.", "theDimensionName": "document", "theCharacteristicType": "warrant", "__python_obj__": "cairis.tools.PseudoClasses.PersonaCharacteristicReference", "theReferenceName": "Work reports are filed"}], pcRebuttal = [{"theReferenceDescription": "Everything that happens is logged.", "theDimensionName": "document", "theCharacteristicType": "rebuttal", "__python_obj__": "cairis.tools.PseudoClasses.PersonaCharacteristicReference", "theReferenceName": "Everything is logged"}], pcBacking = ['Business compliance GT concept']) self.new_pc_dict = { 'session_id' : 'test', 'object': self.new_pc } self.existing_pc_name = 'Personal safety is an infosec hygiene factor' def test_get_all(self): method = 'test_get_persona_characteristics' url = '/api/persona_characteristics?session_id=test' self.logger.info('[%s] URL: %s', method, url) rv = self.app.get(url) pcs = jsonpickle.decode(rv.data) self.assertIsNotNone(pcs, 'No results after deserialization') self.assertIsInstance(pcs, dict, 'The result is not a dictionary as expected') self.assertGreater(len(pcs), 0, 'No persona characteristics in the dictionary') self.logger.info('[%s] Persona characteristics found: %d', method, len(pcs)) pc = pcs.values()[0] self.logger.info('[%s] First persona characteristic: %s [%d]\n', method, pc['theCharacteristic'], pc['theId']) def test_get_by_name(self): method = 'test_get_by_name' url = '/api/persona_characteristics/name/%s?session_id=test' % quote(self.existing_pc_name) rv = self.app.get(url) self.assertIsNotNone(rv.data, 'No response') self.logger.debug('[%s] Response data: %s', method, rv.data) pc = jsonpickle.decode(rv.data) self.assertIsNotNone(pc, 'No results after deserialization') self.logger.info('[%s] Persona characteristic: %s [%d]\n', method, pc['theCharacteristic'], pc['theId']) def test_post(self): method = 'test_post_new' rv = self.app.post('/api/persona_characteristics', content_type='application/json', data=jsonpickle.encode(self.new_pc_dict)) self.logger.debug('[%s] Response data: %s', method, rv.data) json_resp = json_deserialize(rv.data) self.assertIsNotNone(json_resp, 'No results after deserialization') ackMsg = json_resp.get('message', None) self.assertEqual(ackMsg, 'Persona Characteristic successfully added') def test_put(self): method = 'test_put' self.new_pc_dict['object'].theExcerpt = 'Updated text segment' url = '/api/persona_characteristics/name/%s?session_id=test' % quote(self.new_pc.theCharacteristic) rv = self.app.put(url, content_type='application/json', data=jsonpickle.encode(self.new_pc_dict)) self.logger.debug('[%s] Response data: %s', method, rv.data) json_resp = json_deserialize(rv.data) self.assertIsNotNone(json_resp, 'No results after deserialization') ackMsg = json_resp.get('message', None) self.assertEqual(ackMsg, 'Persona Characteristic successfully updated') def test_delete(self): method = 'test_delete' rv = self.app.post('/api/persona_characteristics', content_type='application/json', data=jsonpickle.encode(self.new_pc_dict)) self.logger.debug('[%s] Response data: %s', method, rv.data) json_resp = json_deserialize(rv.data) url = '/api/persona_characteristics/name/%s?session_id=test' % quote(self.new_pc.theCharacteristic) rv = self.app.delete(url) self.logger.debug('[%s] Response data: %s', method, rv.data) json_resp = json_deserialize(rv.data) self.assertIsNotNone(json_resp, 'No results after deserialization') ackMsg = json_resp.get('message', None) self.assertEqual(ackMsg, 'Persona Characteristic successfully deleted')
en
0.865663
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License.
1.779565
2
app.py
AlJohri/cjmls
0
6625082
#!/usr/bin/env python3 import requests from flask import Flask, jsonify app = Flask(__name__) @app.route("/") def hello(): return "CJMLS" @app.route("/properties/<int:mlsid>") def get_property(mlsid): data = requests.get(f"https://queryserviceb.placester.net/search?sort_field=price&sort_direction=desc&search_num_results=9&search_start_offset=0&purchase_types=buy&mls_id={mlsid}&region_id=nj&origin_ids=51967f537293b476e0000003").json() # mongo_id = data['organic_results']['search_results'][0]['mongo_id'] # url = f"https://www.mcmls.net/property/x/x/x/x/x/{mongo_id}/" # return f'<meta http-equiv="refresh" content="0; url={url}" />' return jsonify(data) if __name__ == "__main__": app.run(debug=True)
#!/usr/bin/env python3 import requests from flask import Flask, jsonify app = Flask(__name__) @app.route("/") def hello(): return "CJMLS" @app.route("/properties/<int:mlsid>") def get_property(mlsid): data = requests.get(f"https://queryserviceb.placester.net/search?sort_field=price&sort_direction=desc&search_num_results=9&search_start_offset=0&purchase_types=buy&mls_id={mlsid}&region_id=nj&origin_ids=51967f537293b476e0000003").json() # mongo_id = data['organic_results']['search_results'][0]['mongo_id'] # url = f"https://www.mcmls.net/property/x/x/x/x/x/{mongo_id}/" # return f'<meta http-equiv="refresh" content="0; url={url}" />' return jsonify(data) if __name__ == "__main__": app.run(debug=True)
en
0.329903
#!/usr/bin/env python3 # mongo_id = data['organic_results']['search_results'][0]['mongo_id'] # url = f"https://www.mcmls.net/property/x/x/x/x/x/{mongo_id}/" # return f'<meta http-equiv="refresh" content="0; url={url}" />'
2.703481
3
nnpy/functions/cost_functions.py
AlexBacho/nnpy
0
6625083
<reponame>AlexBacho/nnpy import numpy as np def mse(actual, predicted): """ https://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.html#cost-function MSE = the mean of (actual_outcome - predicted_outcome) squared """ return np.mean(np.power(actual - predicted, 2)) def prime_mse(actual, predicted): """ Derivate of mse for use with the Gradient Descent optimizer. Output error is calculated either as the result of the derivative of the cost function or as the result of the backpropagation of the previous layer. """ return 2 * (predicted - actual) / actual.size
import numpy as np def mse(actual, predicted): """ https://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.html#cost-function MSE = the mean of (actual_outcome - predicted_outcome) squared """ return np.mean(np.power(actual - predicted, 2)) def prime_mse(actual, predicted): """ Derivate of mse for use with the Gradient Descent optimizer. Output error is calculated either as the result of the derivative of the cost function or as the result of the backpropagation of the previous layer. """ return 2 * (predicted - actual) / actual.size
en
0.835593
https://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.html#cost-function MSE = the mean of (actual_outcome - predicted_outcome) squared Derivate of mse for use with the Gradient Descent optimizer. Output error is calculated either as the result of the derivative of the cost function or as the result of the backpropagation of the previous layer.
3.713768
4
core/python/kungfu/yijinjing/nanomsg.py
yunnant/kungfu
2,209
6625084
NS_NAMESPACE = 0 NS_VERSION = 1 NS_DOMAIN = 2 NS_TRANSPORT = 3 NS_PROTOCOL = 4 NS_OPTION_LEVEL = 5 NS_SOCKET_OPTION = 6 NS_TRANSPORT_OPTION = 7 NS_OPTION_TYPE = 8 NS_OPTION_UNIT = 9 NS_FLAG = 10 NS_ERROR = 11 NS_LIMIT = 12 NS_EVENT = 13 NS_STATISTIC = 14 TYPE_NONE = 0 TYPE_INT = 1 TYPE_STR = 2 UNIT_NONE = 0 UNIT_BYTES = 1 UNIT_MILLISECONDS = 2 UNIT_PRIORITY = 3 UNIT_BOOLEAN = 4 UNIT_COUNTER = 6 UNIT_MESSAGES = 5 VERSION_CURRENT = 5 VERSION_REVISION = 1 VERSION_AGE = 0 AF_SP = 1 AF_SP_RAW = 2 INPROC = -1 IPC = -2 TCP = -3 WS = -4 PAIR = 16 PUB = 32 SUB = 33 REP = 49 REQ = 48 PUSH = 80 PULL = 81 SURVEYOR = 98 RESPONDENT = 99 BUS = 112 SOCKADDR_MAX = 128 SOL_SOCKET = 0 LINGER = 1 SNDBUF = 2 RCVBUF = 3 RCVMAXSIZE = 16 SNDTIMEO = 4 RCVTIMEO = 5 RECONNECT_IVL = 6 RECONNECT_IVL_MAX = 7 SNDPRIO = 8 RCVPRIO = 9 SNDFD = 10 RCVFD = 11 DOMAIN = 12 PROTOCOL = 13 IPV4ONLY = 14 SOCKET_NAME = 15 MAXTTL = 17 SUB_SUBSCRIBE = 1 SUB_UNSUBSCRIBE = 2 REQ_RESEND_IVL = 1 SURVEYOR_DEADLINE = 1 TCP_NODELAY = 1 WS_MSG_TYPE = 1 DONTWAIT = 1 WS_MSG_TYPE_TEXT = 1 WS_MSG_TYPE_BINARY = 2 POLLIN = 1 POLLOUT = 2 EADDRINUSE = 48 EADDRNOTAVAIL = 49 EAFNOSUPPORT = 47 EAGAIN = 35 EBADF = 9 ECONNREFUSED = 61 EFAULT = 14 EFSM = 156384766 EINPROGRESS = 36 EINTR = 4 EINVAL = 22 EMFILE = 24 ENAMETOOLONG = 63 ENETDOWN = 50 ENOBUFS = 55 ENODEV = 19 ENOMEM = 12 ENOPROTOOPT = 42 ENOTSOCK = 38 ENOTSUP = 45 EPROTO = 100 EPROTONOSUPPORT = 43 ETERM = 156384765 ETIMEDOUT = 60 EACCES = 13 ECONNABORTED = 53 ECONNRESET = 54 EHOSTUNREACH = 65 EMSGSIZE = 40 ENETRESET = 52 ENETUNREACH = 51 ENOTCONN = 57 STAT_ESTABLISHED_CONNECTIONS = 101 STAT_ACCEPTED_CONNECTIONS = 102 STAT_DROPPED_CONNECTIONS = 103 STAT_BROKEN_CONNECTIONS = 104 STAT_CONNECT_ERRORS = 105 STAT_BIND_ERRORS = 106 STAT_ACCEPT_ERRORS = 107 STAT_MESSAGES_SENT = 301 STAT_MESSAGES_RECEIVED = 302 STAT_BYTES_SENT = 303 STAT_BYTES_RECEIVED = 304 STAT_CURRENT_CONNECTIONS = 201 STAT_INPROGRESS_CONNECTIONS = 202 STAT_CURRENT_SND_PRIORITY = 401 STAT_CURRENT_EP_ERRORS = 203
NS_NAMESPACE = 0 NS_VERSION = 1 NS_DOMAIN = 2 NS_TRANSPORT = 3 NS_PROTOCOL = 4 NS_OPTION_LEVEL = 5 NS_SOCKET_OPTION = 6 NS_TRANSPORT_OPTION = 7 NS_OPTION_TYPE = 8 NS_OPTION_UNIT = 9 NS_FLAG = 10 NS_ERROR = 11 NS_LIMIT = 12 NS_EVENT = 13 NS_STATISTIC = 14 TYPE_NONE = 0 TYPE_INT = 1 TYPE_STR = 2 UNIT_NONE = 0 UNIT_BYTES = 1 UNIT_MILLISECONDS = 2 UNIT_PRIORITY = 3 UNIT_BOOLEAN = 4 UNIT_COUNTER = 6 UNIT_MESSAGES = 5 VERSION_CURRENT = 5 VERSION_REVISION = 1 VERSION_AGE = 0 AF_SP = 1 AF_SP_RAW = 2 INPROC = -1 IPC = -2 TCP = -3 WS = -4 PAIR = 16 PUB = 32 SUB = 33 REP = 49 REQ = 48 PUSH = 80 PULL = 81 SURVEYOR = 98 RESPONDENT = 99 BUS = 112 SOCKADDR_MAX = 128 SOL_SOCKET = 0 LINGER = 1 SNDBUF = 2 RCVBUF = 3 RCVMAXSIZE = 16 SNDTIMEO = 4 RCVTIMEO = 5 RECONNECT_IVL = 6 RECONNECT_IVL_MAX = 7 SNDPRIO = 8 RCVPRIO = 9 SNDFD = 10 RCVFD = 11 DOMAIN = 12 PROTOCOL = 13 IPV4ONLY = 14 SOCKET_NAME = 15 MAXTTL = 17 SUB_SUBSCRIBE = 1 SUB_UNSUBSCRIBE = 2 REQ_RESEND_IVL = 1 SURVEYOR_DEADLINE = 1 TCP_NODELAY = 1 WS_MSG_TYPE = 1 DONTWAIT = 1 WS_MSG_TYPE_TEXT = 1 WS_MSG_TYPE_BINARY = 2 POLLIN = 1 POLLOUT = 2 EADDRINUSE = 48 EADDRNOTAVAIL = 49 EAFNOSUPPORT = 47 EAGAIN = 35 EBADF = 9 ECONNREFUSED = 61 EFAULT = 14 EFSM = 156384766 EINPROGRESS = 36 EINTR = 4 EINVAL = 22 EMFILE = 24 ENAMETOOLONG = 63 ENETDOWN = 50 ENOBUFS = 55 ENODEV = 19 ENOMEM = 12 ENOPROTOOPT = 42 ENOTSOCK = 38 ENOTSUP = 45 EPROTO = 100 EPROTONOSUPPORT = 43 ETERM = 156384765 ETIMEDOUT = 60 EACCES = 13 ECONNABORTED = 53 ECONNRESET = 54 EHOSTUNREACH = 65 EMSGSIZE = 40 ENETRESET = 52 ENETUNREACH = 51 ENOTCONN = 57 STAT_ESTABLISHED_CONNECTIONS = 101 STAT_ACCEPTED_CONNECTIONS = 102 STAT_DROPPED_CONNECTIONS = 103 STAT_BROKEN_CONNECTIONS = 104 STAT_CONNECT_ERRORS = 105 STAT_BIND_ERRORS = 106 STAT_ACCEPT_ERRORS = 107 STAT_MESSAGES_SENT = 301 STAT_MESSAGES_RECEIVED = 302 STAT_BYTES_SENT = 303 STAT_BYTES_RECEIVED = 304 STAT_CURRENT_CONNECTIONS = 201 STAT_INPROGRESS_CONNECTIONS = 202 STAT_CURRENT_SND_PRIORITY = 401 STAT_CURRENT_EP_ERRORS = 203
none
1
1.153924
1
tests/utils_tests/mask_tests/test_mask_to_bbox.py
souravsingh/chainercv
1,600
6625085
from __future__ import division import unittest import numpy as np from chainer.backends import cuda from chainer import testing from chainer.testing import attr from chainercv.utils import mask_to_bbox @testing.parameterize( {'mask': np.array( [[[False, False, False, False], [False, True, True, True], [False, True, True, True] ]]), 'expected': np.array([[1, 1, 3, 4]], dtype=np.float32) }, {'mask': np.array( [[[False, False], [False, True]], [[True, False], [False, True]]]), 'expected': np.array([[1, 1, 2, 2], [0, 0, 2, 2]], dtype=np.float32) }, {'mask': np.array( [[[False, False], [False, False]], [[True, False], [False, True]]]), 'expected': np.array([[0, 0, 0, 0], [0, 0, 2, 2]], dtype=np.float32) }, ) class TestMaskToBbox(unittest.TestCase): def check(self, mask, expected): bbox = mask_to_bbox(mask) self.assertIsInstance(bbox, type(expected)) self.assertEqual(bbox.dtype, expected.dtype) np.testing.assert_equal( cuda.to_cpu(bbox), cuda.to_cpu(expected)) def test_mask_to_bbox_cpu(self): self.check(self.mask, self.expected) @attr.gpu def test_mask_to_bbox_gpu(self): self.check( cuda.to_gpu(self.mask), cuda.to_gpu(self.expected)) testing.run_module(__name__, __file__)
from __future__ import division import unittest import numpy as np from chainer.backends import cuda from chainer import testing from chainer.testing import attr from chainercv.utils import mask_to_bbox @testing.parameterize( {'mask': np.array( [[[False, False, False, False], [False, True, True, True], [False, True, True, True] ]]), 'expected': np.array([[1, 1, 3, 4]], dtype=np.float32) }, {'mask': np.array( [[[False, False], [False, True]], [[True, False], [False, True]]]), 'expected': np.array([[1, 1, 2, 2], [0, 0, 2, 2]], dtype=np.float32) }, {'mask': np.array( [[[False, False], [False, False]], [[True, False], [False, True]]]), 'expected': np.array([[0, 0, 0, 0], [0, 0, 2, 2]], dtype=np.float32) }, ) class TestMaskToBbox(unittest.TestCase): def check(self, mask, expected): bbox = mask_to_bbox(mask) self.assertIsInstance(bbox, type(expected)) self.assertEqual(bbox.dtype, expected.dtype) np.testing.assert_equal( cuda.to_cpu(bbox), cuda.to_cpu(expected)) def test_mask_to_bbox_cpu(self): self.check(self.mask, self.expected) @attr.gpu def test_mask_to_bbox_gpu(self): self.check( cuda.to_gpu(self.mask), cuda.to_gpu(self.expected)) testing.run_module(__name__, __file__)
none
1
2.186669
2
integration/workflow/bigquery.py
pingsutw/flyte-app
7
6625086
<reponame>pingsutw/flyte-app<gh_stars>1-10 import pandas as pd from flytekit import task, StructuredDataset import os os.environ["GOOGLE_CLOUD_PROJECT"] = "flyte-test-340607" @task def my_task() -> StructuredDataset: df = pd.DataFrame({"Name": ["Tom", "Joseph"], "Age": [20, 22]}) return StructuredDataset(dataframe=df, uri='bq://flyte-test-340607.dataset.test1') @task def my_task1(sd: StructuredDataset) -> pd.DataFrame: return sd.open(pd.DataFrame).all() res = my_task1(sd=StructuredDataset(uri="bq://sp-one-model.quarterly_forecast_2022F1.premium_revenue_tab_input_vat")) print(res) # print(sd.open(pd.DataFrame).all())
import pandas as pd from flytekit import task, StructuredDataset import os os.environ["GOOGLE_CLOUD_PROJECT"] = "flyte-test-340607" @task def my_task() -> StructuredDataset: df = pd.DataFrame({"Name": ["Tom", "Joseph"], "Age": [20, 22]}) return StructuredDataset(dataframe=df, uri='bq://flyte-test-340607.dataset.test1') @task def my_task1(sd: StructuredDataset) -> pd.DataFrame: return sd.open(pd.DataFrame).all() res = my_task1(sd=StructuredDataset(uri="bq://sp-one-model.quarterly_forecast_2022F1.premium_revenue_tab_input_vat")) print(res) # print(sd.open(pd.DataFrame).all())
ru
0.212371
# print(sd.open(pd.DataFrame).all())
2.882097
3
w3id/oauth2/session_auth.py
justinas-vd/python3-w3id
0
6625087
# Copyright 2018 IBM Corp. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implement authentification policy via oauth2 and store the result in a session.""" import json from datetime import datetime import dateutil.parser from aiohttp import web from aiohttp_session import get_session from .abstract_auth import AbstractOAuth2Policy class SessionOAuth2Authentication(AbstractOAuth2Policy): """Ticket authentication mechanism based on OAuth2, with ticket data being stored in a session. """ def __init__(self, client, cookie_name='OAUTH2_OID'): self.client = client self.cookie_name = cookie_name async def _make_cookie(self, request, user_id, data): expires_in = int(data['expires_in']) # Compute the time when the token expires now = datetime.now() fields = { 'user_id' : user_id, 'access_token' : data['access_token'], 'refresh_token' : data['refresh_token'], 'creation_time' : now.isoformat(), 'max_age' : expires_in } # store the ticket data for a request. The cookie will be passed onto # some response during process_response call session = await get_session(request) session[self.cookie_name] = json.dumps(fields) async def get(self, request): """Gets the user_id for the request. Gets the ticket for the request using the get_ticket() function, and authenticates the ticket. Args: request: aiohttp Request object. Returns: The userid for the request, or None if the ticket is not authenticated. """ # Load and parse the ticket. If that fails, go to the authorization page. user_id = None # pylint: disable=bare-except try: session = await get_session(request) ticket = session.get(self.cookie_name) fields = json.loads(ticket) user_id = fields['user_id'] # See if the ticket that we have is not getting stale; # reissue an update if it is stale. creation_time = dateutil.parser.parse(fields['creation_time']) max_age = int(fields['max_age']) # Compute the time difference in seconds tdelta = datetime.now() - creation_time if tdelta.total_seconds() > max_age: # Get the refresh if possible and update the cookie data = await self.client.refresh_access_token(fields) await self._make_cookie(request, user_id, data) except: # Redirect to the login page raise web.HTTPFound(self.client.get_authorization_endpoint()) return user_id async def auth_callback(self, request): "Process the callback from the OAuth2 engine and redirect to the main page." # Report errors if any error = request.query.get('error', None) if error: return web.HTTPBadRequest(reason=error) # If we got the code, then query the access token code = request.query.get(self.client.shared_key, None) if code: # Turn a code into an OAuth2 access token data = await self.client.get_access_token(code) # Verify that we have received the token try: user_id = self.client.user_parse(data) await self._make_cookie(request, user_id, data) return web.HTTPFound('/') except KeyError: raise web.HTTPBadRequest(reason='Failed to obtain OAuth2 access token.') # Default response on this page return web.HTTPForbidden()
# Copyright 2018 IBM Corp. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implement authentification policy via oauth2 and store the result in a session.""" import json from datetime import datetime import dateutil.parser from aiohttp import web from aiohttp_session import get_session from .abstract_auth import AbstractOAuth2Policy class SessionOAuth2Authentication(AbstractOAuth2Policy): """Ticket authentication mechanism based on OAuth2, with ticket data being stored in a session. """ def __init__(self, client, cookie_name='OAUTH2_OID'): self.client = client self.cookie_name = cookie_name async def _make_cookie(self, request, user_id, data): expires_in = int(data['expires_in']) # Compute the time when the token expires now = datetime.now() fields = { 'user_id' : user_id, 'access_token' : data['access_token'], 'refresh_token' : data['refresh_token'], 'creation_time' : now.isoformat(), 'max_age' : expires_in } # store the ticket data for a request. The cookie will be passed onto # some response during process_response call session = await get_session(request) session[self.cookie_name] = json.dumps(fields) async def get(self, request): """Gets the user_id for the request. Gets the ticket for the request using the get_ticket() function, and authenticates the ticket. Args: request: aiohttp Request object. Returns: The userid for the request, or None if the ticket is not authenticated. """ # Load and parse the ticket. If that fails, go to the authorization page. user_id = None # pylint: disable=bare-except try: session = await get_session(request) ticket = session.get(self.cookie_name) fields = json.loads(ticket) user_id = fields['user_id'] # See if the ticket that we have is not getting stale; # reissue an update if it is stale. creation_time = dateutil.parser.parse(fields['creation_time']) max_age = int(fields['max_age']) # Compute the time difference in seconds tdelta = datetime.now() - creation_time if tdelta.total_seconds() > max_age: # Get the refresh if possible and update the cookie data = await self.client.refresh_access_token(fields) await self._make_cookie(request, user_id, data) except: # Redirect to the login page raise web.HTTPFound(self.client.get_authorization_endpoint()) return user_id async def auth_callback(self, request): "Process the callback from the OAuth2 engine and redirect to the main page." # Report errors if any error = request.query.get('error', None) if error: return web.HTTPBadRequest(reason=error) # If we got the code, then query the access token code = request.query.get(self.client.shared_key, None) if code: # Turn a code into an OAuth2 access token data = await self.client.get_access_token(code) # Verify that we have received the token try: user_id = self.client.user_parse(data) await self._make_cookie(request, user_id, data) return web.HTTPFound('/') except KeyError: raise web.HTTPBadRequest(reason='Failed to obtain OAuth2 access token.') # Default response on this page return web.HTTPForbidden()
en
0.823511
# Copyright 2018 IBM Corp. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Implement authentification policy via oauth2 and store the result in a session. Ticket authentication mechanism based on OAuth2, with ticket data being stored in a session. # Compute the time when the token expires # store the ticket data for a request. The cookie will be passed onto # some response during process_response call Gets the user_id for the request. Gets the ticket for the request using the get_ticket() function, and authenticates the ticket. Args: request: aiohttp Request object. Returns: The userid for the request, or None if the ticket is not authenticated. # Load and parse the ticket. If that fails, go to the authorization page. # pylint: disable=bare-except # See if the ticket that we have is not getting stale; # reissue an update if it is stale. # Compute the time difference in seconds # Get the refresh if possible and update the cookie # Redirect to the login page # Report errors if any # If we got the code, then query the access token # Turn a code into an OAuth2 access token # Verify that we have received the token # Default response on this page
2.702933
3
datasets/usps.py
guoyang328/pytorch-dann
1
6625088
"""Dataset setting and data loader for MNIST.""" import torch from torchvision import datasets, transforms import os def get_usps(dataset_root, batch_size, train): """Get USPS datasets loader.""" # image pre-processing pre_process = transforms.Compose([transforms.Resize(28), transforms.ToTensor(), transforms.Normalize( mean=[0.2473], # Mean for USPS train data std=[0.2665] # std for USPS train data ) ]) # datasets and data loader usps_dataset = datasets.USPS(root=os.path.join(dataset_root), train=train, transform=pre_process, download=True) usps_data_loader = torch.utils.data.DataLoader( dataset=usps_dataset, batch_size=batch_size, shuffle=True, drop_last=True, num_workers=8) return usps_data_loader
"""Dataset setting and data loader for MNIST.""" import torch from torchvision import datasets, transforms import os def get_usps(dataset_root, batch_size, train): """Get USPS datasets loader.""" # image pre-processing pre_process = transforms.Compose([transforms.Resize(28), transforms.ToTensor(), transforms.Normalize( mean=[0.2473], # Mean for USPS train data std=[0.2665] # std for USPS train data ) ]) # datasets and data loader usps_dataset = datasets.USPS(root=os.path.join(dataset_root), train=train, transform=pre_process, download=True) usps_data_loader = torch.utils.data.DataLoader( dataset=usps_dataset, batch_size=batch_size, shuffle=True, drop_last=True, num_workers=8) return usps_data_loader
en
0.674192
Dataset setting and data loader for MNIST. Get USPS datasets loader. # image pre-processing # Mean for USPS train data # std for USPS train data # datasets and data loader
2.820618
3
missioncontrol/v0/groundstations.py
Psykar/missioncontrol
0
6625089
from home.models import GroundStation def search(limit=100): return [gs.to_dict() for gs in GroundStation.objects.all().order_by('hwid')[:limit]] def get_hwid(hwid): return GroundStation.objects.get(hwid=hwid).to_dict() def sanitize(groundstation): # XXX move to custom field on model if "latitude" in groundstation: groundstation["latitude"] = str(round(groundstation["latitude"], 6)) if "longitude" in groundstation: groundstation["longitude"] = str(round(groundstation["longitude"], 6)) return groundstation def patch(hwid, groundstation): groundstation["hwid"] = hwid groundstation = sanitize(groundstation) gs = GroundStation.objects.get(hwid=hwid) for key, value in groundstation.items(): setattr(gs, key, value) gs.save() return gs.to_dict() def put(hwid, groundstation): groundstation["hwid"] = hwid groundstation = sanitize(groundstation) m = GroundStation(**groundstation).to_dict() gs, _created = GroundStation.objects.update_or_create( defaults=m, hwid=hwid ) status_code = 201 if _created else 200 return gs.to_dict(), status_code def delete(hwid): gs = GroundStation.objects.get(hwid=hwid) gs.delete() return None, 204
from home.models import GroundStation def search(limit=100): return [gs.to_dict() for gs in GroundStation.objects.all().order_by('hwid')[:limit]] def get_hwid(hwid): return GroundStation.objects.get(hwid=hwid).to_dict() def sanitize(groundstation): # XXX move to custom field on model if "latitude" in groundstation: groundstation["latitude"] = str(round(groundstation["latitude"], 6)) if "longitude" in groundstation: groundstation["longitude"] = str(round(groundstation["longitude"], 6)) return groundstation def patch(hwid, groundstation): groundstation["hwid"] = hwid groundstation = sanitize(groundstation) gs = GroundStation.objects.get(hwid=hwid) for key, value in groundstation.items(): setattr(gs, key, value) gs.save() return gs.to_dict() def put(hwid, groundstation): groundstation["hwid"] = hwid groundstation = sanitize(groundstation) m = GroundStation(**groundstation).to_dict() gs, _created = GroundStation.objects.update_or_create( defaults=m, hwid=hwid ) status_code = 201 if _created else 200 return gs.to_dict(), status_code def delete(hwid): gs = GroundStation.objects.get(hwid=hwid) gs.delete() return None, 204
en
0.600746
# XXX move to custom field on model
2.466944
2
app/decorators/__init__.py
spetrovic450/ksvotes.org
10
6625090
<filename>app/decorators/__init__.py<gh_stars>1-10 from .insession import InSession
<filename>app/decorators/__init__.py<gh_stars>1-10 from .insession import InSession
none
1
1.238787
1
lib/rel_model.py
bknyaz/s
65
6625091
""" Base class for relationship models """ import torch.nn as nn import torch.nn.parallel import torchvision import copy from lib.get_union_boxes import UnionBoxesAndFeats from lib.pytorch_misc import diagonal_inds, bbox_overlaps, gather_res from lib.sparse_targets import FrequencyBias from config import * from torchvision.models.detection.faster_rcnn import FastRCNNPredictor MODES = ('sgdet', 'sgcls', 'predcls') class RelModelBase(nn.Module): """ RELATIONSHIPS """ def __init__(self, train_data, mode='sgdet', num_gpus=1, require_overlap_det=True, use_bias=False, test_bias=False, detector_model='baseline', RELS_PER_IMG=1024): """ :param mode: (sgcls, predcls, or sgdet) :param num_gpus: how many GPUS 2 use :param require_overlap_det: Whether two objects must intersect """ super(RelModelBase, self).__init__() self.classes = train_data.ind_to_classes self.rel_classes = train_data.ind_to_predicates self.num_gpus = num_gpus assert mode in MODES self.mode = mode self.detector_model = detector_model self.RELS_PER_IMG = RELS_PER_IMG self.pooling_size = 7 self.stride = 16 self.obj_dim = 4096 self.use_bias = use_bias self.test_bias = test_bias self.require_overlap = require_overlap_det and self.mode == 'sgdet' if self.detector_model == 'mrcnn': print('\nLoading COCO pretrained model maskrcnn_resnet50_fpn...\n') # See https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html self.detector = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True, box_detections_per_img=50, box_score_thresh=0.2) in_features = self.detector.roi_heads.box_predictor.cls_score.in_features # replace the pre-trained head with a new one self.detector.roi_heads.box_predictor = FastRCNNPredictor(in_features, len(self.classes)) self.detector.roi_heads.mask_predictor = None self.union_boxes = UnionBoxesAndFeats(pooling_size=self.pooling_size, stride=self.stride, dim=256 if self.detector_model == 'mrcnn' else 512) if self.detector_model == 'mrcnn': layers = list(self.detector.roi_heads.children())[:2] self.roi_fmap_obj = copy.deepcopy(layers[1]) self.roi_fmap = copy.deepcopy(layers[1]) self.multiscale_roi_pool = copy.deepcopy(layers[0]) else: raise NotImplementedError(self.detector_model) if self.use_bias: self.freq_bias = FrequencyBias(train_data) @property def num_classes(self): return len(self.classes) @property def num_rels(self): return len(self.rel_classes) def get_rel_inds(self, rel_labels, im_inds, box_priors): # Get the relationship candidates if self.training: rel_inds = rel_labels[:, :3].data.clone() else: rel_cands = im_inds.data[:, None] == im_inds.data[None] rel_cands.view(-1)[diagonal_inds(rel_cands)] = 0 # Require overlap for detection if self.require_overlap: rel_cands = rel_cands & (bbox_overlaps(box_priors.data, box_priors.data) > 0) # if there are fewer then 100 things then we might as well add some? amt_to_add = 100 - rel_cands.long().sum() rel_cands = rel_cands.nonzero() if rel_cands.dim() == 0: rel_cands = im_inds.data.new(1, 2).fill_(0) rel_inds = torch.cat((im_inds.data[rel_cands[:, 0]][:, None], rel_cands), 1) return rel_inds def predict(self, node_feat, edge_feat, rel_inds, rois, im_sizes): raise NotImplementedError('predict') def forward(self, x, im_sizes, image_offset, gt_boxes=None, gt_classes=None, gt_rels=None, *arg): """ Forward pass for detection :param x: Images@[batch_size, 3, IM_SIZE, IM_SIZE] :param im_sizes: A numpy array of (h, w, scale) for each image. :param image_offset: Offset onto what image we're on for MGPU training (if single GPU this is 0) :param gt_boxes: Training parameters: :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2] gt boxes where each one is (img_id, class) :param train_anchor_inds: a [num_train, 2] array of indices for the anchors that will be used to compute the training loss. Each (img_ind, fpn_idx) :return: If train: scores, boxdeltas, labels, boxes, boxtargets, rpnscores, rpnboxes, rellabels if test: prob dists, boxes, img inds, maxscores, classes """ raise NotImplementedError('forward') def forward_parallel(self, batch): # define as a function here so that wandb can watch gradients """ Hack to do multi-GPU training""" batch.scatter() if self.num_gpus == 1: return self(*batch[0]) else: raise NotImplementedError('need to make sure it is correct') replicas = nn.parallel.replicate(self, devices=list(range(self.num_gpus))) outputs = nn.parallel.parallel_apply(replicas, [batch[i] for i in range(self.num_gpus)]) if self.training: return gather_res(outputs, 0, dim=0) return outputs
""" Base class for relationship models """ import torch.nn as nn import torch.nn.parallel import torchvision import copy from lib.get_union_boxes import UnionBoxesAndFeats from lib.pytorch_misc import diagonal_inds, bbox_overlaps, gather_res from lib.sparse_targets import FrequencyBias from config import * from torchvision.models.detection.faster_rcnn import FastRCNNPredictor MODES = ('sgdet', 'sgcls', 'predcls') class RelModelBase(nn.Module): """ RELATIONSHIPS """ def __init__(self, train_data, mode='sgdet', num_gpus=1, require_overlap_det=True, use_bias=False, test_bias=False, detector_model='baseline', RELS_PER_IMG=1024): """ :param mode: (sgcls, predcls, or sgdet) :param num_gpus: how many GPUS 2 use :param require_overlap_det: Whether two objects must intersect """ super(RelModelBase, self).__init__() self.classes = train_data.ind_to_classes self.rel_classes = train_data.ind_to_predicates self.num_gpus = num_gpus assert mode in MODES self.mode = mode self.detector_model = detector_model self.RELS_PER_IMG = RELS_PER_IMG self.pooling_size = 7 self.stride = 16 self.obj_dim = 4096 self.use_bias = use_bias self.test_bias = test_bias self.require_overlap = require_overlap_det and self.mode == 'sgdet' if self.detector_model == 'mrcnn': print('\nLoading COCO pretrained model maskrcnn_resnet50_fpn...\n') # See https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html self.detector = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True, box_detections_per_img=50, box_score_thresh=0.2) in_features = self.detector.roi_heads.box_predictor.cls_score.in_features # replace the pre-trained head with a new one self.detector.roi_heads.box_predictor = FastRCNNPredictor(in_features, len(self.classes)) self.detector.roi_heads.mask_predictor = None self.union_boxes = UnionBoxesAndFeats(pooling_size=self.pooling_size, stride=self.stride, dim=256 if self.detector_model == 'mrcnn' else 512) if self.detector_model == 'mrcnn': layers = list(self.detector.roi_heads.children())[:2] self.roi_fmap_obj = copy.deepcopy(layers[1]) self.roi_fmap = copy.deepcopy(layers[1]) self.multiscale_roi_pool = copy.deepcopy(layers[0]) else: raise NotImplementedError(self.detector_model) if self.use_bias: self.freq_bias = FrequencyBias(train_data) @property def num_classes(self): return len(self.classes) @property def num_rels(self): return len(self.rel_classes) def get_rel_inds(self, rel_labels, im_inds, box_priors): # Get the relationship candidates if self.training: rel_inds = rel_labels[:, :3].data.clone() else: rel_cands = im_inds.data[:, None] == im_inds.data[None] rel_cands.view(-1)[diagonal_inds(rel_cands)] = 0 # Require overlap for detection if self.require_overlap: rel_cands = rel_cands & (bbox_overlaps(box_priors.data, box_priors.data) > 0) # if there are fewer then 100 things then we might as well add some? amt_to_add = 100 - rel_cands.long().sum() rel_cands = rel_cands.nonzero() if rel_cands.dim() == 0: rel_cands = im_inds.data.new(1, 2).fill_(0) rel_inds = torch.cat((im_inds.data[rel_cands[:, 0]][:, None], rel_cands), 1) return rel_inds def predict(self, node_feat, edge_feat, rel_inds, rois, im_sizes): raise NotImplementedError('predict') def forward(self, x, im_sizes, image_offset, gt_boxes=None, gt_classes=None, gt_rels=None, *arg): """ Forward pass for detection :param x: Images@[batch_size, 3, IM_SIZE, IM_SIZE] :param im_sizes: A numpy array of (h, w, scale) for each image. :param image_offset: Offset onto what image we're on for MGPU training (if single GPU this is 0) :param gt_boxes: Training parameters: :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2] gt boxes where each one is (img_id, class) :param train_anchor_inds: a [num_train, 2] array of indices for the anchors that will be used to compute the training loss. Each (img_ind, fpn_idx) :return: If train: scores, boxdeltas, labels, boxes, boxtargets, rpnscores, rpnboxes, rellabels if test: prob dists, boxes, img inds, maxscores, classes """ raise NotImplementedError('forward') def forward_parallel(self, batch): # define as a function here so that wandb can watch gradients """ Hack to do multi-GPU training""" batch.scatter() if self.num_gpus == 1: return self(*batch[0]) else: raise NotImplementedError('need to make sure it is correct') replicas = nn.parallel.replicate(self, devices=list(range(self.num_gpus))) outputs = nn.parallel.parallel_apply(replicas, [batch[i] for i in range(self.num_gpus)]) if self.training: return gather_res(outputs, 0, dim=0) return outputs
en
0.773978
Base class for relationship models RELATIONSHIPS :param mode: (sgcls, predcls, or sgdet) :param num_gpus: how many GPUS 2 use :param require_overlap_det: Whether two objects must intersect # See https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html # replace the pre-trained head with a new one # Get the relationship candidates # Require overlap for detection # if there are fewer then 100 things then we might as well add some? Forward pass for detection :param x: Images@[batch_size, 3, IM_SIZE, IM_SIZE] :param im_sizes: A numpy array of (h, w, scale) for each image. :param image_offset: Offset onto what image we're on for MGPU training (if single GPU this is 0) :param gt_boxes: Training parameters: :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2] gt boxes where each one is (img_id, class) :param train_anchor_inds: a [num_train, 2] array of indices for the anchors that will be used to compute the training loss. Each (img_ind, fpn_idx) :return: If train: scores, boxdeltas, labels, boxes, boxtargets, rpnscores, rpnboxes, rellabels if test: prob dists, boxes, img inds, maxscores, classes # define as a function here so that wandb can watch gradients Hack to do multi-GPU training
2.4205
2
ShortestPathGraphProject/venv/Lib/site-packages/networkx/algorithms/community/quality.py
NathanAllerton/ShortestPathGraph
445
6625092
<filename>ShortestPathGraphProject/venv/Lib/site-packages/networkx/algorithms/community/quality.py # quality.py - functions for measuring partitions of a graph # # Copyright 2015-2019 NetworkX developers. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. """Functions for measuring the quality of a partition (into communities). """ from __future__ import division from functools import wraps from itertools import product import networkx as nx from networkx import NetworkXError from networkx.utils import not_implemented_for from networkx.algorithms.community.community_utils import is_partition __all__ = ['coverage', 'modularity', 'performance'] class NotAPartition(NetworkXError): """Raised if a given collection is not a partition. """ def __init__(self, G, collection): msg = '{} is not a valid partition of the graph {}' msg = msg.format(G, collection) super(NotAPartition, self).__init__(msg) def require_partition(func): """Decorator that raises an exception if a partition is not a valid partition of the nodes of a graph. Raises :exc:`networkx.NetworkXError` if the partition is not valid. This decorator should be used on functions whose first two arguments are a graph and a partition of the nodes of that graph (in that order):: >>> @require_partition ... def foo(G, partition): ... print('partition is valid!') ... >>> G = nx.complete_graph(5) >>> partition = [{0, 1}, {2, 3}, {4}] >>> foo(G, partition) partition is valid! >>> partition = [{0}, {2, 3}, {4}] >>> foo(G, partition) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NetworkXError: `partition` is not a valid partition of the nodes of G >>> partition = [{0, 1}, {1, 2, 3}, {4}] >>> foo(G, partition) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NetworkXError: `partition` is not a valid partition of the nodes of G """ @wraps(func) def new_func(*args, **kw): # Here we assume that the first two arguments are (G, partition). if not is_partition(*args[:2]): raise nx.NetworkXError('`partition` is not a valid partition of' ' the nodes of G') return func(*args, **kw) return new_func def intra_community_edges(G, partition): """Returns the number of intra-community edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. The "intra-community edges" are those edges joining a pair of nodes in the same block of the partition. """ return sum(G.subgraph(block).size() for block in partition) def inter_community_edges(G, partition): """Returns the number of inter-community edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. The *inter-community edges* are those edges joining a pair of nodes in different blocks of the partition. Implementation note: this function creates an intermediate graph that may require the same amount of memory as required to store `G`. """ # Alternate implementation that does not require constructing a new # graph object (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in G.edges() if aff[u] != aff[v]) # if G.is_directed(): return nx.quotient_graph(G, partition, create_using=nx.MultiDiGraph()).size() else: return nx.quotient_graph(G, partition, create_using=nx.MultiGraph()).size() def inter_community_non_edges(G, partition): """Returns the number of inter-community non-edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. A *non-edge* is a pair of nodes (undirected if `G` is undirected) that are not adjacent in `G`. The *inter-community non-edges* are those non-edges on a pair of nodes in different blocks of the partition. Implementation note: this function creates two intermediate graphs, which may require up to twice the amount of memory as required to store `G`. """ # Alternate implementation that does not require constructing two # new graph objects (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v]) # return inter_community_edges(nx.complement(G), partition) @not_implemented_for('multigraph') @require_partition def performance(G, partition): """Returns the performance of a partition. The *performance* of a partition is the ratio of the number of intra-community edges plus inter-community non-edges with the total number of potential edges. Parameters ---------- G : NetworkX graph A simple graph (directed or undirected). partition : sequence Partition of the nodes of `G`, represented as a sequence of sets of nodes. Each block of the partition represents a community. Returns ------- float The performance of the partition, as defined above. Raises ------ NetworkXError If `partition` is not a valid partition of the nodes of `G`. References ---------- .. [1] <NAME>. "Community Detection in Graphs". *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174 <https://arxiv.org/abs/0906.0612> """ # Compute the number of intra-community edges and inter-community # edges. intra_edges = intra_community_edges(G, partition) inter_edges = inter_community_non_edges(G, partition) # Compute the number of edges in the complete graph (directed or # undirected, as it depends on `G`) on `n` nodes. # # (If `G` is an undirected graph, we divide by two since we have # double-counted each potential edge. We use integer division since # `total_pairs` is guaranteed to be even.) n = len(G) total_pairs = n * (n - 1) if not G.is_directed(): total_pairs //= 2 return (intra_edges + inter_edges) / total_pairs @require_partition def coverage(G, partition): """Returns the coverage of a partition. The *coverage* of a partition is the ratio of the number of intra-community edges to the total number of edges in the graph. Parameters ---------- G : NetworkX graph partition : sequence Partition of the nodes of `G`, represented as a sequence of sets of nodes. Each block of the partition represents a community. Returns ------- float The coverage of the partition, as defined above. Raises ------ NetworkXError If `partition` is not a valid partition of the nodes of `G`. Notes ----- If `G` is a multigraph, the multiplicity of edges is counted. References ---------- .. [1] <NAME>. "Community Detection in Graphs". *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174 <https://arxiv.org/abs/0906.0612> """ intra_edges = intra_community_edges(G, partition) total_edges = G.number_of_edges() return intra_edges / total_edges def modularity(G, communities, weight='weight'): r"""Returns the modularity of the given partition of the graph. Modularity is defined in [1]_ as .. math:: Q = \frac{1}{2m} \sum_{ij} \left( A_{ij} - \frac{k_ik_j}{2m}\right) \delta(c_i,c_j) where $m$ is the number of edges, $A$ is the adjacency matrix of `G`, $k_i$ is the degree of $i$ and $\delta(c_i, c_j)$ is 1 if $i$ and $j$ are in the same community and 0 otherwise. Parameters ---------- G : NetworkX Graph communities : list List of sets of nodes of `G` representing a partition of the nodes. Returns ------- Q : float The modularity of the paritition. Raises ------ NotAPartition If `communities` is not a partition of the nodes of `G`. Examples -------- >>> G = nx.barbell_graph(3, 0) >>> nx.algorithms.community.modularity(G, [{0, 1, 2}, {3, 4, 5}]) 0.35714285714285704 References ---------- .. [1] <NAME> *Networks: An Introduction*, page 224. Oxford University Press, 2011. """ if not is_partition(G, communities): raise NotAPartition(G, communities) multigraph = G.is_multigraph() directed = G.is_directed() m = G.size(weight=weight) if directed: out_degree = dict(G.out_degree(weight=weight)) in_degree = dict(G.in_degree(weight=weight)) norm = 1 / m else: out_degree = dict(G.degree(weight=weight)) in_degree = out_degree norm = 1 / (2 * m) def val(u, v): try: if multigraph: w = sum(d.get(weight, 1) for k, d in G[u][v].items()) else: w = G[u][v].get(weight, 1) except KeyError: w = 0 # Double count self-loops if the graph is undirected. if u == v and not directed: w *= 2 return w - in_degree[u] * out_degree[v] * norm Q = sum(val(u, v) for c in communities for u, v in product(c, repeat=2)) return Q * norm
<filename>ShortestPathGraphProject/venv/Lib/site-packages/networkx/algorithms/community/quality.py # quality.py - functions for measuring partitions of a graph # # Copyright 2015-2019 NetworkX developers. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. """Functions for measuring the quality of a partition (into communities). """ from __future__ import division from functools import wraps from itertools import product import networkx as nx from networkx import NetworkXError from networkx.utils import not_implemented_for from networkx.algorithms.community.community_utils import is_partition __all__ = ['coverage', 'modularity', 'performance'] class NotAPartition(NetworkXError): """Raised if a given collection is not a partition. """ def __init__(self, G, collection): msg = '{} is not a valid partition of the graph {}' msg = msg.format(G, collection) super(NotAPartition, self).__init__(msg) def require_partition(func): """Decorator that raises an exception if a partition is not a valid partition of the nodes of a graph. Raises :exc:`networkx.NetworkXError` if the partition is not valid. This decorator should be used on functions whose first two arguments are a graph and a partition of the nodes of that graph (in that order):: >>> @require_partition ... def foo(G, partition): ... print('partition is valid!') ... >>> G = nx.complete_graph(5) >>> partition = [{0, 1}, {2, 3}, {4}] >>> foo(G, partition) partition is valid! >>> partition = [{0}, {2, 3}, {4}] >>> foo(G, partition) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NetworkXError: `partition` is not a valid partition of the nodes of G >>> partition = [{0, 1}, {1, 2, 3}, {4}] >>> foo(G, partition) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NetworkXError: `partition` is not a valid partition of the nodes of G """ @wraps(func) def new_func(*args, **kw): # Here we assume that the first two arguments are (G, partition). if not is_partition(*args[:2]): raise nx.NetworkXError('`partition` is not a valid partition of' ' the nodes of G') return func(*args, **kw) return new_func def intra_community_edges(G, partition): """Returns the number of intra-community edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. The "intra-community edges" are those edges joining a pair of nodes in the same block of the partition. """ return sum(G.subgraph(block).size() for block in partition) def inter_community_edges(G, partition): """Returns the number of inter-community edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. The *inter-community edges* are those edges joining a pair of nodes in different blocks of the partition. Implementation note: this function creates an intermediate graph that may require the same amount of memory as required to store `G`. """ # Alternate implementation that does not require constructing a new # graph object (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in G.edges() if aff[u] != aff[v]) # if G.is_directed(): return nx.quotient_graph(G, partition, create_using=nx.MultiDiGraph()).size() else: return nx.quotient_graph(G, partition, create_using=nx.MultiGraph()).size() def inter_community_non_edges(G, partition): """Returns the number of inter-community non-edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. A *non-edge* is a pair of nodes (undirected if `G` is undirected) that are not adjacent in `G`. The *inter-community non-edges* are those non-edges on a pair of nodes in different blocks of the partition. Implementation note: this function creates two intermediate graphs, which may require up to twice the amount of memory as required to store `G`. """ # Alternate implementation that does not require constructing two # new graph objects (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v]) # return inter_community_edges(nx.complement(G), partition) @not_implemented_for('multigraph') @require_partition def performance(G, partition): """Returns the performance of a partition. The *performance* of a partition is the ratio of the number of intra-community edges plus inter-community non-edges with the total number of potential edges. Parameters ---------- G : NetworkX graph A simple graph (directed or undirected). partition : sequence Partition of the nodes of `G`, represented as a sequence of sets of nodes. Each block of the partition represents a community. Returns ------- float The performance of the partition, as defined above. Raises ------ NetworkXError If `partition` is not a valid partition of the nodes of `G`. References ---------- .. [1] <NAME>. "Community Detection in Graphs". *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174 <https://arxiv.org/abs/0906.0612> """ # Compute the number of intra-community edges and inter-community # edges. intra_edges = intra_community_edges(G, partition) inter_edges = inter_community_non_edges(G, partition) # Compute the number of edges in the complete graph (directed or # undirected, as it depends on `G`) on `n` nodes. # # (If `G` is an undirected graph, we divide by two since we have # double-counted each potential edge. We use integer division since # `total_pairs` is guaranteed to be even.) n = len(G) total_pairs = n * (n - 1) if not G.is_directed(): total_pairs //= 2 return (intra_edges + inter_edges) / total_pairs @require_partition def coverage(G, partition): """Returns the coverage of a partition. The *coverage* of a partition is the ratio of the number of intra-community edges to the total number of edges in the graph. Parameters ---------- G : NetworkX graph partition : sequence Partition of the nodes of `G`, represented as a sequence of sets of nodes. Each block of the partition represents a community. Returns ------- float The coverage of the partition, as defined above. Raises ------ NetworkXError If `partition` is not a valid partition of the nodes of `G`. Notes ----- If `G` is a multigraph, the multiplicity of edges is counted. References ---------- .. [1] <NAME>. "Community Detection in Graphs". *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174 <https://arxiv.org/abs/0906.0612> """ intra_edges = intra_community_edges(G, partition) total_edges = G.number_of_edges() return intra_edges / total_edges def modularity(G, communities, weight='weight'): r"""Returns the modularity of the given partition of the graph. Modularity is defined in [1]_ as .. math:: Q = \frac{1}{2m} \sum_{ij} \left( A_{ij} - \frac{k_ik_j}{2m}\right) \delta(c_i,c_j) where $m$ is the number of edges, $A$ is the adjacency matrix of `G`, $k_i$ is the degree of $i$ and $\delta(c_i, c_j)$ is 1 if $i$ and $j$ are in the same community and 0 otherwise. Parameters ---------- G : NetworkX Graph communities : list List of sets of nodes of `G` representing a partition of the nodes. Returns ------- Q : float The modularity of the paritition. Raises ------ NotAPartition If `communities` is not a partition of the nodes of `G`. Examples -------- >>> G = nx.barbell_graph(3, 0) >>> nx.algorithms.community.modularity(G, [{0, 1, 2}, {3, 4, 5}]) 0.35714285714285704 References ---------- .. [1] <NAME> *Networks: An Introduction*, page 224. Oxford University Press, 2011. """ if not is_partition(G, communities): raise NotAPartition(G, communities) multigraph = G.is_multigraph() directed = G.is_directed() m = G.size(weight=weight) if directed: out_degree = dict(G.out_degree(weight=weight)) in_degree = dict(G.in_degree(weight=weight)) norm = 1 / m else: out_degree = dict(G.degree(weight=weight)) in_degree = out_degree norm = 1 / (2 * m) def val(u, v): try: if multigraph: w = sum(d.get(weight, 1) for k, d in G[u][v].items()) else: w = G[u][v].get(weight, 1) except KeyError: w = 0 # Double count self-loops if the graph is undirected. if u == v and not directed: w *= 2 return w - in_degree[u] * out_degree[v] * norm Q = sum(val(u, v) for c in communities for u, v in product(c, repeat=2)) return Q * norm
en
0.826519
# quality.py - functions for measuring partitions of a graph # # Copyright 2015-2019 NetworkX developers. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. Functions for measuring the quality of a partition (into communities). Raised if a given collection is not a partition. Decorator that raises an exception if a partition is not a valid partition of the nodes of a graph. Raises :exc:`networkx.NetworkXError` if the partition is not valid. This decorator should be used on functions whose first two arguments are a graph and a partition of the nodes of that graph (in that order):: >>> @require_partition ... def foo(G, partition): ... print('partition is valid!') ... >>> G = nx.complete_graph(5) >>> partition = [{0, 1}, {2, 3}, {4}] >>> foo(G, partition) partition is valid! >>> partition = [{0}, {2, 3}, {4}] >>> foo(G, partition) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NetworkXError: `partition` is not a valid partition of the nodes of G >>> partition = [{0, 1}, {1, 2, 3}, {4}] >>> foo(G, partition) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NetworkXError: `partition` is not a valid partition of the nodes of G # Here we assume that the first two arguments are (G, partition). Returns the number of intra-community edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. The "intra-community edges" are those edges joining a pair of nodes in the same block of the partition. Returns the number of inter-community edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. The *inter-community edges* are those edges joining a pair of nodes in different blocks of the partition. Implementation note: this function creates an intermediate graph that may require the same amount of memory as required to store `G`. # Alternate implementation that does not require constructing a new # graph object (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in G.edges() if aff[u] != aff[v]) # Returns the number of inter-community non-edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. A *non-edge* is a pair of nodes (undirected if `G` is undirected) that are not adjacent in `G`. The *inter-community non-edges* are those non-edges on a pair of nodes in different blocks of the partition. Implementation note: this function creates two intermediate graphs, which may require up to twice the amount of memory as required to store `G`. # Alternate implementation that does not require constructing two # new graph objects (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v]) # Returns the performance of a partition. The *performance* of a partition is the ratio of the number of intra-community edges plus inter-community non-edges with the total number of potential edges. Parameters ---------- G : NetworkX graph A simple graph (directed or undirected). partition : sequence Partition of the nodes of `G`, represented as a sequence of sets of nodes. Each block of the partition represents a community. Returns ------- float The performance of the partition, as defined above. Raises ------ NetworkXError If `partition` is not a valid partition of the nodes of `G`. References ---------- .. [1] <NAME>. "Community Detection in Graphs". *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174 <https://arxiv.org/abs/0906.0612> # Compute the number of intra-community edges and inter-community # edges. # Compute the number of edges in the complete graph (directed or # undirected, as it depends on `G`) on `n` nodes. # # (If `G` is an undirected graph, we divide by two since we have # double-counted each potential edge. We use integer division since # `total_pairs` is guaranteed to be even.) Returns the coverage of a partition. The *coverage* of a partition is the ratio of the number of intra-community edges to the total number of edges in the graph. Parameters ---------- G : NetworkX graph partition : sequence Partition of the nodes of `G`, represented as a sequence of sets of nodes. Each block of the partition represents a community. Returns ------- float The coverage of the partition, as defined above. Raises ------ NetworkXError If `partition` is not a valid partition of the nodes of `G`. Notes ----- If `G` is a multigraph, the multiplicity of edges is counted. References ---------- .. [1] <NAME>. "Community Detection in Graphs". *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174 <https://arxiv.org/abs/0906.0612> Returns the modularity of the given partition of the graph. Modularity is defined in [1]_ as .. math:: Q = \frac{1}{2m} \sum_{ij} \left( A_{ij} - \frac{k_ik_j}{2m}\right) \delta(c_i,c_j) where $m$ is the number of edges, $A$ is the adjacency matrix of `G`, $k_i$ is the degree of $i$ and $\delta(c_i, c_j)$ is 1 if $i$ and $j$ are in the same community and 0 otherwise. Parameters ---------- G : NetworkX Graph communities : list List of sets of nodes of `G` representing a partition of the nodes. Returns ------- Q : float The modularity of the paritition. Raises ------ NotAPartition If `communities` is not a partition of the nodes of `G`. Examples -------- >>> G = nx.barbell_graph(3, 0) >>> nx.algorithms.community.modularity(G, [{0, 1, 2}, {3, 4, 5}]) 0.35714285714285704 References ---------- .. [1] <NAME> *Networks: An Introduction*, page 224. Oxford University Press, 2011. # Double count self-loops if the graph is undirected.
2.694675
3
scripts/update_now.py
DS1SQM/OPKR081R3_201230
0
6625093
#!/usr/bin/env python3 import datetime from common.params import Params from selfdrive.data_collection import gps_uploader print("Don't forget to pray!") params = Params() t = datetime.datetime.utcnow().isoformat() params.put("LastUpdateTime", t.encode('utf8')) if params.get("IsOffroad") == b"1": print("Please wait for gps to upload to aviod this in future!") gps_uploader.upload_data() else: print("Please switch off car and try again!")
#!/usr/bin/env python3 import datetime from common.params import Params from selfdrive.data_collection import gps_uploader print("Don't forget to pray!") params = Params() t = datetime.datetime.utcnow().isoformat() params.put("LastUpdateTime", t.encode('utf8')) if params.get("IsOffroad") == b"1": print("Please wait for gps to upload to aviod this in future!") gps_uploader.upload_data() else: print("Please switch off car and try again!")
fr
0.221828
#!/usr/bin/env python3
2.907248
3
bleach/sanitizer.py
bope/bleach
0
6625094
from __future__ import unicode_literals from itertools import chain import re import six from six.moves.urllib.parse import urlparse from xml.sax.saxutils import unescape from bleach import html5lib_shim from bleach.utils import alphabetize_attributes, force_unicode #: List of allowed tags ALLOWED_TAGS = [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul', ] #: Map of allowed attributes by tag ALLOWED_ATTRIBUTES = { 'a': ['href', 'title'], 'abbr': ['title'], 'acronym': ['title'], } #: List of allowed styles ALLOWED_STYLES = [] #: List of allowed protocols ALLOWED_PROTOCOLS = ['http', 'https', 'mailto'] #: Invisible characters--0 to and including 31 except 9 (tab), 10 (lf), and 13 (cr) INVISIBLE_CHARACTERS = ''.join([chr(c) for c in chain(range(0, 9), range(11, 13), range(14, 32))]) #: Regexp for characters that are invisible INVISIBLE_CHARACTERS_RE = re.compile( '[' + INVISIBLE_CHARACTERS + ']', re.UNICODE ) #: String to replace invisible characters with. This can be a character, a #: string, or even a function that takes a Python re matchobj INVISIBLE_REPLACEMENT_CHAR = '?' class Cleaner(object): """Cleaner for cleaning HTML fragments of malicious content This cleaner is a security-focused function whose sole purpose is to remove malicious content from a string such that it can be displayed as content in a web page. To use:: from bleach.sanitizer import Cleaner cleaner = Cleaner() for text in all_the_yucky_things: sanitized = cleaner.clean(text) .. Note:: This cleaner is not designed to use to transform content to be used in non-web-page contexts. .. Warning:: This cleaner is not thread-safe--the html parser has internal state. Create a separate cleaner per thread! """ def __init__(self, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, styles=ALLOWED_STYLES, protocols=ALLOWED_PROTOCOLS, strip=False, strip_comments=True, filters=None): """Initializes a Cleaner :arg list tags: allowed list of tags; defaults to ``bleach.sanitizer.ALLOWED_TAGS`` :arg dict attributes: allowed attributes; can be a callable, list or dict; defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES`` :arg list styles: allowed list of css styles; defaults to ``bleach.sanitizer.ALLOWED_STYLES`` :arg list protocols: allowed list of protocols for links; defaults to ``bleach.sanitizer.ALLOWED_PROTOCOLS`` :arg bool strip: whether or not to strip disallowed elements :arg bool strip_comments: whether or not to strip HTML comments :arg list filters: list of html5lib Filter classes to pass streamed content through .. seealso:: http://html5lib.readthedocs.io/en/latest/movingparts.html#filters .. Warning:: Using filters changes the output of ``bleach.Cleaner.clean``. Make sure the way the filters change the output are secure. """ self.tags = tags self.attributes = attributes self.styles = styles self.protocols = protocols self.strip = strip self.strip_comments = strip_comments self.filters = filters or [] self.parser = html5lib_shim.BleachHTMLParser( tags=self.tags, strip=self.strip, consume_entities=False, namespaceHTMLElements=False ) self.walker = html5lib_shim.getTreeWalker('etree') self.serializer = html5lib_shim.BleachHTMLSerializer( quote_attr_values='always', omit_optional_tags=False, escape_lt_in_attrs=True, # We want to leave entities as they are without escaping or # resolving or expanding resolve_entities=False, # Bleach has its own sanitizer, so don't use the html5lib one sanitize=False, # Bleach sanitizer alphabetizes already, so don't use the html5lib one alphabetical_attributes=False, ) def clean(self, text): """Cleans text and returns sanitized result as unicode :arg str text: text to be cleaned :returns: sanitized text as unicode :raises TypeError: if ``text`` is not a text type """ if not isinstance(text, six.string_types): message = "argument cannot be of '{name}' type, must be of text type".format( name=text.__class__.__name__) raise TypeError(message) if not text: return '' text = force_unicode(text) dom = self.parser.parseFragment(text) filtered = BleachSanitizerFilter( source=self.walker(dom), # Bleach-sanitizer-specific things attributes=self.attributes, strip_disallowed_elements=self.strip, strip_html_comments=self.strip_comments, # html5lib-sanitizer things allowed_elements=self.tags, allowed_css_properties=self.styles, allowed_protocols=self.protocols, allowed_svg_properties=[], ) # Apply any filters after the BleachSanitizerFilter for filter_class in self.filters: filtered = filter_class(source=filtered) return self.serializer.render(filtered) def attribute_filter_factory(attributes): """Generates attribute filter function for the given attributes value The attributes value can take one of several shapes. This returns a filter function appropriate to the attributes value. One nice thing about this is that there's less if/then shenanigans in the ``allow_token`` method. """ if callable(attributes): return attributes if isinstance(attributes, dict): def _attr_filter(tag, attr, value): if tag in attributes: attr_val = attributes[tag] if callable(attr_val): return attr_val(tag, attr, value) if attr in attr_val: return True if '*' in attributes: attr_val = attributes['*'] if callable(attr_val): return attr_val(tag, attr, value) return attr in attr_val return False return _attr_filter if isinstance(attributes, list): def _attr_filter(tag, attr, value): return attr in attributes return _attr_filter raise ValueError('attributes needs to be a callable, a list or a dict') class BleachSanitizerFilter(html5lib_shim.SanitizerFilter): """html5lib Filter that sanitizes text This filter can be used anywhere html5lib filters can be used. """ def __init__(self, source, attributes=ALLOWED_ATTRIBUTES, strip_disallowed_elements=False, strip_html_comments=True, **kwargs): """Creates a BleachSanitizerFilter instance :arg Treewalker source: stream :arg list tags: allowed list of tags; defaults to ``bleach.sanitizer.ALLOWED_TAGS`` :arg dict attributes: allowed attributes; can be a callable, list or dict; defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES`` :arg list styles: allowed list of css styles; defaults to ``bleach.sanitizer.ALLOWED_STYLES`` :arg list protocols: allowed list of protocols for links; defaults to ``bleach.sanitizer.ALLOWED_PROTOCOLS`` :arg bool strip_disallowed_elements: whether or not to strip disallowed elements :arg bool strip_html_comments: whether or not to strip HTML comments """ self.attr_filter = attribute_filter_factory(attributes) self.strip_disallowed_elements = strip_disallowed_elements self.strip_html_comments = strip_html_comments return super(BleachSanitizerFilter, self).__init__(source, **kwargs) def sanitize_stream(self, token_iterator): for token in token_iterator: ret = self.sanitize_token(token) if not ret: continue if isinstance(ret, list): for subtoken in ret: yield subtoken else: yield ret def merge_characters(self, token_iterator): """Merge consecutive Characters tokens in a stream""" characters_buffer = [] for token in token_iterator: if characters_buffer: if token['type'] == 'Characters': characters_buffer.append(token) continue else: # Merge all the characters tokens together into one and then # operate on it. new_token = { 'data': ''.join([char_token['data'] for char_token in characters_buffer]), 'type': 'Characters' } characters_buffer = [] yield new_token elif token['type'] == 'Characters': characters_buffer.append(token) continue yield token new_token = { 'data': ''.join([char_token['data'] for char_token in characters_buffer]), 'type': 'Characters' } yield new_token def __iter__(self): return self.merge_characters(self.sanitize_stream(html5lib_shim.Filter.__iter__(self))) def sanitize_token(self, token): """Sanitize a token either by HTML-encoding or dropping. Unlike sanitizer.Filter, allowed_attributes can be a dict of {'tag': ['attribute', 'pairs'], 'tag': callable}. Here callable is a function with two arguments of attribute name and value. It should return true of false. Also gives the option to strip tags instead of encoding. :arg dict token: token to sanitize :returns: token or list of tokens """ token_type = token['type'] if token_type in ['StartTag', 'EndTag', 'EmptyTag']: if token['name'] in self.allowed_elements: return self.allow_token(token) elif self.strip_disallowed_elements: return None else: if 'data' in token: # Alphabetize the attributes before calling .disallowed_token() # so that the resulting string is stable token['data'] = alphabetize_attributes(token['data']) return self.disallowed_token(token) elif token_type == 'Comment': if not self.strip_html_comments: return token else: return None elif token_type == 'Characters': return self.sanitize_characters(token) else: return token def sanitize_characters(self, token): """Handles Characters tokens Our overridden tokenizer doesn't do anything with entities. However, that means that the serializer will convert all ``&`` in Characters tokens to ``&amp;``. Since we don't want that, we extract entities here and convert them to Entity tokens so the serializer will let them be. :arg token: the Characters token to work on :returns: a list of tokens """ data = token.get('data', '') if not data: return token data = INVISIBLE_CHARACTERS_RE.sub(INVISIBLE_REPLACEMENT_CHAR, data) token['data'] = data # If there isn't a & in the data, we can return now if '&' not in data: return token new_tokens = [] # For each possible entity that starts with a "&", we try to extract an # actual entity and re-tokenize accordingly for part in html5lib_shim.next_possible_entity(data): if not part: continue if part.startswith('&'): entity = html5lib_shim.match_entity(part) if entity is not None: if entity == 'amp': # LinkifyFilter can't match urls across token boundaries # which is problematic with &amp; since that shows up in # querystrings all the time. This special-cases &amp; # and converts it to a & and sticks it in as a # Characters token. It'll get merged with surrounding # tokens in the BleachSanitizerfilter.__iter__ and # escaped in the serializer. new_tokens.append({'type': 'Characters', 'data': '&'}) else: new_tokens.append({'type': 'Entity', 'name': entity}) # Length of the entity plus 2--one for & at the beginning # and and one for ; at the end remainder = part[len(entity) + 2:] if remainder: new_tokens.append({'type': 'Characters', 'data': remainder}) continue new_tokens.append({'type': 'Characters', 'data': part}) return new_tokens def sanitize_uri_value(self, value, allowed_protocols): """Checks a uri value to see if it's allowed :arg value: the uri value to sanitize :arg allowed_protocols: list of allowed protocols :returns: allowed value or None """ # NOTE(willkg): This transforms the value into one that's easier to # match and verify, but shouldn't get returned since it's vastly # different than the original value. # Convert all character entities in the value new_value = html5lib_shim.convert_entities(value) # Nix backtick, space characters, and control characters new_value = re.sub( r"[`\000-\040\177-\240\s]+", '', new_value ) # Remove REPLACEMENT characters new_value = new_value.replace('\ufffd', '') # Lowercase it--this breaks the value, but makes it easier to match # against new_value = new_value.lower() try: # Drop attributes with uri values that have protocols that aren't # allowed parsed = urlparse(new_value) except ValueError: # URI is impossible to parse, therefore it's not allowed return None if parsed.scheme: # If urlparse found a scheme, check that if parsed.scheme in allowed_protocols: return value else: # Allow uris that are just an anchor if new_value.startswith('#'): return value # Handle protocols that urlparse doesn't recognize like "myprotocol" if ':' in new_value and new_value.split(':')[0] in allowed_protocols: return value # If there's no protocol/scheme specified, then assume it's "http" # and see if that's allowed if 'http' in allowed_protocols: return value return None def allow_token(self, token): """Handles the case where we're allowing the tag""" if 'data' in token: # Loop through all the attributes and drop the ones that are not # allowed, are unsafe or break other rules. Additionally, fix # attribute values that need fixing. # # At the end of this loop, we have the final set of attributes # we're keeping. attrs = {} for namespaced_name, val in token['data'].items(): namespace, name = namespaced_name # Drop attributes that are not explicitly allowed # # NOTE(willkg): We pass in the attribute name--not a namespaced # name. if not self.attr_filter(token['name'], name, val): continue # Drop attributes with uri values that use a disallowed protocol # Sanitize attributes with uri values if namespaced_name in self.attr_val_is_uri: new_value = self.sanitize_uri_value(val, self.allowed_protocols) if new_value is None: continue val = new_value # Drop values in svg attrs with non-local IRIs if namespaced_name in self.svg_attr_val_allows_ref: new_val = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', ' ', unescape(val)) new_val = new_val.strip() if not new_val: continue else: # Replace the val with the unescaped version because # it's a iri val = new_val # Drop href and xlink:href attr for svg elements with non-local IRIs if (None, token['name']) in self.svg_allow_local_href: if namespaced_name in [ (None, 'href'), (html5lib_shim.namespaces['xlink'], 'href') ]: if re.search(r'^\s*[^#\s]', val): continue # If it's a style attribute, sanitize it if namespaced_name == (None, 'style'): val = self.sanitize_css(val) # At this point, we want to keep the attribute, so add it in attrs[namespaced_name] = val token['data'] = alphabetize_attributes(attrs) return token def disallowed_token(self, token): token_type = token["type"] if token_type == "EndTag": token["data"] = "</%s>" % token["name"] elif token["data"]: assert token_type in ("StartTag", "EmptyTag") attrs = [] for (ns, name), v in token["data"].items(): # If we end up with a namespace, but no name, switch them so we # have a valid name to use. if ns and not name: ns, name = name, ns # Figure out namespaced name if the namespace is appropriate # and exists; if the ns isn't in prefixes, then drop it. if ns is None or ns not in html5lib_shim.prefixes: namespaced_name = name else: namespaced_name = '%s:%s' % (html5lib_shim.prefixes[ns], name) attrs.append(' %s="%s"' % ( namespaced_name, # NOTE(willkg): HTMLSerializer escapes attribute values # already, so if we do it here (like HTMLSerializer does), # then we end up double-escaping. v) ) token["data"] = "<%s%s>" % (token["name"], ''.join(attrs)) else: token["data"] = "<%s>" % token["name"] if token.get("selfClosing"): token["data"] = token["data"][:-1] + "/>" token["type"] = "Characters" del token["name"] return token def sanitize_css(self, style): """Sanitizes css in style tags""" # Convert entities in the style so that it can be parsed as CSS style = html5lib_shim.convert_entities(style) # Drop any url values before we do anything else style = re.compile(r'url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) # The gauntlet of sanitization # Validate the css in the style tag and if it's not valid, then drop # the whole thing. parts = style.split(';') gauntlet = re.compile( r"""^([-/:,#%.'"\s!\w]|\w-\w|'[\s\w]+'\s*|"[\s\w]+"|\([\d,%\.\s]+\))*$""", flags=re.U ) for part in parts: if not gauntlet.match(part): return '' if not re.match(r"^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): return '' clean = [] for prop, value in re.findall(r'([-\w]+)\s*:\s*([^:;]*)', style): if not value: continue if prop.lower() in self.allowed_css_properties: clean.append(prop + ': ' + value + ';') elif prop.lower() in self.allowed_svg_properties: clean.append(prop + ': ' + value + ';') return ' '.join(clean)
from __future__ import unicode_literals from itertools import chain import re import six from six.moves.urllib.parse import urlparse from xml.sax.saxutils import unescape from bleach import html5lib_shim from bleach.utils import alphabetize_attributes, force_unicode #: List of allowed tags ALLOWED_TAGS = [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul', ] #: Map of allowed attributes by tag ALLOWED_ATTRIBUTES = { 'a': ['href', 'title'], 'abbr': ['title'], 'acronym': ['title'], } #: List of allowed styles ALLOWED_STYLES = [] #: List of allowed protocols ALLOWED_PROTOCOLS = ['http', 'https', 'mailto'] #: Invisible characters--0 to and including 31 except 9 (tab), 10 (lf), and 13 (cr) INVISIBLE_CHARACTERS = ''.join([chr(c) for c in chain(range(0, 9), range(11, 13), range(14, 32))]) #: Regexp for characters that are invisible INVISIBLE_CHARACTERS_RE = re.compile( '[' + INVISIBLE_CHARACTERS + ']', re.UNICODE ) #: String to replace invisible characters with. This can be a character, a #: string, or even a function that takes a Python re matchobj INVISIBLE_REPLACEMENT_CHAR = '?' class Cleaner(object): """Cleaner for cleaning HTML fragments of malicious content This cleaner is a security-focused function whose sole purpose is to remove malicious content from a string such that it can be displayed as content in a web page. To use:: from bleach.sanitizer import Cleaner cleaner = Cleaner() for text in all_the_yucky_things: sanitized = cleaner.clean(text) .. Note:: This cleaner is not designed to use to transform content to be used in non-web-page contexts. .. Warning:: This cleaner is not thread-safe--the html parser has internal state. Create a separate cleaner per thread! """ def __init__(self, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, styles=ALLOWED_STYLES, protocols=ALLOWED_PROTOCOLS, strip=False, strip_comments=True, filters=None): """Initializes a Cleaner :arg list tags: allowed list of tags; defaults to ``bleach.sanitizer.ALLOWED_TAGS`` :arg dict attributes: allowed attributes; can be a callable, list or dict; defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES`` :arg list styles: allowed list of css styles; defaults to ``bleach.sanitizer.ALLOWED_STYLES`` :arg list protocols: allowed list of protocols for links; defaults to ``bleach.sanitizer.ALLOWED_PROTOCOLS`` :arg bool strip: whether or not to strip disallowed elements :arg bool strip_comments: whether or not to strip HTML comments :arg list filters: list of html5lib Filter classes to pass streamed content through .. seealso:: http://html5lib.readthedocs.io/en/latest/movingparts.html#filters .. Warning:: Using filters changes the output of ``bleach.Cleaner.clean``. Make sure the way the filters change the output are secure. """ self.tags = tags self.attributes = attributes self.styles = styles self.protocols = protocols self.strip = strip self.strip_comments = strip_comments self.filters = filters or [] self.parser = html5lib_shim.BleachHTMLParser( tags=self.tags, strip=self.strip, consume_entities=False, namespaceHTMLElements=False ) self.walker = html5lib_shim.getTreeWalker('etree') self.serializer = html5lib_shim.BleachHTMLSerializer( quote_attr_values='always', omit_optional_tags=False, escape_lt_in_attrs=True, # We want to leave entities as they are without escaping or # resolving or expanding resolve_entities=False, # Bleach has its own sanitizer, so don't use the html5lib one sanitize=False, # Bleach sanitizer alphabetizes already, so don't use the html5lib one alphabetical_attributes=False, ) def clean(self, text): """Cleans text and returns sanitized result as unicode :arg str text: text to be cleaned :returns: sanitized text as unicode :raises TypeError: if ``text`` is not a text type """ if not isinstance(text, six.string_types): message = "argument cannot be of '{name}' type, must be of text type".format( name=text.__class__.__name__) raise TypeError(message) if not text: return '' text = force_unicode(text) dom = self.parser.parseFragment(text) filtered = BleachSanitizerFilter( source=self.walker(dom), # Bleach-sanitizer-specific things attributes=self.attributes, strip_disallowed_elements=self.strip, strip_html_comments=self.strip_comments, # html5lib-sanitizer things allowed_elements=self.tags, allowed_css_properties=self.styles, allowed_protocols=self.protocols, allowed_svg_properties=[], ) # Apply any filters after the BleachSanitizerFilter for filter_class in self.filters: filtered = filter_class(source=filtered) return self.serializer.render(filtered) def attribute_filter_factory(attributes): """Generates attribute filter function for the given attributes value The attributes value can take one of several shapes. This returns a filter function appropriate to the attributes value. One nice thing about this is that there's less if/then shenanigans in the ``allow_token`` method. """ if callable(attributes): return attributes if isinstance(attributes, dict): def _attr_filter(tag, attr, value): if tag in attributes: attr_val = attributes[tag] if callable(attr_val): return attr_val(tag, attr, value) if attr in attr_val: return True if '*' in attributes: attr_val = attributes['*'] if callable(attr_val): return attr_val(tag, attr, value) return attr in attr_val return False return _attr_filter if isinstance(attributes, list): def _attr_filter(tag, attr, value): return attr in attributes return _attr_filter raise ValueError('attributes needs to be a callable, a list or a dict') class BleachSanitizerFilter(html5lib_shim.SanitizerFilter): """html5lib Filter that sanitizes text This filter can be used anywhere html5lib filters can be used. """ def __init__(self, source, attributes=ALLOWED_ATTRIBUTES, strip_disallowed_elements=False, strip_html_comments=True, **kwargs): """Creates a BleachSanitizerFilter instance :arg Treewalker source: stream :arg list tags: allowed list of tags; defaults to ``bleach.sanitizer.ALLOWED_TAGS`` :arg dict attributes: allowed attributes; can be a callable, list or dict; defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES`` :arg list styles: allowed list of css styles; defaults to ``bleach.sanitizer.ALLOWED_STYLES`` :arg list protocols: allowed list of protocols for links; defaults to ``bleach.sanitizer.ALLOWED_PROTOCOLS`` :arg bool strip_disallowed_elements: whether or not to strip disallowed elements :arg bool strip_html_comments: whether or not to strip HTML comments """ self.attr_filter = attribute_filter_factory(attributes) self.strip_disallowed_elements = strip_disallowed_elements self.strip_html_comments = strip_html_comments return super(BleachSanitizerFilter, self).__init__(source, **kwargs) def sanitize_stream(self, token_iterator): for token in token_iterator: ret = self.sanitize_token(token) if not ret: continue if isinstance(ret, list): for subtoken in ret: yield subtoken else: yield ret def merge_characters(self, token_iterator): """Merge consecutive Characters tokens in a stream""" characters_buffer = [] for token in token_iterator: if characters_buffer: if token['type'] == 'Characters': characters_buffer.append(token) continue else: # Merge all the characters tokens together into one and then # operate on it. new_token = { 'data': ''.join([char_token['data'] for char_token in characters_buffer]), 'type': 'Characters' } characters_buffer = [] yield new_token elif token['type'] == 'Characters': characters_buffer.append(token) continue yield token new_token = { 'data': ''.join([char_token['data'] for char_token in characters_buffer]), 'type': 'Characters' } yield new_token def __iter__(self): return self.merge_characters(self.sanitize_stream(html5lib_shim.Filter.__iter__(self))) def sanitize_token(self, token): """Sanitize a token either by HTML-encoding or dropping. Unlike sanitizer.Filter, allowed_attributes can be a dict of {'tag': ['attribute', 'pairs'], 'tag': callable}. Here callable is a function with two arguments of attribute name and value. It should return true of false. Also gives the option to strip tags instead of encoding. :arg dict token: token to sanitize :returns: token or list of tokens """ token_type = token['type'] if token_type in ['StartTag', 'EndTag', 'EmptyTag']: if token['name'] in self.allowed_elements: return self.allow_token(token) elif self.strip_disallowed_elements: return None else: if 'data' in token: # Alphabetize the attributes before calling .disallowed_token() # so that the resulting string is stable token['data'] = alphabetize_attributes(token['data']) return self.disallowed_token(token) elif token_type == 'Comment': if not self.strip_html_comments: return token else: return None elif token_type == 'Characters': return self.sanitize_characters(token) else: return token def sanitize_characters(self, token): """Handles Characters tokens Our overridden tokenizer doesn't do anything with entities. However, that means that the serializer will convert all ``&`` in Characters tokens to ``&amp;``. Since we don't want that, we extract entities here and convert them to Entity tokens so the serializer will let them be. :arg token: the Characters token to work on :returns: a list of tokens """ data = token.get('data', '') if not data: return token data = INVISIBLE_CHARACTERS_RE.sub(INVISIBLE_REPLACEMENT_CHAR, data) token['data'] = data # If there isn't a & in the data, we can return now if '&' not in data: return token new_tokens = [] # For each possible entity that starts with a "&", we try to extract an # actual entity and re-tokenize accordingly for part in html5lib_shim.next_possible_entity(data): if not part: continue if part.startswith('&'): entity = html5lib_shim.match_entity(part) if entity is not None: if entity == 'amp': # LinkifyFilter can't match urls across token boundaries # which is problematic with &amp; since that shows up in # querystrings all the time. This special-cases &amp; # and converts it to a & and sticks it in as a # Characters token. It'll get merged with surrounding # tokens in the BleachSanitizerfilter.__iter__ and # escaped in the serializer. new_tokens.append({'type': 'Characters', 'data': '&'}) else: new_tokens.append({'type': 'Entity', 'name': entity}) # Length of the entity plus 2--one for & at the beginning # and and one for ; at the end remainder = part[len(entity) + 2:] if remainder: new_tokens.append({'type': 'Characters', 'data': remainder}) continue new_tokens.append({'type': 'Characters', 'data': part}) return new_tokens def sanitize_uri_value(self, value, allowed_protocols): """Checks a uri value to see if it's allowed :arg value: the uri value to sanitize :arg allowed_protocols: list of allowed protocols :returns: allowed value or None """ # NOTE(willkg): This transforms the value into one that's easier to # match and verify, but shouldn't get returned since it's vastly # different than the original value. # Convert all character entities in the value new_value = html5lib_shim.convert_entities(value) # Nix backtick, space characters, and control characters new_value = re.sub( r"[`\000-\040\177-\240\s]+", '', new_value ) # Remove REPLACEMENT characters new_value = new_value.replace('\ufffd', '') # Lowercase it--this breaks the value, but makes it easier to match # against new_value = new_value.lower() try: # Drop attributes with uri values that have protocols that aren't # allowed parsed = urlparse(new_value) except ValueError: # URI is impossible to parse, therefore it's not allowed return None if parsed.scheme: # If urlparse found a scheme, check that if parsed.scheme in allowed_protocols: return value else: # Allow uris that are just an anchor if new_value.startswith('#'): return value # Handle protocols that urlparse doesn't recognize like "myprotocol" if ':' in new_value and new_value.split(':')[0] in allowed_protocols: return value # If there's no protocol/scheme specified, then assume it's "http" # and see if that's allowed if 'http' in allowed_protocols: return value return None def allow_token(self, token): """Handles the case where we're allowing the tag""" if 'data' in token: # Loop through all the attributes and drop the ones that are not # allowed, are unsafe or break other rules. Additionally, fix # attribute values that need fixing. # # At the end of this loop, we have the final set of attributes # we're keeping. attrs = {} for namespaced_name, val in token['data'].items(): namespace, name = namespaced_name # Drop attributes that are not explicitly allowed # # NOTE(willkg): We pass in the attribute name--not a namespaced # name. if not self.attr_filter(token['name'], name, val): continue # Drop attributes with uri values that use a disallowed protocol # Sanitize attributes with uri values if namespaced_name in self.attr_val_is_uri: new_value = self.sanitize_uri_value(val, self.allowed_protocols) if new_value is None: continue val = new_value # Drop values in svg attrs with non-local IRIs if namespaced_name in self.svg_attr_val_allows_ref: new_val = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', ' ', unescape(val)) new_val = new_val.strip() if not new_val: continue else: # Replace the val with the unescaped version because # it's a iri val = new_val # Drop href and xlink:href attr for svg elements with non-local IRIs if (None, token['name']) in self.svg_allow_local_href: if namespaced_name in [ (None, 'href'), (html5lib_shim.namespaces['xlink'], 'href') ]: if re.search(r'^\s*[^#\s]', val): continue # If it's a style attribute, sanitize it if namespaced_name == (None, 'style'): val = self.sanitize_css(val) # At this point, we want to keep the attribute, so add it in attrs[namespaced_name] = val token['data'] = alphabetize_attributes(attrs) return token def disallowed_token(self, token): token_type = token["type"] if token_type == "EndTag": token["data"] = "</%s>" % token["name"] elif token["data"]: assert token_type in ("StartTag", "EmptyTag") attrs = [] for (ns, name), v in token["data"].items(): # If we end up with a namespace, but no name, switch them so we # have a valid name to use. if ns and not name: ns, name = name, ns # Figure out namespaced name if the namespace is appropriate # and exists; if the ns isn't in prefixes, then drop it. if ns is None or ns not in html5lib_shim.prefixes: namespaced_name = name else: namespaced_name = '%s:%s' % (html5lib_shim.prefixes[ns], name) attrs.append(' %s="%s"' % ( namespaced_name, # NOTE(willkg): HTMLSerializer escapes attribute values # already, so if we do it here (like HTMLSerializer does), # then we end up double-escaping. v) ) token["data"] = "<%s%s>" % (token["name"], ''.join(attrs)) else: token["data"] = "<%s>" % token["name"] if token.get("selfClosing"): token["data"] = token["data"][:-1] + "/>" token["type"] = "Characters" del token["name"] return token def sanitize_css(self, style): """Sanitizes css in style tags""" # Convert entities in the style so that it can be parsed as CSS style = html5lib_shim.convert_entities(style) # Drop any url values before we do anything else style = re.compile(r'url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) # The gauntlet of sanitization # Validate the css in the style tag and if it's not valid, then drop # the whole thing. parts = style.split(';') gauntlet = re.compile( r"""^([-/:,#%.'"\s!\w]|\w-\w|'[\s\w]+'\s*|"[\s\w]+"|\([\d,%\.\s]+\))*$""", flags=re.U ) for part in parts: if not gauntlet.match(part): return '' if not re.match(r"^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): return '' clean = [] for prop, value in re.findall(r'([-\w]+)\s*:\s*([^:;]*)', style): if not value: continue if prop.lower() in self.allowed_css_properties: clean.append(prop + ': ' + value + ';') elif prop.lower() in self.allowed_svg_properties: clean.append(prop + ': ' + value + ';') return ' '.join(clean)
en
0.7954
#: List of allowed tags #: Map of allowed attributes by tag #: List of allowed styles #: List of allowed protocols #: Invisible characters--0 to and including 31 except 9 (tab), 10 (lf), and 13 (cr) #: Regexp for characters that are invisible #: String to replace invisible characters with. This can be a character, a #: string, or even a function that takes a Python re matchobj Cleaner for cleaning HTML fragments of malicious content This cleaner is a security-focused function whose sole purpose is to remove malicious content from a string such that it can be displayed as content in a web page. To use:: from bleach.sanitizer import Cleaner cleaner = Cleaner() for text in all_the_yucky_things: sanitized = cleaner.clean(text) .. Note:: This cleaner is not designed to use to transform content to be used in non-web-page contexts. .. Warning:: This cleaner is not thread-safe--the html parser has internal state. Create a separate cleaner per thread! Initializes a Cleaner :arg list tags: allowed list of tags; defaults to ``bleach.sanitizer.ALLOWED_TAGS`` :arg dict attributes: allowed attributes; can be a callable, list or dict; defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES`` :arg list styles: allowed list of css styles; defaults to ``bleach.sanitizer.ALLOWED_STYLES`` :arg list protocols: allowed list of protocols for links; defaults to ``bleach.sanitizer.ALLOWED_PROTOCOLS`` :arg bool strip: whether or not to strip disallowed elements :arg bool strip_comments: whether or not to strip HTML comments :arg list filters: list of html5lib Filter classes to pass streamed content through .. seealso:: http://html5lib.readthedocs.io/en/latest/movingparts.html#filters .. Warning:: Using filters changes the output of ``bleach.Cleaner.clean``. Make sure the way the filters change the output are secure. # We want to leave entities as they are without escaping or # resolving or expanding # Bleach has its own sanitizer, so don't use the html5lib one # Bleach sanitizer alphabetizes already, so don't use the html5lib one Cleans text and returns sanitized result as unicode :arg str text: text to be cleaned :returns: sanitized text as unicode :raises TypeError: if ``text`` is not a text type # Bleach-sanitizer-specific things # html5lib-sanitizer things # Apply any filters after the BleachSanitizerFilter Generates attribute filter function for the given attributes value The attributes value can take one of several shapes. This returns a filter function appropriate to the attributes value. One nice thing about this is that there's less if/then shenanigans in the ``allow_token`` method. html5lib Filter that sanitizes text This filter can be used anywhere html5lib filters can be used. Creates a BleachSanitizerFilter instance :arg Treewalker source: stream :arg list tags: allowed list of tags; defaults to ``bleach.sanitizer.ALLOWED_TAGS`` :arg dict attributes: allowed attributes; can be a callable, list or dict; defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES`` :arg list styles: allowed list of css styles; defaults to ``bleach.sanitizer.ALLOWED_STYLES`` :arg list protocols: allowed list of protocols for links; defaults to ``bleach.sanitizer.ALLOWED_PROTOCOLS`` :arg bool strip_disallowed_elements: whether or not to strip disallowed elements :arg bool strip_html_comments: whether or not to strip HTML comments Merge consecutive Characters tokens in a stream # Merge all the characters tokens together into one and then # operate on it. Sanitize a token either by HTML-encoding or dropping. Unlike sanitizer.Filter, allowed_attributes can be a dict of {'tag': ['attribute', 'pairs'], 'tag': callable}. Here callable is a function with two arguments of attribute name and value. It should return true of false. Also gives the option to strip tags instead of encoding. :arg dict token: token to sanitize :returns: token or list of tokens # Alphabetize the attributes before calling .disallowed_token() # so that the resulting string is stable Handles Characters tokens Our overridden tokenizer doesn't do anything with entities. However, that means that the serializer will convert all ``&`` in Characters tokens to ``&amp;``. Since we don't want that, we extract entities here and convert them to Entity tokens so the serializer will let them be. :arg token: the Characters token to work on :returns: a list of tokens # If there isn't a & in the data, we can return now # For each possible entity that starts with a "&", we try to extract an # actual entity and re-tokenize accordingly # LinkifyFilter can't match urls across token boundaries # which is problematic with &amp; since that shows up in # querystrings all the time. This special-cases &amp; # and converts it to a & and sticks it in as a # Characters token. It'll get merged with surrounding # tokens in the BleachSanitizerfilter.__iter__ and # escaped in the serializer. # Length of the entity plus 2--one for & at the beginning # and and one for ; at the end Checks a uri value to see if it's allowed :arg value: the uri value to sanitize :arg allowed_protocols: list of allowed protocols :returns: allowed value or None # NOTE(willkg): This transforms the value into one that's easier to # match and verify, but shouldn't get returned since it's vastly # different than the original value. # Convert all character entities in the value # Nix backtick, space characters, and control characters # Remove REPLACEMENT characters # Lowercase it--this breaks the value, but makes it easier to match # against # Drop attributes with uri values that have protocols that aren't # allowed # URI is impossible to parse, therefore it's not allowed # If urlparse found a scheme, check that # Allow uris that are just an anchor # Handle protocols that urlparse doesn't recognize like "myprotocol" # If there's no protocol/scheme specified, then assume it's "http" # and see if that's allowed Handles the case where we're allowing the tag # Loop through all the attributes and drop the ones that are not # allowed, are unsafe or break other rules. Additionally, fix # attribute values that need fixing. # # At the end of this loop, we have the final set of attributes # we're keeping. # Drop attributes that are not explicitly allowed # # NOTE(willkg): We pass in the attribute name--not a namespaced # name. # Drop attributes with uri values that use a disallowed protocol # Sanitize attributes with uri values # Drop values in svg attrs with non-local IRIs #\s][^)]+?\)', # Replace the val with the unescaped version because # it's a iri # Drop href and xlink:href attr for svg elements with non-local IRIs #\s]', val): # If it's a style attribute, sanitize it # At this point, we want to keep the attribute, so add it in # If we end up with a namespace, but no name, switch them so we # have a valid name to use. # Figure out namespaced name if the namespace is appropriate # and exists; if the ns isn't in prefixes, then drop it. # NOTE(willkg): HTMLSerializer escapes attribute values # already, so if we do it here (like HTMLSerializer does), # then we end up double-escaping. Sanitizes css in style tags # Convert entities in the style so that it can be parsed as CSS # Drop any url values before we do anything else # The gauntlet of sanitization # Validate the css in the style tag and if it's not valid, then drop # the whole thing. ^([-/:,#%.'"\s!\w]|\w-\w|'[\s\w]+'\s*|"[\s\w]+"|\([\d,%\.\s]+\))*$
2.309547
2
channel.py
hashplex/Lightning
48
6625095
<gh_stars>10-100 """Micropayment channel API for a lightning node. Interface: API -- the Blueprint returned by serverutil.api_factory CHANNEL_OPENED -- a blinker signal sent when a channel is opened. Arguments: - address -- the url of the counterparty init(conf) - Set up the database create(url, mymoney, theirmoney) - Open a channel with the node identified by url, where you can send mymoney satoshis, and recieve theirmoney satoshis. send(url, amount) - Update a channel by sending amount satoshis to the node at url. getbalance(url) - Return the number of satoshis you can send in the channel with url. close(url) - Close the channel with url. getcommitmenttransactions(url) - Return a list of the commitment transactions in a payment channel HTLC operation has not yet been defined. Error conditions have not yet been defined. Database: The schema is currently one row for each channel in table CHANNELS. address: url for the counterpary commitment: your commitment transaction """ from sqlalchemy import Column, Integer, String, LargeBinary from flask import g from blinker import Namespace from bitcoin.core import COutPoint, CMutableTxOut, CMutableTxIn from bitcoin.core import CMutableTransaction from bitcoin.core.scripteval import VerifyScript, SCRIPT_VERIFY_P2SH from bitcoin.core.script import CScript, SignatureHash, SIGHASH_ALL from bitcoin.core.script import OP_CHECKMULTISIG, OP_PUBKEY from bitcoin.wallet import CBitcoinAddress import jsonrpcproxy from serverutil import api_factory from serverutil import database from serverutil import ImmutableSerializableType, Base58DataType API, REMOTE, Model = api_factory('channel') SIGNALS = Namespace() CHANNEL_OPENED = SIGNALS.signal('CHANNEL_OPENED') class AnchorScriptSig(object): """Class representing a scriptSig satisfying the anchor output. Uses OP_PUBKEY to hold the place of your signature. """ def __init__(self, my_index=0, sig=b'', redeem=b''): if my_index == b'': my_index = 0 if my_index not in [0, 1]: raise Exception("Unknown index", my_index) self.my_index = my_index self.sig = sig self.redeem = CScript(redeem) @classmethod def from_script(cls, script): """Construct an AnchorScriptSig from a CScript.""" script = list(script) assert len(script) == 4 if script[1] == OP_PUBKEY: return cls(0, script[2], script[3]) elif script[2] == OP_PUBKEY: return cls(1, script[1], script[3]) else: raise Exception("Could not find OP_PUBKEY") def to_script(self, sig=OP_PUBKEY): """Construct a CScript from an AnchorScriptSig.""" if self.my_index == 0: sig1, sig2 = sig, self.sig elif self.my_index == 1: sig1, sig2 = self.sig, sig else: raise Exception("Unknown index", self.my_index) return CScript([0, sig1, sig2, self.redeem]) class Channel(Model): """Model of a payment channel.""" __tablename__ = 'channels' address = Column(String, primary_key=True) anchor_point = Column(ImmutableSerializableType(COutPoint), unique=True, index=True) anchor_index = Column(Integer) their_sig = Column(LargeBinary) anchor_redeem = Column(LargeBinary) our_balance = Column(Integer) our_addr = Column(Base58DataType(CBitcoinAddress)) their_balance = Column(Integer) their_addr = Column(Base58DataType(CBitcoinAddress)) def signature(self, transaction): """Signature for a transaction.""" sighash = SignatureHash(CScript(self.anchor_redeem), transaction, 0, SIGHASH_ALL) sig = g.seckey.sign(sighash) + bytes([SIGHASH_ALL]) return sig def sign(self, transaction): """Sign a transaction.""" sig = self.signature(transaction) anchor_sig = AnchorScriptSig(self.anchor_index, self.their_sig, self.anchor_redeem) transaction.vin[0].scriptSig = anchor_sig.to_script(sig) # verify signing worked VerifyScript(transaction.vin[0].scriptSig, CScript(self.anchor_redeem).to_p2sh_scriptPubKey(), transaction, 0, (SCRIPT_VERIFY_P2SH,)) return transaction def commitment(self, ours=False): """Return an unsigned commitment transaction.""" first = CMutableTxOut(self.our_balance, self.our_addr.to_scriptPubKey()) second = CMutableTxOut(self.their_balance, self.their_addr.to_scriptPubKey()) if not ours: first, second = second, first return CMutableTransaction([CMutableTxIn(self.anchor_point)], [first, second]) def settlement(self): """Generate the settlement transaction.""" # Put outputs in the order of the inputs, so that both versions are the same first = CMutableTxOut(self.our_balance, self.our_addr.to_scriptPubKey()) second = CMutableTxOut(self.their_balance, self.their_addr.to_scriptPubKey()) if self.anchor_index == 0: pass elif self.anchor_index == 1: first, second = second, first else: raise Exception("Unknown index", self.anchor_index) return CMutableTransaction([CMutableTxIn(self.anchor_point)], [first, second]) def select_coins(amount): """Get a txin set and change to spend amount.""" coins = g.bit.listunspent() out = [] for coin in coins: if not coin['spendable']: continue out.append(CMutableTxIn(coin['outpoint'])) amount -= coin['amount'] if amount <= 0: break if amount > 0: raise Exception("Not enough money") change = CMutableTxOut( -amount, g.bit.getrawchangeaddress().to_scriptPubKey()) return out, change def anchor_script(my_pubkey, their_pubkey): """Generate the output script for the anchor transaction.""" script = CScript([2, my_pubkey, their_pubkey, 2, OP_CHECKMULTISIG]) return script def get_pubkey(): """Get a new pubkey.""" return g.seckey.pub def update_db(address, amount, sig): """Update the db for a payment.""" channel = Channel.query.get(address) channel.our_balance += amount channel.their_balance -= amount channel.their_sig = sig database.session.commit() return channel.signature(channel.commitment()) def create(url, mymoney, theirmoney, fees=10000): """Open a payment channel. After this method returns, a payment channel will have been established with the node identified by url, in which you can send mymoney satoshis and recieve theirmoney satoshis. Any blockchain fees involved in the setup and teardown of the channel should be collected at this time. """ bob = jsonrpcproxy.Proxy(url+'channel/') # Choose inputs and change output coins, change = select_coins(mymoney + 2 * fees) pubkey = get_pubkey() my_out_addr = g.bit.getnewaddress() # Tell Bob we want to open a channel transaction, redeem, their_out_addr = bob.open_channel( g.addr, theirmoney, mymoney, fees, coins, change, pubkey, my_out_addr) # Sign and send the anchor transaction = g.bit.signrawtransaction(transaction) assert transaction['complete'] transaction = transaction['tx'] g.bit.sendrawtransaction(transaction) # Set up the channel in the DB channel = Channel(address=url, anchor_point=COutPoint(transaction.GetHash(), 0), anchor_index=1, their_sig=b'', anchor_redeem=redeem, our_balance=mymoney, our_addr=my_out_addr, their_balance=theirmoney, their_addr=their_out_addr, ) # Exchange signatures for the inital commitment transaction channel.their_sig = \ bob.update_anchor(g.addr, transaction.GetHash(), channel.signature(channel.commitment())) database.session.add(channel) database.session.commit() # Event: channel opened CHANNEL_OPENED.send('channel', address=url) def send(url, amount): """Send coin in the channel. Negotiate the update of the channel opened with node url paying that node amount more satoshis than before. No fees should be collected by this method. """ bob = jsonrpcproxy.Proxy(url+'channel/') # ask Bob to sign the new commitment transactions, and update. sig = update_db(url, -amount, bob.propose_update(g.addr, amount)) # tell Bob our signature bob.recieve(g.addr, amount, sig) def getbalance(url): """Get the balance of funds in a payment channel. This returns the number of satoshis you can spend in the channel with the node at url. This should have no side effects. """ return Channel.query.get(url).our_balance def getcommitmenttransactions(url): """Get the current commitment transactions in a payment channel.""" channel = Channel.query.get(url) commitment = channel.sign(channel.commitment(ours=True)) return [commitment,] def close(url): """Close a channel. Close the currently open channel with node url. Any funds in the channel are paid to the wallet, along with any fees collected by create which were unnecessary.""" bob = jsonrpcproxy.Proxy(url+'channel/') channel = Channel.query.get(url) # Tell Bob we are closing the channel, and sign the settlement tx bob.close_channel(g.addr, channel.signature(channel.settlement())) database.session.delete(channel) database.session.commit() @REMOTE def info(): """Get bitcoind info.""" return g.bit.getinfo() @REMOTE def get_address(): """Get payment address.""" return str(g.bit.getnewaddress()) @REMOTE def open_channel(address, mymoney, theirmoney, fees, their_coins, their_change, their_pubkey, their_out_addr): # pylint: disable=too-many-arguments, line-too-long """Open a payment channel.""" # Get inputs and change output coins, change = select_coins(mymoney + 2 * fees) # Make the anchor script anchor_output_script = anchor_script(get_pubkey(), their_pubkey) # Construct the anchor utxo payment = CMutableTxOut(mymoney + theirmoney + 2 * fees, anchor_output_script.to_p2sh_scriptPubKey()) # Anchor tx transaction = CMutableTransaction( their_coins + coins, [payment, change, their_change]) # Half-sign transaction = g.bit.signrawtransaction(transaction)['tx'] # Create channel in DB our_addr = g.bit.getnewaddress() channel = Channel(address=address, anchor_point=COutPoint(transaction.GetHash(), 0), anchor_index=0, their_sig=b'', anchor_redeem=anchor_output_script, our_balance=mymoney, our_addr=our_addr, their_balance=theirmoney, their_addr=their_out_addr, ) database.session.add(channel) database.session.commit() # Event: channel opened CHANNEL_OPENED.send('channel', address=address) return (transaction, anchor_output_script, our_addr) @REMOTE def update_anchor(address, new_anchor, their_sig): """Update the anchor txid after both have signed.""" channel = Channel.query.get(address) channel.anchor_point = COutPoint(new_anchor, channel.anchor_point.n) channel.their_sig = their_sig database.session.commit() return channel.signature(channel.commitment()) @REMOTE def propose_update(address, amount): """Sign commitment transactions.""" channel = Channel.query.get(address) assert amount > 0 channel.our_balance += amount channel.their_balance -= amount # don't persist yet sig = channel.signature(channel.commitment()) channel.our_balance -= amount channel.their_balance += amount return sig @REMOTE def recieve(address, amount, sig): """Recieve money.""" update_db(address, amount, sig) @REMOTE def close_channel(address, their_sig): """Close a channel.""" channel = Channel.query.get(address) # Sign and send settlement tx my_sig = channel.signature(channel.settlement()) channel.their_sig = their_sig transaction = channel.sign(channel.settlement()) g.bit.sendrawtransaction(transaction) database.session.delete(channel) database.session.commit() return my_sig
"""Micropayment channel API for a lightning node. Interface: API -- the Blueprint returned by serverutil.api_factory CHANNEL_OPENED -- a blinker signal sent when a channel is opened. Arguments: - address -- the url of the counterparty init(conf) - Set up the database create(url, mymoney, theirmoney) - Open a channel with the node identified by url, where you can send mymoney satoshis, and recieve theirmoney satoshis. send(url, amount) - Update a channel by sending amount satoshis to the node at url. getbalance(url) - Return the number of satoshis you can send in the channel with url. close(url) - Close the channel with url. getcommitmenttransactions(url) - Return a list of the commitment transactions in a payment channel HTLC operation has not yet been defined. Error conditions have not yet been defined. Database: The schema is currently one row for each channel in table CHANNELS. address: url for the counterpary commitment: your commitment transaction """ from sqlalchemy import Column, Integer, String, LargeBinary from flask import g from blinker import Namespace from bitcoin.core import COutPoint, CMutableTxOut, CMutableTxIn from bitcoin.core import CMutableTransaction from bitcoin.core.scripteval import VerifyScript, SCRIPT_VERIFY_P2SH from bitcoin.core.script import CScript, SignatureHash, SIGHASH_ALL from bitcoin.core.script import OP_CHECKMULTISIG, OP_PUBKEY from bitcoin.wallet import CBitcoinAddress import jsonrpcproxy from serverutil import api_factory from serverutil import database from serverutil import ImmutableSerializableType, Base58DataType API, REMOTE, Model = api_factory('channel') SIGNALS = Namespace() CHANNEL_OPENED = SIGNALS.signal('CHANNEL_OPENED') class AnchorScriptSig(object): """Class representing a scriptSig satisfying the anchor output. Uses OP_PUBKEY to hold the place of your signature. """ def __init__(self, my_index=0, sig=b'', redeem=b''): if my_index == b'': my_index = 0 if my_index not in [0, 1]: raise Exception("Unknown index", my_index) self.my_index = my_index self.sig = sig self.redeem = CScript(redeem) @classmethod def from_script(cls, script): """Construct an AnchorScriptSig from a CScript.""" script = list(script) assert len(script) == 4 if script[1] == OP_PUBKEY: return cls(0, script[2], script[3]) elif script[2] == OP_PUBKEY: return cls(1, script[1], script[3]) else: raise Exception("Could not find OP_PUBKEY") def to_script(self, sig=OP_PUBKEY): """Construct a CScript from an AnchorScriptSig.""" if self.my_index == 0: sig1, sig2 = sig, self.sig elif self.my_index == 1: sig1, sig2 = self.sig, sig else: raise Exception("Unknown index", self.my_index) return CScript([0, sig1, sig2, self.redeem]) class Channel(Model): """Model of a payment channel.""" __tablename__ = 'channels' address = Column(String, primary_key=True) anchor_point = Column(ImmutableSerializableType(COutPoint), unique=True, index=True) anchor_index = Column(Integer) their_sig = Column(LargeBinary) anchor_redeem = Column(LargeBinary) our_balance = Column(Integer) our_addr = Column(Base58DataType(CBitcoinAddress)) their_balance = Column(Integer) their_addr = Column(Base58DataType(CBitcoinAddress)) def signature(self, transaction): """Signature for a transaction.""" sighash = SignatureHash(CScript(self.anchor_redeem), transaction, 0, SIGHASH_ALL) sig = g.seckey.sign(sighash) + bytes([SIGHASH_ALL]) return sig def sign(self, transaction): """Sign a transaction.""" sig = self.signature(transaction) anchor_sig = AnchorScriptSig(self.anchor_index, self.their_sig, self.anchor_redeem) transaction.vin[0].scriptSig = anchor_sig.to_script(sig) # verify signing worked VerifyScript(transaction.vin[0].scriptSig, CScript(self.anchor_redeem).to_p2sh_scriptPubKey(), transaction, 0, (SCRIPT_VERIFY_P2SH,)) return transaction def commitment(self, ours=False): """Return an unsigned commitment transaction.""" first = CMutableTxOut(self.our_balance, self.our_addr.to_scriptPubKey()) second = CMutableTxOut(self.their_balance, self.their_addr.to_scriptPubKey()) if not ours: first, second = second, first return CMutableTransaction([CMutableTxIn(self.anchor_point)], [first, second]) def settlement(self): """Generate the settlement transaction.""" # Put outputs in the order of the inputs, so that both versions are the same first = CMutableTxOut(self.our_balance, self.our_addr.to_scriptPubKey()) second = CMutableTxOut(self.their_balance, self.their_addr.to_scriptPubKey()) if self.anchor_index == 0: pass elif self.anchor_index == 1: first, second = second, first else: raise Exception("Unknown index", self.anchor_index) return CMutableTransaction([CMutableTxIn(self.anchor_point)], [first, second]) def select_coins(amount): """Get a txin set and change to spend amount.""" coins = g.bit.listunspent() out = [] for coin in coins: if not coin['spendable']: continue out.append(CMutableTxIn(coin['outpoint'])) amount -= coin['amount'] if amount <= 0: break if amount > 0: raise Exception("Not enough money") change = CMutableTxOut( -amount, g.bit.getrawchangeaddress().to_scriptPubKey()) return out, change def anchor_script(my_pubkey, their_pubkey): """Generate the output script for the anchor transaction.""" script = CScript([2, my_pubkey, their_pubkey, 2, OP_CHECKMULTISIG]) return script def get_pubkey(): """Get a new pubkey.""" return g.seckey.pub def update_db(address, amount, sig): """Update the db for a payment.""" channel = Channel.query.get(address) channel.our_balance += amount channel.their_balance -= amount channel.their_sig = sig database.session.commit() return channel.signature(channel.commitment()) def create(url, mymoney, theirmoney, fees=10000): """Open a payment channel. After this method returns, a payment channel will have been established with the node identified by url, in which you can send mymoney satoshis and recieve theirmoney satoshis. Any blockchain fees involved in the setup and teardown of the channel should be collected at this time. """ bob = jsonrpcproxy.Proxy(url+'channel/') # Choose inputs and change output coins, change = select_coins(mymoney + 2 * fees) pubkey = get_pubkey() my_out_addr = g.bit.getnewaddress() # Tell Bob we want to open a channel transaction, redeem, their_out_addr = bob.open_channel( g.addr, theirmoney, mymoney, fees, coins, change, pubkey, my_out_addr) # Sign and send the anchor transaction = g.bit.signrawtransaction(transaction) assert transaction['complete'] transaction = transaction['tx'] g.bit.sendrawtransaction(transaction) # Set up the channel in the DB channel = Channel(address=url, anchor_point=COutPoint(transaction.GetHash(), 0), anchor_index=1, their_sig=b'', anchor_redeem=redeem, our_balance=mymoney, our_addr=my_out_addr, their_balance=theirmoney, their_addr=their_out_addr, ) # Exchange signatures for the inital commitment transaction channel.their_sig = \ bob.update_anchor(g.addr, transaction.GetHash(), channel.signature(channel.commitment())) database.session.add(channel) database.session.commit() # Event: channel opened CHANNEL_OPENED.send('channel', address=url) def send(url, amount): """Send coin in the channel. Negotiate the update of the channel opened with node url paying that node amount more satoshis than before. No fees should be collected by this method. """ bob = jsonrpcproxy.Proxy(url+'channel/') # ask Bob to sign the new commitment transactions, and update. sig = update_db(url, -amount, bob.propose_update(g.addr, amount)) # tell Bob our signature bob.recieve(g.addr, amount, sig) def getbalance(url): """Get the balance of funds in a payment channel. This returns the number of satoshis you can spend in the channel with the node at url. This should have no side effects. """ return Channel.query.get(url).our_balance def getcommitmenttransactions(url): """Get the current commitment transactions in a payment channel.""" channel = Channel.query.get(url) commitment = channel.sign(channel.commitment(ours=True)) return [commitment,] def close(url): """Close a channel. Close the currently open channel with node url. Any funds in the channel are paid to the wallet, along with any fees collected by create which were unnecessary.""" bob = jsonrpcproxy.Proxy(url+'channel/') channel = Channel.query.get(url) # Tell Bob we are closing the channel, and sign the settlement tx bob.close_channel(g.addr, channel.signature(channel.settlement())) database.session.delete(channel) database.session.commit() @REMOTE def info(): """Get bitcoind info.""" return g.bit.getinfo() @REMOTE def get_address(): """Get payment address.""" return str(g.bit.getnewaddress()) @REMOTE def open_channel(address, mymoney, theirmoney, fees, their_coins, their_change, their_pubkey, their_out_addr): # pylint: disable=too-many-arguments, line-too-long """Open a payment channel.""" # Get inputs and change output coins, change = select_coins(mymoney + 2 * fees) # Make the anchor script anchor_output_script = anchor_script(get_pubkey(), their_pubkey) # Construct the anchor utxo payment = CMutableTxOut(mymoney + theirmoney + 2 * fees, anchor_output_script.to_p2sh_scriptPubKey()) # Anchor tx transaction = CMutableTransaction( their_coins + coins, [payment, change, their_change]) # Half-sign transaction = g.bit.signrawtransaction(transaction)['tx'] # Create channel in DB our_addr = g.bit.getnewaddress() channel = Channel(address=address, anchor_point=COutPoint(transaction.GetHash(), 0), anchor_index=0, their_sig=b'', anchor_redeem=anchor_output_script, our_balance=mymoney, our_addr=our_addr, their_balance=theirmoney, their_addr=their_out_addr, ) database.session.add(channel) database.session.commit() # Event: channel opened CHANNEL_OPENED.send('channel', address=address) return (transaction, anchor_output_script, our_addr) @REMOTE def update_anchor(address, new_anchor, their_sig): """Update the anchor txid after both have signed.""" channel = Channel.query.get(address) channel.anchor_point = COutPoint(new_anchor, channel.anchor_point.n) channel.their_sig = their_sig database.session.commit() return channel.signature(channel.commitment()) @REMOTE def propose_update(address, amount): """Sign commitment transactions.""" channel = Channel.query.get(address) assert amount > 0 channel.our_balance += amount channel.their_balance -= amount # don't persist yet sig = channel.signature(channel.commitment()) channel.our_balance -= amount channel.their_balance += amount return sig @REMOTE def recieve(address, amount, sig): """Recieve money.""" update_db(address, amount, sig) @REMOTE def close_channel(address, their_sig): """Close a channel.""" channel = Channel.query.get(address) # Sign and send settlement tx my_sig = channel.signature(channel.settlement()) channel.their_sig = their_sig transaction = channel.sign(channel.settlement()) g.bit.sendrawtransaction(transaction) database.session.delete(channel) database.session.commit() return my_sig
en
0.882588
Micropayment channel API for a lightning node. Interface: API -- the Blueprint returned by serverutil.api_factory CHANNEL_OPENED -- a blinker signal sent when a channel is opened. Arguments: - address -- the url of the counterparty init(conf) - Set up the database create(url, mymoney, theirmoney) - Open a channel with the node identified by url, where you can send mymoney satoshis, and recieve theirmoney satoshis. send(url, amount) - Update a channel by sending amount satoshis to the node at url. getbalance(url) - Return the number of satoshis you can send in the channel with url. close(url) - Close the channel with url. getcommitmenttransactions(url) - Return a list of the commitment transactions in a payment channel HTLC operation has not yet been defined. Error conditions have not yet been defined. Database: The schema is currently one row for each channel in table CHANNELS. address: url for the counterpary commitment: your commitment transaction Class representing a scriptSig satisfying the anchor output. Uses OP_PUBKEY to hold the place of your signature. Construct an AnchorScriptSig from a CScript. Construct a CScript from an AnchorScriptSig. Model of a payment channel. Signature for a transaction. Sign a transaction. # verify signing worked Return an unsigned commitment transaction. Generate the settlement transaction. # Put outputs in the order of the inputs, so that both versions are the same Get a txin set and change to spend amount. Generate the output script for the anchor transaction. Get a new pubkey. Update the db for a payment. Open a payment channel. After this method returns, a payment channel will have been established with the node identified by url, in which you can send mymoney satoshis and recieve theirmoney satoshis. Any blockchain fees involved in the setup and teardown of the channel should be collected at this time. # Choose inputs and change output # Tell Bob we want to open a channel # Sign and send the anchor # Set up the channel in the DB # Exchange signatures for the inital commitment transaction # Event: channel opened Send coin in the channel. Negotiate the update of the channel opened with node url paying that node amount more satoshis than before. No fees should be collected by this method. # ask Bob to sign the new commitment transactions, and update. # tell Bob our signature Get the balance of funds in a payment channel. This returns the number of satoshis you can spend in the channel with the node at url. This should have no side effects. Get the current commitment transactions in a payment channel. Close a channel. Close the currently open channel with node url. Any funds in the channel are paid to the wallet, along with any fees collected by create which were unnecessary. # Tell Bob we are closing the channel, and sign the settlement tx Get bitcoind info. Get payment address. # pylint: disable=too-many-arguments, line-too-long Open a payment channel. # Get inputs and change output # Make the anchor script # Construct the anchor utxo # Anchor tx # Half-sign # Create channel in DB # Event: channel opened Update the anchor txid after both have signed. Sign commitment transactions. # don't persist yet Recieve money. Close a channel. # Sign and send settlement tx
2.482913
2
src/ssh/azext_ssh/connectivity_utils.py
haroonf/azure-cli-extensions
0
6625096
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import time import stat import os import urllib.request import json import base64 from glob import glob import colorama from colorama import Fore from colorama import Style from azure.core.exceptions import ResourceNotFoundError from azure.cli.core import telemetry from azure.cli.core import azclierror from azure.mgmt.core.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id from knack import log from . import file_utils from . import constants as consts logger = log.get_logger(__name__) # Get the Access Details to connect to Arc Connectivity platform from the HybridConnectivity RP def get_relay_information(cmd, resource_group, vm_name, certificate_validity_in_seconds): from azext_ssh._client_factory import cf_endpoint client = cf_endpoint(cmd.cli_ctx) if not certificate_validity_in_seconds or \ certificate_validity_in_seconds > consts.RELAY_INFO_MAXIMUM_DURATION_IN_SECONDS: certificate_validity_in_seconds = consts.RELAY_INFO_MAXIMUM_DURATION_IN_SECONDS try: t0 = time.time() result = client.list_credentials(resource_group_name=resource_group, machine_name=vm_name, endpoint_name="default", expiresin=certificate_validity_in_seconds) time_elapsed = time.time() - t0 telemetry.add_extension_event('ssh', {'Context.Default.AzureCLI.SSHListCredentialsTime': time_elapsed}) except ResourceNotFoundError: logger.debug("Default Endpoint couldn't be found. Trying to create Default Endpoint.") _create_default_endpoint(cmd, resource_group, vm_name, client) try: t0 = time.time() result = client.list_credentials(resource_group_name=resource_group, machine_name=vm_name, endpoint_name="default", expiresin=certificate_validity_in_seconds) time_elapsed = time.time() - t0 telemetry.add_extension_event('ssh', {'Context.Default.AzureCLI.SSHListCredentialsTime': time_elapsed}) except Exception as e: raise azclierror.ClientRequestError(f"Request for Azure Relay Information Failed:\n{str(e)}") except Exception as e: raise azclierror.ClientRequestError(f"Request for Azure Relay Information Failed:\n{str(e)}") return result def _create_default_endpoint(cmd, resource_group, vm_name, client): az_resource_id = resource_id(subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group, namespace="Microsoft.HybridCompute", type="machines", name=vm_name) endpoint_resource = {"id": az_resource_id, "type_properties_type": "default"} try: client.create_or_update(resource_group, vm_name, "default", endpoint_resource) except Exception as e: colorama.init() raise azclierror.UnauthorizedError(f"Unable to create Default Endpoint for {vm_name} in {resource_group}." f"\nError: {str(e)}", Fore.YELLOW + "Contact Owner/Contributor of the resource." + Style.RESET_ALL) # Downloads client side proxy to connect to Arc Connectivity Platform def get_client_side_proxy(arc_proxy_folder): request_uri, install_location, older_version_location = _get_proxy_filename_and_url(arc_proxy_folder) install_dir = os.path.dirname(install_location) # Only download new proxy if it doesn't exist already if not os.path.isfile(install_location): t0 = time.time() # download the executable try: with urllib.request.urlopen(request_uri) as response: response_content = response.read() response.close() except Exception as e: raise azclierror.ClientRequestError(f"Failed to download client proxy executable from {request_uri}. " "Error: " + str(e)) from e time_elapsed = time.time() - t0 proxy_data = { 'Context.Default.AzureCLI.SSHProxyDownloadTime': time_elapsed, 'Context.Default.AzureCLI.SSHProxyVersion': consts.CLIENT_PROXY_VERSION } telemetry.add_extension_event('ssh', proxy_data) # if directory doesn't exist, create it if not os.path.isdir(install_dir): file_utils.create_directory(install_dir, f"Failed to create client proxy directory '{install_dir}'. ") # if directory exists, delete any older versions of the proxy else: older_version_files = glob(older_version_location) for f in older_version_files: file_utils.delete_file(f, f"failed to delete older version file {f}", warning=True) # write executable in the install location file_utils.write_to_file(install_location, 'wb', response_content, "Failed to create client proxy file. ") os.chmod(install_location, os.stat(install_location).st_mode | stat.S_IXUSR) colorama.init() print(Fore.GREEN + f"SSH Client Proxy saved to {install_location}" + Style.RESET_ALL) return install_location def _get_proxy_filename_and_url(arc_proxy_folder): import platform operating_system = platform.system() machine = platform.machine() logger.debug("Platform OS: %s", operating_system) logger.debug("Platform architecture: %s", machine) if machine.endswith('64'): architecture = 'amd64' elif machine.endswith('86'): architecture = '386' elif machine == '': raise azclierror.BadRequestError("Couldn't identify the platform architecture.") else: raise azclierror.BadRequestError(f"Unsuported architecture: {machine} is not currently supported") # define the request url and install location based on the os and architecture proxy_name = f"sshProxy_{operating_system.lower()}_{architecture}" request_uri = (f"{consts.CLIENT_PROXY_STORAGE_URL}/{consts.CLIENT_PROXY_RELEASE}" f"/{proxy_name}_{consts.CLIENT_PROXY_VERSION}") install_location = proxy_name + "_" + consts.CLIENT_PROXY_VERSION.replace('.', '_') older_location = proxy_name + "*" if operating_system == 'Windows': request_uri = request_uri + ".exe" install_location = install_location + ".exe" older_location = older_location + ".exe" elif operating_system not in ('Linux', 'Darwin'): raise azclierror.BadRequestError(f"Unsuported OS: {operating_system} platform is not currently supported") if not arc_proxy_folder: install_location = os.path.expanduser(os.path.join('~', os.path.join(".clientsshproxy", install_location))) older_location = os.path.expanduser(os.path.join('~', os.path.join(".clientsshproxy", older_location))) else: install_location = os.path.join(arc_proxy_folder, install_location) older_location = os.path.join(arc_proxy_folder, older_location) return request_uri, install_location, older_location def format_relay_info_string(relay_info): relay_info_string = json.dumps( { "relay": { "namespaceName": relay_info.namespace_name, "namespaceNameSuffix": relay_info.namespace_name_suffix, "hybridConnectionName": relay_info.hybrid_connection_name, "accessKey": relay_info.access_key, "expiresOn": relay_info.expires_on } }) result_bytes = relay_info_string.encode("ascii") enc = base64.b64encode(result_bytes) base64_result_string = enc.decode("ascii") return base64_result_string
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import time import stat import os import urllib.request import json import base64 from glob import glob import colorama from colorama import Fore from colorama import Style from azure.core.exceptions import ResourceNotFoundError from azure.cli.core import telemetry from azure.cli.core import azclierror from azure.mgmt.core.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id from knack import log from . import file_utils from . import constants as consts logger = log.get_logger(__name__) # Get the Access Details to connect to Arc Connectivity platform from the HybridConnectivity RP def get_relay_information(cmd, resource_group, vm_name, certificate_validity_in_seconds): from azext_ssh._client_factory import cf_endpoint client = cf_endpoint(cmd.cli_ctx) if not certificate_validity_in_seconds or \ certificate_validity_in_seconds > consts.RELAY_INFO_MAXIMUM_DURATION_IN_SECONDS: certificate_validity_in_seconds = consts.RELAY_INFO_MAXIMUM_DURATION_IN_SECONDS try: t0 = time.time() result = client.list_credentials(resource_group_name=resource_group, machine_name=vm_name, endpoint_name="default", expiresin=certificate_validity_in_seconds) time_elapsed = time.time() - t0 telemetry.add_extension_event('ssh', {'Context.Default.AzureCLI.SSHListCredentialsTime': time_elapsed}) except ResourceNotFoundError: logger.debug("Default Endpoint couldn't be found. Trying to create Default Endpoint.") _create_default_endpoint(cmd, resource_group, vm_name, client) try: t0 = time.time() result = client.list_credentials(resource_group_name=resource_group, machine_name=vm_name, endpoint_name="default", expiresin=certificate_validity_in_seconds) time_elapsed = time.time() - t0 telemetry.add_extension_event('ssh', {'Context.Default.AzureCLI.SSHListCredentialsTime': time_elapsed}) except Exception as e: raise azclierror.ClientRequestError(f"Request for Azure Relay Information Failed:\n{str(e)}") except Exception as e: raise azclierror.ClientRequestError(f"Request for Azure Relay Information Failed:\n{str(e)}") return result def _create_default_endpoint(cmd, resource_group, vm_name, client): az_resource_id = resource_id(subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group, namespace="Microsoft.HybridCompute", type="machines", name=vm_name) endpoint_resource = {"id": az_resource_id, "type_properties_type": "default"} try: client.create_or_update(resource_group, vm_name, "default", endpoint_resource) except Exception as e: colorama.init() raise azclierror.UnauthorizedError(f"Unable to create Default Endpoint for {vm_name} in {resource_group}." f"\nError: {str(e)}", Fore.YELLOW + "Contact Owner/Contributor of the resource." + Style.RESET_ALL) # Downloads client side proxy to connect to Arc Connectivity Platform def get_client_side_proxy(arc_proxy_folder): request_uri, install_location, older_version_location = _get_proxy_filename_and_url(arc_proxy_folder) install_dir = os.path.dirname(install_location) # Only download new proxy if it doesn't exist already if not os.path.isfile(install_location): t0 = time.time() # download the executable try: with urllib.request.urlopen(request_uri) as response: response_content = response.read() response.close() except Exception as e: raise azclierror.ClientRequestError(f"Failed to download client proxy executable from {request_uri}. " "Error: " + str(e)) from e time_elapsed = time.time() - t0 proxy_data = { 'Context.Default.AzureCLI.SSHProxyDownloadTime': time_elapsed, 'Context.Default.AzureCLI.SSHProxyVersion': consts.CLIENT_PROXY_VERSION } telemetry.add_extension_event('ssh', proxy_data) # if directory doesn't exist, create it if not os.path.isdir(install_dir): file_utils.create_directory(install_dir, f"Failed to create client proxy directory '{install_dir}'. ") # if directory exists, delete any older versions of the proxy else: older_version_files = glob(older_version_location) for f in older_version_files: file_utils.delete_file(f, f"failed to delete older version file {f}", warning=True) # write executable in the install location file_utils.write_to_file(install_location, 'wb', response_content, "Failed to create client proxy file. ") os.chmod(install_location, os.stat(install_location).st_mode | stat.S_IXUSR) colorama.init() print(Fore.GREEN + f"SSH Client Proxy saved to {install_location}" + Style.RESET_ALL) return install_location def _get_proxy_filename_and_url(arc_proxy_folder): import platform operating_system = platform.system() machine = platform.machine() logger.debug("Platform OS: %s", operating_system) logger.debug("Platform architecture: %s", machine) if machine.endswith('64'): architecture = 'amd64' elif machine.endswith('86'): architecture = '386' elif machine == '': raise azclierror.BadRequestError("Couldn't identify the platform architecture.") else: raise azclierror.BadRequestError(f"Unsuported architecture: {machine} is not currently supported") # define the request url and install location based on the os and architecture proxy_name = f"sshProxy_{operating_system.lower()}_{architecture}" request_uri = (f"{consts.CLIENT_PROXY_STORAGE_URL}/{consts.CLIENT_PROXY_RELEASE}" f"/{proxy_name}_{consts.CLIENT_PROXY_VERSION}") install_location = proxy_name + "_" + consts.CLIENT_PROXY_VERSION.replace('.', '_') older_location = proxy_name + "*" if operating_system == 'Windows': request_uri = request_uri + ".exe" install_location = install_location + ".exe" older_location = older_location + ".exe" elif operating_system not in ('Linux', 'Darwin'): raise azclierror.BadRequestError(f"Unsuported OS: {operating_system} platform is not currently supported") if not arc_proxy_folder: install_location = os.path.expanduser(os.path.join('~', os.path.join(".clientsshproxy", install_location))) older_location = os.path.expanduser(os.path.join('~', os.path.join(".clientsshproxy", older_location))) else: install_location = os.path.join(arc_proxy_folder, install_location) older_location = os.path.join(arc_proxy_folder, older_location) return request_uri, install_location, older_location def format_relay_info_string(relay_info): relay_info_string = json.dumps( { "relay": { "namespaceName": relay_info.namespace_name, "namespaceNameSuffix": relay_info.namespace_name_suffix, "hybridConnectionName": relay_info.hybrid_connection_name, "accessKey": relay_info.access_key, "expiresOn": relay_info.expires_on } }) result_bytes = relay_info_string.encode("ascii") enc = base64.b64encode(result_bytes) base64_result_string = enc.decode("ascii") return base64_result_string
en
0.744954
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Get the Access Details to connect to Arc Connectivity platform from the HybridConnectivity RP # Downloads client side proxy to connect to Arc Connectivity Platform # Only download new proxy if it doesn't exist already # download the executable # if directory doesn't exist, create it # if directory exists, delete any older versions of the proxy # write executable in the install location # define the request url and install location based on the os and architecture
1.83695
2
benchmarks/01-LE10-Thick-Plate/python_postprocessing/calculix_automate.py
dantelimac/CoFEA
0
6625097
<gh_stars>0 import numpy as np import subprocess import glob as gb import shutil import time import os import logging import ccx2paraview # Function changing input mesh inside the model.inp file def change_model_inp (input_file, change_mesh): # Input mesh path mesh_path = "*INCLUDE, INPUT="+ change_mesh + "\n" # Pressure load path press_path = change_mesh.replace('Mesh/','Pressure/') press_name = press_path.replace('.inp','.dlo') press_load_path = " *INCLUDE, INPUT=" + press_name + "\n" # Read model.inp with open((input_file + ".inp"),"r") as model_inp: # Read all the lines of model.inp list_of_lines = model_inp.readlines() list_of_lines[0] = mesh_path list_of_lines[25] = press_load_path with open((input_file + ".inp"),"w") as model_inp: model_inp.writelines(list_of_lines) # Function which starts ccx solver and copy results def run_calculix(input_file, mesh_files_inp): name_fild_dir = mesh_files_inp.replace('.inp','') new_name_fil_dir = name_fild_dir.replace('Mesh/','') # Run the CalculiX solver with ccx_2.17_MT commnad subprocess.run(["ccx_2.17_MT", input_file]) os.mkdir("Results/" + new_name_fil_dir) #Variables for copying/saving files frd_result_file = input_file + ".frd" dat_result_file = input_file + ".dat" vtu_result_file = input_file + ".vtu" #convert .frd to .vtu logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') conversion = ccx2paraview.Converter(frd_result_file, ['vtu']) conversion.run() frd_new_name = new_name_fil_dir + ".frd" dat_new_name = new_name_fil_dir + ".dat" vtu_new_name = new_name_fil_dir + ".vtu" frd_dir = "Results/" + new_name_fil_dir + "/" + frd_new_name dat_dir = "Results/" + new_name_fil_dir + "/" + dat_new_name vtu_dir = "Results/" + new_name_fil_dir + "/" + vtu_new_name # Copy the results files shutil.copyfile(frd_result_file, frd_dir) shutil.copyfile(dat_result_file, dat_dir) shutil.copyfile(vtu_result_file, vtu_dir) os.mkdir("Results") # Check the meshes in Mesh folder mesh_file_mames = gb.glob("Mesh/*.inp") # Name of the input inp file for CalculiX ccx_input_file = ("model") for mesh_file_mame in mesh_file_mames: change_model_inp(ccx_input_file, mesh_file_mame) run_calculix(ccx_input_file, mesh_file_mame) print ("All simualations are done!")
import numpy as np import subprocess import glob as gb import shutil import time import os import logging import ccx2paraview # Function changing input mesh inside the model.inp file def change_model_inp (input_file, change_mesh): # Input mesh path mesh_path = "*INCLUDE, INPUT="+ change_mesh + "\n" # Pressure load path press_path = change_mesh.replace('Mesh/','Pressure/') press_name = press_path.replace('.inp','.dlo') press_load_path = " *INCLUDE, INPUT=" + press_name + "\n" # Read model.inp with open((input_file + ".inp"),"r") as model_inp: # Read all the lines of model.inp list_of_lines = model_inp.readlines() list_of_lines[0] = mesh_path list_of_lines[25] = press_load_path with open((input_file + ".inp"),"w") as model_inp: model_inp.writelines(list_of_lines) # Function which starts ccx solver and copy results def run_calculix(input_file, mesh_files_inp): name_fild_dir = mesh_files_inp.replace('.inp','') new_name_fil_dir = name_fild_dir.replace('Mesh/','') # Run the CalculiX solver with ccx_2.17_MT commnad subprocess.run(["ccx_2.17_MT", input_file]) os.mkdir("Results/" + new_name_fil_dir) #Variables for copying/saving files frd_result_file = input_file + ".frd" dat_result_file = input_file + ".dat" vtu_result_file = input_file + ".vtu" #convert .frd to .vtu logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') conversion = ccx2paraview.Converter(frd_result_file, ['vtu']) conversion.run() frd_new_name = new_name_fil_dir + ".frd" dat_new_name = new_name_fil_dir + ".dat" vtu_new_name = new_name_fil_dir + ".vtu" frd_dir = "Results/" + new_name_fil_dir + "/" + frd_new_name dat_dir = "Results/" + new_name_fil_dir + "/" + dat_new_name vtu_dir = "Results/" + new_name_fil_dir + "/" + vtu_new_name # Copy the results files shutil.copyfile(frd_result_file, frd_dir) shutil.copyfile(dat_result_file, dat_dir) shutil.copyfile(vtu_result_file, vtu_dir) os.mkdir("Results") # Check the meshes in Mesh folder mesh_file_mames = gb.glob("Mesh/*.inp") # Name of the input inp file for CalculiX ccx_input_file = ("model") for mesh_file_mame in mesh_file_mames: change_model_inp(ccx_input_file, mesh_file_mame) run_calculix(ccx_input_file, mesh_file_mame) print ("All simualations are done!")
en
0.694996
# Function changing input mesh inside the model.inp file # Input mesh path # Pressure load path # Read model.inp # Read all the lines of model.inp # Function which starts ccx solver and copy results # Run the CalculiX solver with ccx_2.17_MT commnad #Variables for copying/saving files #convert .frd to .vtu # Copy the results files # Check the meshes in Mesh folder # Name of the input inp file for CalculiX
2.202986
2
pygsti/tools/jamiolkowski.py
drewrisinger/pyGSTi
1
6625098
<filename>pygsti/tools/jamiolkowski.py<gh_stars>1-10 """Utility functions related to the Choi representation of gates.""" #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this software. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** import numpy as _np from ..objects.basis import Basis as _Basis from . import basistools as _bt from . import matrixtools as _mt # Gate Mx G: rho --> G rho where G and rho are in the Pauli basis (by definition/convention) # noqa # vec(rhoS) --> GStd vec(rhoS) where GS and rhoS are in the std basis, GS = PtoS * G * StoP # noqa # Choi Mx J: rho --> sum_ij Jij Bi rho Bj^dag where Bi is some basis of mxs for rho-space; independent of basis for rho and Bi # noqa # vec(rhoS) --> sum_ij Jij (BSi x BSj^*) vec(rhoS) where rhoS and BSi's are in std basis # noqa # Now, # noqa # Jkl = Trace( sum_ij Jij (BSi x BSj^*) , (BSk x BSl^*)^dag ) / Trace( (BSk x BSl^*), (BSk x BSl^*)^dag ) # noqa # = Trace( GStd , (BSk x BSl^*)^dag ) / Trace( (BSk x BSl^*), (BSk x BSl^*)^dag ) # noqa # In below function, take Bi's to be Pauli matrices # Note: vec(.) vectorization above is assumed to be done by-*rows* (as numpy.flatten does). # Note that in just the std basis, the construction of the Jamiolkowski representation of a process phi is # noqa # J(Phi) = sum_(0<i,j<n) Phi(|i><j|) x |i><j| where {|i>}_1^n spans the state space # noqa # # Derivation: if we write: # noqa # Phi(|i><j|) = sum_kl C[(kl)(ij)] |k><l| # noqa # and # noqa # rho = sum_ij rho_ij |i><j| # noqa # then # noqa # Phi(rho) = sum_(ij)(kl) C[(kl)(ij)] rho_ij |k><l| # noqa # = sum_(ij)(kl) C[(kl)(ij)] |k> rho_ij <l| # noqa # = sum_(ij)(kl) C[(kl)(ij)] |k> <i| rho |j> <l| # noqa # = sum_(ij)(kl) C[(ik)(jl)] |i> <j| rho |l> <k| (just permute index labels) # noqa # The definition of the Jamiolkoski matrix J is: # noqa # Phi(rho) = sum_(ij)(kl) J(ij)(kl) |i><j| rho |l><k| # noqa # so # noqa # J(ij)(kl) == C[(ik)(jl)] # noqa # # Note: |i><j| x |k><l| is an object in "gate/process" space, since # noqa # it maps a vectorized density matrix, e.g. |a><b| to another density matrix via: # noqa # (|i><j| x |k><l|) vec(|a><b|) = [mx with 1 in (i*dmDim + k) row and (j*dmDim + l) col][vec with 1 in a*dmDim+b row] # noqa # = vec(|i><k|) if |a><b| == |j><l| else 0 # noqa # so (|i><j| x |k><l|) vec(|j><l|) = vec(|i><k|) # noqa # and could write as: (|ik><jl|) |jl> = |ik> # noqa # # Now write J as: # noqa # J = sum_ijkl |ij> J(ij)(kl) <kl| # noqa # = sum_ijkl J(ij)(kl) |ij> <kl| # noqa # = sum_ijkl J(ij)(kl) (|i><k| x |j><l|) # noqa # = sum_ijkl C(ik)(jl) (|i><k| x |j><l|) # noqa # = sum_jl [ sum_ik C(ik)(jl) |i><k| ] x |j><l| (using Note above) # noqa # = sum_jl Phi(|j><l|) x |j><l| (using definition Phi(|i><j|) = sum_kl C[(kl)(ij)] |k><l|) # noqa # which is the original J(Phi) expression. # noqa # # This can be written equivalently as: # noqa # J(Phi) = sum_(0<i,j<n) Phi(Eij) otimes Eij # noqa # where Eij is the matrix unit with a single element in the (i,j)-th position, i.e. Eij == |i><j| # noqa def jamiolkowski_iso(operationMx, opMxBasis='pp', choiMxBasis='pp'): """ Given a operation matrix, return the corresponding Choi matrix that is normalized to have trace == 1. Parameters ---------- operationMx : numpy array the operation matrix to compute Choi matrix of. opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). choiMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array the Choi matrix, normalized to have trace == 1, in the desired basis. """ operationMx = _np.asarray(operationMx) opMxBasis = _bt.build_basis_for_matrix(operationMx, opMxBasis) opMxInStdBasis = _bt.change_basis(operationMx, opMxBasis, opMxBasis.equivalent('std')) #expand operation matrix so it acts on entire space of dmDim x dmDim density matrices # so that we can take dot products with the BVec matrices below opMxInStdBasis = _bt.resize_std_mx(opMxInStdBasis, 'expand', opMxBasis.equivalent( 'std'), opMxBasis.simple_equivalent('std')) N = opMxInStdBasis.shape[0] # dimension of the full-basis (expanded) gate dmDim = int(round(_np.sqrt(N))) # density matrix dimension #Note: we need to use the *full* basis of Matrix Unit, Gell-Mann, or Pauli-product matrices when # generating the Choi matrix, even when the original operation matrix doesn't include the entire basis. # This is because even when the original operation matrix doesn't include a certain basis element (B0 say), # conjugating with this basis element and tracing, i.e. trace(B0^dag * Operation * B0), is not necessarily zero. #get full list of basis matrices (in std basis) -- i.e. we use dmDim if not isinstance(choiMxBasis, _Basis): choiMxBasis = _Basis.cast(choiMxBasis, N) # we'd like a basis of dimension N BVec = choiMxBasis.simple_equivalent().elements M = len(BVec) # can be < N if basis has multiple block dims assert(M == N), 'Expected {}, got {}'.format(M, N) choiMx = _np.empty((N, N), 'complex') for i in range(M): for j in range(M): BiBj = _np.kron(BVec[i], _np.conjugate(BVec[j])) BiBj_dag = _np.transpose(_np.conjugate(BiBj)) choiMx[i, j] = _mt.trace(_np.dot(opMxInStdBasis, BiBj_dag)) \ / _mt.trace(_np.dot(BiBj, BiBj_dag)) # This construction results in a Jmx with trace == dim(H) = sqrt(operationMx.shape[0]) (dimension of density matrix) # but we'd like a Jmx with trace == 1, so normalize: choiMx_normalized = choiMx / dmDim return choiMx_normalized # GStd = sum_ij Jij (BSi x BSj^*) def jamiolkowski_iso_inv(choiMx, choiMxBasis='pp', opMxBasis='pp'): """ Given a choi matrix, return the corresponding operation matrix. This function performs the inverse of jamiolkowski_iso(...). Parameters ---------- choiMx : numpy array the Choi matrix, normalized to have trace == 1, to compute operation matrix for. choiMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array operation matrix in the desired basis. """ choiMx = _np.asarray(choiMx) # will have "expanded" dimension even if bases are for reduced... N = choiMx.shape[0] # dimension of full-basis (expanded) operation matrix if not isinstance(choiMxBasis, _Basis): # if we're not given a basis, build choiMxBasis = _Basis.cast(choiMxBasis, N) # one with the full dimension dmDim = int(round(_np.sqrt(N))) # density matrix dimension #get full list of basis matrices (in std basis) BVec = _bt.basis_matrices(choiMxBasis.simple_equivalent(), N) assert(len(BVec) == N) # make sure the number of basis matrices matches the dim of the choi matrix given # Invert normalization choiMx_unnorm = choiMx * dmDim opMxInStdBasis = _np.zeros((N, N), 'complex') # in matrix unit basis of entire density matrix for i in range(N): for j in range(N): BiBj = _np.kron(BVec[i], _np.conjugate(BVec[j])) opMxInStdBasis += choiMx_unnorm[i, j] * BiBj if not isinstance(opMxBasis, _Basis): opMxBasis = _Basis.cast(opMxBasis, N) # make sure opMxBasis is a Basis; we'd like dimension to be N #project operation matrix so it acts only on the space given by the desired state space blocks opMxInStdBasis = _bt.resize_std_mx(opMxInStdBasis, 'contract', opMxBasis.simple_equivalent('std'), opMxBasis.equivalent('std')) #transform operation matrix into appropriate basis return _bt.change_basis(opMxInStdBasis, opMxBasis.equivalent('std'), opMxBasis) def fast_jamiolkowski_iso_std(operationMx, opMxBasis): """ Given a operation matrix, return the corresponding Choi matrix in the standard basis that is normalized to have trace == 1. This routine *only* computes the case of the Choi matrix being in the standard (matrix unit) basis, but does so more quickly than :func:`jamiolkowski_iso` and so is particuarly useful when only the eigenvalues of the Choi matrix are needed. Parameters ---------- operationMx : numpy array the operation matrix to compute Choi matrix of. opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array the Choi matrix, normalized to have trace == 1, in the std basis. """ #first, get operation matrix into std basis operationMx = _np.asarray(operationMx) opMxBasis = _bt.build_basis_for_matrix(operationMx, opMxBasis) opMxInStdBasis = _bt.change_basis(operationMx, opMxBasis, opMxBasis.equivalent('std')) #expand operation matrix so it acts on entire space of dmDim x dmDim density matrices opMxInStdBasis = _bt.resize_std_mx(opMxInStdBasis, 'expand', opMxBasis.equivalent('std'), opMxBasis.simple_equivalent('std')) #Shuffle indices to go from process matrix to Jamiolkowski matrix (they vectorize differently) N2 = opMxInStdBasis.shape[0]; N = int(_np.sqrt(N2)) assert(N * N == N2) # make sure N2 is a perfect square Jmx = opMxInStdBasis.reshape((N, N, N, N)) Jmx = _np.swapaxes(Jmx, 1, 2).flatten() Jmx = Jmx.reshape((N2, N2)) # This construction results in a Jmx with trace == dim(H) = sqrt(gateMxInPauliBasis.shape[0]) # but we'd like a Jmx with trace == 1, so normalize: Jmx_norm = Jmx / N return Jmx_norm def fast_jamiolkowski_iso_std_inv(choiMx, opMxBasis): """ Given a choi matrix in the standard basis, return the corresponding operation matrix. This function performs the inverse of fast_jamiolkowski_iso_std(...). Parameters ---------- choiMx : numpy array the Choi matrix in the standard (matrix units) basis, normalized to have trace == 1, to compute operation matrix for. opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array operation matrix in the desired basis. """ #Shuffle indices to go from process matrix to Jamiolkowski matrix (they vectorize differently) N2 = choiMx.shape[0]; N = int(_np.sqrt(N2)) assert(N * N == N2) # make sure N2 is a perfect square opMxInStdBasis = choiMx.reshape((N, N, N, N)) * N opMxInStdBasis = _np.swapaxes(opMxInStdBasis, 1, 2).flatten() opMxInStdBasis = opMxInStdBasis.reshape((N2, N2)) opMxBasis = _bt.build_basis_for_matrix(opMxInStdBasis, opMxBasis) #project operation matrix so it acts only on the space given by the desired state space blocks opMxInStdBasis = _bt.resize_std_mx(opMxInStdBasis, 'contract', opMxBasis.simple_equivalent('std'), opMxBasis.equivalent('std')) #transform operation matrix into appropriate basis return _bt.change_basis(opMxInStdBasis, opMxBasis.equivalent('std'), opMxBasis) def sum_of_negative_choi_evals(model, weights=None): """ Compute the amount of non-CP-ness of a model by summing the negative eigenvalues of the Choi matrix for each gate in model. Parameters ---------- model : Model The model to act on. weights : dict A dictionary of weights used to multiply the negative eigenvalues of different gates. Keys are operation labels, values are floating point numbers. Returns ------- float the sum of negative eigenvalues of the Choi matrix for each gate. """ if weights is not None: default = weights.get('gates', 1.0) sums = sums_of_negative_choi_evals(model) return sum([s * weights.get(gl, default) for gl, s in zip(model.operations.keys(), sums)]) else: return sum(sums_of_negative_choi_evals(model)) def sums_of_negative_choi_evals(model): """ Compute the amount of non-CP-ness of a model by summing the negative eigenvalues of the Choi matrix for each gate in model separately. Parameters ---------- model : Model The model to act on. Returns ------- list of floats each element == sum of the negative eigenvalues of the Choi matrix for the corresponding gate (as ordered by model.operations.iteritems()). """ ret = [] for (_, gate) in model.operations.items(): J = fast_jamiolkowski_iso_std(gate, model.basis) # Choi mx basis doesn't matter evals = _np.linalg.eigvals(J) # could use eigvalsh, but wary of this since eigh can be wrong... sumOfNeg = 0.0 for ev in evals: if ev.real < 0: sumOfNeg -= ev.real ret.append(sumOfNeg) return ret def mags_of_negative_choi_evals(model): """ Compute the magnitudes of the negative eigenvalues of the Choi matricies for each gate in model. Parameters ---------- model : Model The model to act on. Returns ------- list of floats list of the magnitues of all negative Choi eigenvalues. The length of this list will vary based on how many negative eigenvalues are found, as positive eigenvalues contribute nothing to this list. """ ret = [] for (_, gate) in model.operations.items(): J = jamiolkowski_iso(gate, model.basis, choiMxBasis=model.basis.simple_equivalent('std')) evals = _np.linalg.eigvals(J) # could use eigvalsh, but wary of this since eigh can be wrong... for ev in evals: ret.append(-ev.real if ev.real < 0 else 0.0) return ret
<filename>pygsti/tools/jamiolkowski.py<gh_stars>1-10 """Utility functions related to the Choi representation of gates.""" #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this software. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** import numpy as _np from ..objects.basis import Basis as _Basis from . import basistools as _bt from . import matrixtools as _mt # Gate Mx G: rho --> G rho where G and rho are in the Pauli basis (by definition/convention) # noqa # vec(rhoS) --> GStd vec(rhoS) where GS and rhoS are in the std basis, GS = PtoS * G * StoP # noqa # Choi Mx J: rho --> sum_ij Jij Bi rho Bj^dag where Bi is some basis of mxs for rho-space; independent of basis for rho and Bi # noqa # vec(rhoS) --> sum_ij Jij (BSi x BSj^*) vec(rhoS) where rhoS and BSi's are in std basis # noqa # Now, # noqa # Jkl = Trace( sum_ij Jij (BSi x BSj^*) , (BSk x BSl^*)^dag ) / Trace( (BSk x BSl^*), (BSk x BSl^*)^dag ) # noqa # = Trace( GStd , (BSk x BSl^*)^dag ) / Trace( (BSk x BSl^*), (BSk x BSl^*)^dag ) # noqa # In below function, take Bi's to be Pauli matrices # Note: vec(.) vectorization above is assumed to be done by-*rows* (as numpy.flatten does). # Note that in just the std basis, the construction of the Jamiolkowski representation of a process phi is # noqa # J(Phi) = sum_(0<i,j<n) Phi(|i><j|) x |i><j| where {|i>}_1^n spans the state space # noqa # # Derivation: if we write: # noqa # Phi(|i><j|) = sum_kl C[(kl)(ij)] |k><l| # noqa # and # noqa # rho = sum_ij rho_ij |i><j| # noqa # then # noqa # Phi(rho) = sum_(ij)(kl) C[(kl)(ij)] rho_ij |k><l| # noqa # = sum_(ij)(kl) C[(kl)(ij)] |k> rho_ij <l| # noqa # = sum_(ij)(kl) C[(kl)(ij)] |k> <i| rho |j> <l| # noqa # = sum_(ij)(kl) C[(ik)(jl)] |i> <j| rho |l> <k| (just permute index labels) # noqa # The definition of the Jamiolkoski matrix J is: # noqa # Phi(rho) = sum_(ij)(kl) J(ij)(kl) |i><j| rho |l><k| # noqa # so # noqa # J(ij)(kl) == C[(ik)(jl)] # noqa # # Note: |i><j| x |k><l| is an object in "gate/process" space, since # noqa # it maps a vectorized density matrix, e.g. |a><b| to another density matrix via: # noqa # (|i><j| x |k><l|) vec(|a><b|) = [mx with 1 in (i*dmDim + k) row and (j*dmDim + l) col][vec with 1 in a*dmDim+b row] # noqa # = vec(|i><k|) if |a><b| == |j><l| else 0 # noqa # so (|i><j| x |k><l|) vec(|j><l|) = vec(|i><k|) # noqa # and could write as: (|ik><jl|) |jl> = |ik> # noqa # # Now write J as: # noqa # J = sum_ijkl |ij> J(ij)(kl) <kl| # noqa # = sum_ijkl J(ij)(kl) |ij> <kl| # noqa # = sum_ijkl J(ij)(kl) (|i><k| x |j><l|) # noqa # = sum_ijkl C(ik)(jl) (|i><k| x |j><l|) # noqa # = sum_jl [ sum_ik C(ik)(jl) |i><k| ] x |j><l| (using Note above) # noqa # = sum_jl Phi(|j><l|) x |j><l| (using definition Phi(|i><j|) = sum_kl C[(kl)(ij)] |k><l|) # noqa # which is the original J(Phi) expression. # noqa # # This can be written equivalently as: # noqa # J(Phi) = sum_(0<i,j<n) Phi(Eij) otimes Eij # noqa # where Eij is the matrix unit with a single element in the (i,j)-th position, i.e. Eij == |i><j| # noqa def jamiolkowski_iso(operationMx, opMxBasis='pp', choiMxBasis='pp'): """ Given a operation matrix, return the corresponding Choi matrix that is normalized to have trace == 1. Parameters ---------- operationMx : numpy array the operation matrix to compute Choi matrix of. opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). choiMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array the Choi matrix, normalized to have trace == 1, in the desired basis. """ operationMx = _np.asarray(operationMx) opMxBasis = _bt.build_basis_for_matrix(operationMx, opMxBasis) opMxInStdBasis = _bt.change_basis(operationMx, opMxBasis, opMxBasis.equivalent('std')) #expand operation matrix so it acts on entire space of dmDim x dmDim density matrices # so that we can take dot products with the BVec matrices below opMxInStdBasis = _bt.resize_std_mx(opMxInStdBasis, 'expand', opMxBasis.equivalent( 'std'), opMxBasis.simple_equivalent('std')) N = opMxInStdBasis.shape[0] # dimension of the full-basis (expanded) gate dmDim = int(round(_np.sqrt(N))) # density matrix dimension #Note: we need to use the *full* basis of Matrix Unit, Gell-Mann, or Pauli-product matrices when # generating the Choi matrix, even when the original operation matrix doesn't include the entire basis. # This is because even when the original operation matrix doesn't include a certain basis element (B0 say), # conjugating with this basis element and tracing, i.e. trace(B0^dag * Operation * B0), is not necessarily zero. #get full list of basis matrices (in std basis) -- i.e. we use dmDim if not isinstance(choiMxBasis, _Basis): choiMxBasis = _Basis.cast(choiMxBasis, N) # we'd like a basis of dimension N BVec = choiMxBasis.simple_equivalent().elements M = len(BVec) # can be < N if basis has multiple block dims assert(M == N), 'Expected {}, got {}'.format(M, N) choiMx = _np.empty((N, N), 'complex') for i in range(M): for j in range(M): BiBj = _np.kron(BVec[i], _np.conjugate(BVec[j])) BiBj_dag = _np.transpose(_np.conjugate(BiBj)) choiMx[i, j] = _mt.trace(_np.dot(opMxInStdBasis, BiBj_dag)) \ / _mt.trace(_np.dot(BiBj, BiBj_dag)) # This construction results in a Jmx with trace == dim(H) = sqrt(operationMx.shape[0]) (dimension of density matrix) # but we'd like a Jmx with trace == 1, so normalize: choiMx_normalized = choiMx / dmDim return choiMx_normalized # GStd = sum_ij Jij (BSi x BSj^*) def jamiolkowski_iso_inv(choiMx, choiMxBasis='pp', opMxBasis='pp'): """ Given a choi matrix, return the corresponding operation matrix. This function performs the inverse of jamiolkowski_iso(...). Parameters ---------- choiMx : numpy array the Choi matrix, normalized to have trace == 1, to compute operation matrix for. choiMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array operation matrix in the desired basis. """ choiMx = _np.asarray(choiMx) # will have "expanded" dimension even if bases are for reduced... N = choiMx.shape[0] # dimension of full-basis (expanded) operation matrix if not isinstance(choiMxBasis, _Basis): # if we're not given a basis, build choiMxBasis = _Basis.cast(choiMxBasis, N) # one with the full dimension dmDim = int(round(_np.sqrt(N))) # density matrix dimension #get full list of basis matrices (in std basis) BVec = _bt.basis_matrices(choiMxBasis.simple_equivalent(), N) assert(len(BVec) == N) # make sure the number of basis matrices matches the dim of the choi matrix given # Invert normalization choiMx_unnorm = choiMx * dmDim opMxInStdBasis = _np.zeros((N, N), 'complex') # in matrix unit basis of entire density matrix for i in range(N): for j in range(N): BiBj = _np.kron(BVec[i], _np.conjugate(BVec[j])) opMxInStdBasis += choiMx_unnorm[i, j] * BiBj if not isinstance(opMxBasis, _Basis): opMxBasis = _Basis.cast(opMxBasis, N) # make sure opMxBasis is a Basis; we'd like dimension to be N #project operation matrix so it acts only on the space given by the desired state space blocks opMxInStdBasis = _bt.resize_std_mx(opMxInStdBasis, 'contract', opMxBasis.simple_equivalent('std'), opMxBasis.equivalent('std')) #transform operation matrix into appropriate basis return _bt.change_basis(opMxInStdBasis, opMxBasis.equivalent('std'), opMxBasis) def fast_jamiolkowski_iso_std(operationMx, opMxBasis): """ Given a operation matrix, return the corresponding Choi matrix in the standard basis that is normalized to have trace == 1. This routine *only* computes the case of the Choi matrix being in the standard (matrix unit) basis, but does so more quickly than :func:`jamiolkowski_iso` and so is particuarly useful when only the eigenvalues of the Choi matrix are needed. Parameters ---------- operationMx : numpy array the operation matrix to compute Choi matrix of. opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array the Choi matrix, normalized to have trace == 1, in the std basis. """ #first, get operation matrix into std basis operationMx = _np.asarray(operationMx) opMxBasis = _bt.build_basis_for_matrix(operationMx, opMxBasis) opMxInStdBasis = _bt.change_basis(operationMx, opMxBasis, opMxBasis.equivalent('std')) #expand operation matrix so it acts on entire space of dmDim x dmDim density matrices opMxInStdBasis = _bt.resize_std_mx(opMxInStdBasis, 'expand', opMxBasis.equivalent('std'), opMxBasis.simple_equivalent('std')) #Shuffle indices to go from process matrix to Jamiolkowski matrix (they vectorize differently) N2 = opMxInStdBasis.shape[0]; N = int(_np.sqrt(N2)) assert(N * N == N2) # make sure N2 is a perfect square Jmx = opMxInStdBasis.reshape((N, N, N, N)) Jmx = _np.swapaxes(Jmx, 1, 2).flatten() Jmx = Jmx.reshape((N2, N2)) # This construction results in a Jmx with trace == dim(H) = sqrt(gateMxInPauliBasis.shape[0]) # but we'd like a Jmx with trace == 1, so normalize: Jmx_norm = Jmx / N return Jmx_norm def fast_jamiolkowski_iso_std_inv(choiMx, opMxBasis): """ Given a choi matrix in the standard basis, return the corresponding operation matrix. This function performs the inverse of fast_jamiolkowski_iso_std(...). Parameters ---------- choiMx : numpy array the Choi matrix in the standard (matrix units) basis, normalized to have trace == 1, to compute operation matrix for. opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array operation matrix in the desired basis. """ #Shuffle indices to go from process matrix to Jamiolkowski matrix (they vectorize differently) N2 = choiMx.shape[0]; N = int(_np.sqrt(N2)) assert(N * N == N2) # make sure N2 is a perfect square opMxInStdBasis = choiMx.reshape((N, N, N, N)) * N opMxInStdBasis = _np.swapaxes(opMxInStdBasis, 1, 2).flatten() opMxInStdBasis = opMxInStdBasis.reshape((N2, N2)) opMxBasis = _bt.build_basis_for_matrix(opMxInStdBasis, opMxBasis) #project operation matrix so it acts only on the space given by the desired state space blocks opMxInStdBasis = _bt.resize_std_mx(opMxInStdBasis, 'contract', opMxBasis.simple_equivalent('std'), opMxBasis.equivalent('std')) #transform operation matrix into appropriate basis return _bt.change_basis(opMxInStdBasis, opMxBasis.equivalent('std'), opMxBasis) def sum_of_negative_choi_evals(model, weights=None): """ Compute the amount of non-CP-ness of a model by summing the negative eigenvalues of the Choi matrix for each gate in model. Parameters ---------- model : Model The model to act on. weights : dict A dictionary of weights used to multiply the negative eigenvalues of different gates. Keys are operation labels, values are floating point numbers. Returns ------- float the sum of negative eigenvalues of the Choi matrix for each gate. """ if weights is not None: default = weights.get('gates', 1.0) sums = sums_of_negative_choi_evals(model) return sum([s * weights.get(gl, default) for gl, s in zip(model.operations.keys(), sums)]) else: return sum(sums_of_negative_choi_evals(model)) def sums_of_negative_choi_evals(model): """ Compute the amount of non-CP-ness of a model by summing the negative eigenvalues of the Choi matrix for each gate in model separately. Parameters ---------- model : Model The model to act on. Returns ------- list of floats each element == sum of the negative eigenvalues of the Choi matrix for the corresponding gate (as ordered by model.operations.iteritems()). """ ret = [] for (_, gate) in model.operations.items(): J = fast_jamiolkowski_iso_std(gate, model.basis) # Choi mx basis doesn't matter evals = _np.linalg.eigvals(J) # could use eigvalsh, but wary of this since eigh can be wrong... sumOfNeg = 0.0 for ev in evals: if ev.real < 0: sumOfNeg -= ev.real ret.append(sumOfNeg) return ret def mags_of_negative_choi_evals(model): """ Compute the magnitudes of the negative eigenvalues of the Choi matricies for each gate in model. Parameters ---------- model : Model The model to act on. Returns ------- list of floats list of the magnitues of all negative Choi eigenvalues. The length of this list will vary based on how many negative eigenvalues are found, as positive eigenvalues contribute nothing to this list. """ ret = [] for (_, gate) in model.operations.items(): J = jamiolkowski_iso(gate, model.basis, choiMxBasis=model.basis.simple_equivalent('std')) evals = _np.linalg.eigvals(J) # could use eigvalsh, but wary of this since eigh can be wrong... for ev in evals: ret.append(-ev.real if ev.real < 0 else 0.0) return ret
en
0.742288
Utility functions related to the Choi representation of gates. #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this software. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** # Gate Mx G: rho --> G rho where G and rho are in the Pauli basis (by definition/convention) # noqa # vec(rhoS) --> GStd vec(rhoS) where GS and rhoS are in the std basis, GS = PtoS * G * StoP # noqa # Choi Mx J: rho --> sum_ij Jij Bi rho Bj^dag where Bi is some basis of mxs for rho-space; independent of basis for rho and Bi # noqa # vec(rhoS) --> sum_ij Jij (BSi x BSj^*) vec(rhoS) where rhoS and BSi's are in std basis # noqa # Now, # noqa # Jkl = Trace( sum_ij Jij (BSi x BSj^*) , (BSk x BSl^*)^dag ) / Trace( (BSk x BSl^*), (BSk x BSl^*)^dag ) # noqa # = Trace( GStd , (BSk x BSl^*)^dag ) / Trace( (BSk x BSl^*), (BSk x BSl^*)^dag ) # noqa # In below function, take Bi's to be Pauli matrices # Note: vec(.) vectorization above is assumed to be done by-*rows* (as numpy.flatten does). # Note that in just the std basis, the construction of the Jamiolkowski representation of a process phi is # noqa # J(Phi) = sum_(0<i,j<n) Phi(|i><j|) x |i><j| where {|i>}_1^n spans the state space # noqa # # Derivation: if we write: # noqa # Phi(|i><j|) = sum_kl C[(kl)(ij)] |k><l| # noqa # and # noqa # rho = sum_ij rho_ij |i><j| # noqa # then # noqa # Phi(rho) = sum_(ij)(kl) C[(kl)(ij)] rho_ij |k><l| # noqa # = sum_(ij)(kl) C[(kl)(ij)] |k> rho_ij <l| # noqa # = sum_(ij)(kl) C[(kl)(ij)] |k> <i| rho |j> <l| # noqa # = sum_(ij)(kl) C[(ik)(jl)] |i> <j| rho |l> <k| (just permute index labels) # noqa # The definition of the Jamiolkoski matrix J is: # noqa # Phi(rho) = sum_(ij)(kl) J(ij)(kl) |i><j| rho |l><k| # noqa # so # noqa # J(ij)(kl) == C[(ik)(jl)] # noqa # # Note: |i><j| x |k><l| is an object in "gate/process" space, since # noqa # it maps a vectorized density matrix, e.g. |a><b| to another density matrix via: # noqa # (|i><j| x |k><l|) vec(|a><b|) = [mx with 1 in (i*dmDim + k) row and (j*dmDim + l) col][vec with 1 in a*dmDim+b row] # noqa # = vec(|i><k|) if |a><b| == |j><l| else 0 # noqa # so (|i><j| x |k><l|) vec(|j><l|) = vec(|i><k|) # noqa # and could write as: (|ik><jl|) |jl> = |ik> # noqa # # Now write J as: # noqa # J = sum_ijkl |ij> J(ij)(kl) <kl| # noqa # = sum_ijkl J(ij)(kl) |ij> <kl| # noqa # = sum_ijkl J(ij)(kl) (|i><k| x |j><l|) # noqa # = sum_ijkl C(ik)(jl) (|i><k| x |j><l|) # noqa # = sum_jl [ sum_ik C(ik)(jl) |i><k| ] x |j><l| (using Note above) # noqa # = sum_jl Phi(|j><l|) x |j><l| (using definition Phi(|i><j|) = sum_kl C[(kl)(ij)] |k><l|) # noqa # which is the original J(Phi) expression. # noqa # # This can be written equivalently as: # noqa # J(Phi) = sum_(0<i,j<n) Phi(Eij) otimes Eij # noqa # where Eij is the matrix unit with a single element in the (i,j)-th position, i.e. Eij == |i><j| # noqa Given a operation matrix, return the corresponding Choi matrix that is normalized to have trace == 1. Parameters ---------- operationMx : numpy array the operation matrix to compute Choi matrix of. opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). choiMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array the Choi matrix, normalized to have trace == 1, in the desired basis. #expand operation matrix so it acts on entire space of dmDim x dmDim density matrices # so that we can take dot products with the BVec matrices below # dimension of the full-basis (expanded) gate # density matrix dimension #Note: we need to use the *full* basis of Matrix Unit, Gell-Mann, or Pauli-product matrices when # generating the Choi matrix, even when the original operation matrix doesn't include the entire basis. # This is because even when the original operation matrix doesn't include a certain basis element (B0 say), # conjugating with this basis element and tracing, i.e. trace(B0^dag * Operation * B0), is not necessarily zero. #get full list of basis matrices (in std basis) -- i.e. we use dmDim # we'd like a basis of dimension N # can be < N if basis has multiple block dims # This construction results in a Jmx with trace == dim(H) = sqrt(operationMx.shape[0]) (dimension of density matrix) # but we'd like a Jmx with trace == 1, so normalize: # GStd = sum_ij Jij (BSi x BSj^*) Given a choi matrix, return the corresponding operation matrix. This function performs the inverse of jamiolkowski_iso(...). Parameters ---------- choiMx : numpy array the Choi matrix, normalized to have trace == 1, to compute operation matrix for. choiMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array operation matrix in the desired basis. # will have "expanded" dimension even if bases are for reduced... # dimension of full-basis (expanded) operation matrix # if we're not given a basis, build # one with the full dimension # density matrix dimension #get full list of basis matrices (in std basis) # make sure the number of basis matrices matches the dim of the choi matrix given # Invert normalization # in matrix unit basis of entire density matrix # make sure opMxBasis is a Basis; we'd like dimension to be N #project operation matrix so it acts only on the space given by the desired state space blocks #transform operation matrix into appropriate basis Given a operation matrix, return the corresponding Choi matrix in the standard basis that is normalized to have trace == 1. This routine *only* computes the case of the Choi matrix being in the standard (matrix unit) basis, but does so more quickly than :func:`jamiolkowski_iso` and so is particuarly useful when only the eigenvalues of the Choi matrix are needed. Parameters ---------- operationMx : numpy array the operation matrix to compute Choi matrix of. opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array the Choi matrix, normalized to have trace == 1, in the std basis. #first, get operation matrix into std basis #expand operation matrix so it acts on entire space of dmDim x dmDim density matrices #Shuffle indices to go from process matrix to Jamiolkowski matrix (they vectorize differently) # make sure N2 is a perfect square # This construction results in a Jmx with trace == dim(H) = sqrt(gateMxInPauliBasis.shape[0]) # but we'd like a Jmx with trace == 1, so normalize: Given a choi matrix in the standard basis, return the corresponding operation matrix. This function performs the inverse of fast_jamiolkowski_iso_std(...). Parameters ---------- choiMx : numpy array the Choi matrix in the standard (matrix units) basis, normalized to have trace == 1, to compute operation matrix for. opMxBasis : Basis object The source and destination basis, respectively. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object). Returns ------- numpy array operation matrix in the desired basis. #Shuffle indices to go from process matrix to Jamiolkowski matrix (they vectorize differently) # make sure N2 is a perfect square #project operation matrix so it acts only on the space given by the desired state space blocks #transform operation matrix into appropriate basis Compute the amount of non-CP-ness of a model by summing the negative eigenvalues of the Choi matrix for each gate in model. Parameters ---------- model : Model The model to act on. weights : dict A dictionary of weights used to multiply the negative eigenvalues of different gates. Keys are operation labels, values are floating point numbers. Returns ------- float the sum of negative eigenvalues of the Choi matrix for each gate. Compute the amount of non-CP-ness of a model by summing the negative eigenvalues of the Choi matrix for each gate in model separately. Parameters ---------- model : Model The model to act on. Returns ------- list of floats each element == sum of the negative eigenvalues of the Choi matrix for the corresponding gate (as ordered by model.operations.iteritems()). # Choi mx basis doesn't matter # could use eigvalsh, but wary of this since eigh can be wrong... Compute the magnitudes of the negative eigenvalues of the Choi matricies for each gate in model. Parameters ---------- model : Model The model to act on. Returns ------- list of floats list of the magnitues of all negative Choi eigenvalues. The length of this list will vary based on how many negative eigenvalues are found, as positive eigenvalues contribute nothing to this list. # could use eigvalsh, but wary of this since eigh can be wrong...
2.022131
2
src/z3c/testsetup/tests/cave/samplesetup_short3.py
zopefoundation/z3c.testsetup
1
6625099
import z3c.testsetup from z3c.testsetup.tests import cave test_suite = z3c.testsetup.register_pytests(cave)
import z3c.testsetup from z3c.testsetup.tests import cave test_suite = z3c.testsetup.register_pytests(cave)
none
1
1.065164
1
backend/reqlock/models/ogranisation_role.py
ChaikaBogdan/reqlock
1
6625100
from django.db import models from .organisation import Organisation from .model_mixins import SoftDeleteModel class OrganisationRole(SoftDeleteModel): code = models.CharField(max_length=255) name = models.CharField(max_length=255) organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE) def __str__(self): return self.name
from django.db import models from .organisation import Organisation from .model_mixins import SoftDeleteModel class OrganisationRole(SoftDeleteModel): code = models.CharField(max_length=255) name = models.CharField(max_length=255) organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE) def __str__(self): return self.name
none
1
2.119909
2
dashboard/dashboard/find_anomalies_test.py
blezek/catapult
0
6625101
<gh_stars>0 # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import unittest import mock from dashboard import find_anomalies from dashboard import find_change_points from dashboard.common import testing_common from dashboard.common import utils from dashboard.models import anomaly from dashboard.models import graph_data from dashboard.models import histogram from dashboard.models import sheriff from tracing.value.diagnostics import reserved_infos # Sample time series. _TEST_ROW_DATA = [ (241105, 2136.7), (241116, 2140.3), (241151, 2149.1), (241154, 2147.2), (241156, 2130.6), (241160, 2136.2), (241188, 2146.7), (241201, 2141.8), (241226, 2140.6), (241247, 2128.1), (241249, 2134.2), (241254, 2130.0), (241262, 2136.0), (241268, 2142.6), (241271, 2149.1), (241282, 2156.6), (241294, 2125.3), (241298, 2155.5), (241303, 2148.5), (241317, 2146.2), (241323, 2123.3), (241330, 2121.5), (241342, 2141.2), (241355, 2145.2), (241371, 2136.3), (241386, 2144.0), (241405, 2138.1), (241420, 2147.6), (241432, 2140.7), (241441, 2132.2), (241452, 2138.2), (241455, 2139.3), (241471, 2134.0), (241488, 2137.2), (241503, 2152.5), (241520, 2136.3), (241524, 2139.3), (241529, 2143.5), (241532, 2145.5), (241535, 2147.0), (241537, 2184.1), (241546, 2180.8), (241553, 2181.5), (241559, 2176.8), (241566, 2174.0), (241577, 2182.8), (241579, 2184.8), (241582, 2190.5), (241584, 2183.1), (241609, 2178.3), (241620, 2178.1), (241645, 2190.8), (241653, 2177.7), (241666, 2185.3), (241697, 2173.8), (241716, 2172.1), (241735, 2172.5), (241757, 2174.7), (241766, 2196.7), (241782, 2184.1), ] def _MakeSampleChangePoint(x_value, median_before, median_after): """Makes a sample find_change_points.ChangePoint for use in these tests.""" # The only thing that matters in these tests is the revision number # and the values before and after. return find_change_points.ChangePoint( x_value=x_value, median_before=median_before, median_after=median_after, window_start=1, window_end=8, size_before=None, size_after=None, relative_change=None, std_dev_before=None, t_statistic=None, degrees_of_freedom=None, p_value=None) class EndRevisionMatcher(object): """Custom matcher to test if an anomaly matches a given end rev.""" def __init__(self, end_revision): """Initializes with the end time to check.""" self._end_revision = end_revision def __eq__(self, rhs): """Checks to see if RHS has the same end time.""" return self._end_revision == rhs.end_revision def __repr__(self): """Shows a readable revision which can be printed when assert fails.""" return '<IsEndRevision %d>' % self._end_revision class ModelMatcher(object): """Custom matcher to check if two ndb entity names match.""" def __init__(self, name): """Initializes with the name of the entity.""" self._name = name def __eq__(self, rhs): """Checks to see if RHS has the same name.""" return rhs.key.string_id() == self._name def __repr__(self): """Shows a readable revision which can be printed when assert fails.""" return '<IsModel %s>' % self._name class ProcessAlertsTest(testing_common.TestCase): def setUp(self): super(ProcessAlertsTest, self).setUp() self.SetCurrentUser('<EMAIL>', is_admin=True) def _AddDataForTests(self): testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'scrolling_benchmark': { 'ref': {}, }, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() ref.units = 'ms' for i in range(9000, 10070, 5): # Internal-only data should be found. test_container_key = utils.GetTestContainerKey(ref.key) graph_data.Row( id=i + 1, value=float(i * 3), parent=test_container_key, internal_only=True).put() @mock.patch.object( find_anomalies.find_change_points, 'FindChangePoints', mock.MagicMock(return_value=[ _MakeSampleChangePoint(10011, 50, 100), _MakeSampleChangePoint(10041, 200, 100), _MakeSampleChangePoint(10061, 0, 100), ])) @mock.patch.object(find_anomalies.email_sheriff, 'EmailSheriff') def testProcessTest(self, mock_email_sheriff): self._AddDataForTests() test_path = 'ChromiumGPU/linux-release/scrolling_benchmark/ref' test = utils.TestKey(test_path).get() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test_path]).put() test.put() find_anomalies.ProcessTests([test.key]) expected_calls = [ mock.call(ModelMatcher('sheriff'), ModelMatcher( 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10011)), mock.call(ModelMatcher('sheriff'), ModelMatcher( 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10041)), mock.call(ModelMatcher('sheriff'), ModelMatcher( 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10061))] self.assertEqual(expected_calls, mock_email_sheriff.call_args_list) anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(len(anomalies), 3) def AnomalyExists( anomalies, test, percent_changed, direction, start_revision, end_revision, sheriff_name, internal_only, units, absolute_delta): for a in anomalies: if (a.test == test and a.percent_changed == percent_changed and a.direction == direction and a.start_revision == start_revision and a.end_revision == end_revision and a.sheriff.string_id() == sheriff_name and a.internal_only == internal_only and a.units == units and a.absolute_delta == absolute_delta): return True return False self.assertTrue( AnomalyExists( anomalies, test.key, percent_changed=100, direction=anomaly.UP, start_revision=10007, end_revision=10011, sheriff_name='sheriff', internal_only=False, units='ms', absolute_delta=50)) self.assertTrue( AnomalyExists( anomalies, test.key, percent_changed=-50, direction=anomaly.DOWN, start_revision=10037, end_revision=10041, sheriff_name='sheriff', internal_only=False, units='ms', absolute_delta=-100)) self.assertTrue( AnomalyExists( anomalies, test.key, percent_changed=sys.float_info.max, direction=anomaly.UP, start_revision=10057, end_revision=10061, sheriff_name='sheriff', internal_only=False, units='ms', absolute_delta=100)) # This is here just to verify that AnomalyExists returns False sometimes. self.assertFalse( AnomalyExists( anomalies, test.key, percent_changed=100, direction=anomaly.DOWN, start_revision=10037, end_revision=10041, sheriff_name='sheriff', internal_only=False, units='ms', absolute_delta=500)) @mock.patch.object( find_anomalies.find_change_points, 'FindChangePoints', mock.MagicMock(return_value=[ _MakeSampleChangePoint(10011, 100, 50) ])) def testProcessTest_ImprovementMarkedAsImprovement(self): self._AddDataForTests() test = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test.test_path]).put() test.improvement_direction = anomaly.DOWN test.put() find_anomalies.ProcessTests([test.key]) anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(len(anomalies), 1) self.assertTrue(anomalies[0].is_improvement) @mock.patch('logging.error') def testProcessTest_NoSheriff_ErrorLogged(self, mock_logging_error): self._AddDataForTests() ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() find_anomalies.ProcessTests([ref.key]) mock_logging_error.assert_called_with('No sheriff for %s', ref.key) @mock.patch.object( find_anomalies.find_change_points, 'FindChangePoints', mock.MagicMock(return_value=[ _MakeSampleChangePoint(10026, 55.2, 57.8), _MakeSampleChangePoint(10041, 45.2, 37.8), ])) @mock.patch.object(find_anomalies.email_sheriff, 'EmailSheriff') def testProcessTest_FiltersOutImprovements(self, mock_email_sheriff): self._AddDataForTests() test = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test.test_path]).put() test.improvement_direction = anomaly.UP test.put() find_anomalies.ProcessTests([test.key]) mock_email_sheriff.assert_called_once_with( ModelMatcher('sheriff'), ModelMatcher('ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10041)) @mock.patch.object( find_anomalies.find_change_points, 'FindChangePoints', mock.MagicMock(return_value=[ _MakeSampleChangePoint(10011, 50, 100), ])) @mock.patch.object(find_anomalies.email_sheriff, 'EmailSheriff') def testProcessTest_InternalOnlyTest(self, mock_email_sheriff): self._AddDataForTests() test = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() test.internal_only = True sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test.test_path]).put() test.put() find_anomalies.ProcessTests([test.key]) expected_calls = [ mock.call(ModelMatcher('sheriff'), ModelMatcher( 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10011))] self.assertEqual(expected_calls, mock_email_sheriff.call_args_list) anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(len(anomalies), 1) self.assertEqual(test.key, anomalies[0].test) self.assertEqual(100, anomalies[0].percent_changed) self.assertEqual(anomaly.UP, anomalies[0].direction) self.assertEqual(10007, anomalies[0].start_revision) self.assertEqual(10011, anomalies[0].end_revision) self.assertTrue(anomalies[0].internal_only) def testProcessTest_CreatesAnAnomaly_RefMovesToo_BenchmarkDuration(self): testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'foo': {'benchmark_duration': {'ref': {}}}, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/foo/benchmark_duration/ref').get() non_ref = utils.TestKey( 'ChromiumGPU/linux-release/foo/benchmark_duration').get() test_container_key = utils.GetTestContainerKey(ref.key) test_container_key_non_ref = utils.GetTestContainerKey(non_ref.key) for row in _TEST_ROW_DATA: graph_data.Row(id=row[0], value=row[1], parent=test_container_key).put() graph_data.Row(id=row[0], value=row[1], parent=test_container_key_non_ref).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[ref.test_path]).put() ref.put() find_anomalies.ProcessTests([ref.key]) new_anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(1, len(new_anomalies)) def testProcessTest_AnomaliesMatchRefSeries_NoAlertCreated(self): # Tests that a Anomaly entity is not created if both the test and its # corresponding ref build series have the same data. testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'scrolling_benchmark': {'ref': {}}, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() non_ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark').get() test_container_key = utils.GetTestContainerKey(ref.key) test_container_key_non_ref = utils.GetTestContainerKey(non_ref.key) for row in _TEST_ROW_DATA: graph_data.Row(id=row[0], value=row[1], parent=test_container_key).put() graph_data.Row(id=row[0], value=row[1], parent=test_container_key_non_ref).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[non_ref.test_path]).put() ref.put() non_ref.put() find_anomalies.ProcessTests([non_ref.key]) new_anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(0, len(new_anomalies)) def testProcessTest_AnomalyDoesNotMatchRefSeries_AlertCreated(self): # Tests that an Anomaly entity is created when non-ref series goes up, but # the ref series stays flat. testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'scrolling_benchmark': {'ref': {}}, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() non_ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark').get() test_container_key = utils.GetTestContainerKey(ref.key) test_container_key_non_ref = utils.GetTestContainerKey(non_ref.key) for row in _TEST_ROW_DATA: graph_data.Row(id=row[0], value=2125.375, parent=test_container_key).put() graph_data.Row(id=row[0], value=row[1], parent=test_container_key_non_ref).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[ref.test_path]).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[non_ref.test_path]).put() ref.put() non_ref.put() find_anomalies.ProcessTests([non_ref.key]) new_anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(len(new_anomalies), 1) def testProcessTest_CreatesAnAnomaly(self): testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'scrolling_benchmark': {'ref': {}}, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() test_container_key = utils.GetTestContainerKey(ref.key) for row in _TEST_ROW_DATA: graph_data.Row(id=row[0], value=row[1], parent=test_container_key).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[ref.test_path]).put() ref.put() find_anomalies.ProcessTests([ref.key]) new_anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(1, len(new_anomalies)) self.assertEqual(anomaly.UP, new_anomalies[0].direction) self.assertEqual(241536, new_anomalies[0].start_revision) self.assertEqual(241537, new_anomalies[0].end_revision) @mock.patch('logging.error') def testProcessTest_LastAlertedRevisionTooHigh_PropertyReset( self, mock_logging_error): # If the last_alerted_revision property of the TestMetadata is too high, # then the property should be reset and an error should be logged. self._AddDataForTests() test = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test.test_path]).put() test.last_alerted_revision = 1234567890 test.put() find_anomalies.ProcessTests([test.key]) self.assertIsNone(test.key.get().last_alerted_revision) calls = [ mock.call( 'last_alerted_revision %d is higher than highest rev %d for test ' '%s; setting last_alerted_revision to None.', 1234567890, 10066, 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), mock.call( 'No rows fetched for %s', 'ChromiumGPU/linux-release/scrolling_benchmark/ref') ] mock_logging_error.assert_has_calls(calls, any_order=True) def testMakeAnomalyEntity_NoRefBuild(self): testing_common.AddTests( ['ChromiumPerf'], ['linux'], { 'page_cycler_v2': { 'cnn': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = utils.TestKey('ChromiumPerf/linux/page_cycler_v2').get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(10011, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertIsNone(alert.ref_test) def testMakeAnomalyEntity_RefBuildSlash(self): testing_common.AddTests( ['ChromiumPerf'], ['linux'], { 'page_cycler_v2': { 'ref': {}, 'cnn': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = utils.TestKey('ChromiumPerf/linux/page_cycler_v2').get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(10011, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertEqual(alert.ref_test.string_id(), 'ChromiumPerf/linux/page_cycler_v2/ref') def testMakeAnomalyEntity_RefBuildUnderscore(self): testing_common.AddTests( ['ChromiumPerf'], ['linux'], { 'page_cycler_v2': { 'cnn': {}, 'cnn_ref': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = utils.TestKey('ChromiumPerf/linux/page_cycler_v2/cnn').get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(10011, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertEqual(alert.ref_test.string_id(), 'ChromiumPerf/linux/page_cycler_v2/cnn_ref') self.assertIsNone(alert.display_start) self.assertIsNone(alert.display_end) def testMakeAnomalyEntity_RevisionRanges(self): testing_common.AddTests( ['ClankInternal'], ['linux'], { 'page_cycler_v2': { 'cnn': {}, 'cnn_ref': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = utils.TestKey('ClankInternal/linux/page_cycler_v2/cnn').get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) for row in graph_data.Row.query(): row.r_commit_pos = int(row.value) + 2 # Different enough to ensure it is # picked up properly. row.put() alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(300, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertEqual(alert.display_start, 203) self.assertEqual(alert.display_end, 302) def testMakeAnomalyEntity_AddsOwnership(self): data_samples = [ { 'type': 'GenericSet', 'guid': 'eb212e80-db58-4cbd-b331-c2245ecbb826', 'values': ['<EMAIL>', '<EMAIL>'] }, { 'type': 'GenericSet', 'guid': 'eb212e80-db58-4cbd-b331-c2245ecbb827', 'values': ['abc'] }] test_key = utils.TestKey('ChromiumPerf/linux/page_cycler_v2/cnn') testing_common.AddTests( ['ChromiumPerf'], ['linux'], { 'page_cycler_v2': { 'cnn': {}, 'cnn_ref': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = test_key.get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) suite_key = utils.TestKey('ChromiumPerf/linux/page_cycler_v2') entity = histogram.SparseDiagnostic( data=data_samples[0], test=suite_key, start_revision=1, end_revision=sys.maxint, id=data_samples[0]['guid'], name=reserved_infos.OWNERS.name) entity.put() entity = histogram.SparseDiagnostic( data=data_samples[1], test=suite_key, start_revision=1, end_revision=sys.maxint, id=data_samples[1]['guid'], name=reserved_infos.BUG_COMPONENTS.name) entity.put() alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(10011, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertEqual(alert.ownership['component'], 'abc') self.assertListEqual(alert.ownership['emails'], ['<EMAIL>', '<EMAIL>']) if __name__ == '__main__': unittest.main()
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import unittest import mock from dashboard import find_anomalies from dashboard import find_change_points from dashboard.common import testing_common from dashboard.common import utils from dashboard.models import anomaly from dashboard.models import graph_data from dashboard.models import histogram from dashboard.models import sheriff from tracing.value.diagnostics import reserved_infos # Sample time series. _TEST_ROW_DATA = [ (241105, 2136.7), (241116, 2140.3), (241151, 2149.1), (241154, 2147.2), (241156, 2130.6), (241160, 2136.2), (241188, 2146.7), (241201, 2141.8), (241226, 2140.6), (241247, 2128.1), (241249, 2134.2), (241254, 2130.0), (241262, 2136.0), (241268, 2142.6), (241271, 2149.1), (241282, 2156.6), (241294, 2125.3), (241298, 2155.5), (241303, 2148.5), (241317, 2146.2), (241323, 2123.3), (241330, 2121.5), (241342, 2141.2), (241355, 2145.2), (241371, 2136.3), (241386, 2144.0), (241405, 2138.1), (241420, 2147.6), (241432, 2140.7), (241441, 2132.2), (241452, 2138.2), (241455, 2139.3), (241471, 2134.0), (241488, 2137.2), (241503, 2152.5), (241520, 2136.3), (241524, 2139.3), (241529, 2143.5), (241532, 2145.5), (241535, 2147.0), (241537, 2184.1), (241546, 2180.8), (241553, 2181.5), (241559, 2176.8), (241566, 2174.0), (241577, 2182.8), (241579, 2184.8), (241582, 2190.5), (241584, 2183.1), (241609, 2178.3), (241620, 2178.1), (241645, 2190.8), (241653, 2177.7), (241666, 2185.3), (241697, 2173.8), (241716, 2172.1), (241735, 2172.5), (241757, 2174.7), (241766, 2196.7), (241782, 2184.1), ] def _MakeSampleChangePoint(x_value, median_before, median_after): """Makes a sample find_change_points.ChangePoint for use in these tests.""" # The only thing that matters in these tests is the revision number # and the values before and after. return find_change_points.ChangePoint( x_value=x_value, median_before=median_before, median_after=median_after, window_start=1, window_end=8, size_before=None, size_after=None, relative_change=None, std_dev_before=None, t_statistic=None, degrees_of_freedom=None, p_value=None) class EndRevisionMatcher(object): """Custom matcher to test if an anomaly matches a given end rev.""" def __init__(self, end_revision): """Initializes with the end time to check.""" self._end_revision = end_revision def __eq__(self, rhs): """Checks to see if RHS has the same end time.""" return self._end_revision == rhs.end_revision def __repr__(self): """Shows a readable revision which can be printed when assert fails.""" return '<IsEndRevision %d>' % self._end_revision class ModelMatcher(object): """Custom matcher to check if two ndb entity names match.""" def __init__(self, name): """Initializes with the name of the entity.""" self._name = name def __eq__(self, rhs): """Checks to see if RHS has the same name.""" return rhs.key.string_id() == self._name def __repr__(self): """Shows a readable revision which can be printed when assert fails.""" return '<IsModel %s>' % self._name class ProcessAlertsTest(testing_common.TestCase): def setUp(self): super(ProcessAlertsTest, self).setUp() self.SetCurrentUser('<EMAIL>', is_admin=True) def _AddDataForTests(self): testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'scrolling_benchmark': { 'ref': {}, }, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() ref.units = 'ms' for i in range(9000, 10070, 5): # Internal-only data should be found. test_container_key = utils.GetTestContainerKey(ref.key) graph_data.Row( id=i + 1, value=float(i * 3), parent=test_container_key, internal_only=True).put() @mock.patch.object( find_anomalies.find_change_points, 'FindChangePoints', mock.MagicMock(return_value=[ _MakeSampleChangePoint(10011, 50, 100), _MakeSampleChangePoint(10041, 200, 100), _MakeSampleChangePoint(10061, 0, 100), ])) @mock.patch.object(find_anomalies.email_sheriff, 'EmailSheriff') def testProcessTest(self, mock_email_sheriff): self._AddDataForTests() test_path = 'ChromiumGPU/linux-release/scrolling_benchmark/ref' test = utils.TestKey(test_path).get() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test_path]).put() test.put() find_anomalies.ProcessTests([test.key]) expected_calls = [ mock.call(ModelMatcher('sheriff'), ModelMatcher( 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10011)), mock.call(ModelMatcher('sheriff'), ModelMatcher( 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10041)), mock.call(ModelMatcher('sheriff'), ModelMatcher( 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10061))] self.assertEqual(expected_calls, mock_email_sheriff.call_args_list) anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(len(anomalies), 3) def AnomalyExists( anomalies, test, percent_changed, direction, start_revision, end_revision, sheriff_name, internal_only, units, absolute_delta): for a in anomalies: if (a.test == test and a.percent_changed == percent_changed and a.direction == direction and a.start_revision == start_revision and a.end_revision == end_revision and a.sheriff.string_id() == sheriff_name and a.internal_only == internal_only and a.units == units and a.absolute_delta == absolute_delta): return True return False self.assertTrue( AnomalyExists( anomalies, test.key, percent_changed=100, direction=anomaly.UP, start_revision=10007, end_revision=10011, sheriff_name='sheriff', internal_only=False, units='ms', absolute_delta=50)) self.assertTrue( AnomalyExists( anomalies, test.key, percent_changed=-50, direction=anomaly.DOWN, start_revision=10037, end_revision=10041, sheriff_name='sheriff', internal_only=False, units='ms', absolute_delta=-100)) self.assertTrue( AnomalyExists( anomalies, test.key, percent_changed=sys.float_info.max, direction=anomaly.UP, start_revision=10057, end_revision=10061, sheriff_name='sheriff', internal_only=False, units='ms', absolute_delta=100)) # This is here just to verify that AnomalyExists returns False sometimes. self.assertFalse( AnomalyExists( anomalies, test.key, percent_changed=100, direction=anomaly.DOWN, start_revision=10037, end_revision=10041, sheriff_name='sheriff', internal_only=False, units='ms', absolute_delta=500)) @mock.patch.object( find_anomalies.find_change_points, 'FindChangePoints', mock.MagicMock(return_value=[ _MakeSampleChangePoint(10011, 100, 50) ])) def testProcessTest_ImprovementMarkedAsImprovement(self): self._AddDataForTests() test = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test.test_path]).put() test.improvement_direction = anomaly.DOWN test.put() find_anomalies.ProcessTests([test.key]) anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(len(anomalies), 1) self.assertTrue(anomalies[0].is_improvement) @mock.patch('logging.error') def testProcessTest_NoSheriff_ErrorLogged(self, mock_logging_error): self._AddDataForTests() ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() find_anomalies.ProcessTests([ref.key]) mock_logging_error.assert_called_with('No sheriff for %s', ref.key) @mock.patch.object( find_anomalies.find_change_points, 'FindChangePoints', mock.MagicMock(return_value=[ _MakeSampleChangePoint(10026, 55.2, 57.8), _MakeSampleChangePoint(10041, 45.2, 37.8), ])) @mock.patch.object(find_anomalies.email_sheriff, 'EmailSheriff') def testProcessTest_FiltersOutImprovements(self, mock_email_sheriff): self._AddDataForTests() test = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test.test_path]).put() test.improvement_direction = anomaly.UP test.put() find_anomalies.ProcessTests([test.key]) mock_email_sheriff.assert_called_once_with( ModelMatcher('sheriff'), ModelMatcher('ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10041)) @mock.patch.object( find_anomalies.find_change_points, 'FindChangePoints', mock.MagicMock(return_value=[ _MakeSampleChangePoint(10011, 50, 100), ])) @mock.patch.object(find_anomalies.email_sheriff, 'EmailSheriff') def testProcessTest_InternalOnlyTest(self, mock_email_sheriff): self._AddDataForTests() test = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() test.internal_only = True sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test.test_path]).put() test.put() find_anomalies.ProcessTests([test.key]) expected_calls = [ mock.call(ModelMatcher('sheriff'), ModelMatcher( 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), EndRevisionMatcher(10011))] self.assertEqual(expected_calls, mock_email_sheriff.call_args_list) anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(len(anomalies), 1) self.assertEqual(test.key, anomalies[0].test) self.assertEqual(100, anomalies[0].percent_changed) self.assertEqual(anomaly.UP, anomalies[0].direction) self.assertEqual(10007, anomalies[0].start_revision) self.assertEqual(10011, anomalies[0].end_revision) self.assertTrue(anomalies[0].internal_only) def testProcessTest_CreatesAnAnomaly_RefMovesToo_BenchmarkDuration(self): testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'foo': {'benchmark_duration': {'ref': {}}}, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/foo/benchmark_duration/ref').get() non_ref = utils.TestKey( 'ChromiumGPU/linux-release/foo/benchmark_duration').get() test_container_key = utils.GetTestContainerKey(ref.key) test_container_key_non_ref = utils.GetTestContainerKey(non_ref.key) for row in _TEST_ROW_DATA: graph_data.Row(id=row[0], value=row[1], parent=test_container_key).put() graph_data.Row(id=row[0], value=row[1], parent=test_container_key_non_ref).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[ref.test_path]).put() ref.put() find_anomalies.ProcessTests([ref.key]) new_anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(1, len(new_anomalies)) def testProcessTest_AnomaliesMatchRefSeries_NoAlertCreated(self): # Tests that a Anomaly entity is not created if both the test and its # corresponding ref build series have the same data. testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'scrolling_benchmark': {'ref': {}}, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() non_ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark').get() test_container_key = utils.GetTestContainerKey(ref.key) test_container_key_non_ref = utils.GetTestContainerKey(non_ref.key) for row in _TEST_ROW_DATA: graph_data.Row(id=row[0], value=row[1], parent=test_container_key).put() graph_data.Row(id=row[0], value=row[1], parent=test_container_key_non_ref).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[non_ref.test_path]).put() ref.put() non_ref.put() find_anomalies.ProcessTests([non_ref.key]) new_anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(0, len(new_anomalies)) def testProcessTest_AnomalyDoesNotMatchRefSeries_AlertCreated(self): # Tests that an Anomaly entity is created when non-ref series goes up, but # the ref series stays flat. testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'scrolling_benchmark': {'ref': {}}, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() non_ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark').get() test_container_key = utils.GetTestContainerKey(ref.key) test_container_key_non_ref = utils.GetTestContainerKey(non_ref.key) for row in _TEST_ROW_DATA: graph_data.Row(id=row[0], value=2125.375, parent=test_container_key).put() graph_data.Row(id=row[0], value=row[1], parent=test_container_key_non_ref).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[ref.test_path]).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[non_ref.test_path]).put() ref.put() non_ref.put() find_anomalies.ProcessTests([non_ref.key]) new_anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(len(new_anomalies), 1) def testProcessTest_CreatesAnAnomaly(self): testing_common.AddTests( ['ChromiumGPU'], ['linux-release'], { 'scrolling_benchmark': {'ref': {}}, }) ref = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() test_container_key = utils.GetTestContainerKey(ref.key) for row in _TEST_ROW_DATA: graph_data.Row(id=row[0], value=row[1], parent=test_container_key).put() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[ref.test_path]).put() ref.put() find_anomalies.ProcessTests([ref.key]) new_anomalies = anomaly.Anomaly.query().fetch() self.assertEqual(1, len(new_anomalies)) self.assertEqual(anomaly.UP, new_anomalies[0].direction) self.assertEqual(241536, new_anomalies[0].start_revision) self.assertEqual(241537, new_anomalies[0].end_revision) @mock.patch('logging.error') def testProcessTest_LastAlertedRevisionTooHigh_PropertyReset( self, mock_logging_error): # If the last_alerted_revision property of the TestMetadata is too high, # then the property should be reset and an error should be logged. self._AddDataForTests() test = utils.TestKey( 'ChromiumGPU/linux-release/scrolling_benchmark/ref').get() sheriff.Sheriff( email='<EMAIL>', id='sheriff', patterns=[test.test_path]).put() test.last_alerted_revision = 1234567890 test.put() find_anomalies.ProcessTests([test.key]) self.assertIsNone(test.key.get().last_alerted_revision) calls = [ mock.call( 'last_alerted_revision %d is higher than highest rev %d for test ' '%s; setting last_alerted_revision to None.', 1234567890, 10066, 'ChromiumGPU/linux-release/scrolling_benchmark/ref'), mock.call( 'No rows fetched for %s', 'ChromiumGPU/linux-release/scrolling_benchmark/ref') ] mock_logging_error.assert_has_calls(calls, any_order=True) def testMakeAnomalyEntity_NoRefBuild(self): testing_common.AddTests( ['ChromiumPerf'], ['linux'], { 'page_cycler_v2': { 'cnn': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = utils.TestKey('ChromiumPerf/linux/page_cycler_v2').get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(10011, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertIsNone(alert.ref_test) def testMakeAnomalyEntity_RefBuildSlash(self): testing_common.AddTests( ['ChromiumPerf'], ['linux'], { 'page_cycler_v2': { 'ref': {}, 'cnn': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = utils.TestKey('ChromiumPerf/linux/page_cycler_v2').get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(10011, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertEqual(alert.ref_test.string_id(), 'ChromiumPerf/linux/page_cycler_v2/ref') def testMakeAnomalyEntity_RefBuildUnderscore(self): testing_common.AddTests( ['ChromiumPerf'], ['linux'], { 'page_cycler_v2': { 'cnn': {}, 'cnn_ref': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = utils.TestKey('ChromiumPerf/linux/page_cycler_v2/cnn').get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(10011, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertEqual(alert.ref_test.string_id(), 'ChromiumPerf/linux/page_cycler_v2/cnn_ref') self.assertIsNone(alert.display_start) self.assertIsNone(alert.display_end) def testMakeAnomalyEntity_RevisionRanges(self): testing_common.AddTests( ['ClankInternal'], ['linux'], { 'page_cycler_v2': { 'cnn': {}, 'cnn_ref': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = utils.TestKey('ClankInternal/linux/page_cycler_v2/cnn').get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) for row in graph_data.Row.query(): row.r_commit_pos = int(row.value) + 2 # Different enough to ensure it is # picked up properly. row.put() alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(300, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertEqual(alert.display_start, 203) self.assertEqual(alert.display_end, 302) def testMakeAnomalyEntity_AddsOwnership(self): data_samples = [ { 'type': 'GenericSet', 'guid': 'eb212e80-db58-4cbd-b331-c2245ecbb826', 'values': ['<EMAIL>', '<EMAIL>'] }, { 'type': 'GenericSet', 'guid': 'eb212e80-db58-4cbd-b331-c2245ecbb827', 'values': ['abc'] }] test_key = utils.TestKey('ChromiumPerf/linux/page_cycler_v2/cnn') testing_common.AddTests( ['ChromiumPerf'], ['linux'], { 'page_cycler_v2': { 'cnn': {}, 'cnn_ref': {}, 'yahoo': {}, 'nytimes': {}, }, }) test = test_key.get() testing_common.AddRows(test.test_path, [100, 200, 300, 400]) suite_key = utils.TestKey('ChromiumPerf/linux/page_cycler_v2') entity = histogram.SparseDiagnostic( data=data_samples[0], test=suite_key, start_revision=1, end_revision=sys.maxint, id=data_samples[0]['guid'], name=reserved_infos.OWNERS.name) entity.put() entity = histogram.SparseDiagnostic( data=data_samples[1], test=suite_key, start_revision=1, end_revision=sys.maxint, id=data_samples[1]['guid'], name=reserved_infos.BUG_COMPONENTS.name) entity.put() alert = find_anomalies._MakeAnomalyEntity( _MakeSampleChangePoint(10011, 50, 100), test, list(graph_data.Row.query())).get_result() self.assertEqual(alert.ownership['component'], 'abc') self.assertListEqual(alert.ownership['emails'], ['<EMAIL>', '<EMAIL>']) if __name__ == '__main__': unittest.main()
en
0.891171
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Sample time series. Makes a sample find_change_points.ChangePoint for use in these tests. # The only thing that matters in these tests is the revision number # and the values before and after. Custom matcher to test if an anomaly matches a given end rev. Initializes with the end time to check. Checks to see if RHS has the same end time. Shows a readable revision which can be printed when assert fails. Custom matcher to check if two ndb entity names match. Initializes with the name of the entity. Checks to see if RHS has the same name. Shows a readable revision which can be printed when assert fails. # Internal-only data should be found. # This is here just to verify that AnomalyExists returns False sometimes. # Tests that a Anomaly entity is not created if both the test and its # corresponding ref build series have the same data. # Tests that an Anomaly entity is created when non-ref series goes up, but # the ref series stays flat. # If the last_alerted_revision property of the TestMetadata is too high, # then the property should be reset and an error should be logged. # Different enough to ensure it is # picked up properly.
1.892878
2
tests/conftest.py
uktrade/directory-ch-client
0
6625102
def pytest_configure(): from django.conf import settings settings.configure( URLS_EXCLUDED_FROM_SIGNATURE_CHECK=[], DIRECTORY_CH_SEARCH_CLIENT_BASE_URL='https://chsearch.com', DIRECTORY_CH_SEARCH_CLIENT_API_KEY='test-api-key', DIRECTORY_CH_SEARCH_CLIENT_SENDER_ID='test-sender', DIRECTORY_CH_SEARCH_CLIENT_DEFAULT_TIMEOUT=5, )
def pytest_configure(): from django.conf import settings settings.configure( URLS_EXCLUDED_FROM_SIGNATURE_CHECK=[], DIRECTORY_CH_SEARCH_CLIENT_BASE_URL='https://chsearch.com', DIRECTORY_CH_SEARCH_CLIENT_API_KEY='test-api-key', DIRECTORY_CH_SEARCH_CLIENT_SENDER_ID='test-sender', DIRECTORY_CH_SEARCH_CLIENT_DEFAULT_TIMEOUT=5, )
none
1
1.518798
2
alembic/versions/2a68ba66c32b_add_active_translation_users.py
go-lab/appcomposer
1
6625103
<reponame>go-lab/appcomposer """Add Active translation users Revision ID: <KEY> Revises: <KEY> Create Date: 2015-04-27 13:32:26.521250 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '<KEY>' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('TranslationCurrentActiveUsers', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bundle_id', sa.Integer(), nullable=True), sa.Column('last_check', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['bundle_id'], ['TranslationBundles.id'], ), sa.ForeignKeyConstraint(['user_id'], ['GoLabOAuthUsers.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(u'ix_TranslationCurrentActiveUsers_last_check', 'TranslationCurrentActiveUsers', ['last_check'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(u'ix_TranslationCurrentActiveUsers_last_check', table_name='TranslationCurrentActiveUsers') op.drop_table('TranslationCurrentActiveUsers') ### end Alembic commands ###
"""Add Active translation users Revision ID: <KEY> Revises: <KEY> Create Date: 2015-04-27 13:32:26.521250 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '<KEY>' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('TranslationCurrentActiveUsers', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('bundle_id', sa.Integer(), nullable=True), sa.Column('last_check', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['bundle_id'], ['TranslationBundles.id'], ), sa.ForeignKeyConstraint(['user_id'], ['GoLabOAuthUsers.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(u'ix_TranslationCurrentActiveUsers_last_check', 'TranslationCurrentActiveUsers', ['last_check'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(u'ix_TranslationCurrentActiveUsers_last_check', table_name='TranslationCurrentActiveUsers') op.drop_table('TranslationCurrentActiveUsers') ### end Alembic commands ###
en
0.513171
Add Active translation users Revision ID: <KEY> Revises: <KEY> Create Date: 2015-04-27 13:32:26.521250 # revision identifiers, used by Alembic. ### commands auto generated by Alembic - please adjust! ### ### end Alembic commands ### ### commands auto generated by Alembic - please adjust! ### ### end Alembic commands ###
1.372053
1
main/pre.py
noil-lion/licencePlateRecognition
0
6625104
<filename>main/pre.py import cv2 import numpy as np def img_preprocess(img): print("这是预处理") height = img.shape[0] width = img.shape[1] img = cv2.GaussianBlur(img, (3, 3), 0) # 高斯模糊去噪点 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) sobel = cv2.Sobel(thresh, cv2.CV_16S, 1, 0, ksize=1) # 垂直边缘检测sobel算子 sobel = cv2.convertScaleAbs(sobel) ret, sobel = cv2.threshold(sobel, 127, 255, cv2.THRESH_OTSU) kernel = np.ones((1, 5), np.uint8) kernel2 = np.ones((5, 1), np.uint8) erosion = cv2.dilate(sobel, kernel, iterations=2) erosion = cv2.erode(erosion, kernel, iterations=1) erosion = cv2.dilate(erosion, kernel2, iterations=1) contours, hier = cv2.findContours(erosion, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) area = 0 for c in contours: x, y, w, h = cv2.boundingRect(c) if (w/h >= 2 and w/h <= 4): if w*h > area and area < 2000: plate = img[y:y+h, x:x+w] area = w*h cv2.imshow('sobel', sobel) cv2.imshow('plate', plate) cv2.imshow('img', img) cv2.imshow('erosion', erosion) cv2.waitKey() cv2.destroyAllWindows() plate = img[int(height/2):height][0:width] return plate
<filename>main/pre.py import cv2 import numpy as np def img_preprocess(img): print("这是预处理") height = img.shape[0] width = img.shape[1] img = cv2.GaussianBlur(img, (3, 3), 0) # 高斯模糊去噪点 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) sobel = cv2.Sobel(thresh, cv2.CV_16S, 1, 0, ksize=1) # 垂直边缘检测sobel算子 sobel = cv2.convertScaleAbs(sobel) ret, sobel = cv2.threshold(sobel, 127, 255, cv2.THRESH_OTSU) kernel = np.ones((1, 5), np.uint8) kernel2 = np.ones((5, 1), np.uint8) erosion = cv2.dilate(sobel, kernel, iterations=2) erosion = cv2.erode(erosion, kernel, iterations=1) erosion = cv2.dilate(erosion, kernel2, iterations=1) contours, hier = cv2.findContours(erosion, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) area = 0 for c in contours: x, y, w, h = cv2.boundingRect(c) if (w/h >= 2 and w/h <= 4): if w*h > area and area < 2000: plate = img[y:y+h, x:x+w] area = w*h cv2.imshow('sobel', sobel) cv2.imshow('plate', plate) cv2.imshow('img', img) cv2.imshow('erosion', erosion) cv2.waitKey() cv2.destroyAllWindows() plate = img[int(height/2):height][0:width] return plate
zh
0.512055
# 高斯模糊去噪点 # 垂直边缘检测sobel算子
3.078723
3
titan/react_state_pkg/behavior/resources.py
mnieber/gen
0
6625105
<filename>titan/react_state_pkg/behavior/resources.py from dataclasses import dataclass from moonleap import Resource from moonleap.utils.inflect import plural @dataclass class Behavior(Resource): name: str item_name: str @property def items_name(self): return plural(self.item_name)
<filename>titan/react_state_pkg/behavior/resources.py from dataclasses import dataclass from moonleap import Resource from moonleap.utils.inflect import plural @dataclass class Behavior(Resource): name: str item_name: str @property def items_name(self): return plural(self.item_name)
none
1
2.018085
2
tests/resources/gatling/gatling-fake.py
IamSaurabh1/taurus
1,743
6625106
<reponame>IamSaurabh1/taurus import os import sys import platform print("Fake gatling output") print("dir:") print(os.path.abspath(os.curdir)) if len(sys.argv) == 2 and sys.argv[1] == '--help': exit(0) java_opts = os.environ.get("JAVA_OPTS", "").strip() + " " res_dir_opt = "gatling.core.directory.resources" start_res_dir = java_opts.find(res_dir_opt) + len(res_dir_opt) + 1 res_dir_str = java_opts[start_res_dir:] res_dir = res_dir_str[:res_dir_str.find(" -D")] if platform.system() != "Windows": res_dir = res_dir[1:-1] scala_files = [fname for fname in os.listdir(res_dir) if fname.endswith('scala')] if len(scala_files) > 1: print("Choose a simulation number:") input() print("started...") default_gatling_home = "False" gatling_home = os.environ.get("GATLING_HOME", default_gatling_home) os.environ["GATLING_HOME"] = gatling_home java_opts = "-server -XX:+UseThreadPriorities -XX:ThreadPriorityPolicy=42 -Xms512M -Xmx512M -Xmn100M " java_opts += "-XX:+HeapDumpOnOutOfMemoryError -XX:+AggressiveOpts -XX:+OptimizeStringConcat " java_opts += "-XX:+UseFastAccessorMethods -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled " java_opts += "-Djava.net.preferIPv4Stack='true' -Djava.net.preferIPv6Addresses='false' " java_opts += os.environ.get("JAVA_OPTS", "") os.environ["JAVA_OPTS"] = java_opts jars = [] jar_dir = os.path.join(gatling_home, "lib") if os.path.isdir(jar_dir): for fname in os.listdir(jar_dir): if os.path.isfile(fname) and fname.endswith(".jar"): jars.append(fname) compilation_classpath = ';'.join(jars) os.environ["COMPILATION_CLASSPATH"] = ':'.join((compilation_classpath, os.environ.get("COMPILATION_CLASSPATH", ""))) print(os.environ.get("GATLING_HOME", "")) print(os.environ.get("COMPILATION_CLASSPATH", "")) print(os.environ.get("NO_PAUSE", "")) print(os.environ.get("JAVA_OPTS", ""))
import os import sys import platform print("Fake gatling output") print("dir:") print(os.path.abspath(os.curdir)) if len(sys.argv) == 2 and sys.argv[1] == '--help': exit(0) java_opts = os.environ.get("JAVA_OPTS", "").strip() + " " res_dir_opt = "gatling.core.directory.resources" start_res_dir = java_opts.find(res_dir_opt) + len(res_dir_opt) + 1 res_dir_str = java_opts[start_res_dir:] res_dir = res_dir_str[:res_dir_str.find(" -D")] if platform.system() != "Windows": res_dir = res_dir[1:-1] scala_files = [fname for fname in os.listdir(res_dir) if fname.endswith('scala')] if len(scala_files) > 1: print("Choose a simulation number:") input() print("started...") default_gatling_home = "False" gatling_home = os.environ.get("GATLING_HOME", default_gatling_home) os.environ["GATLING_HOME"] = gatling_home java_opts = "-server -XX:+UseThreadPriorities -XX:ThreadPriorityPolicy=42 -Xms512M -Xmx512M -Xmn100M " java_opts += "-XX:+HeapDumpOnOutOfMemoryError -XX:+AggressiveOpts -XX:+OptimizeStringConcat " java_opts += "-XX:+UseFastAccessorMethods -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled " java_opts += "-Djava.net.preferIPv4Stack='true' -Djava.net.preferIPv6Addresses='false' " java_opts += os.environ.get("JAVA_OPTS", "") os.environ["JAVA_OPTS"] = java_opts jars = [] jar_dir = os.path.join(gatling_home, "lib") if os.path.isdir(jar_dir): for fname in os.listdir(jar_dir): if os.path.isfile(fname) and fname.endswith(".jar"): jars.append(fname) compilation_classpath = ';'.join(jars) os.environ["COMPILATION_CLASSPATH"] = ':'.join((compilation_classpath, os.environ.get("COMPILATION_CLASSPATH", ""))) print(os.environ.get("GATLING_HOME", "")) print(os.environ.get("COMPILATION_CLASSPATH", "")) print(os.environ.get("NO_PAUSE", "")) print(os.environ.get("JAVA_OPTS", ""))
none
1
2.03057
2
app/core/safety/digest.py
zhongxinghong/EECS-Volunteer-Reservation-2-Backend
0
6625107
<filename>app/core/safety/digest.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # filename: digest.py # modified: 2019-10-25 __all__ = [ "bMD5", "bSHA1", "bSHA256", "xMD5", "xSHA1", "xSHA256", "bHMAC_MD5", "bHMAC_SHA1", "bHMAC_SHA256", "xHMAC_MD5", "xHMAC_SHA1", "xHMAC_SHA256", ] import hashlib import hmac from ..utils.func import b, u def bMD5(s): return hashlib.md5(b(s)).digest() def bSHA1(s): return hashlib.sha1(b(s)).digest() def bSHA256(s): return hashlib.sha256(b(s)).digest() def xMD5(s): return hashlib.md5(b(s)).hexdigest() def xSHA1(s): return hashlib.sha1(b(s)).hexdigest() def xSHA256(s): return hashlib.sha256(b(s)).hexdigest() def bHMAC_MD5(k, s): return hmac.new(b(k), b(s), hashlib.md5).digest() def bHMAC_SHA1(k, s): return hmac.new(b(k), b(s), hashlib.sha1).digest() def bHMAC_SHA256(k, s): return hmac.new(b(k), b(s), hashlib.sha256).digest() def xHMAC_MD5(k, s): return hmac.new(b(k), b(s), hashlib.md5).hexdigest() def xHMAC_SHA1(k, s): return hmac.new(b(k), b(s), hashlib.sha1).hexdigest() def xHMAC_SHA256(k, s): return hmac.new(b(k), b(s), hashlib.sha256).hexdigest()
<filename>app/core/safety/digest.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # filename: digest.py # modified: 2019-10-25 __all__ = [ "bMD5", "bSHA1", "bSHA256", "xMD5", "xSHA1", "xSHA256", "bHMAC_MD5", "bHMAC_SHA1", "bHMAC_SHA256", "xHMAC_MD5", "xHMAC_SHA1", "xHMAC_SHA256", ] import hashlib import hmac from ..utils.func import b, u def bMD5(s): return hashlib.md5(b(s)).digest() def bSHA1(s): return hashlib.sha1(b(s)).digest() def bSHA256(s): return hashlib.sha256(b(s)).digest() def xMD5(s): return hashlib.md5(b(s)).hexdigest() def xSHA1(s): return hashlib.sha1(b(s)).hexdigest() def xSHA256(s): return hashlib.sha256(b(s)).hexdigest() def bHMAC_MD5(k, s): return hmac.new(b(k), b(s), hashlib.md5).digest() def bHMAC_SHA1(k, s): return hmac.new(b(k), b(s), hashlib.sha1).digest() def bHMAC_SHA256(k, s): return hmac.new(b(k), b(s), hashlib.sha256).digest() def xHMAC_MD5(k, s): return hmac.new(b(k), b(s), hashlib.md5).hexdigest() def xHMAC_SHA1(k, s): return hmac.new(b(k), b(s), hashlib.sha1).hexdigest() def xHMAC_SHA256(k, s): return hmac.new(b(k), b(s), hashlib.sha256).hexdigest()
en
0.409658
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # filename: digest.py # modified: 2019-10-25
2.05219
2
redisolar/dao/redis/meter_reading.py
gbpereira1/ru102py
0
6625108
<reponame>gbpereira1/ru102py from redisolar.dao.base import MeterReadingDaoBase from redisolar.dao.redis.base import RedisDaoBase from redisolar.dao.redis.capacity_report import CapacityReportDaoRedis from redisolar.dao.redis.feed import FeedDaoRedis from redisolar.dao.redis.metric_timeseries import MetricDaoRedisTimeseries from redisolar.models import MeterReading # Uncomment for Challenge #3 # from redisolar.dao.redis.site_stats import SiteStatsDaoRedis class MeterReadingDaoRedis(MeterReadingDaoBase, RedisDaoBase): """MeterReadingDaoRedis persists MeterReading models to Redis.""" def add(self, meter_reading: MeterReading, **kwargs) -> None: MetricDaoRedisTimeseries(self.redis, self.key_schema).insert(meter_reading, **kwargs) CapacityReportDaoRedis(self.redis, self.key_schema).update(meter_reading, **kwargs) FeedDaoRedis(self.redis, self.key_schema).insert(meter_reading, **kwargs) # Uncomment for Challenge #3 # SiteStatsDaoRedis(self.redis, self.key_schema).update(meter_reading, **kwargs)
from redisolar.dao.base import MeterReadingDaoBase from redisolar.dao.redis.base import RedisDaoBase from redisolar.dao.redis.capacity_report import CapacityReportDaoRedis from redisolar.dao.redis.feed import FeedDaoRedis from redisolar.dao.redis.metric_timeseries import MetricDaoRedisTimeseries from redisolar.models import MeterReading # Uncomment for Challenge #3 # from redisolar.dao.redis.site_stats import SiteStatsDaoRedis class MeterReadingDaoRedis(MeterReadingDaoBase, RedisDaoBase): """MeterReadingDaoRedis persists MeterReading models to Redis.""" def add(self, meter_reading: MeterReading, **kwargs) -> None: MetricDaoRedisTimeseries(self.redis, self.key_schema).insert(meter_reading, **kwargs) CapacityReportDaoRedis(self.redis, self.key_schema).update(meter_reading, **kwargs) FeedDaoRedis(self.redis, self.key_schema).insert(meter_reading, **kwargs) # Uncomment for Challenge #3 # SiteStatsDaoRedis(self.redis, self.key_schema).update(meter_reading, **kwargs)
en
0.292206
# Uncomment for Challenge #3 # from redisolar.dao.redis.site_stats import SiteStatsDaoRedis MeterReadingDaoRedis persists MeterReading models to Redis. # Uncomment for Challenge #3 # SiteStatsDaoRedis(self.redis, self.key_schema).update(meter_reading, **kwargs)
1.963066
2
eventory/eventorial.py
siku2/Eventory
1
6625109
"""This module contains the Eventorial class and its utility functions. Attributes: URL_REGEX (Pattern): Regex used to check if a string is a url SANITISE_REGEX_STEPS (Tuple[Pattern]): Regex applied to a string in order to obtain a sanitised version of said string. """ import asyncio import logging import os import re from io import TextIOBase from os import path from tempfile import TemporaryDirectory from typing import Any, Union from aiohttp import ClientSession from yarl import URL from . import constants from .eventory import Eventory from .exceptions import EventoryAlreadyLoaded from .parser import load URL_REGEX = re.compile(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+") SANITISE_REGEX_STEPS = ( (re.compile(r"[^a-z0-9_ ]+"), ""), # remove unwanted chars (re.compile(r"[ _]+"), " "), # reduce space (re.compile(r"(^ +)|( +$)"), "") # trim ends ) _DEFAULT = object() log = logging.getLogger(__name__) class Eventorial: """An environment for Eventories. Args: directory: Directory path to store data in. If not provided the Eventorial uses a temporary directory which will be destroyed at the end. When provided with a path, the Eventorial loads all files that already exist in the directory. loop: Loop to use for various async operations. Uses asyncio.get_event_loop() if not specified. Attributes: eventories (Dict[str, Eventory]): Dictionary containing all loaded Eventories loop (AbstractEventLoop): Loop being used aiosession (ClientSession): ClientSession used for internet access directory (str): Path to directory used to store data """ def __init__(self, directory: str = None, *, loop=None): self.eventories = {} self.loop = loop or asyncio.get_event_loop() self.aiosession = ClientSession(loop=self.loop) if directory: self.directory = directory self._load_directory() else: self._tempdir = TemporaryDirectory(prefix="Eventory_") self.directory = self._tempdir.name log.debug(f"{self} created temporary directory in {self.directory}") def __str__(self): return f"<Eventorial {len(self.eventories)} Eventory/ies loaded>" def __len__(self): return len(self.eventories) def __del__(self): self.cleanup() def __contains__(self, item): return (item in self.eventories.keys()) or bool(self.get(item)) def __delitem__(self, key): return self.remove(key) def __getitem__(self, item): return self.get(item) def __iter__(self): return iter(self.eventories) def _load_directory(self): names = os.listdir(self.directory) loaded_eventories = 0 for name in names: if name.endswith(constants.FILE_SUFFIX): with open(path.join(self.directory, name), "r") as f: self.add(load(f)) loaded_eventories += 1 log.info(f"{self} loaded {loaded_eventories} Eventory/ies from directory") def cleanup(self): """Clean the Eventorial. Closes the ClientSession and removes the temporary directory if one has been created. """ if hasattr(self, "_tempdir"): self._tempdir.cleanup() log.debug(f"{self} removed temporary directory") self.loop.create_task(asyncio.gather( self.aiosession.close(), )) log.debug("{self} cleaned up") def add(self, source: Union[Eventory, str, TextIOBase]): """Add an Eventory to this Eventorial. Args: source: Can be an Eventory to add, a string containing a serialised Eventory or an open file to load the Eventory from Raises: TODO """ if isinstance(source, Eventory): eventory = source else: eventory = load(source) sane_title = sanitise_string(eventory.title) if sane_title in self.eventories: raise EventoryAlreadyLoaded(eventory.title) self.eventories[sane_title] = eventory eventory.save(path.join(self.directory, "{filename}")) def remove(self, item: Eventory): """Remove an Eventory from the Eventorial. Args: item: Eventory to removes Raises: KeyError: If the Eventory isn't part of the Eventorial """ title = sanitise_string(item.title) self.eventories.pop(title) os.remove(path.join(self.directory, item.filename)) def get(self, title: str, default: Any = _DEFAULT) -> Eventory: """Get an Eventory from this Eventorial. Args: title: Name of the Eventory to retrieve default: Default value to return if no Eventory found Returns: Eventory Raises: KeyError: If no Eventory with that title was found and default wasn't specified. """ sane_title = sanitise_string(title) story = self.eventories.get(sane_title) if story is None: if default is _DEFAULT: raise KeyError(f"No Eventory with title \"{title}\"") else: return default else: return story async def load_data(self, source: Union[str, URL, TextIOBase], **kwargs) -> str: """Retrieve text from a source. Contrary to the get_data function this method doesn't assume that all strings are urls. It checks whether the string is a url using the URL_REGEX and if it isn't a url it treats it as the name of a file relative to the directory of the Eventorial. Args: source: Source to retrieve text from Returns: str: Retrieved text Raises: TODO """ if isinstance(source, str): if not URL_REGEX.match(source): with open(path.join(self.directory, source), "r", encoding="utf-8") as f: return await self.load_data(f, **kwargs) return await get_data(source, session=self.aiosession, **kwargs) async def load(self, source: Union[str, URL, TextIOBase], **kwargs) -> Eventory: """Load an Eventory from a source into this Eventorial. Contrary to the get_eventory function this method doesn't assume that all strings are urls. It checks whether the string is a url using the URL_REGEX and if it isn't a url it treats it as the name of a file relative to the directory of the Eventorial. Args: source: Source to load Eventory from Returns: Eventory: Eventory that was added to the Eventorial Raises: TODO """ data = await self.load_data(source, **kwargs) eventory = load(data, **kwargs) self.add(eventory) return eventory def sanitise_string(title: str) -> str: """Sanitise a string. Removes all non-alphanumeric characters, trims both ends of redundant spacing and replaces multiple spaces with a single one. Args: title: String to sanitise Returns: str: Sanitised string """ title = title.lower() for regex, repl in SANITISE_REGEX_STEPS: title = regex.sub(repl, title) return title async def get_data(source: Union[str, URL, TextIOBase], session: ClientSession = None, **kwargs) -> str: """Retrieve text from a source. Args: source: Source to get the text from session: Used to fetch online resources Returns: str: Retrieved text Raises: ValueError: When no session was provided but source was a url TypeError: When source isn't of the correct type """ if isinstance(source, (str, URL)): if session is None or not isinstance(session, ClientSession): raise ValueError(f"You need to pass a {ClientSession} in order to download Eventories") async with session.get(source) as resp: data = await resp.text() elif isinstance(source, TextIOBase): data = source.read() else: raise TypeError(f"Make sure to pass the correct type. ({type(source)} is invalid!)") return data async def get_eventory(source: Union[str, URL, TextIOBase], session: ClientSession = None, **kwargs) -> Eventory: """Get an Eventory from a source. Args: source: Source to fetch Eventory from (open file, url) session: Used to fetch online resources Returns: Eventory: Eventory that was loaded from source Raises: ValueError: When no session was provided but source was a url TypeError: When source isn't of the correct type """ data = await get_data(source, session) return load(data, **kwargs)
"""This module contains the Eventorial class and its utility functions. Attributes: URL_REGEX (Pattern): Regex used to check if a string is a url SANITISE_REGEX_STEPS (Tuple[Pattern]): Regex applied to a string in order to obtain a sanitised version of said string. """ import asyncio import logging import os import re from io import TextIOBase from os import path from tempfile import TemporaryDirectory from typing import Any, Union from aiohttp import ClientSession from yarl import URL from . import constants from .eventory import Eventory from .exceptions import EventoryAlreadyLoaded from .parser import load URL_REGEX = re.compile(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+") SANITISE_REGEX_STEPS = ( (re.compile(r"[^a-z0-9_ ]+"), ""), # remove unwanted chars (re.compile(r"[ _]+"), " "), # reduce space (re.compile(r"(^ +)|( +$)"), "") # trim ends ) _DEFAULT = object() log = logging.getLogger(__name__) class Eventorial: """An environment for Eventories. Args: directory: Directory path to store data in. If not provided the Eventorial uses a temporary directory which will be destroyed at the end. When provided with a path, the Eventorial loads all files that already exist in the directory. loop: Loop to use for various async operations. Uses asyncio.get_event_loop() if not specified. Attributes: eventories (Dict[str, Eventory]): Dictionary containing all loaded Eventories loop (AbstractEventLoop): Loop being used aiosession (ClientSession): ClientSession used for internet access directory (str): Path to directory used to store data """ def __init__(self, directory: str = None, *, loop=None): self.eventories = {} self.loop = loop or asyncio.get_event_loop() self.aiosession = ClientSession(loop=self.loop) if directory: self.directory = directory self._load_directory() else: self._tempdir = TemporaryDirectory(prefix="Eventory_") self.directory = self._tempdir.name log.debug(f"{self} created temporary directory in {self.directory}") def __str__(self): return f"<Eventorial {len(self.eventories)} Eventory/ies loaded>" def __len__(self): return len(self.eventories) def __del__(self): self.cleanup() def __contains__(self, item): return (item in self.eventories.keys()) or bool(self.get(item)) def __delitem__(self, key): return self.remove(key) def __getitem__(self, item): return self.get(item) def __iter__(self): return iter(self.eventories) def _load_directory(self): names = os.listdir(self.directory) loaded_eventories = 0 for name in names: if name.endswith(constants.FILE_SUFFIX): with open(path.join(self.directory, name), "r") as f: self.add(load(f)) loaded_eventories += 1 log.info(f"{self} loaded {loaded_eventories} Eventory/ies from directory") def cleanup(self): """Clean the Eventorial. Closes the ClientSession and removes the temporary directory if one has been created. """ if hasattr(self, "_tempdir"): self._tempdir.cleanup() log.debug(f"{self} removed temporary directory") self.loop.create_task(asyncio.gather( self.aiosession.close(), )) log.debug("{self} cleaned up") def add(self, source: Union[Eventory, str, TextIOBase]): """Add an Eventory to this Eventorial. Args: source: Can be an Eventory to add, a string containing a serialised Eventory or an open file to load the Eventory from Raises: TODO """ if isinstance(source, Eventory): eventory = source else: eventory = load(source) sane_title = sanitise_string(eventory.title) if sane_title in self.eventories: raise EventoryAlreadyLoaded(eventory.title) self.eventories[sane_title] = eventory eventory.save(path.join(self.directory, "{filename}")) def remove(self, item: Eventory): """Remove an Eventory from the Eventorial. Args: item: Eventory to removes Raises: KeyError: If the Eventory isn't part of the Eventorial """ title = sanitise_string(item.title) self.eventories.pop(title) os.remove(path.join(self.directory, item.filename)) def get(self, title: str, default: Any = _DEFAULT) -> Eventory: """Get an Eventory from this Eventorial. Args: title: Name of the Eventory to retrieve default: Default value to return if no Eventory found Returns: Eventory Raises: KeyError: If no Eventory with that title was found and default wasn't specified. """ sane_title = sanitise_string(title) story = self.eventories.get(sane_title) if story is None: if default is _DEFAULT: raise KeyError(f"No Eventory with title \"{title}\"") else: return default else: return story async def load_data(self, source: Union[str, URL, TextIOBase], **kwargs) -> str: """Retrieve text from a source. Contrary to the get_data function this method doesn't assume that all strings are urls. It checks whether the string is a url using the URL_REGEX and if it isn't a url it treats it as the name of a file relative to the directory of the Eventorial. Args: source: Source to retrieve text from Returns: str: Retrieved text Raises: TODO """ if isinstance(source, str): if not URL_REGEX.match(source): with open(path.join(self.directory, source), "r", encoding="utf-8") as f: return await self.load_data(f, **kwargs) return await get_data(source, session=self.aiosession, **kwargs) async def load(self, source: Union[str, URL, TextIOBase], **kwargs) -> Eventory: """Load an Eventory from a source into this Eventorial. Contrary to the get_eventory function this method doesn't assume that all strings are urls. It checks whether the string is a url using the URL_REGEX and if it isn't a url it treats it as the name of a file relative to the directory of the Eventorial. Args: source: Source to load Eventory from Returns: Eventory: Eventory that was added to the Eventorial Raises: TODO """ data = await self.load_data(source, **kwargs) eventory = load(data, **kwargs) self.add(eventory) return eventory def sanitise_string(title: str) -> str: """Sanitise a string. Removes all non-alphanumeric characters, trims both ends of redundant spacing and replaces multiple spaces with a single one. Args: title: String to sanitise Returns: str: Sanitised string """ title = title.lower() for regex, repl in SANITISE_REGEX_STEPS: title = regex.sub(repl, title) return title async def get_data(source: Union[str, URL, TextIOBase], session: ClientSession = None, **kwargs) -> str: """Retrieve text from a source. Args: source: Source to get the text from session: Used to fetch online resources Returns: str: Retrieved text Raises: ValueError: When no session was provided but source was a url TypeError: When source isn't of the correct type """ if isinstance(source, (str, URL)): if session is None or not isinstance(session, ClientSession): raise ValueError(f"You need to pass a {ClientSession} in order to download Eventories") async with session.get(source) as resp: data = await resp.text() elif isinstance(source, TextIOBase): data = source.read() else: raise TypeError(f"Make sure to pass the correct type. ({type(source)} is invalid!)") return data async def get_eventory(source: Union[str, URL, TextIOBase], session: ClientSession = None, **kwargs) -> Eventory: """Get an Eventory from a source. Args: source: Source to fetch Eventory from (open file, url) session: Used to fetch online resources Returns: Eventory: Eventory that was loaded from source Raises: ValueError: When no session was provided but source was a url TypeError: When source isn't of the correct type """ data = await get_data(source, session) return load(data, **kwargs)
en
0.845184
This module contains the Eventorial class and its utility functions. Attributes: URL_REGEX (Pattern): Regex used to check if a string is a url SANITISE_REGEX_STEPS (Tuple[Pattern]): Regex applied to a string in order to obtain a sanitised version of said string. # remove unwanted chars # reduce space # trim ends An environment for Eventories. Args: directory: Directory path to store data in. If not provided the Eventorial uses a temporary directory which will be destroyed at the end. When provided with a path, the Eventorial loads all files that already exist in the directory. loop: Loop to use for various async operations. Uses asyncio.get_event_loop() if not specified. Attributes: eventories (Dict[str, Eventory]): Dictionary containing all loaded Eventories loop (AbstractEventLoop): Loop being used aiosession (ClientSession): ClientSession used for internet access directory (str): Path to directory used to store data Clean the Eventorial. Closes the ClientSession and removes the temporary directory if one has been created. Add an Eventory to this Eventorial. Args: source: Can be an Eventory to add, a string containing a serialised Eventory or an open file to load the Eventory from Raises: TODO Remove an Eventory from the Eventorial. Args: item: Eventory to removes Raises: KeyError: If the Eventory isn't part of the Eventorial Get an Eventory from this Eventorial. Args: title: Name of the Eventory to retrieve default: Default value to return if no Eventory found Returns: Eventory Raises: KeyError: If no Eventory with that title was found and default wasn't specified. Retrieve text from a source. Contrary to the get_data function this method doesn't assume that all strings are urls. It checks whether the string is a url using the URL_REGEX and if it isn't a url it treats it as the name of a file relative to the directory of the Eventorial. Args: source: Source to retrieve text from Returns: str: Retrieved text Raises: TODO Load an Eventory from a source into this Eventorial. Contrary to the get_eventory function this method doesn't assume that all strings are urls. It checks whether the string is a url using the URL_REGEX and if it isn't a url it treats it as the name of a file relative to the directory of the Eventorial. Args: source: Source to load Eventory from Returns: Eventory: Eventory that was added to the Eventorial Raises: TODO Sanitise a string. Removes all non-alphanumeric characters, trims both ends of redundant spacing and replaces multiple spaces with a single one. Args: title: String to sanitise Returns: str: Sanitised string Retrieve text from a source. Args: source: Source to get the text from session: Used to fetch online resources Returns: str: Retrieved text Raises: ValueError: When no session was provided but source was a url TypeError: When source isn't of the correct type Get an Eventory from a source. Args: source: Source to fetch Eventory from (open file, url) session: Used to fetch online resources Returns: Eventory: Eventory that was loaded from source Raises: ValueError: When no session was provided but source was a url TypeError: When source isn't of the correct type
2.621054
3
wo/cli/plugins/info.py
BreezeRo/WordOps
1
6625110
<filename>wo/cli/plugins/info.py<gh_stars>1-10 """WOInfo Plugin for WordOps""" import configparser import os from cement.core import handler, hook from cement.core.controller import CementBaseController, expose from pynginxconfig import NginxConfig from wo.core.aptget import WOAptGet from wo.core.logging import Log from wo.core.shellexec import WOShellExec def wo_info_hook(app): pass class WOInfoController(CementBaseController): class Meta: label = 'info' stacked_on = 'base' stacked_type = 'nested' description = ('Display configuration information related to Nginx,' ' PHP and MySQL') arguments = [ (['--mysql'], dict(help='Get MySQL configuration information', action='store_true')), (['--php'], dict(help='Get PHP 7.2 configuration information', action='store_true')), (['--php73'], dict(help='Get PHP 7.3 configuration information', action='store_true')), (['--nginx'], dict(help='Get Nginx configuration information', action='store_true')), ] usage = "wo info [options]" @expose(hide=True) def info_nginx(self): """Display Nginx information""" version = os.popen("/usr/sbin/nginx -v 2>&1 | " "awk -F '/' '{print $2}' | " "awk -F ' ' '{print $1}' | tr '\n' ' '").read() allow = os.popen("grep ^allow /etc/nginx/common/acl.conf | " "cut -d' ' -f2 | cut -d';' -f1 | tr '\n' ' '").read() nc = NginxConfig() nc.loadf('/etc/nginx/nginx.conf') user = nc.get('user')[1] worker_processes = nc.get('worker_processes')[1] worker_connections = nc.get([('events',), 'worker_connections'])[1] keepalive_timeout = nc.get([('http',), 'keepalive_timeout'])[1] fastcgi_read_timeout = nc.get([('http',), 'fastcgi_read_timeout'])[1] client_max_body_size = nc.get([('http',), 'client_max_body_size'])[1] data = dict(version=version, allow=allow, user=user, worker_processes=worker_processes, keepalive_timeout=keepalive_timeout, worker_connections=worker_connections, fastcgi_read_timeout=fastcgi_read_timeout, client_max_body_size=client_max_body_size) self.app.render((data), 'info_nginx.mustache') @expose(hide=True) def info_php(self): """Display PHP information""" version = os.popen("/usr/bin/php7.2 -v 2>/dev/null | " "head -n1 | cut -d' ' -f2 |" " cut -d'+' -f1 | tr -d '\n'").read config = configparser.ConfigParser() config.read('/etc/{0}/fpm/php.ini'.format("php/7.2")) expose_php = config['PHP']['expose_php'] memory_limit = config['PHP']['memory_limit'] post_max_size = config['PHP']['post_max_size'] upload_max_filesize = config['PHP']['upload_max_filesize'] max_execution_time = config['PHP']['max_execution_time'] config.read('/etc/{0}/fpm/pool.d/www.conf'.format("php/7.2")) www_listen = config['www']['listen'] www_ping_path = config['www']['ping.path'] www_pm_status_path = config['www']['pm.status_path'] www_pm = config['www']['pm'] www_pm_max_requests = config['www']['pm.max_requests'] www_pm_max_children = config['www']['pm.max_children'] www_pm_start_servers = config['www']['pm.start_servers'] www_pm_min_spare_servers = config['www']['pm.min_spare_servers'] www_pm_max_spare_servers = config['www']['pm.max_spare_servers'] www_request_terminate_time = (config['www'] ['request_terminate_timeout']) try: www_xdebug = (config['www']['php_admin_flag[xdebug.profiler_enable' '_trigger]']) except Exception as e: Log.debug(self, "{0}".format(e)) www_xdebug = 'off' config.read('/etc/{0}/fpm/pool.d/debug.conf'.format("php/7.2")) debug_listen = config['debug']['listen'] debug_ping_path = config['debug']['ping.path'] debug_pm_status_path = config['debug']['pm.status_path'] debug_pm = config['debug']['pm'] debug_pm_max_requests = config['debug']['pm.max_requests'] debug_pm_max_children = config['debug']['pm.max_children'] debug_pm_start_servers = config['debug']['pm.start_servers'] debug_pm_min_spare_servers = config['debug']['pm.min_spare_servers'] debug_pm_max_spare_servers = config['debug']['pm.max_spare_servers'] debug_request_terminate = (config['debug'] ['request_terminate_timeout']) try: debug_xdebug = (config['debug']['php_admin_flag[xdebug.profiler_' 'enable_trigger]']) except Exception as e: Log.debug(self, "{0}".format(e)) debug_xdebug = 'off' data = dict(version=version, expose_php=expose_php, memory_limit=memory_limit, post_max_size=post_max_size, upload_max_filesize=upload_max_filesize, max_execution_time=max_execution_time, www_listen=www_listen, www_ping_path=www_ping_path, www_pm_status_path=www_pm_status_path, www_pm=www_pm, www_pm_max_requests=www_pm_max_requests, www_pm_max_children=www_pm_max_children, www_pm_start_servers=www_pm_start_servers, www_pm_min_spare_servers=www_pm_min_spare_servers, www_pm_max_spare_servers=www_pm_max_spare_servers, www_request_terminate_timeout=www_request_terminate_time, www_xdebug_profiler_enable_trigger=www_xdebug, debug_listen=debug_listen, debug_ping_path=debug_ping_path, debug_pm_status_path=debug_pm_status_path, debug_pm=debug_pm, debug_pm_max_requests=debug_pm_max_requests, debug_pm_max_children=debug_pm_max_children, debug_pm_start_servers=debug_pm_start_servers, debug_pm_min_spare_servers=debug_pm_min_spare_servers, debug_pm_max_spare_servers=debug_pm_max_spare_servers, debug_request_terminate_timeout=debug_request_terminate, debug_xdebug_profiler_enable_trigger=debug_xdebug) self.app.render((data), 'info_php.mustache') @expose(hide=True) def info_php73(self): """Display PHP information""" version = os.popen("/usr/bin/php7.3 -v 2>/dev/null | " "head -n1 | cut -d' ' -f2 |" " cut -d'+' -f1 | tr -d '\n'").read config = configparser.ConfigParser() config.read('/etc/php/7.3/fpm/php.ini') expose_php = config['PHP']['expose_php'] memory_limit = config['PHP']['memory_limit'] post_max_size = config['PHP']['post_max_size'] upload_max_filesize = config['PHP']['upload_max_filesize'] max_execution_time = config['PHP']['max_execution_time'] config.read('/etc/php/7.3/fpm/pool.d/www.conf') www_listen = config['www']['listen'] www_ping_path = config['www']['ping.path'] www_pm_status_path = config['www']['pm.status_path'] www_pm = config['www']['pm'] www_pm_max_requests = config['www']['pm.max_requests'] www_pm_max_children = config['www']['pm.max_children'] www_pm_start_servers = config['www']['pm.start_servers'] www_pm_min_spare_servers = config['www']['pm.min_spare_servers'] www_pm_max_spare_servers = config['www']['pm.max_spare_servers'] www_request_terminate_time = (config['www'] ['request_terminate_timeout']) try: www_xdebug = (config['www']['php_admin_flag[xdebug.profiler_enable' '_trigger]']) except Exception as e: Log.debug(self, "{0}".format(e)) www_xdebug = 'off' config.read('/etc/php/7.3/fpm/pool.d/debug.conf') debug_listen = config['debug']['listen'] debug_ping_path = config['debug']['ping.path'] debug_pm_status_path = config['debug']['pm.status_path'] debug_pm = config['debug']['pm'] debug_pm_max_requests = config['debug']['pm.max_requests'] debug_pm_max_children = config['debug']['pm.max_children'] debug_pm_start_servers = config['debug']['pm.start_servers'] debug_pm_min_spare_servers = config['debug']['pm.min_spare_servers'] debug_pm_max_spare_servers = config['debug']['pm.max_spare_servers'] debug_request_terminate = (config['debug'] ['request_terminate_timeout']) try: debug_xdebug = (config['debug']['php_admin_flag[xdebug.profiler_' 'enable_trigger]']) except Exception as e: Log.debug(self, "{0}".format(e)) debug_xdebug = 'off' data = dict(version=version, expose_php=expose_php, memory_limit=memory_limit, post_max_size=post_max_size, upload_max_filesize=upload_max_filesize, max_execution_time=max_execution_time, www_listen=www_listen, www_ping_path=www_ping_path, www_pm_status_path=www_pm_status_path, www_pm=www_pm, www_pm_max_requests=www_pm_max_requests, www_pm_max_children=www_pm_max_children, www_pm_start_servers=www_pm_start_servers, www_pm_min_spare_servers=www_pm_min_spare_servers, www_pm_max_spare_servers=www_pm_max_spare_servers, www_request_terminate_timeout=www_request_terminate_time, www_xdebug_profiler_enable_trigger=www_xdebug, debug_listen=debug_listen, debug_ping_path=debug_ping_path, debug_pm_status_path=debug_pm_status_path, debug_pm=debug_pm, debug_pm_max_requests=debug_pm_max_requests, debug_pm_max_children=debug_pm_max_children, debug_pm_start_servers=debug_pm_start_servers, debug_pm_min_spare_servers=debug_pm_min_spare_servers, debug_pm_max_spare_servers=debug_pm_max_spare_servers, debug_request_terminate_timeout=debug_request_terminate, debug_xdebug_profiler_enable_trigger=debug_xdebug) self.app.render((data), 'info_php.mustache') @expose(hide=True) def info_mysql(self): """Display MySQL information""" version = os.popen("/usr/bin/mysql -V | awk '{print($5)}' | " "cut -d ',' " "-f1 | tr -d '\n'").read() host = "localhost" port = os.popen("/usr/bin/mysql -e \"show variables\" | " "/bin/grep ^port | awk " "'{print($2)}' | tr -d '\n'").read() wait_timeout = os.popen("/usr/bin/mysql -e \"show variables\" | grep " "^wait_timeout | awk '{print($2)}' | " "tr -d '\n'").read() interactive_timeout = os.popen("/usr/bin/mysql -e " "\"show variables\" | grep " "^interactive_timeout | awk " "'{print($2)}' | tr -d '\n'").read() max_used_connections = os.popen("/usr/bin/mysql -e " "\"show global status\" | " "grep Max_used_connections | awk " "'{print($2)}' | tr -d '\n'").read() datadir = os.popen("/usr/bin/mysql -e \"show variables\" | " "/bin/grep datadir | awk" " '{print($2)}' | tr -d '\n'").read() socket = os.popen("/usr/bin/mysql -e \"show variables\" | " "/bin/grep \"^socket\" | " "awk '{print($2)}' | tr -d '\n'").read() data = dict(version=version, host=host, port=port, wait_timeout=wait_timeout, interactive_timeout=interactive_timeout, max_used_connections=max_used_connections, datadir=datadir, socket=socket) self.app.render((data), 'info_mysql.mustache') @expose(hide=True) def default(self): """default function for info""" if (not self.app.pargs.nginx and not self.app.pargs.php and not self.app.pargs.mysql and not self.app.pargs.php73): self.app.pargs.nginx = True self.app.pargs.php = True self.app.pargs.mysql = True if WOAptGet.is_installed(self, 'php7.3-fpm'): self.app.pargs.php73 = True if self.app.pargs.nginx: if (WOAptGet.is_installed(self, 'nginx-custom') or WOAptGet.is_installed(self, 'nginx-wo')): self.info_nginx() else: Log.error(self, "Nginx is not installed") if self.app.pargs.php: if WOAptGet.is_installed(self, 'php7.2-fpm'): self.info_php() else: Log.error(self, "PHP 7.2 is not installed") if self.app.pargs.php73: if WOAptGet.is_installed(self, 'php7.3-fpm'): self.info_php73() else: Log.error(self, "PHP 7.3 is not installed") if self.app.pargs.mysql: if WOShellExec.cmd_exec(self, "/usr/bin/mysqladmin ping"): self.info_mysql() else: Log.error(self, "MySQL is not installed") def load(app): # register the plugin class.. this only happens if the plugin is enabled handler.register(WOInfoController) # register a hook (function) to run after arguments are parsed. hook.register('post_argument_parsing', wo_info_hook)
<filename>wo/cli/plugins/info.py<gh_stars>1-10 """WOInfo Plugin for WordOps""" import configparser import os from cement.core import handler, hook from cement.core.controller import CementBaseController, expose from pynginxconfig import NginxConfig from wo.core.aptget import WOAptGet from wo.core.logging import Log from wo.core.shellexec import WOShellExec def wo_info_hook(app): pass class WOInfoController(CementBaseController): class Meta: label = 'info' stacked_on = 'base' stacked_type = 'nested' description = ('Display configuration information related to Nginx,' ' PHP and MySQL') arguments = [ (['--mysql'], dict(help='Get MySQL configuration information', action='store_true')), (['--php'], dict(help='Get PHP 7.2 configuration information', action='store_true')), (['--php73'], dict(help='Get PHP 7.3 configuration information', action='store_true')), (['--nginx'], dict(help='Get Nginx configuration information', action='store_true')), ] usage = "wo info [options]" @expose(hide=True) def info_nginx(self): """Display Nginx information""" version = os.popen("/usr/sbin/nginx -v 2>&1 | " "awk -F '/' '{print $2}' | " "awk -F ' ' '{print $1}' | tr '\n' ' '").read() allow = os.popen("grep ^allow /etc/nginx/common/acl.conf | " "cut -d' ' -f2 | cut -d';' -f1 | tr '\n' ' '").read() nc = NginxConfig() nc.loadf('/etc/nginx/nginx.conf') user = nc.get('user')[1] worker_processes = nc.get('worker_processes')[1] worker_connections = nc.get([('events',), 'worker_connections'])[1] keepalive_timeout = nc.get([('http',), 'keepalive_timeout'])[1] fastcgi_read_timeout = nc.get([('http',), 'fastcgi_read_timeout'])[1] client_max_body_size = nc.get([('http',), 'client_max_body_size'])[1] data = dict(version=version, allow=allow, user=user, worker_processes=worker_processes, keepalive_timeout=keepalive_timeout, worker_connections=worker_connections, fastcgi_read_timeout=fastcgi_read_timeout, client_max_body_size=client_max_body_size) self.app.render((data), 'info_nginx.mustache') @expose(hide=True) def info_php(self): """Display PHP information""" version = os.popen("/usr/bin/php7.2 -v 2>/dev/null | " "head -n1 | cut -d' ' -f2 |" " cut -d'+' -f1 | tr -d '\n'").read config = configparser.ConfigParser() config.read('/etc/{0}/fpm/php.ini'.format("php/7.2")) expose_php = config['PHP']['expose_php'] memory_limit = config['PHP']['memory_limit'] post_max_size = config['PHP']['post_max_size'] upload_max_filesize = config['PHP']['upload_max_filesize'] max_execution_time = config['PHP']['max_execution_time'] config.read('/etc/{0}/fpm/pool.d/www.conf'.format("php/7.2")) www_listen = config['www']['listen'] www_ping_path = config['www']['ping.path'] www_pm_status_path = config['www']['pm.status_path'] www_pm = config['www']['pm'] www_pm_max_requests = config['www']['pm.max_requests'] www_pm_max_children = config['www']['pm.max_children'] www_pm_start_servers = config['www']['pm.start_servers'] www_pm_min_spare_servers = config['www']['pm.min_spare_servers'] www_pm_max_spare_servers = config['www']['pm.max_spare_servers'] www_request_terminate_time = (config['www'] ['request_terminate_timeout']) try: www_xdebug = (config['www']['php_admin_flag[xdebug.profiler_enable' '_trigger]']) except Exception as e: Log.debug(self, "{0}".format(e)) www_xdebug = 'off' config.read('/etc/{0}/fpm/pool.d/debug.conf'.format("php/7.2")) debug_listen = config['debug']['listen'] debug_ping_path = config['debug']['ping.path'] debug_pm_status_path = config['debug']['pm.status_path'] debug_pm = config['debug']['pm'] debug_pm_max_requests = config['debug']['pm.max_requests'] debug_pm_max_children = config['debug']['pm.max_children'] debug_pm_start_servers = config['debug']['pm.start_servers'] debug_pm_min_spare_servers = config['debug']['pm.min_spare_servers'] debug_pm_max_spare_servers = config['debug']['pm.max_spare_servers'] debug_request_terminate = (config['debug'] ['request_terminate_timeout']) try: debug_xdebug = (config['debug']['php_admin_flag[xdebug.profiler_' 'enable_trigger]']) except Exception as e: Log.debug(self, "{0}".format(e)) debug_xdebug = 'off' data = dict(version=version, expose_php=expose_php, memory_limit=memory_limit, post_max_size=post_max_size, upload_max_filesize=upload_max_filesize, max_execution_time=max_execution_time, www_listen=www_listen, www_ping_path=www_ping_path, www_pm_status_path=www_pm_status_path, www_pm=www_pm, www_pm_max_requests=www_pm_max_requests, www_pm_max_children=www_pm_max_children, www_pm_start_servers=www_pm_start_servers, www_pm_min_spare_servers=www_pm_min_spare_servers, www_pm_max_spare_servers=www_pm_max_spare_servers, www_request_terminate_timeout=www_request_terminate_time, www_xdebug_profiler_enable_trigger=www_xdebug, debug_listen=debug_listen, debug_ping_path=debug_ping_path, debug_pm_status_path=debug_pm_status_path, debug_pm=debug_pm, debug_pm_max_requests=debug_pm_max_requests, debug_pm_max_children=debug_pm_max_children, debug_pm_start_servers=debug_pm_start_servers, debug_pm_min_spare_servers=debug_pm_min_spare_servers, debug_pm_max_spare_servers=debug_pm_max_spare_servers, debug_request_terminate_timeout=debug_request_terminate, debug_xdebug_profiler_enable_trigger=debug_xdebug) self.app.render((data), 'info_php.mustache') @expose(hide=True) def info_php73(self): """Display PHP information""" version = os.popen("/usr/bin/php7.3 -v 2>/dev/null | " "head -n1 | cut -d' ' -f2 |" " cut -d'+' -f1 | tr -d '\n'").read config = configparser.ConfigParser() config.read('/etc/php/7.3/fpm/php.ini') expose_php = config['PHP']['expose_php'] memory_limit = config['PHP']['memory_limit'] post_max_size = config['PHP']['post_max_size'] upload_max_filesize = config['PHP']['upload_max_filesize'] max_execution_time = config['PHP']['max_execution_time'] config.read('/etc/php/7.3/fpm/pool.d/www.conf') www_listen = config['www']['listen'] www_ping_path = config['www']['ping.path'] www_pm_status_path = config['www']['pm.status_path'] www_pm = config['www']['pm'] www_pm_max_requests = config['www']['pm.max_requests'] www_pm_max_children = config['www']['pm.max_children'] www_pm_start_servers = config['www']['pm.start_servers'] www_pm_min_spare_servers = config['www']['pm.min_spare_servers'] www_pm_max_spare_servers = config['www']['pm.max_spare_servers'] www_request_terminate_time = (config['www'] ['request_terminate_timeout']) try: www_xdebug = (config['www']['php_admin_flag[xdebug.profiler_enable' '_trigger]']) except Exception as e: Log.debug(self, "{0}".format(e)) www_xdebug = 'off' config.read('/etc/php/7.3/fpm/pool.d/debug.conf') debug_listen = config['debug']['listen'] debug_ping_path = config['debug']['ping.path'] debug_pm_status_path = config['debug']['pm.status_path'] debug_pm = config['debug']['pm'] debug_pm_max_requests = config['debug']['pm.max_requests'] debug_pm_max_children = config['debug']['pm.max_children'] debug_pm_start_servers = config['debug']['pm.start_servers'] debug_pm_min_spare_servers = config['debug']['pm.min_spare_servers'] debug_pm_max_spare_servers = config['debug']['pm.max_spare_servers'] debug_request_terminate = (config['debug'] ['request_terminate_timeout']) try: debug_xdebug = (config['debug']['php_admin_flag[xdebug.profiler_' 'enable_trigger]']) except Exception as e: Log.debug(self, "{0}".format(e)) debug_xdebug = 'off' data = dict(version=version, expose_php=expose_php, memory_limit=memory_limit, post_max_size=post_max_size, upload_max_filesize=upload_max_filesize, max_execution_time=max_execution_time, www_listen=www_listen, www_ping_path=www_ping_path, www_pm_status_path=www_pm_status_path, www_pm=www_pm, www_pm_max_requests=www_pm_max_requests, www_pm_max_children=www_pm_max_children, www_pm_start_servers=www_pm_start_servers, www_pm_min_spare_servers=www_pm_min_spare_servers, www_pm_max_spare_servers=www_pm_max_spare_servers, www_request_terminate_timeout=www_request_terminate_time, www_xdebug_profiler_enable_trigger=www_xdebug, debug_listen=debug_listen, debug_ping_path=debug_ping_path, debug_pm_status_path=debug_pm_status_path, debug_pm=debug_pm, debug_pm_max_requests=debug_pm_max_requests, debug_pm_max_children=debug_pm_max_children, debug_pm_start_servers=debug_pm_start_servers, debug_pm_min_spare_servers=debug_pm_min_spare_servers, debug_pm_max_spare_servers=debug_pm_max_spare_servers, debug_request_terminate_timeout=debug_request_terminate, debug_xdebug_profiler_enable_trigger=debug_xdebug) self.app.render((data), 'info_php.mustache') @expose(hide=True) def info_mysql(self): """Display MySQL information""" version = os.popen("/usr/bin/mysql -V | awk '{print($5)}' | " "cut -d ',' " "-f1 | tr -d '\n'").read() host = "localhost" port = os.popen("/usr/bin/mysql -e \"show variables\" | " "/bin/grep ^port | awk " "'{print($2)}' | tr -d '\n'").read() wait_timeout = os.popen("/usr/bin/mysql -e \"show variables\" | grep " "^wait_timeout | awk '{print($2)}' | " "tr -d '\n'").read() interactive_timeout = os.popen("/usr/bin/mysql -e " "\"show variables\" | grep " "^interactive_timeout | awk " "'{print($2)}' | tr -d '\n'").read() max_used_connections = os.popen("/usr/bin/mysql -e " "\"show global status\" | " "grep Max_used_connections | awk " "'{print($2)}' | tr -d '\n'").read() datadir = os.popen("/usr/bin/mysql -e \"show variables\" | " "/bin/grep datadir | awk" " '{print($2)}' | tr -d '\n'").read() socket = os.popen("/usr/bin/mysql -e \"show variables\" | " "/bin/grep \"^socket\" | " "awk '{print($2)}' | tr -d '\n'").read() data = dict(version=version, host=host, port=port, wait_timeout=wait_timeout, interactive_timeout=interactive_timeout, max_used_connections=max_used_connections, datadir=datadir, socket=socket) self.app.render((data), 'info_mysql.mustache') @expose(hide=True) def default(self): """default function for info""" if (not self.app.pargs.nginx and not self.app.pargs.php and not self.app.pargs.mysql and not self.app.pargs.php73): self.app.pargs.nginx = True self.app.pargs.php = True self.app.pargs.mysql = True if WOAptGet.is_installed(self, 'php7.3-fpm'): self.app.pargs.php73 = True if self.app.pargs.nginx: if (WOAptGet.is_installed(self, 'nginx-custom') or WOAptGet.is_installed(self, 'nginx-wo')): self.info_nginx() else: Log.error(self, "Nginx is not installed") if self.app.pargs.php: if WOAptGet.is_installed(self, 'php7.2-fpm'): self.info_php() else: Log.error(self, "PHP 7.2 is not installed") if self.app.pargs.php73: if WOAptGet.is_installed(self, 'php7.3-fpm'): self.info_php73() else: Log.error(self, "PHP 7.3 is not installed") if self.app.pargs.mysql: if WOShellExec.cmd_exec(self, "/usr/bin/mysqladmin ping"): self.info_mysql() else: Log.error(self, "MySQL is not installed") def load(app): # register the plugin class.. this only happens if the plugin is enabled handler.register(WOInfoController) # register a hook (function) to run after arguments are parsed. hook.register('post_argument_parsing', wo_info_hook)
en
0.386769
WOInfo Plugin for WordOps Display Nginx information Display PHP information Display PHP information Display MySQL information default function for info # register the plugin class.. this only happens if the plugin is enabled # register a hook (function) to run after arguments are parsed.
2.32701
2
sentinel/serializers/alarm_serializer.py
creditease-natrix/natrix
3
6625111
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from rest_framework import serializers from natrix.common.natrix_views.serializers import NatrixSerializer from benchmark.models import Task from sentinel.configurations import alarm_conf from sentinel.models import Alarm from sentinel.models.alarm_models import MONITOR_CHOICE, OPERATION_CHOICE, AGGREGATION_CHOICE from sentinel.backends.deepmonitor import DeepMonitorAlarmManagement logger = logging.getLogger(__name__) class AlarmSerializer(NatrixSerializer): alarm_id = serializers.IntegerField(read_only=True, help_text=u'告警ID') name = serializers.CharField(max_length=64, help_text=u'告警名称', required=False, default='') description = serializers.CharField(max_length=255, help_text=u'告警描述') task_id = serializers.UUIDField(help_text=u'任务ID') monitor_type = serializers.ChoiceField(choices=MONITOR_CHOICE, help_text=u'指标项') operation = serializers.ChoiceField(choices=OPERATION_CHOICE, help_text=u'判断操作', required=False, allow_null=True) threshold = serializers.FloatField(help_text=u'阈值', required=False, allow_null=True) aggregation_type = serializers.ChoiceField(choices=AGGREGATION_CHOICE, help_text=u'聚合方式', required=False, allow_null=True) aggregation_condition = serializers.FloatField(help_text=u'聚合条件', allow_null=True, required=False) def validate_task_id(self, value): # TODO: validate if this task is your owned task or followed task try: task = Task.objects.get(id=value) self.task = task return value except Task.DoesNotExist: raise serializers.ValidationError('The task({}) is not exist!'.format(value)) def is_valid(self, raise_exception=False): flag = super(AlarmSerializer, self).is_valid() if not flag: return flag if hasattr(self, 'instance') and self.instance: if self.instance.task != self.task: self._errors['task_id'] = ['Task can not be changed in edit api'] return False protocol_type = self.task.get_protocol_type() monitor_type = self.initial_data.get('monitor_type') if protocol_type not in alarm_conf.MONITOR_TYPE.get(monitor_type, {}).get('protocol', []): self._errors['monitor_type'] = ['{} task without {} monitor!'.format(protocol_type, monitor_type)] return False # TODO: validate aggregation configuration return flag def create(self, validated_data): name = validated_data.get('name') description = validated_data.get('description') monitor_type = validated_data.get('monitor_type') operation = validated_data.get('operation') threshold = validated_data.get('threshold') aggregation_type = validated_data.get('aggregation_type') aggregation_condition = validated_data.get('aggregation_condition') aggregation_condition = aggregation_condition if aggregation_condition is not None else 0 alarm = Alarm(name=name, description=description, task=self.task, monitor_type=monitor_type, operation=operation, threshold=threshold, aggregation_type=aggregation_type, agg_condition=aggregation_condition, owner=self.user, group=self.group) alarm_backend = DeepMonitorAlarmManagement(alarm) backend_id = alarm_backend.add() alarm.deepmonitor_uuid = backend_id alarm.save() return alarm def update(self, instance, validated_data): description = validated_data.get('description') instance.name = validated_data.get('name') instance.description = instance.description if description is None else description instance.monitor_type = validated_data.get('monitor_type') instance.operation = validated_data.get('operation') instance.threshold = validated_data.get('threshold') instance.aggregation_type = validated_data.get('aggregation_type') instance.agg_condition = validated_data.get('aggregation_condition') alarm_backend = DeepMonitorAlarmManagement(instance) alarm_backend.modify() instance.save() return instance class AlarmOperationSerializer(NatrixSerializer): alarm_id = serializers.IntegerField(help_text=u'告警ID') operation = serializers.ChoiceField(choices=(('on', u'开启'), ('off', u'关闭')), help_text=u'操作') def validate_alarm_id(self, value): try: alarm = Alarm.objects.get(pk=value, group=self.group) self.instance = alarm except Alarm.DoesNotExist as e: raise serializers.ValidationError('The alarm({}) is not exist!'.format(value)) return value def process(self): assert hasattr(self, '_errors'), ( 'You must call `.isvalid()` before calling `.process()`' ) assert not self.errors, ( 'You can not call `.process()` on a serializer with invalid data.' ) operation = self.validated_data.get('operation') alarm_backend = DeepMonitorAlarmManagement(self.instance) res, desc = alarm_backend.switch() if res: if operation == 'on': self.instance.status = True elif operation == 'off': self.instance.status = False self.instance.save() else: ... class AlarmListSerializer(NatrixSerializer): is_paginate = serializers.NullBooleanField(required=True) pagenum = serializers.IntegerField(min_value=1, required=False)
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from rest_framework import serializers from natrix.common.natrix_views.serializers import NatrixSerializer from benchmark.models import Task from sentinel.configurations import alarm_conf from sentinel.models import Alarm from sentinel.models.alarm_models import MONITOR_CHOICE, OPERATION_CHOICE, AGGREGATION_CHOICE from sentinel.backends.deepmonitor import DeepMonitorAlarmManagement logger = logging.getLogger(__name__) class AlarmSerializer(NatrixSerializer): alarm_id = serializers.IntegerField(read_only=True, help_text=u'告警ID') name = serializers.CharField(max_length=64, help_text=u'告警名称', required=False, default='') description = serializers.CharField(max_length=255, help_text=u'告警描述') task_id = serializers.UUIDField(help_text=u'任务ID') monitor_type = serializers.ChoiceField(choices=MONITOR_CHOICE, help_text=u'指标项') operation = serializers.ChoiceField(choices=OPERATION_CHOICE, help_text=u'判断操作', required=False, allow_null=True) threshold = serializers.FloatField(help_text=u'阈值', required=False, allow_null=True) aggregation_type = serializers.ChoiceField(choices=AGGREGATION_CHOICE, help_text=u'聚合方式', required=False, allow_null=True) aggregation_condition = serializers.FloatField(help_text=u'聚合条件', allow_null=True, required=False) def validate_task_id(self, value): # TODO: validate if this task is your owned task or followed task try: task = Task.objects.get(id=value) self.task = task return value except Task.DoesNotExist: raise serializers.ValidationError('The task({}) is not exist!'.format(value)) def is_valid(self, raise_exception=False): flag = super(AlarmSerializer, self).is_valid() if not flag: return flag if hasattr(self, 'instance') and self.instance: if self.instance.task != self.task: self._errors['task_id'] = ['Task can not be changed in edit api'] return False protocol_type = self.task.get_protocol_type() monitor_type = self.initial_data.get('monitor_type') if protocol_type not in alarm_conf.MONITOR_TYPE.get(monitor_type, {}).get('protocol', []): self._errors['monitor_type'] = ['{} task without {} monitor!'.format(protocol_type, monitor_type)] return False # TODO: validate aggregation configuration return flag def create(self, validated_data): name = validated_data.get('name') description = validated_data.get('description') monitor_type = validated_data.get('monitor_type') operation = validated_data.get('operation') threshold = validated_data.get('threshold') aggregation_type = validated_data.get('aggregation_type') aggregation_condition = validated_data.get('aggregation_condition') aggregation_condition = aggregation_condition if aggregation_condition is not None else 0 alarm = Alarm(name=name, description=description, task=self.task, monitor_type=monitor_type, operation=operation, threshold=threshold, aggregation_type=aggregation_type, agg_condition=aggregation_condition, owner=self.user, group=self.group) alarm_backend = DeepMonitorAlarmManagement(alarm) backend_id = alarm_backend.add() alarm.deepmonitor_uuid = backend_id alarm.save() return alarm def update(self, instance, validated_data): description = validated_data.get('description') instance.name = validated_data.get('name') instance.description = instance.description if description is None else description instance.monitor_type = validated_data.get('monitor_type') instance.operation = validated_data.get('operation') instance.threshold = validated_data.get('threshold') instance.aggregation_type = validated_data.get('aggregation_type') instance.agg_condition = validated_data.get('aggregation_condition') alarm_backend = DeepMonitorAlarmManagement(instance) alarm_backend.modify() instance.save() return instance class AlarmOperationSerializer(NatrixSerializer): alarm_id = serializers.IntegerField(help_text=u'告警ID') operation = serializers.ChoiceField(choices=(('on', u'开启'), ('off', u'关闭')), help_text=u'操作') def validate_alarm_id(self, value): try: alarm = Alarm.objects.get(pk=value, group=self.group) self.instance = alarm except Alarm.DoesNotExist as e: raise serializers.ValidationError('The alarm({}) is not exist!'.format(value)) return value def process(self): assert hasattr(self, '_errors'), ( 'You must call `.isvalid()` before calling `.process()`' ) assert not self.errors, ( 'You can not call `.process()` on a serializer with invalid data.' ) operation = self.validated_data.get('operation') alarm_backend = DeepMonitorAlarmManagement(self.instance) res, desc = alarm_backend.switch() if res: if operation == 'on': self.instance.status = True elif operation == 'off': self.instance.status = False self.instance.save() else: ... class AlarmListSerializer(NatrixSerializer): is_paginate = serializers.NullBooleanField(required=True) pagenum = serializers.IntegerField(min_value=1, required=False)
en
0.694358
# -*- coding: utf-8 -*- # TODO: validate if this task is your owned task or followed task # TODO: validate aggregation configuration
1.86877
2
accounts/tokens.py
PudgyPoppins/AP-Crowd-2020
0
6625112
<gh_stars>0 from django.contrib.auth.tokens import PasswordResetTokenGenerator import uuid #from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( str(user.pk) + str(timestamp) + str(user.is_active) ) account_activation_token = TokenGenerator()
from django.contrib.auth.tokens import PasswordResetTokenGenerator import uuid #from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( str(user.pk) + str(timestamp) + str(user.is_active) ) account_activation_token = TokenGenerator()
en
0.187487
#from django.utils import six
2.291242
2
gprm/datasets/Seafloor.py
siwill22/GPlatesReconstructionModel
7
6625113
<reponame>siwill22/GPlatesReconstructionModel from pooch import os_cache as _os_cache from pooch import retrieve as _retrieve from pooch import HTTPDownloader as _HTTPDownloader from pooch import Untar as _Untar from pooch import Unzip as _Unzip import pandas as _pd import geopandas as _gpd import os as _os def MagneticPicks(load=True): ''' Magnetic Picks from the 'Global Seafloor Fabric (and) Magnetic Linations' database, returned as a geopandas dataframe Alternatively, select 'load=False' to return filname of '.gmt' file in cache folder ''' fname = _retrieve( url="http://www.soest.hawaii.edu/PT/GSFML/ML/DATA/GSFML.global.picks.gmt", known_hash="sha256:0895b76597f600a6c6184a7bec0edc0df5ca9234255f3f7bac0fe944317caf65", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) if load: return _gpd.read_file(fname) else: return fname def SeafloorFabric(feature_type='FZ', load=True): ''' Seafloor fabric from the 'Global Seafloor Fabric (and) Magnetic Linations' database, returned as a geopandas dataframe. Alternatively, select 'load=False' to return filname of '.gmt' file in cache folder Parameters ---------- feature_type (str), choose from one of: 'FZ': Fracture Zones (Kara Matthews) 'FZLC': Fracture Zones, Less Certainty (Kara Matthews) 'DZ': Discordant Zones 'VANOM': V-Shaped Structures 'PR': Propagating Ridges 'ER': Extinct Ridge 'UNCV': Unclassified V-Anomalies Additonal Fracture Zone interpretations: 'FZ_JW': from <NAME> 'FZ_RM': from <NAME>ill 'FZ_MC': from <NAME> ''' fnames = _retrieve( url="http://www.soest.hawaii.edu/PT/GSFML/SF/DATA/GSFML_SF.tbz", known_hash="sha256:e27a73dc544611685144b4587d17f03bde24438ee4646963f10761f8ec2e6036", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), processor=_Untar(extract_dir='SeafloorFabric'), ) FABRIC_TYPE = { "FZ": "GSFML_SF_FZ_KM.gmt", "FZLC": "GSFML_SF_FZLC_KM.gmt", "UNCV": "GSFML_SF_UNCV_KM.gmt", "DZ": "GSFML_SF_DZ_KM.gmt", "PR": "GSFML_SF_PR_KM.gmt", "VANOM": "GSFML_SF_VANOM_KM.gmt", "ER": "GSFML_SF_ER_KM.gmt", "FZ_JW": "GSFML_SF_FZ_JW.gmt", "FZ_RM": "GSFML_SF_FZ_RM.gmt", "FZ_MC": "GSFML_SF_FZ_MC.gmt", } if feature_type not in FABRIC_TYPE.keys(): raise ValueError('Unknown feature type {:s}'.format(feature_type)) for fname in fnames: if _os.path.split(fname)[1]==FABRIC_TYPE[feature_type]: if load: return _gpd.read_file(fname) else: return fname def PacificSeamountAges(load=True): ''' Pacific Seamount Age compilation from GMT website ''' fname = _retrieve( url="https://www.earthbyte.org/webdav/gmt_mirror/gmt/data/cache/Pacific_Ages.txt", known_hash="sha256:8c5e57b478c2c2f5581527c7aea5ef282e976c36c5e00452210885a92e635021", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) if load: df = _pd.read_csv(fname, comment='#', delim_whitespace=True, names=['Long', 'Lat', 'Average_Age_Ma', 'Average_Age_Error_Ma', 'Tag', 'SeamountName', 'SeamountChain']) return _gpd.GeoDataFrame(df, geometry=_gpd.points_from_xy(df.Long, df.Lat)) else: return fname def Seamounts(catalogue='KimWessel', load=True): ''' Seamount Census from Kim and Wessel ''' if catalogue in ['KimWessel', 'KW']: fname = _retrieve( url="http://www.soest.hawaii.edu/PT/SMTS/kwsmts/KWSMTSv01.txt", known_hash="sha256:91c93302c44463a424835aa4051b7b2a1ea04d6675d928ca8405b231ae7cea9a", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) if load: df = _pd.read_csv(fname, delim_whitespace=True, skiprows=17, comment='>', names=['Long', 'Lat', 'Azimuth', 'Major', 'Minor', 'Height', 'FAA', 'VGG', 'Depth', 'CrustAge', 'ID']) return _gpd.GeoDataFrame(df, geometry=_gpd.points_from_xy(df.Long, df.Lat)) else: return fname elif catalogue in ['HillierWatts', 'HW']: fname = _retrieve( url="https://www.wattsgeophysics.co.uk/downloadfile/5616459", known_hash="sha256:d0b9aa7d15754ad9aabecfedf881005d22254e79183af8edf0806be840a549ac", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) if load: df = _pd.read_csv(fname, delim_whitespace=True, names=['Long', 'Lat', 'Height']) return _gpd.GeoDataFrame(df, geometry=_gpd.points_from_xy(df.Long, df.Lat)) else: return fname else: raise ValueError('Unknown catalogue {:s}'.format(catalogue)) def LargeIgneousProvinces(catalogue='Whittaker', load=True): ''' (Large) Igneous Province polygons included in GPlates sample data: - 'Whittaker' [default], from Whittaker et al (2015) - 'Johansson' from Johansson et al (2018) and also - 'UTIG' from the 2011 version of the UTIG LIP compilation ''' if catalogue in ['Whittaker', 'Johansson']: fnames = _retrieve( url="https://www.earthbyte.org/webdav/ftp/earthbyte/GPlates/SampleData_GPlates2.2/Individual/FeatureCollections/LargeIgneousProvinces_VolcanicProvinces.zip", known_hash="sha256:8f86ab86a12761f5534beaaeaddbed5b4e3e6d3d9b52b0c87ee9b15af2a797cd", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), processor=_Unzip(extract_dir='LIPs'), ) for fname in fnames: if _os.path.split(fname)[1] == 'License.txt': dirname = _os.path.split(fname)[0] if catalogue=='Whittaker': fname='{:s}/LargeIgneousProvinces_VolcanicProvinces/Whittaker_etal_2015_LargeIgneousProvinces/SHP/Whittaker_etal_2015_LIPs.shp'.format(dirname) elif catalogue=='Johansson': fname='{:s}/LargeIgneousProvinces_VolcanicProvinces/Johansson_etal_2018_VolcanicProvinces/SHP/Johansson_etal_2018_VolcanicProvinces_v2.shp'.format(dirname) elif catalogue=='UTIG': fname = _retrieve( url="http://www-udc.ig.utexas.edu/external/plates/data/LIPS/Data/LIPS.2011.gmt", known_hash="sha256:11cd037382c518ec0b54b93728fef5e476ec3d8d57e5c433a1ccf14420ee99dd", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) else: raise ValueError('Unknown catalogue {:s}'.format(catalogue)) if load: return _gpd.read_file(fname) else: return fname
from pooch import os_cache as _os_cache from pooch import retrieve as _retrieve from pooch import HTTPDownloader as _HTTPDownloader from pooch import Untar as _Untar from pooch import Unzip as _Unzip import pandas as _pd import geopandas as _gpd import os as _os def MagneticPicks(load=True): ''' Magnetic Picks from the 'Global Seafloor Fabric (and) Magnetic Linations' database, returned as a geopandas dataframe Alternatively, select 'load=False' to return filname of '.gmt' file in cache folder ''' fname = _retrieve( url="http://www.soest.hawaii.edu/PT/GSFML/ML/DATA/GSFML.global.picks.gmt", known_hash="sha256:0895b76597f600a6c6184a7bec0edc0df5ca9234255f3f7bac0fe944317caf65", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) if load: return _gpd.read_file(fname) else: return fname def SeafloorFabric(feature_type='FZ', load=True): ''' Seafloor fabric from the 'Global Seafloor Fabric (and) Magnetic Linations' database, returned as a geopandas dataframe. Alternatively, select 'load=False' to return filname of '.gmt' file in cache folder Parameters ---------- feature_type (str), choose from one of: 'FZ': Fracture Zones (Kara Matthews) 'FZLC': Fracture Zones, Less Certainty (Kara Matthews) 'DZ': Discordant Zones 'VANOM': V-Shaped Structures 'PR': Propagating Ridges 'ER': Extinct Ridge 'UNCV': Unclassified V-Anomalies Additonal Fracture Zone interpretations: 'FZ_JW': from <NAME> 'FZ_RM': from <NAME>ill 'FZ_MC': from <NAME> ''' fnames = _retrieve( url="http://www.soest.hawaii.edu/PT/GSFML/SF/DATA/GSFML_SF.tbz", known_hash="sha256:e27a73dc544611685144b4587d17f03bde24438ee4646963f10761f8ec2e6036", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), processor=_Untar(extract_dir='SeafloorFabric'), ) FABRIC_TYPE = { "FZ": "GSFML_SF_FZ_KM.gmt", "FZLC": "GSFML_SF_FZLC_KM.gmt", "UNCV": "GSFML_SF_UNCV_KM.gmt", "DZ": "GSFML_SF_DZ_KM.gmt", "PR": "GSFML_SF_PR_KM.gmt", "VANOM": "GSFML_SF_VANOM_KM.gmt", "ER": "GSFML_SF_ER_KM.gmt", "FZ_JW": "GSFML_SF_FZ_JW.gmt", "FZ_RM": "GSFML_SF_FZ_RM.gmt", "FZ_MC": "GSFML_SF_FZ_MC.gmt", } if feature_type not in FABRIC_TYPE.keys(): raise ValueError('Unknown feature type {:s}'.format(feature_type)) for fname in fnames: if _os.path.split(fname)[1]==FABRIC_TYPE[feature_type]: if load: return _gpd.read_file(fname) else: return fname def PacificSeamountAges(load=True): ''' Pacific Seamount Age compilation from GMT website ''' fname = _retrieve( url="https://www.earthbyte.org/webdav/gmt_mirror/gmt/data/cache/Pacific_Ages.txt", known_hash="sha256:8c5e57b478c2c2f5581527c7aea5ef282e976c36c5e00452210885a92e635021", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) if load: df = _pd.read_csv(fname, comment='#', delim_whitespace=True, names=['Long', 'Lat', 'Average_Age_Ma', 'Average_Age_Error_Ma', 'Tag', 'SeamountName', 'SeamountChain']) return _gpd.GeoDataFrame(df, geometry=_gpd.points_from_xy(df.Long, df.Lat)) else: return fname def Seamounts(catalogue='KimWessel', load=True): ''' Seamount Census from Kim and Wessel ''' if catalogue in ['KimWessel', 'KW']: fname = _retrieve( url="http://www.soest.hawaii.edu/PT/SMTS/kwsmts/KWSMTSv01.txt", known_hash="sha256:91c93302c44463a424835aa4051b7b2a1ea04d6675d928ca8405b231ae7cea9a", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) if load: df = _pd.read_csv(fname, delim_whitespace=True, skiprows=17, comment='>', names=['Long', 'Lat', 'Azimuth', 'Major', 'Minor', 'Height', 'FAA', 'VGG', 'Depth', 'CrustAge', 'ID']) return _gpd.GeoDataFrame(df, geometry=_gpd.points_from_xy(df.Long, df.Lat)) else: return fname elif catalogue in ['HillierWatts', 'HW']: fname = _retrieve( url="https://www.wattsgeophysics.co.uk/downloadfile/5616459", known_hash="sha256:d0b9aa7d15754ad9aabecfedf881005d22254e79183af8edf0806be840a549ac", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) if load: df = _pd.read_csv(fname, delim_whitespace=True, names=['Long', 'Lat', 'Height']) return _gpd.GeoDataFrame(df, geometry=_gpd.points_from_xy(df.Long, df.Lat)) else: return fname else: raise ValueError('Unknown catalogue {:s}'.format(catalogue)) def LargeIgneousProvinces(catalogue='Whittaker', load=True): ''' (Large) Igneous Province polygons included in GPlates sample data: - 'Whittaker' [default], from Whittaker et al (2015) - 'Johansson' from Johansson et al (2018) and also - 'UTIG' from the 2011 version of the UTIG LIP compilation ''' if catalogue in ['Whittaker', 'Johansson']: fnames = _retrieve( url="https://www.earthbyte.org/webdav/ftp/earthbyte/GPlates/SampleData_GPlates2.2/Individual/FeatureCollections/LargeIgneousProvinces_VolcanicProvinces.zip", known_hash="sha256:8f86ab86a12761f5534beaaeaddbed5b4e3e6d3d9b52b0c87ee9b15af2a797cd", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), processor=_Unzip(extract_dir='LIPs'), ) for fname in fnames: if _os.path.split(fname)[1] == 'License.txt': dirname = _os.path.split(fname)[0] if catalogue=='Whittaker': fname='{:s}/LargeIgneousProvinces_VolcanicProvinces/Whittaker_etal_2015_LargeIgneousProvinces/SHP/Whittaker_etal_2015_LIPs.shp'.format(dirname) elif catalogue=='Johansson': fname='{:s}/LargeIgneousProvinces_VolcanicProvinces/Johansson_etal_2018_VolcanicProvinces/SHP/Johansson_etal_2018_VolcanicProvinces_v2.shp'.format(dirname) elif catalogue=='UTIG': fname = _retrieve( url="http://www-udc.ig.utexas.edu/external/plates/data/LIPS/Data/LIPS.2011.gmt", known_hash="sha256:11cd037382c518ec0b54b93728fef5e476ec3d8d57e5c433a1ccf14420ee99dd", downloader=_HTTPDownloader(progressbar=True), path=_os_cache('gprm'), ) else: raise ValueError('Unknown catalogue {:s}'.format(catalogue)) if load: return _gpd.read_file(fname) else: return fname
en
0.682297
Magnetic Picks from the 'Global Seafloor Fabric (and) Magnetic Linations' database, returned as a geopandas dataframe Alternatively, select 'load=False' to return filname of '.gmt' file in cache folder Seafloor fabric from the 'Global Seafloor Fabric (and) Magnetic Linations' database, returned as a geopandas dataframe. Alternatively, select 'load=False' to return filname of '.gmt' file in cache folder Parameters ---------- feature_type (str), choose from one of: 'FZ': Fracture Zones (Kara Matthews) 'FZLC': Fracture Zones, Less Certainty (Kara Matthews) 'DZ': Discordant Zones 'VANOM': V-Shaped Structures 'PR': Propagating Ridges 'ER': Extinct Ridge 'UNCV': Unclassified V-Anomalies Additonal Fracture Zone interpretations: 'FZ_JW': from <NAME> 'FZ_RM': from <NAME>ill 'FZ_MC': from <NAME> Pacific Seamount Age compilation from GMT website Seamount Census from Kim and Wessel (Large) Igneous Province polygons included in GPlates sample data: - 'Whittaker' [default], from Whittaker et al (2015) - 'Johansson' from Johansson et al (2018) and also - 'UTIG' from the 2011 version of the UTIG LIP compilation
2.537485
3
rst2pdf/extensions/plantuml.py
oz123/rst2pdf
39
6625114
<gh_stars>10-100 ''' A rst2pdf extension to implement something similar to sphinx's plantuml extension (see http://pypi.python.org/pypi/sphinxcontrib-plantuml) Therefore, stuff may be copied from that code. Ergo: :copyright: Copyright 2010 by <NAME> <<EMAIL>>. :license: BSD, (he says see LICENSE but the file is not there ;-) ''' import errno from docutils import nodes from docutils.parsers import rst from docutils.parsers.rst import directives import rst2pdf.genelements as genelements from rst2pdf.image import MyImage import tempfile import subprocess class plantuml(nodes.General, nodes.Element): pass class UmlDirective(rst.Directive): """Directive to insert PlantUML markup Example:: .. uml:: :alt: Alice and Bob Alice -> Bob: Hello Alice <- Bob: Hi You can use a :format: option to change between SVG and PNG diagrams, however, the SVG plantuml generates doesn't look very good to me. """ has_content = True option_spec = { 'alt': directives.unchanged, 'format': directives.unchanged, } def run(self): node = plantuml() node['uml'] = '\n'.join(self.content) node['alt'] = self.options.get('alt', None) node['format'] = self.options.get('format', 'png') return [node] class UMLHandler(genelements.NodeHandler, plantuml): """Class to handle UML nodes""" def gather_elements(self, client, node, style): # Create image calling plantuml tfile = tempfile.NamedTemporaryFile(dir='.', delete=False, suffix='.'+node['format']) args = 'plantuml -pipe -charset utf-8' if node['format'].lower() == 'svg': args+=' -tsvg' client.to_unlink.append(tfile.name) try: p = subprocess.Popen(args.split(), stdout=tfile, stdin=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as err: if err.errno != errno.ENOENT: raise raise PlantUmlError('plantuml command %r cannot be run' % self.builder.config.plantuml) serr = p.communicate(node['uml'].encode('utf-8'))[1] if p.returncode != 0: raise PlantUmlError('error while running plantuml\n\n' + serr) # Add Image node with the right image return [MyImage(tfile.name, client=client)] directives.register_directive("uml", UmlDirective)
''' A rst2pdf extension to implement something similar to sphinx's plantuml extension (see http://pypi.python.org/pypi/sphinxcontrib-plantuml) Therefore, stuff may be copied from that code. Ergo: :copyright: Copyright 2010 by <NAME> <<EMAIL>>. :license: BSD, (he says see LICENSE but the file is not there ;-) ''' import errno from docutils import nodes from docutils.parsers import rst from docutils.parsers.rst import directives import rst2pdf.genelements as genelements from rst2pdf.image import MyImage import tempfile import subprocess class plantuml(nodes.General, nodes.Element): pass class UmlDirective(rst.Directive): """Directive to insert PlantUML markup Example:: .. uml:: :alt: Alice and Bob Alice -> Bob: Hello Alice <- Bob: Hi You can use a :format: option to change between SVG and PNG diagrams, however, the SVG plantuml generates doesn't look very good to me. """ has_content = True option_spec = { 'alt': directives.unchanged, 'format': directives.unchanged, } def run(self): node = plantuml() node['uml'] = '\n'.join(self.content) node['alt'] = self.options.get('alt', None) node['format'] = self.options.get('format', 'png') return [node] class UMLHandler(genelements.NodeHandler, plantuml): """Class to handle UML nodes""" def gather_elements(self, client, node, style): # Create image calling plantuml tfile = tempfile.NamedTemporaryFile(dir='.', delete=False, suffix='.'+node['format']) args = 'plantuml -pipe -charset utf-8' if node['format'].lower() == 'svg': args+=' -tsvg' client.to_unlink.append(tfile.name) try: p = subprocess.Popen(args.split(), stdout=tfile, stdin=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as err: if err.errno != errno.ENOENT: raise raise PlantUmlError('plantuml command %r cannot be run' % self.builder.config.plantuml) serr = p.communicate(node['uml'].encode('utf-8'))[1] if p.returncode != 0: raise PlantUmlError('error while running plantuml\n\n' + serr) # Add Image node with the right image return [MyImage(tfile.name, client=client)] directives.register_directive("uml", UmlDirective)
en
0.811742
A rst2pdf extension to implement something similar to sphinx's plantuml extension (see http://pypi.python.org/pypi/sphinxcontrib-plantuml) Therefore, stuff may be copied from that code. Ergo: :copyright: Copyright 2010 by <NAME> <<EMAIL>>. :license: BSD, (he says see LICENSE but the file is not there ;-) Directive to insert PlantUML markup Example:: .. uml:: :alt: Alice and Bob Alice -> Bob: Hello Alice <- Bob: Hi You can use a :format: option to change between SVG and PNG diagrams, however, the SVG plantuml generates doesn't look very good to me. Class to handle UML nodes # Create image calling plantuml # Add Image node with the right image
2.717124
3
OasisPy/montage.py
ahstewart/OASIS
0
6625115
<filename>OasisPy/montage.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 13 18:40:54 2019 @author: andrew """ # Startup. The Montage modules are pretty much self-contained # but this script needs a few extra utilities. import os import sys import shutil import glob from astropy.io import fits import numpy as np from MontagePy.main import * from MontagePy.archive import * from IPython.display import Image def MOSAIC(): '''Interfaces with MontagePy to build a mosaic from a set of input images. All parameters are supplied through terminal prompts. See documentation for details. ''' # name the mosaic project workdir = input("-> Name of mosaic project (ex. 'Andromeda' or 'Messier031'): ") # define location of mosaic construction mosaic_loc = input("-> Directory where mosaic building will take place (default = cwd): ") if mosaic_loc == '': mosaic_loc = os.getcwd() # ask how the data is being collected # database = FITS images from some known astronomical database # personal = FITS images user has already downloaded onto their machine data_origin = input("-> Enter method of data retrieval (database/personal): ") # get name of database if data_origin == 'database': # get region location or coordinates location = input("-> Mosaic location (ex. 'M 31', '4h23m11s -12d14m32.3s'): ") # get name of database to download data from dataset = input("-> Survey/mission name and observing band (ex. SDSS g): ") # define size of mosaic size = input("-> Mosaic region size in degrees (leave blank if using personal data): ") if size == '': size = 1.0 else: try: size = float(size) except: print("-> Error: invalid size choice\n-> Exiting...") sys.exit() elif data_origin == 'personal': dataset = '' else: print("-> Error: invalid input\n-> Exiting...") sys.exit() # We create and move into subdirectories in this notebook # but we want to come back to the original startup directory # whenever we restart the processing. # move into directory where the mosaic will be built try: os.chdir(mosaic_loc) except FileNotFoundError: print('-> Mosaic location not found\n-> Creating directory now...') try: os.mkdir(mosaic_loc) os.chdir(mosaic_loc) except: print("-> Error: issue with creating mosaic location\n-> Exiting...") sys.exit() print("Mosaic location: " + mosaic_loc) # Clean out any old copy of the work tree, then remake it # and the set of the subdirectories we will need. remove_check = input("-> Remove previous mosaic data for this location if it exists? (y/n): ") if remove_check == 'y': try: shutil.rmtree(workdir) except: print("Can't delete work tree; probably doesn't exist yet", flush=True) elif remove_check == 'n': pass else: print("-> Error: invalid input\n-> Exiting...") sys.exit() # make work directory try: os.makedirs(workdir) except FileExistsError: pass print("Work directory: " + workdir, flush=True) # move into work directory print("-> Moving into work directory...") os.chdir(workdir) # create necessary subfolders print("-> Creating subdirectories that will hold mosaic data...") try: os.makedirs("raw") os.makedirs("projected") os.makedirs("diffs") os.makedirs("corrected") except FileExistsError: print("-> Subdirectories already exist") # retrieve images from archive if 'database' was chosen for data_origin # move images into "raw" if 'personal' was chosen for data_origin if data_origin == 'database': try: getdata = mArchiveDownload(dataset, location, size, "raw") if getdata[getdata.find('count') + 8] == '0': print("-> Warning: No images downloaded") except: print('-> Error: issue with database information\n-> Exiting...') sys.exit() elif data_origin == 'personal': image_loc = input("-> Location of FITS images (if left blank you must manually move images into 'raw' directory): ") if image_loc != '': images = glob.glob("%s/*.fits" % (image_loc)) images_gz = glob.glob("%s/*.gz" % (image_loc)) images_fz = glob.glob("%s/*.fz" % (image_loc)) for gz in images_gz: images.append(gz) for fz in images_fz: images.append(fz) if len(images) == 0: print("-> Error: Could not find any images in %s\n-> Exiting..." % (image_loc)) sys.exit() for im in images: os.system("cp %s 'raw'" % (im)) elif image_loc == '': moved = input("-> Move FITS images into 'raw' directory now\n-> (press ENTER when done)") else: print("-> Error: invalid input\n-> Exiting...") sys.exit() mask_ask = input("-> Read in image masks? (y/n): ") if mask_ask == 'y': mask_method = input("-> Mask type (weight map/mask): ") bkg_ask = input("-> Match image backgrounds? (y/n): ") output_image = input("-> Enter completed mosaic output image name: ") output_image += '.fits' # mask input images if user says so if mask_ask == 'n' or mask_ask == '': pass elif mask_ask == 'y': images = glob.glob("%s/%s/raw/*.fits" % (mosaic_loc, workdir)) print(images) for i in images: data = fits.getdata(i) hdr = fits.getheader(i) mask = fits.getdata(i, 1) if mask_method == 'weight map': new_mask = (mask - 1) * -1 elif mask_method == 'mask': new_mask = mask else: print("-> Error- Unknown input\n-> Exiting...") sys.exit() data += (new_mask*1000000000) data[data > 100000000] = np.nan hdu = fits.PrimaryHDU(data, header=hdr) hdu_mask = fits.ImageHDU(mask) hdu_list = fits.HDUList([hdu, hdu_mask]) hdu_list.writeto(i[:-5]+'_masked.fits', overwrite=True) os.remove(i) else: print("-> Error- Unknown input\n-> Exiting...") # make table of metadata from set of FITS images in 'raw' print("-> Making table of metadata from selected FITS images...") rtn = mImgtbl("raw", "images.tbl") print("mImgtbl: " + str(rtn), flush=True) # make collective FITS header to use in mosaic construction print("-> Making collective FITS header to use in mosaic construction...") rtn2 = mMakeHdr("images.tbl", "template.hdr") print("mMakeHdr: " + str(rtn2), flush=True) # reproject images to the frame defined in the mMakeHdr step print("-> Reprojecting input images...") rtn3 = mProjExec("raw", "images.tbl", "template.hdr", projdir="projected") print("mProjExec: " + str(rtn3), flush=True) # repeat metadata generation steps with reprojected data print("-> Generating metadata table again with reprojected images...") rtn = mImgtbl("projected", "pimages.tbl") print("mImgtbl (projected): " + str(rtn), flush=True) # ask if user wants to background correct images if bkg_ask == 'n': print("-> Constructing final mosaic...") rtn_final = mAdd("projected", "pimages.tbl", "template.hdr", output_image) print("mAdd: " + str(rtn_final), flush=True) elif bkg_ask == 'y' or bkg_ask == '': # background correct images before coaddition print("-> Background correcting images before coaddition...") # Determine the overlaps between images (for background modeling). rtn4 = mOverlaps("pimages.tbl", "diffs.tbl") print("mOverlaps: " + str(rtn4), flush=True) # Generate difference images and fit them. rtn5 = mDiffFitExec("projected", "diffs.tbl", "template.hdr", "diffs", "fits.tbl") print("mDiffFitExec: " + str(rtn5), flush=True) # Model the background corrections. rtn6 = mBgModel("pimages.tbl", "fits.tbl", "corrections.tbl") print("mBgModel: " + str(rtn6), flush=True) # Background correct the projected images. rtn7 = mBgExec("projected", "pimages.tbl", "corrections.tbl", "corrected") print("mBgExec: " + str(rtn7), flush=True) # repeat metadata generation steps with reprojected and background-corrected data rtn = mImgtbl("corrected", "cimages.tbl") print("mImgtbl (corrected): " + str(rtn), flush=True) # make mosaic by coadding reprojected and background-corrected images together print("-> Constructing final mosaic...") rtn_final = mAdd("corrected", "cimages.tbl", "template.hdr", output_image) print("mAdd: " + str(rtn_final), flush=True) else: print("-> Error- Unknown input\n-> Exiting...") sys.exit() # Make a PNG rendering of the data and display it. rtn_view = mViewer("-ct 1 -gray %s -2s max gaussian-log -out %s" % (output_image, output_image.replace('fits','png')), "", mode=2) print("mViewer: " + str(rtn_view), flush=True) Image(filename=output_image.replace('fits','png')) if __name__ == '__main__': MOSAIC()
<filename>OasisPy/montage.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 13 18:40:54 2019 @author: andrew """ # Startup. The Montage modules are pretty much self-contained # but this script needs a few extra utilities. import os import sys import shutil import glob from astropy.io import fits import numpy as np from MontagePy.main import * from MontagePy.archive import * from IPython.display import Image def MOSAIC(): '''Interfaces with MontagePy to build a mosaic from a set of input images. All parameters are supplied through terminal prompts. See documentation for details. ''' # name the mosaic project workdir = input("-> Name of mosaic project (ex. 'Andromeda' or 'Messier031'): ") # define location of mosaic construction mosaic_loc = input("-> Directory where mosaic building will take place (default = cwd): ") if mosaic_loc == '': mosaic_loc = os.getcwd() # ask how the data is being collected # database = FITS images from some known astronomical database # personal = FITS images user has already downloaded onto their machine data_origin = input("-> Enter method of data retrieval (database/personal): ") # get name of database if data_origin == 'database': # get region location or coordinates location = input("-> Mosaic location (ex. 'M 31', '4h23m11s -12d14m32.3s'): ") # get name of database to download data from dataset = input("-> Survey/mission name and observing band (ex. SDSS g): ") # define size of mosaic size = input("-> Mosaic region size in degrees (leave blank if using personal data): ") if size == '': size = 1.0 else: try: size = float(size) except: print("-> Error: invalid size choice\n-> Exiting...") sys.exit() elif data_origin == 'personal': dataset = '' else: print("-> Error: invalid input\n-> Exiting...") sys.exit() # We create and move into subdirectories in this notebook # but we want to come back to the original startup directory # whenever we restart the processing. # move into directory where the mosaic will be built try: os.chdir(mosaic_loc) except FileNotFoundError: print('-> Mosaic location not found\n-> Creating directory now...') try: os.mkdir(mosaic_loc) os.chdir(mosaic_loc) except: print("-> Error: issue with creating mosaic location\n-> Exiting...") sys.exit() print("Mosaic location: " + mosaic_loc) # Clean out any old copy of the work tree, then remake it # and the set of the subdirectories we will need. remove_check = input("-> Remove previous mosaic data for this location if it exists? (y/n): ") if remove_check == 'y': try: shutil.rmtree(workdir) except: print("Can't delete work tree; probably doesn't exist yet", flush=True) elif remove_check == 'n': pass else: print("-> Error: invalid input\n-> Exiting...") sys.exit() # make work directory try: os.makedirs(workdir) except FileExistsError: pass print("Work directory: " + workdir, flush=True) # move into work directory print("-> Moving into work directory...") os.chdir(workdir) # create necessary subfolders print("-> Creating subdirectories that will hold mosaic data...") try: os.makedirs("raw") os.makedirs("projected") os.makedirs("diffs") os.makedirs("corrected") except FileExistsError: print("-> Subdirectories already exist") # retrieve images from archive if 'database' was chosen for data_origin # move images into "raw" if 'personal' was chosen for data_origin if data_origin == 'database': try: getdata = mArchiveDownload(dataset, location, size, "raw") if getdata[getdata.find('count') + 8] == '0': print("-> Warning: No images downloaded") except: print('-> Error: issue with database information\n-> Exiting...') sys.exit() elif data_origin == 'personal': image_loc = input("-> Location of FITS images (if left blank you must manually move images into 'raw' directory): ") if image_loc != '': images = glob.glob("%s/*.fits" % (image_loc)) images_gz = glob.glob("%s/*.gz" % (image_loc)) images_fz = glob.glob("%s/*.fz" % (image_loc)) for gz in images_gz: images.append(gz) for fz in images_fz: images.append(fz) if len(images) == 0: print("-> Error: Could not find any images in %s\n-> Exiting..." % (image_loc)) sys.exit() for im in images: os.system("cp %s 'raw'" % (im)) elif image_loc == '': moved = input("-> Move FITS images into 'raw' directory now\n-> (press ENTER when done)") else: print("-> Error: invalid input\n-> Exiting...") sys.exit() mask_ask = input("-> Read in image masks? (y/n): ") if mask_ask == 'y': mask_method = input("-> Mask type (weight map/mask): ") bkg_ask = input("-> Match image backgrounds? (y/n): ") output_image = input("-> Enter completed mosaic output image name: ") output_image += '.fits' # mask input images if user says so if mask_ask == 'n' or mask_ask == '': pass elif mask_ask == 'y': images = glob.glob("%s/%s/raw/*.fits" % (mosaic_loc, workdir)) print(images) for i in images: data = fits.getdata(i) hdr = fits.getheader(i) mask = fits.getdata(i, 1) if mask_method == 'weight map': new_mask = (mask - 1) * -1 elif mask_method == 'mask': new_mask = mask else: print("-> Error- Unknown input\n-> Exiting...") sys.exit() data += (new_mask*1000000000) data[data > 100000000] = np.nan hdu = fits.PrimaryHDU(data, header=hdr) hdu_mask = fits.ImageHDU(mask) hdu_list = fits.HDUList([hdu, hdu_mask]) hdu_list.writeto(i[:-5]+'_masked.fits', overwrite=True) os.remove(i) else: print("-> Error- Unknown input\n-> Exiting...") # make table of metadata from set of FITS images in 'raw' print("-> Making table of metadata from selected FITS images...") rtn = mImgtbl("raw", "images.tbl") print("mImgtbl: " + str(rtn), flush=True) # make collective FITS header to use in mosaic construction print("-> Making collective FITS header to use in mosaic construction...") rtn2 = mMakeHdr("images.tbl", "template.hdr") print("mMakeHdr: " + str(rtn2), flush=True) # reproject images to the frame defined in the mMakeHdr step print("-> Reprojecting input images...") rtn3 = mProjExec("raw", "images.tbl", "template.hdr", projdir="projected") print("mProjExec: " + str(rtn3), flush=True) # repeat metadata generation steps with reprojected data print("-> Generating metadata table again with reprojected images...") rtn = mImgtbl("projected", "pimages.tbl") print("mImgtbl (projected): " + str(rtn), flush=True) # ask if user wants to background correct images if bkg_ask == 'n': print("-> Constructing final mosaic...") rtn_final = mAdd("projected", "pimages.tbl", "template.hdr", output_image) print("mAdd: " + str(rtn_final), flush=True) elif bkg_ask == 'y' or bkg_ask == '': # background correct images before coaddition print("-> Background correcting images before coaddition...") # Determine the overlaps between images (for background modeling). rtn4 = mOverlaps("pimages.tbl", "diffs.tbl") print("mOverlaps: " + str(rtn4), flush=True) # Generate difference images and fit them. rtn5 = mDiffFitExec("projected", "diffs.tbl", "template.hdr", "diffs", "fits.tbl") print("mDiffFitExec: " + str(rtn5), flush=True) # Model the background corrections. rtn6 = mBgModel("pimages.tbl", "fits.tbl", "corrections.tbl") print("mBgModel: " + str(rtn6), flush=True) # Background correct the projected images. rtn7 = mBgExec("projected", "pimages.tbl", "corrections.tbl", "corrected") print("mBgExec: " + str(rtn7), flush=True) # repeat metadata generation steps with reprojected and background-corrected data rtn = mImgtbl("corrected", "cimages.tbl") print("mImgtbl (corrected): " + str(rtn), flush=True) # make mosaic by coadding reprojected and background-corrected images together print("-> Constructing final mosaic...") rtn_final = mAdd("corrected", "cimages.tbl", "template.hdr", output_image) print("mAdd: " + str(rtn_final), flush=True) else: print("-> Error- Unknown input\n-> Exiting...") sys.exit() # Make a PNG rendering of the data and display it. rtn_view = mViewer("-ct 1 -gray %s -2s max gaussian-log -out %s" % (output_image, output_image.replace('fits','png')), "", mode=2) print("mViewer: " + str(rtn_view), flush=True) Image(filename=output_image.replace('fits','png')) if __name__ == '__main__': MOSAIC()
en
0.849561
#!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Wed Mar 13 18:40:54 2019 @author: andrew # Startup. The Montage modules are pretty much self-contained # but this script needs a few extra utilities. Interfaces with MontagePy to build a mosaic from a set of input images. All parameters are supplied through terminal prompts. See documentation for details. # name the mosaic project # define location of mosaic construction # ask how the data is being collected # database = FITS images from some known astronomical database # personal = FITS images user has already downloaded onto their machine # get name of database # get region location or coordinates # get name of database to download data from # define size of mosaic # We create and move into subdirectories in this notebook # but we want to come back to the original startup directory # whenever we restart the processing. # move into directory where the mosaic will be built # Clean out any old copy of the work tree, then remake it # and the set of the subdirectories we will need. # make work directory # move into work directory # create necessary subfolders # retrieve images from archive if 'database' was chosen for data_origin # move images into "raw" if 'personal' was chosen for data_origin # mask input images if user says so # make table of metadata from set of FITS images in 'raw' # make collective FITS header to use in mosaic construction # reproject images to the frame defined in the mMakeHdr step # repeat metadata generation steps with reprojected data # ask if user wants to background correct images # background correct images before coaddition # Determine the overlaps between images (for background modeling). # Generate difference images and fit them. # Model the background corrections. # Background correct the projected images. # repeat metadata generation steps with reprojected and background-corrected data # make mosaic by coadding reprojected and background-corrected images together # Make a PNG rendering of the data and display it.
2.914061
3
shylock/core/celery/celery.py
ufcg-lsd/shylock
1
6625116
<reponame>ufcg-lsd/shylock import os from datetime import datetime from core.conf import conf_file from pytz import timezone from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.settings") app = Celery("core") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks(['keystone', 'cinder', 'nova', 'monasca', 'core']) openstack_timer = "*/%d" % conf_file['openstack']['collect_period'] monasca_timer = "*/%d" % conf_file['monasca']['collect_period'] # Aggregate report crontab crontab_daily_hour = conf_file['billing']['operators']['crontab_daily_hour'] crontab_daily_hour_replaced = timezone(conf_file['billing']['timezone'])\ .localize(datetime(1970, 1, 1, crontab_daily_hour, 0))\ .astimezone(timezone('UTC')).hour app.conf.beat_schedule = { # cinder "cinder_save_volumes": { "task": "cinder.tasks.save_volumes", "schedule": crontab(minute=openstack_timer), }, "cinder_save_backups": { "task": "cinder.tasks.save_backups", "schedule": crontab(minute=openstack_timer), }, "cinder_save_snapshots": { "task": "cinder.tasks.save_snapshots", "schedule": crontab(minute=openstack_timer), }, # keystone "keystone_save_domains": { "task": "keystone.tasks.save_domains", "schedule": crontab(minute=openstack_timer), }, "keystone_save_projects_and_sponsors": { "task": "keystone.tasks.save_projects_and_sponsors", "schedule": crontab(minute=openstack_timer), }, "keystone_save_services": { "task": "keystone.tasks.save_services", "schedule": crontab(minute=openstack_timer), }, "keystone_save_regions": { "task": "keystone.tasks.save_regions", "schedule": crontab(minute=openstack_timer), }, "keystone_save_quotas": { "task": "keystone.tasks.save_quotas", "schedule": crontab(minute=openstack_timer), }, # nova "nova_save_services": { "task": "nova.tasks.save_services", "schedule": crontab(minute=openstack_timer), }, "nova_save_hypervisors": { "task": "nova.tasks.save_hypervisors", "schedule": crontab(minute=openstack_timer), }, "nova_save_aggregates": { "task": "nova.tasks.save_aggregates", "schedule": crontab(minute=openstack_timer), }, "nova_save_flavors": { "task": "nova.tasks.save_flavors", "schedule": crontab(minute=openstack_timer), }, "nova_save_servers": { "task": "nova.tasks.save_servers", "schedule": crontab(minute=openstack_timer), }, "nova_save_instance_actions": { "task": "nova.tasks.save_instance_actions", "schedule": crontab(minute=openstack_timer), }, # monasca "monasca_schedule_save_statistics": { "task": "monasca.tasks.schedule_save_statistics", "schedule": crontab(minute=monasca_timer), }, # core reports "generate_aggregates_report": { "task": "core.tasks.generate_aggregates_report", "schedule": crontab( minute=0, hour=crontab_daily_hour_replaced), "args": [conf_file['billing']['operators']['send_email'], ], }, "generate_sponsors_report": { "task": "core.tasks.generate_sponsors_report", "schedule": crontab( minute=0, hour=0, day_of_month=conf_file['billing']['sponsors']['crontab_month_day']), "args": [conf_file['billing']['sponsors']['send_email'], ], } }
import os from datetime import datetime from core.conf import conf_file from pytz import timezone from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.settings") app = Celery("core") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks(['keystone', 'cinder', 'nova', 'monasca', 'core']) openstack_timer = "*/%d" % conf_file['openstack']['collect_period'] monasca_timer = "*/%d" % conf_file['monasca']['collect_period'] # Aggregate report crontab crontab_daily_hour = conf_file['billing']['operators']['crontab_daily_hour'] crontab_daily_hour_replaced = timezone(conf_file['billing']['timezone'])\ .localize(datetime(1970, 1, 1, crontab_daily_hour, 0))\ .astimezone(timezone('UTC')).hour app.conf.beat_schedule = { # cinder "cinder_save_volumes": { "task": "cinder.tasks.save_volumes", "schedule": crontab(minute=openstack_timer), }, "cinder_save_backups": { "task": "cinder.tasks.save_backups", "schedule": crontab(minute=openstack_timer), }, "cinder_save_snapshots": { "task": "cinder.tasks.save_snapshots", "schedule": crontab(minute=openstack_timer), }, # keystone "keystone_save_domains": { "task": "keystone.tasks.save_domains", "schedule": crontab(minute=openstack_timer), }, "keystone_save_projects_and_sponsors": { "task": "keystone.tasks.save_projects_and_sponsors", "schedule": crontab(minute=openstack_timer), }, "keystone_save_services": { "task": "keystone.tasks.save_services", "schedule": crontab(minute=openstack_timer), }, "keystone_save_regions": { "task": "keystone.tasks.save_regions", "schedule": crontab(minute=openstack_timer), }, "keystone_save_quotas": { "task": "keystone.tasks.save_quotas", "schedule": crontab(minute=openstack_timer), }, # nova "nova_save_services": { "task": "nova.tasks.save_services", "schedule": crontab(minute=openstack_timer), }, "nova_save_hypervisors": { "task": "nova.tasks.save_hypervisors", "schedule": crontab(minute=openstack_timer), }, "nova_save_aggregates": { "task": "nova.tasks.save_aggregates", "schedule": crontab(minute=openstack_timer), }, "nova_save_flavors": { "task": "nova.tasks.save_flavors", "schedule": crontab(minute=openstack_timer), }, "nova_save_servers": { "task": "nova.tasks.save_servers", "schedule": crontab(minute=openstack_timer), }, "nova_save_instance_actions": { "task": "nova.tasks.save_instance_actions", "schedule": crontab(minute=openstack_timer), }, # monasca "monasca_schedule_save_statistics": { "task": "monasca.tasks.schedule_save_statistics", "schedule": crontab(minute=monasca_timer), }, # core reports "generate_aggregates_report": { "task": "core.tasks.generate_aggregates_report", "schedule": crontab( minute=0, hour=crontab_daily_hour_replaced), "args": [conf_file['billing']['operators']['send_email'], ], }, "generate_sponsors_report": { "task": "core.tasks.generate_sponsors_report", "schedule": crontab( minute=0, hour=0, day_of_month=conf_file['billing']['sponsors']['crontab_month_day']), "args": [conf_file['billing']['sponsors']['send_email'], ], } }
en
0.587807
# Aggregate report crontab # cinder # keystone # nova # monasca # core reports
2.078143
2
Lectures/observed_energy_budget.py
EasezzZ/Climate_Modeling_Lect
136
6625117
<gh_stars>100-1000 ''' This module sets values for the observed global mean planetary energy budget Based on values reported in Trenberth and Fasullo (2012) Surv. Geophys. All values in units of W/m2 Four dictionaries are defined: - SW (the shortwave radiation budget) - LW (the longwave radiation budget) - Turbulent (surface turbulent fluxes) - NetAbsorbed (the net heating rate for atmosphere, surface, and planet) This module is used in the Lecture Notes for ATM 623, Climate Modeling <NAME> University at Albany <EMAIL> ''' SW = {} SW['Incoming Solar Radiation'] = 341.3 SW['Reflected by Clouds and Atmosphere'] = 78.9 SW['Reflected by Surface'] = 23. SW['Reflected Solar Radiation'] = (SW['Reflected by Clouds and Atmosphere'] + SW['Reflected by Surface']) SW['Absorbed by Surface'] = 161. SW['Absorbed by Atmosphere'] = (SW['Incoming Solar Radiation'] - SW['Reflected Solar Radiation'] - SW['Absorbed by Surface']) SW['Absorbed Solar Radiation'] = (SW['Incoming Solar Radiation'] - SW['Reflected Solar Radiation']) LW = {} LW['Surface Radiation'] = 396. LW['Downwelling Radiation'] = 333. LW['Emitted by Atmosphere'] = 187. + 29.5 LW['Absorbed by Atmosphere'] = 374. LW['Atmospheric Window'] = 22. LW['Outgoing Longwave Radiation'] = (LW['Emitted by Atmosphere'] + LW['Atmospheric Window']) Turbulent = {} Turbulent['Thermals'] = 17.1 Turbulent['Evapotranspiration'] = 80. NetAbsorbed = {} NetAbsorbed['Atmosphere'] = (SW['Absorbed by Atmosphere'] + LW['Absorbed by Atmosphere'] - LW['Downwelling Radiation'] - LW['Emitted by Atmosphere'] + Turbulent['Thermals'] + Turbulent['Evapotranspiration']) NetAbsorbed['Surface'] = (SW['Absorbed by Surface'] + LW['Downwelling Radiation'] - LW['Surface Radiation'] - Turbulent['Thermals'] - Turbulent['Evapotranspiration']) NetAbsorbed['Planet'] = (SW['Absorbed Solar Radiation'] - LW['Outgoing Longwave Radiation'])
''' This module sets values for the observed global mean planetary energy budget Based on values reported in Trenberth and Fasullo (2012) Surv. Geophys. All values in units of W/m2 Four dictionaries are defined: - SW (the shortwave radiation budget) - LW (the longwave radiation budget) - Turbulent (surface turbulent fluxes) - NetAbsorbed (the net heating rate for atmosphere, surface, and planet) This module is used in the Lecture Notes for ATM 623, Climate Modeling <NAME> University at Albany <EMAIL> ''' SW = {} SW['Incoming Solar Radiation'] = 341.3 SW['Reflected by Clouds and Atmosphere'] = 78.9 SW['Reflected by Surface'] = 23. SW['Reflected Solar Radiation'] = (SW['Reflected by Clouds and Atmosphere'] + SW['Reflected by Surface']) SW['Absorbed by Surface'] = 161. SW['Absorbed by Atmosphere'] = (SW['Incoming Solar Radiation'] - SW['Reflected Solar Radiation'] - SW['Absorbed by Surface']) SW['Absorbed Solar Radiation'] = (SW['Incoming Solar Radiation'] - SW['Reflected Solar Radiation']) LW = {} LW['Surface Radiation'] = 396. LW['Downwelling Radiation'] = 333. LW['Emitted by Atmosphere'] = 187. + 29.5 LW['Absorbed by Atmosphere'] = 374. LW['Atmospheric Window'] = 22. LW['Outgoing Longwave Radiation'] = (LW['Emitted by Atmosphere'] + LW['Atmospheric Window']) Turbulent = {} Turbulent['Thermals'] = 17.1 Turbulent['Evapotranspiration'] = 80. NetAbsorbed = {} NetAbsorbed['Atmosphere'] = (SW['Absorbed by Atmosphere'] + LW['Absorbed by Atmosphere'] - LW['Downwelling Radiation'] - LW['Emitted by Atmosphere'] + Turbulent['Thermals'] + Turbulent['Evapotranspiration']) NetAbsorbed['Surface'] = (SW['Absorbed by Surface'] + LW['Downwelling Radiation'] - LW['Surface Radiation'] - Turbulent['Thermals'] - Turbulent['Evapotranspiration']) NetAbsorbed['Planet'] = (SW['Absorbed Solar Radiation'] - LW['Outgoing Longwave Radiation'])
en
0.759481
This module sets values for the observed global mean planetary energy budget Based on values reported in Trenberth and Fasullo (2012) Surv. Geophys. All values in units of W/m2 Four dictionaries are defined: - SW (the shortwave radiation budget) - LW (the longwave radiation budget) - Turbulent (surface turbulent fluxes) - NetAbsorbed (the net heating rate for atmosphere, surface, and planet) This module is used in the Lecture Notes for ATM 623, Climate Modeling <NAME> University at Albany <EMAIL>
2.273482
2
gpu_utils.py
ZmeiGorynych/basic_pytorch
2
6625118
use_gpu=True if use_gpu: from torch.cuda import FloatTensor, LongTensor, ByteTensor def to_gpu(x): return x.cuda() else: from torch import FloatTensor, LongTensor, ByteTensor def to_gpu(x): return x.cpu() x1 = FloatTensor() x2 = ByteTensor() # the below function is from the Pytorch forums # https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/3 import subprocess def get_gpu_memory_map(): """Get the current gpu usage. Returns ------- usage: dict Keys are device ids as integers. Values are memory usage as integers in MB. """ try: result = subprocess.check_output( [ 'nvidia-smi', '--query-gpu=memory.used', '--format=csv,nounits,noheader' ], encoding='utf-8') # Convert lines into a dictionary gpu_memory = [int(x) for x in result.strip().split('\n')] gpu_memory_map = dict(zip(range(len(gpu_memory)), gpu_memory)) except: gpu_memory_map = {0: 0} return gpu_memory_map
use_gpu=True if use_gpu: from torch.cuda import FloatTensor, LongTensor, ByteTensor def to_gpu(x): return x.cuda() else: from torch import FloatTensor, LongTensor, ByteTensor def to_gpu(x): return x.cpu() x1 = FloatTensor() x2 = ByteTensor() # the below function is from the Pytorch forums # https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/3 import subprocess def get_gpu_memory_map(): """Get the current gpu usage. Returns ------- usage: dict Keys are device ids as integers. Values are memory usage as integers in MB. """ try: result = subprocess.check_output( [ 'nvidia-smi', '--query-gpu=memory.used', '--format=csv,nounits,noheader' ], encoding='utf-8') # Convert lines into a dictionary gpu_memory = [int(x) for x in result.strip().split('\n')] gpu_memory_map = dict(zip(range(len(gpu_memory)), gpu_memory)) except: gpu_memory_map = {0: 0} return gpu_memory_map
en
0.809254
# the below function is from the Pytorch forums # https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/3 Get the current gpu usage. Returns ------- usage: dict Keys are device ids as integers. Values are memory usage as integers in MB. # Convert lines into a dictionary
3.07768
3
gazoo_device/tests/unit_tests/utils/unifi_poe_switch_device_logs.py
dedsec-9/gazoo-device
14
6625119
<filename>gazoo_device/tests/unit_tests/utils/unifi_poe_switch_device_logs.py # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Device logs for unifi poe switch.""" RETURN_CODE = "0\n" ERROR_RETURN_CODE = "127\n" DEFAULT_BEHAVIOR = { "mca-cli-op info;echo Return Code: $?\n": f""" Model: USW-8P-150 Version: 4.3.13.11253 MAC Address: 12:34:56:78:90:ab IP Address: 172.16.58.3 Hostname: UBNT Uptime: 44625 seconds Status: Unknown[11] (http://172.16.58.3:8080/inform) Return Code: {RETURN_CODE}""", "reboot;echo Return Code: $?\n": f""" Return Code: {RETURN_CODE}""", "sh -c 'echo \"--- GDM Log Marker ---\" >> /var/log/messages';echo Return " "Code: $?\n": f""" Return Code: {RETURN_CODE}""", "echo 'exit' | telnet localhost;echo Return Code: $?\n": f""" Return Code: {RETURN_CODE}\n""", } HEALTH_CHECK_FAILURE = { "echo 'exit' | telnet localhost;echo Return Code: $?\n": f""" Return Code: {ERROR_RETURN_CODE}\n""", } TELNET_COMMAND_RESPONSES = { "telnet localhost\n": """ Entering character mode Escape character is '^]'. Warning! The changes may break controller settings and only be effective until reboot. (UBNT) >""", "enable\n": "(UBNT) #", "config\n": "(UBNT) (Config)#", "interface 0/1\n": "(Interface 0/1)#", "interface 0/2\n": "(Interface 0/2)#", "interface 0/3\n": "(Interface 0/3)#", "interface 0/4\n": "(Interface 0/4)#", "interface 0/5\n": "(Interface 0/5)#", "interface 0/6\n": "(Interface 0/6)#", "interface 0/7\n": "(Interface 0/7)#", "interface 0/8\n": "(Interface 0/8)#", "exit\n": """ Connection closed by foreign host (UBNT) > (UBNT) # (UBNT) (Config)# """, "show hardware\n": """ Switch: 1 System Description............................. USW-8P-150, 4.3.13.11253, Linux 3.6.5 Machine Type................................... USW-8P-150 Machine Model.................................. US8P150 Serial Number.................................. 1234567890ab Burned In MAC Address.......................... 12:34:56:78:90:AB Software Version............................... 4.3.13.11253 (UBNT) #""" } SHOW_POE_PORT_AUTO = { "show poe port 0/1\n": """ (UBNT) (Config)#show poe port 0/1 OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/2\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/2 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/3\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/3 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/4\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/4 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/5\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/5 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/6\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/6 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/7\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/7 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/8\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/8 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port all\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Auto Enable 802.3at Enable Enable Enable 0/2 Auto Enable 802.3at Enable Enable Enable 0/3 Auto Enable 802.3at Enable Enable Enable 0/4 Auto Enable 802.3at Enable Enable Enable 0/5 Auto Enable 802.3at Enable Enable Enable 0/6 Auto Enable 802.3at Enable Enable Enable 0/7 Auto Enable 802.3at Enable Enable Enable 0/8 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""" } SHOW_POE_PORT_SHUTDOWN = { "show poe port 0/1\n": """ (UBNT) (Config)#show poe port 0/1 OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/2\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/2 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/3\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/3 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/4\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/4 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/5\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/5 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/6\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/6 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/7\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/7 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/8\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/8 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port all\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Shutdown Enable 802.3at Enable Enable Enable 0/2 Shutdown Enable 802.3at Enable Enable Enable 0/3 Shutdown Enable 802.3at Enable Enable Enable 0/4 Shutdown Enable 802.3at Enable Enable Enable 0/5 Shutdown Enable 802.3at Enable Enable Enable 0/6 Shutdown Enable 802.3at Enable Enable Enable 0/7 Shutdown Enable 802.3at Enable Enable Enable 0/8 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""" }
<filename>gazoo_device/tests/unit_tests/utils/unifi_poe_switch_device_logs.py # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Device logs for unifi poe switch.""" RETURN_CODE = "0\n" ERROR_RETURN_CODE = "127\n" DEFAULT_BEHAVIOR = { "mca-cli-op info;echo Return Code: $?\n": f""" Model: USW-8P-150 Version: 4.3.13.11253 MAC Address: 12:34:56:78:90:ab IP Address: 172.16.58.3 Hostname: UBNT Uptime: 44625 seconds Status: Unknown[11] (http://172.16.58.3:8080/inform) Return Code: {RETURN_CODE}""", "reboot;echo Return Code: $?\n": f""" Return Code: {RETURN_CODE}""", "sh -c 'echo \"--- GDM Log Marker ---\" >> /var/log/messages';echo Return " "Code: $?\n": f""" Return Code: {RETURN_CODE}""", "echo 'exit' | telnet localhost;echo Return Code: $?\n": f""" Return Code: {RETURN_CODE}\n""", } HEALTH_CHECK_FAILURE = { "echo 'exit' | telnet localhost;echo Return Code: $?\n": f""" Return Code: {ERROR_RETURN_CODE}\n""", } TELNET_COMMAND_RESPONSES = { "telnet localhost\n": """ Entering character mode Escape character is '^]'. Warning! The changes may break controller settings and only be effective until reboot. (UBNT) >""", "enable\n": "(UBNT) #", "config\n": "(UBNT) (Config)#", "interface 0/1\n": "(Interface 0/1)#", "interface 0/2\n": "(Interface 0/2)#", "interface 0/3\n": "(Interface 0/3)#", "interface 0/4\n": "(Interface 0/4)#", "interface 0/5\n": "(Interface 0/5)#", "interface 0/6\n": "(Interface 0/6)#", "interface 0/7\n": "(Interface 0/7)#", "interface 0/8\n": "(Interface 0/8)#", "exit\n": """ Connection closed by foreign host (UBNT) > (UBNT) # (UBNT) (Config)# """, "show hardware\n": """ Switch: 1 System Description............................. USW-8P-150, 4.3.13.11253, Linux 3.6.5 Machine Type................................... USW-8P-150 Machine Model.................................. US8P150 Serial Number.................................. 1234567890ab Burned In MAC Address.......................... 12:34:56:78:90:AB Software Version............................... 4.3.13.11253 (UBNT) #""" } SHOW_POE_PORT_AUTO = { "show poe port 0/1\n": """ (UBNT) (Config)#show poe port 0/1 OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/2\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/2 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/3\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/3 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/4\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/4 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/5\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/5 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/6\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/6 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/7\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/7 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/8\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/8 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port all\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Auto Enable 802.3at Enable Enable Enable 0/2 Auto Enable 802.3at Enable Enable Enable 0/3 Auto Enable 802.3at Enable Enable Enable 0/4 Auto Enable 802.3at Enable Enable Enable 0/5 Auto Enable 802.3at Enable Enable Enable 0/6 Auto Enable 802.3at Enable Enable Enable 0/7 Auto Enable 802.3at Enable Enable Enable 0/8 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)#""" } SHOW_POE_PORT_SHUTDOWN = { "show poe port 0/1\n": """ (UBNT) (Config)#show poe port 0/1 OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/2\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/2 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/3\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/3 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/4\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/4 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/5\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/5 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/6\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/6 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/7\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/7 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port 0/8\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/8 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""", "show poe port all\n": """ OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Shutdown Enable 802.3at Enable Enable Enable 0/2 Shutdown Enable 802.3at Enable Enable Enable 0/3 Shutdown Enable 802.3at Enable Enable Enable 0/4 Shutdown Enable 802.3at Enable Enable Enable 0/5 Shutdown Enable 802.3at Enable Enable Enable 0/6 Shutdown Enable 802.3at Enable Enable Enable 0/7 Shutdown Enable 802.3at Enable Enable Enable 0/8 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#""" }
en
0.467305
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Device logs for unifi poe switch. Model: USW-8P-150 Version: 4.3.13.11253 MAC Address: 12:34:56:78:90:ab IP Address: 172.16.58.3 Hostname: UBNT Uptime: 44625 seconds Status: Unknown[11] (http://172.16.58.3:8080/inform) Return Code: {RETURN_CODE} Return Code: {RETURN_CODE} Return Code: {RETURN_CODE} Return Code: {RETURN_CODE}\n Return Code: {ERROR_RETURN_CODE}\n Entering character mode Escape character is '^]'. Warning! The changes may break controller settings and only be effective until reboot. (UBNT) > #", #", #", #", #", #", #", #", #", #", Connection closed by foreign host (UBNT) > (UBNT) # (UBNT) (Config)# Switch: 1 System Description............................. USW-8P-150, 4.3.13.11253, Linux 3.6.5 Machine Type................................... USW-8P-150 Machine Model.................................. US8P150 Serial Number.................................. 1234567890ab Burned In MAC Address.......................... 12:34:56:78:90:AB Software Version............................... 4.3.13.11253 (UBNT) # (UBNT) (Config)#show poe port 0/1 OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/2 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/3 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/4 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/5 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/6 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/7 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/8 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Auto Enable 802.3at Enable Enable Enable 0/2 Auto Enable 802.3at Enable Enable Enable 0/3 Auto Enable 802.3at Enable Enable Enable 0/4 Auto Enable 802.3at Enable Enable Enable 0/5 Auto Enable 802.3at Enable Enable Enable 0/6 Auto Enable 802.3at Enable Enable Enable 0/7 Auto Enable 802.3at Enable Enable Enable 0/8 Auto Enable 802.3at Enable Enable Enable (UBNT) (Config)# (UBNT) (Config)#show poe port 0/1 OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/2 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/3 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/4 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/5 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/6 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/7 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/8 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)# OP HP HP Detect Disconnect Class Intf Mode Enable Mode Enable Enable Enable --------- ---------------- ------- ------- ------- ---------- ------- 0/1 Shutdown Enable 802.3at Enable Enable Enable 0/2 Shutdown Enable 802.3at Enable Enable Enable 0/3 Shutdown Enable 802.3at Enable Enable Enable 0/4 Shutdown Enable 802.3at Enable Enable Enable 0/5 Shutdown Enable 802.3at Enable Enable Enable 0/6 Shutdown Enable 802.3at Enable Enable Enable 0/7 Shutdown Enable 802.3at Enable Enable Enable 0/8 Shutdown Enable 802.3at Enable Enable Enable (UBNT) (Config)#
1.991622
2
app/view/__init__.py
LuckyQueen0928/tanna
3
6625120
<gh_stars>1-10 # -*- coding: utf-8 -*- from flask import Blueprint view = Blueprint('view', __name__) from . import views
# -*- coding: utf-8 -*- from flask import Blueprint view = Blueprint('view', __name__) from . import views
en
0.769321
# -*- coding: utf-8 -*-
1.209938
1
fgapiservergui_config.py
FutureGatewayFramework/fgAPIServerGUI
0
6625121
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015: # Istituto Nazionale di Fisica Nucleare (INFN), Italy # # See http://www.infn.it for details on the copyrigh holder # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import json import yaml import logging __author__ = '<NAME>' __copyright__ = '2019' __license__ = 'Apache' __version__ = 'v0.0.0' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'devel' __update__ = '2019-06-24 17:00:59' # Logging object logger = logging.getLogger(__name__) class FGApiServerConfig(dict): """ FutureGateway API Server configuration values class This class inherits from dict class aiming to store all configutation values of the FutureGateway module fgAPIServer. The class internally stores all available configuration settings and their related default values. The class also takes configuration values from environment variables, in this case they have the higher priority """ # Default values for configuration settings def_api_ver = '1.0' def_fg_ver = __version__ # Default values; used when conf file does not exists # or an option is missing on configuration file # the use of default values is notified by the # class variable fgConfigMsg defaults = { 'fgapiservergui': { 'service_name': 'FutureGateway API Server GUI', 'url_prefix': '', 'debug': 'True', 'json_indent': '4', 'logging_conf': 'logging.conf', 'apiserver': 'http://localhost/fgapiserver', 'fgapiver': 'V1.0', 'fgapiserver_user': 'futuregateway', 'fgapiserver_password': '<PASSWORD>', }, 'fgapiserver_db': { 'fgapisrv_db_host': '127.0.0.1', 'fgapisrv_db_port': '3306', 'fgapisrv_db_user': 'fgapiserver', 'fgapisrv_db_pass': '<PASSWORD>', 'fgapisrv_db_name': 'fgapiserver', 'dbver': '0.0.13', }, } # Configuration data types # Following vectors consider only int and bool types remaining # configuration options will be considered strings as default int_types = ['json_indent', 'fgapisrv_db_port', ] bool_types = ['debug', ] # Configuration messages informs about the loading # of configuration values fg_config_messages = "Configuration messages ...\n" def __init__(self, config_file): """ Initialize the configutation object loading the given configuration file """ dict.__init__(self) logging.debug("Initializing config object") # Load config from config_file if config_file is None: config_file = '' conf_yaml = {} try: conf_file = open(config_file, 'r') conf_yaml = yaml.load(conf_file, Loader=yaml.FullLoader) self.config_file = config_file except IOError: logging.warn( "Couldn't find configuration file '%s'; " " default options will be used" % config_file) pass # Load configuration settings using hardcoded key values as key # reference for section in self.defaults.keys(): for conf_name in self.defaults[section].keys(): def_value = self.defaults[section][conf_name] try: self[conf_name] = conf_yaml[section][conf_name] except KeyError: self[conf_name] = def_value logging.warn( "Couldn't find option '%s' " "in section '%s'; " "using default value '%s'" % (conf_name, section, def_value)) # The use of environment varialbes override any default or # configuration setting present in the configuration file try: env_value = os.environ[conf_name.upper()] logging.warn( "Environment bypass of '%s': '%s' <- '%s'" % (conf_name, self[conf_name], env_value)) self[conf_name] = env_value except KeyError: # Corresponding environment variable not exists pass if self['debug']: logging.debug(self.show_conf()) def __getitem__(self, key): conf_value = dict.__getitem__(self, key) if key in self.bool_types: conf_value = (str(conf_value).lower() == 'true') if key in self.int_types: conf_value = int(conf_value) return conf_value def __setitem__(self, key, value): if key in self.bool_types: conf_value = (str(value).lower() == 'true') elif key in self.int_types: conf_value = int(value) else: conf_value = value dict.__setitem__(self, key, conf_value) def __repr__(self): """ Perform object representation as in defaults scheme :return: """ config = {} for section in self.defaults.keys(): section_config = {} for key in self.defaults[section]: section_config[key] = self[key] config[section] = section_config return json.dumps(config, indent=int(self['json_indent'])) def show_conf(self): """ Show the loaded APIServer fron-end configuration :return: """ config = {} for section in self.defaults.keys(): section_config = {} for key in self.defaults[section]: section_config[key] = self[key] config[section] = section_config return ("\n" "---------------------------------------\n" " FutureGateway API ServerDaemon config \n" "---------------------------------------\n" "%s\n" % self) def get_messages(self): """ Return the messages created during configuration loading """ return self.fg_config_messages def load_config(self, cfg_dict): """ Save configuration settings stored in the given dictionary """ if cfg_dict is not None: for key in cfg_dict: value = cfg_dict[key] self[key] = value # fgAPIServerDeemon configuration file config_file = 'fgapiservergui.yaml' # Load configuration fg_config = FGApiServerConfig(config_file)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015: # Istituto Nazionale di Fisica Nucleare (INFN), Italy # # See http://www.infn.it for details on the copyrigh holder # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import json import yaml import logging __author__ = '<NAME>' __copyright__ = '2019' __license__ = 'Apache' __version__ = 'v0.0.0' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'devel' __update__ = '2019-06-24 17:00:59' # Logging object logger = logging.getLogger(__name__) class FGApiServerConfig(dict): """ FutureGateway API Server configuration values class This class inherits from dict class aiming to store all configutation values of the FutureGateway module fgAPIServer. The class internally stores all available configuration settings and their related default values. The class also takes configuration values from environment variables, in this case they have the higher priority """ # Default values for configuration settings def_api_ver = '1.0' def_fg_ver = __version__ # Default values; used when conf file does not exists # or an option is missing on configuration file # the use of default values is notified by the # class variable fgConfigMsg defaults = { 'fgapiservergui': { 'service_name': 'FutureGateway API Server GUI', 'url_prefix': '', 'debug': 'True', 'json_indent': '4', 'logging_conf': 'logging.conf', 'apiserver': 'http://localhost/fgapiserver', 'fgapiver': 'V1.0', 'fgapiserver_user': 'futuregateway', 'fgapiserver_password': '<PASSWORD>', }, 'fgapiserver_db': { 'fgapisrv_db_host': '127.0.0.1', 'fgapisrv_db_port': '3306', 'fgapisrv_db_user': 'fgapiserver', 'fgapisrv_db_pass': '<PASSWORD>', 'fgapisrv_db_name': 'fgapiserver', 'dbver': '0.0.13', }, } # Configuration data types # Following vectors consider only int and bool types remaining # configuration options will be considered strings as default int_types = ['json_indent', 'fgapisrv_db_port', ] bool_types = ['debug', ] # Configuration messages informs about the loading # of configuration values fg_config_messages = "Configuration messages ...\n" def __init__(self, config_file): """ Initialize the configutation object loading the given configuration file """ dict.__init__(self) logging.debug("Initializing config object") # Load config from config_file if config_file is None: config_file = '' conf_yaml = {} try: conf_file = open(config_file, 'r') conf_yaml = yaml.load(conf_file, Loader=yaml.FullLoader) self.config_file = config_file except IOError: logging.warn( "Couldn't find configuration file '%s'; " " default options will be used" % config_file) pass # Load configuration settings using hardcoded key values as key # reference for section in self.defaults.keys(): for conf_name in self.defaults[section].keys(): def_value = self.defaults[section][conf_name] try: self[conf_name] = conf_yaml[section][conf_name] except KeyError: self[conf_name] = def_value logging.warn( "Couldn't find option '%s' " "in section '%s'; " "using default value '%s'" % (conf_name, section, def_value)) # The use of environment varialbes override any default or # configuration setting present in the configuration file try: env_value = os.environ[conf_name.upper()] logging.warn( "Environment bypass of '%s': '%s' <- '%s'" % (conf_name, self[conf_name], env_value)) self[conf_name] = env_value except KeyError: # Corresponding environment variable not exists pass if self['debug']: logging.debug(self.show_conf()) def __getitem__(self, key): conf_value = dict.__getitem__(self, key) if key in self.bool_types: conf_value = (str(conf_value).lower() == 'true') if key in self.int_types: conf_value = int(conf_value) return conf_value def __setitem__(self, key, value): if key in self.bool_types: conf_value = (str(value).lower() == 'true') elif key in self.int_types: conf_value = int(value) else: conf_value = value dict.__setitem__(self, key, conf_value) def __repr__(self): """ Perform object representation as in defaults scheme :return: """ config = {} for section in self.defaults.keys(): section_config = {} for key in self.defaults[section]: section_config[key] = self[key] config[section] = section_config return json.dumps(config, indent=int(self['json_indent'])) def show_conf(self): """ Show the loaded APIServer fron-end configuration :return: """ config = {} for section in self.defaults.keys(): section_config = {} for key in self.defaults[section]: section_config[key] = self[key] config[section] = section_config return ("\n" "---------------------------------------\n" " FutureGateway API ServerDaemon config \n" "---------------------------------------\n" "%s\n" % self) def get_messages(self): """ Return the messages created during configuration loading """ return self.fg_config_messages def load_config(self, cfg_dict): """ Save configuration settings stored in the given dictionary """ if cfg_dict is not None: for key in cfg_dict: value = cfg_dict[key] self[key] = value # fgAPIServerDeemon configuration file config_file = 'fgapiservergui.yaml' # Load configuration fg_config = FGApiServerConfig(config_file)
en
0.707997
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015: # Istituto Nazionale di Fisica Nucleare (INFN), Italy # # See http://www.infn.it for details on the copyrigh holder # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Logging object FutureGateway API Server configuration values class This class inherits from dict class aiming to store all configutation values of the FutureGateway module fgAPIServer. The class internally stores all available configuration settings and their related default values. The class also takes configuration values from environment variables, in this case they have the higher priority # Default values for configuration settings # Default values; used when conf file does not exists # or an option is missing on configuration file # the use of default values is notified by the # class variable fgConfigMsg # Configuration data types # Following vectors consider only int and bool types remaining # configuration options will be considered strings as default # Configuration messages informs about the loading # of configuration values Initialize the configutation object loading the given configuration file # Load config from config_file # Load configuration settings using hardcoded key values as key # reference # The use of environment varialbes override any default or # configuration setting present in the configuration file # Corresponding environment variable not exists Perform object representation as in defaults scheme :return: Show the loaded APIServer fron-end configuration :return: Return the messages created during configuration loading Save configuration settings stored in the given dictionary # fgAPIServerDeemon configuration file # Load configuration
1.837953
2
data/video_dataset.py
MikeWangWZHL/BLIP
473
6625122
<reponame>MikeWangWZHL/BLIP from torch.utils.data import Dataset from torchvision.datasets.utils import download_url from PIL import Image import torch import numpy as np import random import decord from decord import VideoReader import json import os from data.utils import pre_caption decord.bridge.set_bridge("torch") class ImageNorm(object): """Apply Normalization to Image Pixels on GPU """ def __init__(self, mean, std): self.mean = torch.tensor(mean).view(1, 3, 1, 1) self.std = torch.tensor(std).view(1, 3, 1, 1) def __call__(self, img): if torch.max(img) > 1 and self.mean.max() <= 1: img.div_(255.) return img.sub_(self.mean).div_(self.std) def load_jsonl(filename): with open(filename, "r") as f: return [json.loads(l.strip("\n")) for l in f.readlines()] class VideoDataset(Dataset): def __init__(self, video_root, ann_root, num_frm=4, frm_sampling_strategy="rand", max_img_size=384, video_fmt='.mp4'): ''' image_root (string): Root directory of video ann_root (string): directory to store the annotation file ''' url = 'https://storage.googleapis.com/sfr-vision-language-research/datasets/msrvtt_test.jsonl' filename = 'msrvtt_test.jsonl' download_url(url,ann_root) self.annotation = load_jsonl(os.path.join(ann_root,filename)) self.num_frm = num_frm self.frm_sampling_strategy = frm_sampling_strategy self.max_img_size = max_img_size self.video_root = video_root self.video_fmt = video_fmt self.img_norm = ImageNorm(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711)) self.text = [pre_caption(ann['caption'],40) for ann in self.annotation] self.txt2video = [i for i in range(len(self.annotation))] self.video2txt = self.txt2video def __len__(self): return len(self.annotation) def __getitem__(self, index): ann = self.annotation[index] video_path = os.path.join(self.video_root, ann['clip_name'] + self.video_fmt) vid_frm_array = self._load_video_from_path_decord(video_path, height=self.max_img_size, width=self.max_img_size) video = self.img_norm(vid_frm_array.float()) return video, ann['clip_name'] def _load_video_from_path_decord(self, video_path, height=None, width=None, start_time=None, end_time=None, fps=-1): try: if not height or not width: vr = VideoReader(video_path) else: vr = VideoReader(video_path, width=width, height=height) vlen = len(vr) if start_time or end_time: assert fps > 0, 'must provide video fps if specifying start and end time.' start_idx = min(int(start_time * fps), vlen) end_idx = min(int(end_time * fps), vlen) else: start_idx, end_idx = 0, vlen if self.frm_sampling_strategy == 'uniform': frame_indices = np.arange(start_idx, end_idx, vlen / self.num_frm, dtype=int) elif self.frm_sampling_strategy == 'rand': frame_indices = sorted(random.sample(range(vlen), self.num_frm)) elif self.frm_sampling_strategy == 'headtail': frame_indices_head = sorted(random.sample(range(vlen // 2), self.num_frm // 2)) frame_indices_tail = sorted(random.sample(range(vlen // 2, vlen), self.num_frm // 2)) frame_indices = frame_indices_head + frame_indices_tail else: raise NotImplementedError('Invalid sampling strategy {} '.format(self.frm_sampling_strategy)) raw_sample_frms = vr.get_batch(frame_indices) except Exception as e: return None raw_sample_frms = raw_sample_frms.permute(0, 3, 1, 2) return raw_sample_frms
from torch.utils.data import Dataset from torchvision.datasets.utils import download_url from PIL import Image import torch import numpy as np import random import decord from decord import VideoReader import json import os from data.utils import pre_caption decord.bridge.set_bridge("torch") class ImageNorm(object): """Apply Normalization to Image Pixels on GPU """ def __init__(self, mean, std): self.mean = torch.tensor(mean).view(1, 3, 1, 1) self.std = torch.tensor(std).view(1, 3, 1, 1) def __call__(self, img): if torch.max(img) > 1 and self.mean.max() <= 1: img.div_(255.) return img.sub_(self.mean).div_(self.std) def load_jsonl(filename): with open(filename, "r") as f: return [json.loads(l.strip("\n")) for l in f.readlines()] class VideoDataset(Dataset): def __init__(self, video_root, ann_root, num_frm=4, frm_sampling_strategy="rand", max_img_size=384, video_fmt='.mp4'): ''' image_root (string): Root directory of video ann_root (string): directory to store the annotation file ''' url = 'https://storage.googleapis.com/sfr-vision-language-research/datasets/msrvtt_test.jsonl' filename = 'msrvtt_test.jsonl' download_url(url,ann_root) self.annotation = load_jsonl(os.path.join(ann_root,filename)) self.num_frm = num_frm self.frm_sampling_strategy = frm_sampling_strategy self.max_img_size = max_img_size self.video_root = video_root self.video_fmt = video_fmt self.img_norm = ImageNorm(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711)) self.text = [pre_caption(ann['caption'],40) for ann in self.annotation] self.txt2video = [i for i in range(len(self.annotation))] self.video2txt = self.txt2video def __len__(self): return len(self.annotation) def __getitem__(self, index): ann = self.annotation[index] video_path = os.path.join(self.video_root, ann['clip_name'] + self.video_fmt) vid_frm_array = self._load_video_from_path_decord(video_path, height=self.max_img_size, width=self.max_img_size) video = self.img_norm(vid_frm_array.float()) return video, ann['clip_name'] def _load_video_from_path_decord(self, video_path, height=None, width=None, start_time=None, end_time=None, fps=-1): try: if not height or not width: vr = VideoReader(video_path) else: vr = VideoReader(video_path, width=width, height=height) vlen = len(vr) if start_time or end_time: assert fps > 0, 'must provide video fps if specifying start and end time.' start_idx = min(int(start_time * fps), vlen) end_idx = min(int(end_time * fps), vlen) else: start_idx, end_idx = 0, vlen if self.frm_sampling_strategy == 'uniform': frame_indices = np.arange(start_idx, end_idx, vlen / self.num_frm, dtype=int) elif self.frm_sampling_strategy == 'rand': frame_indices = sorted(random.sample(range(vlen), self.num_frm)) elif self.frm_sampling_strategy == 'headtail': frame_indices_head = sorted(random.sample(range(vlen // 2), self.num_frm // 2)) frame_indices_tail = sorted(random.sample(range(vlen // 2, vlen), self.num_frm // 2)) frame_indices = frame_indices_head + frame_indices_tail else: raise NotImplementedError('Invalid sampling strategy {} '.format(self.frm_sampling_strategy)) raw_sample_frms = vr.get_batch(frame_indices) except Exception as e: return None raw_sample_frms = raw_sample_frms.permute(0, 3, 1, 2) return raw_sample_frms
en
0.691833
Apply Normalization to Image Pixels on GPU image_root (string): Root directory of video ann_root (string): directory to store the annotation file
2.4863
2
ironic/api/controllers/v1/volume_connector.py
inmotionhosting/ironic
1
6625123
# Copyright (c) 2017 Hitachi, Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from http import client as http_client from ironic_lib import metrics_utils from oslo_utils import uuidutils from pecan import rest from ironic import api from ironic.api.controllers import link from ironic.api.controllers.v1 import collection from ironic.api.controllers.v1 import notification_utils as notify from ironic.api.controllers.v1 import utils as api_utils from ironic.api import method from ironic.common import args from ironic.common import exception from ironic.common.i18n import _ from ironic import objects METRICS = metrics_utils.get_metrics_logger(__name__) _DEFAULT_RETURN_FIELDS = ['uuid', 'node_uuid', 'type', 'connector_id'] CONNECTOR_SCHEMA = { 'type': 'object', 'properties': { 'connector_id': {'type': 'string'}, 'extra': {'type': ['object', 'null']}, 'node_uuid': {'type': 'string'}, 'type': {'type': 'string'}, 'uuid': {'type': ['string', 'null']}, }, 'required': ['connector_id', 'node_uuid', 'type'], 'additionalProperties': False, } CONNECTOR_VALIDATOR_EXTRA = args.dict_valid( node_uuid=args.uuid, uuid=args.uuid, ) CONNECTOR_VALIDATOR = args.and_valid( args.schema(CONNECTOR_SCHEMA), CONNECTOR_VALIDATOR_EXTRA ) PATCH_ALLOWED_FIELDS = [ 'connector_id', 'extra', 'node_uuid', 'type' ] def convert_with_links(rpc_connector, fields=None, sanitize=True): connector = api_utils.object_to_dict( rpc_connector, link_resource='volume/connectors', fields=('connector_id', 'extra', 'type') ) api_utils.populate_node_uuid(rpc_connector, connector) if fields is not None: api_utils.check_for_invalid_fields(fields, connector) if not sanitize: return connector api_utils.sanitize_dict(connector, fields) return connector def list_convert_with_links(rpc_connectors, limit, url=None, fields=None, detail=None, **kwargs): if detail: kwargs['detail'] = detail return collection.list_convert_with_links( items=[convert_with_links(p, fields=fields, sanitize=False) for p in rpc_connectors], item_name='connectors', limit=limit, url=url, fields=fields, sanitize_func=api_utils.sanitize_dict, **kwargs ) class VolumeConnectorsController(rest.RestController): """REST controller for VolumeConnectors.""" invalid_sort_key_list = ['extra'] def __init__(self, node_ident=None): super(VolumeConnectorsController, self).__init__() self.parent_node_ident = node_ident def _get_volume_connectors_collection(self, node_ident, marker, limit, sort_key, sort_dir, resource_url=None, fields=None, detail=None): limit = api_utils.validate_limit(limit) sort_dir = api_utils.validate_sort_dir(sort_dir) marker_obj = None if marker: marker_obj = objects.VolumeConnector.get_by_uuid( api.request.context, marker) if sort_key in self.invalid_sort_key_list: raise exception.InvalidParameterValue( _("The sort_key value %(key)s is an invalid field for " "sorting") % {'key': sort_key}) node_ident = self.parent_node_ident or node_ident if node_ident: # FIXME(comstud): Since all we need is the node ID, we can # make this more efficient by only querying # for that column. This will get cleaned up # as we move to the object interface. node = api_utils.get_rpc_node(node_ident) connectors = objects.VolumeConnector.list_by_node_id( api.request.context, node.id, limit, marker_obj, sort_key=sort_key, sort_dir=sort_dir) else: connectors = objects.VolumeConnector.list(api.request.context, limit, marker_obj, sort_key=sort_key, sort_dir=sort_dir) return list_convert_with_links(connectors, limit, url=resource_url, fields=fields, sort_key=sort_key, sort_dir=sort_dir, detail=detail) @METRICS.timer('VolumeConnectorsController.get_all') @method.expose() @args.validate(node=args.uuid_or_name, marker=args.uuid, limit=args.integer, sort_key=args.string, sort_dir=args.string, fields=args.string_list, detail=args.boolean) def get_all(self, node=None, marker=None, limit=None, sort_key='id', sort_dir='asc', fields=None, detail=None): """Retrieve a list of volume connectors. :param node: UUID or name of a node, to get only volume connectors for that node. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. This value cannot be larger than the value of max_limit in the [api] section of the ironic configuration, or only max_limit resources will be returned. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: "asc". :param fields: Optional, a list with a specified set of fields of the resource to be returned. :param detail: Optional, whether to retrieve with detail. :returns: a list of volume connectors, or an empty list if no volume connector is found. :raises: InvalidParameterValue if sort_key does not exist :raises: InvalidParameterValue if sort key is invalid for sorting. :raises: InvalidParameterValue if both fields and detail are specified. """ api_utils.check_policy('baremetal:volume:get') if fields is None and not detail: fields = _DEFAULT_RETURN_FIELDS if fields and detail: raise exception.InvalidParameterValue( _("Can't fetch a subset of fields with 'detail' set")) resource_url = 'volume/connectors' return self._get_volume_connectors_collection( node, marker, limit, sort_key, sort_dir, resource_url=resource_url, fields=fields, detail=detail) @METRICS.timer('VolumeConnectorsController.get_one') @method.expose() @args.validate(connector_uuid=args.uuid, fields=args.string_list) def get_one(self, connector_uuid, fields=None): """Retrieve information about the given volume connector. :param connector_uuid: UUID of a volume connector. :param fields: Optional, a list with a specified set of fields of the resource to be returned. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: VolumeConnectorNotFound if no volume connector exists with the specified UUID. """ api_utils.check_policy('baremetal:volume:get') if self.parent_node_ident: raise exception.OperationNotPermitted() rpc_connector = objects.VolumeConnector.get_by_uuid( api.request.context, connector_uuid) return convert_with_links(rpc_connector, fields=fields) @METRICS.timer('VolumeConnectorsController.post') @method.expose(status_code=http_client.CREATED) @method.body('connector') @args.validate(connector=CONNECTOR_VALIDATOR) def post(self, connector): """Create a new volume connector. :param connector: a volume connector within the request body. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: VolumeConnectorTypeAndIdAlreadyExists if a volume connector already exists with the same type and connector_id :raises: VolumeConnectorAlreadyExists if a volume connector with the same UUID already exists """ context = api.request.context api_utils.check_policy('baremetal:volume:create') if self.parent_node_ident: raise exception.OperationNotPermitted() # NOTE(hshiina): UUID is mandatory for notification payload if not connector.get('uuid'): connector['uuid'] = uuidutils.generate_uuid() node = api_utils.replace_node_uuid_with_id(connector) new_connector = objects.VolumeConnector(context, **connector) notify.emit_start_notification(context, new_connector, 'create', node_uuid=node.uuid) with notify.handle_error_notification(context, new_connector, 'create', node_uuid=node.uuid): new_connector.create() notify.emit_end_notification(context, new_connector, 'create', node_uuid=node.uuid) # Set the HTTP Location Header api.response.location = link.build_url('volume/connectors', new_connector.uuid) return convert_with_links(new_connector) @METRICS.timer('VolumeConnectorsController.patch') @method.expose() @method.body('patch') @args.validate(connector_uuid=args.uuid, patch=args.patch) def patch(self, connector_uuid, patch): """Update an existing volume connector. :param connector_uuid: UUID of a volume connector. :param patch: a json PATCH document to apply to this volume connector. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: PatchError if a given patch can not be applied. :raises: VolumeConnectorNotFound if no volume connector exists with the specified UUID. :raises: InvalidParameterValue if the volume connector's UUID is being changed :raises: NodeLocked if node is locked by another conductor :raises: NodeNotFound if the node associated with the connector does not exist :raises: VolumeConnectorTypeAndIdAlreadyExists if another connector already exists with the same values for type and connector_id fields :raises: InvalidUUID if invalid node UUID is passed in the patch. :raises: InvalidStateRequested If a node associated with the volume connector is not powered off. """ context = api.request.context api_utils.check_policy('baremetal:volume:update') if self.parent_node_ident: raise exception.OperationNotPermitted() api_utils.patch_validate_allowed_fields(patch, PATCH_ALLOWED_FIELDS) for value in api_utils.get_patch_values(patch, '/node_uuid'): if not uuidutils.is_uuid_like(value): message = _("Expected a UUID for node_uuid, but received " "%(uuid)s.") % {'uuid': str(value)} raise exception.InvalidUUID(message=message) rpc_connector = objects.VolumeConnector.get_by_uuid(context, connector_uuid) connector_dict = rpc_connector.as_dict() # NOTE(smoriya): # 1) Remove node_id because it's an internal value and # not present in the API object # 2) Add node_uuid rpc_node = api_utils.replace_node_id_with_uuid(connector_dict) connector_dict = api_utils.apply_jsonpatch(connector_dict, patch) try: if connector_dict['node_uuid'] != rpc_node.uuid: rpc_node = objects.Node.get( api.request.context, connector_dict['node_uuid']) except exception.NodeNotFound as e: # Change error code because 404 (NotFound) is inappropriate # response for a PATCH request to change a Port e.code = http_client.BAD_REQUEST # BadRequest raise api_utils.patched_validate_with_schema( connector_dict, CONNECTOR_SCHEMA, CONNECTOR_VALIDATOR) api_utils.patch_update_changed_fields( connector_dict, rpc_connector, fields=objects.VolumeConnector.fields, schema=CONNECTOR_SCHEMA, id_map={'node_id': rpc_node.id} ) notify.emit_start_notification(context, rpc_connector, 'update', node_uuid=rpc_node.uuid) with notify.handle_error_notification(context, rpc_connector, 'update', node_uuid=rpc_node.uuid): topic = api.request.rpcapi.get_topic_for(rpc_node) new_connector = api.request.rpcapi.update_volume_connector( context, rpc_connector, topic) api_connector = convert_with_links(new_connector) notify.emit_end_notification(context, new_connector, 'update', node_uuid=rpc_node.uuid) return api_connector @METRICS.timer('VolumeConnectorsController.delete') @method.expose(status_code=http_client.NO_CONTENT) @args.validate(connector_uuid=args.uuid) def delete(self, connector_uuid): """Delete a volume connector. :param connector_uuid: UUID of a volume connector. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: NodeLocked if node is locked by another conductor :raises: NodeNotFound if the node associated with the connector does not exist :raises: VolumeConnectorNotFound if the volume connector cannot be found :raises: InvalidStateRequested If a node associated with the volume connector is not powered off. """ context = api.request.context api_utils.check_policy('baremetal:volume:delete') if self.parent_node_ident: raise exception.OperationNotPermitted() rpc_connector = objects.VolumeConnector.get_by_uuid(context, connector_uuid) rpc_node = objects.Node.get_by_id(context, rpc_connector.node_id) notify.emit_start_notification(context, rpc_connector, 'delete', node_uuid=rpc_node.uuid) with notify.handle_error_notification(context, rpc_connector, 'delete', node_uuid=rpc_node.uuid): topic = api.request.rpcapi.get_topic_for(rpc_node) api.request.rpcapi.destroy_volume_connector(context, rpc_connector, topic) notify.emit_end_notification(context, rpc_connector, 'delete', node_uuid=rpc_node.uuid)
# Copyright (c) 2017 Hitachi, Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from http import client as http_client from ironic_lib import metrics_utils from oslo_utils import uuidutils from pecan import rest from ironic import api from ironic.api.controllers import link from ironic.api.controllers.v1 import collection from ironic.api.controllers.v1 import notification_utils as notify from ironic.api.controllers.v1 import utils as api_utils from ironic.api import method from ironic.common import args from ironic.common import exception from ironic.common.i18n import _ from ironic import objects METRICS = metrics_utils.get_metrics_logger(__name__) _DEFAULT_RETURN_FIELDS = ['uuid', 'node_uuid', 'type', 'connector_id'] CONNECTOR_SCHEMA = { 'type': 'object', 'properties': { 'connector_id': {'type': 'string'}, 'extra': {'type': ['object', 'null']}, 'node_uuid': {'type': 'string'}, 'type': {'type': 'string'}, 'uuid': {'type': ['string', 'null']}, }, 'required': ['connector_id', 'node_uuid', 'type'], 'additionalProperties': False, } CONNECTOR_VALIDATOR_EXTRA = args.dict_valid( node_uuid=args.uuid, uuid=args.uuid, ) CONNECTOR_VALIDATOR = args.and_valid( args.schema(CONNECTOR_SCHEMA), CONNECTOR_VALIDATOR_EXTRA ) PATCH_ALLOWED_FIELDS = [ 'connector_id', 'extra', 'node_uuid', 'type' ] def convert_with_links(rpc_connector, fields=None, sanitize=True): connector = api_utils.object_to_dict( rpc_connector, link_resource='volume/connectors', fields=('connector_id', 'extra', 'type') ) api_utils.populate_node_uuid(rpc_connector, connector) if fields is not None: api_utils.check_for_invalid_fields(fields, connector) if not sanitize: return connector api_utils.sanitize_dict(connector, fields) return connector def list_convert_with_links(rpc_connectors, limit, url=None, fields=None, detail=None, **kwargs): if detail: kwargs['detail'] = detail return collection.list_convert_with_links( items=[convert_with_links(p, fields=fields, sanitize=False) for p in rpc_connectors], item_name='connectors', limit=limit, url=url, fields=fields, sanitize_func=api_utils.sanitize_dict, **kwargs ) class VolumeConnectorsController(rest.RestController): """REST controller for VolumeConnectors.""" invalid_sort_key_list = ['extra'] def __init__(self, node_ident=None): super(VolumeConnectorsController, self).__init__() self.parent_node_ident = node_ident def _get_volume_connectors_collection(self, node_ident, marker, limit, sort_key, sort_dir, resource_url=None, fields=None, detail=None): limit = api_utils.validate_limit(limit) sort_dir = api_utils.validate_sort_dir(sort_dir) marker_obj = None if marker: marker_obj = objects.VolumeConnector.get_by_uuid( api.request.context, marker) if sort_key in self.invalid_sort_key_list: raise exception.InvalidParameterValue( _("The sort_key value %(key)s is an invalid field for " "sorting") % {'key': sort_key}) node_ident = self.parent_node_ident or node_ident if node_ident: # FIXME(comstud): Since all we need is the node ID, we can # make this more efficient by only querying # for that column. This will get cleaned up # as we move to the object interface. node = api_utils.get_rpc_node(node_ident) connectors = objects.VolumeConnector.list_by_node_id( api.request.context, node.id, limit, marker_obj, sort_key=sort_key, sort_dir=sort_dir) else: connectors = objects.VolumeConnector.list(api.request.context, limit, marker_obj, sort_key=sort_key, sort_dir=sort_dir) return list_convert_with_links(connectors, limit, url=resource_url, fields=fields, sort_key=sort_key, sort_dir=sort_dir, detail=detail) @METRICS.timer('VolumeConnectorsController.get_all') @method.expose() @args.validate(node=args.uuid_or_name, marker=args.uuid, limit=args.integer, sort_key=args.string, sort_dir=args.string, fields=args.string_list, detail=args.boolean) def get_all(self, node=None, marker=None, limit=None, sort_key='id', sort_dir='asc', fields=None, detail=None): """Retrieve a list of volume connectors. :param node: UUID or name of a node, to get only volume connectors for that node. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. This value cannot be larger than the value of max_limit in the [api] section of the ironic configuration, or only max_limit resources will be returned. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: "asc". :param fields: Optional, a list with a specified set of fields of the resource to be returned. :param detail: Optional, whether to retrieve with detail. :returns: a list of volume connectors, or an empty list if no volume connector is found. :raises: InvalidParameterValue if sort_key does not exist :raises: InvalidParameterValue if sort key is invalid for sorting. :raises: InvalidParameterValue if both fields and detail are specified. """ api_utils.check_policy('baremetal:volume:get') if fields is None and not detail: fields = _DEFAULT_RETURN_FIELDS if fields and detail: raise exception.InvalidParameterValue( _("Can't fetch a subset of fields with 'detail' set")) resource_url = 'volume/connectors' return self._get_volume_connectors_collection( node, marker, limit, sort_key, sort_dir, resource_url=resource_url, fields=fields, detail=detail) @METRICS.timer('VolumeConnectorsController.get_one') @method.expose() @args.validate(connector_uuid=args.uuid, fields=args.string_list) def get_one(self, connector_uuid, fields=None): """Retrieve information about the given volume connector. :param connector_uuid: UUID of a volume connector. :param fields: Optional, a list with a specified set of fields of the resource to be returned. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: VolumeConnectorNotFound if no volume connector exists with the specified UUID. """ api_utils.check_policy('baremetal:volume:get') if self.parent_node_ident: raise exception.OperationNotPermitted() rpc_connector = objects.VolumeConnector.get_by_uuid( api.request.context, connector_uuid) return convert_with_links(rpc_connector, fields=fields) @METRICS.timer('VolumeConnectorsController.post') @method.expose(status_code=http_client.CREATED) @method.body('connector') @args.validate(connector=CONNECTOR_VALIDATOR) def post(self, connector): """Create a new volume connector. :param connector: a volume connector within the request body. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: VolumeConnectorTypeAndIdAlreadyExists if a volume connector already exists with the same type and connector_id :raises: VolumeConnectorAlreadyExists if a volume connector with the same UUID already exists """ context = api.request.context api_utils.check_policy('baremetal:volume:create') if self.parent_node_ident: raise exception.OperationNotPermitted() # NOTE(hshiina): UUID is mandatory for notification payload if not connector.get('uuid'): connector['uuid'] = uuidutils.generate_uuid() node = api_utils.replace_node_uuid_with_id(connector) new_connector = objects.VolumeConnector(context, **connector) notify.emit_start_notification(context, new_connector, 'create', node_uuid=node.uuid) with notify.handle_error_notification(context, new_connector, 'create', node_uuid=node.uuid): new_connector.create() notify.emit_end_notification(context, new_connector, 'create', node_uuid=node.uuid) # Set the HTTP Location Header api.response.location = link.build_url('volume/connectors', new_connector.uuid) return convert_with_links(new_connector) @METRICS.timer('VolumeConnectorsController.patch') @method.expose() @method.body('patch') @args.validate(connector_uuid=args.uuid, patch=args.patch) def patch(self, connector_uuid, patch): """Update an existing volume connector. :param connector_uuid: UUID of a volume connector. :param patch: a json PATCH document to apply to this volume connector. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: PatchError if a given patch can not be applied. :raises: VolumeConnectorNotFound if no volume connector exists with the specified UUID. :raises: InvalidParameterValue if the volume connector's UUID is being changed :raises: NodeLocked if node is locked by another conductor :raises: NodeNotFound if the node associated with the connector does not exist :raises: VolumeConnectorTypeAndIdAlreadyExists if another connector already exists with the same values for type and connector_id fields :raises: InvalidUUID if invalid node UUID is passed in the patch. :raises: InvalidStateRequested If a node associated with the volume connector is not powered off. """ context = api.request.context api_utils.check_policy('baremetal:volume:update') if self.parent_node_ident: raise exception.OperationNotPermitted() api_utils.patch_validate_allowed_fields(patch, PATCH_ALLOWED_FIELDS) for value in api_utils.get_patch_values(patch, '/node_uuid'): if not uuidutils.is_uuid_like(value): message = _("Expected a UUID for node_uuid, but received " "%(uuid)s.") % {'uuid': str(value)} raise exception.InvalidUUID(message=message) rpc_connector = objects.VolumeConnector.get_by_uuid(context, connector_uuid) connector_dict = rpc_connector.as_dict() # NOTE(smoriya): # 1) Remove node_id because it's an internal value and # not present in the API object # 2) Add node_uuid rpc_node = api_utils.replace_node_id_with_uuid(connector_dict) connector_dict = api_utils.apply_jsonpatch(connector_dict, patch) try: if connector_dict['node_uuid'] != rpc_node.uuid: rpc_node = objects.Node.get( api.request.context, connector_dict['node_uuid']) except exception.NodeNotFound as e: # Change error code because 404 (NotFound) is inappropriate # response for a PATCH request to change a Port e.code = http_client.BAD_REQUEST # BadRequest raise api_utils.patched_validate_with_schema( connector_dict, CONNECTOR_SCHEMA, CONNECTOR_VALIDATOR) api_utils.patch_update_changed_fields( connector_dict, rpc_connector, fields=objects.VolumeConnector.fields, schema=CONNECTOR_SCHEMA, id_map={'node_id': rpc_node.id} ) notify.emit_start_notification(context, rpc_connector, 'update', node_uuid=rpc_node.uuid) with notify.handle_error_notification(context, rpc_connector, 'update', node_uuid=rpc_node.uuid): topic = api.request.rpcapi.get_topic_for(rpc_node) new_connector = api.request.rpcapi.update_volume_connector( context, rpc_connector, topic) api_connector = convert_with_links(new_connector) notify.emit_end_notification(context, new_connector, 'update', node_uuid=rpc_node.uuid) return api_connector @METRICS.timer('VolumeConnectorsController.delete') @method.expose(status_code=http_client.NO_CONTENT) @args.validate(connector_uuid=args.uuid) def delete(self, connector_uuid): """Delete a volume connector. :param connector_uuid: UUID of a volume connector. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: NodeLocked if node is locked by another conductor :raises: NodeNotFound if the node associated with the connector does not exist :raises: VolumeConnectorNotFound if the volume connector cannot be found :raises: InvalidStateRequested If a node associated with the volume connector is not powered off. """ context = api.request.context api_utils.check_policy('baremetal:volume:delete') if self.parent_node_ident: raise exception.OperationNotPermitted() rpc_connector = objects.VolumeConnector.get_by_uuid(context, connector_uuid) rpc_node = objects.Node.get_by_id(context, rpc_connector.node_id) notify.emit_start_notification(context, rpc_connector, 'delete', node_uuid=rpc_node.uuid) with notify.handle_error_notification(context, rpc_connector, 'delete', node_uuid=rpc_node.uuid): topic = api.request.rpcapi.get_topic_for(rpc_node) api.request.rpcapi.destroy_volume_connector(context, rpc_connector, topic) notify.emit_end_notification(context, rpc_connector, 'delete', node_uuid=rpc_node.uuid)
en
0.749382
# Copyright (c) 2017 Hitachi, Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. REST controller for VolumeConnectors. # FIXME(comstud): Since all we need is the node ID, we can # make this more efficient by only querying # for that column. This will get cleaned up # as we move to the object interface. Retrieve a list of volume connectors. :param node: UUID or name of a node, to get only volume connectors for that node. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. This value cannot be larger than the value of max_limit in the [api] section of the ironic configuration, or only max_limit resources will be returned. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: "asc". :param fields: Optional, a list with a specified set of fields of the resource to be returned. :param detail: Optional, whether to retrieve with detail. :returns: a list of volume connectors, or an empty list if no volume connector is found. :raises: InvalidParameterValue if sort_key does not exist :raises: InvalidParameterValue if sort key is invalid for sorting. :raises: InvalidParameterValue if both fields and detail are specified. Retrieve information about the given volume connector. :param connector_uuid: UUID of a volume connector. :param fields: Optional, a list with a specified set of fields of the resource to be returned. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: VolumeConnectorNotFound if no volume connector exists with the specified UUID. Create a new volume connector. :param connector: a volume connector within the request body. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: VolumeConnectorTypeAndIdAlreadyExists if a volume connector already exists with the same type and connector_id :raises: VolumeConnectorAlreadyExists if a volume connector with the same UUID already exists # NOTE(hshiina): UUID is mandatory for notification payload # Set the HTTP Location Header Update an existing volume connector. :param connector_uuid: UUID of a volume connector. :param patch: a json PATCH document to apply to this volume connector. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: PatchError if a given patch can not be applied. :raises: VolumeConnectorNotFound if no volume connector exists with the specified UUID. :raises: InvalidParameterValue if the volume connector's UUID is being changed :raises: NodeLocked if node is locked by another conductor :raises: NodeNotFound if the node associated with the connector does not exist :raises: VolumeConnectorTypeAndIdAlreadyExists if another connector already exists with the same values for type and connector_id fields :raises: InvalidUUID if invalid node UUID is passed in the patch. :raises: InvalidStateRequested If a node associated with the volume connector is not powered off. # NOTE(smoriya): # 1) Remove node_id because it's an internal value and # not present in the API object # 2) Add node_uuid # Change error code because 404 (NotFound) is inappropriate # response for a PATCH request to change a Port # BadRequest Delete a volume connector. :param connector_uuid: UUID of a volume connector. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: NodeLocked if node is locked by another conductor :raises: NodeNotFound if the node associated with the connector does not exist :raises: VolumeConnectorNotFound if the volume connector cannot be found :raises: InvalidStateRequested If a node associated with the volume connector is not powered off.
1.70926
2
examples/frompapers/Rothman_Manis_2003.py
awillats/brian2
674
6625124
#!/usr/bin/env python """ Cochlear neuron model of Rothman & Manis ---------------------------------------- <NAME>, <NAME> (2003) The roles potassium currents play in regulating the electrical activity of ventral cochlear nucleus neurons. J Neurophysiol 89:3097-113. All model types differ only by the maximal conductances. Adapted from their Neuron implementation by <NAME> """ from brian2 import * #defaultclock.dt=0.025*ms # for better precision ''' Simulation parameters: choose current amplitude and neuron type (from type1c, type1t, type12, type 21, type2, type2o) ''' neuron_type = 'type1c' Ipulse = 250*pA C = 12*pF Eh = -43*mV EK = -70*mV # -77*mV in mod file El = -65*mV ENa = 50*mV nf = 0.85 # proportion of n vs p kinetics zss = 0.5 # steady state inactivation of glt temp = 22. # temperature in degree celcius q10 = 3. ** ((temp - 22) / 10.) # hcno current (octopus cell) frac = 0.0 qt = 4.5 ** ((temp - 33.) / 10.) # Maximal conductances of different cell types in nS maximal_conductances = dict( type1c=(1000, 150, 0, 0, 0.5, 0, 2), type1t=(1000, 80, 0, 65, 0.5, 0, 2), type12=(1000, 150, 20, 0, 2, 0, 2), type21=(1000, 150, 35, 0, 3.5, 0, 2), type2=(1000, 150, 200, 0, 20, 0, 2), type2o=(1000, 150, 600, 0, 0, 40, 2) # octopus cell ) gnabar, gkhtbar, gkltbar, gkabar, ghbar, gbarno, gl = [x * nS for x in maximal_conductances[neuron_type]] # Classical Na channel eqs_na = """ ina = gnabar*m**3*h*(ENa-v) : amp dm/dt=q10*(minf-m)/mtau : 1 dh/dt=q10*(hinf-h)/htau : 1 minf = 1./(1+exp(-(vu + 38.) / 7.)) : 1 hinf = 1./(1+exp((vu + 65.) / 6.)) : 1 mtau = ((10. / (5*exp((vu+60.) / 18.) + 36.*exp(-(vu+60.) / 25.))) + 0.04)*ms : second htau = ((100. / (7*exp((vu+60.) / 11.) + 10.*exp(-(vu+60.) / 25.))) + 0.6)*ms : second """ # KHT channel (delayed-rectifier K+) eqs_kht = """ ikht = gkhtbar*(nf*n**2 + (1-nf)*p)*(EK-v) : amp dn/dt=q10*(ninf-n)/ntau : 1 dp/dt=q10*(pinf-p)/ptau : 1 ninf = (1 + exp(-(vu + 15) / 5.))**-0.5 : 1 pinf = 1. / (1 + exp(-(vu + 23) / 6.)) : 1 ntau = ((100. / (11*exp((vu+60) / 24.) + 21*exp(-(vu+60) / 23.))) + 0.7)*ms : second ptau = ((100. / (4*exp((vu+60) / 32.) + 5*exp(-(vu+60) / 22.))) + 5)*ms : second """ # Ih channel (subthreshold adaptive, non-inactivating) eqs_ih = """ ih = ghbar*r*(Eh-v) : amp dr/dt=q10*(rinf-r)/rtau : 1 rinf = 1. / (1+exp((vu + 76.) / 7.)) : 1 rtau = ((100000. / (237.*exp((vu+60.) / 12.) + 17.*exp(-(vu+60.) / 14.))) + 25.)*ms : second """ # KLT channel (low threshold K+) eqs_klt = """ iklt = gkltbar*w**4*z*(EK-v) : amp dw/dt=q10*(winf-w)/wtau : 1 dz/dt=q10*(zinf-z)/ztau : 1 winf = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25 : 1 zinf = zss + ((1.-zss) / (1 + exp((vu + 71.) / 10.))) : 1 wtau = ((100. / (6.*exp((vu+60.) / 6.) + 16.*exp(-(vu+60.) / 45.))) + 1.5)*ms : second ztau = ((1000. / (exp((vu+60.) / 20.) + exp(-(vu+60.) / 8.))) + 50)*ms : second """ # Ka channel (transient K+) eqs_ka = """ ika = gkabar*a**4*b*c*(EK-v): amp da/dt=q10*(ainf-a)/atau : 1 db/dt=q10*(binf-b)/btau : 1 dc/dt=q10*(cinf-c)/ctau : 1 ainf = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25 : 1 binf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1 cinf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1 atau = ((100. / (7*exp((vu+60) / 14.) + 29*exp(-(vu+60) / 24.))) + 0.1)*ms : second btau = ((1000. / (14*exp((vu+60) / 27.) + 29*exp(-(vu+60) / 24.))) + 1)*ms : second ctau = ((90. / (1 + exp((-66-vu) / 17.))) + 10)*ms : second """ # Leak eqs_leak = """ ileak = gl*(El-v) : amp """ # h current for octopus cells eqs_hcno = """ ihcno = gbarno*(h1*frac + h2*(1-frac))*(Eh-v) : amp dh1/dt=(hinfno-h1)/tau1 : 1 dh2/dt=(hinfno-h2)/tau2 : 1 hinfno = 1./(1+exp((vu+66.)/7.)) : 1 tau1 = bet1/(qt*0.008*(1+alp1))*ms : second tau2 = bet2/(qt*0.0029*(1+alp2))*ms : second alp1 = exp(1e-3*3*(vu+50)*9.648e4/(8.315*(273.16+temp))) : 1 bet1 = exp(1e-3*3*0.3*(vu+50)*9.648e4/(8.315*(273.16+temp))) : 1 alp2 = exp(1e-3*3*(vu+84)*9.648e4/(8.315*(273.16+temp))) : 1 bet2 = exp(1e-3*3*0.6*(vu+84)*9.648e4/(8.315*(273.16+temp))) : 1 """ eqs = """ dv/dt = (ileak + ina + ikht + iklt + ika + ih + ihcno + I)/C : volt vu = v/mV : 1 # unitless v I : amp """ eqs += eqs_leak + eqs_ka + eqs_na + eqs_ih + eqs_klt + eqs_kht + eqs_hcno neuron = NeuronGroup(1, eqs, method='exponential_euler') neuron.v = El run(50*ms, report='text') # Go to rest M = StateMonitor(neuron, 'v', record=0) neuron.I = Ipulse run(100*ms, report='text') plot(M.t / ms, M[0].v / mV) xlabel('t (ms)') ylabel('v (mV)') show()
#!/usr/bin/env python """ Cochlear neuron model of Rothman & Manis ---------------------------------------- <NAME>, <NAME> (2003) The roles potassium currents play in regulating the electrical activity of ventral cochlear nucleus neurons. J Neurophysiol 89:3097-113. All model types differ only by the maximal conductances. Adapted from their Neuron implementation by <NAME> """ from brian2 import * #defaultclock.dt=0.025*ms # for better precision ''' Simulation parameters: choose current amplitude and neuron type (from type1c, type1t, type12, type 21, type2, type2o) ''' neuron_type = 'type1c' Ipulse = 250*pA C = 12*pF Eh = -43*mV EK = -70*mV # -77*mV in mod file El = -65*mV ENa = 50*mV nf = 0.85 # proportion of n vs p kinetics zss = 0.5 # steady state inactivation of glt temp = 22. # temperature in degree celcius q10 = 3. ** ((temp - 22) / 10.) # hcno current (octopus cell) frac = 0.0 qt = 4.5 ** ((temp - 33.) / 10.) # Maximal conductances of different cell types in nS maximal_conductances = dict( type1c=(1000, 150, 0, 0, 0.5, 0, 2), type1t=(1000, 80, 0, 65, 0.5, 0, 2), type12=(1000, 150, 20, 0, 2, 0, 2), type21=(1000, 150, 35, 0, 3.5, 0, 2), type2=(1000, 150, 200, 0, 20, 0, 2), type2o=(1000, 150, 600, 0, 0, 40, 2) # octopus cell ) gnabar, gkhtbar, gkltbar, gkabar, ghbar, gbarno, gl = [x * nS for x in maximal_conductances[neuron_type]] # Classical Na channel eqs_na = """ ina = gnabar*m**3*h*(ENa-v) : amp dm/dt=q10*(minf-m)/mtau : 1 dh/dt=q10*(hinf-h)/htau : 1 minf = 1./(1+exp(-(vu + 38.) / 7.)) : 1 hinf = 1./(1+exp((vu + 65.) / 6.)) : 1 mtau = ((10. / (5*exp((vu+60.) / 18.) + 36.*exp(-(vu+60.) / 25.))) + 0.04)*ms : second htau = ((100. / (7*exp((vu+60.) / 11.) + 10.*exp(-(vu+60.) / 25.))) + 0.6)*ms : second """ # KHT channel (delayed-rectifier K+) eqs_kht = """ ikht = gkhtbar*(nf*n**2 + (1-nf)*p)*(EK-v) : amp dn/dt=q10*(ninf-n)/ntau : 1 dp/dt=q10*(pinf-p)/ptau : 1 ninf = (1 + exp(-(vu + 15) / 5.))**-0.5 : 1 pinf = 1. / (1 + exp(-(vu + 23) / 6.)) : 1 ntau = ((100. / (11*exp((vu+60) / 24.) + 21*exp(-(vu+60) / 23.))) + 0.7)*ms : second ptau = ((100. / (4*exp((vu+60) / 32.) + 5*exp(-(vu+60) / 22.))) + 5)*ms : second """ # Ih channel (subthreshold adaptive, non-inactivating) eqs_ih = """ ih = ghbar*r*(Eh-v) : amp dr/dt=q10*(rinf-r)/rtau : 1 rinf = 1. / (1+exp((vu + 76.) / 7.)) : 1 rtau = ((100000. / (237.*exp((vu+60.) / 12.) + 17.*exp(-(vu+60.) / 14.))) + 25.)*ms : second """ # KLT channel (low threshold K+) eqs_klt = """ iklt = gkltbar*w**4*z*(EK-v) : amp dw/dt=q10*(winf-w)/wtau : 1 dz/dt=q10*(zinf-z)/ztau : 1 winf = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25 : 1 zinf = zss + ((1.-zss) / (1 + exp((vu + 71.) / 10.))) : 1 wtau = ((100. / (6.*exp((vu+60.) / 6.) + 16.*exp(-(vu+60.) / 45.))) + 1.5)*ms : second ztau = ((1000. / (exp((vu+60.) / 20.) + exp(-(vu+60.) / 8.))) + 50)*ms : second """ # Ka channel (transient K+) eqs_ka = """ ika = gkabar*a**4*b*c*(EK-v): amp da/dt=q10*(ainf-a)/atau : 1 db/dt=q10*(binf-b)/btau : 1 dc/dt=q10*(cinf-c)/ctau : 1 ainf = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25 : 1 binf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1 cinf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1 atau = ((100. / (7*exp((vu+60) / 14.) + 29*exp(-(vu+60) / 24.))) + 0.1)*ms : second btau = ((1000. / (14*exp((vu+60) / 27.) + 29*exp(-(vu+60) / 24.))) + 1)*ms : second ctau = ((90. / (1 + exp((-66-vu) / 17.))) + 10)*ms : second """ # Leak eqs_leak = """ ileak = gl*(El-v) : amp """ # h current for octopus cells eqs_hcno = """ ihcno = gbarno*(h1*frac + h2*(1-frac))*(Eh-v) : amp dh1/dt=(hinfno-h1)/tau1 : 1 dh2/dt=(hinfno-h2)/tau2 : 1 hinfno = 1./(1+exp((vu+66.)/7.)) : 1 tau1 = bet1/(qt*0.008*(1+alp1))*ms : second tau2 = bet2/(qt*0.0029*(1+alp2))*ms : second alp1 = exp(1e-3*3*(vu+50)*9.648e4/(8.315*(273.16+temp))) : 1 bet1 = exp(1e-3*3*0.3*(vu+50)*9.648e4/(8.315*(273.16+temp))) : 1 alp2 = exp(1e-3*3*(vu+84)*9.648e4/(8.315*(273.16+temp))) : 1 bet2 = exp(1e-3*3*0.6*(vu+84)*9.648e4/(8.315*(273.16+temp))) : 1 """ eqs = """ dv/dt = (ileak + ina + ikht + iklt + ika + ih + ihcno + I)/C : volt vu = v/mV : 1 # unitless v I : amp """ eqs += eqs_leak + eqs_ka + eqs_na + eqs_ih + eqs_klt + eqs_kht + eqs_hcno neuron = NeuronGroup(1, eqs, method='exponential_euler') neuron.v = El run(50*ms, report='text') # Go to rest M = StateMonitor(neuron, 'v', record=0) neuron.I = Ipulse run(100*ms, report='text') plot(M.t / ms, M[0].v / mV) xlabel('t (ms)') ylabel('v (mV)') show()
en
0.26286
#!/usr/bin/env python Cochlear neuron model of Rothman & Manis ---------------------------------------- <NAME>, <NAME> (2003) The roles potassium currents play in regulating the electrical activity of ventral cochlear nucleus neurons. J Neurophysiol 89:3097-113. All model types differ only by the maximal conductances. Adapted from their Neuron implementation by <NAME> #defaultclock.dt=0.025*ms # for better precision Simulation parameters: choose current amplitude and neuron type (from type1c, type1t, type12, type 21, type2, type2o) # -77*mV in mod file # proportion of n vs p kinetics # steady state inactivation of glt # temperature in degree celcius # hcno current (octopus cell) # Maximal conductances of different cell types in nS # octopus cell # Classical Na channel ina = gnabar*m**3*h*(ENa-v) : amp dm/dt=q10*(minf-m)/mtau : 1 dh/dt=q10*(hinf-h)/htau : 1 minf = 1./(1+exp(-(vu + 38.) / 7.)) : 1 hinf = 1./(1+exp((vu + 65.) / 6.)) : 1 mtau = ((10. / (5*exp((vu+60.) / 18.) + 36.*exp(-(vu+60.) / 25.))) + 0.04)*ms : second htau = ((100. / (7*exp((vu+60.) / 11.) + 10.*exp(-(vu+60.) / 25.))) + 0.6)*ms : second # KHT channel (delayed-rectifier K+) ikht = gkhtbar*(nf*n**2 + (1-nf)*p)*(EK-v) : amp dn/dt=q10*(ninf-n)/ntau : 1 dp/dt=q10*(pinf-p)/ptau : 1 ninf = (1 + exp(-(vu + 15) / 5.))**-0.5 : 1 pinf = 1. / (1 + exp(-(vu + 23) / 6.)) : 1 ntau = ((100. / (11*exp((vu+60) / 24.) + 21*exp(-(vu+60) / 23.))) + 0.7)*ms : second ptau = ((100. / (4*exp((vu+60) / 32.) + 5*exp(-(vu+60) / 22.))) + 5)*ms : second # Ih channel (subthreshold adaptive, non-inactivating) ih = ghbar*r*(Eh-v) : amp dr/dt=q10*(rinf-r)/rtau : 1 rinf = 1. / (1+exp((vu + 76.) / 7.)) : 1 rtau = ((100000. / (237.*exp((vu+60.) / 12.) + 17.*exp(-(vu+60.) / 14.))) + 25.)*ms : second # KLT channel (low threshold K+) iklt = gkltbar*w**4*z*(EK-v) : amp dw/dt=q10*(winf-w)/wtau : 1 dz/dt=q10*(zinf-z)/ztau : 1 winf = (1. / (1 + exp(-(vu + 48.) / 6.)))**0.25 : 1 zinf = zss + ((1.-zss) / (1 + exp((vu + 71.) / 10.))) : 1 wtau = ((100. / (6.*exp((vu+60.) / 6.) + 16.*exp(-(vu+60.) / 45.))) + 1.5)*ms : second ztau = ((1000. / (exp((vu+60.) / 20.) + exp(-(vu+60.) / 8.))) + 50)*ms : second # Ka channel (transient K+) ika = gkabar*a**4*b*c*(EK-v): amp da/dt=q10*(ainf-a)/atau : 1 db/dt=q10*(binf-b)/btau : 1 dc/dt=q10*(cinf-c)/ctau : 1 ainf = (1. / (1 + exp(-(vu + 31) / 6.)))**0.25 : 1 binf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1 cinf = 1. / (1 + exp((vu + 66) / 7.))**0.5 : 1 atau = ((100. / (7*exp((vu+60) / 14.) + 29*exp(-(vu+60) / 24.))) + 0.1)*ms : second btau = ((1000. / (14*exp((vu+60) / 27.) + 29*exp(-(vu+60) / 24.))) + 1)*ms : second ctau = ((90. / (1 + exp((-66-vu) / 17.))) + 10)*ms : second # Leak ileak = gl*(El-v) : amp # h current for octopus cells ihcno = gbarno*(h1*frac + h2*(1-frac))*(Eh-v) : amp dh1/dt=(hinfno-h1)/tau1 : 1 dh2/dt=(hinfno-h2)/tau2 : 1 hinfno = 1./(1+exp((vu+66.)/7.)) : 1 tau1 = bet1/(qt*0.008*(1+alp1))*ms : second tau2 = bet2/(qt*0.0029*(1+alp2))*ms : second alp1 = exp(1e-3*3*(vu+50)*9.648e4/(8.315*(273.16+temp))) : 1 bet1 = exp(1e-3*3*0.3*(vu+50)*9.648e4/(8.315*(273.16+temp))) : 1 alp2 = exp(1e-3*3*(vu+84)*9.648e4/(8.315*(273.16+temp))) : 1 bet2 = exp(1e-3*3*0.6*(vu+84)*9.648e4/(8.315*(273.16+temp))) : 1 dv/dt = (ileak + ina + ikht + iklt + ika + ih + ihcno + I)/C : volt vu = v/mV : 1 # unitless v I : amp # Go to rest
2.783093
3
cinder/image/accelerator.py
cloudification-io/cinder
8
6625125
<reponame>cloudification-io/cinder # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc from oslo_config import cfg from oslo_utils import importutils from cinder import exception from cinder.i18n import _ CONF = cfg.CONF # NOTE(ZhengMa): The order of the option is improtant, accelerators # are looked by this list order # Be careful to edit it _ACCEL_PATH_PREFERENCE_ORDER_LIST = [ 'cinder.image.accelerators.qat.AccelQAT', 'cinder.image.accelerators.gzip.AccelGZIP', ] class AccelBase(object, metaclass=abc.ABCMeta): def __init__(self): return @abc.abstractmethod def is_accel_exist(self): return @abc.abstractmethod def compress_img(self, run_as_root): return @abc.abstractmethod def decompress_img(self, run_as_root): return class ImageAccel(object): def __init__(self, src, dest): self.src = src self.dest = dest self.compression_format = CONF.compression_format if(self.compression_format == 'gzip'): self._accel_engine_path = _ACCEL_PATH_PREFERENCE_ORDER_LIST else: self._accel_engine_path = None self.engine = self._get_engine() def _get_engine(self, *args, **kwargs): if self._accel_engine_path: for accel in self._accel_engine_path: engine_cls = importutils.import_class(accel) eng = engine_cls(*args, **kwargs) if eng.is_accel_exist(): return eng ex_msg = _("No valid accelerator") raise exception.CinderException(ex_msg) def is_engine_ready(self): if not self.engine: return False if not self.engine.is_accel_exist(): return False return True def compress_img(self, run_as_root): if not self.is_engine_ready(): return self.engine.compress_img(self.src, self.dest, run_as_root) def decompress_img(self, run_as_root): if not self.is_engine_ready(): return self.engine.decompress_img(self.src, self.dest, run_as_root) def is_gzip_compressed(image_file): # The first two bytes of a gzip file are: 1f 8b GZIP_MAGIC_BYTES = b'\x1f\x8b' with open(image_file, 'rb') as f: return f.read(2) == GZIP_MAGIC_BYTES
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc from oslo_config import cfg from oslo_utils import importutils from cinder import exception from cinder.i18n import _ CONF = cfg.CONF # NOTE(ZhengMa): The order of the option is improtant, accelerators # are looked by this list order # Be careful to edit it _ACCEL_PATH_PREFERENCE_ORDER_LIST = [ 'cinder.image.accelerators.qat.AccelQAT', 'cinder.image.accelerators.gzip.AccelGZIP', ] class AccelBase(object, metaclass=abc.ABCMeta): def __init__(self): return @abc.abstractmethod def is_accel_exist(self): return @abc.abstractmethod def compress_img(self, run_as_root): return @abc.abstractmethod def decompress_img(self, run_as_root): return class ImageAccel(object): def __init__(self, src, dest): self.src = src self.dest = dest self.compression_format = CONF.compression_format if(self.compression_format == 'gzip'): self._accel_engine_path = _ACCEL_PATH_PREFERENCE_ORDER_LIST else: self._accel_engine_path = None self.engine = self._get_engine() def _get_engine(self, *args, **kwargs): if self._accel_engine_path: for accel in self._accel_engine_path: engine_cls = importutils.import_class(accel) eng = engine_cls(*args, **kwargs) if eng.is_accel_exist(): return eng ex_msg = _("No valid accelerator") raise exception.CinderException(ex_msg) def is_engine_ready(self): if not self.engine: return False if not self.engine.is_accel_exist(): return False return True def compress_img(self, run_as_root): if not self.is_engine_ready(): return self.engine.compress_img(self.src, self.dest, run_as_root) def decompress_img(self, run_as_root): if not self.is_engine_ready(): return self.engine.decompress_img(self.src, self.dest, run_as_root) def is_gzip_compressed(image_file): # The first two bytes of a gzip file are: 1f 8b GZIP_MAGIC_BYTES = b'\x1f\x8b' with open(image_file, 'rb') as f: return f.read(2) == GZIP_MAGIC_BYTES
en
0.876763
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # NOTE(ZhengMa): The order of the option is improtant, accelerators # are looked by this list order # Be careful to edit it # The first two bytes of a gzip file are: 1f 8b
2.008881
2
src/kmeans_all/kmeans_training.py
tapojyotipaul/xgboost-benchmarks
0
6625126
<reponame>tapojyotipaul/xgboost-benchmarks from timeit import default_timer as timer import xgboost as xgb from sklearn.metrics import mean_squared_error import daal4py as d4p import numpy as np import pandas as pd from sklearn.cluster import KMeans import common kmeans_kwargs = { "init": "random", "n_init": 10, "max_iter": 100, "random_state": 42, } NUM_LOOPS = 100 print("Computing for KMeans Clustering Training without Daal") cluster = KMeans(n_clusters=5, **kmeans_kwargs) cluster.fit(common.X_dfc) def run_inference(num_observations:int = 1000): """Run xgboost for specified number of observations""" # Load data test_df = common.get_test_data_df(X=common.X_dfc,size = num_observations) num_rows = len(test_df) ###################### print("_______________________________________") print("Total Number of Rows", num_rows) run_times = [] inference_times = [] for _ in range(NUM_LOOPS): start_time = timer() cluster = KMeans(n_clusters=5, **kmeans_kwargs) cluster.fit(test_df) end_time = timer() total_time = end_time - start_time run_times.append(total_time*10e3) inference_time = total_time*(10e6)/num_rows inference_times.append(inference_time) return_elem = common.calculate_stats(inference_times) print(num_observations, ", ", return_elem) return return_elem
from timeit import default_timer as timer import xgboost as xgb from sklearn.metrics import mean_squared_error import daal4py as d4p import numpy as np import pandas as pd from sklearn.cluster import KMeans import common kmeans_kwargs = { "init": "random", "n_init": 10, "max_iter": 100, "random_state": 42, } NUM_LOOPS = 100 print("Computing for KMeans Clustering Training without Daal") cluster = KMeans(n_clusters=5, **kmeans_kwargs) cluster.fit(common.X_dfc) def run_inference(num_observations:int = 1000): """Run xgboost for specified number of observations""" # Load data test_df = common.get_test_data_df(X=common.X_dfc,size = num_observations) num_rows = len(test_df) ###################### print("_______________________________________") print("Total Number of Rows", num_rows) run_times = [] inference_times = [] for _ in range(NUM_LOOPS): start_time = timer() cluster = KMeans(n_clusters=5, **kmeans_kwargs) cluster.fit(test_df) end_time = timer() total_time = end_time - start_time run_times.append(total_time*10e3) inference_time = total_time*(10e6)/num_rows inference_times.append(inference_time) return_elem = common.calculate_stats(inference_times) print(num_observations, ", ", return_elem) return return_elem
de
0.182904
Run xgboost for specified number of observations # Load data ######################
2.923475
3
MOCVRP/POMO/MOCVRPEnv.py
Xi-L/PMOCO
0
6625127
from dataclasses import dataclass import torch from MOCVRProblemDef import get_random_problems, augment_xy_data_by_8_fold @dataclass class Reset_State: depot_xy: torch.Tensor = None node_xy: torch.Tensor = None node_demand: torch.Tensor = None # shape: (batch, problem) @dataclass class Step_State: BATCH_IDX: torch.Tensor = None POMO_IDX: torch.Tensor = None # shape: (batch, pomo) selected_count: int = None current_node: torch.Tensor = None # shape: (batch, pomo) ninf_mask: torch.Tensor = None # shape: (batch, pomo, problem+1) finished: torch.Tensor = None # shape: (batch, pomo) class CVRPEnv: def __init__(self, **env_params): # Const @INIT #################################### self.env_params = env_params self.problem_size = env_params['problem_size'] self.pomo_size = env_params['pomo_size'] # Const @Load_Problem #################################### self.batch_size = None self.BATCH_IDX = None self.POMO_IDX = None # IDX.shape: (batch, pomo) self.depot_node_xy = None # shape: (batch, problem+1, 2) self.depot_node_demand = None # shape: (batch, problem+1) # Dynamic-1 #################################### self.selected_count = None self.current_node = None # shape: (batch, pomo) self.selected_node_list = None # shape: (batch, pomo, 0~) # Dynamic-2 #################################### self.at_the_depot = None # shape: (batch, pomo) self.load = None # shape: (batch, pomo) self.visited_ninf_flag = None # shape: (batch, pomo, problem+1) self.ninf_mask = None # shape: (batch, pomo, problem+1) self.finished = None # shape: (batch, pomo) # states to return #################################### self.reset_state = Reset_State() self.step_state = Step_State() def load_problems(self, batch_size, aug_factor=1): self.batch_size = batch_size depot_xy, node_xy, node_demand = get_random_problems(batch_size, self.problem_size) if aug_factor > 1: if aug_factor == 8: self.batch_size = self.batch_size * 8 depot_xy = augment_xy_data_by_8_fold(depot_xy) node_xy = augment_xy_data_by_8_fold(node_xy) node_demand = node_demand.repeat(8, 1) else: raise NotImplementedError self.depot_node_xy = torch.cat((depot_xy, node_xy), dim=1) # shape: (batch, problem+1, 2) depot_demand = torch.zeros(size=(self.batch_size, 1)) # shape: (batch, 1) self.depot_node_demand = torch.cat((depot_demand, node_demand), dim=1) # shape: (batch, problem+1) self.BATCH_IDX = torch.arange(self.batch_size)[:, None].expand(self.batch_size, self.pomo_size) self.POMO_IDX = torch.arange(self.pomo_size)[None, :].expand(self.batch_size, self.pomo_size) self.reset_state.depot_xy = depot_xy self.reset_state.node_xy = node_xy self.reset_state.node_demand = node_demand self.step_state.BATCH_IDX = self.BATCH_IDX self.step_state.POMO_IDX = self.POMO_IDX def reset(self): self.selected_count = 0 self.current_node = None # shape: (batch, pomo) self.selected_node_list = torch.zeros((self.batch_size, self.pomo_size, 0), dtype=torch.long) # shape: (batch, pomo, 0~) self.at_the_depot = torch.ones(size=(self.batch_size, self.pomo_size), dtype=torch.bool) # shape: (batch, pomo) self.load = torch.ones(size=(self.batch_size, self.pomo_size)) # shape: (batch, pomo) self.visited_ninf_flag = torch.zeros(size=(self.batch_size, self.pomo_size, self.problem_size+1)) # shape: (batch, pomo, problem+1) self.ninf_mask = torch.zeros(size=(self.batch_size, self.pomo_size, self.problem_size+1)) # shape: (batch, pomo, problem+1) self.finished = torch.zeros(size=(self.batch_size, self.pomo_size), dtype=torch.bool) # shape: (batch, pomo) reward = None done = False return self.reset_state, reward, done def pre_step(self): self.step_state.selected_count = self.selected_count self.step_state.current_node = self.current_node self.step_state.ninf_mask = self.ninf_mask self.step_state.finished = self.finished reward = None done = False return self.step_state, reward, done def step(self, selected): # selected.shape: (batch, pomo) # Dynamic-1 #################################### self.selected_count += 1 self.current_node = selected # shape: (batch, pomo) self.selected_node_list = torch.cat((self.selected_node_list, self.current_node[:, :, None]), dim=2) # shape: (batch, pomo, 0~) # Dynamic-2 #################################### self.at_the_depot = (selected == 0) demand_list = self.depot_node_demand[:, None, :].expand(self.batch_size, self.pomo_size, -1) # shape: (batch, pomo, problem+1) gathering_index = selected[:, :, None] # shape: (batch, pomo, 1) selected_demand = demand_list.gather(dim=2, index=gathering_index).squeeze(dim=2) # shape: (batch, pomo) self.load -= selected_demand self.load[self.at_the_depot] = 1 # refill loaded at the depot self.visited_ninf_flag[self.BATCH_IDX, self.POMO_IDX, selected] = float('-inf') # shape: (batch, pomo, problem+1) self.visited_ninf_flag[:, :, 0][~self.at_the_depot] = 0 # depot is considered unvisited, unless you are AT the depot self.ninf_mask = self.visited_ninf_flag.clone() round_error_epsilon = 0.00001 demand_too_large = self.load[:, :, None] + round_error_epsilon < demand_list # shape: (batch, pomo, problem+1) self.ninf_mask[demand_too_large] = float('-inf') # shape: (batch, pomo, problem+1) newly_finished = (self.visited_ninf_flag == float('-inf')).all(dim=2) # shape: (batch, pomo) self.finished = self.finished + newly_finished # shape: (batch, pomo) # do not mask depot for finished episode. self.ninf_mask[:, :, 0][self.finished] = 0 self.step_state.selected_count = self.selected_count self.step_state.current_node = self.current_node self.step_state.ninf_mask = self.ninf_mask self.step_state.finished = self.finished # returning values done = self.finished.all() if done: reward = -self._get_travel_distance() # note the minus sign! else: reward = None return self.step_state, reward, done def _get_travel_distance(self): gathering_index = self.selected_node_list[:, :, :, None].expand(-1, -1, -1, 2) # shape: (batch, pomo, selected_list_length, 2) all_xy = self.depot_node_xy[:, None, :, :].expand(-1, self.pomo_size, -1, -1) # shape: (batch, pomo, problem+1, 2) # obj1: travel_distances ordered_seq = all_xy.gather(dim=2, index=gathering_index) # shape: (batch, pomo, selected_list_length, 2) rolled_seq = ordered_seq.roll(dims=2, shifts=-1) segment_lengths = ((ordered_seq-rolled_seq)**2).sum(3).sqrt() # shape: (batch, pomo, selected_list_length) travel_distances = segment_lengths.sum(2) # shape: (batch, pomo) # obj2: makespans not_idx = (gathering_index[:,:,:,0] > 0) cum_lengths = torch.cumsum(segment_lengths, dim = 2) cum_lengths[not_idx] = 0 sorted_cum_lengths, _ = cum_lengths.sort(axis = 2) rolled_sorted_cum_lengths = sorted_cum_lengths.roll(dims=2, shifts = 1) diff_mat = sorted_cum_lengths - rolled_sorted_cum_lengths diff_mat[diff_mat < 0] = 0 makespans, _ = torch.max(diff_mat,dim = 2) objs = torch.stack([travel_distances,makespans],axis = 2) return objs
from dataclasses import dataclass import torch from MOCVRProblemDef import get_random_problems, augment_xy_data_by_8_fold @dataclass class Reset_State: depot_xy: torch.Tensor = None node_xy: torch.Tensor = None node_demand: torch.Tensor = None # shape: (batch, problem) @dataclass class Step_State: BATCH_IDX: torch.Tensor = None POMO_IDX: torch.Tensor = None # shape: (batch, pomo) selected_count: int = None current_node: torch.Tensor = None # shape: (batch, pomo) ninf_mask: torch.Tensor = None # shape: (batch, pomo, problem+1) finished: torch.Tensor = None # shape: (batch, pomo) class CVRPEnv: def __init__(self, **env_params): # Const @INIT #################################### self.env_params = env_params self.problem_size = env_params['problem_size'] self.pomo_size = env_params['pomo_size'] # Const @Load_Problem #################################### self.batch_size = None self.BATCH_IDX = None self.POMO_IDX = None # IDX.shape: (batch, pomo) self.depot_node_xy = None # shape: (batch, problem+1, 2) self.depot_node_demand = None # shape: (batch, problem+1) # Dynamic-1 #################################### self.selected_count = None self.current_node = None # shape: (batch, pomo) self.selected_node_list = None # shape: (batch, pomo, 0~) # Dynamic-2 #################################### self.at_the_depot = None # shape: (batch, pomo) self.load = None # shape: (batch, pomo) self.visited_ninf_flag = None # shape: (batch, pomo, problem+1) self.ninf_mask = None # shape: (batch, pomo, problem+1) self.finished = None # shape: (batch, pomo) # states to return #################################### self.reset_state = Reset_State() self.step_state = Step_State() def load_problems(self, batch_size, aug_factor=1): self.batch_size = batch_size depot_xy, node_xy, node_demand = get_random_problems(batch_size, self.problem_size) if aug_factor > 1: if aug_factor == 8: self.batch_size = self.batch_size * 8 depot_xy = augment_xy_data_by_8_fold(depot_xy) node_xy = augment_xy_data_by_8_fold(node_xy) node_demand = node_demand.repeat(8, 1) else: raise NotImplementedError self.depot_node_xy = torch.cat((depot_xy, node_xy), dim=1) # shape: (batch, problem+1, 2) depot_demand = torch.zeros(size=(self.batch_size, 1)) # shape: (batch, 1) self.depot_node_demand = torch.cat((depot_demand, node_demand), dim=1) # shape: (batch, problem+1) self.BATCH_IDX = torch.arange(self.batch_size)[:, None].expand(self.batch_size, self.pomo_size) self.POMO_IDX = torch.arange(self.pomo_size)[None, :].expand(self.batch_size, self.pomo_size) self.reset_state.depot_xy = depot_xy self.reset_state.node_xy = node_xy self.reset_state.node_demand = node_demand self.step_state.BATCH_IDX = self.BATCH_IDX self.step_state.POMO_IDX = self.POMO_IDX def reset(self): self.selected_count = 0 self.current_node = None # shape: (batch, pomo) self.selected_node_list = torch.zeros((self.batch_size, self.pomo_size, 0), dtype=torch.long) # shape: (batch, pomo, 0~) self.at_the_depot = torch.ones(size=(self.batch_size, self.pomo_size), dtype=torch.bool) # shape: (batch, pomo) self.load = torch.ones(size=(self.batch_size, self.pomo_size)) # shape: (batch, pomo) self.visited_ninf_flag = torch.zeros(size=(self.batch_size, self.pomo_size, self.problem_size+1)) # shape: (batch, pomo, problem+1) self.ninf_mask = torch.zeros(size=(self.batch_size, self.pomo_size, self.problem_size+1)) # shape: (batch, pomo, problem+1) self.finished = torch.zeros(size=(self.batch_size, self.pomo_size), dtype=torch.bool) # shape: (batch, pomo) reward = None done = False return self.reset_state, reward, done def pre_step(self): self.step_state.selected_count = self.selected_count self.step_state.current_node = self.current_node self.step_state.ninf_mask = self.ninf_mask self.step_state.finished = self.finished reward = None done = False return self.step_state, reward, done def step(self, selected): # selected.shape: (batch, pomo) # Dynamic-1 #################################### self.selected_count += 1 self.current_node = selected # shape: (batch, pomo) self.selected_node_list = torch.cat((self.selected_node_list, self.current_node[:, :, None]), dim=2) # shape: (batch, pomo, 0~) # Dynamic-2 #################################### self.at_the_depot = (selected == 0) demand_list = self.depot_node_demand[:, None, :].expand(self.batch_size, self.pomo_size, -1) # shape: (batch, pomo, problem+1) gathering_index = selected[:, :, None] # shape: (batch, pomo, 1) selected_demand = demand_list.gather(dim=2, index=gathering_index).squeeze(dim=2) # shape: (batch, pomo) self.load -= selected_demand self.load[self.at_the_depot] = 1 # refill loaded at the depot self.visited_ninf_flag[self.BATCH_IDX, self.POMO_IDX, selected] = float('-inf') # shape: (batch, pomo, problem+1) self.visited_ninf_flag[:, :, 0][~self.at_the_depot] = 0 # depot is considered unvisited, unless you are AT the depot self.ninf_mask = self.visited_ninf_flag.clone() round_error_epsilon = 0.00001 demand_too_large = self.load[:, :, None] + round_error_epsilon < demand_list # shape: (batch, pomo, problem+1) self.ninf_mask[demand_too_large] = float('-inf') # shape: (batch, pomo, problem+1) newly_finished = (self.visited_ninf_flag == float('-inf')).all(dim=2) # shape: (batch, pomo) self.finished = self.finished + newly_finished # shape: (batch, pomo) # do not mask depot for finished episode. self.ninf_mask[:, :, 0][self.finished] = 0 self.step_state.selected_count = self.selected_count self.step_state.current_node = self.current_node self.step_state.ninf_mask = self.ninf_mask self.step_state.finished = self.finished # returning values done = self.finished.all() if done: reward = -self._get_travel_distance() # note the minus sign! else: reward = None return self.step_state, reward, done def _get_travel_distance(self): gathering_index = self.selected_node_list[:, :, :, None].expand(-1, -1, -1, 2) # shape: (batch, pomo, selected_list_length, 2) all_xy = self.depot_node_xy[:, None, :, :].expand(-1, self.pomo_size, -1, -1) # shape: (batch, pomo, problem+1, 2) # obj1: travel_distances ordered_seq = all_xy.gather(dim=2, index=gathering_index) # shape: (batch, pomo, selected_list_length, 2) rolled_seq = ordered_seq.roll(dims=2, shifts=-1) segment_lengths = ((ordered_seq-rolled_seq)**2).sum(3).sqrt() # shape: (batch, pomo, selected_list_length) travel_distances = segment_lengths.sum(2) # shape: (batch, pomo) # obj2: makespans not_idx = (gathering_index[:,:,:,0] > 0) cum_lengths = torch.cumsum(segment_lengths, dim = 2) cum_lengths[not_idx] = 0 sorted_cum_lengths, _ = cum_lengths.sort(axis = 2) rolled_sorted_cum_lengths = sorted_cum_lengths.roll(dims=2, shifts = 1) diff_mat = sorted_cum_lengths - rolled_sorted_cum_lengths diff_mat[diff_mat < 0] = 0 makespans, _ = torch.max(diff_mat,dim = 2) objs = torch.stack([travel_distances,makespans],axis = 2) return objs
en
0.534456
# shape: (batch, problem) # shape: (batch, pomo) # shape: (batch, pomo) # shape: (batch, pomo, problem+1) # shape: (batch, pomo) # Const @INIT #################################### # Const @Load_Problem #################################### # IDX.shape: (batch, pomo) # shape: (batch, problem+1, 2) # shape: (batch, problem+1) # Dynamic-1 #################################### # shape: (batch, pomo) # shape: (batch, pomo, 0~) # Dynamic-2 #################################### # shape: (batch, pomo) # shape: (batch, pomo) # shape: (batch, pomo, problem+1) # shape: (batch, pomo, problem+1) # shape: (batch, pomo) # states to return #################################### # shape: (batch, problem+1, 2) # shape: (batch, 1) # shape: (batch, problem+1) # shape: (batch, pomo) # shape: (batch, pomo, 0~) # shape: (batch, pomo) # shape: (batch, pomo) # shape: (batch, pomo, problem+1) # shape: (batch, pomo, problem+1) # shape: (batch, pomo) # selected.shape: (batch, pomo) # Dynamic-1 #################################### # shape: (batch, pomo) # shape: (batch, pomo, 0~) # Dynamic-2 #################################### # shape: (batch, pomo, problem+1) # shape: (batch, pomo, 1) # shape: (batch, pomo) # refill loaded at the depot # shape: (batch, pomo, problem+1) # depot is considered unvisited, unless you are AT the depot # shape: (batch, pomo, problem+1) # shape: (batch, pomo, problem+1) # shape: (batch, pomo) # shape: (batch, pomo) # do not mask depot for finished episode. # returning values # note the minus sign! # shape: (batch, pomo, selected_list_length, 2) # shape: (batch, pomo, problem+1, 2) # obj1: travel_distances # shape: (batch, pomo, selected_list_length, 2) # shape: (batch, pomo, selected_list_length) # shape: (batch, pomo) # obj2: makespans
2.258219
2
python/tvm/script/tir/ty.py
BaldLee/tvm
10
6625128
<filename>python/tvm/script/tir/ty.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """TVM Script Parser Typing Class for TIR This module provides typing class for TVM script type annotation usage, it can be viewed as a wrapper for uniform Type system in IR """ # pylint: disable=invalid-name import tvm class TypeGeneric: # pylint: disable=too-few-public-methods """Base class for all the TVM script typing class""" def evaluate(self): """Return an actual ir.Type Object that this Generic class wraps""" raise TypeError("Cannot get tvm.Type from a generic type") class ConcreteType(TypeGeneric): # pylint: disable=too-few-public-methods """TVM script typing class for uniform Type objects""" def __init__(self, vtype): self.type = vtype def evaluate(self): return tvm.ir.PrimType(self.type) class GenericPtrType(TypeGeneric): """TVM script typing class generator for PtrType [] operator is overloaded, accepts a ConcreteType and returns a ConcreteType wrapping PtrType """ def __getitem__(self, vtype): return ConcreteType(tvm.ir.PointerType(vtype.evaluate())) class GenericTupleType(TypeGeneric): """TVM script typing class generator for TupleType [] operator is overloaded, accepts a list of ConcreteType and returns a ConcreteType wrapping TupleType """ def __getitem__(self, vtypes): return ConcreteType(tvm.ir.TupleType([vtype.evaluate() for vtype in vtypes])) int8 = ConcreteType("int8") int16 = ConcreteType("int16") int32 = ConcreteType("int32") int64 = ConcreteType("int64") float16 = ConcreteType("float16") float32 = ConcreteType("float32") float64 = ConcreteType("float64") boolean = ConcreteType("bool") handle = ConcreteType("handle") Ptr = GenericPtrType() Tuple = GenericTupleType()
<filename>python/tvm/script/tir/ty.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """TVM Script Parser Typing Class for TIR This module provides typing class for TVM script type annotation usage, it can be viewed as a wrapper for uniform Type system in IR """ # pylint: disable=invalid-name import tvm class TypeGeneric: # pylint: disable=too-few-public-methods """Base class for all the TVM script typing class""" def evaluate(self): """Return an actual ir.Type Object that this Generic class wraps""" raise TypeError("Cannot get tvm.Type from a generic type") class ConcreteType(TypeGeneric): # pylint: disable=too-few-public-methods """TVM script typing class for uniform Type objects""" def __init__(self, vtype): self.type = vtype def evaluate(self): return tvm.ir.PrimType(self.type) class GenericPtrType(TypeGeneric): """TVM script typing class generator for PtrType [] operator is overloaded, accepts a ConcreteType and returns a ConcreteType wrapping PtrType """ def __getitem__(self, vtype): return ConcreteType(tvm.ir.PointerType(vtype.evaluate())) class GenericTupleType(TypeGeneric): """TVM script typing class generator for TupleType [] operator is overloaded, accepts a list of ConcreteType and returns a ConcreteType wrapping TupleType """ def __getitem__(self, vtypes): return ConcreteType(tvm.ir.TupleType([vtype.evaluate() for vtype in vtypes])) int8 = ConcreteType("int8") int16 = ConcreteType("int16") int32 = ConcreteType("int32") int64 = ConcreteType("int64") float16 = ConcreteType("float16") float32 = ConcreteType("float32") float64 = ConcreteType("float64") boolean = ConcreteType("bool") handle = ConcreteType("handle") Ptr = GenericPtrType() Tuple = GenericTupleType()
en
0.76743
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. TVM Script Parser Typing Class for TIR This module provides typing class for TVM script type annotation usage, it can be viewed as a wrapper for uniform Type system in IR # pylint: disable=invalid-name # pylint: disable=too-few-public-methods Base class for all the TVM script typing class Return an actual ir.Type Object that this Generic class wraps # pylint: disable=too-few-public-methods TVM script typing class for uniform Type objects TVM script typing class generator for PtrType [] operator is overloaded, accepts a ConcreteType and returns a ConcreteType wrapping PtrType TVM script typing class generator for TupleType [] operator is overloaded, accepts a list of ConcreteType and returns a ConcreteType wrapping TupleType
1.799069
2
shop/models.py
Zex0n/django-simple-cms
1
6625129
from django.db import models from django.utils.translation import ugettext_lazy as _, ugettext from mptt.models import MPTTModel, TreeForeignKey from taggit.managers import TaggableManager from urllib.parse import urljoin from django.core.urlresolvers import resolve, reverse from django.conf import settings from django.core.cache import cache from multiselectfield import MultiSelectField from django.utils.functional import lazy from ckeditor_uploader.fields import RichTextUploadingField from django.contrib.auth.models import User as auth_user from sorl.thumbnail import ImageField from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import User class UserProfile(models.Model): LEVEL_STATUS_CHOICES = ( (0, 'Уровень 1'), (1, 'Уровень 2'), (2, 'Уровень 3'), ) user = models.OneToOneField(User,related_name='related_name_user') member_type = models.IntegerField('Уровень скидок', choices=LEVEL_STATUS_CHOICES, default=0) name = models.CharField(_("Контактное лицо"), max_length=1000, default='') id1c = models.CharField(_("1C - ID"), blank=True, max_length=255) phone = models.CharField(_("Телефон"), max_length=1000, default='') company_name = models.CharField(_("Название компании"), max_length=1000, default='') inn = models.CharField(_("ИНН"), max_length=1000, default='') kpp = models.CharField(_("КПП"), max_length=1000, default='') orgn = models.CharField(_("ОГРН"), max_length=1000, default='') bank = models.CharField(_("Наименование банка"), max_length=1000, default='') bik = models.CharField(_("БИК"), max_length=1000, default='') rs = models.CharField(_("Р/C"), max_length=1000, default='') ks = models.CharField(_("К/C"), max_length=1000, default='') city = models.CharField(_("Город"), max_length=1000, default='') adres = models.CharField(_("Адрес доставки"), max_length=1000, default='') class Meta: verbose_name = _("Профиль пользователя") verbose_name_plural = _("Профили пользователя") class BaseShop(models.Model): created_date = models.DateTimeField(_("Дата создания"), auto_now_add=True, editable=False) edited_date = models.DateTimeField(_("Дата редактирования"), auto_now=True, editable=False, null=True) title = models.CharField(_("Название"), max_length=1000, default='') meta_description = models.CharField(_("Description"), max_length=1000, blank=True) meta_keywords = models.CharField(_("Keywords"), max_length=1000, blank=True) slug = models.SlugField(_("Имя для url"), unique=True, blank=True, help_text=_("Только английские буквы, цифры и знаки минус и подчеркивание.")) tags = TaggableManager(_("Тэги"), blank=True), file = ImageField(_("Обложка для категории 250X250"), upload_to='category', blank=True) class Meta: abstract = True def __str__(self): return self.title class Category(MPTTModel, BaseShop): parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, verbose_name=u"Родительский элемент") content = RichTextUploadingField("Описание", blank=True) num = models.IntegerField(default=0, verbose_name=u'Порядковый номер') new_flag = models.BooleanField("Показывать как новинку", default=False) new_flag_text = models.CharField(_("Текст надписи НОВИНКА"), max_length=200, default='', blank=True) new_flag_color = models.CharField(_("Цвет подложки надписи"), max_length=200, default='', blank=True) code1c = models.IntegerField(_("Код базы"), default=0) class Meta: verbose_name = _("Категория") verbose_name_plural = _("Категории") ordering = ['num'] class Discount(models.Model): title = models.CharField('Название системы скидок', max_length=255) level1 = models.IntegerField(_("Уровень 1 - %"), blank=False, default=0) level2 = models.IntegerField(_("Уровень 2 - %"), blank=False, default=0) level3 = models.IntegerField(_("Уровень 3 - %"), blank=False, default=0) class Meta: verbose_name = _("Система скидок") verbose_name_plural = _("Системы скидок") ordering = ['id', ] def __str__(self): return self.title class Item(BaseShop): content_small = offer_name1 = models.CharField(_("Краткое описание"), max_length=800, default='', blank=True) content = RichTextUploadingField("Описание", blank=True) category = models.ManyToManyField(Category, verbose_name=u'Категория') status = models.BooleanField("Опубликовано", default=True) new_flag = models.BooleanField("Показывать как новинку", default=False) new_flag_text = models.CharField(_("Текст надписи НОВИНКА"), max_length=200, default='', blank=True) new_flag_color = models.CharField(_("Цвет подложки надписи"), max_length=200, default='', blank=True) min_offer = models.CharField(_("Минимальная партия"),max_length=50, blank=True, db_index=True,) offer = models.BooleanField("Показывать в спецпредложениях", default=False, blank=True) offer_name1 = models.CharField(_("Наименование бренд"), max_length=200, default='', blank=True) offer_name2 = models.CharField(_("Наименование модель"), max_length=200, default='', blank=True) offer_text_price = models.CharField(_("Цена текст"), max_length=200, default='', blank=True) offer_text_cost = models.CharField(_("Цена"), max_length=200, default='', blank=True) offer_text1 = models.CharField(_("Строка описания 1:"), max_length=200, default='', blank=True) offer_text2 = models.CharField(_("Строка описания 2:"), max_length=200, default='', blank=True) min_lot = models.IntegerField(default=1, verbose_name=u'Множитель для товара') num = models.IntegerField(default=0, verbose_name=u'Порядковый номер') offer_price=models.DecimalField(_("Цена без скидки"), max_digits=10, decimal_places=2, blank=True, null=True) discount_system=models.ForeignKey(Discount, on_delete=models.CASCADE,default=1) class Meta: verbose_name = _("Товар") verbose_name_plural = _("Товары") ordering = ['num'] class Item_variation(models.Model): ITEM_STOCK_CHOICES = ( (0, 'Нет в наличии'), (1, 'На складе'), (2, 'Ожидается'), ) title = models.CharField(_("Название"), default='', max_length=255,blank=True) vendor_code = models.CharField(_("Артикул"), blank=True, max_length=255) default_variation = models.BooleanField(_("Вариация по умолчанию"), default=False) stock = models.IntegerField(_("На складе"), choices=ITEM_STOCK_CHOICES, default=1) in_stock = models.IntegerField(default=0, verbose_name=u'Количество на складе (шт.)') stock_text = models.CharField(_("Когда ожидается"), default='', max_length=255, blank=True) price_1 = models.DecimalField(_("Розничная цена"), max_digits=10, decimal_places=2, blank=True, null=True) price_2 = models.DecimalField(_("Оптовая цена"), max_digits=10, decimal_places=2, blank=True, null=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) num = models.IntegerField(_("Порядковый номер"), default=0, blank=True, db_index=True) class Meta: verbose_name = _("Вариация") verbose_name_plural = _("Вариации") ordering = ['num', ] def __str__(self): return self.title class Item_image(models.Model): title = models.CharField(_("Название"), max_length=1000, default='', blank=True) file = models.ImageField(_("Изображение"), upload_to='shop') item_variation = models.ForeignKey(Item_variation, on_delete=models.CASCADE, blank=True,) num = models.IntegerField(_("Порядковый номер"), default=0, blank=True, db_index=True) class Meta: verbose_name = _("Изображение") verbose_name_plural = _("Изображения") ordering = ['num', ] def __str__(self): return self.file.url # Заказы class BaseOrder(models.Model): created_date = models.DateTimeField(_("Дата создания"), auto_now_add=True, editable=False) edited_date = models.DateTimeField(_("Дата редактирования"), auto_now=True, editable=False, null=True) class Meta: abstract = True class Status(models.Model): title = models.CharField('Название', max_length=255) num = models.IntegerField('Порядковый номер', default=0) default_status = models.BooleanField("Статус заказа при создании", default=False) class Meta: verbose_name = 'Статус заказа' verbose_name_plural = 'Статусы заказов' ordering = ['num'] def __str__(self): return self.title class Order(BaseOrder): customer = models.ForeignKey(auth_user, verbose_name=u'Пользователь') total_price = models.DecimalField(_("Общая стоимость"), max_digits=10, decimal_places=2, blank=True, null=True) status = models.ForeignKey(Status, verbose_name=u'Текущий статус', blank=True, null=True) email = models.EmailField(_("Email"), default='') address = models.TextField(_("Адрес доставки")) phone_number = PhoneNumberField(_("Телефон"),default='') class Meta: verbose_name = _("Заказ") verbose_name_plural = _("Заказы") class OrderItem(BaseOrder): order = models.ForeignKey(Order, verbose_name=u'Заказ', on_delete=models.CASCADE) item = models.ForeignKey(Item_variation, on_delete=models.SET_NULL, null=True) title = models.CharField(_("Название"), default='', max_length=255) cols = models.IntegerField(_("Количество"), blank=True, default=0) price = models.DecimalField(_("Стоимость"), max_digits=10, decimal_places=2, blank=True, null=True) class Meta: verbose_name = _("Товар заказа") verbose_name_plural = _("Товары заказа") def __str__(self): return self.title class TreeCash(models.Model): cat_id=models.ForeignKey(Category,on_delete=models.SET_NULL, null=True) created_date = models.DateTimeField(_("Дата создания"), auto_now_add=True, editable=False) elm_cols=models.IntegerField('Количество в категории', default=0) price_from = models.DecimalField(_("Цены от"), max_digits=10, decimal_places=2, blank=True, null=True) price_to = models.DecimalField(_("Цены до"), max_digits=10, decimal_places=2, blank=True, null=True) price_from_anon=models.DecimalField(_("Цены от анонимный"), max_digits=10, decimal_places=2, blank=True, null=True) price_to_anon = models.DecimalField(_("Цены до анонимный"), max_digits=10, decimal_places=2, blank=True, null=True)
from django.db import models from django.utils.translation import ugettext_lazy as _, ugettext from mptt.models import MPTTModel, TreeForeignKey from taggit.managers import TaggableManager from urllib.parse import urljoin from django.core.urlresolvers import resolve, reverse from django.conf import settings from django.core.cache import cache from multiselectfield import MultiSelectField from django.utils.functional import lazy from ckeditor_uploader.fields import RichTextUploadingField from django.contrib.auth.models import User as auth_user from sorl.thumbnail import ImageField from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import User class UserProfile(models.Model): LEVEL_STATUS_CHOICES = ( (0, 'Уровень 1'), (1, 'Уровень 2'), (2, 'Уровень 3'), ) user = models.OneToOneField(User,related_name='related_name_user') member_type = models.IntegerField('Уровень скидок', choices=LEVEL_STATUS_CHOICES, default=0) name = models.CharField(_("Контактное лицо"), max_length=1000, default='') id1c = models.CharField(_("1C - ID"), blank=True, max_length=255) phone = models.CharField(_("Телефон"), max_length=1000, default='') company_name = models.CharField(_("Название компании"), max_length=1000, default='') inn = models.CharField(_("ИНН"), max_length=1000, default='') kpp = models.CharField(_("КПП"), max_length=1000, default='') orgn = models.CharField(_("ОГРН"), max_length=1000, default='') bank = models.CharField(_("Наименование банка"), max_length=1000, default='') bik = models.CharField(_("БИК"), max_length=1000, default='') rs = models.CharField(_("Р/C"), max_length=1000, default='') ks = models.CharField(_("К/C"), max_length=1000, default='') city = models.CharField(_("Город"), max_length=1000, default='') adres = models.CharField(_("Адрес доставки"), max_length=1000, default='') class Meta: verbose_name = _("Профиль пользователя") verbose_name_plural = _("Профили пользователя") class BaseShop(models.Model): created_date = models.DateTimeField(_("Дата создания"), auto_now_add=True, editable=False) edited_date = models.DateTimeField(_("Дата редактирования"), auto_now=True, editable=False, null=True) title = models.CharField(_("Название"), max_length=1000, default='') meta_description = models.CharField(_("Description"), max_length=1000, blank=True) meta_keywords = models.CharField(_("Keywords"), max_length=1000, blank=True) slug = models.SlugField(_("Имя для url"), unique=True, blank=True, help_text=_("Только английские буквы, цифры и знаки минус и подчеркивание.")) tags = TaggableManager(_("Тэги"), blank=True), file = ImageField(_("Обложка для категории 250X250"), upload_to='category', blank=True) class Meta: abstract = True def __str__(self): return self.title class Category(MPTTModel, BaseShop): parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, verbose_name=u"Родительский элемент") content = RichTextUploadingField("Описание", blank=True) num = models.IntegerField(default=0, verbose_name=u'Порядковый номер') new_flag = models.BooleanField("Показывать как новинку", default=False) new_flag_text = models.CharField(_("Текст надписи НОВИНКА"), max_length=200, default='', blank=True) new_flag_color = models.CharField(_("Цвет подложки надписи"), max_length=200, default='', blank=True) code1c = models.IntegerField(_("Код базы"), default=0) class Meta: verbose_name = _("Категория") verbose_name_plural = _("Категории") ordering = ['num'] class Discount(models.Model): title = models.CharField('Название системы скидок', max_length=255) level1 = models.IntegerField(_("Уровень 1 - %"), blank=False, default=0) level2 = models.IntegerField(_("Уровень 2 - %"), blank=False, default=0) level3 = models.IntegerField(_("Уровень 3 - %"), blank=False, default=0) class Meta: verbose_name = _("Система скидок") verbose_name_plural = _("Системы скидок") ordering = ['id', ] def __str__(self): return self.title class Item(BaseShop): content_small = offer_name1 = models.CharField(_("Краткое описание"), max_length=800, default='', blank=True) content = RichTextUploadingField("Описание", blank=True) category = models.ManyToManyField(Category, verbose_name=u'Категория') status = models.BooleanField("Опубликовано", default=True) new_flag = models.BooleanField("Показывать как новинку", default=False) new_flag_text = models.CharField(_("Текст надписи НОВИНКА"), max_length=200, default='', blank=True) new_flag_color = models.CharField(_("Цвет подложки надписи"), max_length=200, default='', blank=True) min_offer = models.CharField(_("Минимальная партия"),max_length=50, blank=True, db_index=True,) offer = models.BooleanField("Показывать в спецпредложениях", default=False, blank=True) offer_name1 = models.CharField(_("Наименование бренд"), max_length=200, default='', blank=True) offer_name2 = models.CharField(_("Наименование модель"), max_length=200, default='', blank=True) offer_text_price = models.CharField(_("Цена текст"), max_length=200, default='', blank=True) offer_text_cost = models.CharField(_("Цена"), max_length=200, default='', blank=True) offer_text1 = models.CharField(_("Строка описания 1:"), max_length=200, default='', blank=True) offer_text2 = models.CharField(_("Строка описания 2:"), max_length=200, default='', blank=True) min_lot = models.IntegerField(default=1, verbose_name=u'Множитель для товара') num = models.IntegerField(default=0, verbose_name=u'Порядковый номер') offer_price=models.DecimalField(_("Цена без скидки"), max_digits=10, decimal_places=2, blank=True, null=True) discount_system=models.ForeignKey(Discount, on_delete=models.CASCADE,default=1) class Meta: verbose_name = _("Товар") verbose_name_plural = _("Товары") ordering = ['num'] class Item_variation(models.Model): ITEM_STOCK_CHOICES = ( (0, 'Нет в наличии'), (1, 'На складе'), (2, 'Ожидается'), ) title = models.CharField(_("Название"), default='', max_length=255,blank=True) vendor_code = models.CharField(_("Артикул"), blank=True, max_length=255) default_variation = models.BooleanField(_("Вариация по умолчанию"), default=False) stock = models.IntegerField(_("На складе"), choices=ITEM_STOCK_CHOICES, default=1) in_stock = models.IntegerField(default=0, verbose_name=u'Количество на складе (шт.)') stock_text = models.CharField(_("Когда ожидается"), default='', max_length=255, blank=True) price_1 = models.DecimalField(_("Розничная цена"), max_digits=10, decimal_places=2, blank=True, null=True) price_2 = models.DecimalField(_("Оптовая цена"), max_digits=10, decimal_places=2, blank=True, null=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) num = models.IntegerField(_("Порядковый номер"), default=0, blank=True, db_index=True) class Meta: verbose_name = _("Вариация") verbose_name_plural = _("Вариации") ordering = ['num', ] def __str__(self): return self.title class Item_image(models.Model): title = models.CharField(_("Название"), max_length=1000, default='', blank=True) file = models.ImageField(_("Изображение"), upload_to='shop') item_variation = models.ForeignKey(Item_variation, on_delete=models.CASCADE, blank=True,) num = models.IntegerField(_("Порядковый номер"), default=0, blank=True, db_index=True) class Meta: verbose_name = _("Изображение") verbose_name_plural = _("Изображения") ordering = ['num', ] def __str__(self): return self.file.url # Заказы class BaseOrder(models.Model): created_date = models.DateTimeField(_("Дата создания"), auto_now_add=True, editable=False) edited_date = models.DateTimeField(_("Дата редактирования"), auto_now=True, editable=False, null=True) class Meta: abstract = True class Status(models.Model): title = models.CharField('Название', max_length=255) num = models.IntegerField('Порядковый номер', default=0) default_status = models.BooleanField("Статус заказа при создании", default=False) class Meta: verbose_name = 'Статус заказа' verbose_name_plural = 'Статусы заказов' ordering = ['num'] def __str__(self): return self.title class Order(BaseOrder): customer = models.ForeignKey(auth_user, verbose_name=u'Пользователь') total_price = models.DecimalField(_("Общая стоимость"), max_digits=10, decimal_places=2, blank=True, null=True) status = models.ForeignKey(Status, verbose_name=u'Текущий статус', blank=True, null=True) email = models.EmailField(_("Email"), default='') address = models.TextField(_("Адрес доставки")) phone_number = PhoneNumberField(_("Телефон"),default='') class Meta: verbose_name = _("Заказ") verbose_name_plural = _("Заказы") class OrderItem(BaseOrder): order = models.ForeignKey(Order, verbose_name=u'Заказ', on_delete=models.CASCADE) item = models.ForeignKey(Item_variation, on_delete=models.SET_NULL, null=True) title = models.CharField(_("Название"), default='', max_length=255) cols = models.IntegerField(_("Количество"), blank=True, default=0) price = models.DecimalField(_("Стоимость"), max_digits=10, decimal_places=2, blank=True, null=True) class Meta: verbose_name = _("Товар заказа") verbose_name_plural = _("Товары заказа") def __str__(self): return self.title class TreeCash(models.Model): cat_id=models.ForeignKey(Category,on_delete=models.SET_NULL, null=True) created_date = models.DateTimeField(_("Дата создания"), auto_now_add=True, editable=False) elm_cols=models.IntegerField('Количество в категории', default=0) price_from = models.DecimalField(_("Цены от"), max_digits=10, decimal_places=2, blank=True, null=True) price_to = models.DecimalField(_("Цены до"), max_digits=10, decimal_places=2, blank=True, null=True) price_from_anon=models.DecimalField(_("Цены от анонимный"), max_digits=10, decimal_places=2, blank=True, null=True) price_to_anon = models.DecimalField(_("Цены до анонимный"), max_digits=10, decimal_places=2, blank=True, null=True)
none
1
1.911547
2
napari/layers/shapes/_shapes_models/_polgyon_base.py
Zac-HD/napari
1
6625130
import numpy as np from .._shapes_utils import create_box from .shape import Shape class PolygonBase(Shape): """Class for a polygon or path. Parameters ---------- data : np.ndarray NxD array of vertices specifying the path. edge_width : float thickness of lines and edges. z_index : int Specifier of z order priority. Shapes with higher z order are displayed ontop of others. dims_order : (D,) list Order that the dimensions are to be rendered in. closed : bool Bool if shape edge is a closed path or not. filled : bool Flag if array is filled or not. name : str Name of the shape. """ def __init__( self, data, *, edge_width=1, z_index=0, dims_order=None, ndisplay=2, filled=True, closed=True, name='polygon', ): super().__init__( edge_width=edge_width, z_index=z_index, dims_order=dims_order, ndisplay=ndisplay, ) self._filled = filled self._closed = closed self.data = data self.name = name @property def data(self): """np.ndarray: NxD array of vertices.""" return self._data @data.setter def data(self, data): data = np.array(data).astype(float) if len(self.dims_order) != data.shape[1]: self._dims_order = list(range(data.shape[1])) if len(data) < 2: raise ValueError( f"""Shape needs at least two vertices, {len(data)} provided.""" ) self._data = data self._update_displayed_data() def _update_displayed_data(self): """Update the data that is to be displayed.""" # For path connect every all data self._set_meshes( self.data_displayed, face=self._filled, closed=self._closed ) self._box = create_box(self.data_displayed) data_not_displayed = self.data[:, self.dims_not_displayed] self.slice_key = np.round( [ np.min(data_not_displayed, axis=0), np.max(data_not_displayed, axis=0), ] ).astype('int')
import numpy as np from .._shapes_utils import create_box from .shape import Shape class PolygonBase(Shape): """Class for a polygon or path. Parameters ---------- data : np.ndarray NxD array of vertices specifying the path. edge_width : float thickness of lines and edges. z_index : int Specifier of z order priority. Shapes with higher z order are displayed ontop of others. dims_order : (D,) list Order that the dimensions are to be rendered in. closed : bool Bool if shape edge is a closed path or not. filled : bool Flag if array is filled or not. name : str Name of the shape. """ def __init__( self, data, *, edge_width=1, z_index=0, dims_order=None, ndisplay=2, filled=True, closed=True, name='polygon', ): super().__init__( edge_width=edge_width, z_index=z_index, dims_order=dims_order, ndisplay=ndisplay, ) self._filled = filled self._closed = closed self.data = data self.name = name @property def data(self): """np.ndarray: NxD array of vertices.""" return self._data @data.setter def data(self, data): data = np.array(data).astype(float) if len(self.dims_order) != data.shape[1]: self._dims_order = list(range(data.shape[1])) if len(data) < 2: raise ValueError( f"""Shape needs at least two vertices, {len(data)} provided.""" ) self._data = data self._update_displayed_data() def _update_displayed_data(self): """Update the data that is to be displayed.""" # For path connect every all data self._set_meshes( self.data_displayed, face=self._filled, closed=self._closed ) self._box = create_box(self.data_displayed) data_not_displayed = self.data[:, self.dims_not_displayed] self.slice_key = np.round( [ np.min(data_not_displayed, axis=0), np.max(data_not_displayed, axis=0), ] ).astype('int')
en
0.813905
Class for a polygon or path. Parameters ---------- data : np.ndarray NxD array of vertices specifying the path. edge_width : float thickness of lines and edges. z_index : int Specifier of z order priority. Shapes with higher z order are displayed ontop of others. dims_order : (D,) list Order that the dimensions are to be rendered in. closed : bool Bool if shape edge is a closed path or not. filled : bool Flag if array is filled or not. name : str Name of the shape. np.ndarray: NxD array of vertices. Shape needs at least two vertices, {len(data)} provided. Update the data that is to be displayed. # For path connect every all data
3.092027
3
zerver/views/auth.py
fatihCinarKrtg/zulip
1
6625131
<reponame>fatihCinarKrtg/zulip import logging import secrets import urllib from functools import wraps from typing import Any, Dict, List, Mapping, Optional, cast from urllib.parse import urlencode import jwt from cryptography.hazmat.primitives.ciphers.aead import AESGCM from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.views import LoginView as DjangoLoginView from django.contrib.auth.views import PasswordResetView as DjangoPasswordResetView from django.contrib.auth.views import logout_then_login as django_logout_then_login from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.forms import Form from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.shortcuts import redirect, render from django.template.response import SimpleTemplateResponse from django.urls import reverse from django.utils.html import escape from django.utils.http import url_has_allowed_host_and_scheme from django.utils.translation import gettext as _ from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_safe from jinja2.utils import Markup as mark_safe from social_django.utils import load_backend, load_strategy from two_factor.forms import BackupTokenForm from two_factor.views import LoginView as BaseTwoFactorLoginView from confirmation.models import ( Confirmation, ConfirmationKeyException, create_confirmation_link, get_object_from_key, ) from version import API_FEATURE_LEVEL, ZULIP_MERGE_BASE, ZULIP_VERSION from zerver.context_processors import get_realm_from_request, login_context, zulip_default_context from zerver.decorator import do_login, log_view_func, process_client, require_post from zerver.forms import ( DEACTIVATED_ACCOUNT_ERROR, AuthenticationTokenForm, HomepageForm, OurAuthenticationForm, ZulipPasswordResetForm, ) from zerver.lib.exceptions import ( AuthenticationFailedError, InvalidSubdomainError, JsonableError, PasswordAuthDisabledError, PasswordResetRequiredError, RateLimited, RealmDeactivatedError, UserDeactivatedError, ) from zerver.lib.mobile_auth_otp import otp_encrypt_api_key from zerver.lib.push_notifications import push_notifications_enabled from zerver.lib.pysa import mark_sanitized from zerver.lib.realm_icon import realm_icon_url from zerver.lib.request import REQ, RequestNotes, has_request_variables from zerver.lib.response import json_success from zerver.lib.sessions import set_expirable_session_var from zerver.lib.subdomains import get_subdomain, is_subdomain_root_or_alias from zerver.lib.types import ViewFuncT from zerver.lib.url_encoding import append_url_query_string from zerver.lib.user_agent import parse_user_agent from zerver.lib.users import get_api_key from zerver.lib.utils import has_api_key_format from zerver.lib.validator import validate_login_email from zerver.models import ( MultiuseInvite, PreregistrationUser, Realm, UserProfile, filter_to_valid_prereg_users, get_realm, remote_user_to_email, ) from zerver.signals import email_on_new_login from zproject.backends import ( AUTH_BACKEND_NAME_MAP, AppleAuthBackend, ExternalAuthDataDict, ExternalAuthResult, GenericOpenIdConnectBackend, SAMLAuthBackend, ZulipLDAPAuthBackend, ZulipLDAPConfigurationError, ZulipRemoteUserBackend, auth_enabled_helper, dev_auth_enabled, ldap_auth_enabled, password_auth_enabled, saml_auth_enabled, validate_otp_params, ) ExtraContext = Optional[Dict[str, Any]] def get_safe_redirect_to(url: str, redirect_host: str) -> str: is_url_safe = url_has_allowed_host_and_scheme(url=url, allowed_hosts=None) if is_url_safe: # Mark as safe to prevent Pysa from surfacing false positives for # open redirects. In this branch, we have already checked that the URL # points to the specified 'redirect_host', or is relative. return urllib.parse.urljoin(redirect_host, mark_sanitized(url)) else: return redirect_host def create_preregistration_user( email: str, request: HttpRequest, realm_creation: bool = False, password_required: bool = True, full_name: Optional[str] = None, full_name_validated: bool = False, ) -> PreregistrationUser: realm = None if not realm_creation: try: realm = get_realm(get_subdomain(request)) except Realm.DoesNotExist: pass return PreregistrationUser.objects.create( email=email, realm_creation=realm_creation, password_required=<PASSWORD>, realm=realm, full_name=full_name, full_name_validated=full_name_validated, ) def maybe_send_to_registration( request: HttpRequest, email: str, full_name: str = "", mobile_flow_otp: Optional[str] = None, desktop_flow_otp: Optional[str] = None, is_signup: bool = False, password_required: bool = True, multiuse_object_key: str = "", full_name_validated: bool = False, ) -> HttpResponse: """Given a successful authentication for an email address (i.e. we've confirmed the user controls the email address) that does not currently have a Zulip account in the target realm, send them to the registration flow or the "continue to registration" flow, depending on is_signup, whether the email address can join the organization (checked in HomepageForm), and similar details. """ # In the desktop and mobile registration flows, the sign up # happens in the browser so the user can use their # already-logged-in social accounts. Then at the end, with the # user account created, we pass the appropriate data to the app # via e.g. a `zulip://` redirect. We store the OTP keys for the # mobile/desktop flow in the session with 1-hour expiry, because # we want this configuration of having a successful authentication # result in being logged into the app to persist if the user makes # mistakes while trying to authenticate (E.g. clicks the wrong # Google account, hits back, etc.) during a given browser session, # rather than just logging into the web app in the target browser. # # We can't use our usual pre-account-creation state storage # approach of putting something in PreregistrationUser, because # that would apply to future registration attempts on other # devices, e.g. just creating an account on the web on their laptop. assert not (mobile_flow_otp and desktop_flow_otp) if mobile_flow_otp: set_expirable_session_var( request.session, "registration_mobile_flow_otp", mobile_flow_otp, expiry_seconds=3600 ) elif desktop_flow_otp: set_expirable_session_var( request.session, "registration_desktop_flow_otp", desktop_flow_otp, expiry_seconds=3600 ) multiuse_obj: Optional[MultiuseInvite] = None realm: Optional[Realm] = None from_multiuse_invite = False if multiuse_object_key: from_multiuse_invite = True try: multiuse_obj = get_object_from_key(multiuse_object_key, Confirmation.MULTIUSE_INVITE) except ConfirmationKeyException: return render(request, "zerver/confirmation_link_expired_error.html", status=404) assert multiuse_obj is not None realm = multiuse_obj.realm invited_as = multiuse_obj.invited_as else: try: realm = get_realm(get_subdomain(request)) except Realm.DoesNotExist: pass invited_as = PreregistrationUser.INVITE_AS["MEMBER"] form = HomepageForm({"email": email}, realm=realm, from_multiuse_invite=from_multiuse_invite) if form.is_valid(): # If the email address is allowed to sign up for an account in # this organization, construct a PreregistrationUser and # Confirmation objects, and then send the user to account # creation or confirm-continue-registration depending on # is_signup. try: prereg_user = filter_to_valid_prereg_users( PreregistrationUser.objects.filter(email__iexact=email, realm=realm) ).latest("invited_at") # password_required and full_name data passed here as argument should take precedence # over the defaults with which the existing PreregistrationUser that we've just fetched # was created. prereg_user.password_required = <PASSWORD> update_fields = ["password_required"] if full_name: prereg_user.full_name = full_name prereg_user.full_name_validated = full_name_validated update_fields.extend(["full_name", "full_name_validated"]) prereg_user.save(update_fields=update_fields) except PreregistrationUser.DoesNotExist: prereg_user = create_preregistration_user( email, request, password_required=<PASSWORD>, full_name=full_name, full_name_validated=full_name_validated, ) if multiuse_obj is not None: request.session.modified = True streams_to_subscribe = list(multiuse_obj.streams.all()) prereg_user.streams.set(streams_to_subscribe) prereg_user.invited_as = invited_as prereg_user.save() confirmation_link = create_confirmation_link(prereg_user, Confirmation.USER_REGISTRATION) if is_signup: return redirect(confirmation_link) context = {"email": email, "continue_link": confirmation_link, "full_name": full_name} return render(request, "zerver/confirm_continue_registration.html", context=context) # This email address it not allowed to join this organization, so # just send the user back to the registration page. url = reverse("register") context = login_context(request) extra_context: Mapping[str, Any] = { "form": form, "current_url": lambda: url, "from_multiuse_invite": from_multiuse_invite, "multiuse_object_key": multiuse_object_key, "mobile_flow_otp": mobile_flow_otp, "desktop_flow_otp": desktop_flow_otp, } context.update(extra_context) return render(request, "zerver/accounts_home.html", context=context) def register_remote_user(request: HttpRequest, result: ExternalAuthResult) -> HttpResponse: # We have verified the user controls an email address, but # there's no associated Zulip user account. Consider sending # the request to registration. kwargs: Dict[str, Any] = dict(result.data_dict) # maybe_send_to_registration doesn't take these arguments, so delete them. kwargs.pop("subdomain", None) kwargs.pop("redirect_to", None) kwargs.pop("is_realm_creation", None) kwargs["password_required"] = False return maybe_send_to_registration(request, **kwargs) def login_or_register_remote_user(request: HttpRequest, result: ExternalAuthResult) -> HttpResponse: """Given a successful authentication showing the user controls given email address (email) and potentially a UserProfile object (if the user already has a Zulip account), redirect the browser to the appropriate place: * The logged-in app if the user already has a Zulip account and is trying to log in, potentially to an initial narrow or page that had been saved in the `redirect_to` parameter. * The registration form if is_signup was set (i.e. the user is trying to create a Zulip account) * A special `confirm_continue_registration.html` "do you want to register or try another account" if the user doesn't have a Zulip account but is_signup is False (i.e. the user tried to log in and then did social authentication selecting an email address that does not have a Zulip account in this organization). * A zulip:// URL to send control back to the mobile or desktop apps if they are doing authentication using the mobile_flow_otp or desktop_flow_otp flow. """ user_profile = result.user_profile if user_profile is None or user_profile.is_mirror_dummy: return register_remote_user(request, result) # Otherwise, the user has successfully authenticated to an # account, and we need to do the right thing depending whether # or not they're using the mobile OTP flow or want a browser session. is_realm_creation = result.data_dict.get("is_realm_creation") mobile_flow_otp = result.data_dict.get("mobile_flow_otp") desktop_flow_otp = result.data_dict.get("desktop_flow_otp") if mobile_flow_otp is not None: return finish_mobile_flow(request, user_profile, mobile_flow_otp) elif desktop_flow_otp is not None: return finish_desktop_flow(request, user_profile, desktop_flow_otp) do_login(request, user_profile) redirect_to = result.data_dict.get("redirect_to", "") if is_realm_creation is not None and settings.BILLING_ENABLED: from corporate.lib.stripe import is_free_trial_offer_enabled if is_free_trial_offer_enabled(): redirect_to = "{}?onboarding=true".format(reverse("initial_upgrade")) redirect_to = get_safe_redirect_to(redirect_to, user_profile.realm.uri) return HttpResponseRedirect(redirect_to) def finish_desktop_flow(request: HttpRequest, user_profile: UserProfile, otp: str) -> HttpResponse: """ The desktop otp flow returns to the app (through the clipboard) a token that allows obtaining (through log_into_subdomain) a logged in session for the user account we authenticated in this flow. The token can only be used once and within ExternalAuthResult.LOGIN_KEY_EXPIRATION_SECONDS of being created, as nothing more powerful is needed for the desktop flow and this ensures the key can only be used for completing this authentication attempt. """ result = ExternalAuthResult(user_profile=user_profile) token = result.store_data() key = bytes.fromhex(otp) iv = secrets.token_bytes(12) desktop_data = (iv + AESGCM(key).encrypt(iv, token.encode(), b"")).hex() context = { "desktop_data": desktop_data, "browser_url": reverse("login_page", kwargs={"template_name": "zerver/login.html"}), "realm_icon_url": realm_icon_url(user_profile.realm), } return render(request, "zerver/desktop_redirect.html", context=context) def finish_mobile_flow(request: HttpRequest, user_profile: UserProfile, otp: str) -> HttpResponse: # For the mobile OAuth flow, we send the API key and other # necessary details in a redirect to a zulip:// URI scheme. api_key = get_api_key(user_profile) response = create_response_for_otp_flow( api_key, otp, user_profile, encrypted_key_field_name="otp_encrypted_api_key" ) # Since we are returning an API key instead of going through # the Django login() function (which creates a browser # session, etc.), the "new login" signal handler (which # triggers an email notification new logins) will not run # automatically. So we call it manually here. # # Arguably, sending a fake 'user_logged_in' signal would be a better approach: # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile) email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile) # Mark this request as having a logged-in user for our server logs. process_client(request, user_profile) RequestNotes.get_notes(request).requestor_for_logs = user_profile.format_requestor_for_logs() return response def create_response_for_otp_flow( key: str, otp: str, user_profile: UserProfile, encrypted_key_field_name: str ) -> HttpResponse: realm_uri = user_profile.realm.uri # Check if the mobile URI is overridden in settings, if so, replace it # This block should only apply to the mobile flow, so we if add others, this # needs to be conditional. if realm_uri in settings.REALM_MOBILE_REMAP_URIS: realm_uri = settings.REALM_MOBILE_REMAP_URIS[realm_uri] params = { encrypted_key_field_name: otp_encrypt_api_key(key, otp), "email": user_profile.delivery_email, "realm": realm_uri, } # We can't use HttpResponseRedirect, since it only allows HTTP(S) URLs response = HttpResponse(status=302) response["Location"] = append_url_query_string("zulip://login", urllib.parse.urlencode(params)) return response @log_view_func @has_request_variables def remote_user_sso( request: HttpRequest, mobile_flow_otp: Optional[str] = REQ(default=None), desktop_flow_otp: Optional[str] = REQ(default=None), next: str = REQ(default="/"), ) -> HttpResponse: subdomain = get_subdomain(request) try: realm: Optional[Realm] = get_realm(subdomain) except Realm.DoesNotExist: realm = None if not auth_enabled_helper([ZulipRemoteUserBackend.auth_backend_name], realm): return config_error(request, "remote_user_backend_disabled") try: remote_user = request.META["REMOTE_USER"] except KeyError: return config_error(request, "remote_user_header_missing") # Django invokes authenticate methods by matching arguments, and this # authentication flow will not invoke LDAP authentication because of # this condition of Django so no need to check if LDAP backend is # enabled. validate_login_email(remote_user_to_email(remote_user)) # Here we support the mobile and desktop flow for REMOTE_USER_BACKEND; we # validate the data format and then pass it through to # login_or_register_remote_user if appropriate. validate_otp_params(mobile_flow_otp, desktop_flow_otp) if realm is None: user_profile = None else: user_profile = authenticate(remote_user=remote_user, realm=realm) email = remote_user_to_email(remote_user) data_dict = ExternalAuthDataDict( email=email, mobile_flow_otp=mobile_flow_otp, desktop_flow_otp=desktop_flow_otp, redirect_to=next, ) if realm: data_dict["subdomain"] = realm.subdomain else: data_dict["subdomain"] = "" # realm creation happens on root subdomain result = ExternalAuthResult(user_profile=user_profile, data_dict=data_dict) return login_or_register_remote_user(request, result) @csrf_exempt @log_view_func def remote_user_jwt(request: HttpRequest) -> HttpResponse: subdomain = get_subdomain(request) try: key = settings.JWT_AUTH_KEYS[subdomain]["key"] algorithms = settings.JWT_AUTH_KEYS[subdomain]["algorithms"] except KeyError: raise JsonableError(_("Auth key for this subdomain not found.")) try: json_web_token = request.POST["json_web_token"] options = {"verify_signature": True} payload = jwt.decode(json_web_token, key, algorithms=algorithms, options=options) except KeyError: raise JsonableError(_("No JSON web token passed in request")) except jwt.InvalidTokenError: raise JsonableError(_("Bad JSON web token")) remote_user = payload.get("user", None) if remote_user is None: raise JsonableError(_("No user specified in JSON web token claims")) email_domain = payload.get("realm", None) if email_domain is None: raise JsonableError(_("No organization specified in JSON web token claims")) email = f"{remote_user}@{email_domain}" try: realm = get_realm(subdomain) except Realm.DoesNotExist: raise JsonableError(_("Wrong subdomain")) user_profile = authenticate(username=email, realm=realm, use_dummy_backend=True) if user_profile is None: result = ExternalAuthResult( data_dict={"email": email, "full_name": remote_user, "subdomain": realm.subdomain} ) else: result = ExternalAuthResult(user_profile=user_profile) return login_or_register_remote_user(request, result) @has_request_variables def oauth_redirect_to_root( request: HttpRequest, url: str, sso_type: str, is_signup: bool = False, extra_url_params: Dict[str, str] = {}, next: Optional[str] = REQ(default=None), multiuse_object_key: str = REQ(default=""), mobile_flow_otp: Optional[str] = REQ(default=None), desktop_flow_otp: Optional[str] = REQ(default=None), ) -> HttpResponse: main_site_uri = settings.ROOT_DOMAIN_URI + url if settings.SOCIAL_AUTH_SUBDOMAIN is not None and sso_type == "social": main_site_uri = ( settings.EXTERNAL_URI_SCHEME + settings.SOCIAL_AUTH_SUBDOMAIN + "." + settings.EXTERNAL_HOST ) + url params = { "subdomain": get_subdomain(request), "is_signup": "1" if is_signup else "0", } params["multiuse_object_key"] = multiuse_object_key # mobile_flow_otp is a one-time pad provided by the app that we # can use to encrypt the API key when passing back to the app. validate_otp_params(mobile_flow_otp, desktop_flow_otp) if mobile_flow_otp is not None: params["mobile_flow_otp"] = mobile_flow_otp if desktop_flow_otp is not None: params["desktop_flow_otp"] = desktop_flow_otp if next: params["next"] = next params = {**params, **extra_url_params} return redirect(append_url_query_string(main_site_uri, urllib.parse.urlencode(params))) def handle_desktop_flow(func: ViewFuncT) -> ViewFuncT: @wraps(func) def wrapper(request: HttpRequest, *args: object, **kwargs: object) -> HttpResponse: user_agent = parse_user_agent(request.META.get("HTTP_USER_AGENT", "Missing User-Agent")) if user_agent["name"] == "ZulipElectron": return render(request, "zerver/desktop_login.html") return func(request, *args, **kwargs) return cast(ViewFuncT, wrapper) # https://github.com/python/mypy/issues/1927 @handle_desktop_flow def start_remote_user_sso(request: HttpRequest) -> HttpResponse: """ The purpose of this endpoint is to provide an initial step in the flow on which we can handle the special behavior for the desktop app. /accounts/login/sso may have Apache intercepting requests to it to do authentication, so we need this additional endpoint. """ query = request.META["QUERY_STRING"] return redirect(append_url_query_string(reverse(remote_user_sso), query)) @handle_desktop_flow def start_social_login( request: HttpRequest, backend: str, extra_arg: Optional[str] = None, ) -> HttpResponse: backend_url = reverse("social:begin", args=[backend]) extra_url_params: Dict[str, str] = {} if backend == "saml": if not SAMLAuthBackend.check_config(): return config_error(request, "saml") # This backend requires the name of the IdP (from the list of configured ones) # to be passed as the parameter. if not extra_arg or extra_arg not in settings.SOCIAL_AUTH_SAML_ENABLED_IDPS: logging.info( "Attempted to initiate SAML authentication with wrong idp argument: %s", extra_arg ) return config_error(request, "saml") extra_url_params = {"idp": extra_arg} if backend == "apple" and not AppleAuthBackend.check_config(): return config_error(request, "apple") if backend == "oidc" and not GenericOpenIdConnectBackend.check_config(): return config_error(request, "oidc") # TODO: Add AzureAD also. if backend in ["github", "google", "gitlab"]: key_setting = "SOCIAL_AUTH_" + backend.upper() + "_KEY" secret_setting = "SOCIAL_AUTH_" + backend.upper() + "_SECRET" if not (getattr(settings, key_setting) and getattr(settings, secret_setting)): return config_error(request, backend) return oauth_redirect_to_root(request, backend_url, "social", extra_url_params=extra_url_params) @handle_desktop_flow def start_social_signup( request: HttpRequest, backend: str, extra_arg: Optional[str] = None, ) -> HttpResponse: backend_url = reverse("social:begin", args=[backend]) extra_url_params: Dict[str, str] = {} if backend == "saml": if not SAMLAuthBackend.check_config(): return config_error(request, "saml") if not extra_arg or extra_arg not in settings.SOCIAL_AUTH_SAML_ENABLED_IDPS: logging.info( "Attempted to initiate SAML authentication with wrong idp argument: %s", extra_arg ) return config_error(request, "saml") extra_url_params = {"idp": extra_arg} return oauth_redirect_to_root( request, backend_url, "social", is_signup=True, extra_url_params=extra_url_params ) _subdomain_token_salt = "zerver.views.auth.log_into_subdomain" @log_view_func def log_into_subdomain(request: HttpRequest, token: str) -> HttpResponse: """Given a valid authentication token (generated by redirect_and_log_into_subdomain called on auth.zulip.example.com), call login_or_register_remote_user, passing all the authentication result data that has been stored in Redis, associated with this token. """ # The tokens are intended to have the same format as API keys. if not has_api_key_format(token): logging.warning("log_into_subdomain: Malformed token given: %s", token) return HttpResponse(status=400) try: result = ExternalAuthResult(login_token=token) except ExternalAuthResult.InvalidTokenError: logging.warning("log_into_subdomain: Invalid token given: %s", token) return render(request, "zerver/log_into_subdomain_token_invalid.html", status=400) subdomain = get_subdomain(request) if result.data_dict["subdomain"] != subdomain: raise JsonableError(_("Invalid subdomain")) return login_or_register_remote_user(request, result) def redirect_and_log_into_subdomain(result: ExternalAuthResult) -> HttpResponse: token = result.store_data() realm = get_realm(result.data_dict["subdomain"]) subdomain_login_uri = realm.uri + reverse(log_into_subdomain, args=[token]) return redirect(subdomain_login_uri) def redirect_to_misconfigured_ldap_notice(request: HttpRequest, error_type: int) -> HttpResponse: if error_type == ZulipLDAPAuthBackend.REALM_IS_NONE_ERROR: return config_error(request, "ldap") else: raise AssertionError("Invalid error type") def show_deactivation_notice(request: HttpRequest) -> HttpResponse: realm = get_realm_from_request(request) if realm and realm.deactivated: context = {"deactivated_domain_name": realm.name} if realm.deactivated_redirect is not None: context["deactivated_redirect"] = realm.deactivated_redirect return render(request, "zerver/deactivated.html", context=context) return HttpResponseRedirect(reverse("login_page")) def redirect_to_deactivation_notice() -> HttpResponse: return HttpResponseRedirect(reverse(show_deactivation_notice)) def update_login_page_context(request: HttpRequest, context: Dict[str, Any]) -> None: for key in ("email", "already_registered"): try: context[key] = request.GET[key] except KeyError: pass deactivated_email = request.GET.get("is_deactivated") if deactivated_email is None: return try: validate_email(deactivated_email) context["deactivated_account_error"] = mark_safe( DEACTIVATED_ACCOUNT_ERROR.format(username=escape(deactivated_email)) ) except ValidationError: logging.info("Invalid email in is_deactivated param to login page: %s", deactivated_email) class TwoFactorLoginView(BaseTwoFactorLoginView): extra_context: ExtraContext = None form_list = ( ("auth", OurAuthenticationForm), ("token", AuthenticationTokenForm), ("backup", BackupTokenForm), ) def __init__(self, extra_context: ExtraContext = None, *args: Any, **kwargs: Any) -> None: self.extra_context = extra_context super().__init__(*args, **kwargs) def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) if self.extra_context is not None: context.update(self.extra_context) update_login_page_context(self.request, context) realm = get_realm_from_request(self.request) redirect_to = realm.uri if realm else "/" context["next"] = self.request.POST.get( "next", self.request.GET.get("next", redirect_to), ) return context def done(self, form_list: List[Form], **kwargs: Any) -> HttpResponse: """ Log in the user and redirect to the desired page. We need to override this function so that we can redirect to realm.uri instead of '/'. """ realm_uri = self.get_user().realm.uri # This mock.patch business is an unpleasant hack that we'd # ideally like to remove by instead patching the upstream # module to support better configurability of the # LOGIN_REDIRECT_URL setting. But until then, it works. We # import mock.patch here because mock has an expensive import # process involving pbr -> pkgresources (which is really slow). from unittest.mock import patch with patch.object(settings, "LOGIN_REDIRECT_URL", realm_uri): return super().done(form_list, **kwargs) @has_request_variables def login_page( request: HttpRequest, next: str = REQ(default="/"), **kwargs: Any, ) -> HttpResponse: if settings.SOCIAL_AUTH_SUBDOMAIN == get_subdomain(request): return social_auth_subdomain_login_page(request) # To support previewing the Zulip login pages, we have a special option # that disables the default behavior of redirecting logged-in users to the # logged-in app. is_preview = "preview" in request.GET if settings.TWO_FACTOR_AUTHENTICATION_ENABLED: if request.user and request.user.is_verified(): return HttpResponseRedirect(request.user.realm.uri) elif request.user.is_authenticated and not is_preview: return HttpResponseRedirect(request.user.realm.uri) if is_subdomain_root_or_alias(request) and settings.ROOT_DOMAIN_LANDING_PAGE: redirect_url = reverse("realm_redirect") if request.GET: redirect_url = append_url_query_string(redirect_url, request.GET.urlencode()) return HttpResponseRedirect(redirect_url) realm = get_realm_from_request(request) if realm and realm.deactivated: return redirect_to_deactivation_notice() extra_context = kwargs.pop("extra_context", {}) extra_context["next"] = next if dev_auth_enabled() and kwargs.get("template_name") == "zerver/development/dev_login.html": from zerver.views.development.dev_login import add_dev_login_context if "new_realm" in request.POST: try: realm = get_realm(request.POST["new_realm"]) except Realm.DoesNotExist: realm = None add_dev_login_context(realm, extra_context) if realm and "new_realm" in request.POST: # If we're switching realms, redirect to that realm, but # only if it actually exists. return HttpResponseRedirect(realm.uri) if "username" in request.POST: extra_context["email"] = request.POST["username"] extra_context.update(login_context(request)) if settings.TWO_FACTOR_AUTHENTICATION_ENABLED: return start_two_factor_auth(request, extra_context=extra_context, **kwargs) try: template_response = DjangoLoginView.as_view( authentication_form=OurAuthenticationForm, extra_context=extra_context, **kwargs )(request) except ZulipLDAPConfigurationError as e: assert len(e.args) > 1 return redirect_to_misconfigured_ldap_notice(request, e.args[1]) if isinstance(template_response, SimpleTemplateResponse): # Only those responses that are rendered using a template have # context_data attribute. This attribute doesn't exist otherwise. It is # added in SimpleTemplateResponse class, which is a derived class of # HttpResponse. See django.template.response.SimpleTemplateResponse, # https://github.com/django/django/blob/2.0/django/template/response.py#L19 update_login_page_context(request, template_response.context_data) assert isinstance(template_response, HttpResponse) return template_response def social_auth_subdomain_login_page(request: HttpRequest) -> HttpResponse: origin_subdomain = request.session.get("subdomain") if origin_subdomain is not None: try: origin_realm = get_realm(origin_subdomain) return HttpResponseRedirect(origin_realm.uri) except Realm.DoesNotExist: pass return render(request, "zerver/auth_subdomain.html", status=400) def start_two_factor_auth( request: HttpRequest, extra_context: ExtraContext = None, **kwargs: Any ) -> HttpResponse: two_fa_form_field = "two_factor_login_view-current_step" if two_fa_form_field not in request.POST: # Here we inject the 2FA step in the request context if it's missing to # force the user to go to the first step of 2FA authentication process. # This seems a bit hackish but simplifies things from testing point of # view. I don't think this can result in anything bad because all the # authentication logic runs after the auth step. # # If we don't do this, we will have to modify a lot of auth tests to # insert this variable in the request. request.POST = request.POST.copy() request.POST.update({two_fa_form_field: "auth"}) """ This is how Django implements as_view(), so extra_context will be passed to the __init__ method of TwoFactorLoginView. def as_view(cls, **initkwargs): def view(request, *args, **kwargs): self = cls(**initkwargs) ... return view """ two_fa_view = TwoFactorLoginView.as_view(extra_context=extra_context, **kwargs) return two_fa_view(request, **kwargs) @csrf_exempt @require_post @has_request_variables def api_fetch_api_key( request: HttpRequest, username: str = REQ(), password: str = REQ() ) -> HttpResponse: return_data: Dict[str, bool] = {} realm = get_realm_from_request(request) if realm is None: raise InvalidSubdomainError() if not ldap_auth_enabled(realm=realm): # In case we don't authenticate against LDAP, check for a valid # email. LDAP backend can authenticate against a non-email. validate_login_email(username) user_profile = authenticate( request=request, username=username, password=password, realm=realm, return_data=return_data ) if return_data.get("inactive_user"): raise UserDeactivatedError() if return_data.get("inactive_realm"): raise RealmDeactivatedError() if return_data.get("password_auth_disabled"): raise PasswordAuthDisabledError() if return_data.get("password_reset_needed"): raise PasswordResetRequiredError() if user_profile is None: raise AuthenticationFailedError() assert user_profile.is_authenticated # Maybe sending 'user_logged_in' signal is the better approach: # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile) # Not doing this only because over here we don't add the user information # in the session. If the signal receiver assumes that we do then that # would cause problems. email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile) # Mark this request as having a logged-in user for our server logs. process_client(request, user_profile) RequestNotes.get_notes(request).requestor_for_logs = user_profile.format_requestor_for_logs() api_key = get_api_key(user_profile) return json_success({"api_key": api_key, "email": user_profile.delivery_email}) def get_auth_backends_data(request: HttpRequest) -> Dict[str, Any]: """Returns which authentication methods are enabled on the server""" subdomain = get_subdomain(request) try: realm = Realm.objects.get(string_id=subdomain) except Realm.DoesNotExist: # If not the root subdomain, this is an error if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN: raise JsonableError(_("Invalid subdomain")) # With the root subdomain, it's an error or not depending # whether ROOT_DOMAIN_LANDING_PAGE (which indicates whether # there are some realms without subdomains on this server) # is set. if settings.ROOT_DOMAIN_LANDING_PAGE: raise JsonableError(_("Subdomain required")) else: realm = None result = { "password": password_auth_<PASSWORD>(realm), } for auth_backend_name in AUTH_BACKEND_NAME_MAP: key = auth_backend_name.lower() result[key] = auth_enabled_helper([auth_backend_name], realm) return result def check_server_incompatibility(request: HttpRequest) -> bool: user_agent = parse_user_agent(request.META.get("HTTP_USER_AGENT", "Missing User-Agent")) return user_agent["name"] == "ZulipInvalid" @require_safe @csrf_exempt def api_get_server_settings(request: HttpRequest) -> HttpResponse: # Log which client is making this request. process_client(request, request.user, skip_update_user_activity=True) result = dict( authentication_methods=get_auth_backends_data(request), zulip_version=ZULIP_VERSION, zulip_merge_base=ZULIP_MERGE_BASE, zulip_feature_level=API_FEATURE_LEVEL, push_notifications_enabled=push_notifications_enabled(), is_incompatible=check_server_incompatibility(request), ) context = zulip_default_context(request) context.update(login_context(request)) # IMPORTANT NOTE: # realm_name, realm_icon, etc. are not guaranteed to appear in the response. # * If they do, that means the server URL has only one realm on it # * If they don't, the server has multiple realms, and it's not clear which is # the requested realm, so we can't send back these data. for settings_item in [ "email_auth_enabled", "require_email_format_usernames", "realm_uri", "realm_name", "realm_icon", "realm_description", "external_authentication_methods", ]: if context[settings_item] is not None: result[settings_item] = context[settings_item] return json_success(result) @has_request_variables def json_fetch_api_key( request: HttpRequest, user_profile: UserProfile, password: str = REQ(default="") ) -> HttpResponse: realm = get_realm_from_request(request) if realm is None: raise JsonableError(_("Invalid subdomain")) if password_auth_enabled(user_profile.realm): if not authenticate( request=request, username=user_profile.delivery_email, password=password, realm=realm ): raise JsonableError(_("Your username or password is incorrect.")) api_key = get_api_key(user_profile) return json_success({"api_key": api_key, "email": user_profile.delivery_email}) @require_post def logout_then_login(request: HttpRequest, **kwargs: Any) -> HttpResponse: return django_logout_then_login(request, kwargs) def password_reset(request: HttpRequest) -> HttpResponse: if is_subdomain_root_or_alias(request) and settings.ROOT_DOMAIN_LANDING_PAGE: redirect_url = append_url_query_string( reverse("realm_redirect"), urlencode({"next": reverse("password_reset")}) ) return HttpResponseRedirect(redirect_url) try: response = DjangoPasswordResetView.as_view( template_name="zerver/reset.html", form_class=ZulipPasswordResetForm, success_url="/accounts/password/reset/done/", )(request) except RateLimited as e: assert e.secs_to_freedom is not None return render( request, "zerver/rate_limit_exceeded.html", context={"retry_after": int(e.secs_to_freedom)}, status=429, ) assert isinstance(response, HttpResponse) return response @csrf_exempt def saml_sp_metadata(request: HttpRequest, **kwargs: Any) -> HttpResponse: # nocoverage """ This is the view function for generating our SP metadata for SAML authentication. It's meant for helping check the correctness of the configuration when setting up SAML, or for obtaining the XML metadata if the IdP requires it. Taken from https://python-social-auth.readthedocs.io/en/latest/backends/saml.html """ if not saml_auth_enabled(): return config_error(request, "saml") complete_url = reverse("social:complete", args=("saml",)) saml_backend = load_backend(load_strategy(request), "saml", complete_url) metadata, errors = saml_backend.generate_metadata_xml() if not errors: return HttpResponse(content=metadata, content_type="text/xml") return HttpResponseServerError(content=", ".join(errors)) def config_error(request: HttpRequest, error_category_name: str) -> HttpResponse: contexts = { "apple": {"social_backend_name": "apple", "has_markdown_file": True}, "google": {"social_backend_name": "google", "has_markdown_file": True}, "github": {"social_backend_name": "github", "has_markdown_file": True}, "gitlab": {"social_backend_name": "gitlab", "has_markdown_file": True}, "ldap": {"error_name": "ldap_error_realm_is_none"}, "dev": {"error_name": "dev_not_supported_error"}, "saml": {"social_backend_name": "saml"}, "smtp": {"error_name": "smtp_error"}, "remote_user_backend_disabled": {"error_name": "remoteuser_error_backend_disabled"}, "remote_user_header_missing": {"error_name": "remoteuser_error_remote_user_header_missing"}, # TODO: Improve the config error page for OIDC. "oidc": {"error_name": "oidc_error"}, } return render(request, "zerver/config_error.html", contexts[error_category_name])
import logging import secrets import urllib from functools import wraps from typing import Any, Dict, List, Mapping, Optional, cast from urllib.parse import urlencode import jwt from cryptography.hazmat.primitives.ciphers.aead import AESGCM from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.views import LoginView as DjangoLoginView from django.contrib.auth.views import PasswordResetView as DjangoPasswordResetView from django.contrib.auth.views import logout_then_login as django_logout_then_login from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.forms import Form from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.shortcuts import redirect, render from django.template.response import SimpleTemplateResponse from django.urls import reverse from django.utils.html import escape from django.utils.http import url_has_allowed_host_and_scheme from django.utils.translation import gettext as _ from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_safe from jinja2.utils import Markup as mark_safe from social_django.utils import load_backend, load_strategy from two_factor.forms import BackupTokenForm from two_factor.views import LoginView as BaseTwoFactorLoginView from confirmation.models import ( Confirmation, ConfirmationKeyException, create_confirmation_link, get_object_from_key, ) from version import API_FEATURE_LEVEL, ZULIP_MERGE_BASE, ZULIP_VERSION from zerver.context_processors import get_realm_from_request, login_context, zulip_default_context from zerver.decorator import do_login, log_view_func, process_client, require_post from zerver.forms import ( DEACTIVATED_ACCOUNT_ERROR, AuthenticationTokenForm, HomepageForm, OurAuthenticationForm, ZulipPasswordResetForm, ) from zerver.lib.exceptions import ( AuthenticationFailedError, InvalidSubdomainError, JsonableError, PasswordAuthDisabledError, PasswordResetRequiredError, RateLimited, RealmDeactivatedError, UserDeactivatedError, ) from zerver.lib.mobile_auth_otp import otp_encrypt_api_key from zerver.lib.push_notifications import push_notifications_enabled from zerver.lib.pysa import mark_sanitized from zerver.lib.realm_icon import realm_icon_url from zerver.lib.request import REQ, RequestNotes, has_request_variables from zerver.lib.response import json_success from zerver.lib.sessions import set_expirable_session_var from zerver.lib.subdomains import get_subdomain, is_subdomain_root_or_alias from zerver.lib.types import ViewFuncT from zerver.lib.url_encoding import append_url_query_string from zerver.lib.user_agent import parse_user_agent from zerver.lib.users import get_api_key from zerver.lib.utils import has_api_key_format from zerver.lib.validator import validate_login_email from zerver.models import ( MultiuseInvite, PreregistrationUser, Realm, UserProfile, filter_to_valid_prereg_users, get_realm, remote_user_to_email, ) from zerver.signals import email_on_new_login from zproject.backends import ( AUTH_BACKEND_NAME_MAP, AppleAuthBackend, ExternalAuthDataDict, ExternalAuthResult, GenericOpenIdConnectBackend, SAMLAuthBackend, ZulipLDAPAuthBackend, ZulipLDAPConfigurationError, ZulipRemoteUserBackend, auth_enabled_helper, dev_auth_enabled, ldap_auth_enabled, password_auth_enabled, saml_auth_enabled, validate_otp_params, ) ExtraContext = Optional[Dict[str, Any]] def get_safe_redirect_to(url: str, redirect_host: str) -> str: is_url_safe = url_has_allowed_host_and_scheme(url=url, allowed_hosts=None) if is_url_safe: # Mark as safe to prevent Pysa from surfacing false positives for # open redirects. In this branch, we have already checked that the URL # points to the specified 'redirect_host', or is relative. return urllib.parse.urljoin(redirect_host, mark_sanitized(url)) else: return redirect_host def create_preregistration_user( email: str, request: HttpRequest, realm_creation: bool = False, password_required: bool = True, full_name: Optional[str] = None, full_name_validated: bool = False, ) -> PreregistrationUser: realm = None if not realm_creation: try: realm = get_realm(get_subdomain(request)) except Realm.DoesNotExist: pass return PreregistrationUser.objects.create( email=email, realm_creation=realm_creation, password_required=<PASSWORD>, realm=realm, full_name=full_name, full_name_validated=full_name_validated, ) def maybe_send_to_registration( request: HttpRequest, email: str, full_name: str = "", mobile_flow_otp: Optional[str] = None, desktop_flow_otp: Optional[str] = None, is_signup: bool = False, password_required: bool = True, multiuse_object_key: str = "", full_name_validated: bool = False, ) -> HttpResponse: """Given a successful authentication for an email address (i.e. we've confirmed the user controls the email address) that does not currently have a Zulip account in the target realm, send them to the registration flow or the "continue to registration" flow, depending on is_signup, whether the email address can join the organization (checked in HomepageForm), and similar details. """ # In the desktop and mobile registration flows, the sign up # happens in the browser so the user can use their # already-logged-in social accounts. Then at the end, with the # user account created, we pass the appropriate data to the app # via e.g. a `zulip://` redirect. We store the OTP keys for the # mobile/desktop flow in the session with 1-hour expiry, because # we want this configuration of having a successful authentication # result in being logged into the app to persist if the user makes # mistakes while trying to authenticate (E.g. clicks the wrong # Google account, hits back, etc.) during a given browser session, # rather than just logging into the web app in the target browser. # # We can't use our usual pre-account-creation state storage # approach of putting something in PreregistrationUser, because # that would apply to future registration attempts on other # devices, e.g. just creating an account on the web on their laptop. assert not (mobile_flow_otp and desktop_flow_otp) if mobile_flow_otp: set_expirable_session_var( request.session, "registration_mobile_flow_otp", mobile_flow_otp, expiry_seconds=3600 ) elif desktop_flow_otp: set_expirable_session_var( request.session, "registration_desktop_flow_otp", desktop_flow_otp, expiry_seconds=3600 ) multiuse_obj: Optional[MultiuseInvite] = None realm: Optional[Realm] = None from_multiuse_invite = False if multiuse_object_key: from_multiuse_invite = True try: multiuse_obj = get_object_from_key(multiuse_object_key, Confirmation.MULTIUSE_INVITE) except ConfirmationKeyException: return render(request, "zerver/confirmation_link_expired_error.html", status=404) assert multiuse_obj is not None realm = multiuse_obj.realm invited_as = multiuse_obj.invited_as else: try: realm = get_realm(get_subdomain(request)) except Realm.DoesNotExist: pass invited_as = PreregistrationUser.INVITE_AS["MEMBER"] form = HomepageForm({"email": email}, realm=realm, from_multiuse_invite=from_multiuse_invite) if form.is_valid(): # If the email address is allowed to sign up for an account in # this organization, construct a PreregistrationUser and # Confirmation objects, and then send the user to account # creation or confirm-continue-registration depending on # is_signup. try: prereg_user = filter_to_valid_prereg_users( PreregistrationUser.objects.filter(email__iexact=email, realm=realm) ).latest("invited_at") # password_required and full_name data passed here as argument should take precedence # over the defaults with which the existing PreregistrationUser that we've just fetched # was created. prereg_user.password_required = <PASSWORD> update_fields = ["password_required"] if full_name: prereg_user.full_name = full_name prereg_user.full_name_validated = full_name_validated update_fields.extend(["full_name", "full_name_validated"]) prereg_user.save(update_fields=update_fields) except PreregistrationUser.DoesNotExist: prereg_user = create_preregistration_user( email, request, password_required=<PASSWORD>, full_name=full_name, full_name_validated=full_name_validated, ) if multiuse_obj is not None: request.session.modified = True streams_to_subscribe = list(multiuse_obj.streams.all()) prereg_user.streams.set(streams_to_subscribe) prereg_user.invited_as = invited_as prereg_user.save() confirmation_link = create_confirmation_link(prereg_user, Confirmation.USER_REGISTRATION) if is_signup: return redirect(confirmation_link) context = {"email": email, "continue_link": confirmation_link, "full_name": full_name} return render(request, "zerver/confirm_continue_registration.html", context=context) # This email address it not allowed to join this organization, so # just send the user back to the registration page. url = reverse("register") context = login_context(request) extra_context: Mapping[str, Any] = { "form": form, "current_url": lambda: url, "from_multiuse_invite": from_multiuse_invite, "multiuse_object_key": multiuse_object_key, "mobile_flow_otp": mobile_flow_otp, "desktop_flow_otp": desktop_flow_otp, } context.update(extra_context) return render(request, "zerver/accounts_home.html", context=context) def register_remote_user(request: HttpRequest, result: ExternalAuthResult) -> HttpResponse: # We have verified the user controls an email address, but # there's no associated Zulip user account. Consider sending # the request to registration. kwargs: Dict[str, Any] = dict(result.data_dict) # maybe_send_to_registration doesn't take these arguments, so delete them. kwargs.pop("subdomain", None) kwargs.pop("redirect_to", None) kwargs.pop("is_realm_creation", None) kwargs["password_required"] = False return maybe_send_to_registration(request, **kwargs) def login_or_register_remote_user(request: HttpRequest, result: ExternalAuthResult) -> HttpResponse: """Given a successful authentication showing the user controls given email address (email) and potentially a UserProfile object (if the user already has a Zulip account), redirect the browser to the appropriate place: * The logged-in app if the user already has a Zulip account and is trying to log in, potentially to an initial narrow or page that had been saved in the `redirect_to` parameter. * The registration form if is_signup was set (i.e. the user is trying to create a Zulip account) * A special `confirm_continue_registration.html` "do you want to register or try another account" if the user doesn't have a Zulip account but is_signup is False (i.e. the user tried to log in and then did social authentication selecting an email address that does not have a Zulip account in this organization). * A zulip:// URL to send control back to the mobile or desktop apps if they are doing authentication using the mobile_flow_otp or desktop_flow_otp flow. """ user_profile = result.user_profile if user_profile is None or user_profile.is_mirror_dummy: return register_remote_user(request, result) # Otherwise, the user has successfully authenticated to an # account, and we need to do the right thing depending whether # or not they're using the mobile OTP flow or want a browser session. is_realm_creation = result.data_dict.get("is_realm_creation") mobile_flow_otp = result.data_dict.get("mobile_flow_otp") desktop_flow_otp = result.data_dict.get("desktop_flow_otp") if mobile_flow_otp is not None: return finish_mobile_flow(request, user_profile, mobile_flow_otp) elif desktop_flow_otp is not None: return finish_desktop_flow(request, user_profile, desktop_flow_otp) do_login(request, user_profile) redirect_to = result.data_dict.get("redirect_to", "") if is_realm_creation is not None and settings.BILLING_ENABLED: from corporate.lib.stripe import is_free_trial_offer_enabled if is_free_trial_offer_enabled(): redirect_to = "{}?onboarding=true".format(reverse("initial_upgrade")) redirect_to = get_safe_redirect_to(redirect_to, user_profile.realm.uri) return HttpResponseRedirect(redirect_to) def finish_desktop_flow(request: HttpRequest, user_profile: UserProfile, otp: str) -> HttpResponse: """ The desktop otp flow returns to the app (through the clipboard) a token that allows obtaining (through log_into_subdomain) a logged in session for the user account we authenticated in this flow. The token can only be used once and within ExternalAuthResult.LOGIN_KEY_EXPIRATION_SECONDS of being created, as nothing more powerful is needed for the desktop flow and this ensures the key can only be used for completing this authentication attempt. """ result = ExternalAuthResult(user_profile=user_profile) token = result.store_data() key = bytes.fromhex(otp) iv = secrets.token_bytes(12) desktop_data = (iv + AESGCM(key).encrypt(iv, token.encode(), b"")).hex() context = { "desktop_data": desktop_data, "browser_url": reverse("login_page", kwargs={"template_name": "zerver/login.html"}), "realm_icon_url": realm_icon_url(user_profile.realm), } return render(request, "zerver/desktop_redirect.html", context=context) def finish_mobile_flow(request: HttpRequest, user_profile: UserProfile, otp: str) -> HttpResponse: # For the mobile OAuth flow, we send the API key and other # necessary details in a redirect to a zulip:// URI scheme. api_key = get_api_key(user_profile) response = create_response_for_otp_flow( api_key, otp, user_profile, encrypted_key_field_name="otp_encrypted_api_key" ) # Since we are returning an API key instead of going through # the Django login() function (which creates a browser # session, etc.), the "new login" signal handler (which # triggers an email notification new logins) will not run # automatically. So we call it manually here. # # Arguably, sending a fake 'user_logged_in' signal would be a better approach: # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile) email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile) # Mark this request as having a logged-in user for our server logs. process_client(request, user_profile) RequestNotes.get_notes(request).requestor_for_logs = user_profile.format_requestor_for_logs() return response def create_response_for_otp_flow( key: str, otp: str, user_profile: UserProfile, encrypted_key_field_name: str ) -> HttpResponse: realm_uri = user_profile.realm.uri # Check if the mobile URI is overridden in settings, if so, replace it # This block should only apply to the mobile flow, so we if add others, this # needs to be conditional. if realm_uri in settings.REALM_MOBILE_REMAP_URIS: realm_uri = settings.REALM_MOBILE_REMAP_URIS[realm_uri] params = { encrypted_key_field_name: otp_encrypt_api_key(key, otp), "email": user_profile.delivery_email, "realm": realm_uri, } # We can't use HttpResponseRedirect, since it only allows HTTP(S) URLs response = HttpResponse(status=302) response["Location"] = append_url_query_string("zulip://login", urllib.parse.urlencode(params)) return response @log_view_func @has_request_variables def remote_user_sso( request: HttpRequest, mobile_flow_otp: Optional[str] = REQ(default=None), desktop_flow_otp: Optional[str] = REQ(default=None), next: str = REQ(default="/"), ) -> HttpResponse: subdomain = get_subdomain(request) try: realm: Optional[Realm] = get_realm(subdomain) except Realm.DoesNotExist: realm = None if not auth_enabled_helper([ZulipRemoteUserBackend.auth_backend_name], realm): return config_error(request, "remote_user_backend_disabled") try: remote_user = request.META["REMOTE_USER"] except KeyError: return config_error(request, "remote_user_header_missing") # Django invokes authenticate methods by matching arguments, and this # authentication flow will not invoke LDAP authentication because of # this condition of Django so no need to check if LDAP backend is # enabled. validate_login_email(remote_user_to_email(remote_user)) # Here we support the mobile and desktop flow for REMOTE_USER_BACKEND; we # validate the data format and then pass it through to # login_or_register_remote_user if appropriate. validate_otp_params(mobile_flow_otp, desktop_flow_otp) if realm is None: user_profile = None else: user_profile = authenticate(remote_user=remote_user, realm=realm) email = remote_user_to_email(remote_user) data_dict = ExternalAuthDataDict( email=email, mobile_flow_otp=mobile_flow_otp, desktop_flow_otp=desktop_flow_otp, redirect_to=next, ) if realm: data_dict["subdomain"] = realm.subdomain else: data_dict["subdomain"] = "" # realm creation happens on root subdomain result = ExternalAuthResult(user_profile=user_profile, data_dict=data_dict) return login_or_register_remote_user(request, result) @csrf_exempt @log_view_func def remote_user_jwt(request: HttpRequest) -> HttpResponse: subdomain = get_subdomain(request) try: key = settings.JWT_AUTH_KEYS[subdomain]["key"] algorithms = settings.JWT_AUTH_KEYS[subdomain]["algorithms"] except KeyError: raise JsonableError(_("Auth key for this subdomain not found.")) try: json_web_token = request.POST["json_web_token"] options = {"verify_signature": True} payload = jwt.decode(json_web_token, key, algorithms=algorithms, options=options) except KeyError: raise JsonableError(_("No JSON web token passed in request")) except jwt.InvalidTokenError: raise JsonableError(_("Bad JSON web token")) remote_user = payload.get("user", None) if remote_user is None: raise JsonableError(_("No user specified in JSON web token claims")) email_domain = payload.get("realm", None) if email_domain is None: raise JsonableError(_("No organization specified in JSON web token claims")) email = f"{remote_user}@{email_domain}" try: realm = get_realm(subdomain) except Realm.DoesNotExist: raise JsonableError(_("Wrong subdomain")) user_profile = authenticate(username=email, realm=realm, use_dummy_backend=True) if user_profile is None: result = ExternalAuthResult( data_dict={"email": email, "full_name": remote_user, "subdomain": realm.subdomain} ) else: result = ExternalAuthResult(user_profile=user_profile) return login_or_register_remote_user(request, result) @has_request_variables def oauth_redirect_to_root( request: HttpRequest, url: str, sso_type: str, is_signup: bool = False, extra_url_params: Dict[str, str] = {}, next: Optional[str] = REQ(default=None), multiuse_object_key: str = REQ(default=""), mobile_flow_otp: Optional[str] = REQ(default=None), desktop_flow_otp: Optional[str] = REQ(default=None), ) -> HttpResponse: main_site_uri = settings.ROOT_DOMAIN_URI + url if settings.SOCIAL_AUTH_SUBDOMAIN is not None and sso_type == "social": main_site_uri = ( settings.EXTERNAL_URI_SCHEME + settings.SOCIAL_AUTH_SUBDOMAIN + "." + settings.EXTERNAL_HOST ) + url params = { "subdomain": get_subdomain(request), "is_signup": "1" if is_signup else "0", } params["multiuse_object_key"] = multiuse_object_key # mobile_flow_otp is a one-time pad provided by the app that we # can use to encrypt the API key when passing back to the app. validate_otp_params(mobile_flow_otp, desktop_flow_otp) if mobile_flow_otp is not None: params["mobile_flow_otp"] = mobile_flow_otp if desktop_flow_otp is not None: params["desktop_flow_otp"] = desktop_flow_otp if next: params["next"] = next params = {**params, **extra_url_params} return redirect(append_url_query_string(main_site_uri, urllib.parse.urlencode(params))) def handle_desktop_flow(func: ViewFuncT) -> ViewFuncT: @wraps(func) def wrapper(request: HttpRequest, *args: object, **kwargs: object) -> HttpResponse: user_agent = parse_user_agent(request.META.get("HTTP_USER_AGENT", "Missing User-Agent")) if user_agent["name"] == "ZulipElectron": return render(request, "zerver/desktop_login.html") return func(request, *args, **kwargs) return cast(ViewFuncT, wrapper) # https://github.com/python/mypy/issues/1927 @handle_desktop_flow def start_remote_user_sso(request: HttpRequest) -> HttpResponse: """ The purpose of this endpoint is to provide an initial step in the flow on which we can handle the special behavior for the desktop app. /accounts/login/sso may have Apache intercepting requests to it to do authentication, so we need this additional endpoint. """ query = request.META["QUERY_STRING"] return redirect(append_url_query_string(reverse(remote_user_sso), query)) @handle_desktop_flow def start_social_login( request: HttpRequest, backend: str, extra_arg: Optional[str] = None, ) -> HttpResponse: backend_url = reverse("social:begin", args=[backend]) extra_url_params: Dict[str, str] = {} if backend == "saml": if not SAMLAuthBackend.check_config(): return config_error(request, "saml") # This backend requires the name of the IdP (from the list of configured ones) # to be passed as the parameter. if not extra_arg or extra_arg not in settings.SOCIAL_AUTH_SAML_ENABLED_IDPS: logging.info( "Attempted to initiate SAML authentication with wrong idp argument: %s", extra_arg ) return config_error(request, "saml") extra_url_params = {"idp": extra_arg} if backend == "apple" and not AppleAuthBackend.check_config(): return config_error(request, "apple") if backend == "oidc" and not GenericOpenIdConnectBackend.check_config(): return config_error(request, "oidc") # TODO: Add AzureAD also. if backend in ["github", "google", "gitlab"]: key_setting = "SOCIAL_AUTH_" + backend.upper() + "_KEY" secret_setting = "SOCIAL_AUTH_" + backend.upper() + "_SECRET" if not (getattr(settings, key_setting) and getattr(settings, secret_setting)): return config_error(request, backend) return oauth_redirect_to_root(request, backend_url, "social", extra_url_params=extra_url_params) @handle_desktop_flow def start_social_signup( request: HttpRequest, backend: str, extra_arg: Optional[str] = None, ) -> HttpResponse: backend_url = reverse("social:begin", args=[backend]) extra_url_params: Dict[str, str] = {} if backend == "saml": if not SAMLAuthBackend.check_config(): return config_error(request, "saml") if not extra_arg or extra_arg not in settings.SOCIAL_AUTH_SAML_ENABLED_IDPS: logging.info( "Attempted to initiate SAML authentication with wrong idp argument: %s", extra_arg ) return config_error(request, "saml") extra_url_params = {"idp": extra_arg} return oauth_redirect_to_root( request, backend_url, "social", is_signup=True, extra_url_params=extra_url_params ) _subdomain_token_salt = "zerver.views.auth.log_into_subdomain" @log_view_func def log_into_subdomain(request: HttpRequest, token: str) -> HttpResponse: """Given a valid authentication token (generated by redirect_and_log_into_subdomain called on auth.zulip.example.com), call login_or_register_remote_user, passing all the authentication result data that has been stored in Redis, associated with this token. """ # The tokens are intended to have the same format as API keys. if not has_api_key_format(token): logging.warning("log_into_subdomain: Malformed token given: %s", token) return HttpResponse(status=400) try: result = ExternalAuthResult(login_token=token) except ExternalAuthResult.InvalidTokenError: logging.warning("log_into_subdomain: Invalid token given: %s", token) return render(request, "zerver/log_into_subdomain_token_invalid.html", status=400) subdomain = get_subdomain(request) if result.data_dict["subdomain"] != subdomain: raise JsonableError(_("Invalid subdomain")) return login_or_register_remote_user(request, result) def redirect_and_log_into_subdomain(result: ExternalAuthResult) -> HttpResponse: token = result.store_data() realm = get_realm(result.data_dict["subdomain"]) subdomain_login_uri = realm.uri + reverse(log_into_subdomain, args=[token]) return redirect(subdomain_login_uri) def redirect_to_misconfigured_ldap_notice(request: HttpRequest, error_type: int) -> HttpResponse: if error_type == ZulipLDAPAuthBackend.REALM_IS_NONE_ERROR: return config_error(request, "ldap") else: raise AssertionError("Invalid error type") def show_deactivation_notice(request: HttpRequest) -> HttpResponse: realm = get_realm_from_request(request) if realm and realm.deactivated: context = {"deactivated_domain_name": realm.name} if realm.deactivated_redirect is not None: context["deactivated_redirect"] = realm.deactivated_redirect return render(request, "zerver/deactivated.html", context=context) return HttpResponseRedirect(reverse("login_page")) def redirect_to_deactivation_notice() -> HttpResponse: return HttpResponseRedirect(reverse(show_deactivation_notice)) def update_login_page_context(request: HttpRequest, context: Dict[str, Any]) -> None: for key in ("email", "already_registered"): try: context[key] = request.GET[key] except KeyError: pass deactivated_email = request.GET.get("is_deactivated") if deactivated_email is None: return try: validate_email(deactivated_email) context["deactivated_account_error"] = mark_safe( DEACTIVATED_ACCOUNT_ERROR.format(username=escape(deactivated_email)) ) except ValidationError: logging.info("Invalid email in is_deactivated param to login page: %s", deactivated_email) class TwoFactorLoginView(BaseTwoFactorLoginView): extra_context: ExtraContext = None form_list = ( ("auth", OurAuthenticationForm), ("token", AuthenticationTokenForm), ("backup", BackupTokenForm), ) def __init__(self, extra_context: ExtraContext = None, *args: Any, **kwargs: Any) -> None: self.extra_context = extra_context super().__init__(*args, **kwargs) def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) if self.extra_context is not None: context.update(self.extra_context) update_login_page_context(self.request, context) realm = get_realm_from_request(self.request) redirect_to = realm.uri if realm else "/" context["next"] = self.request.POST.get( "next", self.request.GET.get("next", redirect_to), ) return context def done(self, form_list: List[Form], **kwargs: Any) -> HttpResponse: """ Log in the user and redirect to the desired page. We need to override this function so that we can redirect to realm.uri instead of '/'. """ realm_uri = self.get_user().realm.uri # This mock.patch business is an unpleasant hack that we'd # ideally like to remove by instead patching the upstream # module to support better configurability of the # LOGIN_REDIRECT_URL setting. But until then, it works. We # import mock.patch here because mock has an expensive import # process involving pbr -> pkgresources (which is really slow). from unittest.mock import patch with patch.object(settings, "LOGIN_REDIRECT_URL", realm_uri): return super().done(form_list, **kwargs) @has_request_variables def login_page( request: HttpRequest, next: str = REQ(default="/"), **kwargs: Any, ) -> HttpResponse: if settings.SOCIAL_AUTH_SUBDOMAIN == get_subdomain(request): return social_auth_subdomain_login_page(request) # To support previewing the Zulip login pages, we have a special option # that disables the default behavior of redirecting logged-in users to the # logged-in app. is_preview = "preview" in request.GET if settings.TWO_FACTOR_AUTHENTICATION_ENABLED: if request.user and request.user.is_verified(): return HttpResponseRedirect(request.user.realm.uri) elif request.user.is_authenticated and not is_preview: return HttpResponseRedirect(request.user.realm.uri) if is_subdomain_root_or_alias(request) and settings.ROOT_DOMAIN_LANDING_PAGE: redirect_url = reverse("realm_redirect") if request.GET: redirect_url = append_url_query_string(redirect_url, request.GET.urlencode()) return HttpResponseRedirect(redirect_url) realm = get_realm_from_request(request) if realm and realm.deactivated: return redirect_to_deactivation_notice() extra_context = kwargs.pop("extra_context", {}) extra_context["next"] = next if dev_auth_enabled() and kwargs.get("template_name") == "zerver/development/dev_login.html": from zerver.views.development.dev_login import add_dev_login_context if "new_realm" in request.POST: try: realm = get_realm(request.POST["new_realm"]) except Realm.DoesNotExist: realm = None add_dev_login_context(realm, extra_context) if realm and "new_realm" in request.POST: # If we're switching realms, redirect to that realm, but # only if it actually exists. return HttpResponseRedirect(realm.uri) if "username" in request.POST: extra_context["email"] = request.POST["username"] extra_context.update(login_context(request)) if settings.TWO_FACTOR_AUTHENTICATION_ENABLED: return start_two_factor_auth(request, extra_context=extra_context, **kwargs) try: template_response = DjangoLoginView.as_view( authentication_form=OurAuthenticationForm, extra_context=extra_context, **kwargs )(request) except ZulipLDAPConfigurationError as e: assert len(e.args) > 1 return redirect_to_misconfigured_ldap_notice(request, e.args[1]) if isinstance(template_response, SimpleTemplateResponse): # Only those responses that are rendered using a template have # context_data attribute. This attribute doesn't exist otherwise. It is # added in SimpleTemplateResponse class, which is a derived class of # HttpResponse. See django.template.response.SimpleTemplateResponse, # https://github.com/django/django/blob/2.0/django/template/response.py#L19 update_login_page_context(request, template_response.context_data) assert isinstance(template_response, HttpResponse) return template_response def social_auth_subdomain_login_page(request: HttpRequest) -> HttpResponse: origin_subdomain = request.session.get("subdomain") if origin_subdomain is not None: try: origin_realm = get_realm(origin_subdomain) return HttpResponseRedirect(origin_realm.uri) except Realm.DoesNotExist: pass return render(request, "zerver/auth_subdomain.html", status=400) def start_two_factor_auth( request: HttpRequest, extra_context: ExtraContext = None, **kwargs: Any ) -> HttpResponse: two_fa_form_field = "two_factor_login_view-current_step" if two_fa_form_field not in request.POST: # Here we inject the 2FA step in the request context if it's missing to # force the user to go to the first step of 2FA authentication process. # This seems a bit hackish but simplifies things from testing point of # view. I don't think this can result in anything bad because all the # authentication logic runs after the auth step. # # If we don't do this, we will have to modify a lot of auth tests to # insert this variable in the request. request.POST = request.POST.copy() request.POST.update({two_fa_form_field: "auth"}) """ This is how Django implements as_view(), so extra_context will be passed to the __init__ method of TwoFactorLoginView. def as_view(cls, **initkwargs): def view(request, *args, **kwargs): self = cls(**initkwargs) ... return view """ two_fa_view = TwoFactorLoginView.as_view(extra_context=extra_context, **kwargs) return two_fa_view(request, **kwargs) @csrf_exempt @require_post @has_request_variables def api_fetch_api_key( request: HttpRequest, username: str = REQ(), password: str = REQ() ) -> HttpResponse: return_data: Dict[str, bool] = {} realm = get_realm_from_request(request) if realm is None: raise InvalidSubdomainError() if not ldap_auth_enabled(realm=realm): # In case we don't authenticate against LDAP, check for a valid # email. LDAP backend can authenticate against a non-email. validate_login_email(username) user_profile = authenticate( request=request, username=username, password=password, realm=realm, return_data=return_data ) if return_data.get("inactive_user"): raise UserDeactivatedError() if return_data.get("inactive_realm"): raise RealmDeactivatedError() if return_data.get("password_auth_disabled"): raise PasswordAuthDisabledError() if return_data.get("password_reset_needed"): raise PasswordResetRequiredError() if user_profile is None: raise AuthenticationFailedError() assert user_profile.is_authenticated # Maybe sending 'user_logged_in' signal is the better approach: # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile) # Not doing this only because over here we don't add the user information # in the session. If the signal receiver assumes that we do then that # would cause problems. email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile) # Mark this request as having a logged-in user for our server logs. process_client(request, user_profile) RequestNotes.get_notes(request).requestor_for_logs = user_profile.format_requestor_for_logs() api_key = get_api_key(user_profile) return json_success({"api_key": api_key, "email": user_profile.delivery_email}) def get_auth_backends_data(request: HttpRequest) -> Dict[str, Any]: """Returns which authentication methods are enabled on the server""" subdomain = get_subdomain(request) try: realm = Realm.objects.get(string_id=subdomain) except Realm.DoesNotExist: # If not the root subdomain, this is an error if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN: raise JsonableError(_("Invalid subdomain")) # With the root subdomain, it's an error or not depending # whether ROOT_DOMAIN_LANDING_PAGE (which indicates whether # there are some realms without subdomains on this server) # is set. if settings.ROOT_DOMAIN_LANDING_PAGE: raise JsonableError(_("Subdomain required")) else: realm = None result = { "password": password_auth_<PASSWORD>(realm), } for auth_backend_name in AUTH_BACKEND_NAME_MAP: key = auth_backend_name.lower() result[key] = auth_enabled_helper([auth_backend_name], realm) return result def check_server_incompatibility(request: HttpRequest) -> bool: user_agent = parse_user_agent(request.META.get("HTTP_USER_AGENT", "Missing User-Agent")) return user_agent["name"] == "ZulipInvalid" @require_safe @csrf_exempt def api_get_server_settings(request: HttpRequest) -> HttpResponse: # Log which client is making this request. process_client(request, request.user, skip_update_user_activity=True) result = dict( authentication_methods=get_auth_backends_data(request), zulip_version=ZULIP_VERSION, zulip_merge_base=ZULIP_MERGE_BASE, zulip_feature_level=API_FEATURE_LEVEL, push_notifications_enabled=push_notifications_enabled(), is_incompatible=check_server_incompatibility(request), ) context = zulip_default_context(request) context.update(login_context(request)) # IMPORTANT NOTE: # realm_name, realm_icon, etc. are not guaranteed to appear in the response. # * If they do, that means the server URL has only one realm on it # * If they don't, the server has multiple realms, and it's not clear which is # the requested realm, so we can't send back these data. for settings_item in [ "email_auth_enabled", "require_email_format_usernames", "realm_uri", "realm_name", "realm_icon", "realm_description", "external_authentication_methods", ]: if context[settings_item] is not None: result[settings_item] = context[settings_item] return json_success(result) @has_request_variables def json_fetch_api_key( request: HttpRequest, user_profile: UserProfile, password: str = REQ(default="") ) -> HttpResponse: realm = get_realm_from_request(request) if realm is None: raise JsonableError(_("Invalid subdomain")) if password_auth_enabled(user_profile.realm): if not authenticate( request=request, username=user_profile.delivery_email, password=password, realm=realm ): raise JsonableError(_("Your username or password is incorrect.")) api_key = get_api_key(user_profile) return json_success({"api_key": api_key, "email": user_profile.delivery_email}) @require_post def logout_then_login(request: HttpRequest, **kwargs: Any) -> HttpResponse: return django_logout_then_login(request, kwargs) def password_reset(request: HttpRequest) -> HttpResponse: if is_subdomain_root_or_alias(request) and settings.ROOT_DOMAIN_LANDING_PAGE: redirect_url = append_url_query_string( reverse("realm_redirect"), urlencode({"next": reverse("password_reset")}) ) return HttpResponseRedirect(redirect_url) try: response = DjangoPasswordResetView.as_view( template_name="zerver/reset.html", form_class=ZulipPasswordResetForm, success_url="/accounts/password/reset/done/", )(request) except RateLimited as e: assert e.secs_to_freedom is not None return render( request, "zerver/rate_limit_exceeded.html", context={"retry_after": int(e.secs_to_freedom)}, status=429, ) assert isinstance(response, HttpResponse) return response @csrf_exempt def saml_sp_metadata(request: HttpRequest, **kwargs: Any) -> HttpResponse: # nocoverage """ This is the view function for generating our SP metadata for SAML authentication. It's meant for helping check the correctness of the configuration when setting up SAML, or for obtaining the XML metadata if the IdP requires it. Taken from https://python-social-auth.readthedocs.io/en/latest/backends/saml.html """ if not saml_auth_enabled(): return config_error(request, "saml") complete_url = reverse("social:complete", args=("saml",)) saml_backend = load_backend(load_strategy(request), "saml", complete_url) metadata, errors = saml_backend.generate_metadata_xml() if not errors: return HttpResponse(content=metadata, content_type="text/xml") return HttpResponseServerError(content=", ".join(errors)) def config_error(request: HttpRequest, error_category_name: str) -> HttpResponse: contexts = { "apple": {"social_backend_name": "apple", "has_markdown_file": True}, "google": {"social_backend_name": "google", "has_markdown_file": True}, "github": {"social_backend_name": "github", "has_markdown_file": True}, "gitlab": {"social_backend_name": "gitlab", "has_markdown_file": True}, "ldap": {"error_name": "ldap_error_realm_is_none"}, "dev": {"error_name": "dev_not_supported_error"}, "saml": {"social_backend_name": "saml"}, "smtp": {"error_name": "smtp_error"}, "remote_user_backend_disabled": {"error_name": "remoteuser_error_backend_disabled"}, "remote_user_header_missing": {"error_name": "remoteuser_error_remote_user_header_missing"}, # TODO: Improve the config error page for OIDC. "oidc": {"error_name": "oidc_error"}, } return render(request, "zerver/config_error.html", contexts[error_category_name])
en
0.872089
# Mark as safe to prevent Pysa from surfacing false positives for # open redirects. In this branch, we have already checked that the URL # points to the specified 'redirect_host', or is relative. Given a successful authentication for an email address (i.e. we've confirmed the user controls the email address) that does not currently have a Zulip account in the target realm, send them to the registration flow or the "continue to registration" flow, depending on is_signup, whether the email address can join the organization (checked in HomepageForm), and similar details. # In the desktop and mobile registration flows, the sign up # happens in the browser so the user can use their # already-logged-in social accounts. Then at the end, with the # user account created, we pass the appropriate data to the app # via e.g. a `zulip://` redirect. We store the OTP keys for the # mobile/desktop flow in the session with 1-hour expiry, because # we want this configuration of having a successful authentication # result in being logged into the app to persist if the user makes # mistakes while trying to authenticate (E.g. clicks the wrong # Google account, hits back, etc.) during a given browser session, # rather than just logging into the web app in the target browser. # # We can't use our usual pre-account-creation state storage # approach of putting something in PreregistrationUser, because # that would apply to future registration attempts on other # devices, e.g. just creating an account on the web on their laptop. # If the email address is allowed to sign up for an account in # this organization, construct a PreregistrationUser and # Confirmation objects, and then send the user to account # creation or confirm-continue-registration depending on # is_signup. # password_required and full_name data passed here as argument should take precedence # over the defaults with which the existing PreregistrationUser that we've just fetched # was created. # This email address it not allowed to join this organization, so # just send the user back to the registration page. # We have verified the user controls an email address, but # there's no associated Zulip user account. Consider sending # the request to registration. # maybe_send_to_registration doesn't take these arguments, so delete them. Given a successful authentication showing the user controls given email address (email) and potentially a UserProfile object (if the user already has a Zulip account), redirect the browser to the appropriate place: * The logged-in app if the user already has a Zulip account and is trying to log in, potentially to an initial narrow or page that had been saved in the `redirect_to` parameter. * The registration form if is_signup was set (i.e. the user is trying to create a Zulip account) * A special `confirm_continue_registration.html` "do you want to register or try another account" if the user doesn't have a Zulip account but is_signup is False (i.e. the user tried to log in and then did social authentication selecting an email address that does not have a Zulip account in this organization). * A zulip:// URL to send control back to the mobile or desktop apps if they are doing authentication using the mobile_flow_otp or desktop_flow_otp flow. # Otherwise, the user has successfully authenticated to an # account, and we need to do the right thing depending whether # or not they're using the mobile OTP flow or want a browser session. The desktop otp flow returns to the app (through the clipboard) a token that allows obtaining (through log_into_subdomain) a logged in session for the user account we authenticated in this flow. The token can only be used once and within ExternalAuthResult.LOGIN_KEY_EXPIRATION_SECONDS of being created, as nothing more powerful is needed for the desktop flow and this ensures the key can only be used for completing this authentication attempt. # For the mobile OAuth flow, we send the API key and other # necessary details in a redirect to a zulip:// URI scheme. # Since we are returning an API key instead of going through # the Django login() function (which creates a browser # session, etc.), the "new login" signal handler (which # triggers an email notification new logins) will not run # automatically. So we call it manually here. # # Arguably, sending a fake 'user_logged_in' signal would be a better approach: # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile) # Mark this request as having a logged-in user for our server logs. # Check if the mobile URI is overridden in settings, if so, replace it # This block should only apply to the mobile flow, so we if add others, this # needs to be conditional. # We can't use HttpResponseRedirect, since it only allows HTTP(S) URLs # Django invokes authenticate methods by matching arguments, and this # authentication flow will not invoke LDAP authentication because of # this condition of Django so no need to check if LDAP backend is # enabled. # Here we support the mobile and desktop flow for REMOTE_USER_BACKEND; we # validate the data format and then pass it through to # login_or_register_remote_user if appropriate. # realm creation happens on root subdomain # mobile_flow_otp is a one-time pad provided by the app that we # can use to encrypt the API key when passing back to the app. # https://github.com/python/mypy/issues/1927 The purpose of this endpoint is to provide an initial step in the flow on which we can handle the special behavior for the desktop app. /accounts/login/sso may have Apache intercepting requests to it to do authentication, so we need this additional endpoint. # This backend requires the name of the IdP (from the list of configured ones) # to be passed as the parameter. # TODO: Add AzureAD also. Given a valid authentication token (generated by redirect_and_log_into_subdomain called on auth.zulip.example.com), call login_or_register_remote_user, passing all the authentication result data that has been stored in Redis, associated with this token. # The tokens are intended to have the same format as API keys. Log in the user and redirect to the desired page. We need to override this function so that we can redirect to realm.uri instead of '/'. # This mock.patch business is an unpleasant hack that we'd # ideally like to remove by instead patching the upstream # module to support better configurability of the # LOGIN_REDIRECT_URL setting. But until then, it works. We # import mock.patch here because mock has an expensive import # process involving pbr -> pkgresources (which is really slow). # To support previewing the Zulip login pages, we have a special option # that disables the default behavior of redirecting logged-in users to the # logged-in app. # If we're switching realms, redirect to that realm, but # only if it actually exists. # Only those responses that are rendered using a template have # context_data attribute. This attribute doesn't exist otherwise. It is # added in SimpleTemplateResponse class, which is a derived class of # HttpResponse. See django.template.response.SimpleTemplateResponse, # https://github.com/django/django/blob/2.0/django/template/response.py#L19 # Here we inject the 2FA step in the request context if it's missing to # force the user to go to the first step of 2FA authentication process. # This seems a bit hackish but simplifies things from testing point of # view. I don't think this can result in anything bad because all the # authentication logic runs after the auth step. # # If we don't do this, we will have to modify a lot of auth tests to # insert this variable in the request. This is how Django implements as_view(), so extra_context will be passed to the __init__ method of TwoFactorLoginView. def as_view(cls, **initkwargs): def view(request, *args, **kwargs): self = cls(**initkwargs) ... return view # In case we don't authenticate against LDAP, check for a valid # email. LDAP backend can authenticate against a non-email. # Maybe sending 'user_logged_in' signal is the better approach: # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile) # Not doing this only because over here we don't add the user information # in the session. If the signal receiver assumes that we do then that # would cause problems. # Mark this request as having a logged-in user for our server logs. Returns which authentication methods are enabled on the server # If not the root subdomain, this is an error # With the root subdomain, it's an error or not depending # whether ROOT_DOMAIN_LANDING_PAGE (which indicates whether # there are some realms without subdomains on this server) # is set. # Log which client is making this request. # IMPORTANT NOTE: # realm_name, realm_icon, etc. are not guaranteed to appear in the response. # * If they do, that means the server URL has only one realm on it # * If they don't, the server has multiple realms, and it's not clear which is # the requested realm, so we can't send back these data. # nocoverage This is the view function for generating our SP metadata for SAML authentication. It's meant for helping check the correctness of the configuration when setting up SAML, or for obtaining the XML metadata if the IdP requires it. Taken from https://python-social-auth.readthedocs.io/en/latest/backends/saml.html # TODO: Improve the config error page for OIDC.
1.38864
1
Algorithms/CloudMasking/modis_surface_reflectance_qa_band.py
guy1ziv2/earthengine-py-notebooks
1
6625132
''' <table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td> <td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td> </table> ''' # %% ''' ## Install Earth Engine API Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`. The magic command `%%capture` can be used to hide output from a specific cell. ''' # %% # %%capture # !pip install earthengine-api # !pip install geehydro # %% ''' Import libraries ''' # %% import ee import folium import geehydro # %% ''' Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()` if you are running this notebook for this first time or if you are getting an authentication error. ''' # %% # ee.Authenticate() ee.Initialize() # %% ''' ## Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`. ''' # %% Map = folium.Map(location=[40, -100], zoom_start=4) Map.setOptions('HYBRID') # %% ''' ## Add Earth Engine Python script ''' # %% # Modis Cloud Masking example. # Calculate how frequently a location is labeled as clear (i.e. non-cloudy) # according to the "internal cloud algorithm flag" of the MODIS "state 1km" # QA band. # A function to mask out pixels that did not have observations. # maskEmptyPixels = function(image) { def maskEmptyPixels(image): # Find pixels that had observations. withObs = image.select('num_observations_1km').gt(0) return image.updateMask(withObs) # } # A function to mask out cloudy pixels. # maskClouds = function(image) { def maskClouds(image): # Select the QA band. QA = image.select('state_1km') # Make a mask to get bit 10, the internal_cloud_algorithm_flag bit. bitMask = 1 << 10 # Return an image masking out cloudy areas. return image.updateMask(QA.bitwiseAnd(bitMask).eq(0)) # } # Start with an image collection for a 1 month period. # and mask out areas that were not observed. collection = ee.ImageCollection('MODIS/006/MOD09GA') \ .filterDate('2010-04-01', '2010-05-01') \ .map(maskEmptyPixels) # Get the total number of potential observations for the time interval. totalObsCount = collection \ .select('num_observations_1km') \ .count() # Map the cloud masking function over the collection. collectionCloudMasked = collection.map(maskClouds) # Get the total number of observations for non-cloudy pixels for the time # interval. The result is unmasked to set to unity so that all locations # have counts, and the ratios later computed have values everywhere. clearObsCount = collectionCloudMasked \ .select('num_observations_1km') \ .count() \ .unmask(0) Map.addLayer( collectionCloudMasked.median(), {'bands': ['sur_refl_b01', 'sur_refl_b04', 'sur_refl_b03'], 'gain': 0.07, 'gamma': 1.4 }, 'median of masked collection' ) Map.addLayer( totalObsCount, {'min': 84, 'max': 92}, 'count of total observations', False ) Map.addLayer( clearObsCount, {'min': 0, 'max': 90}, 'count of clear observations', False ) Map.addLayer( clearObsCount.toFloat().divide(totalObsCount), {'min': 0, 'max': 1}, 'ratio of clear to total observations' ) # %% ''' ## Display Earth Engine data layers ''' # %% Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True) Map
''' <table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td> <td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td> </table> ''' # %% ''' ## Install Earth Engine API Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`. The magic command `%%capture` can be used to hide output from a specific cell. ''' # %% # %%capture # !pip install earthengine-api # !pip install geehydro # %% ''' Import libraries ''' # %% import ee import folium import geehydro # %% ''' Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()` if you are running this notebook for this first time or if you are getting an authentication error. ''' # %% # ee.Authenticate() ee.Initialize() # %% ''' ## Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`. ''' # %% Map = folium.Map(location=[40, -100], zoom_start=4) Map.setOptions('HYBRID') # %% ''' ## Add Earth Engine Python script ''' # %% # Modis Cloud Masking example. # Calculate how frequently a location is labeled as clear (i.e. non-cloudy) # according to the "internal cloud algorithm flag" of the MODIS "state 1km" # QA band. # A function to mask out pixels that did not have observations. # maskEmptyPixels = function(image) { def maskEmptyPixels(image): # Find pixels that had observations. withObs = image.select('num_observations_1km').gt(0) return image.updateMask(withObs) # } # A function to mask out cloudy pixels. # maskClouds = function(image) { def maskClouds(image): # Select the QA band. QA = image.select('state_1km') # Make a mask to get bit 10, the internal_cloud_algorithm_flag bit. bitMask = 1 << 10 # Return an image masking out cloudy areas. return image.updateMask(QA.bitwiseAnd(bitMask).eq(0)) # } # Start with an image collection for a 1 month period. # and mask out areas that were not observed. collection = ee.ImageCollection('MODIS/006/MOD09GA') \ .filterDate('2010-04-01', '2010-05-01') \ .map(maskEmptyPixels) # Get the total number of potential observations for the time interval. totalObsCount = collection \ .select('num_observations_1km') \ .count() # Map the cloud masking function over the collection. collectionCloudMasked = collection.map(maskClouds) # Get the total number of observations for non-cloudy pixels for the time # interval. The result is unmasked to set to unity so that all locations # have counts, and the ratios later computed have values everywhere. clearObsCount = collectionCloudMasked \ .select('num_observations_1km') \ .count() \ .unmask(0) Map.addLayer( collectionCloudMasked.median(), {'bands': ['sur_refl_b01', 'sur_refl_b04', 'sur_refl_b03'], 'gain': 0.07, 'gamma': 1.4 }, 'median of masked collection' ) Map.addLayer( totalObsCount, {'min': 84, 'max': 92}, 'count of total observations', False ) Map.addLayer( clearObsCount, {'min': 0, 'max': 90}, 'count of clear observations', False ) Map.addLayer( clearObsCount.toFloat().divide(totalObsCount), {'min': 0, 'max': 1}, 'ratio of clear to total observations' ) # %% ''' ## Display Earth Engine data layers ''' # %% Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True) Map
en
0.610567
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td> <td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td> </table> # %% ## Install Earth Engine API Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`. The magic command `%%capture` can be used to hide output from a specific cell. # %% # %%capture # !pip install earthengine-api # !pip install geehydro # %% Import libraries # %% # %% Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()` if you are running this notebook for this first time or if you are getting an authentication error. # %% # ee.Authenticate() # %% ## Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`. # %% # %% ## Add Earth Engine Python script # %% # Modis Cloud Masking example. # Calculate how frequently a location is labeled as clear (i.e. non-cloudy) # according to the "internal cloud algorithm flag" of the MODIS "state 1km" # QA band. # A function to mask out pixels that did not have observations. # maskEmptyPixels = function(image) { # Find pixels that had observations. # } # A function to mask out cloudy pixels. # maskClouds = function(image) { # Select the QA band. # Make a mask to get bit 10, the internal_cloud_algorithm_flag bit. # Return an image masking out cloudy areas. # } # Start with an image collection for a 1 month period. # and mask out areas that were not observed. # Get the total number of potential observations for the time interval. # Map the cloud masking function over the collection. # Get the total number of observations for non-cloudy pixels for the time # interval. The result is unmasked to set to unity so that all locations # have counts, and the ratios later computed have values everywhere. # %% ## Display Earth Engine data layers # %%
1.248627
1
emails/forms.py
LoveProgramming-Limited/Django-CRM-2
0
6625133
from django import forms from .models import Email class EmailForm(forms.ModelForm): from_email = forms.EmailField(max_length=200, required=True) to_email = forms.EmailField(max_length=200, required=True) subject = forms.CharField(max_length=200, required=True) message = forms.CharField(max_length=200, required=True) class Meta: model = Email fields = ('from_email', 'to_email', 'subject', 'message')
from django import forms from .models import Email class EmailForm(forms.ModelForm): from_email = forms.EmailField(max_length=200, required=True) to_email = forms.EmailField(max_length=200, required=True) subject = forms.CharField(max_length=200, required=True) message = forms.CharField(max_length=200, required=True) class Meta: model = Email fields = ('from_email', 'to_email', 'subject', 'message')
none
1
2.402851
2
test/testSimple.py
18280108415/Interface
0
6625134
<reponame>18280108415/Interface<gh_stars>0 import requests import json import unittest import re import readExcel import json import os path = os.path.dirname(os.getcwd())+"\\data\\C1.2testCase1.xls" testData = readExcel.ReadExcel.readExcel(path, "C12testCase") s = requests.session() class UCTestCase(unittest.TestCase): def test_send_request(self): words= "'error': 0, 'msg': 'success'" res = s.request(method='post', url='https://fanyi.baidu.com/langdetect', headers={'Content-Type':'application/x-www-form-urlencoded','charset':'UTF-8'},params={'query':'I miss you'}, verify=False) #返回的dict类型,str()将dict转换成str re_json=str(res.json()) #type()查看数据类型 print(type(re_json)) #re_json.dump() #print(re_json.dump()) print(res.status_code) self.assertIn(words,re_json,'接口请求失败') def qtest_01_post(self): words = '学会感恩也就学会了快乐' res = s.request(method='get', url='http://www.hjenglish.com/new/p1261643/', headers={'content-type': 'text/html', 'charset': 'utf-8'}, verify=False) #print(re.text) #正则提取里面的文字 htms = re.findall(r"有声双语美文:.*?_沪江英语学习网", res.text) # 通过正则表达式 r"<a.*?>.*?</a>" 找到所有的数据并输出 for item in htms: print(item) #self.assertEqual(200,res.status_code,"接口请求失败") self.assertIn(words,item,'接口请求失败') #self.assertIn(self,words,re.text) # print(re.status_code) def learn_test_02_get(self): re = s.request(method='post', url='https://fanyi.baidu.com/langdetect', headers={'Content-Type': 'application/x-www-form-urlencoded', 'charset': 'UTF-8'}, params={'query': 'I miss you'}, verify=False) print(re.json()) print(re.status_code) if __name__ == '__main__': unittest.main()
import requests import json import unittest import re import readExcel import json import os path = os.path.dirname(os.getcwd())+"\\data\\C1.2testCase1.xls" testData = readExcel.ReadExcel.readExcel(path, "C12testCase") s = requests.session() class UCTestCase(unittest.TestCase): def test_send_request(self): words= "'error': 0, 'msg': 'success'" res = s.request(method='post', url='https://fanyi.baidu.com/langdetect', headers={'Content-Type':'application/x-www-form-urlencoded','charset':'UTF-8'},params={'query':'I miss you'}, verify=False) #返回的dict类型,str()将dict转换成str re_json=str(res.json()) #type()查看数据类型 print(type(re_json)) #re_json.dump() #print(re_json.dump()) print(res.status_code) self.assertIn(words,re_json,'接口请求失败') def qtest_01_post(self): words = '学会感恩也就学会了快乐' res = s.request(method='get', url='http://www.hjenglish.com/new/p1261643/', headers={'content-type': 'text/html', 'charset': 'utf-8'}, verify=False) #print(re.text) #正则提取里面的文字 htms = re.findall(r"有声双语美文:.*?_沪江英语学习网", res.text) # 通过正则表达式 r"<a.*?>.*?</a>" 找到所有的数据并输出 for item in htms: print(item) #self.assertEqual(200,res.status_code,"接口请求失败") self.assertIn(words,item,'接口请求失败') #self.assertIn(self,words,re.text) # print(re.status_code) def learn_test_02_get(self): re = s.request(method='post', url='https://fanyi.baidu.com/langdetect', headers={'Content-Type': 'application/x-www-form-urlencoded', 'charset': 'UTF-8'}, params={'query': 'I miss you'}, verify=False) print(re.json()) print(re.status_code) if __name__ == '__main__': unittest.main()
zh
0.498261
#返回的dict类型,str()将dict转换成str #type()查看数据类型 #re_json.dump() #print(re_json.dump()) #print(re.text) #正则提取里面的文字 # 通过正则表达式 r"<a.*?>.*?</a>" 找到所有的数据并输出 #self.assertEqual(200,res.status_code,"接口请求失败") #self.assertIn(self,words,re.text) # print(re.status_code)
2.867068
3
pushtokindle.py
ritiek/url-to-kindle
15
6625135
import requests import sys FROM = "<EMAIL>" TO = "<EMAIL>" email, domain_name = TO.split("@") available_domain_names = ("free.kindle.com", "kindle.com", "kindle.cn", "iduokan.com", "pbsync.com") domain_int = available_domain_names.index(domain_name) + 1 params = ( ("context", "send"), ("url", sys.argv[1]), ) data = {"from": FROM, "title": "", "email": email, "domain": domain_int,} response = requests.post("https://pushtokindle.fivefilters.org/send.php", params=params, data=data) print(response.text)
import requests import sys FROM = "<EMAIL>" TO = "<EMAIL>" email, domain_name = TO.split("@") available_domain_names = ("free.kindle.com", "kindle.com", "kindle.cn", "iduokan.com", "pbsync.com") domain_int = available_domain_names.index(domain_name) + 1 params = ( ("context", "send"), ("url", sys.argv[1]), ) data = {"from": FROM, "title": "", "email": email, "domain": domain_int,} response = requests.post("https://pushtokindle.fivefilters.org/send.php", params=params, data=data) print(response.text)
none
1
3.056622
3
tensorflow/python/framework/function.py
MathMachado/tensorflow
1
6625136
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Python front-end supports for functions. NOTE: At this time, functions are experimental and subject to change!. Proceed with caution. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import hashlib from tensorflow.core.framework import attr_value_pb2 from tensorflow.core.framework import function_pb2 from tensorflow.python import pywrap_tensorflow as c_api from tensorflow.python.eager import context from tensorflow.python.framework import c_api_util from tensorflow.python.framework import dtypes from tensorflow.python.framework import graph_to_function_def from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.python.util import compat from tensorflow.python.util import function_utils from tensorflow.python.util import object_identity from tensorflow.python.util import tf_contextlib from tensorflow.python.util import tf_inspect class Defun(object): """Decorator used to define TensorFlow functions. Use this decorator to make a Python function usable directly as a TensorFlow function. The decorated function must add ops to the default graph and return zero or more `Tensor` objects. Call the decorator with named arguments, one for each argument of the function to decorate, with the expected type of the argument as value. For example if the function to decorate accepts two `tf.float32` arguments named `x` and `y`, call the decorator with: @Defun(tf.float32, tf.float32) def foo(x, y): ... When you call the decorated function, it adds the `call` ops to the default graph. In addition, it adds the definition of the function into the default graph. Because the addition of the function into the graph is deferred, the decorator can be used anywhere in the program. Any variables created inside of the function are hoisted into the outer graph. Note that the variables are created in the variable scope that was active during the first call to the function. Subsequent function calls will refer to the same set of variables. Definitions of functions in a graph are frozen as soon as the graph is used to create a session. However, new functions and new calls to existing functions may be added to the graph, with the new functions themselves becoming immediately frozen. Example, but also see the [How To on functions](link_needed). ```python # Defining the function. @tf.Defun(tf.float32, tf.float32) def MyFunc(x, y): return x + y, x - y # Building the graph. a = tf.constant([1.0]) b = tf.constant([2.0]) c, d = MyFunc(a, b, name='mycall') ``` """ def __init__(self, *input_types, **kwargs): """Create a `Defun` decorator. Args: *input_types: A list of `tf.DType` **kwargs: Optional keyword arguments, including func_name - (optional). A python string, the name to use to declare this `Function` in the graph. grad_func - (optional). A function implementing the gradient of the function-to-register. This is must be a `_DefinedFunction` object. The gradient function must satisfy the criterion defined in function.proto:GradientDef. python_grad_func - (optional). A function implementing the gradient of the function python-side. This function must take the current op and the gradients w.r.t. its outputs, and return the gradients w.r.t. the inputs. That is it must implement the interface expected by `tf.RegisterGradient`). This will be called by tf.gradients to add the gradient ops to the graph. At most one of grad_func and python_grad_func can be specified. out_names = (optional). A list of strings, one per output tensor. shape_func - (optional). A function taking the op and returning a list of static shapes to set for the function's outputs. """ self._input_types = input_types self._func_name = kwargs.pop("func_name", None) self._grad_func = kwargs.pop("grad_func", None) self._python_grad_func = kwargs.pop("python_grad_func", None) self._out_names = kwargs.pop("out_names", None) self._extra_kwargs = kwargs def __call__(self, func): # Various sanity checks on the callable func. if not callable(func): raise ValueError("function %s must be callable" % func) # Func should not use kwargs and defaults. argspec = tf_inspect.getargspec(func) if argspec.keywords or argspec.defaults: raise ValueError( "function with argument defaults or keywords arguments are not" " supported. {} has defaults {} and keywords {}.".format( func, argspec.defaults, argspec.keywords)) # Computes how many arguments 'func' has. min_args = len(argspec.args) max_args = min_args if argspec.varargs: max_args = 1000000 argnames = argspec.args if tf_inspect.ismethod(func): # 1st argument is the "class" type. min_args -= 1 argnames = argnames[1:] if self._input_types: # If Defun is given a list of types for the inputs, the number # of input types should be compatible with 'func'. num = len(self._input_types) if num < min_args or num > max_args: raise ValueError( "The function has fewer arguments than the number of specified " "input types.") return _DefinedFunction( func, argnames, self._input_types, self._func_name, self._grad_func, self._python_grad_func, out_names=self._out_names, **self._extra_kwargs) # 'func' expects no arguments and input types is an empty list. if min_args == 0 and max_args == 0: return _DefinedFunction( func, [], [], self._func_name, self._grad_func, self._python_grad_func, out_names=self._out_names, **self._extra_kwargs) # Input types are unknown. It's an overloaded function and hence # its definition needs to be deferred until it's called. return _OverloadedFunction( func, argnames, self._func_name, self._grad_func, self._python_grad_func, out_names=self._out_names, **self._extra_kwargs) class _DefinedFunctionDeleter(object): """Unregister function from eager context.""" def __init__(self, name): self.name = name def __del__(self): try: context.remove_function(self.name) except TypeError: # Suppress some exceptions, mainly for the case when we're running on # module deletion. Things that can go wrong include the context module # already being unloaded, self._handle._handle_data no longer being # valid, and so on. Printing warnings in these cases is silly # (exceptions raised from __del__ are printed as warnings to stderr). pass # 'NoneType' object is not callable when the handle has been # partially unloaded. except AttributeError: pass # 'NoneType' object has no attribute 'eager_mode' when context has # been unloaded. Will catch other module unloads as well. class _DefinedFunction(object): """_DefinedFunction encapsulates a function definition and its properties. Attributes: name: The function name. definition: The definition of this function. A FunctionDef proto. grad_func_name: If not None, the name of this function's gradient function. python_grad_func: A python callable implementing the gradient of the function python-side. """ def __init__(self, func, argnames, input_types, func_name=None, grad_func=None, python_grad_func=None, out_names=None, shape_func=None, capture_by_value=False, whitelisted_stateful_ops=None, capture_resource_var_by_value=True, **kwargs): """Creates _DefinedFunction. Args: func: A python callable which constructs a tf function body. argnames: A list of strings for function argument names. input_types: The function's argument types. Can be a tuple, list of tf data types. func_name: The function name. Defaults to None, in which derives from 'func'. grad_func: This function's gradient function, if not None. Defaults to None. python_grad_func: A python callable implementing the gradient of the function python-side. out_names: An optional list of strings for the function return value names. shape_func: An optional function mapping an op to a list of static output shapes. capture_by_value: Boolean (defaults to False). If True, captured values will be copied into the function body. whitelisted_stateful_ops: A set of ops that if stateful we ignore and copy into the function body, when `capture_by_value` is True. capture_resource_var_by_value: Boolean (defaults to True). If False, captured resource variable returns the handle instead of value. **kwargs: The keyword arguments. **kwargs is passed to every call site of this function. Raises: ValueError: The function definition is invalid. """ self._func = func self._input_types = input_types self._func_name = func_name self._grad_func = grad_func self._python_grad_func = python_grad_func self._out_names = out_names self._shape_func = shape_func self._capture_by_value = capture_by_value self._whitelisted_stateful_ops = whitelisted_stateful_ops if self._whitelisted_stateful_ops is None: self._whitelisted_stateful_ops = set() self._capture_resource_var_by_value = capture_resource_var_by_value self._extra_kwargs = kwargs # Constructed only when C API is disabled, lazily self._definition = None # Constructed only when C API is enabled, lazily self._c_func = None self._function_deleter = None self._sub_functions = {} # Constructed with _definition or _c_func # pylint: disable=protected-access device_funcs = ops.get_default_graph()._device_functions_outer_to_inner # pylint: enable=protected-access # Get the innermost device if possbile. self._caller_device = device_funcs[-1] if device_funcs else None # Cached OpDef for this function. When C API is enabled, this is # the only part of FunctionDef that we cache in Python. When C API # is disabled the whole _definition is available and this is simply # another reference to _definition.signature self._op_def = None assert isinstance(input_types, (list, tuple)) self._arg_types = input_types self._arg_names = [argnames[i] if i < len(argnames) else ("arg%d" % i) for i in range(len(input_types))] @property def name(self): """Function name.""" self._create_definition_if_needed() return self._func_name @property def definition(self): """Function definition proto.""" self._create_definition_if_needed() if self._c_func: with c_api_util.tf_buffer() as buf: c_api.TF_FunctionToFunctionDef(self._c_func.func, buf) fdef = function_pb2.FunctionDef() proto_data = c_api.TF_GetBuffer(buf) fdef.ParseFromString(compat.as_bytes(proto_data)) with ops.init_scope(): if context.executing_eagerly(): context.add_function(self._c_func.func) self._function_deleter = _DefinedFunctionDeleter( fdef.signature.name) return fdef return self._definition @property def _signature(self): self._create_definition_if_needed() return self._op_def def set_grad_func(self, grad_func): """Specifies the gradient function of this function.""" assert not self._grad_func assert isinstance(grad_func, _DefinedFunction) self._grad_func = grad_func @property def grad_func_name(self): """Returns the name of the gradient function.""" return self._grad_func.name if self._grad_func else None @property def python_grad_func(self): """Python gradient function callable.""" return self._python_grad_func @property def declared_input_types(self): """Returns the list of data types of explicit declared inputs.""" return self._input_types @property def captured_inputs(self): """Returns the list of implicitly captured inputs.""" self._create_definition_if_needed() return self._extra_inputs @property def stateful_ops(self): """Returns the list of stateful ops in function definition. Returns: A list of (op.name, op.type) pairs. """ self._create_definition_if_needed() return self._stateful_ops def _create_definition_if_needed(self): """Creates the function definition if it's not created yet.""" with context.graph_mode(): self._create_definition_if_needed_impl() def _create_definition_if_needed_impl(self): """This is not what you want, see _create_definition_if_needed.""" if self._definition is not None or self._c_func is not None: return # Copy variable collections (by reference) from the parent graph such that # name based variable sharing (e.g. via tf.make_template) works between the # func graph and parent graph. variable_keys = [] variable_keys.extend(ops.GraphKeys._VARIABLE_COLLECTIONS) # pylint: disable=protected-access variable_keys.append(vs._VARSTORE_KEY) # pylint: disable=protected-access collections_ref = {} parent_collections_ref = ops.get_default_graph()._collections # pylint: disable=protected-access for key in variable_keys: if key not in parent_collections_ref: parent_collections_ref[key] = collections_ref[key] = [] else: collections_ref[key] = parent_collections_ref[key] temp_graph = func_graph_from_py_func( self._func, self._arg_names, self._arg_types, self._func_name, self._capture_by_value, self._caller_device, collections_ref=collections_ref, whitelisted_stateful_ops=self._whitelisted_stateful_ops, capture_resource_var_by_value=self._capture_resource_var_by_value) self._extra_inputs = temp_graph.extra_inputs # pylint: disable=protected-access self._sub_functions = temp_graph._functions # pylint: enable=protected-access # Extra kwargs are treated as attrs on the function def. if self._func_name: base_func_name = self._func_name else: base_func_name = function_utils.get_func_name(self._func) if self._grad_func: base_func_name += ("_%s" % self._grad_func.name) kwargs_attr = _parse_kwargs_as_attrs(base_func_name, **self._extra_kwargs) if not temp_graph._c_graph: # pylint: disable=protected-access # Build the FunctionDef self._definition = graph_to_function_def.graph_to_function_def( temp_graph, temp_graph.get_operations(), temp_graph.inputs, temp_graph.outputs, out_names=self._out_names) for k in kwargs_attr: self._definition.attr[k].CopyFrom(kwargs_attr[k]) # Hash the definition and its dependencies. self._hash_str = self._create_hash_str( self._definition.signature.input_arg, self._definition.signature.output_arg, self._definition.node_def) # Finally, we decide the function name to use. If not specified, # make up something which is almost certainly unique (but deterministic). if not self._func_name: self._func_name = "_".join([base_func_name, self._hash_str]) self._definition.signature.name = self._func_name if self._func.__doc__: self._definition.signature.description = self._func.__doc__ self._op_def = self._definition.signature else: # C API is enabled output_names = ([compat.as_bytes(x) for x in self._out_names] if self._out_names else []) description = self._func.__doc__ or None # pylint: disable=protected-access c_func = c_api.TF_GraphToFunction_wrapper( temp_graph._c_graph, base_func_name, self._func_name is None, # append_hash_to_fn_name None, # opers [t._as_tf_output() for t in temp_graph.inputs], [t._as_tf_output() for t in temp_graph.outputs], output_names, [], # control_outputs [], # control_output_names None, # opts description) self._c_func = c_api_util.ScopedTFFunction(c_func) # pylint: enable=protected-access self._set_c_attrs(kwargs_attr) # Set cached fields: _op_def and _func_name (if not already set) self._op_def = self.definition.signature if self._func_name: assert self._func_name == self._op_def.name else: self._func_name = compat.as_str(self._op_def.name) self._stateful_ops = [(op.name, op.type) for op in temp_graph.get_operations() if op._is_stateful] # pylint: disable=protected-access def _set_c_attrs(self, attrs): """Sets `attrs` as attributes of self._c_func. Requires that self._c_func is not None. Args: attrs: a dictionary from attribute name to attribute proto value """ for name, attr_value in attrs.items(): serialized = attr_value.SerializeToString() # TODO(skyewm): this creates and deletes a new TF_Status for every attr. # It might be worth creating a convenient way to re-use the same status. c_api.TF_FunctionSetAttrValueProto(self._c_func.func, compat.as_str(name), serialized) def _create_hash_str(self, input_arg, output_arg, node_def): """Creates an 8-character string unique to this input. Args: input_arg: the input_arg field of an OpDef (e.g. self._definition.signature.input_arg) output_arg: the output_arg field of an OpDef (e.g. self._definition.signature.output_arg) node_def: the node_def field of a FunctionDef (e.g. self._definition.node_def) Returns: The unique string for this input """ hasher = hashlib.sha1() def update_num(n): hasher.update(compat.as_bytes("%x" % n)) def update_str(s): update_num(len(s)) hasher.update(compat.as_bytes(s)) def update_strs(slist): update_num(len(slist)) for s in slist: update_str(s) for adef in input_arg: update_str(adef.SerializeToString()) for adef in output_arg: update_str(adef.SerializeToString()) for n in sorted(node_def, key=lambda n: n.name): update_str(n.name) update_str(n.op) update_strs(n.input) update_num(len(n.attr)) # NOTE: protobuf map serialization does not guarantee ordering. for k in sorted(n.attr): update_str(k) update_str(n.attr[k].SerializeToString()) return hasher.hexdigest()[:8] def add_to_graph(self, g): """Adds this function into the graph g.""" self._create_definition_if_needed() # Adds this function into 'g'. # pylint: disable=protected-access if context.executing_eagerly(): context.context().add_function_def(self.definition) else: g._add_function(self) # pylint: enable=protected-access # Ensures related sub-routines are defined in 'g', too. for f in self._sub_functions.values(): f.add_to_graph(g) # Adds its gradient function, too. if self._grad_func: self._grad_func.add_to_graph(g) def __call__(self, *args, **kwargs): self.add_to_graph(ops.get_default_graph()) args = [ops.convert_to_tensor(_) for _ in args] + self._extra_inputs ret, op = _call(self._signature, *args, **kwargs) # Set a hidden attr in 'op' so that gradients_impl can refer back # to this _DefinedFunction instance to access python_grad_func. assert isinstance(op, ops.Operation) setattr(op, "__defun", self) if self._shape_func is not None: shapes = self._shape_func(op) if len(shapes) != len(op.outputs): raise ValueError("shape_func produced %d shapes for %d outputs" % (len(shapes), len(op.outputs))) for (t, shape) in zip(op.outputs, shapes): t.set_shape(shape) return ret class _OverloadedFunction(object): """_OverloadedFunction encapsulates an overloaded function. _OverloadedFunction maintains a mapping from input types to instantiated _DefinedFunction in self._overload. """ def __init__(self, func, argnames, func_name=None, grad_func=None, python_grad_func=None, out_names=None, **kwargs): """Creates _DefinedFunction. Args: func: A python callable which constructs a tf function body. argnames: A list of strings for function argument names. func_name: The function name. Defaults to None, in which derives from 'func'. grad_func: This function's gradient function, if not None. Defaults to None. python_grad_func: A python callable implementing the gradient of the function python-side. out_names: A list of strings for the function return value names. **kwargs: The keyword arguments. **kwargs is passed to every call site of this function. Raises: ValueError: The function definition is invalid. """ self._func = func self._argnames = argnames self._func_name = func_name assert grad_func is None or isinstance(grad_func, _OverloadedFunction) self._grad_func = grad_func self._python_grad_func = python_grad_func self._out_names = out_names self._extra_kwargs = kwargs self._overload = {} def instantiate(self, input_types): """Instantiate this function given input argument types. Args: input_types: A list of data types for the inputs. Returns: _DefinedFunction for the given input types. """ # Stringify the type list. key = _type_list_to_str(input_types) defined = self._overload.get(key) if not defined: # If not defined yet, define the function given the input types. name = self._func_name if name is not None: name = "_".join([name, key]) defined = _DefinedFunction( self._func, self._argnames, input_types, name, None, self._python_grad_func, out_names=self._out_names, **self._extra_kwargs) _ = defined.name # Fully instantiate the function definition. if self._grad_func: # If _grad_func is given, it is another # _OverloadedFunction. We need to instantiate it with the # right input types. output_types = [ dtypes.DType(_.type) for _ in defined._signature.output_arg # pylint: disable=protected-access ] # pylint: disable=protected-access defined._grad_func = self._grad_func.instantiate(input_types + output_types) # pylint: enable=protected-access self._overload[key] = defined return defined def __call__(self, *args, **kwargs): input_types = [] args = list(args) for (i, x) in enumerate(args): x = ops.convert_to_tensor(x) if not isinstance(x, ops.Tensor): raise ValueError("Expect a Tensor but get ", x) input_types.append(x.dtype) args[i] = x return self.instantiate(input_types)(*args, **kwargs) class _FuncGraph(ops.Graph): """A helper for constructing a function. _FuncGraph overrides ops.Graph's create_op() so that we can keep track of all inputs into every op created inside the function. If any input is from other graphs, we keep track of it in self.capture and substitute the input with a place holder. Each captured input's corresponding place holder is converted into a function argument and the caller passes in the captured tensor. """ def __init__(self, name, capture_by_value, whitelisted_stateful_ops, capture_resource_var_by_value, *args, **kwargs): super(_FuncGraph, self).__init__(*args, **kwargs) self._capture_by_value = capture_by_value self._whitelisted_stateful_ops = whitelisted_stateful_ops self._capture_resource_var_by_value = capture_resource_var_by_value self._building_function = True self._outer_graph = ops.get_default_graph() self._vscope = vs.get_variable_scope() self._old_custom_getter = self._vscope.custom_getter # The name of the function. self.name = name # Placeholder tensors representing the inputs to this function. The tensors # are in this _FuncGraph. self.inputs = [] # Tensors that will be returned this function. The tensors are in this # _FuncGraph. self.outputs = [] # Maps external tensor -> internal tensor (e.g. input placeholder). self._captured = object_identity.ObjectIdentityDictionary() # The external tensors that have been captured as inputs and must be passed # to this function (empty if capturing by value, otherwise these are the # keys of _captured). self.extra_inputs = [] # Input placeholders that been added for captured values (empty if capturing # by value). self.extra_args = [] # Captured variables. # TODO(skyewm): is this needed? self.extra_vars = [] # pylint: disable=g-doc-return-or-yield @tf_contextlib.contextmanager def container(self, container_name): """Returns a context manager that specifies the resource container to use. Overridden from `tf.Graph` to update both the init_scope container and the present inner container. This is necessary to make sure setting containers applies correctly both to created variables and to stateful ops. Args: container_name: container name string. Returns: A context manager for defining resource containers for stateful ops, yields the container name. """ original_container = self._container # pylint: disable=protected-access with ops.init_scope(): original_init_container = ops.get_default_graph()._container try: self._container = container_name with ops.init_scope(): ops.get_default_graph()._container = container_name yield self._container finally: self._container = original_container with ops.init_scope(): ops.get_default_graph()._container = original_init_container # pylint: enable=protected-access # pylint: enable=g-doc-return-or-yield def getvar( self, getter, name, shape=None, dtype=None, initializer=None, reuse=None, trainable=True, collections=None, # pylint: disable=redefined-outer-name use_resource=None, **kwargs): """A custom variable getter.""" # Here, we switch the default graph to the outer graph and ask the # variable scope in which the function is defined to give us the # variable. The variable is stashed in extra_vars and returned to # the caller. # # We capture these variables so that the variable definition is # hoisted upward to the outer most graph. with self._outer_graph.as_default(): # pylint: disable=protected-access var = self._vscope.get_variable( vs._get_default_variable_store(), name, shape=shape, dtype=dtype, initializer=initializer, reuse=reuse, trainable=trainable, collections=collections, use_resource=use_resource) self.extra_vars.append(var) if (isinstance(var, resource_variable_ops.BaseResourceVariable) and self._capture_resource_var_by_value): # For resource-based variables read the variable outside the function # and pass in the value. This ensures that the function is pure and # differentiable. TODO(apassos) this may have performance problems if # the function will only do embedding lookups on the variable. return var.value() return var def _create_op_internal(self, op_type, inputs, dtypes=None, **kwargs): # pylint: disable=redefined-outer-name for i, x in enumerate(inputs): if isinstance(x, ops.EagerTensor) or x.graph is not self: inputs[i] = self.capture(x) return super(_FuncGraph, self)._create_op_internal( op_type, inputs, dtypes=dtypes, **kwargs) def capture(self, tensor, name=None): """Adds the given tensor to this graph and returns the captured tensor.""" if tensor in self._captured: # Captured already. return self._captured[tensor] elif self._capture_by_value: return self._add_tensor_and_parents(tensor) else: return self._capture_tensor_as_extra_input(tensor, name) def _capture_tensor_as_extra_input(self, tensor, name=None): # Substitute with a placeholder. self.extra_inputs.append(tensor) # Hoist the new input placeholder out of any control flow context # we're currently in. with ops.control_dependencies(None): ph = array_ops.placeholder( tensor.dtype, shape=tensor.get_shape(), name=name) # pylint: disable=protected-access if isinstance(tensor, ops.EagerTensor): handle_data = tensor._handle_data if handle_data: handle_data = handle_data.SerializeToString() else: handle_data = c_api.GetHandleShapeAndType(tensor.graph._c_graph, tensor._as_tf_output()) if handle_data: c_api.SetHandleShapeAndType(ph.graph._c_graph, ph._as_tf_output(), compat.as_bytes(handle_data)) # pylint: enable=protected-access self.inputs.append(ph) self._captured[tensor] = ph self.extra_args.append(ph) if _is_guaranteed_const(tensor): with ops.control_dependencies(None): return array_ops.guarantee_const(ph) else: return ph def _add_tensor_and_parents(self, tensor): op = self._add_op_and_parents(tensor.op) return op.outputs[tensor.value_index] def _add_op_and_parents(self, op): # pylint: disable=protected-access op_def = graph_to_function_def._get_op_def(op) if op._is_stateful and op not in self._whitelisted_stateful_ops: raise ValueError("Cannot capture a stateful node (name:%s, type:%s) " "by value." % (op.name, op.type)) elif op.type in ("Placeholder", "PlaceholderV2"): raise ValueError("Cannot capture a placeholder (name:%s, type:%s) " "by value." % (op.name, op.type)) # pylint: enable=protected-access captured_inputs = [self._add_tensor_and_parents(x) for x in op.inputs] captured_op = self._create_op_internal( op.type, captured_inputs, [o.dtype for o in op.outputs], name=op.name, attrs=op.node_def.attr, op_def=op_def) for t, captured_t in zip(op.outputs, captured_op.outputs): self._captured[t] = captured_t return captured_op def func_graph_from_py_func(func, arg_names, arg_types, name=None, capture_by_value=False, device=None, colocation_stack=None, container=None, collections_ref=None, arg_shapes=None, whitelisted_stateful_ops=None, capture_resource_var_by_value=True): """Returns a _FuncGraph generated from `func`. Args: func: A Python callable which constructs a TF function body. The arguments must correspond to `arg_types`. Returns a value or list/tuple of values. No returned value can be None. arg_names: A sequence of strings for the function argument names. arg_types: A sequence of the function's argument types. name: The function name. If None, the name is derived from `func`. capture_by_value: boolean. If True, captured values will be copied into the function body. device: device name or function. colocation_stack: A colocation stack (list) the _FuncGraph should use. container: A container name the _FuncGraph should start with. collections_ref: A reference to a collections dict the _FuncGraph should use internally. arg_shapes: A sequence of the function's argument shapes. whitelisted_stateful_ops: A set of ops that if stateful we ignore and re-create. capture_resource_var_by_value: Boolean (defaults to True). If False, captured resource variable returns the handle instead of value. Returns: A _FuncGraph. Raises: ValueError: if func returns None. """ if not name: name = function_utils.get_func_name(func) func_graph = _FuncGraph(name, capture_by_value, whitelisted_stateful_ops, capture_resource_var_by_value) with func_graph.as_default(), ops.device(device): # pylint: disable=protected-access if collections_ref is not None: func_graph._collections = collections_ref if container is not None: func_graph._container = container if colocation_stack is not None: func_graph._colocation_stack = colocation_stack # pylint: enable=protected-access if arg_shapes is None: arg_shapes = [None] * len(arg_types) # Create placeholders for the function arguments. for (argname, argtype, argshape) in zip(arg_names, arg_types, arg_shapes): argholder = array_ops.placeholder(argtype, shape=argshape, name=argname) func_graph.inputs.append(argholder) # Call func and gather the output tensors. with vs.variable_scope("", custom_getter=func_graph.getvar): outputs = func(*func_graph.inputs) # There is no way of distinguishing between a function not returning # anything and a function returning None in Python. # We need to allow the former and ideally want to forbid the latter as # it is most likely user error. # TODO(iga): Consider adding a @NoOutput decorator on top of @Defun to # allow users to explicitly mark the function as not returning anything. # For now, we allow a single None return and interpret it as a function # with no output. if outputs is None: outputs = [] else: # If func only returned one value, make it a tuple. if not isinstance(outputs, (list, tuple)): outputs = (outputs,) if any(_ is None for _ in outputs): raise ValueError("Function %s can not return None." % name) # Ensures each output is a Tensor in the function graph. outputs = [ops.convert_to_tensor(t) for t in outputs] outputs = [func_graph.capture(t) if t.graph is not func_graph else t for t in outputs] func_graph.outputs = outputs return func_graph def _is_guaranteed_const(tensor): """Determines whether `tensor` is guaranteed to be a constant. A tensor is guaranteed to be a constant if either it was produced by a `GuaranteeConst` op or if all of its children are guaranteed to be constants. Args: tensor: The tensor for which to determine const-ness. Returns: True if `tensor` is guaranteed to be a constant, False otherwise. """ if isinstance(tensor, ops.EagerTensor): return False class Work(object): def __init__(self, op, leaving): self.op = op self.leaving = leaving is_guaranteed_const = lambda op: op.node_def.op == "GuaranteeConst" constants = set([]) def all_inputs_const(op): # If all inputs of an op are guaranteed constants, then we can infer that # the op produces a constant as well. return op.inputs and all(inp.op in constants for inp in op.inputs) visited = set([]) stack = [Work(tensor.op, leaving=False)] while stack: work = stack.pop() if work.leaving: if all_inputs_const(work.op): constants.add(work.op) continue visited.add(work.op) if is_guaranteed_const(work.op): constants.add(work.op) continue # This op will be revisited after all its inputs are checked for const-ness. stack.append(Work(work.op, leaving=True)) for inp in work.op.inputs: if inp.op not in visited: stack.append(Work(inp.op, leaving=False)) return tensor.op in constants def _call(sig, *inputs, **kwargs): """Adds a node calling a function. This adds a `call` op to the default graph that calls the function of signature `sig`, passing the tensors in `inputs` as arguments. It returns the outputs of the call, which are one or more tensors. `sig` is OpDefArg.a `_DefinedFunction` object. You can pass an optional keyword parameter `name=string` to name the added operation. You can pass an optional keyword parameter `noinline=True|False` to instruct the runtime not to inline the function body into the call site. Args: sig: OpDefArg. The signature of the function. *inputs: arguments to the function. **kwargs: Optional keyword arguments. Can only contain 'name' or 'noinline'. Returns: A 2-element tuple. First element: a Tensor if the function returns a single value; a list of Tensors if the function returns multiple value; the Operation if the function returns no values. Second element: the Operation. Raises: ValueError: if the arguments are invalid. """ if len(inputs) != len(sig.input_arg): raise ValueError("Expected number of arguments: %d, received: %d" % (len( sig.input_arg), len(inputs))) name = kwargs.pop("name", None) g = ops.get_default_graph() func_name = sig.name if name is None: name = func_name attrs = _parse_kwargs_as_attrs(func_name, **kwargs) output_types = [dtypes.DType(x.type) for x in sig.output_arg] op = g._create_op_internal( # pylint: disable=protected-access func_name, list(inputs), output_types, name=name, attrs=attrs, op_def=sig) if op.outputs: if len(op.outputs) == 1: ret = op.outputs[0] else: ret = tuple(op.outputs) else: ret = op return ret, op def _from_definition(fdef, grad_func=None): """Creates a _DefinedFunction initialized from a FunctionDef proto. Args: fdef: a FunctionDef grad_func: a _DefinedFunction or None Returns: A _DefinedFunction representing fdef """ # TODO(iga): This method does major surgery on _DefinedFunction. # Make it a named constructor using @classmethod of _DefinedFunction. # The Python callable is only needed to create a FunctionDef. Since we have # the FunctionDef here, we don't need to set _DefinedFunction._func (nor do we # have access to such a callable here). func = None argnames = [arg.name for arg in fdef.signature.input_arg] input_types = tuple( dtypes.as_dtype(arg.type) for arg in fdef.signature.input_arg) func_name = fdef.signature.name # Note: FunctionDefs do not include python gradient functions, so if the # original _DefinedFunction included one it will not be reflected here. python_grad_func = None out_names = [arg.name for arg in fdef.signature.output_arg] result = _DefinedFunction(func, argnames, input_types, func_name, grad_func, python_grad_func, out_names) # pylint: disable=protected-access serialized = fdef.SerializeToString() c_func = c_api.TF_FunctionImportFunctionDef(serialized) result._c_func = c_api_util.ScopedTFFunction(c_func) result._extra_inputs = [] result._op_def = fdef.signature # pylint: enable=protected-access return result def from_library(lib): """Creates _DefinedFunctions initialized from a FunctionDefLibrary proto. This method handles assigning the correct gradient functions to each function. Args: lib: a FunctionDefLibrary Returns: A list of _DefinedFunctions Raises: ValueError: `lib` is invalid """ if not lib.function and not lib.gradient: return [] # function name -> FunctionDef proto funcs = {fdef.signature.name: fdef for fdef in lib.function} # Validate that all references function names have function defs for g in lib.gradient: if g.function_name not in funcs: raise ValueError("FunctionDefLibrary missing '%s' FunctionDef\n%s" % (g.function_name, str(lib))) if g.gradient_func not in funcs: raise ValueError("FunctionDefLibrary missing '%s' FunctionDef\n%s" % (g.gradient_func, str(lib))) # function name -> gradient function name func_to_grad = collections.defaultdict(lambda: None) # gradient function name -> names of functions having that grad function grad_to_funcs = collections.defaultdict(list) for gdef in lib.gradient: func_to_grad[gdef.function_name] = gdef.gradient_func grad_to_funcs[gdef.gradient_func].append(gdef.function_name) # Start with functions without gradients ready = [ fdef for fdef in lib.function if func_to_grad[fdef.signature.name] is None ] if not ready: raise ValueError( "FunctionDefLibrary contains cyclic gradient functions!\n" + str(lib)) # function name -> _DefinedFunction initialized = {} while ready: fdef = ready.pop() name = fdef.signature.name grad = initialized.get(func_to_grad[name]) if func_to_grad[name]: assert grad defined_func = _from_definition(fdef, grad_func=grad) initialized[name] = defined_func ready.extend(funcs[f] for f in grad_to_funcs[name]) return initialized.values() def _get_experimental_kwarg_as_attr(attr_name, value): """Creates an AttrValue for a python object.""" if isinstance(value, bool): return attr_value_pb2.AttrValue(b=value) elif isinstance(value, int): return attr_value_pb2.AttrValue(i=value) elif isinstance(value, float): return attr_value_pb2.AttrValue(f=value) elif isinstance(value, str): return attr_value_pb2.AttrValue(s=compat.as_bytes(value)) else: raise ValueError("Unsupported attribute type for %s with type %s" % (attr_name, type(value))) def _get_kwarg_as_str_attr(attr_name, value): """Creates an AttrValue for a python object.""" if isinstance(value, str): return attr_value_pb2.AttrValue(s=compat.as_bytes(value)) else: raise ValueError("Unsupported attribute type for %s with type %s" % (attr_name, type(value))) def _parse_kwargs_as_attrs(func_name, **kwargs): """Parses **kwargs into a node's attributes.""" attrs = {} noinline = kwargs.pop("noinline", None) if noinline is not None: attrs["_noinline"] = attr_value_pb2.AttrValue(b=bool(noinline)) # For compatibility with previous behavior, Defun does not perform shape # inference through its function call operations. attrs["_disable_call_shape_inference"] = attr_value_pb2.AttrValue(b=True) compiled = kwargs.pop("compiled", None) separate_compiled_gradients = kwargs.pop("separate_compiled_gradients", None) if compiled is not None: attrs["_XlaCompile"] = attr_value_pb2.AttrValue(b=bool(compiled)) attrs["_XlaSeparateCompiledGradients"] = attr_value_pb2.AttrValue( b=bool(separate_compiled_gradients)) # Forward _XlaScope from enclosing context (if set), otherwise create new. # pylint: disable=protected-access if "_XlaScope" in ops.get_default_graph()._attr_scope_map: attrs["_XlaScope"] = ops.get_default_graph()._attr_scope_map["_XlaScope"] else: attrs["_XlaScope"] = attr_value_pb2.AttrValue( s=("function_%s" % func_name).encode()) # pylint: enable=protected-access kwargs_keys = list(kwargs.keys()) for key in kwargs_keys: if key.startswith("experimental_"): attrs[key] = _get_experimental_kwarg_as_attr(key, kwargs[key]) del kwargs[key] # Support for https://github.com/tensorflow/community/pull/113/files. elif key == "_implements" or key == "_reference": attrs[key] = _get_kwarg_as_str_attr(key, kwargs[key]) del kwargs[key] if kwargs: raise ValueError("Unknown keyword arguments: %s" % kwargs.keys()) return attrs def get_extra_vars(): """Returns the captured variables by the function. Returns: If the default graph is being used to define a function, the returned list of variables are those created inside the function body so far. Otherwise, returns an empty list. """ g = ops.get_default_graph() if isinstance(g, _FuncGraph): return g.extra_vars else: return [] def get_extra_inputs(): """Returns the captured input tensors by the function. Returns: If the default graph is being used to define a function, the returned list of tensors are those accessed inside the function body but defined outside the function body so far. Otherwise, returns an empty list. """ g = ops.get_default_graph() if isinstance(g, _FuncGraph): return g.extra_inputs else: return [] def get_extra_args(): """Returns the corresponding function arguments for the captured inputs. Returns: If the default graph is being used to define a function, the returned list of place holders are those used inside the function body corresponding those returned by get_extra_inputs(). Otherwise, returns an empty list. """ g = ops.get_default_graph() if isinstance(g, _FuncGraph): return g.extra_args else: return [] def _type_list_to_str(types): if any(_ not in _DTYPE_TO_STR for _ in types): raise ValueError("Unsupported dtypes: %s" % types) return "".join([_DTYPE_TO_STR[_] for _ in types]) # NOTE: The list needs to be extended when more data types are added. _DTYPE_TO_STR = { dtypes.float16: "f16", dtypes.float32: "f32", dtypes.float64: "f64", dtypes.int32: "i32", dtypes.uint8: "i8", dtypes.uint16: "u16", dtypes.uint32: "u32", dtypes.uint64: "u64", dtypes.int16: "i16", dtypes.int8: "i8", dtypes.string: "s", dtypes.complex64: "c64", dtypes.complex128: "c128", dtypes.int64: "i64", dtypes.bool: "b", dtypes.qint8: "qi8", dtypes.quint8: "qu8", dtypes.qint16: "qi16", dtypes.quint16: "qu16", dtypes.qint32: "qi32", dtypes.bfloat16: "b16" } def function_def_from_tf_function(c_func): """Converts a SWIG-wrapped TF_Function* to a FunctionDef proto.""" with c_api_util.tf_buffer() as buf: c_api.TF_FunctionToFunctionDef(c_func, buf) data = c_api.TF_GetBuffer(buf) fdef = function_pb2.FunctionDef() fdef.ParseFromString(compat.as_bytes(data)) return fdef
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Python front-end supports for functions. NOTE: At this time, functions are experimental and subject to change!. Proceed with caution. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import hashlib from tensorflow.core.framework import attr_value_pb2 from tensorflow.core.framework import function_pb2 from tensorflow.python import pywrap_tensorflow as c_api from tensorflow.python.eager import context from tensorflow.python.framework import c_api_util from tensorflow.python.framework import dtypes from tensorflow.python.framework import graph_to_function_def from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.python.util import compat from tensorflow.python.util import function_utils from tensorflow.python.util import object_identity from tensorflow.python.util import tf_contextlib from tensorflow.python.util import tf_inspect class Defun(object): """Decorator used to define TensorFlow functions. Use this decorator to make a Python function usable directly as a TensorFlow function. The decorated function must add ops to the default graph and return zero or more `Tensor` objects. Call the decorator with named arguments, one for each argument of the function to decorate, with the expected type of the argument as value. For example if the function to decorate accepts two `tf.float32` arguments named `x` and `y`, call the decorator with: @Defun(tf.float32, tf.float32) def foo(x, y): ... When you call the decorated function, it adds the `call` ops to the default graph. In addition, it adds the definition of the function into the default graph. Because the addition of the function into the graph is deferred, the decorator can be used anywhere in the program. Any variables created inside of the function are hoisted into the outer graph. Note that the variables are created in the variable scope that was active during the first call to the function. Subsequent function calls will refer to the same set of variables. Definitions of functions in a graph are frozen as soon as the graph is used to create a session. However, new functions and new calls to existing functions may be added to the graph, with the new functions themselves becoming immediately frozen. Example, but also see the [How To on functions](link_needed). ```python # Defining the function. @tf.Defun(tf.float32, tf.float32) def MyFunc(x, y): return x + y, x - y # Building the graph. a = tf.constant([1.0]) b = tf.constant([2.0]) c, d = MyFunc(a, b, name='mycall') ``` """ def __init__(self, *input_types, **kwargs): """Create a `Defun` decorator. Args: *input_types: A list of `tf.DType` **kwargs: Optional keyword arguments, including func_name - (optional). A python string, the name to use to declare this `Function` in the graph. grad_func - (optional). A function implementing the gradient of the function-to-register. This is must be a `_DefinedFunction` object. The gradient function must satisfy the criterion defined in function.proto:GradientDef. python_grad_func - (optional). A function implementing the gradient of the function python-side. This function must take the current op and the gradients w.r.t. its outputs, and return the gradients w.r.t. the inputs. That is it must implement the interface expected by `tf.RegisterGradient`). This will be called by tf.gradients to add the gradient ops to the graph. At most one of grad_func and python_grad_func can be specified. out_names = (optional). A list of strings, one per output tensor. shape_func - (optional). A function taking the op and returning a list of static shapes to set for the function's outputs. """ self._input_types = input_types self._func_name = kwargs.pop("func_name", None) self._grad_func = kwargs.pop("grad_func", None) self._python_grad_func = kwargs.pop("python_grad_func", None) self._out_names = kwargs.pop("out_names", None) self._extra_kwargs = kwargs def __call__(self, func): # Various sanity checks on the callable func. if not callable(func): raise ValueError("function %s must be callable" % func) # Func should not use kwargs and defaults. argspec = tf_inspect.getargspec(func) if argspec.keywords or argspec.defaults: raise ValueError( "function with argument defaults or keywords arguments are not" " supported. {} has defaults {} and keywords {}.".format( func, argspec.defaults, argspec.keywords)) # Computes how many arguments 'func' has. min_args = len(argspec.args) max_args = min_args if argspec.varargs: max_args = 1000000 argnames = argspec.args if tf_inspect.ismethod(func): # 1st argument is the "class" type. min_args -= 1 argnames = argnames[1:] if self._input_types: # If Defun is given a list of types for the inputs, the number # of input types should be compatible with 'func'. num = len(self._input_types) if num < min_args or num > max_args: raise ValueError( "The function has fewer arguments than the number of specified " "input types.") return _DefinedFunction( func, argnames, self._input_types, self._func_name, self._grad_func, self._python_grad_func, out_names=self._out_names, **self._extra_kwargs) # 'func' expects no arguments and input types is an empty list. if min_args == 0 and max_args == 0: return _DefinedFunction( func, [], [], self._func_name, self._grad_func, self._python_grad_func, out_names=self._out_names, **self._extra_kwargs) # Input types are unknown. It's an overloaded function and hence # its definition needs to be deferred until it's called. return _OverloadedFunction( func, argnames, self._func_name, self._grad_func, self._python_grad_func, out_names=self._out_names, **self._extra_kwargs) class _DefinedFunctionDeleter(object): """Unregister function from eager context.""" def __init__(self, name): self.name = name def __del__(self): try: context.remove_function(self.name) except TypeError: # Suppress some exceptions, mainly for the case when we're running on # module deletion. Things that can go wrong include the context module # already being unloaded, self._handle._handle_data no longer being # valid, and so on. Printing warnings in these cases is silly # (exceptions raised from __del__ are printed as warnings to stderr). pass # 'NoneType' object is not callable when the handle has been # partially unloaded. except AttributeError: pass # 'NoneType' object has no attribute 'eager_mode' when context has # been unloaded. Will catch other module unloads as well. class _DefinedFunction(object): """_DefinedFunction encapsulates a function definition and its properties. Attributes: name: The function name. definition: The definition of this function. A FunctionDef proto. grad_func_name: If not None, the name of this function's gradient function. python_grad_func: A python callable implementing the gradient of the function python-side. """ def __init__(self, func, argnames, input_types, func_name=None, grad_func=None, python_grad_func=None, out_names=None, shape_func=None, capture_by_value=False, whitelisted_stateful_ops=None, capture_resource_var_by_value=True, **kwargs): """Creates _DefinedFunction. Args: func: A python callable which constructs a tf function body. argnames: A list of strings for function argument names. input_types: The function's argument types. Can be a tuple, list of tf data types. func_name: The function name. Defaults to None, in which derives from 'func'. grad_func: This function's gradient function, if not None. Defaults to None. python_grad_func: A python callable implementing the gradient of the function python-side. out_names: An optional list of strings for the function return value names. shape_func: An optional function mapping an op to a list of static output shapes. capture_by_value: Boolean (defaults to False). If True, captured values will be copied into the function body. whitelisted_stateful_ops: A set of ops that if stateful we ignore and copy into the function body, when `capture_by_value` is True. capture_resource_var_by_value: Boolean (defaults to True). If False, captured resource variable returns the handle instead of value. **kwargs: The keyword arguments. **kwargs is passed to every call site of this function. Raises: ValueError: The function definition is invalid. """ self._func = func self._input_types = input_types self._func_name = func_name self._grad_func = grad_func self._python_grad_func = python_grad_func self._out_names = out_names self._shape_func = shape_func self._capture_by_value = capture_by_value self._whitelisted_stateful_ops = whitelisted_stateful_ops if self._whitelisted_stateful_ops is None: self._whitelisted_stateful_ops = set() self._capture_resource_var_by_value = capture_resource_var_by_value self._extra_kwargs = kwargs # Constructed only when C API is disabled, lazily self._definition = None # Constructed only when C API is enabled, lazily self._c_func = None self._function_deleter = None self._sub_functions = {} # Constructed with _definition or _c_func # pylint: disable=protected-access device_funcs = ops.get_default_graph()._device_functions_outer_to_inner # pylint: enable=protected-access # Get the innermost device if possbile. self._caller_device = device_funcs[-1] if device_funcs else None # Cached OpDef for this function. When C API is enabled, this is # the only part of FunctionDef that we cache in Python. When C API # is disabled the whole _definition is available and this is simply # another reference to _definition.signature self._op_def = None assert isinstance(input_types, (list, tuple)) self._arg_types = input_types self._arg_names = [argnames[i] if i < len(argnames) else ("arg%d" % i) for i in range(len(input_types))] @property def name(self): """Function name.""" self._create_definition_if_needed() return self._func_name @property def definition(self): """Function definition proto.""" self._create_definition_if_needed() if self._c_func: with c_api_util.tf_buffer() as buf: c_api.TF_FunctionToFunctionDef(self._c_func.func, buf) fdef = function_pb2.FunctionDef() proto_data = c_api.TF_GetBuffer(buf) fdef.ParseFromString(compat.as_bytes(proto_data)) with ops.init_scope(): if context.executing_eagerly(): context.add_function(self._c_func.func) self._function_deleter = _DefinedFunctionDeleter( fdef.signature.name) return fdef return self._definition @property def _signature(self): self._create_definition_if_needed() return self._op_def def set_grad_func(self, grad_func): """Specifies the gradient function of this function.""" assert not self._grad_func assert isinstance(grad_func, _DefinedFunction) self._grad_func = grad_func @property def grad_func_name(self): """Returns the name of the gradient function.""" return self._grad_func.name if self._grad_func else None @property def python_grad_func(self): """Python gradient function callable.""" return self._python_grad_func @property def declared_input_types(self): """Returns the list of data types of explicit declared inputs.""" return self._input_types @property def captured_inputs(self): """Returns the list of implicitly captured inputs.""" self._create_definition_if_needed() return self._extra_inputs @property def stateful_ops(self): """Returns the list of stateful ops in function definition. Returns: A list of (op.name, op.type) pairs. """ self._create_definition_if_needed() return self._stateful_ops def _create_definition_if_needed(self): """Creates the function definition if it's not created yet.""" with context.graph_mode(): self._create_definition_if_needed_impl() def _create_definition_if_needed_impl(self): """This is not what you want, see _create_definition_if_needed.""" if self._definition is not None or self._c_func is not None: return # Copy variable collections (by reference) from the parent graph such that # name based variable sharing (e.g. via tf.make_template) works between the # func graph and parent graph. variable_keys = [] variable_keys.extend(ops.GraphKeys._VARIABLE_COLLECTIONS) # pylint: disable=protected-access variable_keys.append(vs._VARSTORE_KEY) # pylint: disable=protected-access collections_ref = {} parent_collections_ref = ops.get_default_graph()._collections # pylint: disable=protected-access for key in variable_keys: if key not in parent_collections_ref: parent_collections_ref[key] = collections_ref[key] = [] else: collections_ref[key] = parent_collections_ref[key] temp_graph = func_graph_from_py_func( self._func, self._arg_names, self._arg_types, self._func_name, self._capture_by_value, self._caller_device, collections_ref=collections_ref, whitelisted_stateful_ops=self._whitelisted_stateful_ops, capture_resource_var_by_value=self._capture_resource_var_by_value) self._extra_inputs = temp_graph.extra_inputs # pylint: disable=protected-access self._sub_functions = temp_graph._functions # pylint: enable=protected-access # Extra kwargs are treated as attrs on the function def. if self._func_name: base_func_name = self._func_name else: base_func_name = function_utils.get_func_name(self._func) if self._grad_func: base_func_name += ("_%s" % self._grad_func.name) kwargs_attr = _parse_kwargs_as_attrs(base_func_name, **self._extra_kwargs) if not temp_graph._c_graph: # pylint: disable=protected-access # Build the FunctionDef self._definition = graph_to_function_def.graph_to_function_def( temp_graph, temp_graph.get_operations(), temp_graph.inputs, temp_graph.outputs, out_names=self._out_names) for k in kwargs_attr: self._definition.attr[k].CopyFrom(kwargs_attr[k]) # Hash the definition and its dependencies. self._hash_str = self._create_hash_str( self._definition.signature.input_arg, self._definition.signature.output_arg, self._definition.node_def) # Finally, we decide the function name to use. If not specified, # make up something which is almost certainly unique (but deterministic). if not self._func_name: self._func_name = "_".join([base_func_name, self._hash_str]) self._definition.signature.name = self._func_name if self._func.__doc__: self._definition.signature.description = self._func.__doc__ self._op_def = self._definition.signature else: # C API is enabled output_names = ([compat.as_bytes(x) for x in self._out_names] if self._out_names else []) description = self._func.__doc__ or None # pylint: disable=protected-access c_func = c_api.TF_GraphToFunction_wrapper( temp_graph._c_graph, base_func_name, self._func_name is None, # append_hash_to_fn_name None, # opers [t._as_tf_output() for t in temp_graph.inputs], [t._as_tf_output() for t in temp_graph.outputs], output_names, [], # control_outputs [], # control_output_names None, # opts description) self._c_func = c_api_util.ScopedTFFunction(c_func) # pylint: enable=protected-access self._set_c_attrs(kwargs_attr) # Set cached fields: _op_def and _func_name (if not already set) self._op_def = self.definition.signature if self._func_name: assert self._func_name == self._op_def.name else: self._func_name = compat.as_str(self._op_def.name) self._stateful_ops = [(op.name, op.type) for op in temp_graph.get_operations() if op._is_stateful] # pylint: disable=protected-access def _set_c_attrs(self, attrs): """Sets `attrs` as attributes of self._c_func. Requires that self._c_func is not None. Args: attrs: a dictionary from attribute name to attribute proto value """ for name, attr_value in attrs.items(): serialized = attr_value.SerializeToString() # TODO(skyewm): this creates and deletes a new TF_Status for every attr. # It might be worth creating a convenient way to re-use the same status. c_api.TF_FunctionSetAttrValueProto(self._c_func.func, compat.as_str(name), serialized) def _create_hash_str(self, input_arg, output_arg, node_def): """Creates an 8-character string unique to this input. Args: input_arg: the input_arg field of an OpDef (e.g. self._definition.signature.input_arg) output_arg: the output_arg field of an OpDef (e.g. self._definition.signature.output_arg) node_def: the node_def field of a FunctionDef (e.g. self._definition.node_def) Returns: The unique string for this input """ hasher = hashlib.sha1() def update_num(n): hasher.update(compat.as_bytes("%x" % n)) def update_str(s): update_num(len(s)) hasher.update(compat.as_bytes(s)) def update_strs(slist): update_num(len(slist)) for s in slist: update_str(s) for adef in input_arg: update_str(adef.SerializeToString()) for adef in output_arg: update_str(adef.SerializeToString()) for n in sorted(node_def, key=lambda n: n.name): update_str(n.name) update_str(n.op) update_strs(n.input) update_num(len(n.attr)) # NOTE: protobuf map serialization does not guarantee ordering. for k in sorted(n.attr): update_str(k) update_str(n.attr[k].SerializeToString()) return hasher.hexdigest()[:8] def add_to_graph(self, g): """Adds this function into the graph g.""" self._create_definition_if_needed() # Adds this function into 'g'. # pylint: disable=protected-access if context.executing_eagerly(): context.context().add_function_def(self.definition) else: g._add_function(self) # pylint: enable=protected-access # Ensures related sub-routines are defined in 'g', too. for f in self._sub_functions.values(): f.add_to_graph(g) # Adds its gradient function, too. if self._grad_func: self._grad_func.add_to_graph(g) def __call__(self, *args, **kwargs): self.add_to_graph(ops.get_default_graph()) args = [ops.convert_to_tensor(_) for _ in args] + self._extra_inputs ret, op = _call(self._signature, *args, **kwargs) # Set a hidden attr in 'op' so that gradients_impl can refer back # to this _DefinedFunction instance to access python_grad_func. assert isinstance(op, ops.Operation) setattr(op, "__defun", self) if self._shape_func is not None: shapes = self._shape_func(op) if len(shapes) != len(op.outputs): raise ValueError("shape_func produced %d shapes for %d outputs" % (len(shapes), len(op.outputs))) for (t, shape) in zip(op.outputs, shapes): t.set_shape(shape) return ret class _OverloadedFunction(object): """_OverloadedFunction encapsulates an overloaded function. _OverloadedFunction maintains a mapping from input types to instantiated _DefinedFunction in self._overload. """ def __init__(self, func, argnames, func_name=None, grad_func=None, python_grad_func=None, out_names=None, **kwargs): """Creates _DefinedFunction. Args: func: A python callable which constructs a tf function body. argnames: A list of strings for function argument names. func_name: The function name. Defaults to None, in which derives from 'func'. grad_func: This function's gradient function, if not None. Defaults to None. python_grad_func: A python callable implementing the gradient of the function python-side. out_names: A list of strings for the function return value names. **kwargs: The keyword arguments. **kwargs is passed to every call site of this function. Raises: ValueError: The function definition is invalid. """ self._func = func self._argnames = argnames self._func_name = func_name assert grad_func is None or isinstance(grad_func, _OverloadedFunction) self._grad_func = grad_func self._python_grad_func = python_grad_func self._out_names = out_names self._extra_kwargs = kwargs self._overload = {} def instantiate(self, input_types): """Instantiate this function given input argument types. Args: input_types: A list of data types for the inputs. Returns: _DefinedFunction for the given input types. """ # Stringify the type list. key = _type_list_to_str(input_types) defined = self._overload.get(key) if not defined: # If not defined yet, define the function given the input types. name = self._func_name if name is not None: name = "_".join([name, key]) defined = _DefinedFunction( self._func, self._argnames, input_types, name, None, self._python_grad_func, out_names=self._out_names, **self._extra_kwargs) _ = defined.name # Fully instantiate the function definition. if self._grad_func: # If _grad_func is given, it is another # _OverloadedFunction. We need to instantiate it with the # right input types. output_types = [ dtypes.DType(_.type) for _ in defined._signature.output_arg # pylint: disable=protected-access ] # pylint: disable=protected-access defined._grad_func = self._grad_func.instantiate(input_types + output_types) # pylint: enable=protected-access self._overload[key] = defined return defined def __call__(self, *args, **kwargs): input_types = [] args = list(args) for (i, x) in enumerate(args): x = ops.convert_to_tensor(x) if not isinstance(x, ops.Tensor): raise ValueError("Expect a Tensor but get ", x) input_types.append(x.dtype) args[i] = x return self.instantiate(input_types)(*args, **kwargs) class _FuncGraph(ops.Graph): """A helper for constructing a function. _FuncGraph overrides ops.Graph's create_op() so that we can keep track of all inputs into every op created inside the function. If any input is from other graphs, we keep track of it in self.capture and substitute the input with a place holder. Each captured input's corresponding place holder is converted into a function argument and the caller passes in the captured tensor. """ def __init__(self, name, capture_by_value, whitelisted_stateful_ops, capture_resource_var_by_value, *args, **kwargs): super(_FuncGraph, self).__init__(*args, **kwargs) self._capture_by_value = capture_by_value self._whitelisted_stateful_ops = whitelisted_stateful_ops self._capture_resource_var_by_value = capture_resource_var_by_value self._building_function = True self._outer_graph = ops.get_default_graph() self._vscope = vs.get_variable_scope() self._old_custom_getter = self._vscope.custom_getter # The name of the function. self.name = name # Placeholder tensors representing the inputs to this function. The tensors # are in this _FuncGraph. self.inputs = [] # Tensors that will be returned this function. The tensors are in this # _FuncGraph. self.outputs = [] # Maps external tensor -> internal tensor (e.g. input placeholder). self._captured = object_identity.ObjectIdentityDictionary() # The external tensors that have been captured as inputs and must be passed # to this function (empty if capturing by value, otherwise these are the # keys of _captured). self.extra_inputs = [] # Input placeholders that been added for captured values (empty if capturing # by value). self.extra_args = [] # Captured variables. # TODO(skyewm): is this needed? self.extra_vars = [] # pylint: disable=g-doc-return-or-yield @tf_contextlib.contextmanager def container(self, container_name): """Returns a context manager that specifies the resource container to use. Overridden from `tf.Graph` to update both the init_scope container and the present inner container. This is necessary to make sure setting containers applies correctly both to created variables and to stateful ops. Args: container_name: container name string. Returns: A context manager for defining resource containers for stateful ops, yields the container name. """ original_container = self._container # pylint: disable=protected-access with ops.init_scope(): original_init_container = ops.get_default_graph()._container try: self._container = container_name with ops.init_scope(): ops.get_default_graph()._container = container_name yield self._container finally: self._container = original_container with ops.init_scope(): ops.get_default_graph()._container = original_init_container # pylint: enable=protected-access # pylint: enable=g-doc-return-or-yield def getvar( self, getter, name, shape=None, dtype=None, initializer=None, reuse=None, trainable=True, collections=None, # pylint: disable=redefined-outer-name use_resource=None, **kwargs): """A custom variable getter.""" # Here, we switch the default graph to the outer graph and ask the # variable scope in which the function is defined to give us the # variable. The variable is stashed in extra_vars and returned to # the caller. # # We capture these variables so that the variable definition is # hoisted upward to the outer most graph. with self._outer_graph.as_default(): # pylint: disable=protected-access var = self._vscope.get_variable( vs._get_default_variable_store(), name, shape=shape, dtype=dtype, initializer=initializer, reuse=reuse, trainable=trainable, collections=collections, use_resource=use_resource) self.extra_vars.append(var) if (isinstance(var, resource_variable_ops.BaseResourceVariable) and self._capture_resource_var_by_value): # For resource-based variables read the variable outside the function # and pass in the value. This ensures that the function is pure and # differentiable. TODO(apassos) this may have performance problems if # the function will only do embedding lookups on the variable. return var.value() return var def _create_op_internal(self, op_type, inputs, dtypes=None, **kwargs): # pylint: disable=redefined-outer-name for i, x in enumerate(inputs): if isinstance(x, ops.EagerTensor) or x.graph is not self: inputs[i] = self.capture(x) return super(_FuncGraph, self)._create_op_internal( op_type, inputs, dtypes=dtypes, **kwargs) def capture(self, tensor, name=None): """Adds the given tensor to this graph and returns the captured tensor.""" if tensor in self._captured: # Captured already. return self._captured[tensor] elif self._capture_by_value: return self._add_tensor_and_parents(tensor) else: return self._capture_tensor_as_extra_input(tensor, name) def _capture_tensor_as_extra_input(self, tensor, name=None): # Substitute with a placeholder. self.extra_inputs.append(tensor) # Hoist the new input placeholder out of any control flow context # we're currently in. with ops.control_dependencies(None): ph = array_ops.placeholder( tensor.dtype, shape=tensor.get_shape(), name=name) # pylint: disable=protected-access if isinstance(tensor, ops.EagerTensor): handle_data = tensor._handle_data if handle_data: handle_data = handle_data.SerializeToString() else: handle_data = c_api.GetHandleShapeAndType(tensor.graph._c_graph, tensor._as_tf_output()) if handle_data: c_api.SetHandleShapeAndType(ph.graph._c_graph, ph._as_tf_output(), compat.as_bytes(handle_data)) # pylint: enable=protected-access self.inputs.append(ph) self._captured[tensor] = ph self.extra_args.append(ph) if _is_guaranteed_const(tensor): with ops.control_dependencies(None): return array_ops.guarantee_const(ph) else: return ph def _add_tensor_and_parents(self, tensor): op = self._add_op_and_parents(tensor.op) return op.outputs[tensor.value_index] def _add_op_and_parents(self, op): # pylint: disable=protected-access op_def = graph_to_function_def._get_op_def(op) if op._is_stateful and op not in self._whitelisted_stateful_ops: raise ValueError("Cannot capture a stateful node (name:%s, type:%s) " "by value." % (op.name, op.type)) elif op.type in ("Placeholder", "PlaceholderV2"): raise ValueError("Cannot capture a placeholder (name:%s, type:%s) " "by value." % (op.name, op.type)) # pylint: enable=protected-access captured_inputs = [self._add_tensor_and_parents(x) for x in op.inputs] captured_op = self._create_op_internal( op.type, captured_inputs, [o.dtype for o in op.outputs], name=op.name, attrs=op.node_def.attr, op_def=op_def) for t, captured_t in zip(op.outputs, captured_op.outputs): self._captured[t] = captured_t return captured_op def func_graph_from_py_func(func, arg_names, arg_types, name=None, capture_by_value=False, device=None, colocation_stack=None, container=None, collections_ref=None, arg_shapes=None, whitelisted_stateful_ops=None, capture_resource_var_by_value=True): """Returns a _FuncGraph generated from `func`. Args: func: A Python callable which constructs a TF function body. The arguments must correspond to `arg_types`. Returns a value or list/tuple of values. No returned value can be None. arg_names: A sequence of strings for the function argument names. arg_types: A sequence of the function's argument types. name: The function name. If None, the name is derived from `func`. capture_by_value: boolean. If True, captured values will be copied into the function body. device: device name or function. colocation_stack: A colocation stack (list) the _FuncGraph should use. container: A container name the _FuncGraph should start with. collections_ref: A reference to a collections dict the _FuncGraph should use internally. arg_shapes: A sequence of the function's argument shapes. whitelisted_stateful_ops: A set of ops that if stateful we ignore and re-create. capture_resource_var_by_value: Boolean (defaults to True). If False, captured resource variable returns the handle instead of value. Returns: A _FuncGraph. Raises: ValueError: if func returns None. """ if not name: name = function_utils.get_func_name(func) func_graph = _FuncGraph(name, capture_by_value, whitelisted_stateful_ops, capture_resource_var_by_value) with func_graph.as_default(), ops.device(device): # pylint: disable=protected-access if collections_ref is not None: func_graph._collections = collections_ref if container is not None: func_graph._container = container if colocation_stack is not None: func_graph._colocation_stack = colocation_stack # pylint: enable=protected-access if arg_shapes is None: arg_shapes = [None] * len(arg_types) # Create placeholders for the function arguments. for (argname, argtype, argshape) in zip(arg_names, arg_types, arg_shapes): argholder = array_ops.placeholder(argtype, shape=argshape, name=argname) func_graph.inputs.append(argholder) # Call func and gather the output tensors. with vs.variable_scope("", custom_getter=func_graph.getvar): outputs = func(*func_graph.inputs) # There is no way of distinguishing between a function not returning # anything and a function returning None in Python. # We need to allow the former and ideally want to forbid the latter as # it is most likely user error. # TODO(iga): Consider adding a @NoOutput decorator on top of @Defun to # allow users to explicitly mark the function as not returning anything. # For now, we allow a single None return and interpret it as a function # with no output. if outputs is None: outputs = [] else: # If func only returned one value, make it a tuple. if not isinstance(outputs, (list, tuple)): outputs = (outputs,) if any(_ is None for _ in outputs): raise ValueError("Function %s can not return None." % name) # Ensures each output is a Tensor in the function graph. outputs = [ops.convert_to_tensor(t) for t in outputs] outputs = [func_graph.capture(t) if t.graph is not func_graph else t for t in outputs] func_graph.outputs = outputs return func_graph def _is_guaranteed_const(tensor): """Determines whether `tensor` is guaranteed to be a constant. A tensor is guaranteed to be a constant if either it was produced by a `GuaranteeConst` op or if all of its children are guaranteed to be constants. Args: tensor: The tensor for which to determine const-ness. Returns: True if `tensor` is guaranteed to be a constant, False otherwise. """ if isinstance(tensor, ops.EagerTensor): return False class Work(object): def __init__(self, op, leaving): self.op = op self.leaving = leaving is_guaranteed_const = lambda op: op.node_def.op == "GuaranteeConst" constants = set([]) def all_inputs_const(op): # If all inputs of an op are guaranteed constants, then we can infer that # the op produces a constant as well. return op.inputs and all(inp.op in constants for inp in op.inputs) visited = set([]) stack = [Work(tensor.op, leaving=False)] while stack: work = stack.pop() if work.leaving: if all_inputs_const(work.op): constants.add(work.op) continue visited.add(work.op) if is_guaranteed_const(work.op): constants.add(work.op) continue # This op will be revisited after all its inputs are checked for const-ness. stack.append(Work(work.op, leaving=True)) for inp in work.op.inputs: if inp.op not in visited: stack.append(Work(inp.op, leaving=False)) return tensor.op in constants def _call(sig, *inputs, **kwargs): """Adds a node calling a function. This adds a `call` op to the default graph that calls the function of signature `sig`, passing the tensors in `inputs` as arguments. It returns the outputs of the call, which are one or more tensors. `sig` is OpDefArg.a `_DefinedFunction` object. You can pass an optional keyword parameter `name=string` to name the added operation. You can pass an optional keyword parameter `noinline=True|False` to instruct the runtime not to inline the function body into the call site. Args: sig: OpDefArg. The signature of the function. *inputs: arguments to the function. **kwargs: Optional keyword arguments. Can only contain 'name' or 'noinline'. Returns: A 2-element tuple. First element: a Tensor if the function returns a single value; a list of Tensors if the function returns multiple value; the Operation if the function returns no values. Second element: the Operation. Raises: ValueError: if the arguments are invalid. """ if len(inputs) != len(sig.input_arg): raise ValueError("Expected number of arguments: %d, received: %d" % (len( sig.input_arg), len(inputs))) name = kwargs.pop("name", None) g = ops.get_default_graph() func_name = sig.name if name is None: name = func_name attrs = _parse_kwargs_as_attrs(func_name, **kwargs) output_types = [dtypes.DType(x.type) for x in sig.output_arg] op = g._create_op_internal( # pylint: disable=protected-access func_name, list(inputs), output_types, name=name, attrs=attrs, op_def=sig) if op.outputs: if len(op.outputs) == 1: ret = op.outputs[0] else: ret = tuple(op.outputs) else: ret = op return ret, op def _from_definition(fdef, grad_func=None): """Creates a _DefinedFunction initialized from a FunctionDef proto. Args: fdef: a FunctionDef grad_func: a _DefinedFunction or None Returns: A _DefinedFunction representing fdef """ # TODO(iga): This method does major surgery on _DefinedFunction. # Make it a named constructor using @classmethod of _DefinedFunction. # The Python callable is only needed to create a FunctionDef. Since we have # the FunctionDef here, we don't need to set _DefinedFunction._func (nor do we # have access to such a callable here). func = None argnames = [arg.name for arg in fdef.signature.input_arg] input_types = tuple( dtypes.as_dtype(arg.type) for arg in fdef.signature.input_arg) func_name = fdef.signature.name # Note: FunctionDefs do not include python gradient functions, so if the # original _DefinedFunction included one it will not be reflected here. python_grad_func = None out_names = [arg.name for arg in fdef.signature.output_arg] result = _DefinedFunction(func, argnames, input_types, func_name, grad_func, python_grad_func, out_names) # pylint: disable=protected-access serialized = fdef.SerializeToString() c_func = c_api.TF_FunctionImportFunctionDef(serialized) result._c_func = c_api_util.ScopedTFFunction(c_func) result._extra_inputs = [] result._op_def = fdef.signature # pylint: enable=protected-access return result def from_library(lib): """Creates _DefinedFunctions initialized from a FunctionDefLibrary proto. This method handles assigning the correct gradient functions to each function. Args: lib: a FunctionDefLibrary Returns: A list of _DefinedFunctions Raises: ValueError: `lib` is invalid """ if not lib.function and not lib.gradient: return [] # function name -> FunctionDef proto funcs = {fdef.signature.name: fdef for fdef in lib.function} # Validate that all references function names have function defs for g in lib.gradient: if g.function_name not in funcs: raise ValueError("FunctionDefLibrary missing '%s' FunctionDef\n%s" % (g.function_name, str(lib))) if g.gradient_func not in funcs: raise ValueError("FunctionDefLibrary missing '%s' FunctionDef\n%s" % (g.gradient_func, str(lib))) # function name -> gradient function name func_to_grad = collections.defaultdict(lambda: None) # gradient function name -> names of functions having that grad function grad_to_funcs = collections.defaultdict(list) for gdef in lib.gradient: func_to_grad[gdef.function_name] = gdef.gradient_func grad_to_funcs[gdef.gradient_func].append(gdef.function_name) # Start with functions without gradients ready = [ fdef for fdef in lib.function if func_to_grad[fdef.signature.name] is None ] if not ready: raise ValueError( "FunctionDefLibrary contains cyclic gradient functions!\n" + str(lib)) # function name -> _DefinedFunction initialized = {} while ready: fdef = ready.pop() name = fdef.signature.name grad = initialized.get(func_to_grad[name]) if func_to_grad[name]: assert grad defined_func = _from_definition(fdef, grad_func=grad) initialized[name] = defined_func ready.extend(funcs[f] for f in grad_to_funcs[name]) return initialized.values() def _get_experimental_kwarg_as_attr(attr_name, value): """Creates an AttrValue for a python object.""" if isinstance(value, bool): return attr_value_pb2.AttrValue(b=value) elif isinstance(value, int): return attr_value_pb2.AttrValue(i=value) elif isinstance(value, float): return attr_value_pb2.AttrValue(f=value) elif isinstance(value, str): return attr_value_pb2.AttrValue(s=compat.as_bytes(value)) else: raise ValueError("Unsupported attribute type for %s with type %s" % (attr_name, type(value))) def _get_kwarg_as_str_attr(attr_name, value): """Creates an AttrValue for a python object.""" if isinstance(value, str): return attr_value_pb2.AttrValue(s=compat.as_bytes(value)) else: raise ValueError("Unsupported attribute type for %s with type %s" % (attr_name, type(value))) def _parse_kwargs_as_attrs(func_name, **kwargs): """Parses **kwargs into a node's attributes.""" attrs = {} noinline = kwargs.pop("noinline", None) if noinline is not None: attrs["_noinline"] = attr_value_pb2.AttrValue(b=bool(noinline)) # For compatibility with previous behavior, Defun does not perform shape # inference through its function call operations. attrs["_disable_call_shape_inference"] = attr_value_pb2.AttrValue(b=True) compiled = kwargs.pop("compiled", None) separate_compiled_gradients = kwargs.pop("separate_compiled_gradients", None) if compiled is not None: attrs["_XlaCompile"] = attr_value_pb2.AttrValue(b=bool(compiled)) attrs["_XlaSeparateCompiledGradients"] = attr_value_pb2.AttrValue( b=bool(separate_compiled_gradients)) # Forward _XlaScope from enclosing context (if set), otherwise create new. # pylint: disable=protected-access if "_XlaScope" in ops.get_default_graph()._attr_scope_map: attrs["_XlaScope"] = ops.get_default_graph()._attr_scope_map["_XlaScope"] else: attrs["_XlaScope"] = attr_value_pb2.AttrValue( s=("function_%s" % func_name).encode()) # pylint: enable=protected-access kwargs_keys = list(kwargs.keys()) for key in kwargs_keys: if key.startswith("experimental_"): attrs[key] = _get_experimental_kwarg_as_attr(key, kwargs[key]) del kwargs[key] # Support for https://github.com/tensorflow/community/pull/113/files. elif key == "_implements" or key == "_reference": attrs[key] = _get_kwarg_as_str_attr(key, kwargs[key]) del kwargs[key] if kwargs: raise ValueError("Unknown keyword arguments: %s" % kwargs.keys()) return attrs def get_extra_vars(): """Returns the captured variables by the function. Returns: If the default graph is being used to define a function, the returned list of variables are those created inside the function body so far. Otherwise, returns an empty list. """ g = ops.get_default_graph() if isinstance(g, _FuncGraph): return g.extra_vars else: return [] def get_extra_inputs(): """Returns the captured input tensors by the function. Returns: If the default graph is being used to define a function, the returned list of tensors are those accessed inside the function body but defined outside the function body so far. Otherwise, returns an empty list. """ g = ops.get_default_graph() if isinstance(g, _FuncGraph): return g.extra_inputs else: return [] def get_extra_args(): """Returns the corresponding function arguments for the captured inputs. Returns: If the default graph is being used to define a function, the returned list of place holders are those used inside the function body corresponding those returned by get_extra_inputs(). Otherwise, returns an empty list. """ g = ops.get_default_graph() if isinstance(g, _FuncGraph): return g.extra_args else: return [] def _type_list_to_str(types): if any(_ not in _DTYPE_TO_STR for _ in types): raise ValueError("Unsupported dtypes: %s" % types) return "".join([_DTYPE_TO_STR[_] for _ in types]) # NOTE: The list needs to be extended when more data types are added. _DTYPE_TO_STR = { dtypes.float16: "f16", dtypes.float32: "f32", dtypes.float64: "f64", dtypes.int32: "i32", dtypes.uint8: "i8", dtypes.uint16: "u16", dtypes.uint32: "u32", dtypes.uint64: "u64", dtypes.int16: "i16", dtypes.int8: "i8", dtypes.string: "s", dtypes.complex64: "c64", dtypes.complex128: "c128", dtypes.int64: "i64", dtypes.bool: "b", dtypes.qint8: "qi8", dtypes.quint8: "qu8", dtypes.qint16: "qi16", dtypes.quint16: "qu16", dtypes.qint32: "qi32", dtypes.bfloat16: "b16" } def function_def_from_tf_function(c_func): """Converts a SWIG-wrapped TF_Function* to a FunctionDef proto.""" with c_api_util.tf_buffer() as buf: c_api.TF_FunctionToFunctionDef(c_func, buf) data = c_api.TF_GetBuffer(buf) fdef = function_pb2.FunctionDef() fdef.ParseFromString(compat.as_bytes(data)) return fdef
en
0.716719
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= Python front-end supports for functions. NOTE: At this time, functions are experimental and subject to change!. Proceed with caution. Decorator used to define TensorFlow functions. Use this decorator to make a Python function usable directly as a TensorFlow function. The decorated function must add ops to the default graph and return zero or more `Tensor` objects. Call the decorator with named arguments, one for each argument of the function to decorate, with the expected type of the argument as value. For example if the function to decorate accepts two `tf.float32` arguments named `x` and `y`, call the decorator with: @Defun(tf.float32, tf.float32) def foo(x, y): ... When you call the decorated function, it adds the `call` ops to the default graph. In addition, it adds the definition of the function into the default graph. Because the addition of the function into the graph is deferred, the decorator can be used anywhere in the program. Any variables created inside of the function are hoisted into the outer graph. Note that the variables are created in the variable scope that was active during the first call to the function. Subsequent function calls will refer to the same set of variables. Definitions of functions in a graph are frozen as soon as the graph is used to create a session. However, new functions and new calls to existing functions may be added to the graph, with the new functions themselves becoming immediately frozen. Example, but also see the [How To on functions](link_needed). ```python # Defining the function. @tf.Defun(tf.float32, tf.float32) def MyFunc(x, y): return x + y, x - y # Building the graph. a = tf.constant([1.0]) b = tf.constant([2.0]) c, d = MyFunc(a, b, name='mycall') ``` Create a `Defun` decorator. Args: *input_types: A list of `tf.DType` **kwargs: Optional keyword arguments, including func_name - (optional). A python string, the name to use to declare this `Function` in the graph. grad_func - (optional). A function implementing the gradient of the function-to-register. This is must be a `_DefinedFunction` object. The gradient function must satisfy the criterion defined in function.proto:GradientDef. python_grad_func - (optional). A function implementing the gradient of the function python-side. This function must take the current op and the gradients w.r.t. its outputs, and return the gradients w.r.t. the inputs. That is it must implement the interface expected by `tf.RegisterGradient`). This will be called by tf.gradients to add the gradient ops to the graph. At most one of grad_func and python_grad_func can be specified. out_names = (optional). A list of strings, one per output tensor. shape_func - (optional). A function taking the op and returning a list of static shapes to set for the function's outputs. # Various sanity checks on the callable func. # Func should not use kwargs and defaults. # Computes how many arguments 'func' has. # 1st argument is the "class" type. # If Defun is given a list of types for the inputs, the number # of input types should be compatible with 'func'. # 'func' expects no arguments and input types is an empty list. # Input types are unknown. It's an overloaded function and hence # its definition needs to be deferred until it's called. Unregister function from eager context. # Suppress some exceptions, mainly for the case when we're running on # module deletion. Things that can go wrong include the context module # already being unloaded, self._handle._handle_data no longer being # valid, and so on. Printing warnings in these cases is silly # (exceptions raised from __del__ are printed as warnings to stderr). # 'NoneType' object is not callable when the handle has been # partially unloaded. # 'NoneType' object has no attribute 'eager_mode' when context has # been unloaded. Will catch other module unloads as well. _DefinedFunction encapsulates a function definition and its properties. Attributes: name: The function name. definition: The definition of this function. A FunctionDef proto. grad_func_name: If not None, the name of this function's gradient function. python_grad_func: A python callable implementing the gradient of the function python-side. Creates _DefinedFunction. Args: func: A python callable which constructs a tf function body. argnames: A list of strings for function argument names. input_types: The function's argument types. Can be a tuple, list of tf data types. func_name: The function name. Defaults to None, in which derives from 'func'. grad_func: This function's gradient function, if not None. Defaults to None. python_grad_func: A python callable implementing the gradient of the function python-side. out_names: An optional list of strings for the function return value names. shape_func: An optional function mapping an op to a list of static output shapes. capture_by_value: Boolean (defaults to False). If True, captured values will be copied into the function body. whitelisted_stateful_ops: A set of ops that if stateful we ignore and copy into the function body, when `capture_by_value` is True. capture_resource_var_by_value: Boolean (defaults to True). If False, captured resource variable returns the handle instead of value. **kwargs: The keyword arguments. **kwargs is passed to every call site of this function. Raises: ValueError: The function definition is invalid. # Constructed only when C API is disabled, lazily # Constructed only when C API is enabled, lazily # Constructed with _definition or _c_func # pylint: disable=protected-access # pylint: enable=protected-access # Get the innermost device if possbile. # Cached OpDef for this function. When C API is enabled, this is # the only part of FunctionDef that we cache in Python. When C API # is disabled the whole _definition is available and this is simply # another reference to _definition.signature Function name. Function definition proto. Specifies the gradient function of this function. Returns the name of the gradient function. Python gradient function callable. Returns the list of data types of explicit declared inputs. Returns the list of implicitly captured inputs. Returns the list of stateful ops in function definition. Returns: A list of (op.name, op.type) pairs. Creates the function definition if it's not created yet. This is not what you want, see _create_definition_if_needed. # Copy variable collections (by reference) from the parent graph such that # name based variable sharing (e.g. via tf.make_template) works between the # func graph and parent graph. # pylint: disable=protected-access # pylint: disable=protected-access # pylint: disable=protected-access # pylint: disable=protected-access # pylint: enable=protected-access # Extra kwargs are treated as attrs on the function def. # pylint: disable=protected-access # Build the FunctionDef # Hash the definition and its dependencies. # Finally, we decide the function name to use. If not specified, # make up something which is almost certainly unique (but deterministic). # C API is enabled # pylint: disable=protected-access # append_hash_to_fn_name # opers # control_outputs # control_output_names # opts # pylint: enable=protected-access # Set cached fields: _op_def and _func_name (if not already set) # pylint: disable=protected-access Sets `attrs` as attributes of self._c_func. Requires that self._c_func is not None. Args: attrs: a dictionary from attribute name to attribute proto value # TODO(skyewm): this creates and deletes a new TF_Status for every attr. # It might be worth creating a convenient way to re-use the same status. Creates an 8-character string unique to this input. Args: input_arg: the input_arg field of an OpDef (e.g. self._definition.signature.input_arg) output_arg: the output_arg field of an OpDef (e.g. self._definition.signature.output_arg) node_def: the node_def field of a FunctionDef (e.g. self._definition.node_def) Returns: The unique string for this input # NOTE: protobuf map serialization does not guarantee ordering. Adds this function into the graph g. # Adds this function into 'g'. # pylint: disable=protected-access # pylint: enable=protected-access # Ensures related sub-routines are defined in 'g', too. # Adds its gradient function, too. # Set a hidden attr in 'op' so that gradients_impl can refer back # to this _DefinedFunction instance to access python_grad_func. _OverloadedFunction encapsulates an overloaded function. _OverloadedFunction maintains a mapping from input types to instantiated _DefinedFunction in self._overload. Creates _DefinedFunction. Args: func: A python callable which constructs a tf function body. argnames: A list of strings for function argument names. func_name: The function name. Defaults to None, in which derives from 'func'. grad_func: This function's gradient function, if not None. Defaults to None. python_grad_func: A python callable implementing the gradient of the function python-side. out_names: A list of strings for the function return value names. **kwargs: The keyword arguments. **kwargs is passed to every call site of this function. Raises: ValueError: The function definition is invalid. Instantiate this function given input argument types. Args: input_types: A list of data types for the inputs. Returns: _DefinedFunction for the given input types. # Stringify the type list. # If not defined yet, define the function given the input types. # Fully instantiate the function definition. # If _grad_func is given, it is another # _OverloadedFunction. We need to instantiate it with the # right input types. # pylint: disable=protected-access # pylint: disable=protected-access # pylint: enable=protected-access A helper for constructing a function. _FuncGraph overrides ops.Graph's create_op() so that we can keep track of all inputs into every op created inside the function. If any input is from other graphs, we keep track of it in self.capture and substitute the input with a place holder. Each captured input's corresponding place holder is converted into a function argument and the caller passes in the captured tensor. # The name of the function. # Placeholder tensors representing the inputs to this function. The tensors # are in this _FuncGraph. # Tensors that will be returned this function. The tensors are in this # _FuncGraph. # Maps external tensor -> internal tensor (e.g. input placeholder). # The external tensors that have been captured as inputs and must be passed # to this function (empty if capturing by value, otherwise these are the # keys of _captured). # Input placeholders that been added for captured values (empty if capturing # by value). # Captured variables. # TODO(skyewm): is this needed? # pylint: disable=g-doc-return-or-yield Returns a context manager that specifies the resource container to use. Overridden from `tf.Graph` to update both the init_scope container and the present inner container. This is necessary to make sure setting containers applies correctly both to created variables and to stateful ops. Args: container_name: container name string. Returns: A context manager for defining resource containers for stateful ops, yields the container name. # pylint: disable=protected-access # pylint: enable=protected-access # pylint: enable=g-doc-return-or-yield # pylint: disable=redefined-outer-name A custom variable getter. # Here, we switch the default graph to the outer graph and ask the # variable scope in which the function is defined to give us the # variable. The variable is stashed in extra_vars and returned to # the caller. # # We capture these variables so that the variable definition is # hoisted upward to the outer most graph. # pylint: disable=protected-access # For resource-based variables read the variable outside the function # and pass in the value. This ensures that the function is pure and # differentiable. TODO(apassos) this may have performance problems if # the function will only do embedding lookups on the variable. # pylint: disable=redefined-outer-name Adds the given tensor to this graph and returns the captured tensor. # Captured already. # Substitute with a placeholder. # Hoist the new input placeholder out of any control flow context # we're currently in. # pylint: disable=protected-access # pylint: enable=protected-access # pylint: disable=protected-access # pylint: enable=protected-access Returns a _FuncGraph generated from `func`. Args: func: A Python callable which constructs a TF function body. The arguments must correspond to `arg_types`. Returns a value or list/tuple of values. No returned value can be None. arg_names: A sequence of strings for the function argument names. arg_types: A sequence of the function's argument types. name: The function name. If None, the name is derived from `func`. capture_by_value: boolean. If True, captured values will be copied into the function body. device: device name or function. colocation_stack: A colocation stack (list) the _FuncGraph should use. container: A container name the _FuncGraph should start with. collections_ref: A reference to a collections dict the _FuncGraph should use internally. arg_shapes: A sequence of the function's argument shapes. whitelisted_stateful_ops: A set of ops that if stateful we ignore and re-create. capture_resource_var_by_value: Boolean (defaults to True). If False, captured resource variable returns the handle instead of value. Returns: A _FuncGraph. Raises: ValueError: if func returns None. # pylint: disable=protected-access # pylint: enable=protected-access # Create placeholders for the function arguments. # Call func and gather the output tensors. # There is no way of distinguishing between a function not returning # anything and a function returning None in Python. # We need to allow the former and ideally want to forbid the latter as # it is most likely user error. # TODO(iga): Consider adding a @NoOutput decorator on top of @Defun to # allow users to explicitly mark the function as not returning anything. # For now, we allow a single None return and interpret it as a function # with no output. # If func only returned one value, make it a tuple. # Ensures each output is a Tensor in the function graph. Determines whether `tensor` is guaranteed to be a constant. A tensor is guaranteed to be a constant if either it was produced by a `GuaranteeConst` op or if all of its children are guaranteed to be constants. Args: tensor: The tensor for which to determine const-ness. Returns: True if `tensor` is guaranteed to be a constant, False otherwise. # If all inputs of an op are guaranteed constants, then we can infer that # the op produces a constant as well. # This op will be revisited after all its inputs are checked for const-ness. Adds a node calling a function. This adds a `call` op to the default graph that calls the function of signature `sig`, passing the tensors in `inputs` as arguments. It returns the outputs of the call, which are one or more tensors. `sig` is OpDefArg.a `_DefinedFunction` object. You can pass an optional keyword parameter `name=string` to name the added operation. You can pass an optional keyword parameter `noinline=True|False` to instruct the runtime not to inline the function body into the call site. Args: sig: OpDefArg. The signature of the function. *inputs: arguments to the function. **kwargs: Optional keyword arguments. Can only contain 'name' or 'noinline'. Returns: A 2-element tuple. First element: a Tensor if the function returns a single value; a list of Tensors if the function returns multiple value; the Operation if the function returns no values. Second element: the Operation. Raises: ValueError: if the arguments are invalid. # pylint: disable=protected-access Creates a _DefinedFunction initialized from a FunctionDef proto. Args: fdef: a FunctionDef grad_func: a _DefinedFunction or None Returns: A _DefinedFunction representing fdef # TODO(iga): This method does major surgery on _DefinedFunction. # Make it a named constructor using @classmethod of _DefinedFunction. # The Python callable is only needed to create a FunctionDef. Since we have # the FunctionDef here, we don't need to set _DefinedFunction._func (nor do we # have access to such a callable here). # Note: FunctionDefs do not include python gradient functions, so if the # original _DefinedFunction included one it will not be reflected here. # pylint: disable=protected-access # pylint: enable=protected-access Creates _DefinedFunctions initialized from a FunctionDefLibrary proto. This method handles assigning the correct gradient functions to each function. Args: lib: a FunctionDefLibrary Returns: A list of _DefinedFunctions Raises: ValueError: `lib` is invalid # function name -> FunctionDef proto # Validate that all references function names have function defs # function name -> gradient function name # gradient function name -> names of functions having that grad function # Start with functions without gradients # function name -> _DefinedFunction Creates an AttrValue for a python object. Creates an AttrValue for a python object. Parses **kwargs into a node's attributes. # For compatibility with previous behavior, Defun does not perform shape # inference through its function call operations. # Forward _XlaScope from enclosing context (if set), otherwise create new. # pylint: disable=protected-access # pylint: enable=protected-access # Support for https://github.com/tensorflow/community/pull/113/files. Returns the captured variables by the function. Returns: If the default graph is being used to define a function, the returned list of variables are those created inside the function body so far. Otherwise, returns an empty list. Returns the captured input tensors by the function. Returns: If the default graph is being used to define a function, the returned list of tensors are those accessed inside the function body but defined outside the function body so far. Otherwise, returns an empty list. Returns the corresponding function arguments for the captured inputs. Returns: If the default graph is being used to define a function, the returned list of place holders are those used inside the function body corresponding those returned by get_extra_inputs(). Otherwise, returns an empty list. # NOTE: The list needs to be extended when more data types are added. Converts a SWIG-wrapped TF_Function* to a FunctionDef proto.
1.894041
2
rplugin/python3/deoplete/filter/matcher_full_fuzzy.py
nholik/deoplete.nvim
0
6625137
# ============================================================================ # FILE: matcher_full_fuzzy.py # AUTHOR: <NAME> <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================ import re from deoplete.base.filter import Base from deoplete.util import fuzzy_escape class Filter(Base): def __init__(self, vim): super().__init__(vim) self.name = 'matcher_full_fuzzy' self.description = 'full fuzzy matcher' def filter(self, context): complete_str = context['complete_str'] if context['ignorecase']: complete_str = complete_str.lower() p = re.compile(fuzzy_escape(complete_str, context['camelcase'])) if context['ignorecase']: return [x for x in context['candidates'] if p.search(x['word'].lower())] else: return [x for x in context['candidates'] if p.search(x['word'])]
# ============================================================================ # FILE: matcher_full_fuzzy.py # AUTHOR: <NAME> <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================ import re from deoplete.base.filter import Base from deoplete.util import fuzzy_escape class Filter(Base): def __init__(self, vim): super().__init__(vim) self.name = 'matcher_full_fuzzy' self.description = 'full fuzzy matcher' def filter(self, context): complete_str = context['complete_str'] if context['ignorecase']: complete_str = complete_str.lower() p = re.compile(fuzzy_escape(complete_str, context['camelcase'])) if context['ignorecase']: return [x for x in context['candidates'] if p.search(x['word'].lower())] else: return [x for x in context['candidates'] if p.search(x['word'])]
en
0.332418
# ============================================================================ # FILE: matcher_full_fuzzy.py # AUTHOR: <NAME> <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================
2.468983
2
util/tfrecord.py
entn-at/yamagishilab_tacotron2
80
6625138
<reponame>entn-at/yamagishilab_tacotron2 # ============================================================================== # Copyright (c) 2018, Yamagishi Laboratory, National Institute of Informatics # Author: <NAME> (<EMAIL>) # All rights reserved. # ============================================================================== """ Reading and writing TFRecord files """ import tensorflow as tf import numpy as np from collections import namedtuple from collections.abc import Iterable class PreprocessedSourceData(namedtuple("PreprocessedSourceData", ["id", "text", "source", "source_length", "text2", "source2", "source_length2"])): pass class PreprocessedTargetData(namedtuple("PreprocessedTargetData", ["id", "spec", "spec_width", "mel", "mel_width", "target_length"])): pass def bytes_feature(value): assert isinstance(value, Iterable) return tf.train.Feature(bytes_list=tf.train.BytesList(value=value)) def int64_feature(value): assert isinstance(value, Iterable) return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) def write_tfrecord(example: tf.train.Example, filename: str): with tf.python_io.TFRecordWriter(filename) as writer: writer.write(example.SerializeToString()) def write_preprocessed_target_data(id: int, spec: np.ndarray, mel: np.ndarray, filename: str): raw_spec = spec.tostring() raw_mel = mel.tostring() example = tf.train.Example(features=tf.train.Features(feature={ 'id': int64_feature([id]), 'spec': bytes_feature([raw_spec]), 'spec_width': int64_feature([spec.shape[1]]), 'mel': bytes_feature([raw_mel]), 'mel_width': int64_feature([mel.shape[1]]), 'target_length': int64_feature([len(mel)]), })) write_tfrecord(example, filename) def write_preprocessed_source_data2(id: int, text1: str, source1: np.ndarray, text2: str, source2: np.ndarray, filename: str): raw_source1 = source1.tostring() raw_source2 = source2.tostring() example = tf.train.Example(features=tf.train.Features(feature={ 'id': int64_feature([id]), 'text': bytes_feature([text1.encode('utf-8'), text2.encode('utf-8')]), 'source': bytes_feature([raw_source1, raw_source2]), 'source_length': int64_feature([len(source1), len(source2)]), })) write_tfrecord(example, filename) def parse_preprocessed_target_data(proto): features = { 'id': tf.FixedLenFeature((), tf.int64), 'spec': tf.FixedLenFeature((), tf.string), 'spec_width': tf.FixedLenFeature((), tf.int64), 'mel': tf.FixedLenFeature((), tf.string), 'mel_width': tf.FixedLenFeature((), tf.int64), 'target_length': tf.FixedLenFeature((), tf.int64), } parsed_features = tf.parse_single_example(proto, features) return parsed_features def decode_preprocessed_target_data(parsed): spec_width = parsed['spec_width'] mel_width = parsed['mel_width'] target_length = parsed['target_length'] spec = tf.decode_raw(parsed['spec'], tf.float32) mel = tf.decode_raw(parsed['mel'], tf.float32) return PreprocessedTargetData( id=parsed['id'], spec=tf.reshape(spec, shape=tf.stack([target_length, spec_width], axis=0)), spec_width=spec_width, mel=tf.reshape(mel, shape=tf.stack([target_length, mel_width], axis=0)), mel_width=mel_width, target_length=target_length, ) def parse_preprocessed_source_data(proto): features = { 'id': tf.FixedLenFeature((), tf.int64), 'text': tf.FixedLenFeature((2), tf.string), 'source': tf.FixedLenFeature((2), tf.string), 'source_length': tf.FixedLenFeature((2), tf.int64), } parsed_features = tf.parse_single_example(proto, features) return parsed_features def decode_preprocessed_source_data(parsed): source = tf.decode_raw(parsed['source'][0], tf.int64) source2 = tf.decode_raw(parsed['source'][1], tf.int64) return PreprocessedSourceData( id=parsed['id'], text=parsed['text'][0], source=source, source_length=parsed['source_length'][0], text2=parsed['text'][1], source2=source2, source_length2=parsed['source_length'][1], )
# ============================================================================== # Copyright (c) 2018, Yamagishi Laboratory, National Institute of Informatics # Author: <NAME> (<EMAIL>) # All rights reserved. # ============================================================================== """ Reading and writing TFRecord files """ import tensorflow as tf import numpy as np from collections import namedtuple from collections.abc import Iterable class PreprocessedSourceData(namedtuple("PreprocessedSourceData", ["id", "text", "source", "source_length", "text2", "source2", "source_length2"])): pass class PreprocessedTargetData(namedtuple("PreprocessedTargetData", ["id", "spec", "spec_width", "mel", "mel_width", "target_length"])): pass def bytes_feature(value): assert isinstance(value, Iterable) return tf.train.Feature(bytes_list=tf.train.BytesList(value=value)) def int64_feature(value): assert isinstance(value, Iterable) return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) def write_tfrecord(example: tf.train.Example, filename: str): with tf.python_io.TFRecordWriter(filename) as writer: writer.write(example.SerializeToString()) def write_preprocessed_target_data(id: int, spec: np.ndarray, mel: np.ndarray, filename: str): raw_spec = spec.tostring() raw_mel = mel.tostring() example = tf.train.Example(features=tf.train.Features(feature={ 'id': int64_feature([id]), 'spec': bytes_feature([raw_spec]), 'spec_width': int64_feature([spec.shape[1]]), 'mel': bytes_feature([raw_mel]), 'mel_width': int64_feature([mel.shape[1]]), 'target_length': int64_feature([len(mel)]), })) write_tfrecord(example, filename) def write_preprocessed_source_data2(id: int, text1: str, source1: np.ndarray, text2: str, source2: np.ndarray, filename: str): raw_source1 = source1.tostring() raw_source2 = source2.tostring() example = tf.train.Example(features=tf.train.Features(feature={ 'id': int64_feature([id]), 'text': bytes_feature([text1.encode('utf-8'), text2.encode('utf-8')]), 'source': bytes_feature([raw_source1, raw_source2]), 'source_length': int64_feature([len(source1), len(source2)]), })) write_tfrecord(example, filename) def parse_preprocessed_target_data(proto): features = { 'id': tf.FixedLenFeature((), tf.int64), 'spec': tf.FixedLenFeature((), tf.string), 'spec_width': tf.FixedLenFeature((), tf.int64), 'mel': tf.FixedLenFeature((), tf.string), 'mel_width': tf.FixedLenFeature((), tf.int64), 'target_length': tf.FixedLenFeature((), tf.int64), } parsed_features = tf.parse_single_example(proto, features) return parsed_features def decode_preprocessed_target_data(parsed): spec_width = parsed['spec_width'] mel_width = parsed['mel_width'] target_length = parsed['target_length'] spec = tf.decode_raw(parsed['spec'], tf.float32) mel = tf.decode_raw(parsed['mel'], tf.float32) return PreprocessedTargetData( id=parsed['id'], spec=tf.reshape(spec, shape=tf.stack([target_length, spec_width], axis=0)), spec_width=spec_width, mel=tf.reshape(mel, shape=tf.stack([target_length, mel_width], axis=0)), mel_width=mel_width, target_length=target_length, ) def parse_preprocessed_source_data(proto): features = { 'id': tf.FixedLenFeature((), tf.int64), 'text': tf.FixedLenFeature((2), tf.string), 'source': tf.FixedLenFeature((2), tf.string), 'source_length': tf.FixedLenFeature((2), tf.int64), } parsed_features = tf.parse_single_example(proto, features) return parsed_features def decode_preprocessed_source_data(parsed): source = tf.decode_raw(parsed['source'][0], tf.int64) source2 = tf.decode_raw(parsed['source'][1], tf.int64) return PreprocessedSourceData( id=parsed['id'], text=parsed['text'][0], source=source, source_length=parsed['source_length'][0], text2=parsed['text'][1], source2=source2, source_length2=parsed['source_length'][1], )
en
0.568486
# ============================================================================== # Copyright (c) 2018, Yamagishi Laboratory, National Institute of Informatics # Author: <NAME> (<EMAIL>) # All rights reserved. # ============================================================================== Reading and writing TFRecord files
2.471753
2
synapse/federation/federation_client.py
chagai95/synapse
0
6625139
# Copyright 2015-2022 The Matrix.org Foundation C.I.C. # Copyright 2020 Sorunome # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import itertools import logging from typing import ( TYPE_CHECKING, Awaitable, Callable, Collection, Container, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, TypeVar, Union, ) import attr from prometheus_client import Counter from synapse.api.constants import EventContentFields, EventTypes, Membership from synapse.api.errors import ( CodeMessageException, Codes, FederationDeniedError, HttpResponseException, RequestSendFailed, SynapseError, UnsupportedRoomVersionError, ) from synapse.api.room_versions import ( KNOWN_ROOM_VERSIONS, EventFormatVersions, RoomVersion, RoomVersions, ) from synapse.events import EventBase, builder from synapse.federation.federation_base import FederationBase, event_from_pdu_json from synapse.federation.transport.client import SendJoinResponse from synapse.http.types import QueryParams from synapse.types import JsonDict, UserID, get_domain_from_id from synapse.util.async_helpers import concurrently_execute from synapse.util.caches.expiringcache import ExpiringCache from synapse.util.retryutils import NotRetryingDestination if TYPE_CHECKING: from synapse.server import HomeServer logger = logging.getLogger(__name__) sent_queries_counter = Counter("synapse_federation_client_sent_queries", "", ["type"]) PDU_RETRY_TIME_MS = 1 * 60 * 1000 T = TypeVar("T") class InvalidResponseError(RuntimeError): """Helper for _try_destination_list: indicates that the server returned a response we couldn't parse """ @attr.s(slots=True, frozen=True, auto_attribs=True) class SendJoinResult: # The event to persist. event: EventBase # A string giving the server the event was sent to. origin: str state: List[EventBase] auth_chain: List[EventBase] # True if 'state' elides non-critical membership events partial_state: bool # if 'partial_state' is set, a list of the servers in the room (otherwise empty) servers_in_room: List[str] class FederationClient(FederationBase): def __init__(self, hs: "HomeServer"): super().__init__(hs) self.pdu_destination_tried: Dict[str, Dict[str, int]] = {} self._clock.looping_call(self._clear_tried_cache, 60 * 1000) self.state = hs.get_state_handler() self.transport_layer = hs.get_federation_transport_client() self.hostname = hs.hostname self.signing_key = hs.signing_key self._get_pdu_cache: ExpiringCache[str, EventBase] = ExpiringCache( cache_name="get_pdu_cache", clock=self._clock, max_len=1000, expiry_ms=120 * 1000, reset_expiry_on_get=False, ) # A cache for fetching the room hierarchy over federation. # # Some stale data over federation is OK, but must be refreshed # periodically since the local server is in the room. # # It is a map of (room ID, suggested-only) -> the response of # get_room_hierarchy. self._get_room_hierarchy_cache: ExpiringCache[ Tuple[str, bool], Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]], ] = ExpiringCache( cache_name="get_room_hierarchy_cache", clock=self._clock, max_len=1000, expiry_ms=5 * 60 * 1000, reset_expiry_on_get=False, ) def _clear_tried_cache(self) -> None: """Clear pdu_destination_tried cache""" now = self._clock.time_msec() old_dict = self.pdu_destination_tried self.pdu_destination_tried = {} for event_id, destination_dict in old_dict.items(): destination_dict = { dest: time for dest, time in destination_dict.items() if time + PDU_RETRY_TIME_MS > now } if destination_dict: self.pdu_destination_tried[event_id] = destination_dict async def make_query( self, destination: str, query_type: str, args: QueryParams, retry_on_dns_fail: bool = False, ignore_backoff: bool = False, ) -> JsonDict: """Sends a federation Query to a remote homeserver of the given type and arguments. Args: destination: Domain name of the remote homeserver query_type: Category of the query type; should match the handler name used in register_query_handler(). args: Mapping of strings to strings containing the details of the query request. ignore_backoff: true to ignore the historical backoff data and try the request anyway. Returns: The JSON object from the response """ sent_queries_counter.labels(query_type).inc() return await self.transport_layer.make_query( destination, query_type, args, retry_on_dns_fail=retry_on_dns_fail, ignore_backoff=ignore_backoff, ) async def query_client_keys( self, destination: str, content: JsonDict, timeout: int ) -> JsonDict: """Query device keys for a device hosted on a remote server. Args: destination: Domain name of the remote homeserver content: The query content. Returns: The JSON object from the response """ sent_queries_counter.labels("client_device_keys").inc() return await self.transport_layer.query_client_keys( destination, content, timeout ) async def query_user_devices( self, destination: str, user_id: str, timeout: int = 30000 ) -> JsonDict: """Query the device keys for a list of user ids hosted on a remote server. """ sent_queries_counter.labels("user_devices").inc() return await self.transport_layer.query_user_devices( destination, user_id, timeout ) async def claim_client_keys( self, destination: str, content: JsonDict, timeout: int ) -> JsonDict: """Claims one-time keys for a device hosted on a remote server. Args: destination: Domain name of the remote homeserver content: The query content. Returns: The JSON object from the response """ sent_queries_counter.labels("client_one_time_keys").inc() return await self.transport_layer.claim_client_keys( destination, content, timeout ) async def backfill( self, dest: str, room_id: str, limit: int, extremities: Collection[str] ) -> Optional[List[EventBase]]: """Requests some more historic PDUs for the given room from the given destination server. Args: dest: The remote homeserver to ask. room_id: The room_id to backfill. limit: The maximum number of events to return. extremities: our current backwards extremities, to backfill from Must be a Collection that is falsy when empty. (Iterable is not enough here!) """ logger.debug("backfill extrem=%s", extremities) # If there are no extremities then we've (probably) reached the start. if not extremities: return None transaction_data = await self.transport_layer.backfill( dest, room_id, extremities, limit ) logger.debug("backfill transaction_data=%r", transaction_data) if not isinstance(transaction_data, dict): # TODO we probably want an exception type specific to federation # client validation. raise TypeError("Backfill transaction_data is not a dict.") transaction_data_pdus = transaction_data.get("pdus") if not isinstance(transaction_data_pdus, list): # TODO we probably want an exception type specific to federation # client validation. raise TypeError("transaction_data.pdus is not a list.") room_version = await self.store.get_room_version(room_id) pdus = [event_from_pdu_json(p, room_version) for p in transaction_data_pdus] # Check signatures and hash of pdus, removing any from the list that fail checks pdus[:] = await self._check_sigs_and_hash_and_fetch( dest, pdus, room_version=room_version ) return pdus async def get_pdu_from_destination_raw( self, destination: str, event_id: str, room_version: RoomVersion, timeout: Optional[int] = None, ) -> Optional[EventBase]: """Requests the PDU with given origin and ID from the remote home server. Does not have any caching or rate limiting! Args: destination: Which homeserver to query event_id: event to fetch room_version: version of the room timeout: How long to try (in ms) each destination for before moving to the next destination. None indicates no timeout. Returns: The requested PDU, or None if we were unable to find it. Raises: SynapseError, NotRetryingDestination, FederationDeniedError """ transaction_data = await self.transport_layer.get_event( destination, event_id, timeout=timeout ) logger.debug( "retrieved event id %s from %s: %r", event_id, destination, transaction_data, ) pdu_list: List[EventBase] = [ event_from_pdu_json(p, room_version) for p in transaction_data["pdus"] ] if pdu_list and pdu_list[0]: pdu = pdu_list[0] # Check signatures are correct. signed_pdu = await self._check_sigs_and_hash(room_version, pdu) return signed_pdu return None async def get_pdu( self, destinations: Iterable[str], event_id: str, room_version: RoomVersion, timeout: Optional[int] = None, ) -> Optional[EventBase]: """Requests the PDU with given origin and ID from the remote home servers. Will attempt to get the PDU from each destination in the list until one succeeds. Args: destinations: Which homeservers to query event_id: event to fetch room_version: version of the room timeout: How long to try (in ms) each destination for before moving to the next destination. None indicates no timeout. Returns: The requested PDU, or None if we were unable to find it. """ # TODO: Rate limit the number of times we try and get the same event. ev = self._get_pdu_cache.get(event_id) if ev: return ev pdu_attempts = self.pdu_destination_tried.setdefault(event_id, {}) signed_pdu = None for destination in destinations: now = self._clock.time_msec() last_attempt = pdu_attempts.get(destination, 0) if last_attempt + PDU_RETRY_TIME_MS > now: continue try: signed_pdu = await self.get_pdu_from_destination_raw( destination=destination, event_id=event_id, room_version=room_version, timeout=timeout, ) pdu_attempts[destination] = now except SynapseError as e: logger.info( "Failed to get PDU %s from %s because %s", event_id, destination, e ) continue except NotRetryingDestination as e: logger.info(str(e)) continue except FederationDeniedError as e: logger.info(str(e)) continue except Exception as e: pdu_attempts[destination] = now logger.info( "Failed to get PDU %s from %s because %s", event_id, destination, e ) continue if signed_pdu: self._get_pdu_cache[event_id] = signed_pdu return signed_pdu async def get_room_state_ids( self, destination: str, room_id: str, event_id: str ) -> Tuple[List[str], List[str]]: """Calls the /state_ids endpoint to fetch the state at a particular point in the room, and the auth events for the given event Returns: a tuple of (state event_ids, auth event_ids) """ result = await self.transport_layer.get_room_state_ids( destination, room_id, event_id=event_id ) state_event_ids = result["pdu_ids"] auth_event_ids = result.get("auth_chain_ids", []) if not isinstance(state_event_ids, list) or not isinstance( auth_event_ids, list ): raise Exception("invalid response from /state_ids") return state_event_ids, auth_event_ids async def get_room_state( self, destination: str, room_id: str, event_id: str, room_version: RoomVersion, ) -> Tuple[List[EventBase], List[EventBase]]: """Calls the /state endpoint to fetch the state at a particular point in the room. Any invalid events (those with incorrect or unverifiable signatures or hashes) are filtered out from the response, and any duplicate events are removed. (Size limits and other event-format checks are *not* performed.) Note that the result is not ordered, so callers must be careful to process the events in an order that handles dependencies. Returns: a tuple of (state events, auth events) """ result = await self.transport_layer.get_room_state( room_version, destination, room_id, event_id, ) state_events = result.state auth_events = result.auth_events # we may as well filter out any duplicates from the response, to save # processing them multiple times. (In particular, events may be present in # `auth_events` as well as `state`, which is redundant). # # We don't rely on the sort order of the events, so we can just stick them # in a dict. state_event_map = {event.event_id: event for event in state_events} auth_event_map = { event.event_id: event for event in auth_events if event.event_id not in state_event_map } logger.info( "Processing from /state: %d state events, %d auth events", len(state_event_map), len(auth_event_map), ) valid_auth_events = await self._check_sigs_and_hash_and_fetch( destination, auth_event_map.values(), room_version ) valid_state_events = await self._check_sigs_and_hash_and_fetch( destination, state_event_map.values(), room_version ) return valid_state_events, valid_auth_events async def _check_sigs_and_hash_and_fetch( self, origin: str, pdus: Collection[EventBase], room_version: RoomVersion, ) -> List[EventBase]: """Checks the signatures and hashes of a list of events. If a PDU fails its signature check then we check if we have it in the database, and if not then request it from the sender's server (if that is different from `origin`). If that still fails, the event is omitted from the returned list. If a PDU fails its content hash check then it is redacted. Also runs each event through the spam checker; if it fails, redacts the event and flags it as soft-failed. The given list of PDUs are not modified; instead the function returns a new list. Args: origin: The server that sent us these events pdus: The events to be checked room_version: the version of the room these events are in Returns: A list of PDUs that have valid signatures and hashes. """ # We limit how many PDUs we check at once, as if we try to do hundreds # of thousands of PDUs at once we see large memory spikes. valid_pdus = [] async def _execute(pdu: EventBase) -> None: valid_pdu = await self._check_sigs_and_hash_and_fetch_one( pdu=pdu, origin=origin, room_version=room_version, ) if valid_pdu: valid_pdus.append(valid_pdu) await concurrently_execute(_execute, pdus, 10000) return valid_pdus async def _check_sigs_and_hash_and_fetch_one( self, pdu: EventBase, origin: str, room_version: RoomVersion, ) -> Optional[EventBase]: """Takes a PDU and checks its signatures and hashes. If the PDU fails its signature check then we check if we have it in the database; if not, we then request it from sender's server (if that is not the same as `origin`). If that still fails, we return None. If the PDU fails its content hash check, it is redacted. Also runs the event through the spam checker; if it fails, redacts the event and flags it as soft-failed. Args: origin pdu room_version Returns: The PDU (possibly redacted) if it has valid signatures and hashes. """ res = None try: res = await self._check_sigs_and_hash(room_version, pdu) except SynapseError: pass if not res: # Check local db. res = await self.store.get_event( pdu.event_id, allow_rejected=True, allow_none=True ) pdu_origin = get_domain_from_id(pdu.sender) if not res and pdu_origin != origin: try: res = await self.get_pdu( destinations=[pdu_origin], event_id=pdu.event_id, room_version=room_version, timeout=10000, ) except SynapseError: pass if not res: logger.warning( "Failed to find copy of %s with valid signature", pdu.event_id ) return res async def get_event_auth( self, destination: str, room_id: str, event_id: str ) -> List[EventBase]: res = await self.transport_layer.get_event_auth(destination, room_id, event_id) room_version = await self.store.get_room_version(room_id) auth_chain = [event_from_pdu_json(p, room_version) for p in res["auth_chain"]] signed_auth = await self._check_sigs_and_hash_and_fetch( destination, auth_chain, room_version=room_version ) return signed_auth def _is_unknown_endpoint( self, e: HttpResponseException, synapse_error: Optional[SynapseError] = None ) -> bool: """ Returns true if the response was due to an endpoint being unimplemented. Args: e: The error response received from the remote server. synapse_error: The above error converted to a SynapseError. This is automatically generated if not provided. """ if synapse_error is None: synapse_error = e.to_synapse_error() # There is no good way to detect an "unknown" endpoint. # # Dendrite returns a 404 (with a body of "404 page not found"); # Conduit returns a 404 (with no body); and Synapse returns a 400 # with M_UNRECOGNISED. # # This needs to be rather specific as some endpoints truly do return 404 # errors. return ( e.code == 404 and (not e.response or e.response == b"404 page not found") ) or (e.code == 400 and synapse_error.errcode == Codes.UNRECOGNIZED) async def _try_destination_list( self, description: str, destinations: Iterable[str], callback: Callable[[str], Awaitable[T]], failover_errcodes: Optional[Container[str]] = None, failover_on_unknown_endpoint: bool = False, ) -> T: """Try an operation on a series of servers, until it succeeds Args: description: description of the operation we're doing, for logging destinations: list of server_names to try callback: Function to run for each server. Passed a single argument: the server_name to try. If the callback raises a CodeMessageException with a 300/400 code or an UnsupportedRoomVersionError, attempts to perform the operation stop immediately and the exception is reraised. Otherwise, if the callback raises an Exception the error is logged and the next server tried. Normally the stacktrace is logged but this is suppressed if the exception is an InvalidResponseError. failover_errcodes: Error codes (specific to this endpoint) which should cause a failover when received as part of an HTTP 400 error. failover_on_unknown_endpoint: if True, we will try other servers if it looks like a server doesn't support the endpoint. This is typically useful if the endpoint in question is new or experimental. Returns: The result of callback, if it succeeds Raises: SynapseError if the chosen remote server returns a 300/400 code, or no servers were reachable. """ if failover_errcodes is None: failover_errcodes = () for destination in destinations: if destination == self.server_name: continue try: return await callback(destination) except ( RequestSendFailed, InvalidResponseError, NotRetryingDestination, ) as e: logger.warning("Failed to %s via %s: %s", description, destination, e) except UnsupportedRoomVersionError: raise except HttpResponseException as e: synapse_error = e.to_synapse_error() failover = False # Failover should occur: # # * On internal server errors. # * If the destination responds that it cannot complete the request. # * If the destination doesn't implemented the endpoint for some reason. if 500 <= e.code < 600: failover = True elif e.code == 400 and synapse_error.errcode in failover_errcodes: failover = True elif failover_on_unknown_endpoint and self._is_unknown_endpoint( e, synapse_error ): failover = True if not failover: raise synapse_error from e logger.warning( "Failed to %s via %s: %i %s", description, destination, e.code, e.args[0], ) except Exception: logger.warning( "Failed to %s via %s", description, destination, exc_info=True ) raise SynapseError(502, "Failed to %s via any server" % (description,)) async def make_membership_event( self, destinations: Iterable[str], room_id: str, user_id: str, membership: str, content: dict, params: Optional[Mapping[str, Union[str, Iterable[str]]]], ) -> Tuple[str, EventBase, RoomVersion]: """ Creates an m.room.member event, with context, without participating in the room. Does so by asking one of the already participating servers to create an event with proper context. Returns a fully signed and hashed event. Note that this does not append any events to any graphs. Args: destinations: Candidate homeservers which are probably participating in the room. room_id: The room in which the event will happen. user_id: The user whose membership is being evented. membership: The "membership" property of the event. Must be one of "join" or "leave". content: Any additional data to put into the content field of the event. params: Query parameters to include in the request. Returns: `(origin, event, room_version)` where origin is the remote homeserver which generated the event, and room_version is the version of the room. Raises: UnsupportedRoomVersionError: if remote responds with a room version we don't understand. SynapseError: if the chosen remote server returns a 300/400 code, or no servers successfully handle the request. """ valid_memberships = {Membership.JOIN, Membership.LEAVE, Membership.KNOCK} if membership not in valid_memberships: raise RuntimeError( "make_membership_event called with membership='%s', must be one of %s" % (membership, ",".join(valid_memberships)) ) async def send_request(destination: str) -> Tuple[str, EventBase, RoomVersion]: ret = await self.transport_layer.make_membership_event( destination, room_id, user_id, membership, params ) # Note: If not supplied, the room version may be either v1 or v2, # however either way the event format version will be v1. room_version_id = ret.get("room_version", RoomVersions.V1.identifier) room_version = KNOWN_ROOM_VERSIONS.get(room_version_id) if not room_version: raise UnsupportedRoomVersionError() if not room_version.msc2403_knocking and membership == Membership.KNOCK: raise SynapseError( 400, "This room version does not support knocking", errcode=Codes.FORBIDDEN, ) pdu_dict = ret.get("event", None) if not isinstance(pdu_dict, dict): raise InvalidResponseError("Bad 'event' field in response") logger.debug("Got response to make_%s: %s", membership, pdu_dict) pdu_dict["content"].update(content) # The protoevent received over the JSON wire may not have all # the required fields. Lets just gloss over that because # there's some we never care about if "prev_state" not in pdu_dict: pdu_dict["prev_state"] = [] ev = builder.create_local_event_from_event_dict( self._clock, self.hostname, self.signing_key, room_version=room_version, event_dict=pdu_dict, ) return destination, ev, room_version # MSC3083 defines additional error codes for room joins. Unfortunately # we do not yet know the room version, assume these will only be returned # by valid room versions. failover_errcodes = ( (Codes.UNABLE_AUTHORISE_JOIN, Codes.UNABLE_TO_GRANT_JOIN) if membership == Membership.JOIN else None ) return await self._try_destination_list( "make_" + membership, destinations, send_request, failover_errcodes=failover_errcodes, ) async def send_join( self, destinations: Iterable[str], pdu: EventBase, room_version: RoomVersion ) -> SendJoinResult: """Sends a join event to one of a list of homeservers. Doing so will cause the remote server to add the event to the graph, and send the event out to the rest of the federation. Args: destinations: Candidate homeservers which are probably participating in the room. pdu: event to be sent room_version: the version of the room (according to the server that did the make_join) Returns: The result of the send join request. Raises: SynapseError: if the chosen remote server returns a 300/400 code, or no servers successfully handle the request. """ async def send_request(destination: str) -> SendJoinResult: response = await self._do_send_join(room_version, destination, pdu) # If an event was returned (and expected to be returned): # # * Ensure it has the same event ID (note that the event ID is a hash # of the event fields for versions which support MSC3083). # * Ensure the signatures are good. # # Otherwise, fallback to the provided event. if room_version.msc3083_join_rules and response.event: event = response.event valid_pdu = await self._check_sigs_and_hash_and_fetch_one( pdu=event, origin=destination, room_version=room_version, ) if valid_pdu is None or event.event_id != pdu.event_id: raise InvalidResponseError("Returned an invalid join event") else: event = pdu state = response.state auth_chain = response.auth_events create_event = None for e in state: if (e.type, e.state_key) == (EventTypes.Create, ""): create_event = e break if create_event is None: # If the state doesn't have a create event then the room is # invalid, and it would fail auth checks anyway. raise InvalidResponseError("No create event in state") # the room version should be sane. create_room_version = create_event.content.get( "room_version", RoomVersions.V1.identifier ) if create_room_version != room_version.identifier: # either the server that fulfilled the make_join, or the server that is # handling the send_join, is lying. raise InvalidResponseError( "Unexpected room version %s in create event" % (create_room_version,) ) logger.info( "Processing from send_join %d events", len(state) + len(auth_chain) ) # We now go and check the signatures and hashes for the event. Note # that we limit how many events we process at a time to keep the # memory overhead from exploding. valid_pdus_map: Dict[str, EventBase] = {} async def _execute(pdu: EventBase) -> None: valid_pdu = await self._check_sigs_and_hash_and_fetch_one( pdu=pdu, origin=destination, room_version=room_version, ) if valid_pdu: valid_pdus_map[valid_pdu.event_id] = valid_pdu await concurrently_execute( _execute, itertools.chain(state, auth_chain), 10000 ) # NB: We *need* to copy to ensure that we don't have multiple # references being passed on, as that causes... issues. signed_state = [ copy.copy(valid_pdus_map[p.event_id]) for p in state if p.event_id in valid_pdus_map ] signed_auth = [ valid_pdus_map[p.event_id] for p in auth_chain if p.event_id in valid_pdus_map ] # NB: We *need* to copy to ensure that we don't have multiple # references being passed on, as that causes... issues. for s in signed_state: s.internal_metadata = copy.deepcopy(s.internal_metadata) # double-check that the auth chain doesn't include a different create event auth_chain_create_events = [ e.event_id for e in signed_auth if (e.type, e.state_key) == (EventTypes.Create, "") ] if auth_chain_create_events and auth_chain_create_events != [ create_event.event_id ]: raise InvalidResponseError( "Unexpected create event(s) in auth chain: %s" % (auth_chain_create_events,) ) if response.partial_state and not response.servers_in_room: raise InvalidResponseError( "partial_state was set, but no servers were listed in the room" ) return SendJoinResult( event=event, state=signed_state, auth_chain=signed_auth, origin=destination, partial_state=response.partial_state, servers_in_room=response.servers_in_room or [], ) # MSC3083 defines additional error codes for room joins. failover_errcodes = None if room_version.msc3083_join_rules: failover_errcodes = ( Codes.UNABLE_AUTHORISE_JOIN, Codes.UNABLE_TO_GRANT_JOIN, ) # If the join is being authorised via allow rules, we need to send # the /send_join back to the same server that was originally used # with /make_join. if EventContentFields.AUTHORISING_USER in pdu.content: destinations = [ get_domain_from_id(pdu.content[EventContentFields.AUTHORISING_USER]) ] return await self._try_destination_list( "send_join", destinations, send_request, failover_errcodes=failover_errcodes ) async def _do_send_join( self, room_version: RoomVersion, destination: str, pdu: EventBase ) -> SendJoinResponse: time_now = self._clock.time_msec() try: return await self.transport_layer.send_join_v2( room_version=room_version, destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) except HttpResponseException as e: # If an error is received that is due to an unrecognised endpoint, # fallback to the v1 endpoint. Otherwise, consider it a legitimate error # and raise. if not self._is_unknown_endpoint(e): raise logger.debug("Couldn't send_join with the v2 API, falling back to the v1 API") return await self.transport_layer.send_join_v1( room_version=room_version, destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) async def send_invite( self, destination: str, room_id: str, event_id: str, pdu: EventBase, ) -> EventBase: room_version = await self.store.get_room_version(room_id) content = await self._do_send_invite(destination, pdu, room_version) pdu_dict = content["event"] logger.debug("Got response to send_invite: %s", pdu_dict) pdu = event_from_pdu_json(pdu_dict, room_version) # Check signatures are correct. pdu = await self._check_sigs_and_hash(room_version, pdu) # FIXME: We should handle signature failures more gracefully. return pdu async def _do_send_invite( self, destination: str, pdu: EventBase, room_version: RoomVersion ) -> JsonDict: """Actually sends the invite, first trying v2 API and falling back to v1 API if necessary. Returns: The event as a dict as returned by the remote server Raises: SynapseError: if the remote server returns an error or if the server only supports the v1 endpoint and a room version other than "1" or "2" is requested. """ time_now = self._clock.time_msec() try: return await self.transport_layer.send_invite_v2( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content={ "event": pdu.get_pdu_json(time_now), "room_version": room_version.identifier, "invite_room_state": pdu.unsigned.get("invite_room_state", []), }, ) except HttpResponseException as e: # If an error is received that is due to an unrecognised endpoint, # fallback to the v1 endpoint if the room uses old-style event IDs. # Otherwise, consider it a legitimate error and raise. err = e.to_synapse_error() if self._is_unknown_endpoint(e, err): if room_version.event_format != EventFormatVersions.V1: raise SynapseError( 400, "User's homeserver does not support this room version", Codes.UNSUPPORTED_ROOM_VERSION, ) else: raise err # Didn't work, try v1 API. # Note the v1 API returns a tuple of `(200, content)` _, content = await self.transport_layer.send_invite_v1( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) return content async def send_leave(self, destinations: Iterable[str], pdu: EventBase) -> None: """Sends a leave event to one of a list of homeservers. Doing so will cause the remote server to add the event to the graph, and send the event out to the rest of the federation. This is mostly useful to reject received invites. Args: destinations: Candidate homeservers which are probably participating in the room. pdu: event to be sent Raises: SynapseError: if the chosen remote server returns a 300/400 code, or no servers successfully handle the request. """ async def send_request(destination: str) -> None: content = await self._do_send_leave(destination, pdu) logger.debug("Got content: %s", content) return await self._try_destination_list( "send_leave", destinations, send_request ) async def _do_send_leave(self, destination: str, pdu: EventBase) -> JsonDict: time_now = self._clock.time_msec() try: return await self.transport_layer.send_leave_v2( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) except HttpResponseException as e: # If an error is received that is due to an unrecognised endpoint, # fallback to the v1 endpoint. Otherwise, consider it a legitimate error # and raise. if not self._is_unknown_endpoint(e): raise logger.debug("Couldn't send_leave with the v2 API, falling back to the v1 API") resp = await self.transport_layer.send_leave_v1( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) # We expect the v1 API to respond with [200, content], so we only return the # content. return resp[1] async def send_knock(self, destinations: List[str], pdu: EventBase) -> JsonDict: """Attempts to send a knock event to given a list of servers. Iterates through the list until one attempt succeeds. Doing so will cause the remote server to add the event to the graph, and send the event out to the rest of the federation. Args: destinations: A list of candidate homeservers which are likely to be participating in the room. pdu: The event to be sent. Returns: The remote homeserver return some state from the room. The response dictionary is in the form: {"knock_state_events": [<state event dict>, ...]} The list of state events may be empty. Raises: SynapseError: If the chosen remote server returns a 3xx/4xx code. RuntimeError: If no servers were reachable. """ async def send_request(destination: str) -> JsonDict: return await self._do_send_knock(destination, pdu) return await self._try_destination_list( "send_knock", destinations, send_request ) async def _do_send_knock(self, destination: str, pdu: EventBase) -> JsonDict: """Send a knock event to a remote homeserver. Args: destination: The homeserver to send to. pdu: The event to send. Returns: The remote homeserver can optionally return some state from the room. The response dictionary is in the form: {"knock_state_events": [<state event dict>, ...]} The list of state events may be empty. """ time_now = self._clock.time_msec() return await self.transport_layer.send_knock_v1( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) async def get_public_rooms( self, remote_server: str, limit: Optional[int] = None, since_token: Optional[str] = None, search_filter: Optional[Dict] = None, include_all_networks: bool = False, third_party_instance_id: Optional[str] = None, ) -> JsonDict: """Get the list of public rooms from a remote homeserver Args: remote_server: The name of the remote server limit: Maximum amount of rooms to return since_token: Used for result pagination search_filter: A filter dictionary to send the remote homeserver and filter the result set include_all_networks: Whether to include results from all third party instances third_party_instance_id: Whether to only include results from a specific third party instance Returns: The response from the remote server. Raises: HttpResponseException / RequestSendFailed: There was an exception returned from the remote server SynapseException: M_FORBIDDEN when the remote server has disallowed publicRoom requests over federation """ return await self.transport_layer.get_public_rooms( remote_server, limit, since_token, search_filter, include_all_networks=include_all_networks, third_party_instance_id=third_party_instance_id, ) async def get_missing_events( self, destination: str, room_id: str, earliest_events_ids: Iterable[str], latest_events: Iterable[EventBase], limit: int, min_depth: int, timeout: int, ) -> List[EventBase]: """Tries to fetch events we are missing. This is called when we receive an event without having received all of its ancestors. Args: destination room_id earliest_events_ids: List of event ids. Effectively the events we expected to receive, but haven't. `get_missing_events` should only return events that didn't happen before these. latest_events: List of events we have received that we don't have all previous events for. limit: Maximum number of events to return. min_depth: Minimum depth of events to return. timeout: Max time to wait in ms """ try: content = await self.transport_layer.get_missing_events( destination=destination, room_id=room_id, earliest_events=earliest_events_ids, latest_events=[e.event_id for e in latest_events], limit=limit, min_depth=min_depth, timeout=timeout, ) room_version = await self.store.get_room_version(room_id) events = [ event_from_pdu_json(e, room_version) for e in content.get("events", []) ] signed_events = await self._check_sigs_and_hash_and_fetch( destination, events, room_version=room_version ) except HttpResponseException as e: if not e.code == 400: raise # We are probably hitting an old server that doesn't support # get_missing_events signed_events = [] return signed_events async def forward_third_party_invite( self, destinations: Iterable[str], room_id: str, event_dict: JsonDict ) -> None: for destination in destinations: if destination == self.server_name: continue try: await self.transport_layer.exchange_third_party_invite( destination=destination, room_id=room_id, event_dict=event_dict ) return except CodeMessageException: raise except Exception as e: logger.exception( "Failed to send_third_party_invite via %s: %s", destination, str(e) ) raise RuntimeError("Failed to send to any server.") async def get_room_complexity( self, destination: str, room_id: str ) -> Optional[JsonDict]: """ Fetch the complexity of a remote room from another server. Args: destination: The remote server room_id: The room ID to ask about. Returns: Dict contains the complexity metric versions, while None means we could not fetch the complexity. """ try: return await self.transport_layer.get_room_complexity( destination=destination, room_id=room_id ) except CodeMessageException as e: # We didn't manage to get it -- probably a 404. We are okay if other # servers don't give it to us. logger.debug( "Failed to fetch room complexity via %s for %s, got a %d", destination, room_id, e.code, ) except Exception: logger.exception( "Failed to fetch room complexity via %s for %s", destination, room_id ) # If we don't manage to find it, return None. It's not an error if a # server doesn't give it to us. return None async def get_room_hierarchy( self, destinations: Iterable[str], room_id: str, suggested_only: bool, ) -> Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]]: """ Call other servers to get a hierarchy of the given room. Performs simple data validates and parsing of the response. Args: destinations: The remote servers. We will try them in turn, omitting any that have been blacklisted. room_id: ID of the space to be queried suggested_only: If true, ask the remote server to only return children with the "suggested" flag set Returns: A tuple of: The room as a JSON dictionary, without a "children_state" key. A list of `m.space.child` state events. A list of children rooms, as JSON dictionaries. A list of inaccessible children room IDs. Raises: SynapseError if we were unable to get a valid summary from any of the remote servers """ cached_result = self._get_room_hierarchy_cache.get((room_id, suggested_only)) if cached_result: return cached_result async def send_request( destination: str, ) -> Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]]: try: res = await self.transport_layer.get_room_hierarchy( destination=destination, room_id=room_id, suggested_only=suggested_only, ) except HttpResponseException as e: # If an error is received that is due to an unrecognised endpoint, # fallback to the unstable endpoint. Otherwise, consider it a # legitimate error and raise. if not self._is_unknown_endpoint(e): raise logger.debug( "Couldn't fetch room hierarchy with the v1 API, falling back to the unstable API" ) res = await self.transport_layer.get_room_hierarchy_unstable( destination=destination, room_id=room_id, suggested_only=suggested_only, ) room = res.get("room") if not isinstance(room, dict): raise InvalidResponseError("'room' must be a dict") # Validate children_state of the room. children_state = room.pop("children_state", []) if not isinstance(children_state, list): raise InvalidResponseError("'room.children_state' must be a list") if any(not isinstance(e, dict) for e in children_state): raise InvalidResponseError("Invalid event in 'children_state' list") try: for child_state in children_state: _validate_hierarchy_event(child_state) except ValueError as e: raise InvalidResponseError(str(e)) # Validate the children rooms. children = res.get("children", []) if not isinstance(children, list): raise InvalidResponseError("'children' must be a list") if any(not isinstance(r, dict) for r in children): raise InvalidResponseError("Invalid room in 'children' list") # Validate the inaccessible children. inaccessible_children = res.get("inaccessible_children", []) if not isinstance(inaccessible_children, list): raise InvalidResponseError("'inaccessible_children' must be a list") if any(not isinstance(r, str) for r in inaccessible_children): raise InvalidResponseError( "Invalid room ID in 'inaccessible_children' list" ) return room, children_state, children, inaccessible_children result = await self._try_destination_list( "fetch room hierarchy", destinations, send_request, failover_on_unknown_endpoint=True, ) # Cache the result to avoid fetching data over federation every time. self._get_room_hierarchy_cache[(room_id, suggested_only)] = result return result async def timestamp_to_event( self, destination: str, room_id: str, timestamp: int, direction: str ) -> "TimestampToEventResponse": """ Calls a remote federating server at `destination` asking for their closest event to the given timestamp in the given direction. Also validates the response to always return the expected keys or raises an error. Args: destination: Domain name of the remote homeserver room_id: Room to fetch the event from timestamp: The point in time (inclusive) we should navigate from in the given direction to find the closest event. direction: ["f"|"b"] to indicate whether we should navigate forward or backward from the given timestamp to find the closest event. Returns: A parsed TimestampToEventResponse including the closest event_id and origin_server_ts Raises: Various exceptions when the request fails InvalidResponseError when the response does not have the correct keys or wrong types """ remote_response = await self.transport_layer.timestamp_to_event( destination, room_id, timestamp, direction ) if not isinstance(remote_response, dict): raise InvalidResponseError( "Response must be a JSON dictionary but received %r" % remote_response ) try: return TimestampToEventResponse.from_json_dict(remote_response) except ValueError as e: raise InvalidResponseError(str(e)) async def get_account_status( self, destination: str, user_ids: List[str] ) -> Tuple[JsonDict, List[str]]: """Retrieves account statuses for a given list of users on a given remote homeserver. If the request fails for any reason, all user IDs for this destination are marked as failed. Args: destination: the destination to contact user_ids: the user ID(s) for which to request account status(es) Returns: The account statuses, as well as the list of user IDs for which it was not possible to retrieve a status. """ try: res = await self.transport_layer.get_account_status(destination, user_ids) except Exception: # If the query failed for any reason, mark all the users as failed. return {}, user_ids statuses = res.get("account_statuses", {}) failures = res.get("failures", []) if not isinstance(statuses, dict) or not isinstance(failures, list): # Make sure we're not feeding back malformed data back to the caller. logger.warning( "Destination %s responded with malformed data to account_status query", destination, ) return {}, user_ids for user_id in user_ids: # Any account whose status is missing is a user we failed to receive the # status of. if user_id not in statuses and user_id not in failures: failures.append(user_id) # Filter out any user ID that doesn't belong to the remote server that sent its # status (or failure). def filter_user_id(user_id: str) -> bool: try: return UserID.from_string(user_id).domain == destination except SynapseError: # If the user ID doesn't parse, ignore it. return False filtered_statuses = dict( # item is a (key, value) tuple, so item[0] is the user ID. filter(lambda item: filter_user_id(item[0]), statuses.items()) ) filtered_failures = list(filter(filter_user_id, failures)) return filtered_statuses, filtered_failures @attr.s(frozen=True, slots=True, auto_attribs=True) class TimestampToEventResponse: """Typed response dictionary for the federation /timestamp_to_event endpoint""" event_id: str origin_server_ts: int # the raw data, including the above keys data: JsonDict @classmethod def from_json_dict(cls, d: JsonDict) -> "TimestampToEventResponse": """Parsed response from the federation /timestamp_to_event endpoint Args: d: JSON object response to be parsed Raises: ValueError if d does not the correct keys or they are the wrong types """ event_id = d.get("event_id") if not isinstance(event_id, str): raise ValueError( "Invalid response: 'event_id' must be a str but received %r" % event_id ) origin_server_ts = d.get("origin_server_ts") if not isinstance(origin_server_ts, int): raise ValueError( "Invalid response: 'origin_server_ts' must be a int but received %r" % origin_server_ts ) return cls(event_id, origin_server_ts, d) def _validate_hierarchy_event(d: JsonDict) -> None: """Validate an event within the result of a /hierarchy request Args: d: json object to be parsed Raises: ValueError if d is not a valid event """ event_type = d.get("type") if not isinstance(event_type, str): raise ValueError("Invalid event: 'event_type' must be a str") room_id = d.get("room_id") if not isinstance(room_id, str): raise ValueError("Invalid event: 'room_id' must be a str") state_key = d.get("state_key") if not isinstance(state_key, str): raise ValueError("Invalid event: 'state_key' must be a str") content = d.get("content") if not isinstance(content, dict): raise ValueError("Invalid event: 'content' must be a dict") via = content.get("via") if not isinstance(via, list): raise ValueError("Invalid event: 'via' must be a list") if any(not isinstance(v, str) for v in via): raise ValueError("Invalid event: 'via' must be a list of strings")
# Copyright 2015-2022 The Matrix.org Foundation C.I.C. # Copyright 2020 Sorunome # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import itertools import logging from typing import ( TYPE_CHECKING, Awaitable, Callable, Collection, Container, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, TypeVar, Union, ) import attr from prometheus_client import Counter from synapse.api.constants import EventContentFields, EventTypes, Membership from synapse.api.errors import ( CodeMessageException, Codes, FederationDeniedError, HttpResponseException, RequestSendFailed, SynapseError, UnsupportedRoomVersionError, ) from synapse.api.room_versions import ( KNOWN_ROOM_VERSIONS, EventFormatVersions, RoomVersion, RoomVersions, ) from synapse.events import EventBase, builder from synapse.federation.federation_base import FederationBase, event_from_pdu_json from synapse.federation.transport.client import SendJoinResponse from synapse.http.types import QueryParams from synapse.types import JsonDict, UserID, get_domain_from_id from synapse.util.async_helpers import concurrently_execute from synapse.util.caches.expiringcache import ExpiringCache from synapse.util.retryutils import NotRetryingDestination if TYPE_CHECKING: from synapse.server import HomeServer logger = logging.getLogger(__name__) sent_queries_counter = Counter("synapse_federation_client_sent_queries", "", ["type"]) PDU_RETRY_TIME_MS = 1 * 60 * 1000 T = TypeVar("T") class InvalidResponseError(RuntimeError): """Helper for _try_destination_list: indicates that the server returned a response we couldn't parse """ @attr.s(slots=True, frozen=True, auto_attribs=True) class SendJoinResult: # The event to persist. event: EventBase # A string giving the server the event was sent to. origin: str state: List[EventBase] auth_chain: List[EventBase] # True if 'state' elides non-critical membership events partial_state: bool # if 'partial_state' is set, a list of the servers in the room (otherwise empty) servers_in_room: List[str] class FederationClient(FederationBase): def __init__(self, hs: "HomeServer"): super().__init__(hs) self.pdu_destination_tried: Dict[str, Dict[str, int]] = {} self._clock.looping_call(self._clear_tried_cache, 60 * 1000) self.state = hs.get_state_handler() self.transport_layer = hs.get_federation_transport_client() self.hostname = hs.hostname self.signing_key = hs.signing_key self._get_pdu_cache: ExpiringCache[str, EventBase] = ExpiringCache( cache_name="get_pdu_cache", clock=self._clock, max_len=1000, expiry_ms=120 * 1000, reset_expiry_on_get=False, ) # A cache for fetching the room hierarchy over federation. # # Some stale data over federation is OK, but must be refreshed # periodically since the local server is in the room. # # It is a map of (room ID, suggested-only) -> the response of # get_room_hierarchy. self._get_room_hierarchy_cache: ExpiringCache[ Tuple[str, bool], Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]], ] = ExpiringCache( cache_name="get_room_hierarchy_cache", clock=self._clock, max_len=1000, expiry_ms=5 * 60 * 1000, reset_expiry_on_get=False, ) def _clear_tried_cache(self) -> None: """Clear pdu_destination_tried cache""" now = self._clock.time_msec() old_dict = self.pdu_destination_tried self.pdu_destination_tried = {} for event_id, destination_dict in old_dict.items(): destination_dict = { dest: time for dest, time in destination_dict.items() if time + PDU_RETRY_TIME_MS > now } if destination_dict: self.pdu_destination_tried[event_id] = destination_dict async def make_query( self, destination: str, query_type: str, args: QueryParams, retry_on_dns_fail: bool = False, ignore_backoff: bool = False, ) -> JsonDict: """Sends a federation Query to a remote homeserver of the given type and arguments. Args: destination: Domain name of the remote homeserver query_type: Category of the query type; should match the handler name used in register_query_handler(). args: Mapping of strings to strings containing the details of the query request. ignore_backoff: true to ignore the historical backoff data and try the request anyway. Returns: The JSON object from the response """ sent_queries_counter.labels(query_type).inc() return await self.transport_layer.make_query( destination, query_type, args, retry_on_dns_fail=retry_on_dns_fail, ignore_backoff=ignore_backoff, ) async def query_client_keys( self, destination: str, content: JsonDict, timeout: int ) -> JsonDict: """Query device keys for a device hosted on a remote server. Args: destination: Domain name of the remote homeserver content: The query content. Returns: The JSON object from the response """ sent_queries_counter.labels("client_device_keys").inc() return await self.transport_layer.query_client_keys( destination, content, timeout ) async def query_user_devices( self, destination: str, user_id: str, timeout: int = 30000 ) -> JsonDict: """Query the device keys for a list of user ids hosted on a remote server. """ sent_queries_counter.labels("user_devices").inc() return await self.transport_layer.query_user_devices( destination, user_id, timeout ) async def claim_client_keys( self, destination: str, content: JsonDict, timeout: int ) -> JsonDict: """Claims one-time keys for a device hosted on a remote server. Args: destination: Domain name of the remote homeserver content: The query content. Returns: The JSON object from the response """ sent_queries_counter.labels("client_one_time_keys").inc() return await self.transport_layer.claim_client_keys( destination, content, timeout ) async def backfill( self, dest: str, room_id: str, limit: int, extremities: Collection[str] ) -> Optional[List[EventBase]]: """Requests some more historic PDUs for the given room from the given destination server. Args: dest: The remote homeserver to ask. room_id: The room_id to backfill. limit: The maximum number of events to return. extremities: our current backwards extremities, to backfill from Must be a Collection that is falsy when empty. (Iterable is not enough here!) """ logger.debug("backfill extrem=%s", extremities) # If there are no extremities then we've (probably) reached the start. if not extremities: return None transaction_data = await self.transport_layer.backfill( dest, room_id, extremities, limit ) logger.debug("backfill transaction_data=%r", transaction_data) if not isinstance(transaction_data, dict): # TODO we probably want an exception type specific to federation # client validation. raise TypeError("Backfill transaction_data is not a dict.") transaction_data_pdus = transaction_data.get("pdus") if not isinstance(transaction_data_pdus, list): # TODO we probably want an exception type specific to federation # client validation. raise TypeError("transaction_data.pdus is not a list.") room_version = await self.store.get_room_version(room_id) pdus = [event_from_pdu_json(p, room_version) for p in transaction_data_pdus] # Check signatures and hash of pdus, removing any from the list that fail checks pdus[:] = await self._check_sigs_and_hash_and_fetch( dest, pdus, room_version=room_version ) return pdus async def get_pdu_from_destination_raw( self, destination: str, event_id: str, room_version: RoomVersion, timeout: Optional[int] = None, ) -> Optional[EventBase]: """Requests the PDU with given origin and ID from the remote home server. Does not have any caching or rate limiting! Args: destination: Which homeserver to query event_id: event to fetch room_version: version of the room timeout: How long to try (in ms) each destination for before moving to the next destination. None indicates no timeout. Returns: The requested PDU, or None if we were unable to find it. Raises: SynapseError, NotRetryingDestination, FederationDeniedError """ transaction_data = await self.transport_layer.get_event( destination, event_id, timeout=timeout ) logger.debug( "retrieved event id %s from %s: %r", event_id, destination, transaction_data, ) pdu_list: List[EventBase] = [ event_from_pdu_json(p, room_version) for p in transaction_data["pdus"] ] if pdu_list and pdu_list[0]: pdu = pdu_list[0] # Check signatures are correct. signed_pdu = await self._check_sigs_and_hash(room_version, pdu) return signed_pdu return None async def get_pdu( self, destinations: Iterable[str], event_id: str, room_version: RoomVersion, timeout: Optional[int] = None, ) -> Optional[EventBase]: """Requests the PDU with given origin and ID from the remote home servers. Will attempt to get the PDU from each destination in the list until one succeeds. Args: destinations: Which homeservers to query event_id: event to fetch room_version: version of the room timeout: How long to try (in ms) each destination for before moving to the next destination. None indicates no timeout. Returns: The requested PDU, or None if we were unable to find it. """ # TODO: Rate limit the number of times we try and get the same event. ev = self._get_pdu_cache.get(event_id) if ev: return ev pdu_attempts = self.pdu_destination_tried.setdefault(event_id, {}) signed_pdu = None for destination in destinations: now = self._clock.time_msec() last_attempt = pdu_attempts.get(destination, 0) if last_attempt + PDU_RETRY_TIME_MS > now: continue try: signed_pdu = await self.get_pdu_from_destination_raw( destination=destination, event_id=event_id, room_version=room_version, timeout=timeout, ) pdu_attempts[destination] = now except SynapseError as e: logger.info( "Failed to get PDU %s from %s because %s", event_id, destination, e ) continue except NotRetryingDestination as e: logger.info(str(e)) continue except FederationDeniedError as e: logger.info(str(e)) continue except Exception as e: pdu_attempts[destination] = now logger.info( "Failed to get PDU %s from %s because %s", event_id, destination, e ) continue if signed_pdu: self._get_pdu_cache[event_id] = signed_pdu return signed_pdu async def get_room_state_ids( self, destination: str, room_id: str, event_id: str ) -> Tuple[List[str], List[str]]: """Calls the /state_ids endpoint to fetch the state at a particular point in the room, and the auth events for the given event Returns: a tuple of (state event_ids, auth event_ids) """ result = await self.transport_layer.get_room_state_ids( destination, room_id, event_id=event_id ) state_event_ids = result["pdu_ids"] auth_event_ids = result.get("auth_chain_ids", []) if not isinstance(state_event_ids, list) or not isinstance( auth_event_ids, list ): raise Exception("invalid response from /state_ids") return state_event_ids, auth_event_ids async def get_room_state( self, destination: str, room_id: str, event_id: str, room_version: RoomVersion, ) -> Tuple[List[EventBase], List[EventBase]]: """Calls the /state endpoint to fetch the state at a particular point in the room. Any invalid events (those with incorrect or unverifiable signatures or hashes) are filtered out from the response, and any duplicate events are removed. (Size limits and other event-format checks are *not* performed.) Note that the result is not ordered, so callers must be careful to process the events in an order that handles dependencies. Returns: a tuple of (state events, auth events) """ result = await self.transport_layer.get_room_state( room_version, destination, room_id, event_id, ) state_events = result.state auth_events = result.auth_events # we may as well filter out any duplicates from the response, to save # processing them multiple times. (In particular, events may be present in # `auth_events` as well as `state`, which is redundant). # # We don't rely on the sort order of the events, so we can just stick them # in a dict. state_event_map = {event.event_id: event for event in state_events} auth_event_map = { event.event_id: event for event in auth_events if event.event_id not in state_event_map } logger.info( "Processing from /state: %d state events, %d auth events", len(state_event_map), len(auth_event_map), ) valid_auth_events = await self._check_sigs_and_hash_and_fetch( destination, auth_event_map.values(), room_version ) valid_state_events = await self._check_sigs_and_hash_and_fetch( destination, state_event_map.values(), room_version ) return valid_state_events, valid_auth_events async def _check_sigs_and_hash_and_fetch( self, origin: str, pdus: Collection[EventBase], room_version: RoomVersion, ) -> List[EventBase]: """Checks the signatures and hashes of a list of events. If a PDU fails its signature check then we check if we have it in the database, and if not then request it from the sender's server (if that is different from `origin`). If that still fails, the event is omitted from the returned list. If a PDU fails its content hash check then it is redacted. Also runs each event through the spam checker; if it fails, redacts the event and flags it as soft-failed. The given list of PDUs are not modified; instead the function returns a new list. Args: origin: The server that sent us these events pdus: The events to be checked room_version: the version of the room these events are in Returns: A list of PDUs that have valid signatures and hashes. """ # We limit how many PDUs we check at once, as if we try to do hundreds # of thousands of PDUs at once we see large memory spikes. valid_pdus = [] async def _execute(pdu: EventBase) -> None: valid_pdu = await self._check_sigs_and_hash_and_fetch_one( pdu=pdu, origin=origin, room_version=room_version, ) if valid_pdu: valid_pdus.append(valid_pdu) await concurrently_execute(_execute, pdus, 10000) return valid_pdus async def _check_sigs_and_hash_and_fetch_one( self, pdu: EventBase, origin: str, room_version: RoomVersion, ) -> Optional[EventBase]: """Takes a PDU and checks its signatures and hashes. If the PDU fails its signature check then we check if we have it in the database; if not, we then request it from sender's server (if that is not the same as `origin`). If that still fails, we return None. If the PDU fails its content hash check, it is redacted. Also runs the event through the spam checker; if it fails, redacts the event and flags it as soft-failed. Args: origin pdu room_version Returns: The PDU (possibly redacted) if it has valid signatures and hashes. """ res = None try: res = await self._check_sigs_and_hash(room_version, pdu) except SynapseError: pass if not res: # Check local db. res = await self.store.get_event( pdu.event_id, allow_rejected=True, allow_none=True ) pdu_origin = get_domain_from_id(pdu.sender) if not res and pdu_origin != origin: try: res = await self.get_pdu( destinations=[pdu_origin], event_id=pdu.event_id, room_version=room_version, timeout=10000, ) except SynapseError: pass if not res: logger.warning( "Failed to find copy of %s with valid signature", pdu.event_id ) return res async def get_event_auth( self, destination: str, room_id: str, event_id: str ) -> List[EventBase]: res = await self.transport_layer.get_event_auth(destination, room_id, event_id) room_version = await self.store.get_room_version(room_id) auth_chain = [event_from_pdu_json(p, room_version) for p in res["auth_chain"]] signed_auth = await self._check_sigs_and_hash_and_fetch( destination, auth_chain, room_version=room_version ) return signed_auth def _is_unknown_endpoint( self, e: HttpResponseException, synapse_error: Optional[SynapseError] = None ) -> bool: """ Returns true if the response was due to an endpoint being unimplemented. Args: e: The error response received from the remote server. synapse_error: The above error converted to a SynapseError. This is automatically generated if not provided. """ if synapse_error is None: synapse_error = e.to_synapse_error() # There is no good way to detect an "unknown" endpoint. # # Dendrite returns a 404 (with a body of "404 page not found"); # Conduit returns a 404 (with no body); and Synapse returns a 400 # with M_UNRECOGNISED. # # This needs to be rather specific as some endpoints truly do return 404 # errors. return ( e.code == 404 and (not e.response or e.response == b"404 page not found") ) or (e.code == 400 and synapse_error.errcode == Codes.UNRECOGNIZED) async def _try_destination_list( self, description: str, destinations: Iterable[str], callback: Callable[[str], Awaitable[T]], failover_errcodes: Optional[Container[str]] = None, failover_on_unknown_endpoint: bool = False, ) -> T: """Try an operation on a series of servers, until it succeeds Args: description: description of the operation we're doing, for logging destinations: list of server_names to try callback: Function to run for each server. Passed a single argument: the server_name to try. If the callback raises a CodeMessageException with a 300/400 code or an UnsupportedRoomVersionError, attempts to perform the operation stop immediately and the exception is reraised. Otherwise, if the callback raises an Exception the error is logged and the next server tried. Normally the stacktrace is logged but this is suppressed if the exception is an InvalidResponseError. failover_errcodes: Error codes (specific to this endpoint) which should cause a failover when received as part of an HTTP 400 error. failover_on_unknown_endpoint: if True, we will try other servers if it looks like a server doesn't support the endpoint. This is typically useful if the endpoint in question is new or experimental. Returns: The result of callback, if it succeeds Raises: SynapseError if the chosen remote server returns a 300/400 code, or no servers were reachable. """ if failover_errcodes is None: failover_errcodes = () for destination in destinations: if destination == self.server_name: continue try: return await callback(destination) except ( RequestSendFailed, InvalidResponseError, NotRetryingDestination, ) as e: logger.warning("Failed to %s via %s: %s", description, destination, e) except UnsupportedRoomVersionError: raise except HttpResponseException as e: synapse_error = e.to_synapse_error() failover = False # Failover should occur: # # * On internal server errors. # * If the destination responds that it cannot complete the request. # * If the destination doesn't implemented the endpoint for some reason. if 500 <= e.code < 600: failover = True elif e.code == 400 and synapse_error.errcode in failover_errcodes: failover = True elif failover_on_unknown_endpoint and self._is_unknown_endpoint( e, synapse_error ): failover = True if not failover: raise synapse_error from e logger.warning( "Failed to %s via %s: %i %s", description, destination, e.code, e.args[0], ) except Exception: logger.warning( "Failed to %s via %s", description, destination, exc_info=True ) raise SynapseError(502, "Failed to %s via any server" % (description,)) async def make_membership_event( self, destinations: Iterable[str], room_id: str, user_id: str, membership: str, content: dict, params: Optional[Mapping[str, Union[str, Iterable[str]]]], ) -> Tuple[str, EventBase, RoomVersion]: """ Creates an m.room.member event, with context, without participating in the room. Does so by asking one of the already participating servers to create an event with proper context. Returns a fully signed and hashed event. Note that this does not append any events to any graphs. Args: destinations: Candidate homeservers which are probably participating in the room. room_id: The room in which the event will happen. user_id: The user whose membership is being evented. membership: The "membership" property of the event. Must be one of "join" or "leave". content: Any additional data to put into the content field of the event. params: Query parameters to include in the request. Returns: `(origin, event, room_version)` where origin is the remote homeserver which generated the event, and room_version is the version of the room. Raises: UnsupportedRoomVersionError: if remote responds with a room version we don't understand. SynapseError: if the chosen remote server returns a 300/400 code, or no servers successfully handle the request. """ valid_memberships = {Membership.JOIN, Membership.LEAVE, Membership.KNOCK} if membership not in valid_memberships: raise RuntimeError( "make_membership_event called with membership='%s', must be one of %s" % (membership, ",".join(valid_memberships)) ) async def send_request(destination: str) -> Tuple[str, EventBase, RoomVersion]: ret = await self.transport_layer.make_membership_event( destination, room_id, user_id, membership, params ) # Note: If not supplied, the room version may be either v1 or v2, # however either way the event format version will be v1. room_version_id = ret.get("room_version", RoomVersions.V1.identifier) room_version = KNOWN_ROOM_VERSIONS.get(room_version_id) if not room_version: raise UnsupportedRoomVersionError() if not room_version.msc2403_knocking and membership == Membership.KNOCK: raise SynapseError( 400, "This room version does not support knocking", errcode=Codes.FORBIDDEN, ) pdu_dict = ret.get("event", None) if not isinstance(pdu_dict, dict): raise InvalidResponseError("Bad 'event' field in response") logger.debug("Got response to make_%s: %s", membership, pdu_dict) pdu_dict["content"].update(content) # The protoevent received over the JSON wire may not have all # the required fields. Lets just gloss over that because # there's some we never care about if "prev_state" not in pdu_dict: pdu_dict["prev_state"] = [] ev = builder.create_local_event_from_event_dict( self._clock, self.hostname, self.signing_key, room_version=room_version, event_dict=pdu_dict, ) return destination, ev, room_version # MSC3083 defines additional error codes for room joins. Unfortunately # we do not yet know the room version, assume these will only be returned # by valid room versions. failover_errcodes = ( (Codes.UNABLE_AUTHORISE_JOIN, Codes.UNABLE_TO_GRANT_JOIN) if membership == Membership.JOIN else None ) return await self._try_destination_list( "make_" + membership, destinations, send_request, failover_errcodes=failover_errcodes, ) async def send_join( self, destinations: Iterable[str], pdu: EventBase, room_version: RoomVersion ) -> SendJoinResult: """Sends a join event to one of a list of homeservers. Doing so will cause the remote server to add the event to the graph, and send the event out to the rest of the federation. Args: destinations: Candidate homeservers which are probably participating in the room. pdu: event to be sent room_version: the version of the room (according to the server that did the make_join) Returns: The result of the send join request. Raises: SynapseError: if the chosen remote server returns a 300/400 code, or no servers successfully handle the request. """ async def send_request(destination: str) -> SendJoinResult: response = await self._do_send_join(room_version, destination, pdu) # If an event was returned (and expected to be returned): # # * Ensure it has the same event ID (note that the event ID is a hash # of the event fields for versions which support MSC3083). # * Ensure the signatures are good. # # Otherwise, fallback to the provided event. if room_version.msc3083_join_rules and response.event: event = response.event valid_pdu = await self._check_sigs_and_hash_and_fetch_one( pdu=event, origin=destination, room_version=room_version, ) if valid_pdu is None or event.event_id != pdu.event_id: raise InvalidResponseError("Returned an invalid join event") else: event = pdu state = response.state auth_chain = response.auth_events create_event = None for e in state: if (e.type, e.state_key) == (EventTypes.Create, ""): create_event = e break if create_event is None: # If the state doesn't have a create event then the room is # invalid, and it would fail auth checks anyway. raise InvalidResponseError("No create event in state") # the room version should be sane. create_room_version = create_event.content.get( "room_version", RoomVersions.V1.identifier ) if create_room_version != room_version.identifier: # either the server that fulfilled the make_join, or the server that is # handling the send_join, is lying. raise InvalidResponseError( "Unexpected room version %s in create event" % (create_room_version,) ) logger.info( "Processing from send_join %d events", len(state) + len(auth_chain) ) # We now go and check the signatures and hashes for the event. Note # that we limit how many events we process at a time to keep the # memory overhead from exploding. valid_pdus_map: Dict[str, EventBase] = {} async def _execute(pdu: EventBase) -> None: valid_pdu = await self._check_sigs_and_hash_and_fetch_one( pdu=pdu, origin=destination, room_version=room_version, ) if valid_pdu: valid_pdus_map[valid_pdu.event_id] = valid_pdu await concurrently_execute( _execute, itertools.chain(state, auth_chain), 10000 ) # NB: We *need* to copy to ensure that we don't have multiple # references being passed on, as that causes... issues. signed_state = [ copy.copy(valid_pdus_map[p.event_id]) for p in state if p.event_id in valid_pdus_map ] signed_auth = [ valid_pdus_map[p.event_id] for p in auth_chain if p.event_id in valid_pdus_map ] # NB: We *need* to copy to ensure that we don't have multiple # references being passed on, as that causes... issues. for s in signed_state: s.internal_metadata = copy.deepcopy(s.internal_metadata) # double-check that the auth chain doesn't include a different create event auth_chain_create_events = [ e.event_id for e in signed_auth if (e.type, e.state_key) == (EventTypes.Create, "") ] if auth_chain_create_events and auth_chain_create_events != [ create_event.event_id ]: raise InvalidResponseError( "Unexpected create event(s) in auth chain: %s" % (auth_chain_create_events,) ) if response.partial_state and not response.servers_in_room: raise InvalidResponseError( "partial_state was set, but no servers were listed in the room" ) return SendJoinResult( event=event, state=signed_state, auth_chain=signed_auth, origin=destination, partial_state=response.partial_state, servers_in_room=response.servers_in_room or [], ) # MSC3083 defines additional error codes for room joins. failover_errcodes = None if room_version.msc3083_join_rules: failover_errcodes = ( Codes.UNABLE_AUTHORISE_JOIN, Codes.UNABLE_TO_GRANT_JOIN, ) # If the join is being authorised via allow rules, we need to send # the /send_join back to the same server that was originally used # with /make_join. if EventContentFields.AUTHORISING_USER in pdu.content: destinations = [ get_domain_from_id(pdu.content[EventContentFields.AUTHORISING_USER]) ] return await self._try_destination_list( "send_join", destinations, send_request, failover_errcodes=failover_errcodes ) async def _do_send_join( self, room_version: RoomVersion, destination: str, pdu: EventBase ) -> SendJoinResponse: time_now = self._clock.time_msec() try: return await self.transport_layer.send_join_v2( room_version=room_version, destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) except HttpResponseException as e: # If an error is received that is due to an unrecognised endpoint, # fallback to the v1 endpoint. Otherwise, consider it a legitimate error # and raise. if not self._is_unknown_endpoint(e): raise logger.debug("Couldn't send_join with the v2 API, falling back to the v1 API") return await self.transport_layer.send_join_v1( room_version=room_version, destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) async def send_invite( self, destination: str, room_id: str, event_id: str, pdu: EventBase, ) -> EventBase: room_version = await self.store.get_room_version(room_id) content = await self._do_send_invite(destination, pdu, room_version) pdu_dict = content["event"] logger.debug("Got response to send_invite: %s", pdu_dict) pdu = event_from_pdu_json(pdu_dict, room_version) # Check signatures are correct. pdu = await self._check_sigs_and_hash(room_version, pdu) # FIXME: We should handle signature failures more gracefully. return pdu async def _do_send_invite( self, destination: str, pdu: EventBase, room_version: RoomVersion ) -> JsonDict: """Actually sends the invite, first trying v2 API and falling back to v1 API if necessary. Returns: The event as a dict as returned by the remote server Raises: SynapseError: if the remote server returns an error or if the server only supports the v1 endpoint and a room version other than "1" or "2" is requested. """ time_now = self._clock.time_msec() try: return await self.transport_layer.send_invite_v2( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content={ "event": pdu.get_pdu_json(time_now), "room_version": room_version.identifier, "invite_room_state": pdu.unsigned.get("invite_room_state", []), }, ) except HttpResponseException as e: # If an error is received that is due to an unrecognised endpoint, # fallback to the v1 endpoint if the room uses old-style event IDs. # Otherwise, consider it a legitimate error and raise. err = e.to_synapse_error() if self._is_unknown_endpoint(e, err): if room_version.event_format != EventFormatVersions.V1: raise SynapseError( 400, "User's homeserver does not support this room version", Codes.UNSUPPORTED_ROOM_VERSION, ) else: raise err # Didn't work, try v1 API. # Note the v1 API returns a tuple of `(200, content)` _, content = await self.transport_layer.send_invite_v1( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) return content async def send_leave(self, destinations: Iterable[str], pdu: EventBase) -> None: """Sends a leave event to one of a list of homeservers. Doing so will cause the remote server to add the event to the graph, and send the event out to the rest of the federation. This is mostly useful to reject received invites. Args: destinations: Candidate homeservers which are probably participating in the room. pdu: event to be sent Raises: SynapseError: if the chosen remote server returns a 300/400 code, or no servers successfully handle the request. """ async def send_request(destination: str) -> None: content = await self._do_send_leave(destination, pdu) logger.debug("Got content: %s", content) return await self._try_destination_list( "send_leave", destinations, send_request ) async def _do_send_leave(self, destination: str, pdu: EventBase) -> JsonDict: time_now = self._clock.time_msec() try: return await self.transport_layer.send_leave_v2( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) except HttpResponseException as e: # If an error is received that is due to an unrecognised endpoint, # fallback to the v1 endpoint. Otherwise, consider it a legitimate error # and raise. if not self._is_unknown_endpoint(e): raise logger.debug("Couldn't send_leave with the v2 API, falling back to the v1 API") resp = await self.transport_layer.send_leave_v1( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) # We expect the v1 API to respond with [200, content], so we only return the # content. return resp[1] async def send_knock(self, destinations: List[str], pdu: EventBase) -> JsonDict: """Attempts to send a knock event to given a list of servers. Iterates through the list until one attempt succeeds. Doing so will cause the remote server to add the event to the graph, and send the event out to the rest of the federation. Args: destinations: A list of candidate homeservers which are likely to be participating in the room. pdu: The event to be sent. Returns: The remote homeserver return some state from the room. The response dictionary is in the form: {"knock_state_events": [<state event dict>, ...]} The list of state events may be empty. Raises: SynapseError: If the chosen remote server returns a 3xx/4xx code. RuntimeError: If no servers were reachable. """ async def send_request(destination: str) -> JsonDict: return await self._do_send_knock(destination, pdu) return await self._try_destination_list( "send_knock", destinations, send_request ) async def _do_send_knock(self, destination: str, pdu: EventBase) -> JsonDict: """Send a knock event to a remote homeserver. Args: destination: The homeserver to send to. pdu: The event to send. Returns: The remote homeserver can optionally return some state from the room. The response dictionary is in the form: {"knock_state_events": [<state event dict>, ...]} The list of state events may be empty. """ time_now = self._clock.time_msec() return await self.transport_layer.send_knock_v1( destination=destination, room_id=pdu.room_id, event_id=pdu.event_id, content=pdu.get_pdu_json(time_now), ) async def get_public_rooms( self, remote_server: str, limit: Optional[int] = None, since_token: Optional[str] = None, search_filter: Optional[Dict] = None, include_all_networks: bool = False, third_party_instance_id: Optional[str] = None, ) -> JsonDict: """Get the list of public rooms from a remote homeserver Args: remote_server: The name of the remote server limit: Maximum amount of rooms to return since_token: Used for result pagination search_filter: A filter dictionary to send the remote homeserver and filter the result set include_all_networks: Whether to include results from all third party instances third_party_instance_id: Whether to only include results from a specific third party instance Returns: The response from the remote server. Raises: HttpResponseException / RequestSendFailed: There was an exception returned from the remote server SynapseException: M_FORBIDDEN when the remote server has disallowed publicRoom requests over federation """ return await self.transport_layer.get_public_rooms( remote_server, limit, since_token, search_filter, include_all_networks=include_all_networks, third_party_instance_id=third_party_instance_id, ) async def get_missing_events( self, destination: str, room_id: str, earliest_events_ids: Iterable[str], latest_events: Iterable[EventBase], limit: int, min_depth: int, timeout: int, ) -> List[EventBase]: """Tries to fetch events we are missing. This is called when we receive an event without having received all of its ancestors. Args: destination room_id earliest_events_ids: List of event ids. Effectively the events we expected to receive, but haven't. `get_missing_events` should only return events that didn't happen before these. latest_events: List of events we have received that we don't have all previous events for. limit: Maximum number of events to return. min_depth: Minimum depth of events to return. timeout: Max time to wait in ms """ try: content = await self.transport_layer.get_missing_events( destination=destination, room_id=room_id, earliest_events=earliest_events_ids, latest_events=[e.event_id for e in latest_events], limit=limit, min_depth=min_depth, timeout=timeout, ) room_version = await self.store.get_room_version(room_id) events = [ event_from_pdu_json(e, room_version) for e in content.get("events", []) ] signed_events = await self._check_sigs_and_hash_and_fetch( destination, events, room_version=room_version ) except HttpResponseException as e: if not e.code == 400: raise # We are probably hitting an old server that doesn't support # get_missing_events signed_events = [] return signed_events async def forward_third_party_invite( self, destinations: Iterable[str], room_id: str, event_dict: JsonDict ) -> None: for destination in destinations: if destination == self.server_name: continue try: await self.transport_layer.exchange_third_party_invite( destination=destination, room_id=room_id, event_dict=event_dict ) return except CodeMessageException: raise except Exception as e: logger.exception( "Failed to send_third_party_invite via %s: %s", destination, str(e) ) raise RuntimeError("Failed to send to any server.") async def get_room_complexity( self, destination: str, room_id: str ) -> Optional[JsonDict]: """ Fetch the complexity of a remote room from another server. Args: destination: The remote server room_id: The room ID to ask about. Returns: Dict contains the complexity metric versions, while None means we could not fetch the complexity. """ try: return await self.transport_layer.get_room_complexity( destination=destination, room_id=room_id ) except CodeMessageException as e: # We didn't manage to get it -- probably a 404. We are okay if other # servers don't give it to us. logger.debug( "Failed to fetch room complexity via %s for %s, got a %d", destination, room_id, e.code, ) except Exception: logger.exception( "Failed to fetch room complexity via %s for %s", destination, room_id ) # If we don't manage to find it, return None. It's not an error if a # server doesn't give it to us. return None async def get_room_hierarchy( self, destinations: Iterable[str], room_id: str, suggested_only: bool, ) -> Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]]: """ Call other servers to get a hierarchy of the given room. Performs simple data validates and parsing of the response. Args: destinations: The remote servers. We will try them in turn, omitting any that have been blacklisted. room_id: ID of the space to be queried suggested_only: If true, ask the remote server to only return children with the "suggested" flag set Returns: A tuple of: The room as a JSON dictionary, without a "children_state" key. A list of `m.space.child` state events. A list of children rooms, as JSON dictionaries. A list of inaccessible children room IDs. Raises: SynapseError if we were unable to get a valid summary from any of the remote servers """ cached_result = self._get_room_hierarchy_cache.get((room_id, suggested_only)) if cached_result: return cached_result async def send_request( destination: str, ) -> Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]]: try: res = await self.transport_layer.get_room_hierarchy( destination=destination, room_id=room_id, suggested_only=suggested_only, ) except HttpResponseException as e: # If an error is received that is due to an unrecognised endpoint, # fallback to the unstable endpoint. Otherwise, consider it a # legitimate error and raise. if not self._is_unknown_endpoint(e): raise logger.debug( "Couldn't fetch room hierarchy with the v1 API, falling back to the unstable API" ) res = await self.transport_layer.get_room_hierarchy_unstable( destination=destination, room_id=room_id, suggested_only=suggested_only, ) room = res.get("room") if not isinstance(room, dict): raise InvalidResponseError("'room' must be a dict") # Validate children_state of the room. children_state = room.pop("children_state", []) if not isinstance(children_state, list): raise InvalidResponseError("'room.children_state' must be a list") if any(not isinstance(e, dict) for e in children_state): raise InvalidResponseError("Invalid event in 'children_state' list") try: for child_state in children_state: _validate_hierarchy_event(child_state) except ValueError as e: raise InvalidResponseError(str(e)) # Validate the children rooms. children = res.get("children", []) if not isinstance(children, list): raise InvalidResponseError("'children' must be a list") if any(not isinstance(r, dict) for r in children): raise InvalidResponseError("Invalid room in 'children' list") # Validate the inaccessible children. inaccessible_children = res.get("inaccessible_children", []) if not isinstance(inaccessible_children, list): raise InvalidResponseError("'inaccessible_children' must be a list") if any(not isinstance(r, str) for r in inaccessible_children): raise InvalidResponseError( "Invalid room ID in 'inaccessible_children' list" ) return room, children_state, children, inaccessible_children result = await self._try_destination_list( "fetch room hierarchy", destinations, send_request, failover_on_unknown_endpoint=True, ) # Cache the result to avoid fetching data over federation every time. self._get_room_hierarchy_cache[(room_id, suggested_only)] = result return result async def timestamp_to_event( self, destination: str, room_id: str, timestamp: int, direction: str ) -> "TimestampToEventResponse": """ Calls a remote federating server at `destination` asking for their closest event to the given timestamp in the given direction. Also validates the response to always return the expected keys or raises an error. Args: destination: Domain name of the remote homeserver room_id: Room to fetch the event from timestamp: The point in time (inclusive) we should navigate from in the given direction to find the closest event. direction: ["f"|"b"] to indicate whether we should navigate forward or backward from the given timestamp to find the closest event. Returns: A parsed TimestampToEventResponse including the closest event_id and origin_server_ts Raises: Various exceptions when the request fails InvalidResponseError when the response does not have the correct keys or wrong types """ remote_response = await self.transport_layer.timestamp_to_event( destination, room_id, timestamp, direction ) if not isinstance(remote_response, dict): raise InvalidResponseError( "Response must be a JSON dictionary but received %r" % remote_response ) try: return TimestampToEventResponse.from_json_dict(remote_response) except ValueError as e: raise InvalidResponseError(str(e)) async def get_account_status( self, destination: str, user_ids: List[str] ) -> Tuple[JsonDict, List[str]]: """Retrieves account statuses for a given list of users on a given remote homeserver. If the request fails for any reason, all user IDs for this destination are marked as failed. Args: destination: the destination to contact user_ids: the user ID(s) for which to request account status(es) Returns: The account statuses, as well as the list of user IDs for which it was not possible to retrieve a status. """ try: res = await self.transport_layer.get_account_status(destination, user_ids) except Exception: # If the query failed for any reason, mark all the users as failed. return {}, user_ids statuses = res.get("account_statuses", {}) failures = res.get("failures", []) if not isinstance(statuses, dict) or not isinstance(failures, list): # Make sure we're not feeding back malformed data back to the caller. logger.warning( "Destination %s responded with malformed data to account_status query", destination, ) return {}, user_ids for user_id in user_ids: # Any account whose status is missing is a user we failed to receive the # status of. if user_id not in statuses and user_id not in failures: failures.append(user_id) # Filter out any user ID that doesn't belong to the remote server that sent its # status (or failure). def filter_user_id(user_id: str) -> bool: try: return UserID.from_string(user_id).domain == destination except SynapseError: # If the user ID doesn't parse, ignore it. return False filtered_statuses = dict( # item is a (key, value) tuple, so item[0] is the user ID. filter(lambda item: filter_user_id(item[0]), statuses.items()) ) filtered_failures = list(filter(filter_user_id, failures)) return filtered_statuses, filtered_failures @attr.s(frozen=True, slots=True, auto_attribs=True) class TimestampToEventResponse: """Typed response dictionary for the federation /timestamp_to_event endpoint""" event_id: str origin_server_ts: int # the raw data, including the above keys data: JsonDict @classmethod def from_json_dict(cls, d: JsonDict) -> "TimestampToEventResponse": """Parsed response from the federation /timestamp_to_event endpoint Args: d: JSON object response to be parsed Raises: ValueError if d does not the correct keys or they are the wrong types """ event_id = d.get("event_id") if not isinstance(event_id, str): raise ValueError( "Invalid response: 'event_id' must be a str but received %r" % event_id ) origin_server_ts = d.get("origin_server_ts") if not isinstance(origin_server_ts, int): raise ValueError( "Invalid response: 'origin_server_ts' must be a int but received %r" % origin_server_ts ) return cls(event_id, origin_server_ts, d) def _validate_hierarchy_event(d: JsonDict) -> None: """Validate an event within the result of a /hierarchy request Args: d: json object to be parsed Raises: ValueError if d is not a valid event """ event_type = d.get("type") if not isinstance(event_type, str): raise ValueError("Invalid event: 'event_type' must be a str") room_id = d.get("room_id") if not isinstance(room_id, str): raise ValueError("Invalid event: 'room_id' must be a str") state_key = d.get("state_key") if not isinstance(state_key, str): raise ValueError("Invalid event: 'state_key' must be a str") content = d.get("content") if not isinstance(content, dict): raise ValueError("Invalid event: 'content' must be a dict") via = content.get("via") if not isinstance(via, list): raise ValueError("Invalid event: 'via' must be a list") if any(not isinstance(v, str) for v in via): raise ValueError("Invalid event: 'via' must be a list of strings")
en
0.89646
# Copyright 2015-2022 The Matrix.org Foundation C.I.C. # Copyright 2020 Sorunome # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Helper for _try_destination_list: indicates that the server returned a response we couldn't parse # The event to persist. # A string giving the server the event was sent to. # True if 'state' elides non-critical membership events # if 'partial_state' is set, a list of the servers in the room (otherwise empty) # A cache for fetching the room hierarchy over federation. # # Some stale data over federation is OK, but must be refreshed # periodically since the local server is in the room. # # It is a map of (room ID, suggested-only) -> the response of # get_room_hierarchy. Clear pdu_destination_tried cache Sends a federation Query to a remote homeserver of the given type and arguments. Args: destination: Domain name of the remote homeserver query_type: Category of the query type; should match the handler name used in register_query_handler(). args: Mapping of strings to strings containing the details of the query request. ignore_backoff: true to ignore the historical backoff data and try the request anyway. Returns: The JSON object from the response Query device keys for a device hosted on a remote server. Args: destination: Domain name of the remote homeserver content: The query content. Returns: The JSON object from the response Query the device keys for a list of user ids hosted on a remote server. Claims one-time keys for a device hosted on a remote server. Args: destination: Domain name of the remote homeserver content: The query content. Returns: The JSON object from the response Requests some more historic PDUs for the given room from the given destination server. Args: dest: The remote homeserver to ask. room_id: The room_id to backfill. limit: The maximum number of events to return. extremities: our current backwards extremities, to backfill from Must be a Collection that is falsy when empty. (Iterable is not enough here!) # If there are no extremities then we've (probably) reached the start. # TODO we probably want an exception type specific to federation # client validation. # TODO we probably want an exception type specific to federation # client validation. # Check signatures and hash of pdus, removing any from the list that fail checks Requests the PDU with given origin and ID from the remote home server. Does not have any caching or rate limiting! Args: destination: Which homeserver to query event_id: event to fetch room_version: version of the room timeout: How long to try (in ms) each destination for before moving to the next destination. None indicates no timeout. Returns: The requested PDU, or None if we were unable to find it. Raises: SynapseError, NotRetryingDestination, FederationDeniedError # Check signatures are correct. Requests the PDU with given origin and ID from the remote home servers. Will attempt to get the PDU from each destination in the list until one succeeds. Args: destinations: Which homeservers to query event_id: event to fetch room_version: version of the room timeout: How long to try (in ms) each destination for before moving to the next destination. None indicates no timeout. Returns: The requested PDU, or None if we were unable to find it. # TODO: Rate limit the number of times we try and get the same event. Calls the /state_ids endpoint to fetch the state at a particular point in the room, and the auth events for the given event Returns: a tuple of (state event_ids, auth event_ids) Calls the /state endpoint to fetch the state at a particular point in the room. Any invalid events (those with incorrect or unverifiable signatures or hashes) are filtered out from the response, and any duplicate events are removed. (Size limits and other event-format checks are *not* performed.) Note that the result is not ordered, so callers must be careful to process the events in an order that handles dependencies. Returns: a tuple of (state events, auth events) # we may as well filter out any duplicates from the response, to save # processing them multiple times. (In particular, events may be present in # `auth_events` as well as `state`, which is redundant). # # We don't rely on the sort order of the events, so we can just stick them # in a dict. Checks the signatures and hashes of a list of events. If a PDU fails its signature check then we check if we have it in the database, and if not then request it from the sender's server (if that is different from `origin`). If that still fails, the event is omitted from the returned list. If a PDU fails its content hash check then it is redacted. Also runs each event through the spam checker; if it fails, redacts the event and flags it as soft-failed. The given list of PDUs are not modified; instead the function returns a new list. Args: origin: The server that sent us these events pdus: The events to be checked room_version: the version of the room these events are in Returns: A list of PDUs that have valid signatures and hashes. # We limit how many PDUs we check at once, as if we try to do hundreds # of thousands of PDUs at once we see large memory spikes. Takes a PDU and checks its signatures and hashes. If the PDU fails its signature check then we check if we have it in the database; if not, we then request it from sender's server (if that is not the same as `origin`). If that still fails, we return None. If the PDU fails its content hash check, it is redacted. Also runs the event through the spam checker; if it fails, redacts the event and flags it as soft-failed. Args: origin pdu room_version Returns: The PDU (possibly redacted) if it has valid signatures and hashes. # Check local db. Returns true if the response was due to an endpoint being unimplemented. Args: e: The error response received from the remote server. synapse_error: The above error converted to a SynapseError. This is automatically generated if not provided. # There is no good way to detect an "unknown" endpoint. # # Dendrite returns a 404 (with a body of "404 page not found"); # Conduit returns a 404 (with no body); and Synapse returns a 400 # with M_UNRECOGNISED. # # This needs to be rather specific as some endpoints truly do return 404 # errors. Try an operation on a series of servers, until it succeeds Args: description: description of the operation we're doing, for logging destinations: list of server_names to try callback: Function to run for each server. Passed a single argument: the server_name to try. If the callback raises a CodeMessageException with a 300/400 code or an UnsupportedRoomVersionError, attempts to perform the operation stop immediately and the exception is reraised. Otherwise, if the callback raises an Exception the error is logged and the next server tried. Normally the stacktrace is logged but this is suppressed if the exception is an InvalidResponseError. failover_errcodes: Error codes (specific to this endpoint) which should cause a failover when received as part of an HTTP 400 error. failover_on_unknown_endpoint: if True, we will try other servers if it looks like a server doesn't support the endpoint. This is typically useful if the endpoint in question is new or experimental. Returns: The result of callback, if it succeeds Raises: SynapseError if the chosen remote server returns a 300/400 code, or no servers were reachable. # Failover should occur: # # * On internal server errors. # * If the destination responds that it cannot complete the request. # * If the destination doesn't implemented the endpoint for some reason. Creates an m.room.member event, with context, without participating in the room. Does so by asking one of the already participating servers to create an event with proper context. Returns a fully signed and hashed event. Note that this does not append any events to any graphs. Args: destinations: Candidate homeservers which are probably participating in the room. room_id: The room in which the event will happen. user_id: The user whose membership is being evented. membership: The "membership" property of the event. Must be one of "join" or "leave". content: Any additional data to put into the content field of the event. params: Query parameters to include in the request. Returns: `(origin, event, room_version)` where origin is the remote homeserver which generated the event, and room_version is the version of the room. Raises: UnsupportedRoomVersionError: if remote responds with a room version we don't understand. SynapseError: if the chosen remote server returns a 300/400 code, or no servers successfully handle the request. # Note: If not supplied, the room version may be either v1 or v2, # however either way the event format version will be v1. # The protoevent received over the JSON wire may not have all # the required fields. Lets just gloss over that because # there's some we never care about # MSC3083 defines additional error codes for room joins. Unfortunately # we do not yet know the room version, assume these will only be returned # by valid room versions. Sends a join event to one of a list of homeservers. Doing so will cause the remote server to add the event to the graph, and send the event out to the rest of the federation. Args: destinations: Candidate homeservers which are probably participating in the room. pdu: event to be sent room_version: the version of the room (according to the server that did the make_join) Returns: The result of the send join request. Raises: SynapseError: if the chosen remote server returns a 300/400 code, or no servers successfully handle the request. # If an event was returned (and expected to be returned): # # * Ensure it has the same event ID (note that the event ID is a hash # of the event fields for versions which support MSC3083). # * Ensure the signatures are good. # # Otherwise, fallback to the provided event. # If the state doesn't have a create event then the room is # invalid, and it would fail auth checks anyway. # the room version should be sane. # either the server that fulfilled the make_join, or the server that is # handling the send_join, is lying. # We now go and check the signatures and hashes for the event. Note # that we limit how many events we process at a time to keep the # memory overhead from exploding. # NB: We *need* to copy to ensure that we don't have multiple # references being passed on, as that causes... issues. # NB: We *need* to copy to ensure that we don't have multiple # references being passed on, as that causes... issues. # double-check that the auth chain doesn't include a different create event # MSC3083 defines additional error codes for room joins. # If the join is being authorised via allow rules, we need to send # the /send_join back to the same server that was originally used # with /make_join. # If an error is received that is due to an unrecognised endpoint, # fallback to the v1 endpoint. Otherwise, consider it a legitimate error # and raise. # Check signatures are correct. # FIXME: We should handle signature failures more gracefully. Actually sends the invite, first trying v2 API and falling back to v1 API if necessary. Returns: The event as a dict as returned by the remote server Raises: SynapseError: if the remote server returns an error or if the server only supports the v1 endpoint and a room version other than "1" or "2" is requested. # If an error is received that is due to an unrecognised endpoint, # fallback to the v1 endpoint if the room uses old-style event IDs. # Otherwise, consider it a legitimate error and raise. # Didn't work, try v1 API. # Note the v1 API returns a tuple of `(200, content)` Sends a leave event to one of a list of homeservers. Doing so will cause the remote server to add the event to the graph, and send the event out to the rest of the federation. This is mostly useful to reject received invites. Args: destinations: Candidate homeservers which are probably participating in the room. pdu: event to be sent Raises: SynapseError: if the chosen remote server returns a 300/400 code, or no servers successfully handle the request. # If an error is received that is due to an unrecognised endpoint, # fallback to the v1 endpoint. Otherwise, consider it a legitimate error # and raise. # We expect the v1 API to respond with [200, content], so we only return the # content. Attempts to send a knock event to given a list of servers. Iterates through the list until one attempt succeeds. Doing so will cause the remote server to add the event to the graph, and send the event out to the rest of the federation. Args: destinations: A list of candidate homeservers which are likely to be participating in the room. pdu: The event to be sent. Returns: The remote homeserver return some state from the room. The response dictionary is in the form: {"knock_state_events": [<state event dict>, ...]} The list of state events may be empty. Raises: SynapseError: If the chosen remote server returns a 3xx/4xx code. RuntimeError: If no servers were reachable. Send a knock event to a remote homeserver. Args: destination: The homeserver to send to. pdu: The event to send. Returns: The remote homeserver can optionally return some state from the room. The response dictionary is in the form: {"knock_state_events": [<state event dict>, ...]} The list of state events may be empty. Get the list of public rooms from a remote homeserver Args: remote_server: The name of the remote server limit: Maximum amount of rooms to return since_token: Used for result pagination search_filter: A filter dictionary to send the remote homeserver and filter the result set include_all_networks: Whether to include results from all third party instances third_party_instance_id: Whether to only include results from a specific third party instance Returns: The response from the remote server. Raises: HttpResponseException / RequestSendFailed: There was an exception returned from the remote server SynapseException: M_FORBIDDEN when the remote server has disallowed publicRoom requests over federation Tries to fetch events we are missing. This is called when we receive an event without having received all of its ancestors. Args: destination room_id earliest_events_ids: List of event ids. Effectively the events we expected to receive, but haven't. `get_missing_events` should only return events that didn't happen before these. latest_events: List of events we have received that we don't have all previous events for. limit: Maximum number of events to return. min_depth: Minimum depth of events to return. timeout: Max time to wait in ms # We are probably hitting an old server that doesn't support # get_missing_events Fetch the complexity of a remote room from another server. Args: destination: The remote server room_id: The room ID to ask about. Returns: Dict contains the complexity metric versions, while None means we could not fetch the complexity. # We didn't manage to get it -- probably a 404. We are okay if other # servers don't give it to us. # If we don't manage to find it, return None. It's not an error if a # server doesn't give it to us. Call other servers to get a hierarchy of the given room. Performs simple data validates and parsing of the response. Args: destinations: The remote servers. We will try them in turn, omitting any that have been blacklisted. room_id: ID of the space to be queried suggested_only: If true, ask the remote server to only return children with the "suggested" flag set Returns: A tuple of: The room as a JSON dictionary, without a "children_state" key. A list of `m.space.child` state events. A list of children rooms, as JSON dictionaries. A list of inaccessible children room IDs. Raises: SynapseError if we were unable to get a valid summary from any of the remote servers # If an error is received that is due to an unrecognised endpoint, # fallback to the unstable endpoint. Otherwise, consider it a # legitimate error and raise. # Validate children_state of the room. # Validate the children rooms. # Validate the inaccessible children. # Cache the result to avoid fetching data over federation every time. Calls a remote federating server at `destination` asking for their closest event to the given timestamp in the given direction. Also validates the response to always return the expected keys or raises an error. Args: destination: Domain name of the remote homeserver room_id: Room to fetch the event from timestamp: The point in time (inclusive) we should navigate from in the given direction to find the closest event. direction: ["f"|"b"] to indicate whether we should navigate forward or backward from the given timestamp to find the closest event. Returns: A parsed TimestampToEventResponse including the closest event_id and origin_server_ts Raises: Various exceptions when the request fails InvalidResponseError when the response does not have the correct keys or wrong types Retrieves account statuses for a given list of users on a given remote homeserver. If the request fails for any reason, all user IDs for this destination are marked as failed. Args: destination: the destination to contact user_ids: the user ID(s) for which to request account status(es) Returns: The account statuses, as well as the list of user IDs for which it was not possible to retrieve a status. # If the query failed for any reason, mark all the users as failed. # Make sure we're not feeding back malformed data back to the caller. # Any account whose status is missing is a user we failed to receive the # status of. # Filter out any user ID that doesn't belong to the remote server that sent its # status (or failure). # If the user ID doesn't parse, ignore it. # item is a (key, value) tuple, so item[0] is the user ID. Typed response dictionary for the federation /timestamp_to_event endpoint # the raw data, including the above keys Parsed response from the federation /timestamp_to_event endpoint Args: d: JSON object response to be parsed Raises: ValueError if d does not the correct keys or they are the wrong types Validate an event within the result of a /hierarchy request Args: d: json object to be parsed Raises: ValueError if d is not a valid event
1.386191
1
parsec/commands/histories/get_most_recently_used_history.py
erasche/parsec
8
6625140
<gh_stars>1-10 import click from parsec.cli import pass_context, json_loads from parsec.decorators import custom_exception, json_output @click.command('get_most_recently_used_history') @pass_context @custom_exception @json_output def cli(ctx): """Returns the current user's most recently used history (not deleted). Output: History representation """ return ctx.gi.histories.get_most_recently_used_history()
import click from parsec.cli import pass_context, json_loads from parsec.decorators import custom_exception, json_output @click.command('get_most_recently_used_history') @pass_context @custom_exception @json_output def cli(ctx): """Returns the current user's most recently used history (not deleted). Output: History representation """ return ctx.gi.histories.get_most_recently_used_history()
en
0.792143
Returns the current user's most recently used history (not deleted). Output: History representation
2.074104
2
main.py
LiReNa00/JDBot
0
6625141
import os import logging import discord import re import aiohttp import traceback import asyncpg import B from discord.ext import commands async def get_prefix(bot, message): extras = ["test*", "te*", "t*", "jdbot.", "jd.", "test.", "te."] comp = re.compile("^(" + "|".join(map(re.escape, extras)) + ").*", flags=re.I) match = comp.match(message.content) if match is not None: extras.append(match.group(1)) if await bot.is_owner(message.author): extras.append("") return commands.when_mentioned_or(*extras)(bot, message) class JDBotContext(commands.Context): async def send(self, *args, **kwargs): msg = await super().send(*args, **kwargs) view = kwargs.get("view") if view is not None: view.message = msg return msg class JDBot(commands.Bot): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.special_access = {} self.suspended = False async def start(self, *args, **kwargs): self.session = aiohttp.ClientSession() self.db = await asyncpg.create_pool(os.getenv("DB_key")) # loads up some bot variables self.testers = [u.get("user_id") for u in await self.db.fetch("SELECT * FROM testers_list;")] # does the DB connection and then assigns it a tester list self.blacklisted_users = dict(await self.db.fetch("SELECT * FROM BLACKLISTED_USERS;")) self.blacklisted_users.update(dict(await self.db.fetch("SELECT * FROM SUS_USERS;"))) self.history = [h.get("response") for h in await self.db.fetch("SELECT * FROM RANDOM_HISTORY")] await super().start(*args, **kwargs) async def close(self): await self.session.close() await self.db.close() await super().close() async def on_error(self, event, *args, **kwargs): more_information = os.sys.exc_info() error_wanted = traceback.format_exc() traceback.print_exc() # print(event) # print(more_information[0]) # print(args) # print(kwargs) # check about on_error with other repos of mine as well to update this. async def get_context(self, message, *, cls=JDBotContext): return await super().get_context(message, cls=cls) intents = discord.Intents.all() bot = JDBot( command_prefix=(get_prefix), intents=intents, chunk_guilds_at_startup=False, strip_after_prefix=True, allowed_mentions=discord.AllowedMentions(everyone=False, roles=False), ) bot.launch_time = discord.utils.utcnow() @bot.check async def check_command_access(ctx): if ctx.command.name == bot.special_access.get(ctx.author.id): await ctx.reinvoke() if ctx.author.id in bot.special_access: del bot.special_access[ctx.author.id] return True @bot.check async def check_blacklist(ctx): return not ctx.author.id in bot.blacklisted_users @bot.check async def check_suspended(ctx): return not ctx.bot.suspended or await ctx.bot.is_owner(ctx.author) for filename in os.listdir("./cogs"): if filename.endswith(".py"): try: bot.load_extension(f"cogs.{filename[:-3]}") except commands.errors.ExtensionError: traceback.print_exc() logging.basicConfig(level=logging.INFO) B.b() bot.run(os.environ["classic_token"])
import os import logging import discord import re import aiohttp import traceback import asyncpg import B from discord.ext import commands async def get_prefix(bot, message): extras = ["test*", "te*", "t*", "jdbot.", "jd.", "test.", "te."] comp = re.compile("^(" + "|".join(map(re.escape, extras)) + ").*", flags=re.I) match = comp.match(message.content) if match is not None: extras.append(match.group(1)) if await bot.is_owner(message.author): extras.append("") return commands.when_mentioned_or(*extras)(bot, message) class JDBotContext(commands.Context): async def send(self, *args, **kwargs): msg = await super().send(*args, **kwargs) view = kwargs.get("view") if view is not None: view.message = msg return msg class JDBot(commands.Bot): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.special_access = {} self.suspended = False async def start(self, *args, **kwargs): self.session = aiohttp.ClientSession() self.db = await asyncpg.create_pool(os.getenv("DB_key")) # loads up some bot variables self.testers = [u.get("user_id") for u in await self.db.fetch("SELECT * FROM testers_list;")] # does the DB connection and then assigns it a tester list self.blacklisted_users = dict(await self.db.fetch("SELECT * FROM BLACKLISTED_USERS;")) self.blacklisted_users.update(dict(await self.db.fetch("SELECT * FROM SUS_USERS;"))) self.history = [h.get("response") for h in await self.db.fetch("SELECT * FROM RANDOM_HISTORY")] await super().start(*args, **kwargs) async def close(self): await self.session.close() await self.db.close() await super().close() async def on_error(self, event, *args, **kwargs): more_information = os.sys.exc_info() error_wanted = traceback.format_exc() traceback.print_exc() # print(event) # print(more_information[0]) # print(args) # print(kwargs) # check about on_error with other repos of mine as well to update this. async def get_context(self, message, *, cls=JDBotContext): return await super().get_context(message, cls=cls) intents = discord.Intents.all() bot = JDBot( command_prefix=(get_prefix), intents=intents, chunk_guilds_at_startup=False, strip_after_prefix=True, allowed_mentions=discord.AllowedMentions(everyone=False, roles=False), ) bot.launch_time = discord.utils.utcnow() @bot.check async def check_command_access(ctx): if ctx.command.name == bot.special_access.get(ctx.author.id): await ctx.reinvoke() if ctx.author.id in bot.special_access: del bot.special_access[ctx.author.id] return True @bot.check async def check_blacklist(ctx): return not ctx.author.id in bot.blacklisted_users @bot.check async def check_suspended(ctx): return not ctx.bot.suspended or await ctx.bot.is_owner(ctx.author) for filename in os.listdir("./cogs"): if filename.endswith(".py"): try: bot.load_extension(f"cogs.{filename[:-3]}") except commands.errors.ExtensionError: traceback.print_exc() logging.basicConfig(level=logging.INFO) B.b() bot.run(os.environ["classic_token"])
en
0.849408
# loads up some bot variables # does the DB connection and then assigns it a tester list # print(event) # print(more_information[0]) # print(args) # print(kwargs) # check about on_error with other repos of mine as well to update this.
2.291763
2
ci/nfbuildosx.py
dmyers87/NFHTTP
573
6625142
#!/usr/bin/env python ''' * Copyright (c) 2018 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ''' import fnmatch import os import plistlib import re import shutil import subprocess import sys from distutils import dir_util from nfbuild import NFBuild class NFBuildOSX(NFBuild): def __init__(self): super(self.__class__, self).__init__() self.project_file = os.path.join( self.build_directory, 'NFHTTP.xcodeproj') self.cmake_binary = 'cmake' self.curl_directory = self.current_working_directory + '/libraries/curl' self.clang_format_binary = 'clang-format' self.android_ndk_folder = '/usr/local/share/android-ndk' self.ninja_binary = 'ninja' self.ios = False self.android = False self.android_arm = False def generateProject(self, code_coverage=False, address_sanitizer=False, thread_sanitizer=False, undefined_behaviour_sanitizer=False, ios=False, use_curl=False, use_cpprest=False, android=False, android_arm=False, gcc=False): self.use_ninja = android or android_arm self.android = android self.android_arm = android_arm self.ios = ios cmake_call = [ self.cmake_binary, '..'] if self.use_ninja: cmake_call.append('-GNinja') else: cmake_call.append('-GXcode') if self.build_type == 'Release': cmake_call.append('-DCREATE_RELEASE_BUILD=1') else: cmake_call.append('-DCREATE_RELEASE_BUILD=0') if address_sanitizer: cmake_call.append('-DUSE_ADDRESS_SANITIZER=1') cmake_call.append('-DUSE_CURL={}'.format(1 if use_curl else 0)) if use_cpprest: cmake_call.append('-DUSE_CPPRESTSDK=1') if code_coverage: cmake_call.append('-DCODE_COVERAGE=1') else: cmake_call.append('-DCODE_COVERAGE=0') if android or android_arm: android_abi = 'x86_64' android_toolchain_name = 'x86_64-llvm' if android_arm: android_abi = 'arm64-v8a' android_toolchain_name = 'arm64-llvm' cmake_call.extend([ '-DANDROID=1', '-DCMAKE_TOOLCHAIN_FILE=' + self.android_ndk_folder + '/build/cmake/android.toolchain.cmake', '-DANDROID_NDK=' + self.android_ndk_folder, '-DANDROID_ABI=' + android_abi, '-DANDROID_NATIVE_API_LEVEL=21', '-DANDROID_TOOLCHAIN_NAME=' + android_toolchain_name, '-DANDROID_STL=c++_shared']) self.project_file = 'build.ninja' if ios: cmake_call.extend(['-DIOS=1']) cmake_result = subprocess.call(cmake_call, cwd=self.build_directory) if cmake_result != 0: sys.exit(cmake_result) def buildTarget(self, target, sdk='macosx', arch='x86_64'): result = 0 if self.use_ninja: result = subprocess.call([ self.ninja_binary, '-C', self.build_directory, '-f', self.project_file, target]) else: result = subprocess.call([ 'xcodebuild', '-project', self.project_file, '-target', target, '-sdk', sdk, '-arch', arch, '-configuration', self.build_type, 'build']) if result != 0: sys.exit(result) def staticallyAnalyse(self, target, include_regex=None): diagnostics_key = 'diagnostics' files_key = 'files' exceptions_key = 'static_analyzer_exceptions' static_file_exceptions = [] static_analyzer_result = subprocess.check_output([ 'xcodebuild', '-project', self.project_file, '-target', target, '-sdk', 'macosx', '-configuration', self.build_type, '-dry-run', 'analyze']).decode() analyze_command = '--analyze' for line in static_analyzer_result.splitlines(): if analyze_command not in line: continue static_analyzer_line_words = line.split() analyze_command_index = static_analyzer_line_words.index( analyze_command) source_file = static_analyzer_line_words[analyze_command_index + 1] if source_file.startswith(self.current_working_directory): source_file = source_file[ len(self.current_working_directory)+1:] if include_regex is not None: if not re.match(include_regex, source_file): continue if source_file in self.statically_analyzed_files: continue self.build_print('Analysing ' + source_file) stripped_command = line.strip() clang_result = subprocess.call(stripped_command, shell=True) if clang_result: sys.exit(clang_result) self.statically_analyzed_files.append(source_file) static_analyzer_check_passed = True for root, dirnames, filenames in os.walk(self.build_directory): for filename in fnmatch.filter(filenames, '*.plist'): full_filepath = os.path.join(root, filename) static_analyzer_result = {} with open(full_filepath, "rb") as plist_file_handle: static_analyzer_result = plistlib.load(plist_file_handle) if 'clang_version' not in static_analyzer_result \ or files_key not in static_analyzer_result \ or diagnostics_key not in static_analyzer_result: continue if len(static_analyzer_result[files_key]) == 0: continue for static_analyzer_file in static_analyzer_result[files_key]: if static_analyzer_file in static_file_exceptions: continue if self.current_working_directory not in static_analyzer_file: continue normalised_file = static_analyzer_file[ len(self.current_working_directory)+1:] if normalised_file in \ self.build_configuration[exceptions_key]: continue self.build_print('Issues found in: ' + normalised_file) for static_analyzer_issue in \ static_analyzer_result[diagnostics_key]: self.pretty_printer.pprint(static_analyzer_issue) sys.stdout.flush() static_analyzer_check_passed = False if not static_analyzer_check_passed: sys.exit(1)
#!/usr/bin/env python ''' * Copyright (c) 2018 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ''' import fnmatch import os import plistlib import re import shutil import subprocess import sys from distutils import dir_util from nfbuild import NFBuild class NFBuildOSX(NFBuild): def __init__(self): super(self.__class__, self).__init__() self.project_file = os.path.join( self.build_directory, 'NFHTTP.xcodeproj') self.cmake_binary = 'cmake' self.curl_directory = self.current_working_directory + '/libraries/curl' self.clang_format_binary = 'clang-format' self.android_ndk_folder = '/usr/local/share/android-ndk' self.ninja_binary = 'ninja' self.ios = False self.android = False self.android_arm = False def generateProject(self, code_coverage=False, address_sanitizer=False, thread_sanitizer=False, undefined_behaviour_sanitizer=False, ios=False, use_curl=False, use_cpprest=False, android=False, android_arm=False, gcc=False): self.use_ninja = android or android_arm self.android = android self.android_arm = android_arm self.ios = ios cmake_call = [ self.cmake_binary, '..'] if self.use_ninja: cmake_call.append('-GNinja') else: cmake_call.append('-GXcode') if self.build_type == 'Release': cmake_call.append('-DCREATE_RELEASE_BUILD=1') else: cmake_call.append('-DCREATE_RELEASE_BUILD=0') if address_sanitizer: cmake_call.append('-DUSE_ADDRESS_SANITIZER=1') cmake_call.append('-DUSE_CURL={}'.format(1 if use_curl else 0)) if use_cpprest: cmake_call.append('-DUSE_CPPRESTSDK=1') if code_coverage: cmake_call.append('-DCODE_COVERAGE=1') else: cmake_call.append('-DCODE_COVERAGE=0') if android or android_arm: android_abi = 'x86_64' android_toolchain_name = 'x86_64-llvm' if android_arm: android_abi = 'arm64-v8a' android_toolchain_name = 'arm64-llvm' cmake_call.extend([ '-DANDROID=1', '-DCMAKE_TOOLCHAIN_FILE=' + self.android_ndk_folder + '/build/cmake/android.toolchain.cmake', '-DANDROID_NDK=' + self.android_ndk_folder, '-DANDROID_ABI=' + android_abi, '-DANDROID_NATIVE_API_LEVEL=21', '-DANDROID_TOOLCHAIN_NAME=' + android_toolchain_name, '-DANDROID_STL=c++_shared']) self.project_file = 'build.ninja' if ios: cmake_call.extend(['-DIOS=1']) cmake_result = subprocess.call(cmake_call, cwd=self.build_directory) if cmake_result != 0: sys.exit(cmake_result) def buildTarget(self, target, sdk='macosx', arch='x86_64'): result = 0 if self.use_ninja: result = subprocess.call([ self.ninja_binary, '-C', self.build_directory, '-f', self.project_file, target]) else: result = subprocess.call([ 'xcodebuild', '-project', self.project_file, '-target', target, '-sdk', sdk, '-arch', arch, '-configuration', self.build_type, 'build']) if result != 0: sys.exit(result) def staticallyAnalyse(self, target, include_regex=None): diagnostics_key = 'diagnostics' files_key = 'files' exceptions_key = 'static_analyzer_exceptions' static_file_exceptions = [] static_analyzer_result = subprocess.check_output([ 'xcodebuild', '-project', self.project_file, '-target', target, '-sdk', 'macosx', '-configuration', self.build_type, '-dry-run', 'analyze']).decode() analyze_command = '--analyze' for line in static_analyzer_result.splitlines(): if analyze_command not in line: continue static_analyzer_line_words = line.split() analyze_command_index = static_analyzer_line_words.index( analyze_command) source_file = static_analyzer_line_words[analyze_command_index + 1] if source_file.startswith(self.current_working_directory): source_file = source_file[ len(self.current_working_directory)+1:] if include_regex is not None: if not re.match(include_regex, source_file): continue if source_file in self.statically_analyzed_files: continue self.build_print('Analysing ' + source_file) stripped_command = line.strip() clang_result = subprocess.call(stripped_command, shell=True) if clang_result: sys.exit(clang_result) self.statically_analyzed_files.append(source_file) static_analyzer_check_passed = True for root, dirnames, filenames in os.walk(self.build_directory): for filename in fnmatch.filter(filenames, '*.plist'): full_filepath = os.path.join(root, filename) static_analyzer_result = {} with open(full_filepath, "rb") as plist_file_handle: static_analyzer_result = plistlib.load(plist_file_handle) if 'clang_version' not in static_analyzer_result \ or files_key not in static_analyzer_result \ or diagnostics_key not in static_analyzer_result: continue if len(static_analyzer_result[files_key]) == 0: continue for static_analyzer_file in static_analyzer_result[files_key]: if static_analyzer_file in static_file_exceptions: continue if self.current_working_directory not in static_analyzer_file: continue normalised_file = static_analyzer_file[ len(self.current_working_directory)+1:] if normalised_file in \ self.build_configuration[exceptions_key]: continue self.build_print('Issues found in: ' + normalised_file) for static_analyzer_issue in \ static_analyzer_result[diagnostics_key]: self.pretty_printer.pprint(static_analyzer_issue) sys.stdout.flush() static_analyzer_check_passed = False if not static_analyzer_check_passed: sys.exit(1)
en
0.841708
#!/usr/bin/env python * Copyright (c) 2018 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License.
1.845425
2
utils/train_utils.py
HickmannLautaro/GroupNorm
0
6625143
import argparse import os import shutil import sys import time import tensorflow as tf import tensorflow_datasets as tfds def get_parsed_in(): """ Parse command line inputs @return: arguments dictionary containing parsed command line inputs """ parser = argparse.ArgumentParser(description="Configurations to run normalization experiments with ResNet") parser.add_argument('--replace', action='store_true', help='overwrite previous run if it exists') parser.add_argument('--continue', action='store_true', help='continue training: load the latest checkpoint and continue training') parser.add_argument('--cont_epoch', type=int, default=-1, help='Used together with continue, overwrites the saved epoch of the checkpoint and sets the initial epoch for continue training') parser.add_argument('--experimental_data_aug', action='store_true', help='Use experimental data augmentation inside the network instead of the one before the network (Only used for epochs = 100)') parser.add_argument('--cpu', action='store_true', help='train on only cpu') parser.add_argument('--ResNet', type=int, default=3, choices=[3, 5], help='Defines what Resnet model to use, 3-> ResNet 20, 5-> ResNet 32') parser.add_argument('--batch_size', type=int, default=32, choices=[32, 16, 8, 4, 2], help='batch size per worker') parser.add_argument('--epochs', type=int, default=30, choices=[30, 100], help='training epochs') parser.add_argument('--norm', type=str, default='GN', choices=['BN', 'GN'], help='decide if BN (batch normalization) or GN (group normalization is applied)') parser.add_argument('--run', type=int, default=1, help='Differentiate multiple runs for statistical comparison') parser.add_argument('--weight_decay', action='store_true', help='Set to use SGDW (stochastic gradient with weight decay) as optimizer and use weight decay (unstable) otherwise adam is used.') arguments = vars(parser.parse_args()) if arguments['continue'] and arguments['replace']: print("Incompatible options to continue training and remove it to replace choose one or the other") sys.exit() return arguments def create_folders(arguments): """ Creates the folder structure needed to save logs and checkpoints depending on the @param arguments: run configuration @return: log_path where to save logs and models_path where to save the checkpoints. """ if arguments['weight_decay']: path = os.path.join(arguments['norm'], "ResNet" + str(arguments['ResNet'] * 6 + 2), "weight_decay", "epochs_" + str(arguments['epochs']), "batch_" + str(arguments['batch_size']), "run_" + str(arguments['run'])) else: path = os.path.join(arguments['norm'], "ResNet" + str(arguments['ResNet'] * 6 + 2), "no_weight_decay", "epochs_" + str(arguments['epochs']), "batch_" + str(arguments['batch_size']), "run_" + str(arguments['run'])) log_path = os.path.join("train_outputs/logs", path) models_path = os.path.join("train_outputs/checkpoints", path) # If paths exist and replacement is desired delete old files. To solve interference with tensorboard try to delete multiple times. Probably better solutions exist. for i in range(3): if os.path.exists(models_path) and os.path.exists(log_path) and arguments['replace']: print("Delete old models") try: shutil.rmtree(models_path) except OSError as e: print("Error: %s : %s" % (models_path, e.strerror)) sys.exit(1) try: shutil.rmtree(log_path) except OSError as e: print("Error: %s : %s" % (log_path, e.strerror)) sys.exit(1) time.sleep(1) # Create file structures try: os.makedirs(models_path) except OSError: if not arguments['continue']: print("Creation of the directory %s failed, if replacement is desired start script with argument --replace " % models_path) sys.exit(1) else: print("Successfully created the directory %s" % models_path) try: os.makedirs(log_path) except OSError: print("Creation of the directory %s failed" % log_path) if not arguments['continue']: print("Creation of the directory %s failed, if replacement is desired start script with argument --replace " % log_path) sys.exit(1) else: print("Successfully created the directory %s" % log_path) return log_path, models_path @tf.function def random_zoom(image): """ Data augmentation function, random zoom a part of an image and then resize to 32,32,3 @param image: input image @return: zoomed image. """ sz = tf.random.uniform((1,), 24, 32, dtype=tf.int32) # Get random state zoom = tf.image.random_crop(image, size=(sz[0], sz[0], 3)) # Crop image zoomed = tf.image.resize(zoom, (32, 32), method=tf.image.ResizeMethod.BICUBIC) # resize image to correct dimensions return zoomed @tf.function def normalize_img(image, label): """Normalizes images: `uint8` -> `float32`.""" return tf.image.convert_image_dtype(image, tf.float32), label # tf.cast(image, tf.float32) / 255.0, label # tf.image.convert_image_dtype(image, tf.float32), label def prepare_dataset(image, label): """ Apply data augmentation to @param image: input image @param label: corresponding label @return: augmented image and original label """ image = tf.image.random_flip_left_right(image) image = random_zoom(image) return image, label def get_data(arguments): """ Load training and validation data and apply normalization and optionally data augmentation @param arguments: batch size @return: training and validation sets """ batch_size = arguments['batch_size'] (train, test), ds_info = tfds.load('cifar10', split=['train', 'test'], as_supervised=True, with_info=True) # Load CIFAR-10 buffer_size = 10000 if arguments['epochs'] == 30: # For better results and since map is not really random (https://github.com/tensorflow/tensorflow/issues/35682#issuecomment-573777790) # the data is repeated 4 times and therefore the training epochs are reduced from 100 to 25, 30 was used because I mistyped and realized to late. train = train.map(normalize_img).repeat(4).map(prepare_dataset).batch(batch_size).shuffle(buffer_size).cache() else: train = train.map(normalize_img).batch(batch_size).shuffle(buffer_size).cache() # Normalize the validation/test set test = test.map(normalize_img).batch(batch_size) return train, test def get_test_data(arguments): """ Load and normalize only the test dataset @param arguments: batch size @return: test set """ batch_size = arguments['batch_size'] (train, test), ds_info = tfds.load('cifar10', split=['train', 'test'], as_supervised=True, with_info=True) test = test.map(normalize_img).batch(batch_size) return test def select_device(arguments): """ Sets if training should happen on CPU or GPU @param arguments: CPU or GPU @return: string for information print """ if arguments['cpu']: device = 'CPU' os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # Make GPU not visible for tensorflow else: device = 'GPU' # Turn memory growth om to run multiple scripts in parallel on the same GPU gpu_devices = tf.config.experimental.list_physical_devices('GPU') if len(gpu_devices) > 0: tf.config.experimental.set_memory_growth(gpu_devices[0], True) else: print("GPU selected but no GPUs available") sys.exit(1) return device
import argparse import os import shutil import sys import time import tensorflow as tf import tensorflow_datasets as tfds def get_parsed_in(): """ Parse command line inputs @return: arguments dictionary containing parsed command line inputs """ parser = argparse.ArgumentParser(description="Configurations to run normalization experiments with ResNet") parser.add_argument('--replace', action='store_true', help='overwrite previous run if it exists') parser.add_argument('--continue', action='store_true', help='continue training: load the latest checkpoint and continue training') parser.add_argument('--cont_epoch', type=int, default=-1, help='Used together with continue, overwrites the saved epoch of the checkpoint and sets the initial epoch for continue training') parser.add_argument('--experimental_data_aug', action='store_true', help='Use experimental data augmentation inside the network instead of the one before the network (Only used for epochs = 100)') parser.add_argument('--cpu', action='store_true', help='train on only cpu') parser.add_argument('--ResNet', type=int, default=3, choices=[3, 5], help='Defines what Resnet model to use, 3-> ResNet 20, 5-> ResNet 32') parser.add_argument('--batch_size', type=int, default=32, choices=[32, 16, 8, 4, 2], help='batch size per worker') parser.add_argument('--epochs', type=int, default=30, choices=[30, 100], help='training epochs') parser.add_argument('--norm', type=str, default='GN', choices=['BN', 'GN'], help='decide if BN (batch normalization) or GN (group normalization is applied)') parser.add_argument('--run', type=int, default=1, help='Differentiate multiple runs for statistical comparison') parser.add_argument('--weight_decay', action='store_true', help='Set to use SGDW (stochastic gradient with weight decay) as optimizer and use weight decay (unstable) otherwise adam is used.') arguments = vars(parser.parse_args()) if arguments['continue'] and arguments['replace']: print("Incompatible options to continue training and remove it to replace choose one or the other") sys.exit() return arguments def create_folders(arguments): """ Creates the folder structure needed to save logs and checkpoints depending on the @param arguments: run configuration @return: log_path where to save logs and models_path where to save the checkpoints. """ if arguments['weight_decay']: path = os.path.join(arguments['norm'], "ResNet" + str(arguments['ResNet'] * 6 + 2), "weight_decay", "epochs_" + str(arguments['epochs']), "batch_" + str(arguments['batch_size']), "run_" + str(arguments['run'])) else: path = os.path.join(arguments['norm'], "ResNet" + str(arguments['ResNet'] * 6 + 2), "no_weight_decay", "epochs_" + str(arguments['epochs']), "batch_" + str(arguments['batch_size']), "run_" + str(arguments['run'])) log_path = os.path.join("train_outputs/logs", path) models_path = os.path.join("train_outputs/checkpoints", path) # If paths exist and replacement is desired delete old files. To solve interference with tensorboard try to delete multiple times. Probably better solutions exist. for i in range(3): if os.path.exists(models_path) and os.path.exists(log_path) and arguments['replace']: print("Delete old models") try: shutil.rmtree(models_path) except OSError as e: print("Error: %s : %s" % (models_path, e.strerror)) sys.exit(1) try: shutil.rmtree(log_path) except OSError as e: print("Error: %s : %s" % (log_path, e.strerror)) sys.exit(1) time.sleep(1) # Create file structures try: os.makedirs(models_path) except OSError: if not arguments['continue']: print("Creation of the directory %s failed, if replacement is desired start script with argument --replace " % models_path) sys.exit(1) else: print("Successfully created the directory %s" % models_path) try: os.makedirs(log_path) except OSError: print("Creation of the directory %s failed" % log_path) if not arguments['continue']: print("Creation of the directory %s failed, if replacement is desired start script with argument --replace " % log_path) sys.exit(1) else: print("Successfully created the directory %s" % log_path) return log_path, models_path @tf.function def random_zoom(image): """ Data augmentation function, random zoom a part of an image and then resize to 32,32,3 @param image: input image @return: zoomed image. """ sz = tf.random.uniform((1,), 24, 32, dtype=tf.int32) # Get random state zoom = tf.image.random_crop(image, size=(sz[0], sz[0], 3)) # Crop image zoomed = tf.image.resize(zoom, (32, 32), method=tf.image.ResizeMethod.BICUBIC) # resize image to correct dimensions return zoomed @tf.function def normalize_img(image, label): """Normalizes images: `uint8` -> `float32`.""" return tf.image.convert_image_dtype(image, tf.float32), label # tf.cast(image, tf.float32) / 255.0, label # tf.image.convert_image_dtype(image, tf.float32), label def prepare_dataset(image, label): """ Apply data augmentation to @param image: input image @param label: corresponding label @return: augmented image and original label """ image = tf.image.random_flip_left_right(image) image = random_zoom(image) return image, label def get_data(arguments): """ Load training and validation data and apply normalization and optionally data augmentation @param arguments: batch size @return: training and validation sets """ batch_size = arguments['batch_size'] (train, test), ds_info = tfds.load('cifar10', split=['train', 'test'], as_supervised=True, with_info=True) # Load CIFAR-10 buffer_size = 10000 if arguments['epochs'] == 30: # For better results and since map is not really random (https://github.com/tensorflow/tensorflow/issues/35682#issuecomment-573777790) # the data is repeated 4 times and therefore the training epochs are reduced from 100 to 25, 30 was used because I mistyped and realized to late. train = train.map(normalize_img).repeat(4).map(prepare_dataset).batch(batch_size).shuffle(buffer_size).cache() else: train = train.map(normalize_img).batch(batch_size).shuffle(buffer_size).cache() # Normalize the validation/test set test = test.map(normalize_img).batch(batch_size) return train, test def get_test_data(arguments): """ Load and normalize only the test dataset @param arguments: batch size @return: test set """ batch_size = arguments['batch_size'] (train, test), ds_info = tfds.load('cifar10', split=['train', 'test'], as_supervised=True, with_info=True) test = test.map(normalize_img).batch(batch_size) return test def select_device(arguments): """ Sets if training should happen on CPU or GPU @param arguments: CPU or GPU @return: string for information print """ if arguments['cpu']: device = 'CPU' os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # Make GPU not visible for tensorflow else: device = 'GPU' # Turn memory growth om to run multiple scripts in parallel on the same GPU gpu_devices = tf.config.experimental.list_physical_devices('GPU') if len(gpu_devices) > 0: tf.config.experimental.set_memory_growth(gpu_devices[0], True) else: print("GPU selected but no GPUs available") sys.exit(1) return device
en
0.719954
Parse command line inputs @return: arguments dictionary containing parsed command line inputs Creates the folder structure needed to save logs and checkpoints depending on the @param arguments: run configuration @return: log_path where to save logs and models_path where to save the checkpoints. # If paths exist and replacement is desired delete old files. To solve interference with tensorboard try to delete multiple times. Probably better solutions exist. # Create file structures Data augmentation function, random zoom a part of an image and then resize to 32,32,3 @param image: input image @return: zoomed image. # Get random state # Crop image # resize image to correct dimensions Normalizes images: `uint8` -> `float32`. # tf.cast(image, tf.float32) / 255.0, label # tf.image.convert_image_dtype(image, tf.float32), label Apply data augmentation to @param image: input image @param label: corresponding label @return: augmented image and original label Load training and validation data and apply normalization and optionally data augmentation @param arguments: batch size @return: training and validation sets # Load CIFAR-10 # For better results and since map is not really random (https://github.com/tensorflow/tensorflow/issues/35682#issuecomment-573777790) # the data is repeated 4 times and therefore the training epochs are reduced from 100 to 25, 30 was used because I mistyped and realized to late. # Normalize the validation/test set Load and normalize only the test dataset @param arguments: batch size @return: test set Sets if training should happen on CPU or GPU @param arguments: CPU or GPU @return: string for information print # Make GPU not visible for tensorflow # Turn memory growth om to run multiple scripts in parallel on the same GPU
2.681754
3
public/assets/client_installer/payload/usr/local/munkireport/munkilib/FoundationPlist.py
poundbangbash/munkireport-php-1
4
6625144
# encoding: utf-8 # # Copyright 2009-2019 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """FoundationPlist.py -- a tool to generate and parse OS X .plist files. This is intended as a drop-in replacement for Python's included plistlib, with a few caveats: - readPlist() and writePlist() operate only on a filepath, not a file object. - there is no support for the deprecated functions: readPlistFromResource() writePlistToResource() - there is no support for the deprecated Plist class. The Property List (.plist) file format is a simple XML pickle supporting basic object types, like dictionaries, lists, numbers and strings. Usually the top level object is a dictionary. To write out a plist file, use the writePlist(rootObject, filepath) function. 'rootObject' is the top level object, 'filepath' is a filename. To parse a plist from a file, use the readPlist(filepath) function, with a file name. It returns the top level object (again, usually a dictionary). To work with plist data in strings, you can use readPlistFromString() and writePlistToString(). """ # PyLint cannot properly find names inside Cocoa libraries, so issues bogus # No name 'Foo' in module 'Bar' warnings. Disable them. # pylint: disable=E0611 from Foundation import NSData from Foundation import NSPropertyListSerialization from Foundation import NSPropertyListMutableContainers from Foundation import NSPropertyListXMLFormat_v1_0 # pylint: enable=E0611 # Disable PyLint complaining about 'invalid' camelCase names # pylint: disable=C0103 class FoundationPlistException(Exception): """Basic exception for plist errors""" pass class NSPropertyListSerializationException(FoundationPlistException): """Read/parse error for plists""" pass class NSPropertyListWriteException(FoundationPlistException): """Write error for plists""" pass def readPlist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). """ plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" errmsg = "%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject def readPlistFromString(data): '''Read a plist data from a string. Return the root object.''' try: plistData = buffer(data) except TypeError, err: raise NSPropertyListSerializationException(err) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: return dataObject def writePlist(dataObject, filepath): ''' Write 'rootObject' as a plist to filepath. ''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_format_errorDescription_( dataObject, NSPropertyListXMLFormat_v1_0, None)) if plistData is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: if plistData.writeToFile_atomically_(filepath, True): return else: raise NSPropertyListWriteException( "Failed to write plist data to %s" % filepath) def writePlistToString(rootObject): '''Return 'rootObject' as a plist-formatted string.''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_format_errorDescription_( rootObject, NSPropertyListXMLFormat_v1_0, None)) if plistData is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: return str(plistData) if __name__ == '__main__': print 'This is a library of support tools for the Munki Suite.'
# encoding: utf-8 # # Copyright 2009-2019 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """FoundationPlist.py -- a tool to generate and parse OS X .plist files. This is intended as a drop-in replacement for Python's included plistlib, with a few caveats: - readPlist() and writePlist() operate only on a filepath, not a file object. - there is no support for the deprecated functions: readPlistFromResource() writePlistToResource() - there is no support for the deprecated Plist class. The Property List (.plist) file format is a simple XML pickle supporting basic object types, like dictionaries, lists, numbers and strings. Usually the top level object is a dictionary. To write out a plist file, use the writePlist(rootObject, filepath) function. 'rootObject' is the top level object, 'filepath' is a filename. To parse a plist from a file, use the readPlist(filepath) function, with a file name. It returns the top level object (again, usually a dictionary). To work with plist data in strings, you can use readPlistFromString() and writePlistToString(). """ # PyLint cannot properly find names inside Cocoa libraries, so issues bogus # No name 'Foo' in module 'Bar' warnings. Disable them. # pylint: disable=E0611 from Foundation import NSData from Foundation import NSPropertyListSerialization from Foundation import NSPropertyListMutableContainers from Foundation import NSPropertyListXMLFormat_v1_0 # pylint: enable=E0611 # Disable PyLint complaining about 'invalid' camelCase names # pylint: disable=C0103 class FoundationPlistException(Exception): """Basic exception for plist errors""" pass class NSPropertyListSerializationException(FoundationPlistException): """Read/parse error for plists""" pass class NSPropertyListWriteException(FoundationPlistException): """Write error for plists""" pass def readPlist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). """ plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" errmsg = "%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject def readPlistFromString(data): '''Read a plist data from a string. Return the root object.''' try: plistData = buffer(data) except TypeError, err: raise NSPropertyListSerializationException(err) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: return dataObject def writePlist(dataObject, filepath): ''' Write 'rootObject' as a plist to filepath. ''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_format_errorDescription_( dataObject, NSPropertyListXMLFormat_v1_0, None)) if plistData is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: if plistData.writeToFile_atomically_(filepath, True): return else: raise NSPropertyListWriteException( "Failed to write plist data to %s" % filepath) def writePlistToString(rootObject): '''Return 'rootObject' as a plist-formatted string.''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_format_errorDescription_( rootObject, NSPropertyListXMLFormat_v1_0, None)) if plistData is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: return str(plistData) if __name__ == '__main__': print 'This is a library of support tools for the Munki Suite.'
en
0.809702
# encoding: utf-8 # # Copyright 2009-2019 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. FoundationPlist.py -- a tool to generate and parse OS X .plist files. This is intended as a drop-in replacement for Python's included plistlib, with a few caveats: - readPlist() and writePlist() operate only on a filepath, not a file object. - there is no support for the deprecated functions: readPlistFromResource() writePlistToResource() - there is no support for the deprecated Plist class. The Property List (.plist) file format is a simple XML pickle supporting basic object types, like dictionaries, lists, numbers and strings. Usually the top level object is a dictionary. To write out a plist file, use the writePlist(rootObject, filepath) function. 'rootObject' is the top level object, 'filepath' is a filename. To parse a plist from a file, use the readPlist(filepath) function, with a file name. It returns the top level object (again, usually a dictionary). To work with plist data in strings, you can use readPlistFromString() and writePlistToString(). # PyLint cannot properly find names inside Cocoa libraries, so issues bogus # No name 'Foo' in module 'Bar' warnings. Disable them. # pylint: disable=E0611 # pylint: enable=E0611 # Disable PyLint complaining about 'invalid' camelCase names # pylint: disable=C0103 Basic exception for plist errors Read/parse error for plists Write error for plists Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). Read a plist data from a string. Return the root object. Write 'rootObject' as a plist to filepath. Return 'rootObject' as a plist-formatted string.
2.121429
2
pytype/tests/test_super.py
isabella232/pytype
0
6625145
<gh_stars>0 """Tests for super().""" from pytype import file_utils from pytype.tests import test_base class SuperTest(test_base.TargetIndependentTest): """Tests for super().""" def test_set_attr(self): self.Check(""" class Foo(object): def foo(self, name, value): super(Foo, self).__setattr__(name, value) """) def test_str(self): self.Check(""" class Foo(object): def foo(self, name, value): super(Foo, self).__str__() """) def test_get(self): self.Check(""" class Foo(object): def foo(self, name, value): super(Foo, self).__get__(name) """) def test_inherited_get(self): self.Check(""" class Foo(object): def __get__(self, obj, objtype): return 42 class Bar(Foo): def __get__(self, obj, objtype): return super(Bar, self).__get__(obj, objtype) class Baz(object): x = Bar() Baz().x + 1 """) def test_inherited_get_grandparent(self): self.Check(""" class Foo(object): def __get__(self, obj, objtype): return 42 class Mid(Foo): pass class Bar(Mid): def __get__(self, obj, objtype): return super(Bar, self).__get__(obj, objtype) class Baz(object): x = Bar() Baz().x + 1 """) def test_inherited_get_multiple(self): self.Check(""" class Foo(object): def __get__(self, obj, objtype): return 42 class Quux(object): pass class Bar(Quux, Foo): def __get__(self, obj, objtype): return super(Bar, self).__get__(obj, objtype) class Baz(object): x = Bar() Baz().x + 1 """) def test_set(self): _, errors = self.InferWithErrors(""" class Foo(object): def foo(self, name, value): super(Foo, self).__set__(name, value) # attribute-error[e] """) self.assertErrorRegexes(errors, {"e": r"__set__.*super"}) def test_inherited_set(self): self.Check(""" class Foo(object): def __init__(self): self.foo = 1 def __set__(self, name, value): self.foo = value class Bar(Foo): def __set__(self, name, value): super(Bar, self).__set__(name, value) class Baz(): x = Bar() y = Baz() y.x = 42 """) def test_init(self): self.Check(""" class Foo(object): def foo(self, name, value): super(Foo, self).__init__() """) def test_getattr(self): self.Check(""" class Foo(object): def hello(self, name): getattr(super(Foo, self), name) """) def test_getattr_multiple_inheritance(self): self.Check(""" class X(object): pass class Y(object): bla = 123 class Foo(X, Y): def hello(self): getattr(super(Foo, self), "bla") """) def test_getattr_inheritance(self): self.Check(""" class Y(object): bla = 123 class Foo(Y): def hello(self): getattr(super(Foo, self), "bla") """) def test_isinstance(self): self.Check(""" class Y(object): pass class Foo(Y): def hello(self): return isinstance(super(Foo, self), Y) """) def test_call_super(self): _, errorlog = self.InferWithErrors(""" class Y(object): pass class Foo(Y): def hello(self): return super(Foo, self)() # not-callable[e] """) self.assertErrorRegexes(errorlog, {"e": r"super"}) def test_super_type(self): ty = self.Infer(""" class A(object): pass x = super(type, A) """) self.assertTypesMatchPytd(ty, """ class A(object): pass x = ... # type: super """) def test_super_with_ambiguous_base(self): with file_utils.Tempdir() as d: d.create_file("foo.pyi", """ class Grandparent(object): def f(self) -> int """) ty = self.Infer(""" import foo class Parent(foo.Grandparent): pass OtherParent = __any_object__ class Child(OtherParent, Parent): def f(self): return super(Parent, self).f() """, pythonpath=[d.path]) self.assertTypesMatchPytd(ty, """ from typing import Any foo = ... # type: module class Parent(foo.Grandparent): ... OtherParent = ... # type: Any class Child(Any, Parent): def f(self) -> int: ... """) def test_super_with_any(self): self.Check(""" super(__any_object__, __any_object__) """) def test_single_argument_super(self): _, errors = self.InferWithErrors(""" super(object) super(object()) # wrong-arg-types[e] """) self.assertErrorRegexes(errors, {"e": r"cls: type.*cls: object"}) def test_method_on_single_argument_super(self): ty, errors = self.InferWithErrors(""" sup = super(object) sup.foo # attribute-error[e1] sup.__new__(object) # wrong-arg-types[e2] v = sup.__new__(super) """) self.assertTypesMatchPytd(ty, """ sup = ... # type: super v = ... # type: super """) self.assertErrorRegexes(errors, {"e1": r"'foo' on super", "e2": r"Type\[super\].*Type\[object\]"}) def test_super_under_decorator(self): self.Check(""" def decorate(cls): return __any_object__ class Parent(object): def Hello(self): pass @decorate class Child(Parent): def Hello(self): return super(Child, self).Hello() """) def test_super_set_attr(self): _, errors = self.InferWithErrors(""" class Foo(object): def __init__(self): super(Foo, self).foo = 42 # not-writable[e] """) self.assertErrorRegexes(errors, {"e": r"super"}) def test_super_subclass_set_attr(self): _, errors = self.InferWithErrors(""" class Foo(object): pass class Bar(Foo): def __init__(self): super(Bar, self).foo = 42 # not-writable[e] """) self.assertErrorRegexes(errors, {"e": r"super"}) def test_super_nothing_set_attr(self): with file_utils.Tempdir() as d: d.create_file("foo.pyi", """ class Foo(nothing): ... """) _, errors = self.InferWithErrors(""" import foo class Bar(foo.Foo): def __init__(self): super(foo.Foo, self).foo = 42 # not-writable[e] """, pythonpath=[d.path]) self.assertErrorRegexes(errors, {"e": r"super"}) def test_super_any_set_attr(self): _, errors = self.InferWithErrors(""" class Foo(__any_object__): def __init__(self): super(Foo, self).foo = 42 # not-writable[e] """) self.assertErrorRegexes(errors, {"e": r"super"}) test_base.main(globals(), __name__ == "__main__")
"""Tests for super().""" from pytype import file_utils from pytype.tests import test_base class SuperTest(test_base.TargetIndependentTest): """Tests for super().""" def test_set_attr(self): self.Check(""" class Foo(object): def foo(self, name, value): super(Foo, self).__setattr__(name, value) """) def test_str(self): self.Check(""" class Foo(object): def foo(self, name, value): super(Foo, self).__str__() """) def test_get(self): self.Check(""" class Foo(object): def foo(self, name, value): super(Foo, self).__get__(name) """) def test_inherited_get(self): self.Check(""" class Foo(object): def __get__(self, obj, objtype): return 42 class Bar(Foo): def __get__(self, obj, objtype): return super(Bar, self).__get__(obj, objtype) class Baz(object): x = Bar() Baz().x + 1 """) def test_inherited_get_grandparent(self): self.Check(""" class Foo(object): def __get__(self, obj, objtype): return 42 class Mid(Foo): pass class Bar(Mid): def __get__(self, obj, objtype): return super(Bar, self).__get__(obj, objtype) class Baz(object): x = Bar() Baz().x + 1 """) def test_inherited_get_multiple(self): self.Check(""" class Foo(object): def __get__(self, obj, objtype): return 42 class Quux(object): pass class Bar(Quux, Foo): def __get__(self, obj, objtype): return super(Bar, self).__get__(obj, objtype) class Baz(object): x = Bar() Baz().x + 1 """) def test_set(self): _, errors = self.InferWithErrors(""" class Foo(object): def foo(self, name, value): super(Foo, self).__set__(name, value) # attribute-error[e] """) self.assertErrorRegexes(errors, {"e": r"__set__.*super"}) def test_inherited_set(self): self.Check(""" class Foo(object): def __init__(self): self.foo = 1 def __set__(self, name, value): self.foo = value class Bar(Foo): def __set__(self, name, value): super(Bar, self).__set__(name, value) class Baz(): x = Bar() y = Baz() y.x = 42 """) def test_init(self): self.Check(""" class Foo(object): def foo(self, name, value): super(Foo, self).__init__() """) def test_getattr(self): self.Check(""" class Foo(object): def hello(self, name): getattr(super(Foo, self), name) """) def test_getattr_multiple_inheritance(self): self.Check(""" class X(object): pass class Y(object): bla = 123 class Foo(X, Y): def hello(self): getattr(super(Foo, self), "bla") """) def test_getattr_inheritance(self): self.Check(""" class Y(object): bla = 123 class Foo(Y): def hello(self): getattr(super(Foo, self), "bla") """) def test_isinstance(self): self.Check(""" class Y(object): pass class Foo(Y): def hello(self): return isinstance(super(Foo, self), Y) """) def test_call_super(self): _, errorlog = self.InferWithErrors(""" class Y(object): pass class Foo(Y): def hello(self): return super(Foo, self)() # not-callable[e] """) self.assertErrorRegexes(errorlog, {"e": r"super"}) def test_super_type(self): ty = self.Infer(""" class A(object): pass x = super(type, A) """) self.assertTypesMatchPytd(ty, """ class A(object): pass x = ... # type: super """) def test_super_with_ambiguous_base(self): with file_utils.Tempdir() as d: d.create_file("foo.pyi", """ class Grandparent(object): def f(self) -> int """) ty = self.Infer(""" import foo class Parent(foo.Grandparent): pass OtherParent = __any_object__ class Child(OtherParent, Parent): def f(self): return super(Parent, self).f() """, pythonpath=[d.path]) self.assertTypesMatchPytd(ty, """ from typing import Any foo = ... # type: module class Parent(foo.Grandparent): ... OtherParent = ... # type: Any class Child(Any, Parent): def f(self) -> int: ... """) def test_super_with_any(self): self.Check(""" super(__any_object__, __any_object__) """) def test_single_argument_super(self): _, errors = self.InferWithErrors(""" super(object) super(object()) # wrong-arg-types[e] """) self.assertErrorRegexes(errors, {"e": r"cls: type.*cls: object"}) def test_method_on_single_argument_super(self): ty, errors = self.InferWithErrors(""" sup = super(object) sup.foo # attribute-error[e1] sup.__new__(object) # wrong-arg-types[e2] v = sup.__new__(super) """) self.assertTypesMatchPytd(ty, """ sup = ... # type: super v = ... # type: super """) self.assertErrorRegexes(errors, {"e1": r"'foo' on super", "e2": r"Type\[super\].*Type\[object\]"}) def test_super_under_decorator(self): self.Check(""" def decorate(cls): return __any_object__ class Parent(object): def Hello(self): pass @decorate class Child(Parent): def Hello(self): return super(Child, self).Hello() """) def test_super_set_attr(self): _, errors = self.InferWithErrors(""" class Foo(object): def __init__(self): super(Foo, self).foo = 42 # not-writable[e] """) self.assertErrorRegexes(errors, {"e": r"super"}) def test_super_subclass_set_attr(self): _, errors = self.InferWithErrors(""" class Foo(object): pass class Bar(Foo): def __init__(self): super(Bar, self).foo = 42 # not-writable[e] """) self.assertErrorRegexes(errors, {"e": r"super"}) def test_super_nothing_set_attr(self): with file_utils.Tempdir() as d: d.create_file("foo.pyi", """ class Foo(nothing): ... """) _, errors = self.InferWithErrors(""" import foo class Bar(foo.Foo): def __init__(self): super(foo.Foo, self).foo = 42 # not-writable[e] """, pythonpath=[d.path]) self.assertErrorRegexes(errors, {"e": r"super"}) def test_super_any_set_attr(self): _, errors = self.InferWithErrors(""" class Foo(__any_object__): def __init__(self): super(Foo, self).foo = 42 # not-writable[e] """) self.assertErrorRegexes(errors, {"e": r"super"}) test_base.main(globals(), __name__ == "__main__")
en
0.532182
Tests for super(). Tests for super(). class Foo(object): def foo(self, name, value): super(Foo, self).__setattr__(name, value) class Foo(object): def foo(self, name, value): super(Foo, self).__str__() class Foo(object): def foo(self, name, value): super(Foo, self).__get__(name) class Foo(object): def __get__(self, obj, objtype): return 42 class Bar(Foo): def __get__(self, obj, objtype): return super(Bar, self).__get__(obj, objtype) class Baz(object): x = Bar() Baz().x + 1 class Foo(object): def __get__(self, obj, objtype): return 42 class Mid(Foo): pass class Bar(Mid): def __get__(self, obj, objtype): return super(Bar, self).__get__(obj, objtype) class Baz(object): x = Bar() Baz().x + 1 class Foo(object): def __get__(self, obj, objtype): return 42 class Quux(object): pass class Bar(Quux, Foo): def __get__(self, obj, objtype): return super(Bar, self).__get__(obj, objtype) class Baz(object): x = Bar() Baz().x + 1 class Foo(object): def foo(self, name, value): super(Foo, self).__set__(name, value) # attribute-error[e] class Foo(object): def __init__(self): self.foo = 1 def __set__(self, name, value): self.foo = value class Bar(Foo): def __set__(self, name, value): super(Bar, self).__set__(name, value) class Baz(): x = Bar() y = Baz() y.x = 42 class Foo(object): def foo(self, name, value): super(Foo, self).__init__() class Foo(object): def hello(self, name): getattr(super(Foo, self), name) class X(object): pass class Y(object): bla = 123 class Foo(X, Y): def hello(self): getattr(super(Foo, self), "bla") class Y(object): bla = 123 class Foo(Y): def hello(self): getattr(super(Foo, self), "bla") class Y(object): pass class Foo(Y): def hello(self): return isinstance(super(Foo, self), Y) class Y(object): pass class Foo(Y): def hello(self): return super(Foo, self)() # not-callable[e] class A(object): pass x = super(type, A) class A(object): pass x = ... # type: super class Grandparent(object): def f(self) -> int import foo class Parent(foo.Grandparent): pass OtherParent = __any_object__ class Child(OtherParent, Parent): def f(self): return super(Parent, self).f() from typing import Any foo = ... # type: module class Parent(foo.Grandparent): ... OtherParent = ... # type: Any class Child(Any, Parent): def f(self) -> int: ... super(__any_object__, __any_object__) super(object) super(object()) # wrong-arg-types[e] sup = super(object) sup.foo # attribute-error[e1] sup.__new__(object) # wrong-arg-types[e2] v = sup.__new__(super) sup = ... # type: super v = ... # type: super def decorate(cls): return __any_object__ class Parent(object): def Hello(self): pass @decorate class Child(Parent): def Hello(self): return super(Child, self).Hello() class Foo(object): def __init__(self): super(Foo, self).foo = 42 # not-writable[e] class Foo(object): pass class Bar(Foo): def __init__(self): super(Bar, self).foo = 42 # not-writable[e] class Foo(nothing): ... import foo class Bar(foo.Foo): def __init__(self): super(foo.Foo, self).foo = 42 # not-writable[e] class Foo(__any_object__): def __init__(self): super(Foo, self).foo = 42 # not-writable[e]
2.858027
3
homeassistant/components/mysensors/sensor.py
sebcaps/core
2
6625146
<filename>homeassistant/components/mysensors/sensor.py<gh_stars>1-10 """Support for MySensors sensors.""" from __future__ import annotations from awesomeversion import AwesomeVersion from homeassistant.components import mysensors from homeassistant.components.sensor import DOMAIN, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONDUCTIVITY, DEGREE, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, ELECTRICAL_CURRENT_AMPERE, ELECTRICAL_VOLT_AMPERE, ENERGY_KILO_WATT_HOUR, FREQUENCY_HERTZ, LENGTH_METERS, LIGHT_LUX, MASS_KILOGRAMS, PERCENTAGE, POWER_WATT, TEMP_CELSIUS, TEMP_FAHRENHEIT, VOLT, VOLUME_CUBIC_METERS, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import MYSENSORS_DISCOVERY, DiscoveryInfo from .helpers import on_unload SENSORS: dict[str, list[str | None] | dict[str, list[str | None]]] = { "V_TEMP": [None, None, DEVICE_CLASS_TEMPERATURE], "V_HUM": [PERCENTAGE, "mdi:water-percent", DEVICE_CLASS_HUMIDITY], "V_DIMMER": [PERCENTAGE, "mdi:percent", None], "V_PERCENTAGE": [PERCENTAGE, "mdi:percent", None], "V_PRESSURE": [None, "mdi:gauge", None], "V_FORECAST": [None, "mdi:weather-partly-cloudy", None], "V_RAIN": [None, "mdi:weather-rainy", None], "V_RAINRATE": [None, "mdi:weather-rainy", None], "V_WIND": [None, "mdi:weather-windy", None], "V_GUST": [None, "mdi:weather-windy", None], "V_DIRECTION": [DEGREE, "mdi:compass", None], "V_WEIGHT": [MASS_KILOGRAMS, "mdi:weight-kilogram", None], "V_DISTANCE": [LENGTH_METERS, "mdi:ruler", None], "V_IMPEDANCE": ["ohm", None, None], "V_WATT": [POWER_WATT, None, None], "V_KWH": [ENERGY_KILO_WATT_HOUR, None, None], "V_LIGHT_LEVEL": [PERCENTAGE, "mdi:white-balance-sunny", None], "V_FLOW": [LENGTH_METERS, "mdi:gauge", None], "V_VOLUME": [f"{VOLUME_CUBIC_METERS}", None, None], "V_LEVEL": { "S_SOUND": ["dB", "mdi:volume-high", None], "S_VIBRATION": [FREQUENCY_HERTZ, None, None], "S_LIGHT_LEVEL": [LIGHT_LUX, "mdi:white-balance-sunny", None], }, "V_VOLTAGE": [VOLT, "mdi:flash", None], "V_CURRENT": [ELECTRICAL_CURRENT_AMPERE, "mdi:flash-auto", None], "V_PH": ["pH", None, None], "V_ORP": ["mV", None, None], "V_EC": [CONDUCTIVITY, None, None], "V_VAR": ["var", None, None], "V_VA": [ELECTRICAL_VOLT_AMPERE, None, None], } async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up this platform for a specific ConfigEntry(==Gateway).""" async def async_discover(discovery_info: DiscoveryInfo) -> None: """Discover and add a MySensors sensor.""" mysensors.setup_mysensors_platform( hass, DOMAIN, discovery_info, MySensorsSensor, async_add_entities=async_add_entities, ) on_unload( hass, config_entry.entry_id, async_dispatcher_connect( hass, MYSENSORS_DISCOVERY.format(config_entry.entry_id, DOMAIN), async_discover, ), ) class MySensorsSensor(mysensors.device.MySensorsEntity, SensorEntity): """Representation of a MySensors Sensor child node.""" @property def force_update(self) -> bool: """Return True if state updates should be forced. If True, a state change will be triggered anytime the state property is updated, not just when the value changes. """ return True @property def state(self) -> str | None: """Return the state of this entity.""" return self._values.get(self.value_type) @property def device_class(self) -> str | None: """Return the device class of this entity.""" icon = self._get_sensor_type()[2] return icon @property def icon(self) -> str | None: """Return the icon to use in the frontend, if any.""" icon = self._get_sensor_type()[1] return icon @property def unit_of_measurement(self) -> str | None: """Return the unit of measurement of this entity.""" set_req = self.gateway.const.SetReq if ( AwesomeVersion(self.gateway.protocol_version) >= AwesomeVersion("1.5") and set_req.V_UNIT_PREFIX in self._values ): custom_unit: str = self._values[set_req.V_UNIT_PREFIX] return custom_unit if set_req(self.value_type) == set_req.V_TEMP: if self.hass.config.units.is_metric: return TEMP_CELSIUS return TEMP_FAHRENHEIT unit = self._get_sensor_type()[0] return unit def _get_sensor_type(self) -> list[str | None]: """Return list with unit and icon of sensor type.""" pres = self.gateway.const.Presentation set_req = self.gateway.const.SetReq _sensor_type = SENSORS.get(set_req(self.value_type).name, [None, None, None]) if isinstance(_sensor_type, dict): sensor_type = _sensor_type.get( pres(self.child_type).name, [None, None, None] ) else: sensor_type = _sensor_type return sensor_type
<filename>homeassistant/components/mysensors/sensor.py<gh_stars>1-10 """Support for MySensors sensors.""" from __future__ import annotations from awesomeversion import AwesomeVersion from homeassistant.components import mysensors from homeassistant.components.sensor import DOMAIN, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONDUCTIVITY, DEGREE, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, ELECTRICAL_CURRENT_AMPERE, ELECTRICAL_VOLT_AMPERE, ENERGY_KILO_WATT_HOUR, FREQUENCY_HERTZ, LENGTH_METERS, LIGHT_LUX, MASS_KILOGRAMS, PERCENTAGE, POWER_WATT, TEMP_CELSIUS, TEMP_FAHRENHEIT, VOLT, VOLUME_CUBIC_METERS, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import MYSENSORS_DISCOVERY, DiscoveryInfo from .helpers import on_unload SENSORS: dict[str, list[str | None] | dict[str, list[str | None]]] = { "V_TEMP": [None, None, DEVICE_CLASS_TEMPERATURE], "V_HUM": [PERCENTAGE, "mdi:water-percent", DEVICE_CLASS_HUMIDITY], "V_DIMMER": [PERCENTAGE, "mdi:percent", None], "V_PERCENTAGE": [PERCENTAGE, "mdi:percent", None], "V_PRESSURE": [None, "mdi:gauge", None], "V_FORECAST": [None, "mdi:weather-partly-cloudy", None], "V_RAIN": [None, "mdi:weather-rainy", None], "V_RAINRATE": [None, "mdi:weather-rainy", None], "V_WIND": [None, "mdi:weather-windy", None], "V_GUST": [None, "mdi:weather-windy", None], "V_DIRECTION": [DEGREE, "mdi:compass", None], "V_WEIGHT": [MASS_KILOGRAMS, "mdi:weight-kilogram", None], "V_DISTANCE": [LENGTH_METERS, "mdi:ruler", None], "V_IMPEDANCE": ["ohm", None, None], "V_WATT": [POWER_WATT, None, None], "V_KWH": [ENERGY_KILO_WATT_HOUR, None, None], "V_LIGHT_LEVEL": [PERCENTAGE, "mdi:white-balance-sunny", None], "V_FLOW": [LENGTH_METERS, "mdi:gauge", None], "V_VOLUME": [f"{VOLUME_CUBIC_METERS}", None, None], "V_LEVEL": { "S_SOUND": ["dB", "mdi:volume-high", None], "S_VIBRATION": [FREQUENCY_HERTZ, None, None], "S_LIGHT_LEVEL": [LIGHT_LUX, "mdi:white-balance-sunny", None], }, "V_VOLTAGE": [VOLT, "mdi:flash", None], "V_CURRENT": [ELECTRICAL_CURRENT_AMPERE, "mdi:flash-auto", None], "V_PH": ["pH", None, None], "V_ORP": ["mV", None, None], "V_EC": [CONDUCTIVITY, None, None], "V_VAR": ["var", None, None], "V_VA": [ELECTRICAL_VOLT_AMPERE, None, None], } async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up this platform for a specific ConfigEntry(==Gateway).""" async def async_discover(discovery_info: DiscoveryInfo) -> None: """Discover and add a MySensors sensor.""" mysensors.setup_mysensors_platform( hass, DOMAIN, discovery_info, MySensorsSensor, async_add_entities=async_add_entities, ) on_unload( hass, config_entry.entry_id, async_dispatcher_connect( hass, MYSENSORS_DISCOVERY.format(config_entry.entry_id, DOMAIN), async_discover, ), ) class MySensorsSensor(mysensors.device.MySensorsEntity, SensorEntity): """Representation of a MySensors Sensor child node.""" @property def force_update(self) -> bool: """Return True if state updates should be forced. If True, a state change will be triggered anytime the state property is updated, not just when the value changes. """ return True @property def state(self) -> str | None: """Return the state of this entity.""" return self._values.get(self.value_type) @property def device_class(self) -> str | None: """Return the device class of this entity.""" icon = self._get_sensor_type()[2] return icon @property def icon(self) -> str | None: """Return the icon to use in the frontend, if any.""" icon = self._get_sensor_type()[1] return icon @property def unit_of_measurement(self) -> str | None: """Return the unit of measurement of this entity.""" set_req = self.gateway.const.SetReq if ( AwesomeVersion(self.gateway.protocol_version) >= AwesomeVersion("1.5") and set_req.V_UNIT_PREFIX in self._values ): custom_unit: str = self._values[set_req.V_UNIT_PREFIX] return custom_unit if set_req(self.value_type) == set_req.V_TEMP: if self.hass.config.units.is_metric: return TEMP_CELSIUS return TEMP_FAHRENHEIT unit = self._get_sensor_type()[0] return unit def _get_sensor_type(self) -> list[str | None]: """Return list with unit and icon of sensor type.""" pres = self.gateway.const.Presentation set_req = self.gateway.const.SetReq _sensor_type = SENSORS.get(set_req(self.value_type).name, [None, None, None]) if isinstance(_sensor_type, dict): sensor_type = _sensor_type.get( pres(self.child_type).name, [None, None, None] ) else: sensor_type = _sensor_type return sensor_type
en
0.74691
Support for MySensors sensors. Set up this platform for a specific ConfigEntry(==Gateway). Discover and add a MySensors sensor. Representation of a MySensors Sensor child node. Return True if state updates should be forced. If True, a state change will be triggered anytime the state property is updated, not just when the value changes. Return the state of this entity. Return the device class of this entity. Return the icon to use in the frontend, if any. Return the unit of measurement of this entity. Return list with unit and icon of sensor type.
1.739944
2
wiki/web/util/database.py
WillStOnge/CSC-440-Project
0
6625147
from flask import current_app from .singleton import Singleton import pyodbc class Database(Singleton): def __init__(self): """ Initializes an instance of the Database with a connection to the database. """ self._conn = pyodbc.connect(current_app.config['CONNECTION_STRING']) def execute_query_for_result(self, query) -> list: """ Executes a query where a result is expected (SELECT statements). :param query: The query to be executed. :return: A dictionary of the results from the query. None if an error occured. """ try: cursor = self._conn.execute(query) columns = [column[0] for column in cursor.description] records = [dict(zip(columns, row)) for row in cursor.fetchall()] return records except: return None def execute_query(self, query) -> bool: """ Executes a query where no result is expected (INSERT, UPDATE, and DELETE statements). :param query: The query to be executed. :return: True if the query completed without errors, false otherwise. """ try: self._conn.execute(query).commit() return True except: return False
from flask import current_app from .singleton import Singleton import pyodbc class Database(Singleton): def __init__(self): """ Initializes an instance of the Database with a connection to the database. """ self._conn = pyodbc.connect(current_app.config['CONNECTION_STRING']) def execute_query_for_result(self, query) -> list: """ Executes a query where a result is expected (SELECT statements). :param query: The query to be executed. :return: A dictionary of the results from the query. None if an error occured. """ try: cursor = self._conn.execute(query) columns = [column[0] for column in cursor.description] records = [dict(zip(columns, row)) for row in cursor.fetchall()] return records except: return None def execute_query(self, query) -> bool: """ Executes a query where no result is expected (INSERT, UPDATE, and DELETE statements). :param query: The query to be executed. :return: True if the query completed without errors, false otherwise. """ try: self._conn.execute(query).commit() return True except: return False
en
0.82084
Initializes an instance of the Database with a connection to the database. Executes a query where a result is expected (SELECT statements). :param query: The query to be executed. :return: A dictionary of the results from the query. None if an error occured. Executes a query where no result is expected (INSERT, UPDATE, and DELETE statements). :param query: The query to be executed. :return: True if the query completed without errors, false otherwise.
2.959835
3
start.py
SINTEF-SE/PySSMic
0
6625148
from index import app import webbrowser webbrowser.open("127.0.0.1:8050") app.run_server()
from index import app import webbrowser webbrowser.open("127.0.0.1:8050") app.run_server()
none
1
1.935531
2
support/mesos-style.py
maselvaraj/mesos
0
6625149
<reponame>maselvaraj/mesos<gh_stars>0 #!/usr/bin/env python ''' Runs checks for mesos style. ''' import os import re import string import subprocess import sys # Root source paths (will be traversed recursively). source_dirs = ['src', 'include', os.path.join('3rdparty', 'libprocess')] # Add file paths and patterns which should not be checked # This should include 3rdparty libraries, includes and machine generated # source. exclude_files = '(protobuf\-2\.4\.1|gmock\-1\.6\.0|glog\-0\.3\.3|boost\-1\.53\.0|libev\-4\.15|java/jni|\.pb\.cc|\.pb\.h|\.md)' source_files = '\.(cpp|hpp|cc|h)$' def find_candidates(root_dir): exclude_file_regex = re.compile(exclude_files) source_criteria_regex = re.compile(source_files) for root, dirs, files in os.walk(root_dir): for name in files: path = os.path.join(root, name) if exclude_file_regex.search(path) is not None: continue if source_criteria_regex.search(name) is not None: yield path def run_lint(source_paths): ''' Runs cpplint over given files. http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py ''' # See cpplint.py for full list of rules. active_rules = [ 'build/class', 'build/deprecated', 'build/endif_comment', 'readability/todo', 'readability/namespace', 'runtime/vlog', 'whitespace/blank_line', 'whitespace/comma', 'whitespace/end_of_line', 'whitespace/ending_newline', 'whitespace/forcolon', 'whitespace/indent', 'whitespace/line_length', 'whitespace/operators', 'whitespace/semicolon', 'whitespace/tab', 'whitespace/comments', 'whitespace/todo'] rules_filter = '--filter=-,+' + ',+'.join(active_rules) p = subprocess.Popen( ['python', 'support/cpplint.py', rules_filter] + source_paths, stderr=subprocess.PIPE, close_fds=True) # Lines are stored and filtered, only showing found errors instead # of e.g., 'Done processing XXX.' which tends to be dominant output. for line in p.stderr: if re.match('^(Done processing |Total errors found: )', line): continue sys.stderr.write(line) p.wait() return p.returncode def check_license_header(source_paths): ''' Checks the license headers of the given files. ''' error_count = 0 for path in source_paths: with open(path) as source_file: head = source_file.readline() # Check that opening comment has correct style. # TODO(bbannier) We allow `Copyright` for currently deviating files. # This should be removed one we have a uniform license format. if not re.match(r'^\/\/ [Licensed|Copyright]', head): sys.stderr.write( "{path}:1: A license header should appear on the file's " "first line starting with '// Licensed'.: {head}".\ format(path=path, head=head)) error_count += 1 return error_count def check_encoding(source_paths): ''' Checks for encoding errors in the given files. Source code files must contain only printable ascii characters. This excludes the extended ascii characters 128-255. http://www.asciitable.com/ ''' error_count = 0 for path in source_paths: with open(path) as source_file: for line_number, line in enumerate(source_file): # If we find an error, add 1 to both the character and # the line offset to give them 1-based indexing # instead of 0 (as is common in most editors). char_errors = [offset for offset, char in enumerate(line) if char not in string.printable] if char_errors: sys.stderr.write( "{path}:{line_number}: Non-printable characters" " found at [{offsets}]: \"{line}\"\n".format( path=path, line_number=line_number + 1, offsets=', '.join([str(offset + 1) for offset in char_errors]), line=line.rstrip())) error_count += 1 return error_count if __name__ == '__main__': # Verify that source roots are accessible from current working directory. # A common error could be to call the style checker from other # (possibly nested) paths. for source_dir in source_dirs: if not os.path.exists(source_dir): print "Could not find '{dir}'".format(dir=source_dir) print 'Please run from the root of the mesos source directory' exit(1) # Add all source file candidates to candidates list. candidates = [] for source_dir in source_dirs: for candidate in find_candidates(source_dir): candidates.append(candidate) # If file paths are specified, check all file paths that are # candidates; else check all candidates. file_paths = sys.argv[1:] if len(sys.argv) > 1 else candidates # Compute the set intersect of the input file paths and candidates. # This represents the reduced set of candidates to run lint on. candidates_set = set(candidates) clean_file_paths_set = set(map(lambda x: x.rstrip(), file_paths)) filtered_candidates_set = clean_file_paths_set.intersection( candidates_set) if filtered_candidates_set: print 'Checking {num_files} files'.\ format(num_files=len(filtered_candidates_set)) license_errors = check_license_header(filtered_candidates_set) encoding_errors = check_encoding(list(filtered_candidates_set)) lint_errors = run_lint(list(filtered_candidates_set)) total_errors = license_errors + encoding_errors + lint_errors sys.stderr.write('Total errors found: {num_errors}\n'.\ format(num_errors=total_errors)) sys.exit(total_errors) else: print "No files to lint\n" sys.exit(0)
#!/usr/bin/env python ''' Runs checks for mesos style. ''' import os import re import string import subprocess import sys # Root source paths (will be traversed recursively). source_dirs = ['src', 'include', os.path.join('3rdparty', 'libprocess')] # Add file paths and patterns which should not be checked # This should include 3rdparty libraries, includes and machine generated # source. exclude_files = '(protobuf\-2\.4\.1|gmock\-1\.6\.0|glog\-0\.3\.3|boost\-1\.53\.0|libev\-4\.15|java/jni|\.pb\.cc|\.pb\.h|\.md)' source_files = '\.(cpp|hpp|cc|h)$' def find_candidates(root_dir): exclude_file_regex = re.compile(exclude_files) source_criteria_regex = re.compile(source_files) for root, dirs, files in os.walk(root_dir): for name in files: path = os.path.join(root, name) if exclude_file_regex.search(path) is not None: continue if source_criteria_regex.search(name) is not None: yield path def run_lint(source_paths): ''' Runs cpplint over given files. http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py ''' # See cpplint.py for full list of rules. active_rules = [ 'build/class', 'build/deprecated', 'build/endif_comment', 'readability/todo', 'readability/namespace', 'runtime/vlog', 'whitespace/blank_line', 'whitespace/comma', 'whitespace/end_of_line', 'whitespace/ending_newline', 'whitespace/forcolon', 'whitespace/indent', 'whitespace/line_length', 'whitespace/operators', 'whitespace/semicolon', 'whitespace/tab', 'whitespace/comments', 'whitespace/todo'] rules_filter = '--filter=-,+' + ',+'.join(active_rules) p = subprocess.Popen( ['python', 'support/cpplint.py', rules_filter] + source_paths, stderr=subprocess.PIPE, close_fds=True) # Lines are stored and filtered, only showing found errors instead # of e.g., 'Done processing XXX.' which tends to be dominant output. for line in p.stderr: if re.match('^(Done processing |Total errors found: )', line): continue sys.stderr.write(line) p.wait() return p.returncode def check_license_header(source_paths): ''' Checks the license headers of the given files. ''' error_count = 0 for path in source_paths: with open(path) as source_file: head = source_file.readline() # Check that opening comment has correct style. # TODO(bbannier) We allow `Copyright` for currently deviating files. # This should be removed one we have a uniform license format. if not re.match(r'^\/\/ [Licensed|Copyright]', head): sys.stderr.write( "{path}:1: A license header should appear on the file's " "first line starting with '// Licensed'.: {head}".\ format(path=path, head=head)) error_count += 1 return error_count def check_encoding(source_paths): ''' Checks for encoding errors in the given files. Source code files must contain only printable ascii characters. This excludes the extended ascii characters 128-255. http://www.asciitable.com/ ''' error_count = 0 for path in source_paths: with open(path) as source_file: for line_number, line in enumerate(source_file): # If we find an error, add 1 to both the character and # the line offset to give them 1-based indexing # instead of 0 (as is common in most editors). char_errors = [offset for offset, char in enumerate(line) if char not in string.printable] if char_errors: sys.stderr.write( "{path}:{line_number}: Non-printable characters" " found at [{offsets}]: \"{line}\"\n".format( path=path, line_number=line_number + 1, offsets=', '.join([str(offset + 1) for offset in char_errors]), line=line.rstrip())) error_count += 1 return error_count if __name__ == '__main__': # Verify that source roots are accessible from current working directory. # A common error could be to call the style checker from other # (possibly nested) paths. for source_dir in source_dirs: if not os.path.exists(source_dir): print "Could not find '{dir}'".format(dir=source_dir) print 'Please run from the root of the mesos source directory' exit(1) # Add all source file candidates to candidates list. candidates = [] for source_dir in source_dirs: for candidate in find_candidates(source_dir): candidates.append(candidate) # If file paths are specified, check all file paths that are # candidates; else check all candidates. file_paths = sys.argv[1:] if len(sys.argv) > 1 else candidates # Compute the set intersect of the input file paths and candidates. # This represents the reduced set of candidates to run lint on. candidates_set = set(candidates) clean_file_paths_set = set(map(lambda x: x.rstrip(), file_paths)) filtered_candidates_set = clean_file_paths_set.intersection( candidates_set) if filtered_candidates_set: print 'Checking {num_files} files'.\ format(num_files=len(filtered_candidates_set)) license_errors = check_license_header(filtered_candidates_set) encoding_errors = check_encoding(list(filtered_candidates_set)) lint_errors = run_lint(list(filtered_candidates_set)) total_errors = license_errors + encoding_errors + lint_errors sys.stderr.write('Total errors found: {num_errors}\n'.\ format(num_errors=total_errors)) sys.exit(total_errors) else: print "No files to lint\n" sys.exit(0)
en
0.853604
#!/usr/bin/env python Runs checks for mesos style. # Root source paths (will be traversed recursively). # Add file paths and patterns which should not be checked # This should include 3rdparty libraries, includes and machine generated # source. Runs cpplint over given files. http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py # See cpplint.py for full list of rules. # Lines are stored and filtered, only showing found errors instead # of e.g., 'Done processing XXX.' which tends to be dominant output. Checks the license headers of the given files. # Check that opening comment has correct style. # TODO(bbannier) We allow `Copyright` for currently deviating files. # This should be removed one we have a uniform license format. Checks for encoding errors in the given files. Source code files must contain only printable ascii characters. This excludes the extended ascii characters 128-255. http://www.asciitable.com/ # If we find an error, add 1 to both the character and # the line offset to give them 1-based indexing # instead of 0 (as is common in most editors). # Verify that source roots are accessible from current working directory. # A common error could be to call the style checker from other # (possibly nested) paths. # Add all source file candidates to candidates list. # If file paths are specified, check all file paths that are # candidates; else check all candidates. # Compute the set intersect of the input file paths and candidates. # This represents the reduced set of candidates to run lint on.
2.211801
2
src/rubrix/client/sdk/token_classification/api.py
davidkartchner/rubrix
1
6625150
<reponame>davidkartchner/rubrix # coding=utf-8 # Copyright 2021-present, the Recognai S.L. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List, Optional, Union import httpx from rubrix.client.sdk.client import AuthenticatedClient from rubrix.client.sdk.commons.api import build_bulk_response, build_data_response from rubrix.client.sdk.commons.models import ( BulkResponse, ErrorMessage, HTTPValidationError, Response, ) from rubrix.client.sdk.token_classification.models import ( TokenClassificationBulkData, TokenClassificationQuery, TokenClassificationRecord, ) def bulk( client: AuthenticatedClient, name: str, json_body: TokenClassificationBulkData, ) -> Response[Union[BulkResponse, ErrorMessage, HTTPValidationError]]: url = "{}/api/datasets/{name}/TokenClassification:bulk".format( client.base_url, name=name ) response = httpx.post( url=url, headers=client.get_headers(), cookies=client.get_cookies(), timeout=client.get_timeout(), json=json_body.dict(by_alias=True), ) return build_bulk_response(response, name=name, body=json_body) def data( client: AuthenticatedClient, name: str, request: Optional[TokenClassificationQuery] = None, limit: Optional[int] = None, ) -> Response[ Union[List[TokenClassificationRecord], HTTPValidationError, ErrorMessage] ]: url = "{}/api/datasets/{name}/TokenClassification/data".format( client.base_url, name=name ) with httpx.stream( method="POST", url=url, headers=client.get_headers(), cookies=client.get_cookies(), timeout=None, params={"limit": limit} if limit else None, json=request.dict() if request else {}, ) as response: return build_data_response( response=response, data_type=TokenClassificationRecord )
# coding=utf-8 # Copyright 2021-present, the Recognai S.L. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List, Optional, Union import httpx from rubrix.client.sdk.client import AuthenticatedClient from rubrix.client.sdk.commons.api import build_bulk_response, build_data_response from rubrix.client.sdk.commons.models import ( BulkResponse, ErrorMessage, HTTPValidationError, Response, ) from rubrix.client.sdk.token_classification.models import ( TokenClassificationBulkData, TokenClassificationQuery, TokenClassificationRecord, ) def bulk( client: AuthenticatedClient, name: str, json_body: TokenClassificationBulkData, ) -> Response[Union[BulkResponse, ErrorMessage, HTTPValidationError]]: url = "{}/api/datasets/{name}/TokenClassification:bulk".format( client.base_url, name=name ) response = httpx.post( url=url, headers=client.get_headers(), cookies=client.get_cookies(), timeout=client.get_timeout(), json=json_body.dict(by_alias=True), ) return build_bulk_response(response, name=name, body=json_body) def data( client: AuthenticatedClient, name: str, request: Optional[TokenClassificationQuery] = None, limit: Optional[int] = None, ) -> Response[ Union[List[TokenClassificationRecord], HTTPValidationError, ErrorMessage] ]: url = "{}/api/datasets/{name}/TokenClassification/data".format( client.base_url, name=name ) with httpx.stream( method="POST", url=url, headers=client.get_headers(), cookies=client.get_cookies(), timeout=None, params={"limit": limit} if limit else None, json=request.dict() if request else {}, ) as response: return build_data_response( response=response, data_type=TokenClassificationRecord )
en
0.854778
# coding=utf-8 # Copyright 2021-present, the Recognai S.L. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
1.820948
2