import os
import numpy as np
import cv2
import torch
import multiprocessing as mp
from torch.nn import functional as F
from pycocotools.coco import COCO
import json

COLORS = np.array([[255,255,255], [0,255,255],[255,0,255],[255,255,0],[255,125,50],[125,255,50],[50,255,125],[255,50,125],[125,50,255],\
        [50, 125, 255]])

def readFlow(name):
    f = open(name, 'rb')

    header = f.read(4)
    if header.decode("utf-8") != 'PIEH':
        raise Exception('Flow file header does not contain PIEH')

    width = np.fromfile(f, np.int32, 1).squeeze()
    height = np.fromfile(f, np.int32, 1).squeeze()

    flow = np.fromfile(f, np.float32, width * height * 2).reshape((height, width, 2))

    return flow.astype(np.float32)

def flow_warp(x, flo):
    """
    inverse warp an image/tensor (im2) back to im1, according to the optical flow
    x: [B, C, H, W] (im2)
    flo: [B, 2, H, W] flow
    """
    B, C, H, W = x.size()
    # mesh grid
    xx = torch.arange(0, W).view(1, -1).repeat(H, 1).to(x.device)
    yy = torch.arange(0, H).view(-1, 1).repeat(1, W).to(x.device)
    xx = xx.view(1, 1, H, W).repeat(B, 1, 1, 1)
    yy = yy.view(1, 1, H, W).repeat(B, 1, 1, 1)
    grid = torch.cat((xx, yy), 1).float()

    vgrid = grid + flo

    # scale grid to [-1,1]
    vgrid = torch.stack([
        2.0 * vgrid[:, 0, :, :] / max(W - 1, 1) - 1.0,
        2.0 * vgrid[:, 1, :, :] / max(H - 1, 1) - 1.0
    ],
                        dim=1)

    vgrid = vgrid.permute(0, 2, 3, 1)
    output = F.grid_sample(x, vgrid, mode='nearest', padding_mode='border')

    return output.squeeze().numpy().astype(np.uint8)

def instance_warp(fn_list):
    flow_fn, img_name_sur, img_name_des = fn_list
    flow = cv2.imread(flow_fn, -1)[:, :, ::-1].astype(np.float)
    flow = (flow[:, :, :2] - 2.0 ** 15) / 64.0
    flow = torch.Tensor(flow).permute(2, 0, 1).contiguous().unsqueeze(dim=0)
    img_id = reverse_img_dir[img_name_sur]
    img_id_des = reverse_img_dir[img_name_des]
    annIds = coco.getAnnIds(imgIds=[img_id], iscrowd=None)
    annIds_des = coco.getAnnIds(imgIds=[img_id_des], iscrowd=None)
    annos = coco.loadAnns(annIds)
    annos_des = coco.loadAnns(annIds_des)
    instance_ids = [anno['instance_id'] for anno in annos]
    instance_ids_des = [anno['instance_id'] for anno in annos_des]
    sur_color_map = np.zeros((720, 1280, 3))
    tar_color_map = np.zeros((720, 1280, 3))

    color_id = 0
    for anno, instance_id in zip(annos, instance_ids):
        if instance_id not in instance_ids_des:
            continue

        idx = instance_ids_des.index(instance_id)
        anno_des = annos_des[idx]
        mask = coco.annToMask(anno)
        mask_des = coco.annToMask(anno_des)
        mask = torch.Tensor(mask).unsqueeze(dim=0).unsqueeze(dim=1)
        # print(flow.shape)
        new_mask = flow_warp(mask, flow)
        mask = mask.squeeze().numpy().astype(np.uint8)
        print(mask.shape, new_mask.shape)
        sur_color_map[np.where(mask==1)] = COLORS[color_id % len(COLORS)]
        tar_color_map[np.where(new_mask==1)] = COLORS[color_id % len(COLORS)]
        color_id += 1

    sur_save_pth = os.path.join(out_sur_file, img_name_sur[:17], img_name_sur)
    tar_save_pth = os.path.join(out_tar_file, img_name_des[:17], img_name_des)
    if not os.path.exists(os.path.join(out_sur_file, img_name_sur[:17])):
        os.makedirs(os.path.join(out_sur_file, img_name_sur[:17]))

    if not os.path.exists(os.path.join(out_tar_file, img_name_des[:17])):
        os.makedirs(os.path.join(out_tar_file, img_name_des[:17]))

    ok = cv2.imwrite(sur_save_pth, sur_color_map)
    print(ok)
    ok = cv2.imwrite(tar_save_pth, tar_color_map)
    print(ok)

def main():
    global reverse_img_dir
    global coco
    global out_sur_file
    global out_tar_file
    # global anno_to_instance

    fl_base = '/shared/xudongliu/code/semi-flow/hd3/predictions/fc_pre_Sintel_seg_track_val_my/vec'
    json_fn = '/data5/bdd100k/labels/seg_track/seg_track_val_new.json'
    list_file = '/shared/xudongliu/code/pytorch-liteflownet/lists/seg_track_val_new.txt'
    out_sur_file = '/shared/xudongliu/code/semi-flow/hd3/color_mask/frame_1_my'
    out_tar_file = '/shared/xudongliu/code/semi-flow/hd3/color_mask/frame_0_my'
    coco = COCO(json_fn)

    with open(json_fn) as f:
        sur_dir = json.load(f)

    img_dir_list = sur_dir['images']

    reverse_img_dir = {img_dir['file_name']:img_dir['id'] for img_dir in img_dir_list}
    # anno_to_instance = { for anno_dir in anno_dir_list}

    args = []

    with open(list_file) as f:
        pair_list = f.readlines()

    for i, line in enumerate(pair_list):
        flow_name = os.path.join(fl_base, line.strip(' \n').split(' ')[0].split('.')[0] + '.png')
        img_name_sur = os.path.split(line.strip(' \n').split(' ')[1])[-1]
        img_name_des = os.path.split(line.strip(' \n').split(' ')[0])[-1]
        args.append([flow_name, img_name_sur, img_name_des])

    pool = mp.Pool(16)
    pool.map(instance_warp, args)

if __name__ == "__main__":
    main()


# import sys when runing from the batch code

import sys

import os

sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)),"../../../.."))

import pandas as pd

import numpy as np

from datetime import datetime,timedelta

# visualisation packages

import math

import matplotlib.dates as mdates

import matplotlib.pyplot as plt

from matplotlib.backends.backend_pdf import PdfPages

import collections

from matplotlib.font_manager import FontProperties

import current_version.production_ver.Analytics.series_utils as s_util

from current_version.production_ver.Analytics.scoring_methods import scoring_method_collection as smc

import current_version.production_ver.Analytics.abstract_sig as abs_sig

import time

from current_version.production_ver.backtesting_utils.cache import cache_response, clear_cache

from current_version.production_ver.signals.DATA_MATRIX.GENERIC_DATA import signal3 as GENERIC_DATA_sig

import current_version.production_ver.Analytics.wfcreate as wf

from current_version.production_ver.backtesting_utils.chart import generic_plot

from current_version.production_ver.Analytics.series_utils import pickle_off_line_data

class signal3(abs_sig.abstract_sig_genr):

    def __init__(self):

        # in this case, both Econ and csv file data are used

        super(signal3, self).__init__()

    def get_data_dict(self, *args, **kwargs):

        self.add_sig_info()

        self.add_dir_info(**kwargs)

        self.raw_data_new_fmt = {}

        data_short_kw = {'dummy': 0, 'get_or_set_market_data': 'get'}

        data_short_kw.update((k, kwargs[k]) for k in data_short_kw.keys() & kwargs.keys())

        self.raw_data_new_fmt.update(GENERIC_DATA_sig().get_data_dict(**data_short_kw)['raw_data_new_fmt'])

        return self.get_data_dict_core(input_dict=self.raw_data_new_fmt, **kwargs)

    @cache_response('DATA_FX_FWD_IMP_CARRY', 'disk_8h', skip_first_arg=True)

    def get_data_dict_core(self,input_dict,**kw):

        input_dict = input_dict.copy()

        self.add_sig_info()

        self.add_dir_info(**kw)

        self.pre_run_result = self.pre_run(input_dict,**kw)

        input_dict.update(self.pre_run_result)

        new_wf = self.run_step1(input_dict,**kw)

        result_dict = self.fullkey_result_dict(new_wf.df)

        return {'result_dict': result_dict, 'new_wf': new_wf,'econ_vis_dict':new_wf.df}

    def add_sig_info(self):

        self.signal_ID = 'sig_0043'

        self.Short_Name = 'DATA_FX_FWD_IMP_CARRY'

        self.Description = '''

                      FX and forward market implied carry; also return SCI(total return index, not taking funding cost into consideration) index for all currencies'''

        self.exec_path = __file__

    def add_dir_info(self,**kwargs):

        super().add_dir_info(**kwargs)

        self.time_stamp = datetime.strftime(datetime.utcnow().replace(second=0, microsecond=0), '%Y%m%d_%H%M')

        self.BT_ID1 = self.Short_Name_RPT + self.time_stamp + '.pdf'

        self.RPT_DIR = os.path.join(self.RPTDIR,

                                         self.Short_Name_RPT + datetime.utcnow().strftime('%Y%m%d') + '.pdf')

        self.BT_BACKUP_DIR1 = os.path.join(self.SCRATCH_DIR, 'BT_BACKUP', self.BT_ID1)

        self.create_folder(os.path.dirname(self.BT_BACKUP_DIR1))

        self.create_folder(os.path.dirname(self.RPT_DIR))

    def pre_run(self,input_dict,**kwargs):

        return_dict = {}

        return return_dict

    def run_step1(self,input_dict,**kwargs):

        new_wf = wf.initialise_wf()

        new_wf.add_df_with_dict(self.clean_raw_data(input_dict))

        input_dict.update(new_wf.df)

        new_wf.add_df_with_dict(self.get_lc_rate(new_wf,input_dict))

        input_dict.update(new_wf.df)

        new_wf.df.update(self.extend_back_irs_1y_with_implied_lc(input_dict))

        new_wf.add_df_with_dict(self.get_tri(new_wf,input_dict))

        new_wf.add_df_with_dict(self.emfx_sci(new_wf))

        return new_wf

    def clean_raw_data(self,input_dict):

        result_list = []

        # ADD USA

        df = input_dict['USA_LIBOR_1M'].copy()

        df.columns = ['USA_FX_JPM']

        df.loc[:,:] = 1

        result_list.append({'df_name': 'USA_FX_JPM', 'new_df': df, 'to_freq': 'un_change'})

        for k in ['USA_LIBOR_1M','USA_LIBOR_3M','USA_LIBOR_6M','USA_LIBOR_1Y','CAN_FWD_1M_JPM','CHE_FWD_1M_JPM','GBR_FWD_1M_JPM','AUS_FWD_1M_JPM','EUR_FWD_1M_JPM',

                  'JPN_FWD_1M_JPM','NOR_FWD_1M_JPM','NZD_FWD_1M_JPM','SWE_FWD_1M_JPM','BRA_FWD_1M_JPM','CHL_FWD_1M_JPM','KOR_FWD_1M_JPM',

                  'THA_FWD_1M_JPM','TWN_FWD_1M_JPM','CHN_FWD_1M_JPM','SGP_FWD_1M_JPM','TUR_FWD_1M_JPM','SAF_FWD_1M_JPM','IND_FWD_1M_JPM',

                  'COL_FWD_1M_JPM','CZE_FWD_1M_JPM','COL_FWD_3M_JPM','MEX_FWD_1M_JPM','COL_FWD_1Y_JPM','CZE_FWD_3M_JPM','COL_FX_JPM',

                  'MEX_FWD_3M_JPM','PHP_FWD_1M_JPM','CZE_FWD_1Y_JPM','PHP_FWD_3M_JPM','MEX_FWD_1Y_JPM','PHP_FWD_1Y_JPM','CZE_FX_JPM',

                  'PHP_FX_JPM','MEX_FX_JPM','MAL_FWD_1M_JPM','MAL_FWD_3M_JPM','MAL_FWD_1Y_JPM','MAL_FX_JPM',

                  'IDN_FWD_1M_JPM','HUN_FWD_1M_JPM','POL_FWD_1M_JPM','RUS_FWD_1M_JPM','CAN_FWD_3M_JPM','CHE_FWD_3M_JPM','GBR_FWD_3M_JPM',

                  'AUS_FWD_3M_JPM','EUR_FWD_3M_JPM','JPN_FWD_3M_JPM','NOR_FWD_3M_JPM','NZD_FWD_3M_JPM','SWE_FWD_3M_JPM','BRA_FWD_3M_JPM','CHL_FWD_3M_JPM','KOR_FWD_3M_JPM',

                  'THA_FWD_3M_JPM','TWN_FWD_3M_JPM','CHN_FWD_3M_JPM','SGP_FWD_3M_JPM','TUR_FWD_3M_JPM','SAF_FWD_3M_JPM','IND_FWD_3M_JPM',

                  'IDN_FWD_3M_JPM','HUN_FWD_3M_JPM','POL_FWD_3M_JPM','RUS_FWD_3M_JPM','CAN_FWD_1Y_JPM','CHE_FWD_1Y_JPM','GBR_FWD_1Y_JPM',

                  'AUS_FWD_1Y_JPM','EUR_FWD_1Y_JPM','JPN_FWD_1Y_JPM','NOR_FWD_1Y_JPM','NZD_FWD_1Y_JPM','SWE_FWD_1Y_JPM','BRA_FWD_1Y_JPM','CHL_FWD_1Y_JPM','KOR_FWD_1Y_JPM',

                  'THA_FWD_1Y_JPM','TWN_FWD_1Y_JPM','CHN_FWD_1Y_JPM','SGP_FWD_1Y_JPM','TUR_FWD_1Y_JPM','SAF_FWD_1Y_JPM','IND_FWD_1Y_JPM','IDN_FWD_1Y_JPM',

                  'HUN_FWD_1Y_JPM','POL_FWD_1Y_JPM','RUS_FWD_1Y_JPM',

                  'CAN_FX_JPM','CHE_FX_JPM','GBR_FX_JPM','AUS_FX_JPM','EUR_FX_JPM','JPN_FX_JPM',

                  'NOR_FX_JPM','NZD_FX_JPM','SWE_FX_JPM','BRA_FX_JPM','CHL_FX_JPM','KOR_FX_JPM',

                  'THA_FX_JPM','TWN_FX_JPM','CHN_FX_JPM','SGP_FX_JPM','TUR_FX_JPM',

                  'SAF_FX_JPM','IND_FX_JPM','IDN_FX_JPM','HUN_FX_JPM','POL_FX_JPM',

                  'RUS_FX_JPM','ISE_FX_JPM','ISE_FWD_1M_JPM','ISE_FWD_3M_JPM','ISE_FWD_6M_JPM','ISE_FWD_1Y_JPM',

                'CAN_FWD_6M_JPM','CHE_FWD_6M_JPM','GBR_FWD_6M_JPM','AUS_FWD_6M_JPM','EUR_FWD_6M_JPM','NZD_FWD_6M_JPM',

                  'JPN_FWD_6M_JPM','NOR_FWD_6M_JPM','SWE_FWD_6M_JPM','BRA_FWD_6M_JPM','CHL_FWD_6M_JPM','CZE_FWD_6M_JPM',

                  'KOR_FWD_6M_JPM','MEX_FWD_6M_JPM','THA_FWD_6M_JPM','TWN_FWD_6M_JPM','CHN_FWD_6M_JPM','SGP_FWD_6M_JPM',

                  'TUR_FWD_6M_JPM','SAF_FWD_6M_JPM','IND_FWD_6M_JPM','IDN_FWD_6M_JPM','HUN_FWD_6M_JPM','POL_FWD_6M_JPM',

                  'RUS_FWD_6M_JPM','ISE_FWD_6M_JPM','COL_FWD_6M_JPM','PHP_FWD_6M_JPM','MAL_FWD_6M_JPM'

                  ]:

            v = input_dict[k].copy()

            try:

                v.columns = [k]

            except:

                raise ValueError(k, v)

            df = v

            if k in ['CHN_FWD_1M_JPM','CHN_FWD_3M_JPM','CHN_FWD_6M_JPM','CHN_FWD_1Y_JPM']:

                df = df.loc['2000-3':]

            result_list.append({'df_name': k, 'new_df': df, 'to_freq': 'un_change'})

        for tenor in ['1M','3M','6M','1Y']:

            df = input_dict['USA_LIBOR_1M'].copy()

            df.columns = ['USA_FWD_'+tenor]

            df.loc[:,:]=1

            result_list.append({'df_name': 'USA_FWD_'+tenor, 'new_df': df, 'to_freq': 'un_change'})

        return result_list

    def get_lc_rate(self,new_wf,input_dict):

        result_list=[]

        for tenor,number_of_month in zip(['1M','3M','6M','1Y'],[1,3,6,12]):

            for iso in ['USA','CAN','CHE','GBR','AUS','EUR','JPN','NOR','NZD','SWE','BRA','CHL','KOR','THA','TWN','CHN','SGP','TUR','SAF','IND','IDN','HUN','POL','RUS','COL','PHP',

                        'MAL','CZE','MEX','ISE']:

                new_name = iso + '_IMPLIED_RATE_' + tenor

                if iso not in ['USA']:

                    base_ccy_rate = new_wf.df['USA_LIBOR_'+tenor]

                    spot, fwd =  input_dict[iso+'_FX_JPM'],  new_wf.df[iso+'_FWD_' + tenor+'_JPM']

                    lc_rate = self.forward_fetch_inv(spot,fwd,base_ccy_rate,new_name = new_name,number_of_month=number_of_month).dropna()

                    # remove the last 2 data points as they're wrong

                    # lc_rate.iloc[-2:,:] = np.nan

                    # lc_rate = lc_rate.ffill()

                    lc_rate = self.SU.remove_outlier(lc_rate,n=3,use_end_point='1m_ago')

                    result_list.append({'df_name': new_name, 'new_df': lc_rate, 'to_freq': 'un_change'})

                else:

                    pass

        return result_list

    def get_tri(self,new_wf,input_dict):

        result_list = []

        tenor='1M'

        for iso in ['USA','CAN','CHE','GBR','AUS','EUR','JPN','NOR','NZD','SWE','BRA','CHL','KOR','THA','TWN','CHN','SGP','TUR','SAF','IND','IDN','HUN','POL','RUS','COL','PHP',

                        'MAL','CZE','MEX','ISE']:

            spot = input_dict[iso+'_FX_JPM']

            if iso not in ['USA']:

               lc_rate = new_wf.df[iso+'_IMPLIED_RATE_'+tenor]

            else:

                lc_rate = new_wf.df['USA_LIBOR_' + tenor]

            new_name = iso+'_SCI_'+tenor

            df_tri = self.Total_Return_Index(1/spot,lc_rate,new_name=new_name)

            result_list.append({'df_name': new_name, 'new_df': df_tri, 'to_freq': 'un_change'})

        return result_list

    def emfx_sci(self,new_wf):

        result_list = []

        tenor='1M'

        # EMFX vs USD

        df_list = []

        for iso in ['KOR','BRA','CHL','SAF','THA','MEX','MAL','IND','PHP','COL','IDN','TUR','RUS','CHN','HUN','CZE','POL']:

            df_list.append(new_wf.df[iso+'_SCI_'+tenor].dropna())

        df_comb = pd.concat(df_list,axis=1).pct_change()

        EMFX_TOTRET = (df_comb.mean(axis=1)+1).cumprod().to_frame()

        USA_TOT_RET = new_wf.df['USA'+'_SCI_'+tenor].dropna()

        EMFX_TOTRET = (EMFX_TOTRET.iloc[:,0]/USA_TOT_RET.iloc[:,0]).to_frame()

        EMFX_TOTRET.columns = ['EMFX_TOTRET']

        #EMFX vs DW basket

        df_dw = []

        weight = [.5,.2,.15,.05,.05,.05]

        for iso,w in zip(['USA','EUR','JPN','GBR','AUS','CAN'],weight):

            df_dw.append(new_wf.df[iso + '_SCI_' + tenor].dropna().pct_change() * w)

        DW_BASK_TOTRET = (pd.concat(df_dw,axis=1).mean(axis=1)+1).cumprod().to_frame()

        EMFX_TOTRET_DWBASKET = (EMFX_TOTRET.iloc[:,0]/DW_BASK_TOTRET.iloc[:,0]).to_frame()

        EMFX_TOTRET_DWBASKET.columns = ['EMFX/DW_BASK']

        result_list.append({'df_name': 'EMFX_TOTRET', 'new_df': EMFX_TOTRET, 'to_freq': 'un_change'})

        result_list.append({'df_name': 'EMFX/DW_BASK', 'new_df': EMFX_TOTRET_DWBASKET, 'to_freq': 'un_change'})

        return result_list

    def extend_back_irs_1y_with_implied_lc(self,input_dict):

        # for the purpose of long IRS 1y data, extend this back with implied 1y local rate

        out = {}

        for iso in ['USA','CAN','CHE','GBR','AUS','EUR','JPN','NOR','NZD','SWE','BRA','CHL','KOR','THA','TWN','CHN','SGP','TUR','SAF','IND','IDN','HUN','POL','RUS','COL','PHP',

                        'MAL','CZE','MEX','ISE']:

            df1 = input_dict[iso+'_IRS_1Y'].dropna()

            if iso in ['USA:']:

                df2 = input_dict[iso+'_IMPLIED_RATE_1Y'].dropna()

            else:

                df2 = input_dict['USA_LIBOR_1Y'].dropna()

            df_long = self.SU.extend_backward_df1_by_df2(df1,df2,method='aris')

            new_name = iso+'_IRS_1Y_IMPL_RATE_EXT'

            df_long.columns = [new_name]

            out[new_name] = df_long

        return out

    def forward_fetch_inv(self,spot,fwd,base_ccy_rate,new_name,number_of_month):

        # get implied local 1m rates annualised using forward

        spot,fwd,base_ccy_rate = self.SU.conversion_to_bDay(spot),self.SU.conversion_to_bDay(fwd),self.SU.conversion_to_bDay(base_ccy_rate)

        df_rate = (base_ccy_rate.iloc[:,0]-(spot.iloc[:,0]/fwd.iloc[:,0]-1)*12*100/number_of_month).to_frame()

        df_rate.columns = [new_name]#base_ccy_rate.to_csv('base_ccy_rate.csv')

        return df_rate

    def Total_Return_Index(self,spot,LocalRate,new_name,BaseDate=pd.to_datetime('2011-11-11')):

        spot,LocalRate = self.SU.conversion_to_bDay(spot),self.SU.conversion_to_bDay(LocalRate)

        SpotRet = spot.pct_change()+1

        SpotRet = SpotRet.cumprod()

        Carry = LocalRate.shift(1)/25200 + 1

        Carry = Carry.cumprod()

        TRI = (SpotRet.iloc[:,0] * Carry.iloc[:,0]).to_frame()

        TRI = TRI/TRI.loc[BaseDate,:].values[0]

        TRI.columns = [new_name]

        return TRI

    def TOT_RET(self,ret_idx1,ret_idx2,new_name):

        # calc total return index of USA (or EUR) invest in another country:

        ret_idx1,ret_idx2 = self.SU.conversion_to_bDay(ret_idx1),self.SU.conversion_to_bDay(ret_idx2)

        ret1 = ret_idx1.pct_change()+1

        ret1 = ret1.cumprod()

        ret2 = ret_idx2.pct_change()+1

        ret2 = ret2.cumprod()

        TRI = (ret1.iloc[:,0]*ret2.iloc[:,0]).to_frame()

        TRI.columns = [new_name]

        return TRI

    def get_spread_average(self,df1,df2):

        df_spread = (df1.iloc[:,0]-df2.iloc[:,0]).to_frame().dropna()

        df_spread.columns = ['spread']

        df_spread_10y = df_spread.copy()

        if len(df_spread_10y.index)>=252*10:

            df_spread_10y.loc[:,:] = df_spread_10y.iloc[:,0].rolling(252*10).mean().values[-1]

        else:

            df_spread_10y.loc[:, :] = df_spread_10y.mean().values[0]

        df_spread_10y.columns = ['10y avg']

        return df_spread,df_spread_10y

    def run_reporting(self,*args,**kwargs):

        new_wf = self.get_data_dict(*args,**kwargs)['new_wf']

        self.add_sig_info()

        self.add_dir_info(**kwargs)

        df_res = []

        chart_type = []  # chart type is called cmd_estimate_balance_fx

        title_res = []

        #start_dt_list = ['2018-01-01','2015-01-01','2002-1-1']

        for s_date in ['1900-1-1','2015-1-1']:

            for iso in ['USA','CAN','CHE','GBR','AUS','EUR','JPN','NOR','NZD','SWE','BRA','CHL','KOR','THA','TWN','CHN','SGP','TUR','SAF','IND','IDN','HUN','POL','RUS','COL','PHP',

                        'MAL','CZE','MEX']:

                if iso not in ['USA']:

                    df1,df2 = new_wf.df[iso+'_IMPLIED_RATE_1M'].copy().dropna().loc[s_date:,:],new_wf.df['USA_LIBOR_1M'].copy().dropna().loc[s_date:,:]

                    this_title = ' fwd implied 1m vs USA libor 1m'

                    df_res.append((df1,df2))

                    chart_type.append('raw_vs_trend')

                    last_value1,last_value2 = df1.iloc[-1, 0],df2.iloc[-1,0]

                    last_dt = df1.dropna().index[-1]

                    this_title = iso + this_title+' : ' + "{0:.2f}".format(last_value1)+' : '+"{0:.2f}".format(last_value2) + " (" + last_dt.strftime(

                        "%Y-%m-%d") + ")"

                    title_res.append(this_title)

                if iso not in ['USA']:

                    df1,df2 = new_wf.df[iso+'_IMPLIED_RATE_3M'].copy().dropna().loc[s_date:,:],new_wf.df['USA_LIBOR_3M'].copy().dropna().loc[s_date:,:]

                    this_title = ' fwd implied 3m vs USA libor 3m'

                    df_res.append((df1, df2))

                    chart_type.append('raw_vs_trend')

                    last_value1,last_value2 = df1.iloc[-1, 0],df2.iloc[-1,0]

                    last_dt = df1.dropna().index[-1]

                    this_title = iso + this_title+' : '  + "{0:.2f}".format(last_value1)+' : '+"{0:.2f}".format(last_value2) + " (" + last_dt.strftime(

                        "%Y-%m-%d") + ")"

                    title_res.append(this_title)

                # if iso not in ['USA']:

                #     df1,df2 = new_wf.df[iso+'_IMPLIED_RATE_6M'].copy().dropna().loc[s_date:,:],new_wf.df['USA_LIBOR_6M'].copy().dropna().loc[s_date:,:]

                #     this_title = ' fwd implied 3m vs USA libor 6m'

                #

                #     df_res.append((df1, df2))

                #     chart_type.append('raw_vs_trend')

                #     last_value1,last_value2 = df1.iloc[-1, 0],df2.iloc[-1,0]

                #

                #     last_dt = df1.dropna().index[-1]

                #     this_title = iso + this_title+' : '  + "{0:.2f}".format(last_value1)+' : '+"{0:.2f}".format(last_value2) + " (" + last_dt.strftime(

                #         "%Y-%m-%d") + ")"

                #     title_res.append(this_title)

        chart_pack_dict = {

            'chart_type': chart_type,

            'df_res': df_res,

            'title_res': title_res,

        }

        generic_plot(plot_dict=chart_pack_dict, pdfpath=self.BT_BACKUP_DIR1,

                     bt_backup_dir=self.RPT_DIR)

def run(*args,**kwargs):

    reporting_to = sys.argv[1] if len(sys.argv) > 1.01 else None

    signal3().run_reporting(*args,reporting_to=reporting_to,**kwargs)

if __name__ == "__main__":

    clear_cache('DATA_FX_FWD_IMP_CARRY', 'disk_8h')

    reporting_to = sys.argv[1] if len(sys.argv) > 1.01 else None

    # signal3().run_reporting(reporting_to=reporting_to)

    print (signal3().get_data_dict()['econ_vis_dict'].keys())

    signal3().run_reporting(reporting_to=reporting_to)


from bright.api import *
from pyne.material import Material
import os

# Set-up pointer to reactor database
data_dir = os.getenv("BRIGHT_DATA")
lwr_data = data_dir + "/LWR.h5"

# Customize output
bright_conf.write_text = False
bright_conf.write_hdf5 = True
load_track_nucs_hdf5(lwr_data)

# Enrichment Calculation
nu = Material({"U234": 0.000055, "U235": 0.0072, "U238": 0.992745})
leu = uranium_enrichment_defaults()
leu.xP_j = 0.036
enr = Enrichment(enrich_params=leu, name="enrich")
enr.calc(nu)
enr.write()

# Reactor Calculation
lwrd = lwr_defaults()
lwrd.BUt = 35.0
lwrd.batches = 3
lwr = LightWaterReactor1G(lwr_data, lwrd, "LWR")
lwr.calc(enr.mat_prod)
lwr.write()

# Storage Calculation
st = Storage("Storage")
st.decay_time = 5.0 * 365.25 * 24.0 * 3600.0
st.calc(lwr.mat_prod)
st.write()


#!/bin/py
#   -*-coding:utf-8-*-

import requests
from urllib import parse
import re
import time
import os
import random

URL=r'https://www.vipxs.la/57_57619/'#'http://www.vipxs.la/62_62548/'#'http://www.vipxs.la/8_8601'#http://www.vipxs.la/
scheme,netloc,path,query,fragment=parse.urlsplit(URL)
print(parse.urlsplit(URL))
response= requests.get(URL)
page=response.content.decode("utf-8")
chapter_reg=r'
(.*?)
'
title_reg=r''
author_reg=r'
作    者：(.*?)
'

chapter_list=re.findall(chapter_reg,page)
title=re.findall(title_reg,page)
author=re.findall(author_reg,page)
path=os.path.join(".",title[0]+"_"+author[0])
filename=title[0]+"_"+author[0]+".txt"
print(title[0],author[0])

if os.path.exists(path) and os.path.isdir(path):
    for f in os.listdir(path):
        os.remove(os.path.join(path,f))
else:
    os.mkdir(path)

for chapter in chapter_list:
    chapter_url,chapter_name=scheme+"://"+netloc+chapter[0],chapter[1]
    print (chapter_url)

    response= requests.get(chapter_url)
    page =response.content.decode("utf-8")
    reg=r'    (.*?)
'
    result=re.findall(reg,page)
    text=chapter_name+"\r\n"+"\r\n"
    # text+="\t"
    flag=0
    print(result)
    for hang in result:
        text=text+"\t"+hang+"\r\n"
        text=text+"\r"
    # for hang in result:
    #     if hang!="……" and flag==0:
    #         text=text+hang
    #         continue
    #     if hang=="……"  and flag==0:
    #         flag+=1
    #         continue
    #     if hang=="……"  and flag==1:
    #         text=text+"\r\n"
    #         text=text+"\t"
    #         flag=0
    #         continue
    #     if hang!="……" and flag==1:
    #         text=text+"\r\n"
    #         text=text+"\t"+'……'
    #         flag=0
    #         continue
    text+="\r\n"+"\r\n"
    with open(os.path.join(path,chapter_name+".txt"),"w",encoding="utf-8") as f1:
        f1.write(text)
    with open(os.path.join(path,filename),"a",encoding="utf-8") as f2:
        f2.write(text)

 #   s=random.randint(1,3)
  #  print("停止{}秒".format(s))
  #  time.sleep(s)


import pickle

import torch
import torch.nn as nn
import torch.nn.functional as F

class BaseAgent(object):
    """
    BaseAgent class for all RL agents.
    """

    def __init__(self, env, opt):
        self.name = "BaseAgent"
        self.test = False

        self.opt = opt
        self.featureExtractor = opt.featExtractor(env)

        self.action_space = env.action_space

    def get_features(self, ob):
        return torch.tensor(
            self.featureExtractor.getFeatures(ob), dtype=torch.float32
        ).squeeze()

class BaseImitation(BaseAgent):
    def __init__(self, env, opt):
        super().__init__(env, opt)
        self.expert_states, self.expert_actions = self.loadExpertTransitions(
            opt.expert_path
        )
        self.nbActions = self.action_space.n

    def loadExpertTransitions(self, file):
        with open(file, "rb") as handle:
            expertdata = pickle.load(handle).to(torch.float)
            expertstates = expertdata[:, : self.featureExtractor.outSize]
            expertactions = expertdata[:, self.featureExtractor.outSize :]
            expertstates = expertstates.contiguous()
            expertactions = expertactions.contiguous()
            return expertstates, expertactions

    def toOneHot(self, actions):
        actions = actions.view(-1).to(torch.long)
        oneHot = torch.zeros(actions.size()[0], self.nbActions).to(torch.float)
        oneHot[range(actions.size()[0]), actions] = 1
        return oneHot

    def toIndexAction(self, oneHot):
        ac = torch.LongTensor(range(self.nbActions)).view(1, -1)
        ac = ac.expand(oneHot.size()[0], -1).contiguous().view(-1)
        actions = ac[oneHot.view(-1) > 0].view(-1)
        return actions

class ApproxFunction(nn.Module):
    def __init__(
        self,
        input_size,
        output_size,
        hidden_dims,
        output_activation=None,
        hidden_activation=F.relu,
    ):
        super().__init__()
        self.fcinput = nn.Linear(input_size, hidden_dims[0])
        self.fchidden = nn.ModuleList()
        for i, d in enumerate(hidden_dims[1:]):
            self.fchidden.append(nn.Linear(hidden_dims[i], d))
        self.fcoutput = nn.Linear(hidden_dims[-1], output_size)
        self.act_output = output_activation
        self.act_hidden = hidden_activation

    def forward(self, x):
        x = self.act_hidden(self.fcinput(x))
        for layer in self.fchidden:
            x = self.act_hidden(layer(x))
        x = self.fcoutput(x)
        if self.act_output:
            x = self.act_output(x)
        return x


from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.externals import joblib
from nltk.corpus import stopwords
from scipy import sparse
import pandas as pd
import numpy as np
import string
import nltk
import re

#----- Functions to process text
def processText(text):
    result = text.lower().strip()
    result = re.sub(r'\n', ' ', result)
    result = re.sub(r'\r', ' ', result)
    result = re.sub(r'[^\x00-\x7F]+', ' ', result)
    result = re.sub('[\W]+', ' ', result)
    result = re.sub(r' +', ' ', result).strip()
    return result

def replaceText(text):
    result = text.lower().strip()
    result = re.sub(r"\bpm\b", " ", result)
    result = re.sub(r"\byrs\b", " years ", result)
    result = re.sub(r"\bhr\b", " hours ", result)
    result = re.sub(r"\bhrs\b", " hours ", result)
    result = re.sub(r"\bmin\b", " minutes ", result)
    result = re.sub(r"\bmins", " minutes ", result)
    result = re.sub(r"\bdr\b", " doctor ", result)
    result = re.sub(r"\bdoc\b", " doctor ", result)
    result = re.sub(r"\bapt\b", " appointment ", result)
    result = re.sub(r"\bappt\b", " appointment ", result)
    result = re.sub(r' +', ' ', result).strip()
    return result

def prepData(text):
    text = replaceText(text)
    text = processText(text)
    return text

#----- Load the model
model_location = '/Users/degrave/Healthgrades/sentiment/model/'
model = joblib.load(model_location + 'model_logreg_pipe.pkl')

#----- How to use the model
text = "i first met dr. blucher when he arrived at my emergency room to discuss my by pass surgery. immediately i was put at ease with his confidence and positive attitude. i knew right away that i was in good hands. i am now 6 weeks out of surgery and doing great. the surgery could not have gone better. i highly recommend him as a surgeon and have already sung his praises to many friends and family. thank you so much doctor!!"

dt = prepData(text)

#----- Print predicted sentiment polarity score
print('sentiment polarity:', model.predict_proba([dt])[:,0][0])


import logging
import threading
import time

import redis
from kubernetes import client
from kubernetes import config

from compute_provisioner.provisioner import KubernetesAllocator

logger = logging.getLogger('provisioner.kube_cluster')

class KubeCluster(threading.Thread):
    def __init__(self, redis_host, namespace, timeout, dry_run, ignore_lifetime, **kwargs):
        super(KubeCluster, self).__init__(target=self.monitor)

        self.redis_host = redis_host

        self.namespace = namespace

        self.timeout = timeout

        self.dry_run = dry_run

        self.ignore_lifetime = ignore_lifetime

        self.k8s = KubernetesAllocator()

        self.redis = redis.Redis(self.redis_host, db=1)

    def check_resources(self):
        keys = self.redis.hkeys('resource')

        for x in keys:
            expire = self.redis.hget('resource', x)

            logger.info(f'Checking resource group {x}')

            label_selector = f'compute.io/resource-group={x.decode()!s}'

            if expire is None:
                self.k8s.delete_resources(self.namespace, label_selector)
            else:
                expire = float(expire.decode())

                if expire < time.time() or self.ignore_lifetime:
                    self.k8s.delete_resources(self.namespace, label_selector)

                    self.redis.hdel('resource', x)

        logger.info('Removing rogue resources')

        key_list = ', '.join([x.decode() for x in keys])

        rogue_selector = f'compute.io/resource-group,compute.io/resource-group notin ({key_list!s})'

        self.k8s.delete_resources(self.namespace, rogue_selector)

        complete_selector = f'compute.io/resource-group'

        pods = self.k8s.list_pods(self.namespace, complete_selector)

        logger.info(f'Checking {len(pods.items)} resource groups of end of life phase')

        resource_keys = []

        for x in pods.items:
            eol_phase = x.status.phase in ('Succeeded', 'Failed', 'Unknown')
            work_done = x.metadata.labels.get('compute.io/state', '') == 'Done'

            if eol_phase or work_done:
                resource_keys.append(x.metadata.labels['compute.io/resource-group'])

                logger.info(f'Found resource group {resource_keys[-1]} with eol condition')

                count = self.redis.hdel('resource', resource_keys[-1])

                logger.debug(f'Removed {count} entries in redis')

        eol_resource_keys = ', '.join(resource_keys)

        eol_selector = f'compute.io/resource-group,compute.io/resource-group in ({eol_resource_keys!s})'

        self.k8s.delete_resources(self.namespace, eol_selector)

    def monitor(self):
        while True:
            self.check_resources()

            time.sleep(self.timeout)

def main():
    import argparse

    parser = argparse.ArgumentParser()

    parser.add_argument('--log-level', help='Logging level', choices=logging._nameToLevel.keys(), default='INFO')

    parser.add_argument('--redis-host', help='Redis host', required=True)

    parser.add_argument('--namespace', help='Kubernetes namespace to monitor', default='default')

    parser.add_argument('--timeout', help='Resource monitor timeout', type=int, default=30)

    parser.add_argument('--dry-run', help='Does not actually remove resources', action='store_true')

    parser.add_argument('--ignore-lifetime', help='Ignores lifetime', action='store_true')

    args = parser.parse_args()

    logging.basicConfig(level=args.log_level)

    monitor = KubeCluster(**vars(args))

    monitor.start()

    monitor.join()

if __name__ == '__main__':
    main()


import os, sys, math, random, scipy.stats
import numpy as np
import subprocess, sys
qec_playground_root_dir = subprocess.run("git rev-parse --show-toplevel", cwd=os.path.dirname(os.path.abspath(__file__)), shell=True, check=True, capture_output=True).stdout.decode(sys.stdout.encoding).strip(" \r\n")
rust_dir = os.path.join(qec_playground_root_dir, "backend", "rust")
fault_toleran_MWPM_dir = os.path.join(qec_playground_root_dir, "benchmark", "fault_tolerant_MWPM")
sys.path.insert(0, fault_toleran_MWPM_dir)
from automated_threshold_evaluation import qec_playground_fault_tolerant_MWPM_simulator_runner_vec_command
from automated_threshold_evaluation import run_qec_playground_command_get_stdout, compile_code_if_necessary
sys.path.insert(0, os.path.join(qec_playground_root_dir, "benchmark", "slurm_utilities"))
import slurm_distribute
from slurm_distribute import slurm_threads_or as STO
from slurm_distribute import cpu_hours as CH

origin_folder = os.path.join(os.path.dirname(__file__), "..")
legacy_folder = os.path.join(origin_folder, "legacy")

def read_origin_configurations():

    # read in the threshold
    thresholds = []
    with open(os.path.join(origin_folder,  "thresholds.txt"), "r", encoding="utf8") as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip(" \r\n")
            if line == "":
                continue
            pauli_ratio, threshold, dev = line.split(" ")
            thresholds.append((pauli_ratio, float(threshold), float(dev)))

    configurations = []
    for (pauli_ratio, threshold, dev) in thresholds:
        ratio_configurations = []
        filepath = os.path.join(legacy_folder,  f"pauli_ratio_{pauli_ratio}.txt")
        with open(filepath, "r", encoding="utf8") as f:
            lines = f.readlines()
            for line in lines:
                line = line.strip(" \r\n")
                if line == "":
                    continue
                spt = line.split(" ")
                p_pth = float(spt[0])
                # p = float(spt[1])
                # pL = float(spt[7])
                # pL_dev = float(spt[9])
                ratio_configurations.append((p_pth, p_pth * threshold))
        configurations.append((pauli_ratio, ratio_configurations[-8:]))
    return configurations

configurations = read_origin_configurations()
# print(configurations)

di = 5
min_error_cases = 100000
# min_error_cases = 10  # debug

max_N = 100000000

slurm_distribute.SLURM_DISTRIBUTE_TIME = "05:20:00"
slurm_distribute.SLURM_DISTRIBUTE_MEM_PER_TASK = '4G'
slurm_distribute.SLURM_DISTRIBUTE_CPUS_PER_TASK = 12  # use fewer cores for more available resources (use `SLURM_USE_SCAVENGE_PARTITION` option to speed up)
# 18000 sec for 12 cores, that is 60 CPU hours
init_measurement_error_rate = 0.001
noise_model_configuration = f'{{"initialization_error_rate":{init_measurement_error_rate},"measurement_error_rate":{init_measurement_error_rate},"use_correlated_pauli":true}}'
parameters = f"-p{STO(0)} --decoder UF --max_half_weight 100 --time_budget {CH(60)} --use_xzzx_code --noise_model OnlyGateErrorCircuitLevelCorrelatedErasure".split(" ") + ["--noise_model_configuration", noise_model_configuration]  # a maximum 60min for each point

compile_code_if_necessary()
@slurm_distribute.slurm_distribute_run(os.path.dirname(__file__))
def experiment(slurm_commands_vec = None, run_command_get_stdout=run_qec_playground_command_get_stdout):
    lines = []
    for pauli_ratio, ratio_configurations in configurations:
        data = []
        for p_pth, p in ratio_configurations:
            p_pauli = p * float(pauli_ratio)
            p_erasure = p * (1 - float(pauli_ratio))
            command = qec_playground_fault_tolerant_MWPM_simulator_runner_vec_command([p_pauli], [di], [di], [di], parameters + ["--pes", f"[{p_erasure}]"], max_N=max_N, min_error_cases=min_error_cases)
            if slurm_commands_vec is not None:
                slurm_commands_vec.sanity_checked_append(command)
                continue
            print(" ".join(command))

            # run experiment
            stdout, returncode = run_command_get_stdout(command)
            print("\n" + stdout)
            assert returncode == 0, "command fails..."

            # full result
            full_result = stdout.strip(" \r\n").split("\n")[-1]
            lst = full_result.split(" ")
            pL = float(lst[5])
            pL_dev = float(lst[7])

            data.append((p_pth, pL, pL_dev))

        if slurm_commands_vec is not None:
            continue

        X = [math.log(p_pth) for p_pth, pL, pL_dev in data]
        slope_vec = []
        for random_round in range(100):
            Y = [math.log(pL) for p_pth, pL, pL_dev in data]
            for i in range(len(data)):
                Y[i] += random.gauss(0, data[i][2] / 1.96)
            slope, intercept, _, _, _ = scipy.stats.linregress(X, Y)
            slope_vec.append(slope)
            # print(line, slope)
        slope = np.mean(slope_vec)
        slope_confidence_interval = 1.96 * np.std(slope_vec)

        line = f"{pauli_ratio} {slope} {slope_confidence_interval}"
        print(line)
        lines.append(line)

    if slurm_commands_vec is not None:
        return

    content = "\n".join(lines)
    print(content)
    with open(os.path.join(os.path.dirname(__file__), "effective_code_distance.txt"), "w", encoding="utf8") as f:
        f.write(content + "\n")


# coding=utf-8
"""
题目一:
在O(1)的时间内删除链表节点
给定单向链表的头指针和一个节点指针,定义一个函数在O(1)时间内删除该节点
"""

class ListNode(object):
    def __init__(self, value):
        self.value = value
        self.next = None

def delete_node(head_node, to_be_delete_node):
    # 链表只有一个节点,删除该节点
    if head_node.next == None:
        head_node = None
        to_be_delete_node = None
    # 链表有多个节点
    else:
        # 要删除的节点是尾节点
        if to_be_delete_node.next == None:
            current_node = head_node
            while current_node.next != to_be_delete_node:
                current_node = current_node.next
            current_node.next = None
        # 要删除的节点不是尾节点
        else:
            next_node = to_be_delete_node.next
            to_be_delete_node.value = next_node.value
            to_be_delete_node.next = next_node.next
            next_node.next = None

"""
题目二:
删除链表中的重复节点，在一个排序的链表中，如何删除重复的节点
"""

def detele_duplicate(head):
    if not head:
        return head
    first = ListNode(-1)
    first.next = head
    current_node = head
    pre_node = first
    # 从头结点开始遍历到最后一个节点
    while current_node:
        next_node = current_node.next
        if next_node and current_node.value == next_node.value:
            while next_node and current_node.value == next_node.value:
                next_node = next_node.next
            pre_node.next = next_node
            current_node = next_node
        else:
            pre_node = current_node
            current_node = next_node
    return first.next

if __name__ == '__main__':
    node1 = ListNode(3)
    node2 = ListNode(4)
    node3 = ListNode(4)
    node4 = ListNode(2)
    node1.next = node2
    node2.next = node3
    node3.next = node4
    result = detele_duplicate(node4)
    delete_node(node1, node3)

18.删除链表的节点.py

18.删除链表的节点.py


count = 0
def palindrome(reverse,n):
    # list to a int reverse
    # print(list)
    if reverse == n :
        return True
    else :
        return False

def rev(n):
    global count
    # reverse = list[i]
    # print(type(list[i]))
    n = str(n)
    reverse = n[::-1]
    count = count + 1
    reverse = int(reverse)
    if palindrome(reverse,int(n)) == False:
        reverse += int(n)
        rev(reverse)
    elif palindrome(reverse,int(n)) == True and count == 1 :
        reverse += int(n)
        rev(reverse)
    else:
        print("add count & sum:",count-1,reverse)
        count = 0

def main():
    list = []
    i = 0
    n = int(input("n : "))
    for i in range(n):
        list.append(int(input("number to reverse and add : ")))
    for i in range(n):
        rev(list[i])

main()


#!/usr/bin/env python

"""

an example of solving Poisson's equation via smoothing only.  Here, we
solve

u_xx = sin(x)
u = 0 on the boundary [0,1]

The analytic solution is u(x) = -sin(x) + x sin(1)

This version (separate) differs from smooth.py in that we implement the
smoothing here directly, instead of using the MG solver.

M. Zingale (2013-03-31)

"""
#from io import *
import numpy as np
import matplotlib.pyplot as plt
import sys

def true(x):
    # the analytic solution
    return -np.sin(x) + x*np.sin(1.0)

def error(ilo, ihi, dx, r):
    # L2 norm of elements in r, multiplied by dx to normalize
    return np.sqrt(dx*np.sum((r[ilo:ihi+1]**2)))

def f(x):
    # the righthand side
    return np.sin(x)

def compute_residual(ilo, ihi, dx, phi, frhs):
    # compute r = f - L phi
    r = np.zeros(len(phi))
    r[ilo:ihi+1] = frhs[ilo:ihi+1] - \
        (phi[ilo+1:ihi+2] - 2.0*phi[ilo:ihi+1] + phi[ilo-1:ihi])/dx**2
    return r

def smooth_run(nx, method="GS"):

    xmin = 0.0
    xmax = 1.0

    ng = 1

    # initialize the solution to zero.  Put one ghost cell on either end
    phi = np.zeros(nx + 2*ng, dtype=np.float64)
    phinew = np.zeros_like(phi)

    ilo = ng
    ihi = ng + nx - 1

    # coordinates of centers
    dx = (xmax - xmin)/nx
    x = (np.arange(nx+2*ng) - ng + 0.5)*dx + xmin

    # initialize the RHS using the function f
    frhs = f(x)

    # smooth
    n = np.arange(20000) + 1
    e = []
    r = []

    print("source norm: ", error(ilo, ihi, dx, frhs))
    print(np.sum(frhs[ilo:ihi+1]))

    for i in n:

        # fill the ghost cells
        phi[ilo-1] = -phi[ilo]
        phi[ihi+1] = -phi[ihi]

        if method == "Jacobi":
            phinew[ilo:ihi+1] = \
                (-dx*dx*frhs[ilo:ihi+1] + phi[ilo+1:ihi+2] + phi[ilo-1:ihi])/2.0
            phi[:] = phinew[:]

        elif method == "GS":

            # red-black Gauss-Seidel -- first do the odd, then even points
            phi[ilo:ihi+1:2] = \
                0.5*(-dx*dx*frhs[ilo:ihi+1:2] +
                     phi[ilo+1:ihi+2:2] + phi[ilo-1:ihi:2])

            # fill the ghost cells between red and black
            phi[ilo-1] = -phi[ilo]
            phi[ihi+1] = -phi[ihi]

            phi[ilo+1:ihi+1:2] = \
                0.5*(-dx*dx*frhs[ilo+1:ihi+1:2] + \
                     phi[ilo+2:ihi+2:2] + phi[ilo:ihi:2])

        else:
            sys.exit("invalid method")

        # compute the true error (wrt the analytic solution) and residual
        e.append(error(ilo, ihi, dx, phi - true(x)))

        # compute the residual
        resid = compute_residual(ilo, ihi, dx, phi, frhs)
        r.append(error(ilo, ihi, dx, resid))

    return n, np.array(r), np.array(e)

# test the multigrid solver
N = [16, 32, 64]

c = ["r", "g", "b"]

for nx in N:

    n, r, e = smooth_run(nx)
    color = c.pop()
    plt.plot(n, e, color=color, label = str(nx))
    plt.plot(n, r, color=color, ls=":")

ax = plt.gca()
ax.set_xscale('log')
ax.set_yscale('log')

plt.xlabel("# of iterations")
plt.ylabel("L2 norm of true error (solid) and residual (dotted)")
plt.legend(frameon=False, fontsize="small")

plt.savefig("smooth-error.png")


from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template.defaultfilters import slugify
from django.template import RequestContext
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from forms import *
from django.contrib.auth.models import User
# from tiq_login.models import TiqUserProfile
from mail.models import Message, MailMessage, SentMessage
from library import block_quote_from_text
from django.http import Http404
from django.conf import settings
from starfishcommunity.mailer import send_mail
from starfishcommunity.discussion.models import User_Settings, User_Thread_Settings
import hashlib
import datetime
from datetime import timedelta
from datetime import date

def _getIP(request):
	ip = request.META['REMOTE_ADDR']
	if (not ip or ip == '127.0.0.1') and request.META.has_key('HTTP_X_FORWARDED_FOR'):
		ip = request.META['HTTP_X_FORWARDED_FOR']
	return ip

def new(request, user_id=None):

	if request.method == 'POST':
		form = MessageForm(request.POST)

		if form.is_valid():
			#first here, we need to check and see if this person is either a staff member or superuser, or if this user has reached the limit of emails in an hour.  this is in settings as MAX_EMAILS_PER_HOUR
			sender = User.objects.get(id=request.user.id)

			if sender.is_staff or sender.is_superuser:
				pass
			else:
				time_diff = datetime.datetime.now() - timedelta(minutes=60)
				msgList = Message.objects.filter(sender=request.user, sent__gte=time_diff)

				if msgList.count() >= 5:
					request.user.message_set.create(message='You have surpassed your mail limit for the hour.  Please try again later.')
					title = "User " + request.user.username + " has been flagged for email violations."

					vioIP = _getIP(request)
					bip_url = 'http://www.starfishcommunity.net/mod/ban_ip/' + vioIP
					message = settings.VIOLATION_EMAIL % (request.user.username, str(datetime.datetime.now()), vioIP, form.cleaned_data['subject'], form.cleaned_data['message'], bip_url )

					send_mail(title, message, settings.FROM_EMAIL_ADDRESS, ['administration@hisg-it.net'])
					return HttpResponseRedirect('') # Redirect after POST

				#messages = Message.objects.filter(sender=request.user, sent__range=() )

			message = form.cleaned_data['message']
			subject = form.cleaned_data['subject']

			recip = User.objects.get(id=user_id)
			msg = Message()
			msg.sender = sender
			msg.hex_subject = subject
			msg.hex_msg = message
			msg.save()

			smsg = SentMessage()
			smsg.id = msg.id
			smsg.sender = sender
			smsg.hex_subject = subject
			smsg.recipient = recip
			smsg.hex_msg = message
			smsg.save()

			mm = MailMessage(recipient=recip, message=msg, read=False)
			mm.save()

			request.user.message_set.create(message='Mail Sent')

			try:
				user_settings = User_Settings.objects.get(user=recip)
			except User_Settings.DoesNotExist:
				us = User_Settings()
				us.user = recip
				us.save()
				user_settings = User_Settings.objects.get(user=recip)

			used_emails = []
			if user_settings.receive_blast_emails == True:
				if recip.email not in used_emails:
					used_emails.append(recip.email)

			title = """New message on StarfishCommunity.net """

			message = settings.PRIVATE_MESSAGE_EMAIL % (
			   sender.first_name,
			   subject,
			   get_post_preview(message),
			   settings.SITE_ROOT_URL + "/mail/inbox",
			   settings.SITE_ROOT_URL + "/discuss/unsubscribe/" + str(recip.id) + "/" + hashlib.md5(str(recip.id) + recip.email).hexdigest()
			   )

			send_mail(title, message, settings.FROM_EMAIL_ADDRESS, used_emails)

			return HttpResponseRedirect('/discuss/') # Redirect after POST

	else:
		form = MessageForm()
		recip = User.objects.get(id=user_id)
		# recip_name = recip.first_name + ' ' + recip.last_name			# Travis changed this after clogin was installed
		recip_name = recip.first_name
		return render_to_response('mail/new.html', {
	  		'form':form,
	  		'user_id':user_id,
	  		'user_name':recip_name
      		},context_instance=RequestContext(request))

new = login_required(new)

def inbox(request):

	if request.GET.has_key('tab') and (request.GET['tab'] in ['inbox', 'sent']):
		tab = request.GET['tab']
	else:
		tab = 'inbox'

	if tab == 'inbox':
		messages = request.user.messages.filter().order_by('-sent')
		for msg in messages:
			msg.read = MailMessage.objects.get(recipient=request.user.id, message = msg.id).read
			msg.message = msg.hex_msg
			msg.subject = msg.hex_subject
	else:
		messages = SentMessage.objects.filter(sender=request.user).order_by('-sent')
		for msg in messages:
			msg.read = True#MailMessage.objects.get(message=msg).read
			msg.recipient = User.objects.get(id=msg.recipient.id)#MailMessage.objects.get(message = msg.id).recipient
			msg.message = msg.hex_msg
			msg.subject = msg.hex_subject

	return render_to_response('mail/inbox.html', {
	  		'user_name':request.user.first_name,
	  		'user_messages':messages,
	  		'tab':tab
      		},context_instance=RequestContext(request))

inbox = login_required(inbox)

def view_message(request):
	use_sent = False

	if request.method == 'POST':
		#means we have a reply to our message, lets get the stuff we need.
		form = ReplyForm(request.POST)

		if form.is_valid():
			msg_id = request.POST.get('msg_id')
			try:
				original_msg = Message.objects.get(id=msg_id)
			except Message.DoesNotExist:
				use_sent = True
				original_msg = SentMessage.objects.get(id=msg_id)

			sender_id = original_msg.sender.id

			message = form.cleaned_data['message']
			subject = 'Re: ' + SentMessage.objects.get(id=msg_id).hex_subject

			if sender_id == request.user.id:
				if not use_sent:
					mm_recip = original_msg.recipients.filter()
					for rec in mm_recip:
						new_recip = rec.id
					sender = User.objects.get(id=request.user.id)
					recip = User.objects.get(id=new_recip)
				else:
					sender = User.objects.get(id=request.user.id)
					recip = User.objects.get(id=SentMessage.objects.get(id=msg_id).recipient.id)
			else:
				recip = User.objects.get(id=sender_id)
				sender = User.objects.get(id=request.user.id)

			msg = Message()
			msg.sender = sender
			msg.hex_subject = subject
			msg.hex_msg = message + "

" + block_quote_from_text(original_msg.hex_msg, original_msg.sender.first_name)
			msg.save()

			smsg = SentMessage()
			smsg.id = msg.id
			smsg.sender = sender
			smsg.hex_subject = subject
			smsg.recipient = recip
			smsg.hex_msg = message + "

" + block_quote_from_text(original_msg.hex_msg, original_msg.sender.first_name)
			smsg.save()

			if sender_id == request.user.id:
				mm = MailMessage(recipient=recip, message=msg, read=False)
				mm.save()
			else:
				mm = MailMessage(recipient=recip, message=msg, read=False)
				mm.save()

			request.user.message_set.create(message='Reply Sent')

			try:
				user_settings = User_Settings.objects.get(user=recip)
			except User_Settings.DoesNotExist:
				us = User_Settings()
				us.user = recip
				us.save()
				user_settings = User_Settings.objects.get(user=recip)

			used_emails = []
			if user_settings.receive_blast_emails == True:
				if recip.email not in used_emails:
					used_emails.append(recip.email)

			title = """New message on StarfishCommunity.net """
			message = settings.PRIVATE_MESSAGE_EMAIL % (
			   sender.first_name,
			   subject,
			   get_post_preview(message),
			   settings.SITE_ROOT_URL + "/mail/inbox",
			   settings.SITE_ROOT_URL + "/discuss/unsubscribe/" + str(recip.id) + "/" + hashlib.md5(str(recip.id) + recip.email).hexdigest()
			   )

			send_mail(title, message, settings.FROM_EMAIL_ADDRESS, used_emails)
			return HttpResponseRedirect('/mail/inbox') # Redirect after POST
		else:
			request.user.message_set.create(message="An Error Occurred.  This shouldn't happen.")
			return HttpResponseRedirect('/mail/inbox') # Redirect after POST

	else:
		#if its not a POST, then its a page request, so lets get the data we need and send the page through
		msg_id = request.GET.get('id')
		try:

			original_msg = Message.objects.get(id=msg_id)

		except Message.DoesNotExist:
			try:
				original_msg = SentMessage.objects.get(id=msg_id)
			except SentMessage.DoesNotExist:
				#someones just inputing random ids....bad user
				raise Http404
			if request.user.id == original_msg.sender.id:
				sender_id = original_msg.sender.id
				deletable = False
				message = SentMessage.objects.get(id=request.GET.get('id'))
				message.subject = message.hex_subject
				message.message = message.hex_msg

				form = ReplyForm()
				return render_to_response('mail/message.html', {
					'form':form,
	  				'message':message,
	  				'deletable':deletable
      				},context_instance=RequestContext(request))
			else:
				raise Http404

		sender_id = original_msg.sender.id
		mm = MailMessage.objects.get(message=request.GET.get('id'))

		if request.user.id == sender_id or request.user.id == mm.recipient.id:
			pass
		else:
			raise Http404

		if request.user.id == sender_id and original_msg.broadcast == False:
			deletable = False
			pass
		else:
			deletable = True
			mm = MailMessage.objects.get(message=request.GET.get('id'))
			mm.read = True
			mm.save()

		form = ReplyForm()
		message = Message.objects.get(id=request.GET.get('id'))
		message.subject = message.hex_subject
		message.message = message.hex_msg

		return render_to_response('mail/message.html', {
				'form':form,
	  			'message':message,
	  			'deletable':deletable
      			},context_instance=RequestContext(request))

view_message = login_required(view_message)

def delete_message(request):

	if request.method == 'POST':
		msg_id = request.POST.get('msg_id')
		msg = Message.objects.get(id=msg_id)

		msg.delete()

		request.user.message_set.create(message='Message Deleted')
		return HttpResponseRedirect('/mail/inbox') # Redirect after POST

def get_post_preview(markdown_text):
   from BeautifulSoup import BeautifulSoup
   from markdown import markdown

   post_html = markdown(markdown_text)
   post_text = ''.join(BeautifulSoup(post_html).findAll(text=True))
   post_words = post_text.split(' ')
   post_text = ' '.join(post_words)

   return post_text


"""
Copyright 2019 EUROCONTROL
==========================================

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
   disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
   disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

==========================================

Editorial note: this license is an instance of the BSD license template as provided by the Open Source Initiative:
http://opensource.org/licenses/BSD-3-Clause

Details on EUROCONTROL: http://www.eurocontrol.int
"""
import pytest

from broker_rest_client.models import RabbitMQUserPermissions, RabbitMQUser

__author__ = "EUROCONTROL (SWIM)"

@pytest.mark.parametrize('permissions_object, expected_permissions_dict', [
    (
        RabbitMQUserPermissions(configure=".*", write=".*", read=".*"),
        {'configure': '.*', 'write': ".*", 'read': ".*"}
    ),
    (
        RabbitMQUserPermissions(configure="", write="", read=""),
        {'configure': '', 'write': "", 'read': ""}
    )
])
def test_rabbitmquserpermissions__to_json(permissions_object, expected_permissions_dict):
    assert permissions_object.to_json() == expected_permissions_dict

@pytest.mark.parametrize('user_dict, expected_object', [
    (
        {'name': 'username', 'tags': "administrator,management"},
        RabbitMQUser(name='username', tags=['administrator', 'management'])
    ),
    (
        {'name': 'username', 'tags': ""},
        RabbitMQUser(name='username')
    )
])
def test_rabbitmquser__from_json(user_dict, expected_object):
    assert RabbitMQUser.from_json(user_dict) == expected_object


# -*- coding: utf-8 -
from __future__ import absolute_import, unicode_literals

# Arquivo criado para encapsular as funções dos boletos

"""
def modulo_11

Anexo 2 – Cálculo do DAC do Código de Barras - Pagina 43
Método (Módulo 11)
	Por definição da FEBRABAN e do Banco Central do Brasil,
		na 5a posição do Código de Barras, deve ser
		indicado obrigatoriamente o “dígito verificador” (DAC),
		calculado através do módulo 11, conforme
		demonstramos a seguir:

a) Tomando-se os 43 algarismos que compõem o Código de Barras
	(sem considerar a 5a posição),
	multiplique-os, iniciando-se da direita para a esquerda,
	pela seqüência numérica de 2 a 9 ( 2, 3, 4, 5, 6, 7, 8,
	9, 2, 3, 4... e assim por diante);

b) Some o resultado de cada produto efetuado e determine
		o total como (N);
c) Divida o total (N) por 11 e determine o resto obtido
		da divisão como Mod 11(N);
d) Calcule o dígito verificador (DAC) através da expressão:

DAC = 11 - Mod 11(N)

OBS.: Se o resultado desta for igual a 0, 1, 10 ou 11, considere DAC = 1.

"""
def modulo_11(num):
	"""
	 Usando o exemplo como base
	num = '3419166700000123451101234567880057123457000'

	Onde:

	341				= Código do Banco
	9				= Código da Moeda
	?				= DAC do Código de Barras
	1667			= Fator de Vencimento			(01/05/2002)
	0000012345		= Valor do Título				(123,45)
	110123456788	= Carteira / Nosso Número/DAC	(110/12345678-8)
	0057123457		= Agência / Conta Corrente/DAC	(0057/12345-7)
	000				= Posições Livres				(zeros)
	"""

	num = str(num)

	soma = 0
	numero = {}

	# Montando o multiplicador
	multiplicador = []
	for i in range(1,10):
		for j in range(2,10):
			multiplicador.append(j)

	num_inv = num[::-1]

	for i in range(0, len(num_inv)):
		soma = soma + int(num_inv[i])*int(multiplicador[i])

	# Determina-se o resto da Divisão por 11
	resto = soma % 11

	# Calcula-se o DAC:
	DAC = 11 - resto

	# Obs descrita acima
	if DAC == 0  or DAC == 1 or DAC == 10 or DAC == 11:
		DAC = 1

	# Reestruturando a sequencia
	num = num[0:4] + str(DAC) + num[4:]

	return num

"""
Método (Módulo 10) - Página 44
	Conforme demonstrado no item “4” deste manual, a representação
		numérica do código de barras é composta,
		por cinco campos: 1, 2, 3 4 e 5, sendo os três primeiros
		amarrados por DAC's, calculados pelo módulo 10,
		conforme mostramos abaixo:

	a) Multiplica-se cada algarismo do campo pela seqüência de
		multiplicadores 2, 1, 2, 1, 2, 1..., posicionados
		da direita para a esquerda;
	b) Some individualmente, os algarismos dos resultados dos
		produtos, obtendo-se o total (N);
	c) Divida o total encontrado (N) por 10, e
		determine o resto da divisão como MOD 10 (N);
	d) Encontre o DAC através da seguinte expressão:
		DAC = 10 – Mod 10 (N)

	OBS.: Se o resultado da etapa d for 10, considere o DAC = 0.
"""
def modulo_10(num):

	num = str(num)

	soma = 0

	# Montagem da sequencia padrão
	seq12 = []

	for i in range(1,60, 2):
		seq12.append(2)
		seq12.append(1)

	num_inv = num[::-1]

	# Multiplicando a seqüência dos campos pelo módulo 10
	for i in range(0, len(num_inv)):
		soma = soma + int(num_inv[i])*seq12[i]

	# Mod10 (soma)
	mod10 = soma % 10

	# DAC
	DAC = 10 - mod10

	# Obs descrita acima
	if DAC == 10:
		DAC = 0

	return num + str(DAC)

# Alterada por Glauber Portella para especificação do Itaú
def MontaLinhaDigitalizavel(codigo):

	codigo = str(codigo)

	# campo 1
	banco    = codigo[0:3]
	moeda    = codigo[3:4]
	ccc      = codigo[19:22]
	ddnnum   = codigo[22:24]
	dv1      = modulo_10(banco + moeda + ccc + ddnnum)

	# campo 2
	resnnum  = codigo[24:30]
	dac1     = codigo[30:31] #modulo_10(agencia.conta.carteira.nnum)
	dddag    = codigo[31:34]
	dv2      = modulo_10(resnnum + dac1 + dddag)

	# campo 3
	resag    = codigo[34:35]
	contadac = codigo[35:41] # substr(codigo,35,5).modulo_10(substr(codigo,35,5))
	zeros    = codigo[41:44]
	dv3      = modulo_10(resag + contadac + zeros)

	# campo 4
	dv4      = codigo[4:5]

	# campo 5
	fator    = codigo[5:9]
	valor    = codigo[9:19]

	# XXX: Ver isso aqui
	campo1 = (banco + moeda + ccc + ddnnum + dv1)[0:5] + '.' + (banco + moeda + ccc + ddnnum + dv1)[5:10]
	campo2 = (resnnum + dac1 + dddag + dv2)[0:5] + '.' + (resnnum + dac1 + dddag + dv2)[5:11]
	campo3 = (resag + contadac + zeros + dv3)[0:5] + '.' + (resag+contadac+zeros+dv3)[5:11]

	campo4 = dv4
	campo5 = fator + valor

	return campo1 + ' ' + campo2 +' ' + campo3 + ' ' + campo4 + ' ' + campo5

# Retorna o Digito verificador
def DigitoCodigoBanco(num):
	codigo = modulo_11(num)
	DAC = codigo[4:5]
	return str(DAC)

# Retorna o codigo formatado da agencia conta
def AgenciaConta(agencia, conta):
	num = str(agencia) + str(conta)
	cod = (modulo_10(num))[4:5]
	return agencia + ' / ' + conta + ' - ' + cod

#def NossoNumero():
#	nossonumero = carteira.'/'.nnum.'-'.modulo_10(agencia.conta.carteira.nnum)

'''

def geraCodigoBanco(numero)
	parte1 = substr(numero, 0, 3)
	parte2 = modulo_11(parte1)
	return parte1 + "-" + parte2

def barCode():
	codigobanco = "341"
	codigo_banco_com_dv = geraCodigoBanco(codigobanco)
	nummoeda = "9"
	fator_vencimento = fator_vencimento(dadosboleto["data_vencimento"])

	# Valor tem 10 digitos, sem virgula
	valor = formata_numero(dadosboleto["valor_boleto"],10,0,"valor")

	# Agencia é 4 digitos
	agencia = formata_numero(dadosboleto["agencia"],4,0)

	# Conta é 5 digitos + 1 do dv
	conta = formata_numero(dadosboleto["conta"],5,0)
	conta_dv = formata_numero(dadosboleto["conta_dv"],1,0)

	# Carteira 175
	carteira = $dadosboleto["carteira"]

	# Nosso_numero no maximo 8 digitos
	nnum = formata_numero(dadosboleto["nosso_numero"],8,0)

	codigo_barras = codigobanco+nummoeda+fator_vencimento+valor+carteira+nnum+modulo_10(agencia+conta+carteira+nnum)+agencia+conta+modulo_10(agencia+conta)+'000'

	return codigo_barras

	# 43 numeros para o calculo do digito verificador
	dv = digitoVerificador_barra(codigo_barras);
	// Numero para o codigo de barras com 44 digitos
	$linha = substr($codigo_barras,0,4).$dv.substr($codigo_barras,4,43);

	$nossonumero = $carteira.'/'.$nnum.'-'.modulo_10($agencia.$conta.$carteira.$nnum);
	$agencia_codigo = $agencia." / ". $conta."-".modulo_10($agencia.$conta);

	$dadosboleto["codigo_barras"] = $linha;
	$dadosboleto["linha_digitavel"] = monta_linha_digitavel($linha); // verificar
	$dadosboleto["agencia_codigo"] = $agencia_codigo ;
	$dadosboleto["nosso_numero"] = $nossonumero;
	$dadosboleto["codigo_banco_com_dv"] = $codigo_banco_com_dv;

// FUNÇÕES
// Algumas foram retiradas do Projeto PhpBoleto e modificadas para atender as particularidades de cada banco

function digitoVerificador_barra($numero) {
	$resto2 = modulo_11($numero, 9, 1);
	$digito = 11 - $resto2;
     if ($digito == 0 || $digito == 1 || $digito == 10  || $digito == 11) {
        $dv = 1;
     } else {
        $dv = $digito;
     }
	 return $dv;
}

function formata_numero($numero,$loop,$insert,$tipo = "geral") {
	if ($tipo == "geral") {
		$numero = str_replace(",","",$numero);
		while(strlen($numero)<$loop){
			$numero = $insert . $numero;
		}
	}
	if ($tipo == "valor") {
		/*
		retira as virgulas
		formata o numero
		preenche com zeros
		*/
		$numero = str_replace(",","",$numero);
		while(strlen($numero)<$loop){
			$numero = $insert . $numero;
		}
	}
	if ($tipo == "convenio") {
		while(strlen($numero)<$loop){
			$numero = $numero . $insert;
		}
	}
	return $numero;
}

function fbarcode($valor){

$fino = 1 ;
$largo = 3 ;
$altura = 50 ;

  $barcodes[0] = "00110" ;
  $barcodes[1] = "10001" ;
  $barcodes[2] = "01001" ;
  $barcodes[3] = "11000" ;
  $barcodes[4] = "00101" ;
  $barcodes[5] = "10100" ;
  $barcodes[6] = "01100" ;
  $barcodes[7] = "00011" ;
  $barcodes[8] = "10010" ;
  $barcodes[9] = "01010" ;
  for($f1=9;$f1>=0;$f1--){
    for($f2=9;$f2>=0;$f2--){
      $f = ($f1 * 10) + $f2 ;
      $texto = "" ;
      for($i=1;$i<6;$i++){
        $texto .=  substr($barcodes[$f1],($i-1),1) . substr($barcodes[$f2],($i-1),1);
      }
      $barcodes[$f] = $texto;
    }
  }

//Desenho da barra

//Guarda inicial
?><img src=imagens/p.png width=<?php echo $fino?> height=<?php echo $altura?> border=0><img
src=imagens/b.png width=<?php echo $fino?> height=<?php echo $altura?> border=0><img
src=imagens/p.png width=<?php echo $fino?> height=<?php echo $altura?> border=0><img
src=imagens/b.png width=<?php echo $fino?> height=<?php echo $altura?> border=0><img
<?php
$texto = $valor ;
if((strlen($texto) % 2) <> 0){
	$texto = "0" . $texto;
}

// Draw dos dados
while (strlen($texto) > 0) {
  $i = round(esquerda($texto,2));
  $texto = direita($texto,strlen($texto)-2);
  $f = $barcodes[$i];
  for($i=1;$i<11;$i+=2){
    if (substr($f,($i-1),1) == "0") {
      $f1 = $fino ;
    }else{
      $f1 = $largo ;
    }
?>
    src=imagens/p.png width=<?php echo $f1?> height=<?php echo $altura?> border=0><img
<?php
    if (substr($f,$i,1) == "0") {
      $f2 = $fino ;
    }else{
      $f2 = $largo ;
    }
?>
    src=imagens/b.png width=<?php echo $f2?> height=<?php echo $altura?> border=0><img
<?php
  }
}

// Draw guarda final
?>
src=imagens/p.png width=<?php echo $largo?> height=<?php echo $altura?> border=0><img
src=imagens/b.png width=<?php echo $fino?> height=<?php echo $altura?> border=0><img
src=imagens/p.png width=<?php echo 1?> height=<?php echo $altura?> border=0>
  <?php
} //Fim da função

function esquerda($entra,$comp){
	return substr($entra,0,$comp);
}

function direita($entra,$comp){
	return substr($entra,strlen($entra)-$comp,$comp);
}

function fator_vencimento($data) {
	$data = explode("/",$data);
	$ano = $data[2];
	$mes = $data[1];
	$dia = $data[0];
    return(abs((_dateToDays("1997","10","07")) - (_dateToDays($ano, $mes, $dia))));
}

function _dateToDays($year,$month,$day) {
    $century = substr($year, 0, 2);
    $year = substr($year, 2, 2);
    if ($month > 2) {
        $month -= 3;
    } else {
        $month += 9;
        if ($year) {
            $year--;
        } else {
            $year = 99;
            $century --;
        }
    }
    return ( floor((  146097 * $century)    /  4 ) +
            floor(( 1461 * $year)        /  4 ) +
            floor(( 153 * $month +  2) /  5 ) +
                $day +  1721119);
}

?
'''


def print_limerick(L):
    for i in range(len(L)):
        for k in range(len(L[i])):
            print(L[i][k], end=' ')
        print()

def lenghts(L):
    words = 0
    chars = 0
    for i in range(len(L)):
        words += len(L[i])
        for k in range(len(L[i])):
            chars += len(L[i][k])
    return words, chars

limerick = [
    ['There', 'was', 'a', 'young', 'lady', 'named', 'Wright'],
    ['Whose', 'speed', 'was', 'much', 'faster', 'than', 'light'],
    ['She', 'left', 'home', 'one', 'day'],
    ['In', 'a', 'relative', 'way'],
    ['And', 'returned', 'on', 'the', 'previous', 'night']
]

print_limerick(limerick)
print(lenghts(limerick))


# Gerekli kütüphanelerin import edilmesi
import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util
import lirc

client = lirc.Client( #LIRC client oluşturulması
  connection=lirc.LircdConnection(
    #address="/var/run/lirc/lircd",
    #socket=socket.socket(socket.AF_UNIX, socket.SOCK_STREAM),
    timeout = None
  )
)

class VideoStream:
    # Pi kamera modülünün aktifleştirilmesi ve görüntü akışının sağlanması
    def __init__(self,resolution=(640,480),framerate=30):
        self.stream = cv2.VideoCapture(0)
        ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
        ret = self.stream.set(3,resolution[0])
        ret = self.stream.set(4,resolution[1])

        # Kameradan gelen ilk karenin okunması
        (self.grabbed, self.frame) = self.stream.read()

# Kamerayı durdurmak için kullanılan değişken
        self.stopped = False

    def start(self):
# Kareleri okuyan thread in başlatılması
        Thread(target=self.update,args=()).start()
        return self

    def update(self):
        # Thread durana kadar dönen sonsuz döngü
        while True:
            # Kamera durduysa thread i durdur
            if self.stopped:
                self.stream.release()
                return

            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
	# En yeni kareyi dön
        return self.frame

    def stop(self):
	# Kamera ve thread i durdurmak için kullanılan fonksiyon
        self.stopped = True

# Giriş argümanlarını tanımla ve böl
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
                    required=True)
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
                    default='detect.tflite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',
                    default='labelmap.txt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
                    default=0.7)
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
                    default='1280x720')

args = parser.parse_args()

MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
min_conf_threshold = float(args.threshold)
resW, resH = args.resolution.split('x')
imW, imH = int(resW), int(resH)

# Tenserflow kütüphanelerinin importlanması
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
    from tflite_runtime.interpreter import Interpreter

else:
    from tensorflow.lite.python.interpreter import Interpreter

# Açık olan klasörün dosya konumunun bulunması
CWD_PATH = os.getcwd()

# İçerisinde obje tespit modelini barındıran .tflite dosya konumuna ulaşılması
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)

# Label map dosyasının bulunması
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)

# Label map dosyasının yüklenmesi
with open(PATH_TO_LABELS, 'r') as f:
    labels = [line.strip() for line in f.readlines()]

# Label mapde ufak bir düeltme
if labels[0] == '???':
    del(labels[0])

# Tensorflow Lite modelinin yüklenmesi
interpreter = Interpreter(model_path=PATH_TO_CKPT)

interpreter.allocate_tensors()

# Model detaylarının alınması
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]

floating_model = (input_details[0]['dtype'] == np.float32)

input_mean = 127.5
input_std = 127.5

# Video yayının başlaması
videostream = VideoStream(resolution=(imW,imH),framerate=30).start()
time.sleep(1)

while True:

    # Video yayınından karelerin alınması
    frame1 = videostream.read()

    # Yayından alınan karelerin istenilen boyuta getirilmesi
    frame = frame1.copy()
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame_resized = cv2.resize(frame_rgb, (width, height))
    input_data = np.expand_dims(frame_resized, axis=0)

    # Pixel değerlerinin normalize edilmesi
    if floating_model:
        input_data = (np.float32(input_data) - input_mean) / input_std

    #Karenin girdi olarak verilip hareket tespitinin yapılması
    interpreter.set_tensor(input_details[0]['index'],input_data)
    interpreter.invoke()

    # Tespit sonuçlarının alınması
    boxes = interpreter.get_tensor(output_details[0]['index'])[0] # El hareketinin kordinatlarının bulunması
    classes = interpreter.get_tensor(output_details[1]['index'])[0] # Tespit edilen hareketin sınıfı
    scores = interpreter.get_tensor(output_details[2]['index'])[0] # Tespit edilen objenin doğruluğu

    # Tespit edilen tüm hareketlere bak ve en yüksek doğruluğu olanı bul
    for i in range(len(scores)):
        if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):

            ymin = int(max(1,(boxes[i][0] * imH)))
            xmin = int(max(1,(boxes[i][1] * imW)))
            ymax = int(min(imH,(boxes[i][2] * imH)))
            xmax = int(min(imW,(boxes[i][3] * imW)))

            # Etiketi çiz
            object_name = labels[int(classes[i])] # Obje isimlerini label lara bakarak bul
            label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Label ve doğruluğu belirle
            labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Font boyutu
            label_ymin = max(ymin, labelSize[1] + 10)
            cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED)
            cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Label ı ekrana yazdır

            if object_name == 'volumeup': # Volumeup hareketi algılanırsa Volumeup sinyalini gönder
                client.send_start("mamur", "KEY_VOLUMEUP")
                client.send_stop("mamur", "KEY_VOLUMEUP")
                time.sleep(0.5)

            if object_name == 'volumedown': # Volumedown hareketi algılanırsa Volumedown sinyalini gönder
                client.send_start("mamur", "KEY_VOLUMEDOWN")
                client.send_stop("mamur", "KEY_VOLUMEDOWN")
                time.sleep(0.5)

            if object_name == 'channelnext': # channelnext hareketi algılanırsa channelup sinyalini gönder
                client.send_start("mamur", "KEY_CHANNELUP")
                client.send_stop("mamur", "KEY_CHANNELUP")
                time.sleep(0.5)

            if object_name == 'channelpre': # channelpre hareketi algılanırsa channeldown sinyalini gönder
                client.send_start("mamur", "KEY_CHANNELDOWN")
                client.send_stop("mamur", "KEY_CHANNELDOWN")
                time.sleep(0.5)

            if object_name == 'n1': # n1 hareketi algılanırsa 1 sinyalini gönder
                client.send_start("mamur", "BTN_1")
                client.send_stop("mamur", "BTN_1")
                time.sleep(0.5)

            if object_name == 'n2': # n2 hareketi algılanırsa 2 sinyalini gönder
                client.send_start("mamur", "BTN_2")
                client.send_stop("mamur", "BTN_2")
                time.sleep(0.5)

            if object_name == 'n3': # n3 hareketi algılanırsa 3 sinyalini gönder
                client.send_start("mamur", "BTN_3")
                client.send_stop("mamur", "BTN_3")
                time.sleep(0.5)

            if object_name == 'n4': # n4 hareketi algılanırsa 4 sinyalini gönder
                client.send_start("mamur", "BTN_4")
                client.send_stop("mamur", "BTN_4")
                time.sleep(0.5)

            if object_name == 'n5': # n5 hareketi algılanırsa 5 sinyalini gönder
                client.send_start("mamur", "BTN_5")
                client.send_stop("mamur", "BTN_5")
                time.sleep(0.5)

            if object_name == 'n6': # n6 hareketi algılanırsa 6 sinyalini gönder
                client.send_start("mamur", "BTN_6")
                client.send_stop("mamur", "BTN_6")
                time.sleep(0.5)

            if object_name == 'n7': # n7 hareketi algılanırsa 7 sinyalini gönder
                client.send_start("mamur", "BTN_7")
                client.send_stop("mamur", "BTN_7")
                time.sleep(0.5)

            if object_name == 'n8': # n8 hareketi algılanırsa 8 sinyalini gönder
                client.send_start("mamur", "BTN_8")
                client.send_stop("mamur", "BTN_8")
                time.sleep(0.5)

            if object_name == 'n9': # n9 hareketi algılanırsa 9 sinyalini gönder
                client.send_start("mamur", "BTN_9")
                client.send_stop("mamur", "BTN_9")
                time.sleep(0.5)

            if object_name == 'n0': # n0 hareketi algılanırsa 0 sinyalini gönder
                client.send_start("mamur", "BTN_0")
                client.send_stop("mamur", "BTN_0")
                time.sleep(0.5)

            if object_name == 'mute': # mute hareketi algılanırsa mute sinyalini gönder
                client.send_start("mamur", "KEY_MUTE")
                client.send_stop("mamur", "KEY_MUTE")
                time.sleep(0.5)

            if object_name == 'menu': # menu hareketi algılanırsa menu sinyalini gönder
                client.send_start("mamur", "KEY_MENU")
                client.send_stop("mamur", "KEY_MENU")
                time.sleep(0.5)

            if object_name == 'ok': # ok hareketi algılanırsa ok sinyalini gönder
                client.send_start("mamur", "KEY_OK")
                client.send_stop("mamur", "KEY_OK")
                time.sleep(0.5)

            if object_name == 'exit': # exit hareketi algılanırsa exit sinyalini gönder
                client.send_start("mamur", "KEY_EXIT")
                client.send_stop("mamur", "KEY_EXIT")
                time.sleep(0.5)

            if object_name == 'power': # power hareketi algılanırsa power sinyalini gönder
                client.send_start("mamur", "KEY_POWER")
                client.send_stop("mamur", "KEY_POWER")
                time.sleep(0.5)

    # Hesaplanan sonuçların kareye çizdirilmesi
    cv2.imshow('Object detector', frame)

#    time.sleep(1)
    # Kapatmak için q tuşuna basılır
    if cv2.waitKey(1) == ord('q'):
        break

# Pencerelerin kapatılması
cv2.destroyAllWindows()
videostream.stop()


"""

Li-O2 Battery Model:
    This model examines the reactions taking place within the carbon-based
    cathode of a Li-O2 battery. Electrolyte = 1 M LiTFSI in TEGDME

"""

""" Load any needed modules """
"============================================================================"
# Brings in other complex commands as shortcuts
# Shortcut so that code doesn't need to be written out again
import matplotlib.pyplot as plt    # Plotting functions
from scipy.integrate import solve_ivp    #Integrator

""" Read user inputs and initialize variables, vectors, etc. """
"============================================================================"
from li_o2_init import objs, params, SVptr, pltptr, SV_0, tspan, li_o2_residual

# Solve function using IVP solver
SV = solve_ivp(lambda t, y: li_o2_residual(t,y,params,objs,SVptr), [0, tspan], \
     SV_0, method='BDF',atol=params['atol'],rtol=params['rtol'])

""" Plot solutions to concentrations and potentials """
"============================================================================"
legends = []
[legends.append(str(i+1)) for i in range(params['N_y'])]

plt.figure(1)
[plt.plot(SV.t,-SV.y[SVptr['phi_dl']][j]) for j in range(params['N_y'])]
plt.xlabel('Time (s)')
plt.ylabel('Double Layer Potential (V)')
plt.legend(legends)

plt.figure(2)
[plt.plot(SV.t,SV.y[SVptr['eps oxide'][j]]) for j in range(params['N_y'])]
plt.xlabel('Time (s)')
plt.ylabel('Oxide volume fraction')
plt.legend(legends)

oxide = objs['oxide']
elyte = objs['elyte']

eps_oxide = SV.y[SVptr['eps oxide']]    # oxide volume fraction
eps_elyte = params['eps_elyte_0'] - (eps_oxide - params['eps_oxide_0'])
A_int_avail = params['A_int'] - eps_oxide / params['th_oxide']

plt.figure(3)
[plt.plot(SV.t,eps_elyte[j]) for j in range(params['N_y'])]
plt.xlabel('Time (s)')
plt.ylabel('Elyte Volume Fraction')
plt.legend(legends)

plt.figure(4)
[plt.plot(SV.t, SV.y[SVptr['rho_k elyte'][j,2]]/eps_elyte[j]) for j in range(params['N_y'])]
plt.xlabel('Time (s)')
plt.ylabel(elyte.species_names[2]+' kg/m3')
plt.legend(legends)

plt.figure(7)
[plt.plot(SV.t, SV.y[SVptr['rho_k elyte'][j,2]]) for j in range(params['N_y'])]
plt.xlabel('Time (s)')
plt.ylabel(elyte.species_names[2]+' kg/m3')
plt.legend(legends)

plt.figure(5)
[plt.plot(SV.t, SV.y[SVptr['rho_k elyte'][j,4]]) for j in range(params['N_y'])]
plt.xlabel('Time (s)')
plt.ylabel(elyte.species_names[4]+' kg/m3')
plt.legend(legends)

plt.figure(6)
plt.plot(SV.t,A_int_avail[0,:])
plt.xlabel('Time (s)')
plt.ylabel('Available Area (m2)')

plt.show()

#plt.figure(3)
#plt.plot(SV.t,SV.y[pltptr['O2']],SV.t,SV.y[pltptr['Li+']],SV.t,SV.y[pltptr['PF6-']],SV.t,SV.y[pltptr['EC']],SV.t,SV.y[pltptr['EMC']])
#plt.legend(['O2','Li+','PF6-','EC','EMC'])
#plt.xlabel('Time (s)')
#plt.ylabel('Electrolyte Concentration (kg/m3)')
#plt.show()

#t = SV.t
#dl = SV.y[SVptr['phi_dl']]
#Ck_ox = SV.y[SVptr['oxide']]
#
#df = DataFrame({'Time': t, 'Double Layer': dl, 'Oxide Concentration': Ck_ox})
#
#with ExcelWriter('path_to_file.xlsx') as writer:
#    df.to_excel(writer)


import os
import glob
from PIL import Image

# iphone5分辨率：1136×640
# 图片是可以旋转的，也就是长和宽可以互换。1136×640以下和640×1136以下图片都符合要求
# 因此获取图片的长边和1136比，短边和640比，哪个比值大说明要按哪个比值来缩放

# 图片输入目录、输出目录
input_dir = './0005/input_img'
output_dir = './0005/output_img'
#遍历图片，并修改保存
for file in glob.glob(input_dir + '/*.jpg'):
    img = Image.open(file)
    h , w = img.size[0] , img.size[1]
    scale = max( max(h , w) / 1136 , min(h , w) / 640)
    if scale > 1:
        try:
            img = img.resize((int(h/scale),int(w/scale)),Image.BILINEAR)
            img.save(os.path.join(output_dir,os.path.basename(file)))
        except Exception as e:
            print(e)


from pathlib import Path
from datetime import datetime
from shutil import rmtree
from rsm_lib.common import logger
from rsm_lib.database.models import Migration
from rsm_lib.database.common import Session

class MigrationManager:
    migrations_path = Path().cwd().absolute() / 'migrations'

    def __init__(self):
        pass

    def create_migrations_directory(self):
        try:
            self.migrations_path.mkdir(exist_ok=False)
            logger.info('migrations directory not found. Created directory ./migrations successfully. ')
        except FileExistsError:
            pass

    @staticmethod
    def get_file_id(name):
        file_id = datetime.utcnow().strftime('%Y-%m-%d-%H%M%s')
        return f'{file_id}-{name}'

    @staticmethod
    def get_template_path():
        return Path(__file__).parent / 'migration_template.yml'

    def get_migration_path(self, file_name):
        return self.migrations_path / f'{file_name}' / f'{file_name}.yml'

    @staticmethod
    def create_migration_directories(migration_path, template_path):
        sub_dir_names = ['up', 'down']

        for name in sub_dir_names:
            sub_dir = migration_path.parent / name
            sub_dir.mkdir(parents=True)
            sql_path = sub_dir / 'migration.sql'
            sql_path.touch()
            sql_path.write_text('-- put your migration here')

        migration_path.touch()
        migration_path.write_text(template_path.read_text())

    @staticmethod
    def add_migration_db(migration_id, db_session):
        migration = Migration(migration_id)
        db_session.add(migration)

    @staticmethod
    def remove_migration_directories(migration_path):
        rmtree(migration_path.parent.absolute().as_posix())

def create_new_migration(name):

    # first create a migration manager and the parent dir if it does not exist
    migration_manager = MigrationManager()
    migration_manager.create_migrations_directory()

    migration_id = migration_manager.get_file_id(name)
    db_session = Session()

    try:
        logger.info(f'creating migration with id {migration_id}')
        template_path = migration_manager.get_template_path()
        migrations_path = migration_manager.get_migration_path(migration_id)
        migration_manager.add_migration_db(migration_id, db_session)

        logger.info(f'migration added to database. creating migration directories')
        migration_manager.create_migration_directories(migrations_path, template_path)

        logger.info(f'committing migration {migration_id} to database.')
        db_session.commit()

        logger.info(f'migration {migration_id} created successfully!')
    except Exception:
        logger.exception(f'there was a creating the migration {migration_id}. check logs')
        db_session.rollback()
        migration_manager.remove_migration_directories(migrations_path)
        raise

    finally:
        logger.info('migration finished')


"""
===================
pcolormesh(X, Y, Z)
===================

`~.axes.Axes.pcolormesh` is more flexible than `~.axes.Axes.imshow` in that
the x and y vectors need not be equally spaced (indeed they can be skewed).

"""
import matplotlib.pyplot as plt
import numpy as np

plt.style.use('mpl_plot_gallery')

# make full-res data
X, Y = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Z = (1 - X/2. + X**5 + Y**3) * np.exp(-X**2 - Y**2)
Z = Z - Z.min()

# sample unevenly in x:
dx = np.sqrt((np.arange(16) - 8)**2) + 6
dx = np.floor(dx / sum(dx) * 255)
xint = np.cumsum(dx).astype('int')
X = X[0, xint]
Y = Y[::8, 0]
Z = Z[::8, :][:, xint]

# plot
fig, ax = plt.subplots()
ax.grid(False)

ax.pcolormesh(X, Y, Z, vmin=0, vmax=1.5)

plt.show()


import json

with open('words.txt', 'r') as outfile:
	data = json.load(outfile)

def is_noun(x):
    if x in data['nouns'][0]:
        print(x + " is a noun.")
        return True
    else:
        return False

def is_verb(x):
    if x in data['verbs'][0]:
        print(x + " is a verb.")
        return True
    else:
        return False

def is_particle(x):
    if x in data['particles'][0]:
        print(x + " is a particle")
        return True
    else:
        return False

def is_adverb(x):
    if x in data['adverbs'][0]:
        print(x + " is an adverb")
        return True
    else:
        return False

def is_adjective(x):
    if x in data['adjectives'][0]:
        print(x + " is an adjective")
        return True
    else:
        return False

def add_noun(x):
    print(data['nouns'][0])
    data['nouns'][0][x] = 0
    print(data['nouns'][0])

def add_verb(x):
    print(data['verbs'][0])
    data['verbs'][0][x] = 0
    print(data['verbs'][0])

def add_particle(x):
    print(data['particles'][0])
    data['particles'][0][x] = 0
    print(data['particles'][0])

def add_adverb(x):
    print(data['adverbs'][0])
    data['adverbs'][0][x] = 0
    print(data['adverbs'][0])

def add_adjective(x):
    print(data['adjectives'][0])
    data['adjectives'][0][x] = 0
    print(data['adjectives'][0])

def find_word(x):
    noun = is_noun(x)
    verb = is_verb(x)
    particle = is_particle(x)
    adverb = is_adverb(x)
    adjective = is_adjective(x)
    if noun == True:
        print("noun")
    elif verb == True:
        print("verb")
    elif particle == True:
        print("particle")
    elif adverb == True:
        print("particle")
    elif adjective == True:
        print("particle")
    else:
        print("I'm sorry, I don't understant " + x + ".")
        print("Is this a real word or a typo?")
        answer = (input(">> "))
        if answer == "real word":
              print("It is a real word.")
              print("Is it a noun, a verb, adjective, adverb, or a particle?")
              answer_wordtype = input(">> ")
              answer_wordtype = answer_wordtype.lower()
              if answer_wordtype == "noun":
                  add_noun(x)
              if answer_wordtype == "verb":
                  add_verb(x)
              if answer_wordtype == "particle":
                  add_particle(x)
              if answer_wordtype == "adverb":
                  add_adverb(x)
              if answer_wordtype == "adjective":
                  add_adjective(x)
        elif answer == "type":
              print("Could you correct the word for me?")
        else:
              print("I'm sorry, I don't understand.")
              print("Please enter real word or type.")

#We've put the words into parts of speech,
#now we need to identify subjects and objects, etc.
#this is how we will form the sentence.

#script
count = 0
while count < 10:
    print("Give me a sentence")
    sentence = input(">> ")
    sentence = sentence.split()
    print(sentence)
    for x in sentence:
        x = x.lower()
        find_word(x)
    print("Would you like to continue?")
    answer = input(">> ")
    answer = answer.lower()
    if answer == 'no':
        break

#print("In your sentence, " + subj + " " + conjugated_verb + " " + particle + " " + obj + " " + location_particle + " " + location.

print(data)

outfile.close()

with open('words.txt', 'w') as outfile:
	json.dump(data, outfile)
outfile.close()


import imagemounter_mitre.exceptions
import os

from flask import current_app, request
from flask_restful import Resource, marshal_with, abort, fields

from .exceptions import (
    UnexpectedDiskError,
    NoMountableVolumesError,
    ImageNotInDatabaseError,
    DuplicateMountAttemptError
)
from .utils import get_mount_info, get_supported_libraries, mount_image, unmount_image, get_images, add_mountpoint

volume_fields = {
    "size": fields.Integer,
    "offset": fields.Integer,
    "index": fields.Integer,
    "label": fields.String(attribute=lambda obj: obj.info.get("label")),
    "fsdescription": fields.String(attribute=lambda obj: obj.info.get("fsdescription")),
    "fstype": fields.String,
    "mountpoint": fields.String,
}
disk_fields = {
    "name": fields.String(attribute="_name"),
    "imagepath": fields.String(attribute=lambda obj: obj.paths[0]),
    "mountpoint": fields.String,
    "volumes": fields.List(fields.Nested(volume_fields)),
    "paths": fields.Raw(attribute=lambda obj: obj._paths, default=None)
}
disk_mount = {"disk_info": fields.Nested(disk_fields), "ref_count": fields.Integer}

class Mount(Resource):
    """A Mount object that allows you to mount and unmount images.
    """

    def __init__(self):
        """Create a Mount object.
        """
        current_app.logger.debug("Instantiating the Mount class")

    @marshal_with(disk_fields)
    def put(self, image_path):
        """Mounts an image file.

        Parameters
        ----------
        image_path : str
            Relative path to an image file to be mounted.
            This is relative to the Thumbtack server's IMAGE_DIR config variable.
        """
        status = None

        # Create volume-key mapping. Need to find a better appraoch for this
        creds = {}
        if len(request.args.getlist("key")) > 0:
            for i in range(0, 25):
                creds[i] = request.args.getlist("key")[0]
        else:
            creds = None

        try:
            current_app.mnt_mutex.acquire()
            mounted_disk = mount_image(image_path, creds=creds)

            if mounted_disk and mounted_disk.mountpoint is not None:
                current_app.logger.info(f"Image mounted successfully: {image_path}")
                current_app.mnt_mutex.release()
                return mounted_disk

        # TODO: refactor to not duplicate code in the mount_form in views.py
        except imagemounter_mitre.exceptions.SubsystemError:
            status = f"Thumbtack was unable to mount {image_path} using the imagemounter Python library."
        except PermissionError:
            status = f"Thumbtack does not have mounting privileges for {image_path}. Are you running as root?"
        except UnexpectedDiskError:
            status = "Unexpected number of disks. Thumbtack can only handle disk images that contain one disk."
        except NoMountableVolumesError:
            status = f"No volumes in {image_path} were able to be mounted."
        except ImageNotInDatabaseError:
            status = f"Cannot mount {image_path}. Image is not in Thumbtack database."
        except DuplicateMountAttemptError:
            status = "Mount attempt is already in progress for this image. Please wait until the current mount attempt completes."

        current_app.mnt_mutex.release()
        current_app.logger.error(status)
        abort(400, message=str(status))

    @marshal_with(disk_mount)
    def get(self, image_path=None):
        """Retrieve information about tracked images.

        Parameters
        ----------
        image_path : str, optional
            Relative path to an image file.

        Returns
        -------
        dict
            Dictionary of useful information about a mounted disk image or a list of all mounted images.
        """
        mount_info = get_mount_info(image_path)
        if not mount_info:
            # empty list -- nothing mounted -- is ok to return
            if isinstance(mount_info, list):
                return mount_info
            abort(404, message=f"{image_path} not mounted")
        return mount_info

    def delete(self, image_path=None):
        """Unmounts an image file.

        Parameters
        ----------
        image_path : str
            Relative path to an image file to unmount.
        """
        current_app.mnt_mutex.acquire()
        unmount_image(image_path)
        current_app.mnt_mutex.release()

class SupportedLibraries(Resource):
    def get(self):
        return get_supported_libraries()

class Images(Resource):
    def get(self):
        images = get_images()
        # Remove non-serializable parser for api call
        for image in images:
            if "parser" in image:
                image.pop("parser")
        return images

class ImageDir(Resource):
    def put(self):
        image_dir = request.args.getlist("image_dir")[0]
        current_app.config.update(IMAGE_DIR=image_dir)
        return image_dir
    def get(self):
        return current_app.config["IMAGE_DIR"]

class ManualMount(Resource):
    """Mount object that allows users to manually create and add a mountpoint."""

    def __init__(self):
        pass

    def put(self):
        """Adds mountpoint to thumbtack database.

        Parameters
        ----------
        mountpoint_path : str
            Absolute path where the image is mounted
        """

        image_path = request.args.getlist("image_path")[0]
        mountpoint_path = request.args.getlist("mountpoint_path")[0]

        if mountpoint_path is None or mountpoint_path == "":
            status = "No mountpoint provided."
            current_app.logger.error(status)
            abort(400, message=str(status))
        if not os.path.isdir(mountpoint_path):
            status = f"Could not find {mountpoint_path}. Ensure the mountpoint exists before adding it to thumbtack."
            current_app.logger.error(status)
            abort(400, message=str(status))

        mounted_disk = add_mountpoint(image_path, mountpoint_path)
        if mounted_disk:
            status = f"Added mountpoint {mountpoint_path} for image {image_path}"
            return mountpoint_path
        else:
            status = f"Unable to add mountpoint {mountpoint_path} for image {image_path}"
            current_app.logger.error(status)
            abort(400, message=str(status))


#coding=utf-8

from utils import services, GlobalObject, loogoo
from distributed.root import PBRoot, BilateralFactory
from twisted.internet import reactor
from twisted.python import log
import sys
import subprocess
import json
import os

reactor = reactor

rootservice = services.Service("rootservice")
GlobalObject().rootservice = rootservice

class Master(object):
	"""主控服
	"""
	def __init__(self):
		self.configpath = None		#配置文件路径
		self.configdata = {}		#配置数据
		self.pbroot = None			#分布式根节点

	def Config(self, configPath):
		self.configpath = configPath
		self.configdata = json.load(open(configPath, 'r'))
		self.masterconf = self.configdata.get('master', {})

	def Init(self):
		self.mainpath = self.configdata.get("mainpath")
		masterlog = os.path.join(self.mainpath, self.masterconf.get('log'))
		if masterlog:
			log.addObserver(loogoo(masterlog))#日志处理
		log.startLogging(sys.stdout)

		self.InitPBRoot()
		self.InitNetConnectRemote()

	def InitPBRoot(self):
		rootport = self.masterconf.get('rootport')
		self.pbroot = PBRoot()
		self.pbroot.addServiceChannel(rootservice)
		GlobalObject().pbroot = self.pbroot
		reactor.listenTCP(rootport, BilateralFactory(self.pbroot))

	def InitNetConnectRemote(self):
		import netconnect

	def Start(self):
		self.Init()
		reactor.run()