import argparse
import glob
import json
import logging
import os
import platform
import re
import traceback
from pathlib import Path

import fitz

if platform.system() == "Windows":
    logdir = Path(os.environ['USERPROFILE']) / ".pdf_guru"
else:
    logdir = Path(os.environ['HOME']) / ".pdf_guru"
logdir.mkdir(parents=True, exist_ok=True)
logpath = str(logdir / "pdf.log")
cmd_output_path = str(logdir / "cmd_output.json")

def dump_json(path, obj):
    with open(path, "w", encoding="utf-8") as f:
        json.dump(obj, f, ensure_ascii=False)

def parse_range(page_range: str, page_count: int, is_multi_range: bool = False, is_reverse: bool = False, is_unique: bool = True):
    # e.g.: "1-3,5-6,7-10", "1,4-5", "3-N", "even", "odd"
    page_range = page_range.strip()
    if page_range in ["all", ""]:
        roi_indices = list(range(page_count))
        return roi_indices
    if page_range == "even":
        roi_indices = list(range(0, page_count, 2))
        return roi_indices
    if page_range == "odd":
        roi_indices = list(range(1, page_count, 2))
        return roi_indices

    roi_indices = []
    parts = page_range.split(",")
    neg_count = sum([p.startswith("!") for p in parts])
    pos_count = len(parts) - neg_count
    if neg_count > 0 and pos_count > 0:
        raise ValueError("页码格式错误：不能同时使用正向选择和反向选择语法")
    if pos_count > 0:
        for part in parts:
            part = part.strip()
            if re.match("^!?(\d+|N)(\-(\d+|N))?$", part) is None:
                raise ValueError("页码格式错误!")
            out = part.split("-")
            if len(out) == 1:
                if out[0] == "N":
                    roi_indices.append([page_count-1])
                else:
                    roi_indices.append([int(out[0])-1])
            elif len(out) == 2:
                if out[1] == "N":
                    roi_indices.append(list(range(int(out[0])-1, page_count)))
                else:
                    roi_indices.append(list(range(int(out[0])-1, int(out[1]))))
        if is_multi_range:
            return roi_indices
        roi_indices = [i for v in roi_indices for i in v]
        if is_unique:
            roi_indices = list(set(roi_indices))
            roi_indices.sort()
    if neg_count > 0:
        for part in parts:
            part = part.strip()
            if re.match("^!?(\d+|N)(\-(\d+|N))?$", part) is None:
                raise ValueError("页码格式错误!")
            out = part[1:].split("-")
            if len(out) == 1:
                roi_indices.append([int(out[0])-1])
            elif len(out) == 2:
                if out[1] == "N":
                    roi_indices.append(list(range(int(out[0])-1, page_count)))
                else:
                    roi_indices.append(list(range(int(out[0])-1, int(out[1]))))
        if is_multi_range:
            return roi_indices
        roi_indices = [i for v in roi_indices for i in v]
        if is_unique:
            roi_indices = list(set(range(page_count)) - set(roi_indices))
            roi_indices.sort()
    if is_reverse:
        roi_indices = list(set(range(page_count)) - set(roi_indices))
        roi_indices.sort()
    return roi_indices

def batch_process(func):
    def wrapper(*args, **kwargs):
        print(f"args: {args}")
        print(f"kwargs: {kwargs}")
        doc_path = kwargs['doc_path']
        if "*" in doc_path:
            path_list = glob.glob(doc_path)
            print.debug(f"path_list length: {len(path_list) if path_list else 0}")
            if path_list:
                del kwargs['doc_path']
                for path in path_list:
                    func(*args, doc_path=path, **kwargs)
        else:
            func(*args, **kwargs)
        func(*args, **kwargs)
    return wrapper

@batch_process
def convert_docx2pdf(doc_path: str, output_path: str = None):
    try:
        from docx2pdf import convert
        if output_path is None:
            p = Path(doc_path)
            output_path = str(p.parent / f"{p.stem}.pdf")
        convert(doc_path, output_path)
        dump_json(cmd_output_path, {"status": "success", "message": ""})
    except:
        logging.error(traceback.format_exc())
        dump_json(cmd_output_path, {"status": "error", "message": traceback.format_exc()})

@batch_process
def convert_pdf2docx(doc_path: str, page_range: str = "all", output_path: str = None):
    try:
        from pdf2docx import Converter
        doc = fitz.open(doc_path)
        roi_indices = parse_range(page_range, doc.page_count)
        cv = Converter(doc_path)
        if output_path is None:
            p = Path(doc_path)
            output_path = str(p.parent / f"{p.stem}.docx")
        cv.convert(output_path, pages=roi_indices)
        cv.close()
        dump_json(cmd_output_path, {"status": "success", "message": ""})
    except:
        logging.error(traceback.format_exc())
        dump_json(cmd_output_path, {"status": "error", "message": traceback.format_exc()})

def main():
    parser = argparse.ArgumentParser(description="Convert functions")
    parser.add_argument("input_path", type=str, help="pdf文件路径")
    parser.add_argument("--source-type", type=str, choices=["pdf", 'png', "jpg", "svg", "docx"], default="pdf", help="源类型")
    parser.add_argument("--target-type", type=str, choices=['png', "svg", "docx"], default="png", help="目标类型")
    parser.add_argument("--page_range", type=str, default="all", help="页码范围")
    parser.add_argument("-o", "--output", type=str, help="输出文件路径")
    args = parser.parse_args()
    if args.source_type == "pdf":
        if args.target_type == "docx":
            convert_pdf2docx(doc_path=args.input_path, page_range=args.page_range, output_path=args.output)

if __name__ == '__main__':
    main()


from train import get_model
from torchvision import transforms
from PIL import Image
import matplotlib.pyplot as plt
import torch
import os
from torchvision.models import resnet18, ResNet18_Weights
import torch.nn as nn
import numpy as np

class Make_Test(nn.Module):
    def __init__(self, weight_path):
        super(Make_Test, self).__init__()
        self.transform = transforms.Compose([
            transforms.Resize(size=(224, 224)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])

        self.model = get_model()
        self.model.load_state_dict(torch.load(weight_path))
        self.d = {
            0: 'cat',
            1: 'dog'
        }

    def forward(self, image_path):
        image = plt.imread(image_path)
        image = Image.fromarray(image)
        image = self.transform(image).unsqueeze(0)
        self.model.eval()

        out = 0 if self.model(image).squeeze(-1).item() < 0.5 else 1
        return self.d[out]

def visuzalize_loss():
    train_loss = np.load('Accuracy/test_losses.npy')
    train_acc = np.load('test1/test_accs.npy')
    plt.plot(train_loss)
    plt.plot(train_acc)
    plt.show()

def visualize(mk_test, data_path):
    fig = plt.figure(figsize=(9, 9))
    rows, cols = 4, 4

    for i in range(1, rows * cols + 1):
        img = plt.imread(os.path.join("test1", data_path[i - 1]))
        label = mk_test(os.path.join("test1", data_path[i - 1]))
        fig.add_subplot(rows, cols, i)
        plt.imshow(img)
        plt.title(label)
        plt.axis(False)
    plt.show()

if __name__ == '__main__':
    folder = "test1"
    cnt = 0
    mk_test = Make_Test(r"E:\Python test Work\Hieu\Weight\model.pt")
    data_path = os.listdir(folder)[16:32]
    visualize(mk_test, data_path)


"""
    Implements a mixin for remote communication.
"""

import re
import json
import socket

whitespace_re = re.compile(r"\s+")

class RemoteActor:

    ENCODING = "utf-8"
    DECODER = json.JSONDecoder()

    def __init__(self, socket):
        """ Creates a new remote actor able to send and receive from the given socket
        :param socket: socket connection
        """
        self.socket = socket
        self.buffer = ""

    def parse(self, clear_on_partial=False):
        print(self.buffer)
        try:
            decoded, end = self.DECODER.raw_decode(self.buffer)
        except ValueError:
            print(self.buffer, "va")
            return False, False, False

        if not isinstance(decoded, bool) and (isinstance(decoded, int) or isinstance(decoded, float)) and end == len(self.buffer):
            if clear_on_partial:
                self.buffer = self.buffer[end:]
            return True, False, decoded
        else:
            print(decoded, "blah")
            self.buffer = self.buffer[end:]
            return True, True, decoded

    def send(self, data):
        """ Sends the given JSON object to the socket
        :param data: JSON object
        """
        encoded = json.dumps(data).encode(self.ENCODING)
        self.socket.send(encoded)

    def receive(self):
        """ Continuously receives bytes until a JSON object can be deserialized, at which point
          the deserialized object is returned. It is up to the caller to restrict the execution time.
        :return: deserialized JSON object
        """
        data = bytes()
        while True:
            try:
                data += self.socket.recv(1)
            except socket.timeout:
                something, complete, decoded = self.parse(True)
                print(something, complete, decoded)
                if something:
                    return decoded
                raise

            try:
                decoded = data.decode(self.ENCODING)
                self.buffer += decoded
                data = bytes()
            except UnicodeDecodeError:
                continue

            something, complete, decoded = self.parse()
            if something and complete:
                return decoded

    def receive_iterator(self):
        """ Continuously receives data and deserializes JSON objects as they come in """
        while True:
            yield self.receive()


"""
Here I will read access tokens from txt file for safety
"""
import json

class Token:
    def __init__(self):
        with open('tokens.json', 'r') as f:
            data = json.loads(f.readline())
        self.community = data['comm_token']
        self.user = data['usr_token']
        self.comm_id = -167621445
        self.usr_id = 491551942

if __name__=='__main__':
    t = Token()


#!/usr/bin/env python

from utils.analysis import AbsMovingAvg, Threshold, Derivative
from utils.chaser import Chaser

import os
import sys
parentDir = os.path.dirname(os.getcwd())
sys.path.append(parentDir)
def checkImport(lib):
    if not os.path.exists(os.path.join(parentDir, lib)):
        print("%s library not found." % lib)
        print("please clone github.com/andrewbooker/%s.git into %s" % (lib, parentDir))
        exit()

checkImport("mediautils")
from mediautils.mididevices import UsbMidiDevices, MidiOut

## ===== composer =====

checkImport("compositionutils")
from compositionutils.scale import Scale, Modes

tonic = "C"
mode = "aeolian"
print(tonic, mode)

noteSpan = 15
scale = Scale(noteSpan, tonic, Modes.named(mode))

class Consumer():
    def __init__(self, midiOut):
        self.midiOut = midiOut
        self.note = 0

    def on(self, velocity):
        self.note = scale.noteFrom(int(velocity * 100) % noteSpan)
        self.midiOut.note_on(self.note, int(26 + (velocity * 100)), 0)

    def off(self):
        self.midiOut.note_off(self.note, 0, 0)

## =====

midiDevices = UsbMidiDevices()
midiOut = MidiOut(midiDevices)
consumer = Consumer(midiOut.io)
chaser = Chaser(consumer, 0.6, 0.2)

import soundfile as sf

infile = sys.argv[1]
workingDir = os.path.dirname(infile)
print("loading %s" % infile)
(data, sampleRate) = sf.read(infile, dtype="float32")

for s in range(len(data)):
    chaser.add(data[s])

del midiOut
del midiDevices
print("done")


import pandas as pd
import pickle
from pathlib import Path

def preprocess_test_df(test_clin_df, test_prot_df, test_pep_df, save_data=False):

    if 'upd23b_clinical_state_on_medication' in test_clin_df.columns:
        # drop the medication column
        test_clin_df = test_clin_df.drop(columns=['upd23b_clinical_state_on_medication'])

    # create a column with the UniProt and Peptide name combined
    test_pep_df['peptide_uniprot'] = test_pep_df['Peptide'] + '_'+ test_pep_df['UniProt']

    # create a table with the visit_id as the index and the proteins or peptides as the feature and the abundance as the values
    train_prot_pivot = test_prot_df.pivot(index='visit_id', values='NPX', columns='UniProt')
    train_pep_pivot = test_pep_df.pivot(index='visit_id', values='PeptideAbundance', columns='peptide_uniprot')

    # combine the two tables on the visit_id
    full_prot_train_df = train_prot_pivot.join(train_pep_pivot)

    # fill nan with 0
    full_prot_train_df = full_prot_train_df.fillna(0)

    full_train_df = test_clin_df.merge(full_prot_train_df, how='inner', left_on='visit_id', right_on='visit_id')
    full_train_df = full_train_df.sample(frac=1).reset_index(drop=True)

    return full_train_df

test_df = pd.read_csv('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/raw/test.csv')

prot_test_df = pd.read_csv('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/raw/test_proteins.csv')

pep_test_df = pd.read_csv('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/raw/test_peptides.csv')

full_test_df = preprocess_test_df(test_df, prot_test_df, pep_test_df, save_data=False)

updr = 'updrs_1'
month = 0

for updr in ['updrs_1', 'updrs_2', 'updrs_3', 'updrs_4']:
    updr_df = full_test_df[full_test_df['updrs_test'] == updr]
    info_cols = ['visit_id', 'visit_month', 'patient_id', 'updrs_test', 'row_id', 'group_key']
    updr_info = updr_df[info_cols]
    model_df = updr_df.drop(columns=info_cols)

    for month in [0, 6, 12, 24]:
        # Load the saved model from file
        model_path = Path('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/models/model_rf_reg_updrs_1_0.pkl')

        with open(model_path, 'rb') as f:
            rf_reg = pickle.load(f)

        # Use the imported model to make predictions
        y_pred = rfc.predict(model_df)

target = 'updrs_4'
train_df = pd.read_csv(f'~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/processed/train_{target}.csv')
train_df.head()


import numpy as np
import pandas as pd
from collections import OrderedDict
import matplotlib as mlt
import matplotlib.pyplot as plt
from scipy import optimize

def get_data():
    data = OrderedDict(
        amount_spent =  [50,  10, 20, 5,  65,  70,  80,  81, 1],
        send_discount = [0,   1,  1,  1,  0,   0,   0,    0,   1]
        )
    df = pd.DataFrame.from_dict(data) # creating a dataframe
    X = df['amount_spent'].astype('float').values # converting the type to 'float'
    y = df['send_discount'].astype('float').values # converting the type to 'float'
    return (X,y) # returning the X , y

def get_theta(costFunction , X , y , iter = 400):

    options = {'maxiter':iter} # maximum number of iterations

    row , col = X.shape

    initial_theta = np.zeros(col)

    res = optimize.minimize(
        costFunction,
        initial_theta ,
        (X,y),
        jac=True,
        method='TNC',
        options = options
    )
    # the fun property of `OptimizeResult` object returns
    # the value of costFunction at optimized theta
    cost = res.fun

    # the optimized theta is in the x property
    theta = res.x

    return ( cost , theta )

def sigmoid(z):
    # convert input to a numpy array
    z = np.array(z)

    g = np.zeros(z.shape)

    g = 1 / (1 + np.exp(-z))

    return g

def costFunction(theta, X, y):

    m = y.size  # number of training examples

    J = 0
    grad = np.zeros(theta.shape) #

    h = sigmoid(X.dot(theta.T)) # sigmoid function

    J = (1 / m) * np.sum(-y.dot(np.log(h)) - (1 - y).dot(np.log(1 - h)))
    grad = (1 / m) * (h - y).dot(X)

    return J, grad

def load_data(url):
    df=pd.read_csv(url,header=None);
    return ( df.iloc[:,:-1] , df.iloc[:,-1])

def run():

    X , y = load_data('./marks.txt')

    ones = X[y==1] # features X where y == 1
    zeros = X[y==0] # features X where y == 0

    #X,y = get_data()
    row , col = X.shape
    # Add intercept term to X
    X = np.concatenate([np.ones((row, 1)), X], axis=1)

    (cost,theta)=get_theta(costFunction , X , y )

    print('cost => {} , theta => {}'.format(cost,theta) )

    #print(' x ',X[:,1:3]) # prints col 0 , 1

    # calculate min of X - 2 , max of X + 2
    x_treme = np.array([ np.min(X[:,1]) - 2 , np.max(X[:,1]) + 2 ])

    # calculate y extreme
    #y_treme = (-1. / theta[2]) * ( theta[1] * x_treme + theta[0] )

    y_treme = - (( np.dot(theta[1] ,x_treme) ) + theta[0] ) / theta[2]

    plt.plot(x_treme , y_treme)

    plt.scatter(ones[0],ones[1] , label="1's ")
    plt.scatter(zeros[0],zeros[1], label="0's ")

    plt.legend(loc="upper right")
    plt.show()

if __name__ == "__main__":
    run()


from openpyxl import load_workbook
# from openpyxl.cell import Cell

if __name__ == '__main__':
    wb = load_workbook('data/FINODAYS_Доп. материал для Почта Банк_Диалоги.xlsx')
    for sn in wb.sheetnames:
        print(sn)
        marks = []
        for row in wb[sn]:
            if row[1].value == 'CLIENT':
                print(row[2].value)
            elif row[2].value.startswith('Оценка'):
                marks.append(row[2].value)
        print('Оценки:', *marks, end='\n' + '-' * 50 + '\n')


import numpy as np
from torch.utils import data
import torch as t
import matplotlib.pyplot as plt
import h5py
from .utils.utils import mat2gray_nocrop, plot_img_with_labels
import os
import random
import ipdb
from .visualize_predictions import draw_label_img
from scipy.ndimage import gaussian_filter
import monai

def torch_randint(max_v):
    return t.randint(max_v, (1, 1)).view(-1).numpy()[0]

def torch_rand(size=1):
    return t.rand(size).numpy()

def augmentation(img, mask):
    img = img.numpy()
    mask = mask.numpy()
    r = [torch_randint(2), torch_randint(2), torch_randint(4)]
    if r[0]:
        img = np.fliplr(img)
        mask = np.fliplr(mask)
    if r[1]:
        img = np.flipud(img)
        mask = np.flipud(mask)
    img = np.rot90(img, k=r[2])
    mask = np.rot90(mask, k=r[2])

    # min_v = (torch_rand() * 0.96) - 0.48
    # max_v = 1 + (torch_rand() * 0.96) - 0.48
    # for k in range(img.shape[-1]):
    #    img[:, :, k] = mat2gray_nocrop(img[:, :, k], [min_v, max_v]) - 0.5

    """
    r = [torch_randint(2), torch_randint(2), torch_randint(4)]
    if r[0]:
        img = np.fliplr(img)
        mask = np.fliplr(mask)
    if r[1]:
        img = np.flipud(img)
        mask = np.flipud(mask)
    img = np.rot90(img, k=r[2])
    mask = np.rot90(mask, k=r[2])
    img = img.numpy()
    min_v = (torch_rand() * 0.96) - 0.48
    max_v = 1 + (torch_rand() * 0.96) - 0.48
    for k in range(img.shape[2]):

        img[:, :, k] = mat2gray_nocrop(img[:, :, k], [min_v, max_v]) - 0.5

    """
    """
    tmp_img = t.cat([img, label_img], dim=-1)

    transforms = monai.transforms.Compose(
        monai.transforms.RandAxisFlipd(keys=["image"], prob=0.5),
        monai.transforms.RandRotate90d(keys=["image"], prob=0.5),
        monai.transforms.RandGridDistortiond(
            keys=["image"], prob=0.5, distort_limit=0.2
        ),
        monai.transforms.OneOf(
            [
                monai.transforms.RandShiftIntensityd(
                    keys=["image"], prob=0.5, offsets=(0.1, 0.2)
                ),
                # monai.transforms.RandAdjustContrastd(
                #    keys=["image"], prob=0.5, gamma=(1.5, 2.5)
                # ),
                # monai.transforms.RandHistogramShiftd(keys=["image"], prob=0.5),
            ]
        ),
    )
    uba = transforms(dict(image=tmp_img))
    img = uba["image"][:, :, :3]
    # print(f"{img.shape=}")
    label_img = uba["image"][:, :, -2:]
    # print(f"{label_img.shape=}")
    """
    """
    if t.rand(1)[0] > 0.5:
        img = t.flipud(img)
        label_img = t.flipud(label_img)
    if t.rand(1)[0] > 0.5:
        img = t.fliplr(img)
        label_img = t.fliplr(label_img)
    if t.rand(1)[0] > 0.5:
        '''
        img = img + t.randn(img.shape) * 0.05
        img = t.clamp(img, 0, 1)
        '''
    if t.rand(1)[0] > 0.5:
        times = t.randint(4, (1,))[0]
        img = t.rot90(img, k=times)
        label_img = t.rot90(label_img, k=times)
    """
    return t.from_numpy(img.copy()), t.from_numpy(mask.copy())

class FociDataset(data.Dataset):
    def __init__(
        self,
        *,
        hdf5_filename: str,
        filenames: tuple[str, ...],
        split: str,
        crop_size: tuple[int, int],
        out_len: int,
    ):

        self.hdf5_filename = hdf5_filename
        self.split = split
        self.crop_size = crop_size
        self.filenames = filenames
        self.out_len = out_len
        self.h5data = None

    def __len__(self):
        return len(self.filenames)

    def __getitem__(self, idx):

        if self.h5data is None:
            self.h5data = h5py.File(self.hdf5_filename, "r")

        filename = self.filenames[idx]
        img = t.from_numpy(self.h5data[filename + "_image"][...]).permute(
            1, 2, 0
        )
        label = t.from_numpy(self.h5data[filename + "_label"][...]).permute(
            1, 2, 0
        )
        in_size = img.shape
        out_size = self.crop_size
        if not self.split == "test":
            r = [
                t.randint(in_size[i] - out_size[i], (1,))[0] for i in range(2)
            ]
            img = img[
                r[0] : r[0] + out_size[0], r[1] : r[1] + out_size[1], :,
            ]
            label = label[
                r[0] : r[0] + out_size[0],
                r[1] : r[1] + out_size[1],
                :,  # TODO: check this. Why do I need to swap the order of the two indices???
            ]
        if self.split == "train":
            img, label = augmentation(img, label)

        img = img.permute(2, 0, 1).float()
        label = label.permute(2, 0, 1).float()

        return img, label


import numpy as np

import matplotlib.pyplot as plt
import matplotlib.patches as patches

import logic

UI_BOARD_SIZE = (8, 6)
UI_BOARD_OFFSET = 0.25
UI_BOARD_CELL_COLORS = [(0,0,0,0.4), (0,0.9,1,0.7)]

'''
UI front-end implementation
'''
class Board:
    def __init__(self):
        # Create figure and axes
        self.fig, self.ax = plt.subplots(figsize=UI_BOARD_SIZE)
        # Board background color
        self.ax.set_facecolor((0,0,0,0.15))
        # Hiding axes
        self.ax.get_xaxis().set_visible(False)
        self.ax.get_yaxis().set_visible(False)
        # Scale axes
        self.ax.set_xlim([0,1])
        self.ax.set_ylim([0,1])
        self.ax.set_aspect('equal', adjustable='box')

        # Board cells
        self.patches = []

        # Last board state - needed for differential update of board
        self.last_state = None

        # Connect to UI for mouse click event
        connection_id = self.fig.canvas.mpl_connect('button_press_event', self.on_click_cell)
        self.on_click_event_handler = None

        # Generation label
        self.lbl_generation = None

        # Next generation button
        axnext = plt.axes([0.45, 0.9, 0.2, 0.075])
        self.bnext = plt.Button(axnext, 'Next', color=(0, 1, 0.7, 0.7), hovercolor=(0, 1, 0.7, 1))
        self.bnext.label.set_fontsize(16)
        self.bnext.on_clicked(self.on_click_btn_next)

        # Reset button
        axreset = plt.axes([0.25, 0.9, 0.1, 0.075])
        self.breset = plt.Button(axreset, 'Reset', color=(1, 0.2, 0, 0.7), hovercolor=(1, 0.2, 0, 1))
        self.breset.label.set_fontsize(16)
        self.breset.on_clicked(self.on_click_btn_reset)

    def on_click_btn_next(self, event):
        if self.on_click_event_handler is None:
            raise ValueError
        self.on_click_event_handler(logic.EVENT_NEXT_CLICK)

    def on_click_btn_reset(self, event):
        if self.on_click_event_handler is None:
            raise ValueError
        self.on_click_event_handler(logic.EVENT_RESET_CLICK)

    def on_click_cell(self, event):
        if not event.inaxes == self.ax:
            return
        # Left mouse button click to change cell state
        if event.button == 1:
            x = int(np.floor((event.xdata - self.cell_margin[0]) / self.cell_width))
            y = int(np.floor((event.ydata - self.cell_margin[1]) / self.cell_height))
            if self.on_click_event_handler is None:
                raise ValueError
            self.on_click_event_handler(logic.EVENT_CELL_CLICK, data=(x, y))

    def set_click_event_handler(self, handler):
        self.on_click_event_handler = handler

    def redraw_board(self, state):
        # Update cell size and margin
        self.cell_width = 1. / state.shape[0]
        self.cell_height = 1. / state.shape[1]
        self.cell_margin = (self.cell_width * 0.05, self.cell_height * 0.05)

        # Remove all previously drawn patches
        [p.remove() for p in reversed(self.ax.patches)]

        # Add new patches
        for x in range(state.shape[0]):
            for y in range(state.shape[1]):
                rect = patches.Rectangle((x*self.cell_height + self.cell_margin[1], y*self.cell_width + self.cell_margin[0]),
                            self.cell_width*0.9, self.cell_height*0.9,
                            fill=True, facecolor=UI_BOARD_CELL_COLORS[state[x, y]])
                self.ax.add_patch(rect)
        self.patches = self.ax.patches

        # Update last state
        self.last_state = state.copy()

        plt.show()

    def redraw_ui_elements(self, generation=None):
        # UI elements, status, buttons
        if not generation is None:
            if not self.lbl_generation is None:
                self.lbl_generation.remove()

            self.lbl_generation = self.ax.annotate('%d' % generation,
                color='k', weight='bold', fontsize=16, ha='center', va='center',
                xy=(0.95, 1.08), xycoords=self.ax.transAxes, annotation_clip=False)

    def redraw(self, state, generation=None):
        # Redraw game board
        self.redraw_board(state)

        # UI elements, status, buttons
        if not generation is None:
            self.redraw_ui_elements(generation)

    def update(self, state, generation=None):
        # Redraw entire board if state dimension has changed
        if self.last_state is None or state.size != self.last_state.size:
            self.redraw(state, generation)

        # Update only those cells, that have changed since last state
        diff = np.subtract(state, self.last_state)
        changed_idx = list(zip(*diff.nonzero()))
        for xy in changed_idx:
            self.patches[xy[0] * state.shape[0] + xy[1]].set_facecolor(UI_BOARD_CELL_COLORS[state[xy[0], xy[1]]])

        # Update last state
        self.last_state = state.copy()

        # UI elements, status, buttons
        if not generation is None:
            self.redraw_ui_elements(generation)

        plt.show()


from ..utils import Object

class MessageReplyInfo(Object):
    """
    Contains information about replies to a message

    Attributes:
        ID (:obj:`str`): ``MessageReplyInfo``

    Args:
        reply_count (:obj:`int`):
            Number of times the message was directly or indirectly replied
        recent_replier_ids (List of :class:`telegram.api.types.MessageSender`):
            Identifiers of at most 3 recent repliers to the message; available in channels with a discussion supergroupThe users and chats are expected to be inaccessible: only their photo and name will be available
        last_read_inbox_message_id (:obj:`int`):
            Identifier of the last read incoming reply to the message
        last_read_outbox_message_id (:obj:`int`):
            Identifier of the last read outgoing reply to the message
        last_message_id (:obj:`int`):
            Identifier of the last reply to the message

    Returns:
        MessageReplyInfo

    Raises:
        :class:`telegram.Error`
    """
    ID = "messageReplyInfo"

    def __init__(self, reply_count, recent_replier_ids, last_read_inbox_message_id, last_read_outbox_message_id, last_message_id, **kwargs):

        self.reply_count = reply_count  # int
        self.recent_replier_ids = recent_replier_ids  # list of MessageSender
        self.last_read_inbox_message_id = last_read_inbox_message_id  # int
        self.last_read_outbox_message_id = last_read_outbox_message_id  # int
        self.last_message_id = last_message_id  # int

    @staticmethod
    def read(q: dict, *args) -> "MessageReplyInfo":
        reply_count = q.get('reply_count')
        recent_replier_ids = [Object.read(i) for i in q.get('recent_replier_ids', [])]
        last_read_inbox_message_id = q.get('last_read_inbox_message_id')
        last_read_outbox_message_id = q.get('last_read_outbox_message_id')
        last_message_id = q.get('last_message_id')
        return MessageReplyInfo(reply_count, recent_replier_ids, last_read_inbox_message_id, last_read_outbox_message_id, last_message_id)


# drawing the Earth on equirectangular projection

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import numpy
import matplotlib.ticker as mticker

fig = plt.figure(figsize=(64,32), frameon=False)
ax = fig.add_subplot(1,1,1, projection=ccrs.PlateCarree(central_longitude=180))

ax.set_global()
#ax.stock_img()
#ax.coastlines(resolution='50m')

ax.add_feature(cfeature.NaturalEarthFeature('physical', 'ocean', '50m', edgecolor='face', facecolor=cfeature.COLORS['water']))
ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', edgecolor='face', facecolor=cfeature.COLORS['land']))
ax.add_feature(cfeature.NaturalEarthFeature('physical', 'lakes', '50m', edgecolor='face', facecolor=cfeature.COLORS['water']))
ax.add_feature(cfeature.NaturalEarthFeature('physical', 'rivers_lake_centerlines', '50m', edgecolor=cfeature.COLORS['water'], facecolor='none'))
ax.add_feature(cfeature.NaturalEarthFeature('cultural', 'admin_0_countries', '50m', edgecolor='gray', facecolor='none'))

gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, linewidth=1, alpha=0.8)
gl.xlocator = mticker.FixedLocator(list(range(0,361,60)))
gl.ylocator = mticker.FixedLocator(list(range(-90,91,30)))

plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
plt.savefig("earth-equirectanguler3.png", dpi=8192/64)


import torch
from gms_loss import *
from PIL import Image
from torchvision import transforms
from gms_loss import MSGMS_Loss

image_path_1= './lj_test_image/1118_visdon_HR_downsampling_2loss_visstyle/0_SR_x_1105_4.png'
image_path_2 = './lj_test_image/1116_tcl_bright/6_SR_x_1105_4.png'

img_ycbcr_1 = Image.open(image_path_1).convert('YCbCr')
img_y_1, img_cb_1, img_cr_1 = img_ycbcr_1.split()

img_ycbcr_2 = Image.open(image_path_2).convert('YCbCr')
img_y_2, img_cb_2, img_cr_2 = img_ycbcr_2.split()

img_y_1 = img_y_1.crop((0,0, 100, 200))
img_y_2 = img_y_2.crop((0,0, 100, 200))

transform = transforms.ToTensor()
Ir = transform(img_y_1).unsqueeze(0)
Ii = transform(img_y_2).unsqueeze(0)

print(Ir.size())

# print(Ir.size())

loss = MSGMS_Loss()
y = loss.forward(Ii, Ir)

print(y)


import numpy as np
import matplotlib
from matplotlib import pyplot as plt
plt.switch_backend('agg')
import matplotlib.patches
from scipy import stats
import pandas as pd
import math
from mpi4py import MPI
import sys
import itertools
import glob
import os

plt.ioff()

design = str(sys.argv[1])

all_IDs = ['3600687', '7000550', '7200799', '7200645', '3704614', '7202003']#np.genfromtxt('../structures_files/metrics_structures.txt', dtype='str').tolist()
nStructures = len(all_IDs)

percentiles = np.arange(0, 100)

os.chdir('../' + design)
directories = glob.glob('CMIP*_*')
directories.remove('CMIP3_070')
os.chdir('../output_analysis')
scenarios = len(directories)
if design == 'CMIP_curtailment':
    sow = 27

else:
    sow = 1

idx = np.arange(2, sow*2+2, 2)
historical = pd.read_csv('../structures_files/shortages.csv', index_col=0)

def alpha(i, base=0.2):
    l = lambda x: x + base - x * base
    ar = [l(0)]
    for j in range(i):
        ar.append(l(ar[-1]))
    return ar[-1]

def shortage_duration(sequence, threshold):
    cnt_shrt = [sequence[i] > threshold for i in
                range(len(sequence))]  # Returns a list of True values when there's a shortage
    shrt_dur = [sum(1 for _ in group) for key, group in itertools.groupby(cnt_shrt) if
                key]  # Counts groups of True values
    return shrt_dur

def plotSDC(synthetic, histData,  structure_name):
    n = 12
    # Reshape historic data to a [no. years x no. months] matrix
    f_hist = np.reshape(histData, (int(np.size(histData) / n), n))
    # Reshape to annual totals
    f_hist_totals = np.sum(f_hist, 1)
    # Calculate historical shortage duration curves
    F_hist = np.sort(f_hist_totals)  # for inverse sorting add this at the end [::-1]

    # Reshape synthetic data
    # Create matrix of [no. years x no. months x no. samples]
    synthetic_global = np.zeros([int(len(histData) / n), n, scenarios * sow])
    # Loop through every SOW and reshape to [no. years x no. months]
    for j in range(scenarios * sow):
        synthetic_global[:, :, j] = np.reshape(synthetic[:, j], (int(np.size(synthetic[:, j]) / n), n))
    # Reshape to annual totals
    synthetic_global_totals = np.sum(synthetic_global, 1)

    p = np.arange(100, -10, -10)

    # Calculate synthetic shortage duration curves
    F_syn = np.empty([int(len(histData) / n), scenarios * sow])
    F_syn[:] = np.NaN
    for j in range(scenarios * sow):
        F_syn[:, j] = np.sort(synthetic_global_totals[:, j])

    # For each percentile of magnitude, calculate the percentile among the experiments ran
    perc_scores = np.zeros_like(F_syn)
    for m in range(int(len(histData) / n)):
        perc_scores[m, :] = [stats.percentileofscore(F_syn[m, :], j, 'rank') for j in F_syn[m, :]]

    P = np.arange(1., len(histData)/12 + 1) * 100 / (len(histData)/12)

    ylimit = np.max(F_syn)
    fig, (ax1) = plt.subplots(1, 1, figsize=(14.5, 8))
    # ax1
    handles = []
    labels = []
    color = '#000292'
    for i in range(len(p)):
        ax1.fill_between(P, np.min(F_syn[:, :], 1), np.percentile(F_syn[:, :], p[i], axis=1), color=color, alpha=0.1)
        ax1.plot(P, np.percentile(F_syn[:, :], p[i], axis=1), linewidth=0.5, color=color, alpha=0.3)
        handle = matplotlib.patches.Rectangle((0, 0), 1, 1, color=color, alpha=alpha(i, base=0.1))
        handles.append(handle)
        label = "{:.0f} %".format(100 - p[i])
        labels.append(label)
    #Plot 50th percentile line separately
    ax1.plot(P, np.percentile(F_syn[:, :], p[5], axis=1), linewidth=0.7, color=color, alpha=0.7, linestyle='dashed')
    ax1.plot(P, F_hist, c='black', linewidth=2, label='Historical record')
    ax1.set_ylim(0, ylimit)
    ax1.set_xlim(0, 100)
    ax1.legend(handles=handles, labels=labels, framealpha=1, fontsize=8, loc='upper left',
               title='Frequency in experiment', ncol=2)
    ax1.set_xlabel('Shortage magnitude percentile', fontsize=20)
    ax1.set_ylabel('Annual shortage (Million $m^3$)', fontsize=20)

    fig.suptitle('Shortage magnitudes for ' + structure_name, fontsize=16)
    plt.subplots_adjust(bottom=0.2)
    fig.savefig('../' + design + '/ShortagePercentileCurves/' + structure_name + '_' + design + '.svg')
    fig.savefig('../' + design + '/ShortagePercentileCurves/' + structure_name + '_' + design + '.png')
    fig.clf()

# Begin parallel simulation
comm = MPI.COMM_WORLD

# Get the number of processors and the rank of processors
rank = comm.rank
nprocs = comm.size

# Determine the chunk which each processor will neeed to do
count = int(math.floor(nStructures / nprocs))
remainder = nStructures % nprocs

# Use the processor rank to determine the chunk of work each processor will do
if rank < remainder:
    start = rank * (count + 1)
    stop = start + count + 1
else:
    start = remainder * (count + 1) + (rank - remainder) * count
    stop = start + count

for i in range(start, stop):
    histData = historical.loc[all_IDs[i]].values[-768:] * 1233.4818 / 1000000
    synthetic = np.zeros([len(histData), scenarios * sow])
    for j in range(scenarios):
        path = '../' + design + '/Infofiles/' + all_IDs[i] + '/' + all_IDs[i] + '_info_' + directories[j] + '.txt'
        data = np.loadtxt(path)
        synthetic[:, j * sow:j * sow + sow] = data[:, idx] * 1233.4818 / 1000000
    plotSDC(synthetic, histData, all_IDs[i])


# Import all the modules to determine the cofusion matrix
import itertools
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import os

# This function calculates the confusion matrix and visualizes it
def plot_confusion_matrix(y_test, y_pred, file_path,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    Calculates and plots a confusion matrix from
    the given labels

    Parameters
    ----------
    y_test: list
        Already given labels
    y_pred:
        Predictions made by the model
    file_path: str
        Name of the of the file where the results should be stored,
        together with a path
    nomralize: bool
        Whether the confusion matrix should ne bormalized
    title: str
        Whether the plot should have any special title
    cmap: plt.cm.*
        What cholor scheme should be used for plotting

    Returns
    -------
    An image of confusion matrix
    """
    cm = confusion_matrix(y_test, y_pred)
    np.set_printoptions(precision=2)

    classes_pred = [str(i) for i in np.unique(y_pred)]
    classes_test = [str(i) for i in np.unique(y_test)]

    classes = None
    if len(classes_pred)>len(classes_test):
        classes = classes_pred
    else:
        classes = classes_test

    # In case the confusion matrix should be normalized
    if normalize:
        t = cm.sum(axis=1)[:, np.newaxis]
        for i in t:
            if i[0] == 0:
                i[0] = 1
        cm = cm.astype('float') / t

    plt.figure()
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    thresh = cm.max() / 2.0
    plt.tight_layout()
    plt.xticks([], [])
    plt.yticks([], [])
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.savefig("{}.png".format(file_path))
    plt.close()


from django.dispatch import receiver
from django.db.models.signals import post_save
from expensense.models import Expense, ApprovalConditions
from django.utils import timezone

@receiver(post_save, sender=Expense)
def auto_approve_expense(sender, instance, **kwargs):
    """ Method to auto approve expense requests """
    # print('Auto Approved called')
    try:
        #query to get the manager and admin condition for the employee's team and company
        manager_condition = ApprovalConditions.objects.get(user__role = 'MNG',
                                                            team = instance.user_id.team,
                                                            company = instance.user_id.company)

        admin_condition = ApprovalConditions.objects.get(user__role = 'ADM',
                                                         team = instance.user_id.team,
                                                         company = instance.user_id.company)
        # approve the request if the expense amount is lesser than in approval
        #  condition and is pending and the signature similarity is more than 80%
        if (manager_condition and (float(instance.amount) <= manager_condition.max_amount)
             and (int(instance.status)==Expense.pending) and (float(instance.similarity)>80)):
            # Auto approve for manager
            instance.manager_approved_at = timezone.now()
            instance.manager_auto_approved = True
            instance.status = Expense.manager_approved
            instance.save()
            manager_condition = None
        # approve the request if the expense amount is lesser than in approval
        #  condition and is manager approved and the signature similarity is more than 80%
        elif (admin_condition and (int(instance.status) == Expense.manager_approved)
               and (float(instance.amount) <= admin_condition.max_amount) and
               float(instance.similarity)>80):
            # Auto approve for admin
            instance.admin_approved_at = timezone.now()
            instance.admin_auto_approved = True
            instance.status = Expense.admin_approved
            instance.save()
            admin_condition=None

    except ApprovalConditions.DoesNotExist:
        pass


# match close atoms in two moleculas by maximum weighted bipartite matching
import numpy as np
import logging

# weights - numpy 2-dimensional array
def wbm(weights):
    import pulp
    pulp.LpSolverDefault.msg = False
    prob = pulp.LpProblem("WBM_Problem", pulp.LpMinimize)
    m,n = weights.shape
    # print(m,n)
    from_nodes = np.arange(m); to_nodes = np.arange(n)
    # Create The Decision variables
    choices = pulp.LpVariable.dicts("e",(from_nodes, to_nodes), 0, 1, pulp.LpInteger)

    # Add the objective function
    prob += pulp.lpSum([weights[u][v] * choices[u][v]
                   for u in from_nodes
                   for v in to_nodes]), "Total weights of selected edges"

    # Constraint set ensuring that the total from/to each node
    # is less than its capacity (= 1)
    ind1 = np.argsort(weights[:,0].reshape(-1))
    # print(ind1)
    ind2 = np.argsort(weights[0,:].reshape(-1))
    if from_nodes.size >= to_nodes.size:
        for v in to_nodes: prob += pulp.lpSum([choices[u][v] for u in from_nodes]) == 1, ""
        for i in range(m):
            #if i < n//2:
            if i < 0:
                prob += pulp.lpSum([choices[from_nodes[ind1[i]]][v] for v in to_nodes]) == 1, ""
            else: prob += pulp.lpSum([choices[from_nodes[ind1[i]]][v] for v in to_nodes]) <= 1, ""
    else:
        for u in from_nodes: prob += pulp.lpSum([choices[u][v] for v in to_nodes]) == 1, ""
        for i in range(n):
            #if i < m//2:
            if i < 0:
                prob += pulp.lpSum([choices[u][to_nodes[ind2[i]]] for u in from_nodes]) == 1, ""
            else: prob += pulp.lpSum([choices[u][to_nodes[ind2[i]]] for u in from_nodes]) <= 1, ""
    # The problem is solved using PuLP's choice of Solver
    prob.solve()

    # The status of the solution is printed to the screen
    # print( "Status:", pulp.LpStatus[prob.status])
    # Each of the variables is printed with it's resolved optimum value
    # for v in prob.variables():
    #     if v.varValue > 1e-3:
    #         print(f'{v.name} = {v.varValue}')
    # print(f"Sum of wts of selected edges = {round(pulp.value(prob.objective), 4)}")

    # print selected edges
    selected_from = [v.name.split("_")[1] for v in prob.variables() if v.value() > 1e-3]
    selected_to   = [v.name.split("_")[2] for v in prob.variables() if v.value() > 1e-3]
    selected_edges = []
    resultInd = np.zeros(m, dtype='int32')-1
    for su, sv in list(zip(selected_from, selected_to)):
        resultInd[int(su)] = int(sv)
        selected_edges.append((su, sv))
    resultIndExtra = np.copy(resultInd)
    forget = np.setdiff1d(np.arange(n), selected_to)
    if forget.size>0: resultIndExtra = np.concatenate([resultIndExtra,forget])
    return resultInd, resultIndExtra


#Menggambar graf dengan 8 nodes
import matplotlib
import networkx as nx
import itertools

G = nx.Graph()

#Menambah node
L = ['a','b','c','d','e','f','g','h']
G.add_nodes_from(L)
'''
Kak ini kenapa nodesnya selalu kerandom ya? :(
'''

#Menambah edge
pairs = itertools.combinations(L,2)

edges = list()
for pair in pairs:
    edges.append(pair)

for edge in edges:
    G.add_edge(*edge)

#Menampilkan gambar
nx.draw_circular(G, with_labels = True, edge_color='b')
matplotlib.pyplot.show()


from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    # (r'^johnjot/', include('johnjot.foo.urls')),
    (r'^api/', include('core.api.urls')),
    (r'^admin/', include(admin.site.urls)),
)


#!/usr/bin/env python
# coding: utf-8

# # 積み上げ棒グラフを作成する

# In[1]:

get_ipython().run_line_magic('matplotlib', 'inline')
from matplotlib import pyplot as plt
import numpy as np

#数値は適当
bar1 = [100, 50, 200] #積み上げ棒グラフの一段目
bar2 = [100, 200, 50] #積み上げ棒グラフの二段目
bar3 = [100, 250, 100] #積み上げ棒グラフの三段目

bar3_st = np.add(bar1, bar2).tolist() #bar3を積み上げる位置を指定しておく
sample_labels = ['SampleA', 'SampleB', 'SampleC'] #データのラベルを指定
x = [0, 1, 2] #棒グラフを表示させるx軸座標を決めておく
barwidth = 0.7 #棒グラフの幅を指定する。棒グラフのx軸座標を考慮して決める

plt.figure() #Figureオブジェクトを作成
plt.bar(x, bar1, width=barwidth, label='class1')
plt.bar(x, bar2, bottom=bar1, width=barwidth, label='class2') #bottomで2段目のデータを積み上げる位置を指定する
plt.bar(x, bar3, bottom=bar3_st, width=barwidth, label='class3') #bottomで3段目のデータを積み上げる位置を指定する
plt.xticks(x, sample_labels, fontweight='bold') #x軸のラベルを指定する

#データラベルを棒グラフの中に追加したい場合は以下を追加する
ax = plt.gca() #gca()現在の軸情報を取得(get current axis)
handles, labels = ax.get_legend_handles_labels() #handles 線やマーカーを含んだオブジェクト labels 凡例に表示されるラベル
plt.legend(handles[::-1], labels[::-1], loc='upper left', bbox_to_anchor=(1,1)) #handles[::-1], labels[::-1]　凡例を棒グラフの順番と合わせる

for i in range(len(bar1)):
    ax.annotate(str(bar1[i]), xy=(x[i] - 0.1, (bar1[i] / 3)), color='white', fontweight='bold')
for i in range(len(bar2)):
    ax.annotate(str(bar2[i]), xy=(x[i] - 0.1, (bar2[i] / 3) + bar1[i]), color='white', fontweight='bold')
for i in range(len(bar3)):
    ax.annotate(str(bar3[i]), xy=(x[i] - 0.1, (bar3[i] / 3) + bar3_st[i]), color='white', fontweight='bold')

plt.subplots_adjust(right=0.8) #凡例のために余白を広げる rightのdefaultは0.9
plt.title('BarPlot Test')
plt.xlabel('Sample Name')
plt.ylabel('count')
plt.show()
#plt.savefig('barplot.pdf') #pdfで出力する場合
#plt.savefig('barplot.svg',format='svg') #ベクター画像で出力する場合
plt.close()

# **numpy**モジュール **add( )**
#
# ・配列の要素を足し算する。
#
#

#
# **numpy**モジュール **tolist( )**
#
# ・Numpy配列をリスト型に変換する。
#
#

#
# **pyplot**モジュール **gca( )**
#
# ・現在のAxesオブジェクトを取得する。
#
#

#
# **get_legend_handles_labels( )**
#
# ・handlerとlabelを取得する。handlerは線やマーカーを含んだオブジェクト。labelsは凡例に表示されるラベル（リスト型）。
#
# ・Axesオブジェクト用
#
#

#
# **annotate(s, xy)**
#
# ・xyで指定した位置にsで指定した文字を出力する。
#
# ・Axesオブジェクト用
#
#

#
# ---
# ### 積み上げる段が多い場合に対応できるように、for文で処理する

# In[2]:

get_ipython().run_line_magic('matplotlib', 'inline')
from matplotlib import pyplot as plt
import numpy as np

#数値は適当
bar1 = [100, 50, 200] #積み上げ棒グラフの一段目
bar2 = [100, 200, 50] #積み上げ棒グラフの二段目
bar3 = [100, 250, 100] #積み上げ棒グラフの三段目

bar_data = [bar1, bar2, bar3]

sample_labels = ['SampleA', 'SampleB', 'SampleC'] #データのラベルを指定
group_labels = ['class1', 'class2', 'class3']
x = [0, 1, 2] #棒グラフを表示させるx軸座標を決めておく
barwidth = 0.7 #棒グラフの幅を指定する。棒グラフのx軸座標を考慮して決める

fig, ax = plt.subplots() #FigureオブジェクトとAxesオブジェクトを作成

bottom_position = np.zeros(len(bar_data)) #積み上げる位置を指定するため、積み上げる段数と同じ要素数（ここではbar_dataの要素数）の一次元配列を作成する

for i in range(len(bar_data)): #一段ずつデータをaxオブジェクトに格納する
    ax.bar(x, bar_data[i], width=barwidth, bottom=bottom_position, label=group_labels[i])
    for j in range(len(bar_data[i])): #annotateはx軸のポイントごとにデータを格納する必要がるので、for文を使う
        ax.annotate(str(bar_data[i][j]), xy=(x[j] - 0.1, (bar_data[i][j] / 3) + bottom_position.tolist()[j]), color='white', fontweight='bold')
    bottom_position = np.add(bar_data[i], bottom_position)

ax.set_xticks(x)
ax.set_xticklabels(sample_labels, fontweight='bold') #x軸のラベルを指定する
handles, labels = ax.get_legend_handles_labels() #handles 線やマーカーを含んだオブジェクト labels 凡例に表示されるラベル
ax.legend(handles[::-1], labels[::-1], loc='upper left', bbox_to_anchor=(1,1)) #handles[::-1], labels[::-1]　凡例を棒グラフの順番と合わせる

fig.subplots_adjust(right=0.8) #凡例のために余白を広げる rightのdefaultは0.9
ax.set_title('BarPlot Test')
ax.set_xlabel('Sample Name')
ax.set_ylabel('Count')
plt.show()
#fig.savefig('barplot.pdf')
#fig.savefig('barplot.svg',format='svg')
plt.close()

# **numpy**モジュール **zeros(shape)**
#
# ・要素0の配列を生成する。第一引数に配列のshapeを指定できる。


#!/usr/bin/env python
''' This is the parallel recursive solution to the Tower of Hanoi and is copied
from the code written in the parallel/rebuilding-the-tower-of-hanoi/ page
of www.drdobbs.com.

The solution has been modified from drdobbs' solution to work with my limited
knowledge of mpi4py. If you use the sleep() functionality to add some dead
time into the loops - even a second will do - you'll start to see the
computation time decrease as the number of processes increases.

Currently the dead time is set to 2 seconds. The solution times for this dead
time are:
1 proc  30.50s
2 procs 17.03s
4 procs 11.14s
8 procs 9.28s

It's very hard to solve the problem in less than 12 seconds. I haven't been
able to do it!
'''

from mpi4py import MPI
import sys
import time
import math
import pickle
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
name = MPI.Get_processor_name()

def tower(src, dest, temp, idx, offset, noofdiscs, plan):
    if (offset > 0):
        # Defines the level of recursion that we are at. It runs from 0 to
        # noofdiscs-1 throughout the calculation.
        level = noofdiscs - 2 - int(math.log(offset, 2))

        # This if statement splits the processes in half at each level of
        # recursion until only one process is evaluating each 'branch'.
        # From there it evaluates all subsequent sub-branches and moves.
        if (rank % 2**(level+1) < 2**(level) and 2**(level) < size):
            # Recursively call tower again. This is the left branch, so
            # we SUBTRACT offset from idx.
            tower(src, temp, dest, idx-offset, offset/2, noofdiscs, plan);

            # Add some dead time here.
            time.sleep(2)
            # Adds the src and dest poles of move to the plan array.
            plan[idx-1][0] = src;
            plan[idx-1][1] = dest;

        elif (rank % 2**(level+1) >= 2**(level) and 2**(level) < size):
            # Add some dead time here.
            time.sleep(2)
            # Adds the src and dest poles of move to the plan array.
            plan[idx-1][0] = src;
            plan[idx-1][1] = dest;

            # Recursively call tower again. This is the right branch, so
            # we ADD offset to idx.
            tower(temp, dest, src, idx+offset, offset/2, noofdiscs, plan);

        else:
            # Recursively call tower again. This is the left branch, so
            # we SUBTRACT offset from idx.
            tower(src, temp, dest, idx-offset, offset/2, noofdiscs, plan);

            # Add some dead time here.
            time.sleep(2)
            # Adds the src and dest poles of move to the plan array.
            plan[idx-1][0] = src;
            plan[idx-1][1] = dest;

            # Recursively call tower again. This is the right branch, so
            # we ADD offset to idx.
            tower(temp, dest, src, idx+offset, offset/2, noofdiscs, plan);

    else:
        # Add some dead time here.
        time.sleep(2)
        # Once offset reaches zero the algorithm stops recursively calling
        # tower. Hence all that is left to do is populate the last elements
        # of the plan list.
        plan[idx-1][0] = src;
        plan[idx-1][1] = dest;

    return plan

def main():
    # Initialise the number of discs and the list for containing plan.
    # Initially it is populated with pairs of zeroes [0, 0], s.t. the number
    # of pairs is equal to the number of moves.
    #print "The number of processes is", size, "and this is process", rank
    noofdiscs = int(sys.argv[1])
    plan_init = []
    for i in range(0,2**noofdiscs-1):
        plan_init.append([0, 0])
    # These two variables are used to keep track of the level of recursion
    # of the method.
    idx = 2**(noofdiscs - 1)
    offset = 2**(noofdiscs-2)

    # The plan - the set of moves that solves the tower of Hanoi problem -
    # is obtained by initialising the tower function, which recursively calls
    # ifself until the full solution is found. The solution will be
    # distributed across the processes used in the calculation.
    plan = tower(0, 2, 1, idx, offset, noofdiscs, plan_init)

    # Process 0 now gathers all the modified elements of data together into a
    # new list called allplans.
    allplans = comm.gather(plan,root=0)
    #print 'allplans:',allplans
    # The command gather has stuffed a bunch of mostly empty data lists into a
    # list. The first command essentially picks out all the non-trivial data
    # from each list returned from the processes and bundles it all into one
    # list, the solution.
    if rank == 0:
            plan=[max(i) for i in zip(*allplans)]
            #print 'master:',plan

            # We use pickle to make a moves file which we write the
            # plan list. We use pickle in main() to read the list again.
            outfile=open( "moves", "wb" )
            pickle.dump(plan, outfile)

main()


import os, time
from Crypto.Random import get_random_bytes, random
from lib.logger import *
log = Logger()

'''
This class handles the BLE Beacon Transmission (TX).
Because after some time of BLE advertising, a restart of the BLE stack (hciconfig hci0 down / up) might be required,
and because the pybleno class can't be shut down and restarted properly, the actual BLE handling has been placed
in a separate python script "en_beacon.py".
'''

class ENTxService:

    def __init__(self, bdaddr_rotation_interval_min_minutes, bdaddr_rotation_interval_max_minutes):
        self.random_bdaddr = bytes([0x00] * 6)
        self.bdaddr_rotation_interval_min_seconds = bdaddr_rotation_interval_min_minutes * 60 + 1
        self.bdaddr_rotation_interval_max_seconds = bdaddr_rotation_interval_max_minutes * 60 - 1
        if self.bdaddr_rotation_interval_max_seconds < self.bdaddr_rotation_interval_min_seconds:
            self.bdaddr_rotation_interval_max_seconds = self.bdaddr_rotation_interval_min_seconds
        self.bdaddr_next_rotation_seconds = 0

    @staticmethod
    def get_current_unix_epoch_time_seconds():
        return int(time.time())

    @staticmethod
    def get_advertising_tx_power_level():
        return 12  # in real life, this info should come from the BLE transmitter

    def roll_random_bdaddr(self):
        # Create a BLE random "Non-Resolvable Private Address", i.e. the two MSBs must be 0, and not all bits 0 or 1
        while True:
            self.random_bdaddr = bytearray(get_random_bytes(6))
            self.random_bdaddr[0] = self.random_bdaddr[0] & 0b00111111
            self.random_bdaddr = bytes(self.random_bdaddr)
            if (self.random_bdaddr.hex() != "000000000000") and (self.random_bdaddr.hex() != "3fffffffffff"):
                break
        self.bdaddr_next_rotation_seconds = (self.get_current_unix_epoch_time_seconds()
                                             + random.randint(self.bdaddr_rotation_interval_min_seconds,
                                                              self.bdaddr_rotation_interval_max_seconds))

    def bdaddr_should_roll(self):
        return self.get_current_unix_epoch_time_seconds() >= self.bdaddr_next_rotation_seconds

    def start_beacon(self, rpi, aem):
        while True:
            if os.system("python3 en_beacon.py %s %s %s" % (rpi.hex(), aem.hex(), self.random_bdaddr.hex())) == 0:
                # return code 0 means: ok, advertising started.
                break
            log.log()
            log.log("ERROR: Could not start advertising! Timestamp: %s" % time.strftime("%H:%M:%S", time.localtime()))
            log.log()
            # try to recover:
            os.system("sudo hciconfig hci0 down; sudo hciconfig hci0 up")
            time.sleep(1)

    @staticmethod
    def stop_beacon():
        os.system("sudo hciconfig hci0 down; sudo hciconfig hci0 up")


import fileinput
import glob
import os
import random

import time

import re
from urllib.error import HTTPError

from arghandler import ArgumentHandler, subcmd
from google import search
from subprocess import call

from procurer import ultimate_guitar, lastfm, postulate_url
from rules import rules, clean
from songbook_converter import SongBook,  wrap, header
from writer import TexWriter, PdfWriter, FileWriter

def url(keyword):
    searchterm = "site:ultimate-guitar.com chords " + keyword
    results = search(searchterm, stop=10)
    for url in results:
        if 'search' not in url:
            return url
    raise ArithmeticError

import codecs

def filter_existing(lines):
    keywords = set(x for x in lines if not find_file_for_keyword(x))
    excluded = lines - keywords
    if excluded:
        print("Not adding some files ( use --force to override):")
        for item in excluded:
            print(item, find_file_for_keyword(item))
        print("Still looking for")
        for item in keywords:
            print(item, find_file_for_keyword(item))
    return keywords

def addsongs(keywords):
    written = []
    working = 1
    for line in keywords:
        if not working:
            written.append(line)
            continue
        try:
            source = url(line)
            artist, title, blob = ultimate_guitar(source)
            FileWriter(artist, title, blob, directory='raw/', extension='txt').write()
        except HTTPError:
            working = 0
            print("Google said fuck you")
        except Exception as e:
            print("Couldn't add " + line)
            print(e)
            written.append(line)
    return written

def find_file_for_keyword(keyword):
    globs = (filename.split("\\")[-1][:-5] for filename in glob.glob('reviewed/**'))
    for filename in globs:
         if keyword.lower() in filename.lower():
             return True
         if filename.lower() in keyword.lower():
             return True
    return False

@subcmd
def edit(parser, context, args):
    matching_files = find_file_for_keyword("".join(args))
    if len(matching_files) == 1:
        call(["texmaker", matching_files[0]])

@subcmd
def add(parser, context, args):
    source = url(args)
    artist, title, blob = ultimate_guitar(source)
    FileWriter(artist, title, blob, directory='raw/', extension='txt').write()

@subcmd
def addfile(parser, context, args):
    lines = set(line.strip() for line in open(args[0]))
    keywords = lines
    added = addsongs(keywords)
    with open("written.txt", "w") as f:
        f.write("\n".join(added))
    cleanraw(parser,context,())

def files(directory):
    for file in glob.glob(directory + "*"):
        with codecs.open(file, encoding='utf-8')as f:
            artist, title = os.path.split(file)[-1][:-4].split(" - ")
            song = f.read()
        yield artist, title, song

@subcmd
def maketex(parser, context, args=('clean',)):
    if not len(args):
        args=('clean',)
    for artist, title, blob in files(args[0] + "/"):
        converter = SongBook(artist, title, blob)
        latex = converter.produce_song()
        TexWriter(artist, title, latex, directory="library/").write()

@subcmd
def cleanraw(parser, context, args=('raw',)):
    if not len(args):
        args = ('raw',)
    for artist, title, blob in files(args[0] + "/"):
        blob = clean(blob)
        if not "[" in blob:
            blob = "[Instrumental]\n" + blob
        FileWriter(artist, title, blob, directory='clean/', extension='txt').write()
    for artist, title, blob in files("clean/"):
        blob = clean(blob)
        if not "[" in blob:
            blob = "[Instrumental]\n" + blob
        FileWriter(artist, title, blob, directory='clean/', extension='txt').write()

@subcmd
def makepdf(parser, context, args=('library',)):
    if not len(args):
        args=('library',)
    latex = (line for line in fileinput.input(glob.glob(args[0] + '/*.tex'), openhook=fileinput.hook_encoded("utf-8")))
    latex = header() + wrap("document", "\n".join(latex))
    print([(sym,ord(sym)) for sym in latex if ord(sym)>1000])
    PdfWriter("Sebastian", "Songbook", latex).write()

@subcmd
def reviewtopdf(parser, context, args):
    print("Making tex")
    maketex(parser,context,('reviewed',))
    print("Making pdf")
    makepdf(parser,context,args=('library',))
if __name__ == "__main__":
    handler = ArgumentHandler()
    handler.run()


import cv2
import numpy as np
import os
import path
import face_recognition
import getopt, sys

def getOriginalData(file):
    count_vertices = 0
    count_faces = 0
    original_coordinates = []
    faces_indices = []
    texture_coordinates = []
    texture_indices = []
    oc_file = open("Original_Vertices.txt", "w")
    fi_file = open("Face_Indices.txt", "w")
    tc_file = open("Texture_Coordinates.txt", "w")
    ti_file = open("Texture_Indices.txt", "w")
    for line in file.readlines():
        content = line.split(" ")
        # 顶点数据
        if content[0] == "v":
            count_vertices += 1
            coordinate = []
            for i in range(1, 4):
                num = float(content[i].replace("\n", ""))
                coordinate.append(num)
            original_coordinates.append(coordinate)
            oc_file.write(str(coordinate) + "\n")
        # 三角面片数据
        if content[0] == "f":
            count_faces += 1
            vertex_indices = []
            face_texture = []
            for i in range(1, 4):
                a = int(content[i].split("/")[0])
                b = int(content[i].split("/")[1])
                vertex_indices.append(a)
                face_texture.append(b)
            faces_indices.append(vertex_indices)
            texture_indices.append(face_texture)
            fi_file.write(str(vertex_indices) + "\n")
            ti_file.write(str(face_texture) + "\n")
        # 纹理数据
        if content[0] == "vt":
            coordinate = [float(content[1]), float(content[2].replace("\n", ""))]
            tc_file.write(str(coordinate) + "\n")
            texture_coordinates.append(coordinate)
    print("共有三角网格顶点 " + str(count_vertices) + " 个")
    print("共有三角网格面片 " + str(count_faces) + " 个")
    oc_file.close()
    fi_file.close()
    tc_file.close()
    ti_file.close()
    return np.array(original_coordinates, dtype=np.float32),\
           np.array(faces_indices, dtype=np.int32), \
           np.array(texture_indices, dtype=np.int32), \
           np.array(texture_coordinates, dtype=np.float32)

def getRoundingCoordinates(coordinates):
    rc_file = open("Rounding_Vertices.txt", "w")
    rounding_coordinates = np.zeros(coordinates.shape, dtype=np.int32)
    for i in range(coordinates.shape[0]):
        for j in range(coordinates.shape[1]):
            rounding_coordinates[i][j] = int(round(coordinates[i][j], 4) * 10000)
    for coordinate in rounding_coordinates:
        rc_file.write(str(coordinate) + "\n")
    rc_file.close()
    return rounding_coordinates

def getAdjustedCoordinates(coordinates, x_min, y_min):
    ac_file = open("Adjusted_Vertices.txt", "w")
    adjusted_coordinates = np.zeros(coordinates.shape, dtype=np.int32)
    print("偏移量 x : " + str(x_min) + "\ty : " + str(y_min))
    for i in range(coordinates.shape[0]):
        adjusted_coordinates[i][0] = coordinates[i][0] - x_min - 1
        adjusted_coordinates[i][1] = coordinates[i][1] - y_min - 1
        adjusted_coordinates[i][2] = coordinates[i][2]
    for coordinate in adjusted_coordinates:
        ac_file.write(str(coordinate) + "\n")
    ac_file.close()
    return adjusted_coordinates

def renderTexture(texture_coordinates, vertices_coordinates, vertices_indices,
                  texture_indices, texture_file, image):
    '''
    对图像进行着色，遍历每个三角面片，获取当前三角面片的顶点索引与贴图索引
    通过顶点索引与贴图索引获得顶点坐标与贴图坐标
    将三角形按照重心与中线分为三个小四边形并进行着色
    :param texture_coordinates:     纹理贴图坐标
    :param vertices_coordinates:    顶点坐标
    :param vertices_indices:        三角面片顶点索引
    :param texture_indices:         三角面片贴图索引
    :param texture_file:            贴图文件
    :return:
    '''
    texture = cv2.imread(texture_file, cv2.IMREAD_COLOR)
    # 获取纹理图像大小
    height, width, channels = texture.shape
    print("纹理贴图尺寸: " + str(height) + " , " + str(width) + " , " + str(channels))
    # 遍历各面
    for i in range(vertices_indices.shape[0] - 1, 0, -1):
        # 获取当前三角面片顶点索引
        index_va = vertices_indices[i][0] - 1
        index_vb = vertices_indices[i][1] - 1
        index_vc = vertices_indices[i][2] - 1
        # 获取当前三角面片顶点的贴图索引
        index_ta = texture_indices[i][0] - 1
        index_tb = texture_indices[i][1] - 1
        index_tc = texture_indices[i][2] - 1
        # 获取当前三角面片顶点坐标
        va = vertices_coordinates[index_va]
        vb = vertices_coordinates[index_vb]
        vc = vertices_coordinates[index_vc]
        # 获取当前三角面片顶点的贴图坐标
        ta = texture_coordinates[index_ta]
        tb = texture_coordinates[index_tb]
        tc = texture_coordinates[index_tc]
        # 获取贴图 BGR 值，注意贴图首先是高（行），其次是宽（列）
        ca = texture[getTexturePosition(height, 1 - ta[1]), getTexturePosition(width, ta[0])]
        cb = texture[getTexturePosition(height, 1 - tb[1]), getTexturePosition(width, tb[0])]
        cc = texture[getTexturePosition(height, 1 - tc[1]), getTexturePosition(width, tc[0])]
        # 求三角形重心坐标
        gravity_centre = []
        for j in range(3):
            gravity_centre.append(int((va[j] + vb[j] + vc[j]) / 3))
        # 求各顶点对边中点，注意此时应当舍弃 z 坐标
        ab = [int((va[0] + vb[0]) / 2), int((va[1] + vb[1]) / 2)]
        ac = [int((va[0] + vc[0]) / 2), int((va[1] + vc[1]) / 2)]
        bc = [int((vc[0] + vb[0]) / 2), int((vc[1] + vb[1]) / 2)]

        cv2.fillConvexPoly(image, np.array([[va[0], va[1]], ab, [gravity_centre[0],
                            gravity_centre[1]], ac], dtype=np.int32), ca.tolist())
        cv2.fillConvexPoly(image, np.array([[vb[0], vb[1]], ab, [gravity_centre[0],
                            gravity_centre[1]], bc], dtype=np.int32), cb.tolist())
        cv2.fillConvexPoly(image, np.array([[vc[0], vc[1]], bc, [gravity_centre[0],
                            gravity_centre[1]], ac], dtype=np.int32), cc.tolist())
    cv2.imwrite("Textured.jpg", color_image)
    return

def renderDepth(vertices_coordinates, vertices_indices, depth_image, min_depth, max_depth):
    # 生成深度图像
    # 遍历各面
    temp_depth_a = np.zeros(depth_image.shape, np.uint8)
    temp_depth_b = np.zeros(depth_image.shape, np.uint8)
    for i in range(vertices_indices.shape[0] - 1, 0, -1):
        # 获取当前三角面片顶点索引
        index_va = vertices_indices[i][0] - 1
        index_vb = vertices_indices[i][1] - 1
        index_vc = vertices_indices[i][2] - 1
        # 获取当前三角面片顶点坐标
        va = vertices_coordinates[index_va]
        vb = vertices_coordinates[index_vb]
        vc = vertices_coordinates[index_vc]
        # 计算三角面片平均深度
        mean_depth = (va[2] + vb[2] + vc[2]) / 3
        # 归一化深度为 0-255 的灰度
        scale = int((mean_depth - min_depth) / (max_depth - min_depth) * 255)
        grey_scale = [scale, scale, scale]
        cv2.fillConvexPoly(temp_depth_a, np.array([[va[0], va[1]], [vb[0], vb[1]], [vc[0], vc[1]]], dtype=np.int32), grey_scale)
    for i in range(vertices_indices.shape[0]):
        # 获取当前三角面片顶点索引
        index_va = vertices_indices[i][0] - 1
        index_vb = vertices_indices[i][1] - 1
        index_vc = vertices_indices[i][2] - 1
        # 获取当前三角面片顶点坐标
        va = vertices_coordinates[index_va]
        vb = vertices_coordinates[index_vb]
        vc = vertices_coordinates[index_vc]
        # 计算三角面片平均深度
        mean_depth = (va[2] + vb[2] + vc[2]) / 3
        # 归一化深度为 0-255 的灰度
        scale = int((mean_depth - min_depth) / (max_depth - min_depth) * 255)
        grey_scale = [scale, scale, scale]
        cv2.fillConvexPoly(temp_depth_b, np.array([[va[0], va[1]], [vb[0], vb[1]], [vc[0], vc[1]]], dtype=np.int32), grey_scale)
    for row in range(depth_image.shape[0]):
        for col in range(depth_image.shape[1]):
            front = 0
            grey_a = temp_depth_a[row][col][0]
            grey_b = temp_depth_b[row][col][0]
            if grey_a <= grey_b:
                front = grey_b
            else:
                front = grey_a
            depth_image[row][col] = front
    cv2.imwrite("Depth.jpg", depth_image)
    return

def drawTriangularMesh(vertices_indices, coordinates, image, color):
    for faces_index in vertices_indices:
        # 由索引获取坐标
        # print("三角网格索引 " + str(faces_index))
        vertex_a = coordinates[faces_index[0] - 1]
        vertex_b = coordinates[faces_index[1] - 1]
        vertex_c = coordinates[faces_index[2] - 1]
        # print("三角面片顶点坐标为 " + str(vertex_a) + "\t" + str(vertex_b) + "\t" + str(vertex_c))
        cv2.line(image, (vertex_a[0], vertex_a[1]), (vertex_b[0], vertex_b[1]), color)
        cv2.line(image, (vertex_c[0], vertex_c[1]), (vertex_b[0], vertex_b[1]), color)
        cv2.line(image, (vertex_a[0], vertex_a[1]), (vertex_c[0], vertex_c[1]), color)
    for coordinate in coordinates:
        # 注意图片的坐标是 height, width
        image[int(coordinate[1]), int(coordinate[0])] = black
    return

def getTexturePosition(length, ratio):
    p = int(np.floor(length * ratio))
    if p >= length:
        p = length - 1
    return p

def getFaceFeatures():
    #利用 FaceAlignment 获取特征坐标点
    image = face_recognition.load_image_file("./Textured.jpg")
    face_landmarks_list = face_recognition.face_landmarks(image)
    alignment_image = cv2.imread("./Textured.jpg", cv2.IMREAD_COLOR)
    alignment_coordinates = open("Alignment.txt", "w")
    if len(face_landmarks_list) >= 1:
        print("成功检测面部")
    else:
        print("未检测到面部，请核查输入文件！")
        return

    for face_landmarks in face_landmarks_list:
        # 打印此图像中每个面部特征的位置
        facial_features = [
            'chin',
            'left_eyebrow',
            'right_eyebrow',
            'nose_bridge',
            'nose_tip',
            'left_eye',
            'right_eye',
            'top_lip',
            'bottom_lip'
        ]
        for facial_feature in facial_features:
            print("The {} in this face has the following points: {}"
                  .format(facial_feature, face_landmarks[facial_feature]))
        for facial_feature in facial_features:
            #alignment_image[][] = face_landmarks[facial_feature]
            alignment_coordinates.write(facial_feature + ": " + str(face_landmarks[facial_feature]) + "\n")
    alignment_coordinates.close()
    return face_landmarks_list[0]

def drawLandmarks(face_landmarks, image):
    red = (0, 0, 255)
    for face_landmark in face_landmarks.values():
        for coordinate in face_landmark:
            cv2.circle(image, coordinate, 5, red, -1)
    cv2.imwrite("FaceLandMarked.jpg", image)

def landmarksDictToList(face_landmarks):
    all_coordinates = []
    for face_landmark in face_landmarks.values():
        for coordinate in face_landmark:
            all_coordinates.append(coordinate)
    return all_coordinates

def getSurroundFaces(adjusted_coordinates, vertices_indices, all_coordinates):
    landmarks_dict = {}
    faces_dict = {}
    landmark_triangles = open("Landmark_Triangles.txt", "w")
    for coordinate in all_coordinates:
        landmarks_dict.update({})
        faces_dict.update({str(coordinate): []})
    for vertices_index in vertices_indices:
        index_a = vertices_index[0] - 1
        index_b = vertices_index[1] - 1
        index_c = vertices_index[2] - 1
        va = adjusted_coordinates[index_a]
        vb = adjusted_coordinates[index_b]
        vc = adjusted_coordinates[index_c]
        for coordinate in all_coordinates:
            if cv2.pointPolygonTest(np.array([[va[0], va[1]], [vb[0], vb[1]], [vc[0], vc[1]]], dtype=np.int32),
                                    coordinate, False) >= 0:
                faces_dict[str(coordinate)].append([va, vb, vc])
    for landmark, triangle in faces_dict.items():
        landmark_triangles.write(str(landmark) + ":\t" + str(triangle) + "\n")
    landmark_triangles.close()
    refined = refineTriangleFaces(faces_dict)
    return refined

def refineTriangleFaces(faces_dict):
    refined = {}
    for landmark, triangles in faces_dict.items():
        if len(triangles) == 1:
            refined.update({str(landmark): triangles[0]})
        elif len(triangles) == 0:
            refined.update({str(landmark): []})
        else:
            depth = []
            for triangle in triangles:
                z = triangle[0][2] + triangle[1][2] + triangle[2][2]
                depth.append(z)
            index = np.argmin(depth)
            refined.update({str(landmark): triangles[index]})
    refined_file = open("refined.txt", "w")
    for k, v in refined.items():
        refined_file.write(str(k) + ":\t" + str(v) + "\n")
    refined_file.close()
    return refined

def getDistance(feature_a, index_a, feature_b, index_b, landmark_triangles, feature_landmarks, xy = True):
    # to be continue
    distance = 0
    return distance

def getGlassesDistanceInformation(face_landmarks):
    information_file = open("manInformation.txt", "w")
    distances = []
    a = (face_landmarks['chin'][16][0] - face_landmarks['chin'][0][0])/10
    b = (face_landmarks['right_eye'][3][0] - face_landmarks['left_eye'][0][0])/10
    c = (face_landmarks['right_eye'][1][0] + face_landmarks['right_eye'][2][0] - face_landmarks['left_eye'][1][0] - face_landmarks['left_eye'][2][0]) / 20
    d = (face_landmarks['right_eye'][1][0] - face_landmarks['left_eye'][3][0])/10
    h = (face_landmarks['right_eye'][2][1] - face_landmarks['right_eyebrow'][2][1])/10
    f = (face_landmarks['nose_bridge'][3][1] - face_landmarks['nose_bridge'][0][1])/10
    g = round(0.7 * h, 1)
    e = round(2.2 * f, 1)
    distances.append(a)
    distances.append(b)
    distances.append(c)
    distances.append(d)
    distances.append(e)
    distances.append(f)
    distances.append(g)
    distances.append(h)
    print("配镜所需参数依次为...")
    for distance in distances:
        information_file.write(str(distance) + "\n")
        print(str(distance) + " (mm)")
    information_file.close()
    return distances

def cutPointCloud(old_obj, threshold):
    # 对 z 轴设定阈值，以消除 z 坐标重复
    # obj 文件包含 顶点 v, 纹理 vt, 三角面片 f（f中存放顶点与纹理的索引） 信息
    # 通过 z 坐标过滤顶点 v，此时包含顶点 v 的三角面片也应当去除
    # 若去除三角面片，则其含有的纹理信息也应当去除
    # 首先遍历原始 obj 文件，获取顶点列表、纹理列表、三角面片索引信息列表
    # 遍历顶点列表，获取要去除的顶点的索引
    # 遍历三角面片索引信息列表，将含有要去除的索引的三角面片信息去除
    # 记录所去除的面的纹理坐标，遍历纹理列表并去除
    # 最终形成新的文件
    cut_obj = open("cut_obj.obj", "w")
    original_vertices = []
    original_texture = []
    original_faces = []
    remove_vertices_indices = set()
    remove_face_indices = set()
    remove_texture_indices = set()
    for line in old_obj.readlines():
        content = line.split(" ")
        # 顶点数据
        if content[0] == "v":
            original_vertices.append(line)
        # 三角面片数据
        if content[0] == "f":
            original_faces.append(line)
        # 纹理数据
        if content[0] == "vt":
            original_texture.append(line)
    old_obj.close()
    print("未裁剪文件 顶点:\t" + str(len(original_vertices)) +
          "\t纹理:\t" + str(len(original_texture)) + "\t三角面:\t" + str(len(original_faces)))
    for index, line in enumerate(original_vertices):
        content = line.split(" ")
        if float(content[3]) > threshold:
            remove_vertices_indices.add(index)
        else:
            continue
    for index, line in enumerate(original_faces):
        content = line.split(" ")
        for i in range(1, 4):
            v = int(content[i].split("/")[0])
            vt = int(content[i].split("/")[1])
            if v - 1 in remove_vertices_indices:
                remove_face_indices.add(index)
                remove_texture_indices.add(vt - 1)
    print("需去除点:\t" + str(len(remove_vertices_indices)) + "\t去除纹理:\t" +
          str(len(remove_texture_indices)) + "\t去除网格:\t" + str(len(remove_face_indices)))
    # 注意，f 信息中储存的索引是从 1 开始的
    # 所以上述代码索引都是从 0 开始的
    for index, line in enumerate(original_vertices):
        if index not in remove_vertices_indices:
            cut_obj.write(line)
        else:
            # 本行仅是行号补位作用，无意义
            cut_obj.write("v 0.042966 -0.094774 0.43439\n")
    for index, line in enumerate(original_texture):
        if index not in remove_texture_indices:
            cut_obj.write(line)
        else:
            cut_obj.write("vt 0.14193 0.20604\n")
    for index, line in enumerate(original_faces):
        if index not in remove_face_indices:
            cut_obj.write(line)
    cut_obj.close()

opts, args = getopt.getopt(sys.argv[1:], "o:t:")
obj_file_path = r"C:\Users\liyanxiang\Desktop\head\resUnWarpMesh.obj"
texture_file_path = r"C:\Users\liyanxiang\Desktop\head\clonedBlur.png"
for opt, value in opts:
    print("输入文件 : " + value)
    if opt == "-o":
        print("obj 文件路径为 : " + value)
        obj_file_path = value
    if opt == "-t":
        print("texture 文件路径为 : " + value)
        texture_file_path = value
obj_file = open(obj_file_path, "r")
threshold = 0.45
cutPointCloud(obj_file, threshold)
cut_obj = open("cut_obj.obj", "r")
# original_coordinates 原始顶点坐标
# vertices_indices 三角面片顶点索引
# texture_indices 三角面片贴图索引
# texture_coordinates 贴图坐标
original_coordinates, vertices_indices, texture_indices, texture_coordinates = getOriginalData(cut_obj)
cut_obj.close()
rounding_coordinates = getRoundingCoordinates(original_coordinates)
x_max = np.max(rounding_coordinates[:, 0])
x_min = np.min(rounding_coordinates[:, 0])
y_max = np.max(rounding_coordinates[:, 1])
y_min = np.min(rounding_coordinates[:, 1])
z_max = np.max(rounding_coordinates[:, 2])
z_min = np.min(rounding_coordinates[:, 2])
print("X max: " + str(x_max) + "\t\tX min: " + str(x_min) + "\nY max: " + str(y_max) +
      "\t\tY min: " + str(y_min) + "\nZ max: " + str(z_max) + "\t\tZ min: " + str(z_min))

height = int(y_max - y_min)
width = int(x_max - x_min)
depth = int(z_max - z_min)
print("图片高度为: " + str(height))
print("图片宽度为: " + str(width))
adjusted_coordinates = getAdjustedCoordinates(rounding_coordinates, x_min, y_min)
color_image = np.zeros((height, width, 3), np.uint8)
depth_image = np.zeros((height, width, 3), np.uint8)
white = (255, 255, 255)
green = (0, 255, 0)
black = (0, 0, 0)
color_image[:, :] = white
depth_image[:, :] = white

faces_coordinates_file = open("Faces_Coordinates.txt", "w")
'''
for coordinate in rounding_coordinates:
    blank_image[int(coordinate[1] - y_min - 1)][int(coordinate[0] - x_min - 1)] = black
'''

drawTriangularMesh(vertices_indices, adjusted_coordinates, color_image, green)
cv2.imwrite("Triangular.jpg", color_image)

renderTexture(texture_coordinates, adjusted_coordinates, vertices_indices, texture_indices, texture_file_path, color_image)

drawTriangularMesh(vertices_indices, adjusted_coordinates, color_image, green)
cv2.imwrite("TextureCombineTriangle.jpg", color_image)

renderDepth(adjusted_coordinates, vertices_indices, depth_image, z_max, z_min)

face_landmarks = getFaceFeatures()
drawLandmarks(face_landmarks, color_image)

all_coordinates = landmarksDictToList(face_landmarks)
landmarks_faces = getSurroundFaces(adjusted_coordinates, vertices_indices, all_coordinates)

distances = getGlassesDistanceInformation(face_landmarks)

faces_coordinates_file.close()
cv2.imshow("Created", color_image)
cv2.imwrite("Created.jpg", color_image)
print("image saved!")
#cv2.waitKey(0)
#cv2.destroyWindow()


__author__ = 'Dennis Qiu'
from PIL import Image

def de_steg(encrypted_file):
    f, e = encrypted_file.split('.')
    steg = Image.open(encrypted_file)
    out = Image.new('RGB', (steg.width,steg.height))
    for x in range(steg.width):
        for y in range(steg.height):
            r, g, b = steg.getpixel((x, y))
            rh, gh, bh = (r&0x0F)<<4, (g&0x0F)<<4, (b&0x0F)<<4
            out.putpixel((x, y), (rh, gh, bh))
    out.save(f+"hiddenImage.png")
    steg.show()
    out.show()

def im_histogram(im='lowContrastBW.png'):
    default = Image.open(im)
    h = []
    for i in range(256):
        h.append(0)
    for x in range (default.width):
        for y in range (default.height):
            p = default.getpixel((x, y))
            h[p] += 1
    default.show()
    print('List h:\n{}'.format(h))

    default_copy2 = default.copy()
    size = default.width * default.height
    Lut = im_lut(h, size)
    for x in range (default.width):
        for y in range (default.height):
            p = default.getpixel((x, y))
            default_copy2.putpixel((x, y), Lut[p])
    default_copy2.show()

def im_lut(list_h, size_n):
    lut = []
    sum_h = 0
    for i in range(256):
        sum_h += list_h[i]
        lut.append(int((255 / size_n) * sum_h))
    print('List lut:\n{}'.format(lut))
    return lut

if __name__ == '__main__':
    encrypted = 'encrypted4bits.png encrypted4bits1.png encrypted4bits2.png encrypted4bits3.png'.split()
    for e in encrypted:
        de_steg(e)
    im_histogram()


from django.contrib import admin

from .models import CalendarEvent, CalendarEventAttendee, UserCalendar

class CalendarEventAttendeeInline(admin.TabularInline):
    model = CalendarEventAttendee
    extra = 0

    autocomplete_fields = (
        'user',
    )

class UserCalendarInline(admin.TabularInline):
    model = UserCalendar
    extra = 0

    readonly_fields = (
        "uuid",
    )

@admin.register(CalendarEvent)
class CalendarEvent(admin.ModelAdmin):
    inlines = (
        CalendarEventAttendeeInline,
    )

    autocomplete_fields = (
        'organizer',
    )


#!/usr/bin/env python
from __future__ import with_statement

import logging
import logging.handlers

LOG_FILE_HDL = '/tmp/logging_example.out'
mylogger = logging.getLogger("MyLogger")
mylogger.setLevel(logging.DEBUG)

ch_handler = logging.StreamHandler()
ch_handler.setLevel(logging.DEBUG+1)

mylogger.addHandler(ch_handler)

handler = logging.handlers.TimedRotatingFileHandler(
            LOG_FILE_HDL, 'M', 1, backupCount=6)
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter("%(asctime)s--%(levelname)s--%(message)s"))

mylogger.addHandler(handler)

mylogger.log(logging.DEBUG+1, "begin")

for i in range(20):
    mylogger.debug('count i = %d' % i)

#handler.doRollover()

mylogger.log(logging.INFO, "rolled")

logging.shutdown()


import json
import codecs
import sys

if len(sys.argv) != 3:
    print('Usage: ' + sys.argv[0] + " <input json path> <output csv path>")
    exit()

infilename = sys.argv[1]
outfilename = sys.argv[2]
sep = "|"

out = open(outfilename, 'w')

def processSource(sourceStr):
    source = sourceStr.lower()
    listOfAppleDevices = ["iphone", "ipad", "for ios", "for mac", "os x", "apple.com"]
    listOfAutoTools = ["ifttt", "dlvr.it", "hootsuite", "twitterfeed", "tweetbot",
                       "twittbot", "roundteam", "hubspot", "socialoomph", "smqueue",
                       "linkis.com", "tweet jukebox", "tweetsuite", "bufferapp",
                       "thousandtweets", "postplanner", "manageflitter", "crowdfire"]
    listOfSocialPlatforms = ["facebook", "linkedin", "tumblr", "wordpress",
                             "instagram", "pinterest"]
    listOfOtherMobile = ["windows phone", "mobile web", "for blackberry"]
    if "android" in source:
        return "android"
    for apple in listOfAppleDevices:
        if apple in source:
            return "appledevice"
    if "tweetdeck" in source:
        return "tweetdeck"
    if "twitter web client" in source:
        return "webclient"
    for soc in listOfSocialPlatforms:
        if soc in source:
            return "socialsite"
    for autoTool in listOfAutoTools:
        if autoTool in source:
            return "automated"
    for i in listOfOtherMobile:
        if i in source:
            return "othermobile"
    return "other"

def isNiceRetweet(tweet):
    if 'retweeted_status' in tweet and tweet['retweeted_status'] != None:
        rts = tweet['retweeted_status']
        if ('favorite_count' in rts and rts['favorite_count'] != None and
                'retweet_count' in rts and rts['retweet_count'] != None and
                'created_at' in rts and rts['created_at'] != None and
                'source' in rts and rts['source'] != None and
                'user' in rts and rts['user'] != None and
                'followers_count' in rts['user'] and rts['user']['followers_count'] != None):
            return True
    return False

def getRetweetedTweetId(tweet, isRetweet):
    if isRetweet:
        return tweet['retweeted_status']['id']
    else:
        return None

def getRetweetedTweetTime(tweet, isRetweet):
    if isRetweet:
        return tweet['retweeted_status']['created_at']
    else:
        return None

def getRetweetedTweetLikesNum(tweet, isRetweet):
    if isRetweet:
        return int(tweet['retweeted_status']['favorite_count'])
    else:
        return 0

def getRetweetedTweetRTNum(tweet, isRetweet):
    if isRetweet:
        return int(tweet['retweeted_status']['retweet_count'])
    else:
        return 0

def getRetweetedTweetSource(tweet, isRetweet):
    if isRetweet:
        rtstr = tweet['retweeted_status']['source']
        return processSource(rtstr)
    else:
        return None

def getRetweetedTweetAuthorFollowerCount(tweet, isRetweet):
    if isRetweet:
        rts = tweet['retweeted_status']
        return rts['user']['followers_count']
    else:
        return 0

def getLang(tweet):
    if 'lang' in tweet:
        return tweet['lang']
    return None

with open(infilename, 'r') as f:
    for line in f:
        tweet = json.loads(unicode(line.encode('utf-8'), 'utf-8'))
        if "source" in tweet.keys():
            out.write(str(tweet['id']) + sep)
            out.write(str(tweet['created_at']) + sep)
            out.write(str(processSource(tweet['source'])) + sep)
            out.write(str(getLang(tweet)) + sep)
            isRetweet = isNiceRetweet(tweet)
            out.write(str(isRetweet) + sep)
            out.write(str(getRetweetedTweetId(tweet, isRetweet)) + sep)
            out.write(str(getRetweetedTweetTime(tweet, isRetweet)) + sep)
            out.write(str(getRetweetedTweetLikesNum(tweet, isRetweet)) + sep)
            out.write(str(getRetweetedTweetRTNum(tweet, isRetweet)) + sep)
            out.write(str(getRetweetedTweetSource(tweet, isRetweet)) + sep)
            out.write(str(getRetweetedTweetAuthorFollowerCount(tweet, isRetweet)) + sep)
            out.write(repr(str(tweet['text'].encode('utf-8'))))
            out.write("\n")


#!/bin/python3

import os
import sys
import pathlib
from amp_database import download_DRAMP

def check_samplelist(samplelist, tools, path):
    if(samplelist==[]):
        print('<--sample-list> was not given, sample names will be inferred from directory names')
        for dirpath, subdirs, files in os.walk(path):
            for dir in subdirs:
                if (dir not in tools):
                    samplelist.append(dir)
        return list(set(samplelist))
    else:
        return samplelist

def check_pathlist(filepaths, samplelist, fileending, path):
    if(filepaths==[]):
        print('<--path-list> was not given, paths to AMP-results-files will be inferred')
        for sample in samplelist:
            pathlist = []
            for dirpath, subdirs, files in os.walk(path):
                for file in files:
                    if ((sample in dirpath) and ((list(filter(file.endswith, fileending))!=[]))):
                        pathlist.append(dirpath+'/'+file)
            filepaths.append(pathlist)
        return filepaths
    else:
        return filepaths

def check_faa_path(faa_path, samplename):
    if(os.path.isdir(faa_path)):
        path_list = list(pathlib.Path(faa_path).rglob(f"*{samplename}*.faa"))
        if (len(path_list)>1):
            sys.exit(f'AMPcombi interrupted: There is more than one .faa file for {samplename} in the folder given with --faa_path')
        elif(not path_list):
            sys.exit(f'AMPcombi interrupted: There is no .faa file containing {samplename} in the folder given with --faa_path')
        return path_list[0]
    elif(os.path.isfile(faa_path)):
        return faa_path
    else:
        sys.exit(f'AMPcombi interrupted: The input given with --faa_path does not seem to be a valid directory or file. Please check.')

def check_ref_database(database):
    if((database==None) and (not os.path.exists('amp_ref_database'))):
        print('<--AMP_database> was not given, the current DRAMP general-AMP database will be downloaded and used')
        database = 'amp_ref_database'
        os.makedirs(database, exist_ok=True)
        db = database
        download_DRAMP(db)
        return db
    elif ((not database==None)):
        if (os.path.exists(database)):
            db = database
            print(f'<--AMP_database> = ${db} is found and will be used')
            return db
        if (not os.path.exists(database)):
            sys.exit(f'Reference amp database path {database} does not exist, please check the path.')
    elif((database==None) and (os.path.exists('amp_ref_database'))):
        print('<--AMP_database> = DRAMP is already downloaded and will be reused')
        database = 'amp_ref_database'
        db = database
        return db

def check_path(path):
    return os.path.exists(path) #returns True or False

def check_directory_tree(path, tools, samplelist):
    print(f'Checking directory tree {path} for sub-directories \n ')
    # get first level of sub-directories, check if at least one is named by a tool-name
    subdirs_1 = [x for x in os.listdir(path) if x in tools]
    if (not subdirs_1):
        sys.exit(f'AMPcombi interrupted: First level sub-directories in {path} are not named by tool-names. Please check the directories names and the keys given in "--tooldict". \n ')
    else:
        print('First level sub-directories passed check.')
    # get second level of sub-directories, check if at least one is named by a sample-name
    subdirs_2 = []
    for dir in subdirs_1:
        subdirs = [x for x in os.listdir(path+dir) if x in samplelist]
        if (subdirs):
            subdirs_2.append(subdirs)
    if (not subdirs_2):
        sys.exit(f'AMPcombi interrupted: Second level sub-directories in {path} are not named by sample-names. Please check the directories names and the names given as "--sample_list" \n ')
    else:
        print('Second level sub-directories passed check')
    print('Finished directory check')

def check_input_complete(path, samplelist, filepaths, tools):
    # 1. Head folder does not exist and filepaths-list was not given
    if((not check_path(path)) and (not filepaths)):
        sys.exit('AMPcombi interrupted: Please provide the correct path to either the folder containing all amp files to be summarized (--amp_results) or the list of paths to the files (--path_list)')
    # 2. Head folder does not exist, filepaths-list was given but no samplelist
    elif((not check_path(path)) and (filepaths) and (not samplelist)):
        sys.exit('AMPcombi interrupted: Please provide a list of sample-names (--sample_list) in addition to --path_list')
    # 3. Head folder does not exist, filepaths- and samplelist are given:
    elif((not check_path(path)) and (not filepaths) and (not samplelist)):
        for file in filepaths:
            print(f'in check_input_complete the file in filepath is:')
            # 3.1. check if paths in filepath-list exist
            if(not check_path(file)):
                sys.exit(f'AMPcombi interrupted: The path {file} does not exist. Please check the --path_list input.')
            # 3.2. check if paths contain sample-names from samplelist
            if(not any(n in file for n in samplelist)):
                sys.exit(f'AMPcombi interrupted: The path {file} does not contain any of the sample-names given in --sample_list')
    # 4. Head folder and sample-list are given
    elif((check_path(path)) and (not samplelist)):
        check_directory_tree(path, tools, samplelist)


from ..utils import Object

class ThemeParameters(Object):
    """
    Contains parameters of the application theme

    Attributes:
        ID (:obj:`str`): ``ThemeParameters``

    Args:
        background_color (:obj:`int`):
            A color of the background in the RGB24 format
        secondary_background_color (:obj:`int`):
            A secondary color for the background in the RGB24 format
        text_color (:obj:`int`):
            A color of text in the RGB24 format
        hint_color (:obj:`int`):
            A color of hints in the RGB24 format
        link_color (:obj:`int`):
            A color of links in the RGB24 format
        button_color (:obj:`int`):
            A color of the buttons in the RGB24 format
        button_text_color (:obj:`int`):
            A color of text on the buttons in the RGB24 format

    Returns:
        ThemeParameters

    Raises:
        :class:`telegram.Error`
    """
    ID = "themeParameters"

    def __init__(self, background_color, secondary_background_color, text_color, hint_color, link_color, button_color, button_text_color, **kwargs):

        self.background_color = background_color  # int
        self.secondary_background_color = secondary_background_color  # int
        self.text_color = text_color  # int
        self.hint_color = hint_color  # int
        self.link_color = link_color  # int
        self.button_color = button_color  # int
        self.button_text_color = button_text_color  # int

    @staticmethod
    def read(q: dict, *args) -> "ThemeParameters":
        background_color = q.get('background_color')
        secondary_background_color = q.get('secondary_background_color')
        text_color = q.get('text_color')
        hint_color = q.get('hint_color')
        link_color = q.get('link_color')
        button_color = q.get('button_color')
        button_text_color = q.get('button_text_color')
        return ThemeParameters(background_color, secondary_background_color, text_color, hint_color, link_color, button_color, button_text_color)


# -*- coding: utf-8 -*-
'''
This file is part of Habitam.

Habitam is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

Habitam is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public
License along with Habitam. If not, see
<http://www.gnu.org/licenses/>.

Created on Apr 21, 2013

@author: Stefan Guna
'''
from django import forms
from django.db.models.query_utils import Q
from habitam.entities.models import AccountLink
from habitam.financial.models import Account
from habitam.ui.forms.generic import NewDocPaymentForm
from django.forms.util import ErrorDict
from django.utils.translation import ugettext as _
from django.forms.forms import NON_FIELD_ERRORS

MONEY_TYPES = (
    ('cash', _('bani lichizi')),
    ('bank', _(u'bancă'))
)
TYPES = (
    ('std', _('standard')),
    ('repairs', _('repairs')),
    ('rulment', _('rulment')),
    ('special', _('special')),
)

class EditAccountForm(forms.ModelForm):
    money_type = forms.ChoiceField(label=_('Tip bani'), choices=MONEY_TYPES)
    type = forms.ChoiceField(label=_('Tip'), choices=TYPES)

    class Meta:
        model = Account
        fields = ('name', 'type', 'money_type')

    def __init__(self, *args, **kwargs):
        if 'building' in kwargs.keys():
            self._building = kwargs['building']
            del kwargs['building']
        else:
            self._building = None
        del kwargs['user']
        super(EditAccountForm, self).__init__(*args, **kwargs)
        if self.instance.type == 'penalties':
            del self.fields['type']
        if self.instance.online_payments:
            del self.fields['money_type']

    def save(self, commit=True):
        instance = super(EditAccountForm, self).save(commit=False)
        if commit:
            instance.save()
            if self._building != None:
                al = AccountLink.objects.create(holder=self._building,
                                                account=instance)
                al.save()

        return instance

    def add_form_error(self, error_message):
        if not self._errors:
            self._errors = ErrorDict()
        if not NON_FIELD_ERRORS in self._errors:
            self._errors[NON_FIELD_ERRORS] = self.error_class()
        self._errors[NON_FIELD_ERRORS].append(error_message)

class NewFundTransfer(NewDocPaymentForm):
    dest_account = forms.ModelChoiceField(label=_(u'Destinație'),
                            queryset=Account.objects.all())

    def __init__(self, *args, **kwargs):
        building = kwargs['building']
        account = kwargs['account']
        del kwargs['building']
        del kwargs['account']
        del kwargs['user']
        super(NewFundTransfer, self).__init__(*args, **kwargs)

        qdirect = Q(accountlink__holder=building)
        qparent = Q(accountlink__holder__parent=building)
        qbuilding_accounts = Q(qdirect | qparent)

        qbilled_direct = Q(collectingfund__billed=building)
        qbilled_parent = Q(collectingfund__billed__parent=building)
        qbilled = Q(qbilled_direct | qbilled_parent)
        qnotarchived = Q(~Q(collectingfund__archived=True) & qbilled)

        queryset = Account.objects.filter(Q(qbuilding_accounts | qnotarchived))
        queryset = queryset.exclude(pk=account.id).exclude(type='penalties')
        self.fields['dest_account'].queryset = queryset


import glob
import os
import shutil
import tempfile
import unittest

from ample import constants
from ample.testing import test_funcs
from ample.util import ample_util, spicker

@unittest.skip("unreliable test cases")
@unittest.skipUnless(test_funcs.found_exe("spicker" + ample_util.EXE_EXT), "spicker exec missing")
class Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.thisd = os.path.abspath(os.path.dirname(__file__))
        cls.ample_share = constants.SHARE_DIR
        cls.testfiles_dir = os.path.join(cls.ample_share, 'testfiles')
        cls.tests_dir = tempfile.gettempdir()
        cls.spicker_exe = ample_util.find_exe('spicker' + ample_util.EXE_EXT)

    def test_spicker(self):
        mdir = os.path.join(self.testfiles_dir, "models")
        models = glob.glob(mdir + os.sep + "*.pdb")
        work_dir = os.path.join(self.tests_dir, "spicker")
        if os.path.isdir(work_dir):
            shutil.rmtree(work_dir)
        os.mkdir(work_dir)
        spickerer = spicker.Spickerer(spicker_exe=self.spicker_exe)
        spickerer.cluster(models, run_dir=work_dir)
        # This with spicker from ccp4 6.5.010 on osx 10.9.5
        names = sorted([os.path.basename(m) for m in spickerer.results[0].models])
        ref = [
            '5_S_00000005.pdb',
            '4_S_00000005.pdb',
            '5_S_00000004.pdb',
            '4_S_00000002.pdb',
            '4_S_00000003.pdb',
            '3_S_00000006.pdb',
            '3_S_00000004.pdb',
            '2_S_00000005.pdb',
            '2_S_00000001.pdb',
            '3_S_00000003.pdb',
            '1_S_00000005.pdb',
            '1_S_00000002.pdb',
            '1_S_00000004.pdb',
        ]
        self.assertEqual(names, sorted(ref))  # seem to get different results on osx
        self.assertEqual(len(names), len(ref))
        # Centroid of third cluster
        self.assertEqual(
            os.path.basename(spickerer.results[2].centroid),
            '5_S_00000006.pdb',
            "WARNING: Spicker might run differently on different operating systems",
        )
        shutil.rmtree(work_dir)

if __name__ == "__main__":
    unittest.main()