from typing import Dict
import numpy as np
import torch

from scipy.ndimage import gaussian_filter1d
from scipy.signal.windows import triang
from scipy.stats import pearsonr, spearmanr, gmean

def get_text_field_mask(text_field_tensors: Dict[str, torch.Tensor]) -> torch.LongTensor:
    """
    Takes the dictionary of tensors produced by a ``TextField`` and returns a mask of shape
    ``(batch_size, num_tokens)``.  This mask will be 0 where the tokens are padding, and 1
    otherwise.

    There could be several entries in the tensor dictionary with different shapes (e.g., one for
    word ids, one for character ids).  In order to get a token mask, we assume that the tensor in
    the dictionary with the lowest number of dimensions has plain token ids.  This allows us to
    also handle cases where the input is actually a ``ListField[TextField]``.

    NOTE: Our functions for generating masks create torch.LongTensors, because using
    torch.byteTensors inside Variables makes it easy to run into overflow errors
    when doing mask manipulation, such as summing to get the lengths of sequences - see below.
    >>> mask = torch.ones([260]).byte()
    >>> mask.sum() # equals 260.
    >>> var_mask = torch.autograd.Variable(mask)
    >>> var_mask.sum() # equals 4, due to 8 bit precision - the sum overflows.
    """
    tensor_dims = [(tensor.dim(), tensor) for tensor in text_field_tensors.values()]
    tensor_dims.sort(key=lambda x: x[0])
    token_tensor = tensor_dims[0][1]

    return (token_tensor != 0).long()

def device_mapping(cuda_device: int):
    """
    In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),
    you have to supply a `map_location` function. Call this with
    the desired `cuda_device` to get the function that `torch.load()` needs.
    """
    def inner_device_mapping(storage: torch.Storage, location) -> torch.Storage:
        if cuda_device >= 0:
            return storage.cuda(cuda_device)
        else:
            return storage
    return inner_device_mapping

def query_yes_no(question):
    """ Ask a yes/no question via input() and return their answer. """
    valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
    prompt = " [Y/n] "

    while True:
        print(question + prompt, end=':')
        choice = input().lower()
        if choice == '':
            return valid['y']
        elif choice in valid:
            return valid[choice]
        else:
            print("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")

def calibrate_mean_var(matrix, m1, v1, m2, v2, clip_min=0.5, clip_max=2.):
    if torch.sum(v1) < 1e-10:
        return matrix
    if (v1 <= 0.).any() or (v2 < 0.).any():
        valid_pos = (((v1 > 0.) + (v2 >= 0.)) == 2)
        factor = torch.clamp(v2[valid_pos] / v1[valid_pos], clip_min, clip_max)
        matrix[:, valid_pos] = (matrix[:, valid_pos] - m1[valid_pos]) * torch.sqrt(factor) + m2[valid_pos]
        return matrix

    factor = torch.clamp(v2 / v1, clip_min, clip_max)
    return (matrix - m1) * torch.sqrt(factor) + m2

def resume_checkpoint(model, model_state, backbone_only=False):
    model.pair_encoder.load_state_dict(
        {k.split('.', 1)[1]: v for k, v in model_state.items() if 'pair_encoder' in k}
    )
    if not backbone_only:
        getattr(model, 'sts-b_pred_layer').load_state_dict(
            {k.split('.', 1)[1]: v for k, v in model_state.items() if 'sts-b_pred_layer' in k}
        )

    return model

def get_lds_kernel_window(kernel, ks, sigma):
    assert kernel in ['gaussian', 'triang', 'laplace']
    half_ks = (ks - 1) // 2
    if kernel == 'gaussian':
        base_kernel = [0.] * half_ks + [1.] + [0.] * half_ks
        kernel_window = gaussian_filter1d(base_kernel, sigma=sigma) / max(gaussian_filter1d(base_kernel, sigma=sigma))
        # kernel = gaussian(ks)
    elif kernel == 'triang':
        kernel_window = triang(ks)
    else:
        laplace = lambda x: np.exp(-abs(x) / sigma) / (2. * sigma)
        kernel_window = list(map(laplace, np.arange(-half_ks, half_ks + 1))) / max(map(laplace, np.arange(-half_ks, half_ks + 1)))

    return kernel_window

class STSShotAverage:
    def __init__(self, metric):
        self._pred = []
        self._label = []
        self._count = 0
        self._metric = metric
        self._num_bins = 50
        # under np.float32 division
        self._shot_idx = {
            'many': [0, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 49],
            'medium': [2, 4, 6, 8, 27, 35, 37],
            'few': [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 29, 31, 33, 39, 41, 43, 45, 47]
        }

        def get_bin_idx(label):
            _, bins_edges = np.histogram(a=np.array([], dtype=np.float32), bins=self._num_bins, range=(0., 5.))
            if label == 5.:
                return self._num_bins - 1
            else:
                return np.where(bins_edges > label)[0][0] - 1
        self._get_bin_idx = get_bin_idx

    def __call__(self, pred, label):
        self._pred += pred.tolist()
        self._label += label.tolist()
        self._count += len(pred)

    def get_metric(self, reset=False, type=None):
        label_bin_idx = list(map(self._get_bin_idx, self._label))
        def bin2shot(idx):
            if idx in self._shot_idx['many']:
                return 'many'
            elif idx in self._shot_idx['medium']:
                return 'medium'
            else:
                return 'few'
        label_category = np.array(list(map(bin2shot, label_bin_idx)))

        pred_shot = {'many': [], 'medium': [], 'few': [], 'overall': []}
        label_shot = {'many': [], 'medium': [], 'few': [], 'overall': []}
        metric = {'many': {}, 'medium': {}, 'few': {}, 'overall': {}}
        for shot in ['overall', 'many', 'medium', 'few']:
            pred_shot[shot] = np.array(self._pred)[label_category == shot] * 5. if shot != 'overall' else np.array(self._pred) * 5.
            label_shot[shot] = np.array(self._label)[label_category == shot] if shot != 'overall' else np.array(self._label)
            if 'mse' in self._metric:
                metric[shot]['mse'] = np.mean((pred_shot[shot] - label_shot[shot]) ** 2) if pred_shot[shot].size > 0 else 0.
            if 'l1' in self._metric:
                metric[shot]['l1'] = np.mean(np.abs(pred_shot[shot] - label_shot[shot])) if pred_shot[shot].size > 0 else 0.
            if 'gmean' in self._metric:
                if pred_shot[shot].size <= 0:
                    metric[shot]['gmean'] = 0.
                else:
                    diff = np.abs(pred_shot[shot] - label_shot[shot])
                    if diff[diff == 0.].size:
                        diff[diff == 0.] += 1e-10
                        metric[shot]['gmean'] = gmean(diff) if pred_shot[shot].size > 0 else 0.
                    else:
                        metric[shot]['gmean'] = gmean(np.abs(pred_shot[shot] - label_shot[shot])) if pred_shot[shot].size > 0 else 0.
            if 'pearsonr' in self._metric:
                metric[shot]['pearsonr'] = pearsonr(pred_shot[shot], label_shot[shot])[0] if pred_shot[shot].size > 1 else 0.
            if 'spearmanr' in self._metric:
                metric[shot]['spearmanr'] = spearmanr(pred_shot[shot], label_shot[shot])[0] if pred_shot[shot].size > 1 else 0.
            metric[shot]['num_samples'] = pred_shot[shot].size
        if reset:
            self.reset()
        return metric['overall'] if type == 'overall' else metric

    def reset(self):
        self._pred = []
        self._label = []
        self._count = 0


from math import radians, sin, cos, tan

ang = float(input('Digite o angulo que voce deseja: '))

sen = radians(sin(ang))
cos = radians(cos(ang))
tg = radians(tan(ang))

print('o seno, cosseno e tangente respectivamente do angulo {:.0f} é: {:.4f}, {:.4f}, {:.4f}'.format(
    ang, sen, cos, tg))


import threading
from Queue import Queue, PriorityQueue

class Thread(threading.Thread):
    output = None
    target = None
    args = None
    newborn = True

    def __init__(self, target, args):
        super(Thread, self).__init__()
        self.args = args
        self.target = target

    def run(self):
        self.newborn = False
        idx, data = self.args
        opt = self.target(data)
        self.output = (idx, opt)

class ThreadRecycler:
    args = None
    target = None
    thread = None
    state = 'stop'  # busy/stop
    name = ''

    def __init__(self, name=''):
        self.name = name

    def setTarget(self, target):
        self.target = target

    def feed(self, args):
        self.args = args

    def run(self):
        self.thread = Thread(self.args)
        self.thread.start()
        self.state = 'busy'

    def join(self):
        if self.thread.isAlive():
            self.thread.join()
        self.state = 'stop'

    def isAvailable(self):
        return not (self.thread.newborn or self.thread.isAlive())

    def get(self, block=True, timeout=None):
        if block:
            self.thread.join(timeout)
            opt = self.thread.output
        else:
            opt = self.thread.output
        self.state = 'stop'
        return opt

class Pool:
    input_queue = Queue()
    output_queue = PriorityQueue()
    thread_pool = list()

    def __init__(self, target, num_worker):
        for i in range(num_worker):
            self.thread_pool.append(ThreadRecycler(target=target, name=str(i)))

    def run(self, interval = 1):
        tsk = self.input_queue.qsize()
        hash_table = set()
        while len(hash_table) != tsk:
            for t in self.thread_pool:
                if self.input_queue.empty():
                    if t.state == 'stop':
                        t.state = 'busy'
                if t.state == 'stop':
                    data = self.input_queue.get()
                    #print '[feed] %2d -> %2s'%(data[1], t.name)
                    t.feed(data)
                    t.run()
                if t.isAvailable():
                    idx, data = t.get()
                    if idx not in hash_table:
                        hash_table.add(idx)
                        #print '[get ]       %2s -> %2d'%(t.name, data)
                        self.output_queue.put(data)

    def feed(self, data):
        for n, elem in enumerate(data):
            self.input_queue.put((n, elem))

    def get(self):
        return self.output_queue.get()


from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
import sys
from connection.connector import Connector

from qtpy import QtGui

from movement_service import MovementService
from widgets.console import Console
from widgets.render import Renderer
from widgets.stats import StatsWidget

class Window(QtWidgets.QMainWindow):
    def __init__(self):
        self.app = QApplication(sys.argv)
        super().__init__()
        self.connector = Connector(self, 'COM8', 115200)
        self.renderer = Renderer(self)
        self.movementService = MovementService(self.connector)

        self.isAlive = True

        #### <GUI> ####
        self.setGeometry(-1920, 60, 1920, 1020)
        self.setWindowTitle('ARACHNE')

        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.darkGray)
        self.setPalette(p)

        self.setCentralWidget(QWidget())

        grid_layout = QGridLayout()
        grid_layout.setColumnStretch(0, 2)
        grid_layout.setColumnStretch(1, 1)
        grid_layout.setRowStretch(0, 1)
        grid_layout.setRowStretch(1, 1)
        self.centralWidget().setLayout(grid_layout)

        self.consoleInput = Console(self)
        grid_layout.addWidget(self.consoleInput, 0, 0, 2, 1)

        self.stats = StatsWidget(self)
        grid_layout.addWidget(self.stats, 0, 1)

        grid_layout.addWidget(self.renderer, 1, 1)

        self.show()

    def tick(self):
        while self.isAlive:
            if self.connector.has_connection():
                self.connector.checkForData()
            if self.movementService.hasMove():
                self.movementService.nextMove()
            self.update()
            self.app.processEvents()

    def single_tick(self):
        if self.connector.has_connection():
            while self.connector.checkForData():
                pass
        self.update()
        self.app.processEvents()

    def update(self) -> None:
        super().update()
        self.renderer._update_canvas()
        if self.connector.has_connection():
            pass

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        self.isAlive = False
        self.app.quit()
        super().closeEvent(a0)


class DList:
    class Node:
        def __init__(self, item, prev, link):
            self.item = item
            self.prev = prev
            self.next = link

    def __init__(self):
        self.head = self.Node(None, None, None)
        self.tail = self.Node(None, self.head, None)
        self.head.next = self.tail
        self.size = 0

    def size(self): return self.size
    def is_empty(self): return self.size == 0

    def insert(self, item):
        f = self.head
        n = self.Node(item, f, f.next)
        f.next.prev = n
        f.next = n
        self.size += 1

    def insert_before(self, p, item):
        t = p.prev
        n = self.Node(item, t, p)
        t.next = n
        p.prev = n
        self.size += 1

    def insert_after(self, p, item):
        t = p.next
        n = self.Node(item, p, t)
        t.prev = n
        p.next = n
        self.size += 1

    def delete_h(self, x):
        p = x.prev
        t = x.next
        p.next = t
        t.prev = p
        self.size -= 1
        return x.item

    def search(self, target):
        p = self.head.next
        for k in range(self.size):
            if target == p.item:
                return k
            p = p.next
        return None

    def add(self, r, e):
        if self.is_empty():
            self.insert(e)
        elif self.size < r:
            self.insert_after(self.tail.prev, e)
        else:
            p = self.head.next
            while self.search(p.item)+1 != r:
                p = p.next
            self.insert_before(p, e)

    def delete(self, r):
        p = self.head.next
        while self.search(p.item) + 1 != r:
            p = p.next
        self.delete_h(p)

    def get(self, r):
        if self.size < r:
            return print('invalid position')
        p = self.head.next
        while self.search(p.item)+1 != r:
            p = p.next
        return print(p.item)

    def print(self):
        if self.is_empty():
            return print('리스트 비어있음')
        p = self.head.next
        while p != self.tail:
            if p.next != self.tail:
                print(p.item, end='')
            else:
                print(p.item)
            p = p.next
        return None

class EmptyError(Exception):
    pass

num = int(input('연산의 개수 : '))
s = DList()
for i in range(num):
    inputs = input('Input : ')
    operation = inputs[0]
    if operation == 'A':
        pos = int(inputs[2:-1])
        alphabet = inputs[-1]
        s.add(pos, alphabet)
    elif operation == 'D':
        pos = int(inputs[2:])
        s.delete(pos)
    elif operation == 'G':
        pos = int(inputs[2:])
        s.get(pos)
    elif operation == 'P':
        s.print()


import pandas as pd
import numpy as np
import datetime
from models.classification import (Perceptron, AdalineGD, AdalineSGD,
                                  LogisticRegressionGD, KNearestNeighbors)
from models.tree import DecisionTree, RandomForest
from models.regression import LinearRegressionGD, RANSACRegressor

def train_val_split(x, y, val_size=0.2):
    val_samples = int(len(x) * val_size)
    idx = np.random.permutation(len(x))
    return x[idx[val_samples:]], y[idx[val_samples:]], x[idx[:val_samples]], y[idx[:val_samples]]

def test_model(model, x_train, y_train, x_val, y_val):
    start_time = datetime.datetime.now()

    if hasattr(model, "early_stopping") and model.early_stopping:
        model.fit(x_train, y_train, x_val, y_val, early_stopping=True)
    elif isinstance(model, RANSACRegressor):
        model.fit(x_train, y_train)
    else:
        model.fit(x_train, y_train, x_val, y_val)

    if isinstance(model, (LinearRegressionGD, RANSACRegressor)):
        metric = np.sqrt(np.mean((y_val - model.predict(x_val))**2))
        metric_name = "RMSE"
    else:
        metric = np.mean(y_val == model.predict(x_val))
        metric_name = "accuracy"

    elapsed_time = (datetime.datetime.now() - start_time).total_seconds() * 1000
    return metric_name, metric, elapsed_time

def normalize(data):
    return (data - np.mean(data, axis=0)) / np.std(data, axis=0)

def load_dataset(dataset):
    data_loaders = {
        "iris": load_iris,
        "wdbc": load_wdbc,
        "realestate": load_realestate
    }
    return data_loaders[dataset]()

def load_iris():
    df = pd.read_csv("data/iris.data", header=None)
    x = df.iloc[:, [0, 2]].values
    y = np.where(df.iloc[:, 4].values == 'Iris-setosa', 1, 0)
    return normalize(x), y

def load_wdbc():
    df = pd.read_csv("data/wdbc.data", header=None).drop(columns=[0])
    df[1] = df[1].map({'M': 1, 'B': 0})
    return normalize(df.iloc[:, 1:].values), df[1].values

def load_realestate():
    df = pd.read_csv("data/real_estate.csv").drop(columns=["No"])
    return normalize(df.iloc[:, :-1].values), df.iloc[:, -1].values

def display_results(model, metric_name, metric, elapsed_time):
    print(f"{model.__class__.__name__} fitting time: {elapsed_time:.2f} ms")
    if metric_name == "accuracy":
        print(f"{model.__class__.__name__} {metric_name}: {metric:.2%}")
    else:
        print(f"{model.__class__.__name__} {metric_name}: {metric:.4f}")

def main():
    for dataset_name, models in [("wdbc", [Perceptron(), AdalineGD(), AdalineSGD(), LogisticRegressionGD(), DecisionTree(), RandomForest(n_trees=5, max_depth=1), KNearestNeighbors(k=10)]),
                                 ("realestate", [LinearRegressionGD(), RANSACRegressor(LinearRegressionGD())])]:
        x, y = load_dataset(dataset_name)
        x_train, y_train, x_val, y_val = train_val_split(x, y)

        for model in models:
            metric_name, metric, elapsed_time = test_model(model, x_train, y_train, x_val, y_val)
            display_results(model, metric_name, metric, elapsed_time)

if __name__ == "__main__":
    main()


from statistics import mean, stdev
from datetime import datetime

class Empenho:
    nrEmpenho = 0
    listDtPagamentos = []
    listValoresPagamentos = []
    datasPagamentosDateTime = []
    scoreRegularidade = 1000
    cpf = ""
    cnpj = ""
    nmFornecedor = ""
    vlEmpenho = 0
    descricao = ""
    vlMes1 = 0
    vlMedioMensal = 0

    def __init__(self, _nr_Emp, _datasPag, _valoresPag, _cpf, _cnpj, _vlEmpenho, _isSalario, _descricao, _nmFornecedor):
        self.listDtPagamentos = []
        self.listValoresPagamentos = []
        self.datasPagamentosDateTime = []
        self.scoreRegularidade = 1000
        self.vlEmpenho = _vlEmpenho
        self.cpf = _cpf
        self.cnpj = _cnpj
        self.nrEmpenho = _nr_Emp
        self.listDtPagamentos = _datasPag
        self.listValoresPagamentos = _valoresPag
        self.descricao = _descricao
        self.nmFornecedor = _nmFornecedor
        if (_isSalario == 1):
            self.getScoreRegularidadeSalario()
        else:
            self.getScoreRegularidadeAntecipacoesServicos()

    def getDtPagamentosDatetime(self):
        for i in self.listDtPagamentos:
            self.datasPagamentosDateTime.append(
                datetime.strptime(i, "%Y-%m-%d").date())
        return self.datasPagamentosDateTime

    def getScoreRegularidadeSalario(self):

        datasPagamentos = self.getDtPagamentosDatetime()
        listaSimilaridadesA30DiasIntervalo = []
        maisQueDoisPagamentos = False
        for idx in range(1, len(datasPagamentos)):
            diff = datasPagamentos[idx] - datasPagamentos[idx-1]
            listaSimilaridadesA30DiasIntervalo.append(abs(diff.days - 30))
            maisQueDoisPagamentos = True

        pagamentosNormalizados = self.listValoresPagamentos
        desvioPadrao = 0
        if (max(pagamentosNormalizados) != min(pagamentosNormalizados)):
            norm = [(float(i)-min(pagamentosNormalizados))/(max(pagamentosNormalizados) -
                                                            min(pagamentosNormalizados)) for i in pagamentosNormalizados]
            desvioPadrao = stdev(norm)

        if (maisQueDoisPagamentos):
            self.scoreRegularidade = mean(
                listaSimilaridadesA30DiasIntervalo) + desvioPadrao
        else:
            self.scoreRegularidade = 1000

    def getScoreRegularidadeAntecipacoesServicos(self):

        datasPagamentos = self.getDtPagamentosDatetime()
        listaSimilaridadesA30DiasIntervalo = []
        maisQueDoisPagamentos = False
        for idx in range(1, len(datasPagamentos)):
            diff = datasPagamentos[idx] - datasPagamentos[idx-1]
            listaSimilaridadesA30DiasIntervalo.append(abs(diff.days - 30))
            maisQueDoisPagamentos = True

        pagamentosNormalizados = self.listValoresPagamentos
        desvioPadrao = 0
        if (max(pagamentosNormalizados) != min(pagamentosNormalizados)):
            norm = [(float(i)-min(pagamentosNormalizados))/(max(pagamentosNormalizados) -
                                                            min(pagamentosNormalizados)) for i in pagamentosNormalizados]
            desvioPadrao = stdev(norm)

        dictPagsPorMes = {}
        for idx in range(len(datasPagamentos)):
            if datasPagamentos[idx].month not in dictPagsPorMes:
                dictPagsPorMes[datasPagamentos[idx].month] = self.listValoresPagamentos[idx]
            else:
                dictPagsPorMes[datasPagamentos[idx].month] += self.listValoresPagamentos[idx]

        keysList = list(dictPagsPorMes.keys())

        keysList = sorted(keysList)

        listPagsPorMes = []
        for l in keysList:
            listPagsPorMes.append(dictPagsPorMes[l])

        if (len(listPagsPorMes) > 2):
            mediaPags = mean(listPagsPorMes[1:-1])
            self.vlMedioMensal = mediaPags
            primeiroPagMensal = listPagsPorMes[0]
            self.vlMes1 = primeiroPagMensal
            percent = (primeiroPagMensal * 100) / mediaPags

            diffPercentual = (percent - 100) / 100
            # Printa diferença percentural, fornecedor e média para pagamentos por mês > 2
            #print(str(diffPercentual)+" "+self.nmFornecedor + " "+ str(mediaPags))

            incrScore = 0
            if (stdev(self.listValoresPagamentos) == 0):
                incrScore = 100

            # esse score estah muito grosseiro, precisa de melhor preparacao
            #self.scoreRegularidade = mean(listaSimilaridadesA30DiasIntervalo)  - 5*diffPercentual
            self.scoreRegularidade = - diffPercentual + incrScore
        else:
            self.scoreRegularidade = 1000

    def getScoreRegularidadeServico(self):

        datasPagamentos = self.getDtPagamentosDatetime()
        listaSimilaridadesA30DiasIntervalo = []
        maisQueDoisPagamentos = False
        for idx in range(1, len(datasPagamentos)):
            diff = datasPagamentos[idx] - datasPagamentos[idx-1]
            listaSimilaridadesA30DiasIntervalo.append(abs(diff.days - 30))
            maisQueDoisPagamentos = True

        if (maisQueDoisPagamentos):
            self.scoreRegularidade = mean(listaSimilaridadesA30DiasIntervalo)
        else:
            self.scoreRegularidade = 1000


""" Join Module
    Class-based representation of the various Join smart contracts
    (contains only what is necessary for the simulation)
"""

from pydss.pymaker.numeric import Wad, Rad
from pydss.util import require

class GemJoin:
    """
    ADDRESS = ""

    vat = Vat
    ilk_id = ""
    gem = Token
    """

    def __init__(self, vat, ilk_id, gem):
        self.ADDRESS = f"gem_join-{ilk_id}"
        self.vat = vat
        self.ilk_id = ilk_id
        self.gem = gem

    def join(self, sender, usr, wad):
        require(wad >= Wad(0), "GemJoin/overflow")
        self.vat.slip(self.ilk_id, usr, wad)
        require(
            self.gem.transferFrom(sender, self.ADDRESS, float(wad)),
            "GemJoin/failed-transfer",
        )

    def exit(self, sender, usr, wad):
        require(wad <= Wad(2 ** 255), "GemJoin/overflow")
        self.vat.slip(self.ilk_id, sender, Wad(0) - wad)
        require(
            self.gem.transferFrom(self.ADDRESS, usr, float(wad)),
            "GemJoin/failed-transfer",
        )

class DaiJoin:
    """
    ADDRESS = str

    vat = Vat
    dai = Token
    """

    def __init__(self, vat, dai):
        self.ADDRESS = "dai_join"
        self.vat = vat
        self.dai = dai

    def join(self, sender, usr, wad):
        self.vat.move(self.ADDRESS, usr, Rad(wad))
        self.dai.burn(sender, float(wad))

    def exit(self, sender, usr, wad):
        self.vat.move(sender, self.ADDRESS, Rad(wad))
        self.dai.mint(usr, float(wad))


from tkinter import *
from tkinter import ttk
from tkinter import messagebox
pagina = Tk()
pagina.resizable(width = False, height = False)
panza = Canvas(pagina, width = "400", height = "300")
panza.pack()
butoane = [
    '(',')','n!','<-',
    '7','8','9','*',
    '4','5','6','/',
    '1','2','3','+',
    '.','0','-','Clear'
]
scris = Entry(panza,selectbackground="black",selectforeground="red", selectborderwidth=5,   width = 62 )
scris.grid(row = 0,column = 1, columnspan = 4)
ttk.Style().configure("TButton", padding = 10, relief = "flat", background = "black" )
c = 3
cc = 0
deschis = 0
semne2 = 0
for i in butoane:
    cc += 1
    ttk.Button(panza, text = i , command = lambda x = i :adauga(x)).grid(row = c, column = cc)
    if (cc == 4):
        cc = 0
        c += 1
ttk.Button(panza, text = "=", width = 58, command = lambda x = '=':adauga(x)).grid(row = 8,column = 0, columnspan = 5)

def adauga(x):
    ok = False
    if (x == '('):
        global deschis
        deschis += 1
    semne1 = ['+','-','*','/']
    if (x in semne1):
        global semne2
        semne2 += 1
    semne = ['1','2','3','4','5','6','7','8','9','0','+','-','*','/','.','(']
    for i in semne:
        if (i == x):
            ok = True
    if (ok == True):
        y = scris.get()
        scris.insert(len(y),x)
    elif (x == "Clear"):
        semne2 = 0
        scris.delete(0,END)
    elif (x == ")" and deschis != 0):
        y = scris.get()
        scris.insert(len(y),x)
        deschis -= 1
    elif ( x == ")" and deschis == 0):
        messagebox.showerror('Eroare','Paranteza nu are pereche')
    elif (x == "<-"):

        y = scris.get()
        if (len(y) > 0):
            if (y[len(y)-1] in semne1 ):
                semne2 -= 1
        scris.delete(len(y)-1,len(y))
    elif (x == "n!" and semne2 != 0):
        messagebox.showerror("Eroare!","Trebuie sa ai doar un numar pentru a efectua factorialul")
    elif ((x == "n!") and semne2 == 0):
        y = int (scris.get())
        if (y > 100):
            messagebox.showwarning("Warning!","Numarul este prea mare,va supraincarca sistemyl!!")
        else:
            yy = 1
            for i in range(1,y+1):
                yy *= i
            scris.delete(0,END)
            scris.insert(0,yy)
    elif (x == '='):
        semne3 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-', '*', '/', '.', '(',')']
        y = scris.get()
        okk = False
        oj = True
        for i  in y:
            for j in semne3:
                if (i == j): okk = True
            if (okk == False) : oj = False
        if (oj == True):
            try :
                yy = int (eval(scris.get()))
                scris.delete(0,END)
                scris.insert(0,yy)
                semne2 = 0
            except:
                messagebox.showerror("Eroare!","Matinca undeva imparte la zero sau ai pus egal aiurea sau ceva la paranteze")
        else:
            messagebox.showerror("Eroare!","Ceva nu ai facut bine!")

pagina.mainloop()


#!/usr/bin/env python3
# vim: set fileencoding=utf-8 :

from argparse import ArgumentParser
from calendar import timegm
from pathlib import Path
from time import sleep, strptime, time
from urllib.parse import quote

import db
import json
import os
import requests
import shelve
import sys

argparser = ArgumentParser(description='''
  Fetch tweets that match a query, and add them to db/tweets.
''')

defaultargs = {}
configpath = Path('db/config.json')
try:
  with configpath.open() as config:
    defaultargs = json.load(config)
    if False:
      print(defaultargs)
except Exception as e:
  sys.stderr.write('W: no db/config.json {}\n'.format(e))
def argdef(k):
  return defaultargs[k] if k in defaultargs else None

argparser.add_argument('-q',
  help='query')
argparser.add_argument('-geocode', default=argdef('geocode'),
  help='e.g., 44.447924,26.097879,150km')
argparser.add_argument('-authors', default=argdef('authors'), nargs='+',
  help='filter by author')
argparser.add_argument('-count', default=argdef('count'), type=int,
  help='batch size')
argparser.add_argument('-total', default=argdef('total'), type=int,
  help='total number of tweets to fetch')
argparser.add_argument('-delay', default=argdef('delay'), type=float,
  help='delay between batches, in seconds')
argparser.add_argument('-r', '--refetch', action='store_true',
  help='refetch tweets even if we have them')
argparser.add_argument('-verbose', action='store_true')
argparser.add_argument('-d', '--debug', action='store_true',
  help='print to stderr how tweets are parsed')

SEARCH_API_URL = 'https://api.twitter.com/1.1/search/tweets.json'
verbose = None

args = None

# used (rarely) for flow control
class Done(BaseException):
  pass
class NoNewResults(BaseException):
  pass

oauth2_headers = None

last_get = None
def get(url, delay):
  global oauth2_headers
  global last_get
  if last_get:
    sleep(max(0, time() - delay - last_get))
  if False:
    print('GET ', url)
  if oauth2_headers is None:
    with open('secret.credentials') as f:
      for line in f:
        ws = line.split()
        if ws[0] == 'access-token':
          oauth2_headers = {'Authorization' : 'Bearer {}'.format(ws[1])}
          break
  if oauth2_headers is None:
    sys.stderr.write('Please run oauth.py\n')
    raise NoNewResults
  r = requests.get(url, headers=oauth2_headers)
  if verbose and 'x-rate-limit-remaining' in r.headers:
    sys.stderr.write('api-rate-limit-remaining {}\n'.format(r.headers['x-rate-limit-remaining']))
  last_get = time()
  return r.json()

def build_query(q, geocode, count, authors):
  query = ''
  query += '?result_type=recent'
  assert count is not None
  query += '&count={}'.format(count)
  if authors:
    if q is None:
      q = ''
    qs = ['{} from:{}'.format(q, a) for a in authors]
    query += '&q={}'.format(quote(' OR '.join(qs)))
  elif q:
    query += '&q={}'.format(quote(q))
  if geocode:
    query += '&geocode={}'.format(geocode)
  return query

def time_of_raw_tweet(t):
  assert 'created_at' in t
  return timegm(strptime(t['created_at'], '%a %b %d %H:%M:%S +0000 %Y'))

def postprocess_raw_tweets():
  with shelve.open('db/raw') as raw:
    # Update users.
    with shelve.open('db/users') as users:
      for t in raw.values():
        u = t['user']
        users[u['id_str']] = db.User(u['screen_name'])
        for u in t['entities']['user_mentions']:
          users[u['id_str']] = db.User(u['screen_name'])
        if t['in_reply_to_user_id_str']:
          if t['in_reply_to_screen_name']:
            users[t['in_reply_to_user_id_str']] = db.User(t['in_reply_to_screen_name'])

    # Update tweets.
    with shelve.open('db/tweets') as tweets:
      for i, t in raw.items():
        if not args.refetch and i in tweets:
          sys.stderr.write('W: tweet {} already in db\n'.format(i))
        else:
          text = t['text']
          time = time_of_raw_tweet(t)
          author = t['user']['id_str']
          mention = db.Mention()
          for u in t['entities']['user_mentions']:
            mention.users.add(u['id_str'])
          if t['in_reply_to_user_id_str']:
            mention.users.add(t['in_reply_to_user_id_str'])
          for u in t['entities']['urls']:
            mention.urls.add(u['expanded_url'])
          if 'retweeted_status' in t:
            mention.tweets.add(t['retweeted_status']['id_str'])
            mention.users.add(t['retweeted_status']['user']['id_str'])
            for u in t['retweeted_status']['entities']['urls']:
              mention.urls.add(u['expanded_url'])
          if 'quoted_status' in t:
            mention.tweets.add(t['quoted_status']['id_str'])
            mention.users.add(t['quoted_status']['user']['id_str'])
            for u in t['quoted_status']['entities']['urls']:
              mention.urls.add(u['expanded_url'])
          parsed = db.Tweet(text, time, author, mention)
          tweets[i] = parsed
          if args.debug:
            json.dump({'in':t, 'out':parsed.as_dict()}, sys.stderr)
            sys.stderr.write('\n')
  os.remove('db/raw')

bad_times = False
def check_times(tweets):
  global bad_times
  if bad_times:
    return
  p = None
  bad = False
  for t in tweets:
    if p is None:
      p = time_of_raw_tweet(t)
    else:
      n = time_of_raw_tweet(t)
      if p < n:
        bad_times = True
        sys.stderr.write('W: tweet times are not ordered\n')

def main():
  global args
  global verbose
  args = argparser.parse_args()
  verbose = args.verbose
  if not args.authors:
    args.authors = [[]]
  else:
    args.authors = [args.authors[i:i+5] for i in range(0,len(args.authors),5)]
  args.total = 1 + args.total // len(args.authors)
  for authors in args.authors:
    processed = 0
    sys.stderr.write('fetching {} from {}\n'.format(args.total, ' '.join(authors)))
    query = build_query(args.q, args.geocode, args.count, authors)
    try:
      with shelve.open('db/tweets') as tweets:
        with shelve.open('db/raw') as raw:
          page = get('{}{}'.format(SEARCH_API_URL, query), args.delay)
          while True:
            check_times(page['statuses'])
            for s in page['statuses']:
              if not args.refetch and s['id_str'] in tweets:
                raise Done # assumes that times are descending
              raw[s['id_str']] = s
              processed += 1
              if args.total and processed >= args.total:
                raise Done
            raw.sync()
            sys.stderr.write('fetched {} tweets\n'.format(processed))
            if 'next_results' not in page['search_metadata']:
              if not args.refetch:
                sys.stderr.write('W: gap in tweet data; run me more often\n')
              raise Done
            query = page['search_metadata']['next_results']
            page = get('{}{}'.format(SEARCH_API_URL, query), args.delay)
    except Done:
      sys.stderr.write('fetched {} tweets (DONE)\n'.format(processed))
    except NoNewResults:
      sys.stderr.write('no tweets to fetch\n')
    postprocess_raw_tweets()

if __name__ == '__main__':
  main()


import requests
import json

def merge_response(url):
    # Call the target api endpoint and receive it's content in json format
    r = requests.get(url)
    if r.status_code != 200:
        return False
    res = json.loads(r.text)

    # Construct a new dict where  key: priority value / value: dict with values
    new_res = {}
    for i in res["ranked"]:
        new_res[i["priority"]] = i["vals"]

    # Sort the constructed dict by the priority in descending order
    sorted_res = dict(sorted(new_res.items(), reverse=True))

    # Merge values according to their priority, where lower priority overwrites higher priority
    result = {}
    for i in sorted_res.values():
        for j in i:
            if not j.startswith('skip'):
                result[j] = i[j]
    return result


import tensorflow as tf
import sys
import time
import numpy as np
from sparse_factorize_tensorflow import *

if __name__=="__main__":
    np.random.seed(0)
    tf.set_random_seed(0)
    random.seed(0)

    factorize_dimension = int(sys.argv[1])
    product_of_n_matrices_generation = int(sys.argv[2])
    hyperparameter_space = eval(open(sys.argv[3], "r").read())
    outdir = sys.argv[4]
    if len(sys.argv) > 5:
        load_from = sys.argv[5]
    else:
        load_from = None

    matrix_to_factorize = debug_generate_factorizable_matrix(factorize_dimension, product_of_n_matrices_generation)

    n_matrices_ranges = [2, 10, 15, 20, 30]
    #n_matrices_ranges = [30]
    sparsity_ranges = [.1, .2, .4, .6, .8, .9]

    binned_results = {}
    for a in n_matrices_ranges:
        for b in sparsity_ranges:
            binned_results[(a,b)] = []

    # Load from pikle
    if load_from is not None:
        binned_results = pkl.load(open(load_from, "rb"))
        for k,v in binned_results.items():
            print(k, len(v))

    n_to_collect_per_bin = 15

    while True:
        for n_matrices in n_matrices_ranges:
            hyperparameters = sample_from_space(hyperparameter_space)
            hyperparameters["n_matrices_to_factorize_into"] = n_matrices
            hyperparameters["intermediate_dimension"] = factorize_dimension
            results = sparse_factorize(matrix_to_factorize, **hyperparameters)

            n_nnz_elements = results["n_nnz_elements"]
            orig_nnz_elements = np.prod(results["target_matrix"].shape)
            result_sparsity = n_nnz_elements / orig_nnz_elements

            for i in range(len(sparsity_ranges)):
                if i == 0:
                    lower = 0
                else:
                    lower = sparsity_ranges[i-1]
                upper = sparsity_ranges[i]
                if lower <= result_sparsity and result_sparsity <= upper:
                    binned_results[(n_matrices, upper)].append(results)

        lengths = [len(v) for k,v in binned_results.items()]
        print("Progress: ", lengths)
        if min(lengths) >= n_to_collect_per_bin:
            break

        with open("%s/factorization_experiment_dim=%d_nprod=%d" % (outdir, factorize_dimension, product_of_n_matrices_generation), "wb") as f:
              pkl.dump(binned_results, f)


import requests
import datetime
from config import open_weather_token

def get_weather(city, open_weather_token):

    code_to_smile = {
        "Clear":"Ясно ☀",
        "Clouds": "Облачно ⛅",
        "Rain": "Дождь 🌨",
        "Drizzle": "Дождь \U00002614",
        "Thunderstorm": "Гроза \U000026A1",
        "Snow": "Снег \U0001F328",
        "Mist": "Туман \U0001F32B",
    }

    try:
        r = requests.get(
            f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={open_weather_token}&units=metric"
        )
        data = r.json()
        # pprint(data)

        city = data["name"]
        cur_weather = data["main"]["temp"]

        weather_des = data["weather"][0]["main"]
        if weather_des in code_to_smile:
            wd = code_to_smile[weather_des]
        else:
            wd = "Сам посмотри что за погода я не знаю!"

        humidity = data["main"]["humidity"]
        pressure = data["main"]["pressure"]
        wind = data["wind"]["speed"]
        sunrise_ts = datetime.datetime.fromtimestamp(data["sys"]["sunrise"])
        sunset_ts = datetime.datetime.fromtimestamp(data["sys"]["sunset"])
        length_of_day = datetime.datetime.fromtimestamp(data["sys"]["sunset"]) - datetime.datetime.fromtimestamp(data["sys"]["sunrise"])

        print(f"***{datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}***\n"
                f"Погода в городе: {city}\nТемпература: {cur_weather}C {wd}\n"
                f"Влажность: {humidity}%\nДавление: {pressure} мм.рт.ст\nВетер: {wind}\n"
                f"Восход солнца: {sunrise_ts}\nЗакат солнца: {sunset_ts}\nПродолжительность дня: {length_of_day}\n"
                f"Хорошего для!")

    except Exception as ex:
        print(ex)
        print("Error")

def main():
    city = input("Enter city name: ")
    get_weather(city, open_weather_token)

if __name__ == '__main__':
    main()

# api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}


from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import User, Project
from django.forms.widgets import TextInput, Textarea, ChoiceWidget
from django.utils import timezone
from task_tracker.models import Status, Task

class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm):
        model = User
        fields = ('username', 'password1', 'password2')

class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = User
        fields = ('username', 'password')

class ProjectForm(forms.ModelForm):

    class Meta:
        model = Project
        fields = ('user', 'project_name', 'project_text')
        exclude = ( 'user',)
        widgets = {
            "project_name": TextInput(
                attrs={
                    'placeholder': 'Название'
                }
            ),
            "project_text": Textarea(
                attrs={
                    'placeholder': 'Текст'
                }
            )
        }

class TaskForm(forms.ModelForm):

    class Meta:
        model = Task
        fields = ('project', 'task_name', 'task_text', 'status')
        exclude = ( 'project',)
        widgets = {
            "task_name": TextInput(
                attrs={
                    'placeholder': 'Название'
                }
            ),
            "task_text": Textarea(
                attrs={
                    'placeholder': 'Текст'
                }
            )
        }


# -*- coding: utf-8 -*-
# It's work!
import requests
from bs4 import BeautifulSoup as BS
import codecs
import time

stop_list = ['Senior', 'Sr.']
template = '<!doctype html><meta charset="utf-8">'
end = ''

session = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:47.0) Gecko/20100101 Firefox/47.0','Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
base_url = 'https://djinni.co/jobs/?primary_keyword=Python&location=%D0%9A%D0%B8%D0%B5%D0%B2'
urls = []
urls.append(base_url)
urls.append(base_url+'&page=2')
jobs = []
a_href = 'https://djinni.co'
for url in urls:
    req = session.get(url, headers=headers)
    time.sleep(2)
    if req.status_code == 200:
        bsObj = BS(req.content, "html.parser")
        list_of_li = bsObj.find_all('li', attrs={'class':'list-jobs__item'})
        if list_of_li:
            for li in list_of_li:
                div = li.find('div', attrs={'class':'list-jobs__title'})
                # print('div', div.a['href'], div.a.text)
                div_description = li.find('div', attrs={'class':'list-jobs__description'})
                descr='No Discription!'
                title = div.a.text
                if div_description:
                    descr=div_description.p.text
                title_list = title.split(' ')
                if not any(word in stop_list for word in title_list):
                    jobs.append({'href': a_href+div.a['href'],
                                    'title': title,
                                    'descript': str(descr)})

        else:
            jobs.append({'href': url,
                            'title': 'djinni.co - The page is empty',
                            'descript': ''
                                })
    else:
        jobs.append({'href': base_url,
                        'title': 'djinni.co - Page do not response',
                        'descript': ''
                            })
content = '
 Djinni
'
for job in jobs:
    content += '{}

{}

'.format(job['href'], job['title'], job['descript'])
    content += '--------------

'
data = template + content + end
handle = codecs.open('djinni.html', "w", 'utf-8')
handle.write(str(data))
handle.close()


#import dependency yang dibutuhkan
import numpy as np

#fungsi untuk mengeksport console ke puzzle
def consoleToPuzzle():
    puzzle = [[0] * 4 for _ in range(4)]
    for i in range(4):
        lines = list(map(int, input().split()))
        for j in range(4):
            puzzle[i][j] = lines[j]
    puzzles = np.reshape(puzzle,(4,4)).astype('int32')
    #Mengembalikan puzzle
    return puzzles

#fungsi untuk membaca file
def readFile(filename):
    f = open(filename,"r")
    return f

#fungsi untuk mengubah file ke puzzle
def fileToPuzzle(filename):
    text = readFile(filename)
    temp = text.read().split()
    puzzle = np.reshape(temp,(4,4)).astype('int32')
    return puzzle

#fungsi untuk mencetak path
def cetakPath(simpul):
    if(simpul.parent == None):
        return
    cetakPath(simpul.parent)
    print("\033[35m\n==============================\033[0m")
    print("\033[31mLangkah ke - "+str(simpul.dalam)+" : "+"\033[0m")
    #cetak puzzle
    cetakPuzzle(simpul.puzzle)

#fungsi untuk mencetak puzzle
def cetakPuzzle(puzzle):
    print("\033[34m╔═══╦═══╦═══╦═══╗\033[0m")
    for i in range(4):
        for j in range(4):
            print("\033[34m║\033[0m ",end="")
            print(puzzle[i][j], end="")
            if(puzzle[i][j] < 10):
                print(" ", end="")
        print("\033[34m║\033[0m")
        if(i != 3):
            print("\033[34m╠═══╬═══╬═══╬═══╣\033[0m")
    print("\033[34m╚═══╩═══╩═══╩═══╝\033[0m")

#fungsi untuk mengecek apakah puzzle kosong
def cekApakahKosong(puzzle):
    for i in range(4):
        for j in range(4):
            if(puzzle[i][j] == 0):
                row = i
                column = j
    return row,column

#fungsi untuk mengubah angka 0 menjadi posisi yang seharusnya
def ubahAngka0(puzzle):
    x,y = cekApakahKosong(puzzle)
    puzzle[x][y] = 16
    return puzzle

#fungsi untuk mencari nilai x
def temukanX(puzzle):
    puzzle_temp = puzzle.copy()
    x,y = cekApakahKosong(puzzle_temp)
    sum = x+y
    return (sum % 2)

#fungsi untuk menghitung cost
def hitungCost(dalam,puzzle,mat):
    hitung = 0
    for i in range(4):
        for j in range(4):
            if((puzzle[i][j] != mat[i][j]) and puzzle[i][j] != 0):
                hitung += 1
    return (dalam+hitung)

#fungsi untuk mencari nilai fungsi kurang setiap ubin
def fungsiKurang(puzzle):
    hitung = 0
    puzzle_temp = puzzle.copy()
    puzzle_temp = ubahAngka0(puzzle_temp)
    puzzle_temp = np.reshape(puzzle_temp,(16,))
    for i in range(16):
        temp = puzzle_temp[i]
        for j in range(i,16):
            if(temp > puzzle_temp[j]):
                hitung += 1
    return hitung

#fungsi untuk mencetak fungsi kurang setiap ubin
def cetakFungsiKurang(puzzle):
    puzzle_temp = puzzle.copy()
    puzzle_temp = ubahAngka0(puzzle_temp)
    puzzle_temp = np.reshape(puzzle_temp,(16,))
    for i in range(16):
        hitung = 0
        temp = puzzle_temp[i]
        for j in range(i,16):
            if(temp > puzzle_temp[j]):
                hitung += 1
        print("Fungsi Kurang("+ str(temp)+") = "+ str(hitung))

#fungsi untuk mencari nilai sum
def result(puzzle):
    sum = temukanX(puzzle)
    sum += fungsiKurang(puzzle)
    return sum

#fungsi untuk menentukan apakah puzzle dapat diselesaikan
def solvable(puzzle):
    sum = result(puzzle)
    if(sum % 2 == 0):
        return True
    else:
        return False

#fungsi untuk menukar posisi puzzle
def swap(puzzle,row,column):
    x,y = cekApakahKosong(puzzle)
    puzzle[x][y] = puzzle[row][column]
    puzzle[row][column] = 0
    return puzzle

#fungsi untuk mencari nilai pindah
def move(puzzle,pindah):
    puzzle_temp = puzzle.copy()
    x,y = cekApakahKosong(puzzle_temp)
    if(pindah == "left"):
        if(y != 0):
            y -= 1
    elif(pindah == "right"):
        if(y != 3):
            y += 1
    elif(pindah == "up"):
        if(x != 0):
            x -= 1
    elif(pindah == "down"):
        if(x != 3):
            x += 1
    puzzle_temp = swap(puzzle_temp,x,y)
    return puzzle_temp

#fungsi untuk mencari lawan dari move
def move_mirror(pindah):
    if(pindah == "left"):
        return "right"
    elif(pindah == "right"):
        return "left"
    elif(pindah == "up"):
        return "down"
    elif(pindah == "down"):
        return "up"

#fungsi untuk mengecek apakah kedua puzzle sama
def apakahSama(puzzle,mat):
    for i in range(4):
        for j in range(4):
            if(puzzle[i][j] != mat[i][j]):
                return False
    return True


class Singleton(object):
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance

s_instance1 = Singleton()
s_instance1.name = "Singleton1"

s_instance2 = Singleton()
s_instance2.name

print("Printing class instance 1 \"name\" attibute %s" % s_instance1.name)
print("Printing class instance 2 \"name\" attibute %s" % s_instance2.name)

# notes: limitation of Singleton - when used as a  subclass , the subclass will not follow as singleton (solution is to use BorgSingleton pattern)


def finonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        arr = [0] * (n+1) #inicializar valores a cero

        arr[0] = 1
        arr[1] = 1

        for i in range(2, n+1):
            arr[i] = arr[i-2] + arr[i-1]
        return(arr[n])

print(finonacci(10000))


import math
from typing import Tuple

import noise

ZONES = {
    "S": (0.0, 0.3),  # Snow
    "F": (0.3, 0.4),  # Forest
    "P": (0.4, 0.7),  # Forest
    "D": (0.7, 1.0)  # Desert
}

def get_for_noise(noise_val):
    noise_val += 1.0
    noise_val /= 2.0
    noise_val = max(0.00, noise_val)
    noise_val = min(0.99, noise_val)

    for zone, temperature in ZONES.items():
        if temperature[0] <= noise_val < temperature[1]:
            return zone

def noise_octave(noise_func=None, octaves: int = 1, persistence: float = 1.0, coordinates: Tuple[float, ...] = ()):
    total = 0.0
    frequency = 1.0
    amplitude = 1.0
    max_value = 0.0
    for _ in range(octaves):
        noise_value = noise_func(*tuple(coord * frequency for coord in coordinates)) * amplitude
        total += noise_value
        max_value += amplitude

        amplitude *= persistence
        frequency *= 2

    return total / max_value

def generate_terrain(dimensions, zone_size=15, spawn_range=50, seed=None):
    # map_middle = dimensions // 2
    # map = [["?" for x in range(dimensions)] for y in range(dimensions)]
    # features = [[None for x in range(dimensions)] for y in range(dimensions)]
    #
    # if not seed:
    #     seed = random.randrange(-1000, 1000)
    #
    # for x in range(dimensions):
    #     for y in range(dimensions):
    #         # within_spawn_range = spawn_range > math.sqrt((x - map_middle) ** 2 + (y - map_middle) ** 2)
    #         pass

    pass

def tile_terrain(x: int, y: int, seed: int, map_size: int, spawn_range=50):
    map_middle = map_size // 2
    terrain_data = get_for_noise(
        noise_octave(
            noise_func=noise.snoise3,
            octaves=2,
            persistence=0.1,
            coordinates=(x / 40, y / 40, seed)
        )
    )
    feature = ""

    # Since we want to avoid having a lot of water near the spawn range, we can use
    # a down-pointing elliptic paraboloid to represent the probability of a river at
    # that position.

    # This is all ad-hoc. Not a lot of thought went into the math.

    # check if the coordinates are within the spawn range (pythagoras theorem)
    max_noise_range = 0.15
    within_spawn_range = spawn_range > math.sqrt((x - map_middle) ** 2 + (y - map_middle) ** 2)
    if within_spawn_range:
        max_noise_range /= 2
        # max_noise_range = ((x ** 2) / 16 + (y ** 2) / 16) / 100000
    river_val = noise_octave(
        noise_func=noise.snoise3,
        octaves=1,
        persistence=0.1,
        coordinates=(x / 50, y / 50, seed)
    )

    if max_noise_range > river_val > 0.0:
        terrain_data = "W"

    # For cities, we will base it off the river noise (cities are typically close to water bodies).
    # But since we don't want cities everywhere, we will do a noise cross between the river noise
    # and a new noise (nRiver X nCities) = nCoastCities.

    city_val = noise_octave(
        noise_func=noise.snoise3,
        octaves=2,
        persistence=0.2,
        coordinates=(x / 30, y / 30, seed)
    )

    if max_noise_range + 0.2 > river_val > max_noise_range > city_val > 0:
        feature = "fC"

    # For shelters, we'll try to keep them pretty far from the cities for the added challenge.
    # The generation is done by making a highly sparse (+octave) noise and using an invert treshold from
    # the cities

    shelter_val = noise_octave(
        noise_func=noise.snoise3,
        octaves=4,
        persistence=0.4,
        coordinates=(x, y, seed)
    )

    if max_noise_range + 0.8 > shelter_val > max_noise_range + 0.75:
        feature = "fS"

    return terrain_data, feature


import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

def is_element_present(how, what):
    if len(driver.find_elements(by=how, value=what)) == 0:
        return False
    else:
        return True

driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())

driver.get('http://www.tizag.com/htmlT/htmlcheckboxes.php')
driver.maximize_window()
driver.implicitly_wait(10)

# driver.find_element(By.XPATH, '//div[4]//input[1]').click()
# driver.find_element(By.XPATH, '//div[4]//input[2]').click()
# driver.find_element(By.XPATH, '//div[4]//input[3]').click()
# driver.find_element(By.XPATH, '//div[4]//input[4]').click()

# i = 1
#
# while is_element_present(By.XPATH, "//div[4]/input["+str(i)+"]"):
#     driver.find_element(By.XPATH, "//div[4]/input["+str(i)+"]").click()
#     i += 1

# print('Total checkboxes are :', i - 1)

checkboxes = driver.find_elements(By.NAME, 'sports')
print(len(checkboxes))

block = driver.find_element(By.XPATH, "//div[@class='display'][1]")

checkbox_in_block = block.find_elements(By.NAME, 'sports')
print(len(checkbox_in_block))

for checkbox in checkboxes:
    print('Before clicking: ', checkbox.is_selected())
    checkbox.click()
    print('After clicking: ', checkbox.is_selected())

time.sleep(3)


from binary_tree import *
import argparse
import csv
import sys

parser = argparse.ArgumentParser(description='annotate with genome loci')
parser.add_argument('input_csv', type=argparse.FileType('r'), help='final checked csv')
parser.add_argument('loci_list_csv', help='csv list of locus,start,end')
parser.add_argument('output_csv', type=argparse.FileType('w'), help='output csv with locus annotation')

def main():
    args = parser.parse_args()
    with open(args.loci_list_csv, 'r') as amr:
        lines = amr.readlines()

    features = []
    for each in lines:
        feat = each.rstrip().split(',')
        # Convert BED coordinates to VCF coordinates
        features.append((feat[0], int(feat[1])+1, int(feat[2])))
    mytree = RangeTree(features)

    variants_reader = csv.DictReader(args.input_csv)
    fieldnames = variants_reader.fieldnames
    fieldnames.append('LOCI')
    writer = csv.DictWriter(args.output_csv, fieldnames = fieldnames)
    writer.writeheader()
    variant = next(variants_reader, None)
    while variant:
        variant['LOCI'] = mytree.assign(int(variant['POS']))
        writer.writerow(variant)
        variant = next(variants_reader, None)
    #print(mytree.assign(5245))

if __name__ == '__main__':
    sys.exit(main())


from flask import Flask, render_template, redirect
import pymongo
import scrape_mars

client = pymongo.MongoClient('mongodb://localhost:27017')
db = client.mars_db
collection = db.mars

app = Flask(__name__)

@app.route("/")
def index():
    mars = collection.find_one()
    return render_template("index.html", mars = mars)

@app.route("/scrape")
def scrape():
    #mars = mongo.db.mars
    mars_data = scrape_mars.scrape(collection)
    collection.update({}, mars_data, upsert=True)
    return redirect("http://localhost:5000/", code=302)

if __name__ == '__main__':
	app.run(debug=True)


import random
'''
Ответы на вопросы:

1. Из всех методов списка (list) выбрать 5 тех, которые по вашему мнению используются чаще всего:
2.
    списки - list.sort(reverse=True), list.append('x'), list.pop('10') list.remove('x'), list.count('x')
    словари -  dict.get('key'), dict.items(), dict.keys(), dict.values(), dict.clear()
    множества - set.update(set2), set.add('x'), set.remove('x'), set.intersection_update(set2), set.difference_update(set2);
    строки - len(s), S1 + S2, S.find(str, [start],[end]), S.split(символ), S[i:j:step]
'''

day_set = ('первое', 'второе', 'третье', 'четвёртое',
        'пятое', 'шестое', 'седьмое', 'восьмое',
        'девятое', 'десятое', 'одиннадцатое', 'двенадцатое',
        'тринадцатое', 'четырнадцатое', 'пятнадцатое', 'шестнадцатое',
        'семнадцатое', 'восемнадцатое', 'девятнадцатое', 'двадцатое',
        'двадцать первое', 'двадцать второе', 'двадцать третье',
        'двадацать четвёртое', 'двадцать пятое', 'двадцать шестое',
        'двадцать седьмое', 'двадцать восьмое', 'двадцать девятое',
        'тридцатое', 'тридцать первое')
month_set = ('января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
       'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря')

fameus_person ={
    'Исаак Ньютон' : '25.12.1642',
    'Конфуций' : '28.10.-551',
    'Николай Коперник' : '19.02.1473',
    'Наполеон I' : '05.05.1769',
    'Людвиг ван Бетховен' : '26.03.1770',
    'Александр Белл' : '03.03.1847',
    'Макс Планк' : '04.10.1858',
    'Вильгельм Рентген' : '27.03.1845',
    'Иоганн Кеплер' : '15.11.1571',
    'Энрико Ферми' : '28.11.1901'
}

wrong_ansvers = 0
rigth_answers = 0

fameus_person = random.sample(list(fameus_person.items()), 5)

for key, value in fameus_person:
    if input(f'Введите дату рождения для: \'{key}:\' ') == value:
        rigth_answers += 1
        date = value.split('.')
        print(f"{day_set[int(date[0])-1]} {month_set[int(date[1])-1]} {date[2]} года ")
    else:
        wrong_ansvers += 1

print(f'Правильных ответов = {rigth_answers * 100 // len(fameus_person)}')
print(f'Неправильных ответов = {wrong_ansvers * 100 // len(fameus_person)}')


import numpy as np
import sys
import math
import copy
import codecs

# GET_ERROR Retrieves an error of the distance between two values and the
# input time.
#   INPUT:
#       val1 - First value to use.
#       val2 - Second value to use.
#       time - Value to check against.
#
def get_error(value1, value2, time):
    return (value1 - value2) - time

# LINEAR_APPROX Used to approximate a diameter at an intermediate point.
#   This will take two diameters and two timestamps, along with a time and
#   it will output a linear approximation for that time
#
#   diameter
#       ^
#       |       x
#       |      / (ts2, val2)
# val_out|____/
#       |    /|
#       |   / |
#       |  x  |
#       |   (ts1, val1)
#       |-----|------------------> timestamps
#             |
#          ts_final
#
#
#   INPUT: Described through the graph.
#
def linear_approx(val1, ts1, val2, ts2, ts_final, error=None, default_val=0):
    if error is not None:
        if error == 0:
            return val1 if default_val == 1 else val2
    line_slope = (val2 - val1) / (ts2 - ts1)
    line_const = (val1 - (ts1 * line_slope))
    return (ts_final * line_slope) + line_const

# MAKE_EPOCHMAT Produces a matrix of epochs in a given pupil dataset.
def make_epochmat(PUPIL_EPOCHED, trigger_ind):
    # Produce a matrix of the epoch data across all epochs.
    print('before mat:')
    len_dat = np.size(PUPIL_EPOCHED.eye0.epochs[0]['epochs'][0]['data'])
    print(PUPIL_EPOCHED.eye0.epochs[0]['epochs'][0]['data'][1:len_dat])
    epoch_size = np.size(PUPIL_EPOCHED.eye0.epochs[trigger_ind]['epochs'])
    print('epochs')
    print(epoch_size)
    data_size = np.size(PUPIL_EPOCHED.eye0.epochs[trigger_ind]['epochs'][0]['data'])
    PUPIL_EPOCHED.eye0.epochs[trigger_ind]['epochmat'] = \
        np.zeros((epoch_size, data_size))
    for l in range(0, epoch_size, 1):
        PUPIL_EPOCHED.eye0.epochs[trigger_ind]['epochmat'][l, :] = \
            PUPIL_EPOCHED.eye0.epochs[trigger_ind]['epochs'][l]['data']

    epoch_size = np.size(PUPIL_EPOCHED.eye1.epochs[trigger_ind]['epochs'])
    data_size = np.size(PUPIL_EPOCHED.eye1.epochs[trigger_ind]['epochs'][0]['data'])
    PUPIL_EPOCHED.eye1.epochs[trigger_ind]['epochmat'] = \
        np.zeros((epoch_size, data_size))
    for l in range(0, epoch_size, 1):
        PUPIL_EPOCHED.eye1.epochs[trigger_ind]['epochmat'][l, :] = \
            PUPIL_EPOCHED.eye1.epochs[trigger_ind]['epochs'][l]['data']

    print('after mat:')
    print(PUPIL_EPOCHED.eye0.epochs[trigger_ind]['epochmat'][0,:])

    return PUPIL_EPOCHED

# MAKE_RMB_PC_MATS Used to produce the percent change graph and remove the
# baseline from a measurement.
def make_rmb_pc_mats(PUPIL_EPOCHED, trig_ind):
    # Remove the baseline and get the rest mean for each set of
    # trigger.

    k = trig_ind

    # Get baseline removed data set.
    [PUPIL_EPOCHED.eye0.epochs[k]['epochmat_rmb'], PUPIL_EPOCHED.eye0.epochs[k]['rest_mean']] = \
        PUPIL_EPOCHED.eye0.pupil_rmbaselineeye(0, k)

    [PUPIL_EPOCHED.eye1.epochs[k]['epochmat_rmb'], PUPIL_EPOCHED.eye1.epochs[k]['rest_mean']] = \
        PUPIL_EPOCHED.eye1.pupil_rmbaselineeye(0, k)

    # Calculate the percent change graph.
    PUPIL_EPOCHED.eye0.epochs[k]['epochmat_pc'] = PUPIL_EPOCHED.eye0.pupil_datapercenteye(k)
    PUPIL_EPOCHED.eye1.epochs[k]['epochmat_pc'] = PUPIL_EPOCHED.eye1.pupil_datapercenteye(k)
    return PUPIL_EPOCHED

# PARSE_TRIGS Parses a pupil entry for a trigger index.
#   INPUT:
#       PUPIL - PUPIL data, which has the same epoch triggers in each eye.
#       trig  - The name of the trigger in the form of a string.
#
def parse_trigs(PUPIL_EYE, trig):
    for i in range(0, np.size(PUPIL_EYE.epochs, 2)-1, 1):
        if trig == PUPIL_EYE.epochs[i].name:
            return i

'''
    Both of these are used to handle errors that are recognized
    in the pupil analyzer. *args lets you set a status code.
'''
def error(msg, *args):
    status_code = 1
    for arg in args:
        status_code = arg
    np.disp('Error found: ' + msg)
    sys.exit(status_code)

'''
    Can be used to obtain indices using a lambda function.
'''
def indices(a, func):
    return [i for (i, val) in enumerate(a) if func(val)]

'''
    Can be used to obtain values at a given set of indices.
'''
def indVal(list_used, indices):
    return [list_used[i] for i in indices]

'''
    Filter out 'nan' numbers from a list, and it's associated list.
'''
def nanFilter(data, ts):
    inds = []
    for i in range(0, len(data), 1):
        if math.isnan(data[i]):
            inds.append(i)
    full_ind0 = range(0, len(data), 1)
    inds0 = [i for i in full_ind0 if i not in inds]

    for i in range(0, len(inds0), 1):
        if inds0[i] in inds:
            print('failure')

    return [indVal(data, inds0), indVal(ts, inds0)]

'''
    Gets the indicies for a given marker name from a set of marker
    names corresponding to an entire pupil experiment.
'''
def get_marker_indices(marker_names, trig):
    inds = []
    for i in range(0, np.size(marker_names)):
        if marker_names[i] == trig:
            inds.append(i)
    return inds

def custom_interval_upsample(data, times, interval):
    new_data = []
    new_times = []
    old_length = len(data)
    final_ind = old_length - 1
    beforeLast_ind = final_ind - 1

    for i in range(0, beforeLast_ind):
        new_data.append(data[i])
        new_times.append(times[i])

        curr_time = times[i]
        next_time = times[i + 1]
        while curr_time + interval < next_time:
            curr_time = curr_time + interval
            new_times.append(curr_time)
            new_data.append(
                linear_approx(data[i], times[i], data[i + 1], times[i + 1], curr_time))

        if i == beforeLast_ind-1:
            new_data.append(data[i+1])
            new_times.append(times[i+1])

    return [new_data, new_times]

# Don't replace these fields.
BLACKLIST = {
    'parsed_yaml': False,
    'max_workers': False,
    'logger': False,
    'store': False
}
def parse_yaml_for_config(config, name):
    new_config = copy.deepcopy(config)
    name_config = config['parsed_yaml'].get(name, None)

    if not name_config:
        # Check if some other portion of the config (higher-level)
        # exists and use that one
        newname = ':'.join(name.split(':')[:-1])
        name_config = config['parsed_yaml'].get(newname, None)
        while not name_config and len(newname.split(':')) > 2:
            newname = ':'.join(newname.split(':')[:-1])
            name_config = config['parsed_yaml'].get(newname, None)
        if not name_config:
            return config

    for option in name_config:
        if option not in BLACKLIST:
            new_config[option] = name_config[option]
    return new_config

def jsonify_pd(data):
    new_data = data
    if isinstance(data, dict):
        for name, val in data.items():
            new_data[name] = jsonify_pd(val)
    elif isinstance(data, np.ndarray):
        new_data = data.tolist()
    elif isinstance(data, set):
        new_data = list(data)
    return new_data

def union(a, b):
    return list(set(a) | set(b))


import math
from argparse import ArgumentParser
from logging import warning

import pathlib
import os
import re
import shutil
import json
from pathlib import Path

def process_script(ds_name, package, file_name, id_, type_, name, known_results, path_to_results):
    from evaluate_ctrl import main
    key = f"{id_}_{type_}"
    if key not in known_results:
        script_results = main(file_name=file_name, package=package, ds_name=ds_name)
        known_results[key] = script_results
        known_results[key]["name"] = name
        with path_to_results.open("w") as f:
            json.dump(dict(sorted(known_results.items())), f, indent=4)
        print("#" * 100)
    return known_results

def load_current_results(results_folder):
    current_results = {}
    for p in results_folder.glob('*json'):
        try:
            for fres in results_folder.glob("results*.json"):
                with fres.open("r") as inp:
                    current_results.update(json.load(inp))
        except Exception as e:
            warning(str(e))
    return current_results

SOLUTION_REGEX = r"(?P<name>^[^_]*)_(?:LATE_)?(?P<id>[0-9]{4,})_.*_(?P<type>[\w-]*$)"

if __name__ == "__main__":

    parser = ArgumentParser()
    parser.add_argument("--hw_folder", help="Path to solutions folder. "
                                            "Should have 'submissions' subfolder with assignment solution files"
                                            "solution file format should match SOLUTION_REGEX",
                        type=Path)
    parser.add_argument("--index", help="Index of the submission to evaluate. Use for parallel evaluation.",
                        default=None,
                        type=int)
    parser.add_argument("--ds_name", help="Dataset name.",
                        default="FILIMDB_hidden",
                        type=str)
    args = parser.parse_args()

    hw_folder = args.hw_folder
    ds_name = args.ds_name

    if not hw_folder.exists():
        raise FileNotFoundError("Solutions directory does not exist")

    eval_folder = hw_folder / "evaluation"
    results_folder = hw_folder / "results"
    submissions_folder = hw_folder / "submissions"

    for folder in [eval_folder, results_folder]:
        if not folder.exists():
            folder.mkdir()

    current_results = load_current_results(results_folder)
    for index, file_path in enumerate(sorted(submissions_folder.glob("*/*.py"))):
        file_name = str(file_path.stem)
        if "__init__" in file_name:
            continue
        print(file_name, SOLUTION_REGEX)
        matched = re.search(SOLUTION_REGEX, file_name)
        if matched is None:
            print(f"Couldn't match filename {file_name} with regex {SOLUTION_REGEX}")
            continue
        matched = matched.groups()

        student_name, student_id, submission_type = matched
        print(index, file_name, student_name, student_id, submission_type, sep=', ', flush=True)
        if args.index is None or args.index == index:
            process_script(ds_name=ds_name, file_name=file_name, id_=student_id, type_=submission_type, name=student_name,
                           known_results=current_results,
                           package=".".join(str(file_path).split("/")[:-1]),
                           path_to_results=results_folder / f"results{index}.json")


from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.views.generic import ListView, DetailView
from .models import Item, OrderItem, Order
from django.contrib import messages
from django.utils import timezone
from django.views import View

class HomeView(View):

    def get(self, request, *args, **kwargs):
        # Get all items from the Item model
        products = Item.objects.all()

        # Get the current user's cart items, assuming the user is logged in via admin panel
        # You can update this logic as per your authentication implementation
        if request.user.is_authenticated:
        # Assuming Order model has a one-to-one relationship with User model
        # You can adjust the relationship based on your actual model structure
            order = Order.objects.filter(user=request.user, ordered=False).first()
            if order:
                # Count only the OrderItems that are still associated with the Order
                cart_count = order.items.filter(ordered=False).count()
            else:
                cart_count = 0
        else:
            cart_count = 0

        context = {
            'products': products,
            'cart_count': cart_count
        }
        return render(request, 'home.html', context)

        # Add cart_items_count to the context

class ProductDetailView(DetailView):
    model = Item
    template_name = 'product.html'
    context_object_name = 'product'

class AddToCartView(View):
    def get(self, request, slug):
        item = get_object_or_404(Item, slug=slug)
        order_item, created = OrderItem.objects.get_or_create(item=item, user=request.user, ordered=False)
        order_qs = Order.objects.filter(user=request.user, ordered=False)
        if order_qs.exists():
            order = order_qs[0]
            if order.items.filter(item__slug=item.slug):
                order_item.quantity += 1
                order_item.save()
                messages.success(request, f"{item.title}'s quantity was successfully updated in cart")
                return redirect('product', slug=slug)
            else:
                order.items.add(order_item)
                order.save()
                messages.success(request, f"{item.title} was successfully added to cart")
                return redirect('product', slug=slug)

        else:
            ordered_date = timezone.now()
            order = Order.objects.create(user=request.user, ordered=False, ordered_date=ordered_date)
            order.items.add(order_item)
            order.save()
            messages.success(request, f"{item.title} was successfully added to cart")
            return redirect('product', slug=slug)

    def post(self, request, slug):
        return self.get(request, slug)

class RemoveItemFromCartView(View):
    def get(self, request, slug):
        item = get_object_or_404(Item, slug=slug)
        order_item = OrderItem.objects.filter(item=item, user=request.user, ordered=False)
        order_qs = Order.objects.filter(user=request.user, ordered=False)
        if order_qs.exists():
            order = order_qs[0]
            if order.items.filter(item__slug=item.slug).exists():
                order_item.delete()  # Remove the item from OrderItem table
                order.save()
                messages.success(request, f"{item.title} was successfully removed from your cart")
                return redirect('product', slug=slug)
            else:
                messages.info(request, f"{item.title} was not in your cart")
                return redirect('product', slug=slug)
        else:
            messages.info(request, "You do not have an active order!")
            return redirect('product', slug=slug)

    def post(self, request, slug):
        return self.get(request, slug)

class CartView(View):
    def get(self, request, *args, **kwargs):
        cart = None
        cart_total = 0
        if request.user.is_authenticated:
            # Assuming Order model has a one-to-one relationship with User model
            # You can adjust the relationship based on your actual model structure
            order = Order.objects.filter(user=request.user, ordered=False).first()
            if order:
                # Count only the OrderItems that are still associated with the Order
                cart = order.items.filter(ordered=False)
                # Calculate the total amount for checked items in the cart
                checked_items = request.GET.getlist('items')  # Get the list of checked items from query parameters
                cart_total = sum(item.item.price * item.quantity for item in cart if str(item.item.slug) in checked_items)
            else:
                messages.info(request, 'You have no item in your cart!')
        else:
            messages.info(request, 'Please sign in to view your cart')

        context = {'cart': cart, 'cart_total': cart_total}
        return render(request, 'cart.html', context)


'''
Crie um programa onde o usuario digite uma expressão qualquer que usa parentêses, seu
aplicativo deverá analisar se a expressão passada está com os parênteses abertos e
fechado na ordem correta.

from sympy import sympify, symbols # Modulo sympy que faz verificação de expressões matematicas
expr = input('Digite uma expressão: ') # Input expressão
Simbolos = symbols('x y ()') #
try:
    expr = sympify(expr)
    print('A expressão é valida')

except(SyntaxError, TypeError):
    print('Expressão Invalida!')
'''
expr = str(input('Digite uma expressão: '))
pilha = []
for símb in expr:
    if símb == '(':
        pilha.append('(')
    elif símb == ')':
        if len(pilha) > 0:
            pilha.pop()
        else:
            pilha.append(')')
            break
if len(pilha) == 0:
    print('Sua expressão está válida!')
else:
    print('Sua expressão está invalida!')


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

from django.db import models, migrations
from django.conf import settings
import datetime

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('varer', '0017_salgsvare_kassenavn'),
    ]

    operations = [
        migrations.AddField(
            model_name='varetellingvare',
            name='added_by',
            field=models.ForeignKey(help_text='Brukeren som registrerte oppføringen', null=True, to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE),
        ),
        migrations.AddField(
            model_name='varetellingvare',
            name='time_added',
            field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2016, 1, 28, 22, 3, 18, 828239, tzinfo=datetime.timezone.utc)),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='varetellingvare',
            name='time_price',
            field=models.DateTimeField(blank=True, help_text='Overstyring av tidspunkt varen skal prises', null=True),
        ),
        migrations.AlterField(
            model_name='varetellingvare',
            name='sted',
            field=models.CharField(blank=True, max_length=50, null=True),
        ),
    ]


__author__ = 'Mark Sattolo'
__author_email__ = 'epistemik@gmail.com'
__python_version__ = 3.6
__created__ = '2019-07-01'
__updated__ = '2019-08-12'

import copy
import re
from gnucash import Session, Book, Account, Transaction, Split, GncNumeric, GncPrice, GncPriceDB, GncCommodity
from gnucash.gnucash_core_c import CREC
from Configuration import *

class GnucashSession:
    """
    Create and manage a Gnucash session
    """
    def __init__(self, p_mrec:InvestmentRecord, p_mode:str, p_gncfile:str, p_debug:bool, p_domain:str,
                 p_pdb:GncPriceDB=None, p_book:Book=None, p_root:Account=None,
                 p_curr:GncCommodity=None, p_grec:InvestmentRecord=None):
        self.logger = Gnulog(p_debug)
        self.monarch_record = p_mrec
        self.gnucash_record = p_grec
        self.gnc_file  = p_gncfile
        self.mode      = p_mode
        self.domain    = p_domain
        self.price_db  = p_pdb
        self.book      = p_book
        self.root_acct = p_root
        self.currency  = p_curr
        self.gnc_util  = GncUtilities()
        self.logger.print_info("class GnucashSession: Runtime = {}\n".format(dt.now().strftime(DATE_STR_FORMAT)), MAGENTA)

    def set_gnc_rec(self, p_gncrec:InvestmentRecord):
        self.gnucash_record = p_gncrec

    def get_trade_info(self, mtx:dict, plan_type:str, ast_parent:Account, rev_acct:Account):
        """
        Parse the Monarch trade transactions from a copy&paste JSON file
        Asset accounts: use the proper path to find the parent then search for the Fund Code in the descendants
        Revenue accounts: pick the proper account based on owner and plan type
        gross_curr: re match to Gross then concatenate the two match groups
        date: convert the date then get day, month and year to form a Gnc date
        Units: re match and concatenate the two groups on either side of decimal point
        Description: use DESC and Fund Company
        :param        mtx: Monarch copied trade tx information
        :param  plan_type: plan names from Configuration.InvestmentRecord
        :param ast_parent: Asset parent account
        :param   rev_acct: Revenue account
        :return: dict, dict
        """
        self.logger.print_info('get_trade_info()', BLUE)

        # set the regex needed to match the required groups in each value
        re_gross  = re.compile(r"^(-?)\$([0-9,]{1,6})\.([0-9]{2}).*")
        re_units  = re.compile(r"^(-?)([0-9]{1,5})\.([0-9]{4}).*")

        fund_name = mtx[FUND]

        # self.dbg.print_info("trade date = {}".format(mtx[TRADE_DATE]))
        conv_date = dt.strptime(mtx[TRADE_DATE], "%d-%b-%Y")
        # self.dbg.print_info("converted date = {}".format(conv_date))
        init_tx = { FUND:fund_name, TRADE_DATE:mtx[TRADE_DATE],
                    TRADE_DAY:conv_date.day, TRADE_MTH:conv_date.month, TRADE_YR:conv_date.year }
        self.logger.print_info("trade day-month-year = '{}-{}-{}'"
                               .format(init_tx[TRADE_DAY], init_tx[TRADE_MTH], init_tx[TRADE_YR]))

        # check if we have a switch-in/out
        sw_ind = mtx[DESC].split()[-1]
        switch = True if sw_ind == SW_IN or sw_ind == SW_OUT else False
        init_tx[SWITCH] = switch
        self.logger.print_info("{} Have a Switch!".format('***' if switch else 'DO NOT'), BLUE)

        asset_acct, rev_acct = self.get_accounts(ast_parent, fund_name, rev_acct)
        init_tx[ACCT] = asset_acct
        # save the (possibly modified) Revenue account to the Gnc tx
        init_tx[REVENUE] = rev_acct

        # get the dollar value of the tx
        re_match = re.match(re_gross, mtx[GROSS])
        if re_match:
            str_gross_curr = re_match.group(2) + re_match.group(3)
            # remove possible comma
            gross_curr = int(str_gross_curr.replace(',', ''))
            # if match group 1 is not empty, amount is negative
            if re_match.group(1) != '':
                gross_curr *= -1
            self.logger.print_info("gross_curr = {}".format(gross_curr))
            init_tx[GROSS] = gross_curr
        else:
            raise Exception("PROBLEM[100]!! re_gross DID NOT match with value '{}'!".format(mtx[GROSS]))

        # get the units of the tx
        re_match = re.match(re_units, mtx[UNITS])
        if re_match:
            units = int(re_match.group(2) + re_match.group(3))
            # if match group 1 is not empty, units is negative
            if re_match.group(1) != '':
                units *= -1
            init_tx[UNITS] = units
            self.logger.print_info("units = {}".format(units))
        else:
            raise Exception("PROBLEM[105]!! re_units DID NOT match with value '{}'!".format(mtx[UNITS]))

        # assemble the Description string
        descr = "{} {}".format(mtx[DESC], fund_name)
        init_tx[DESC] = descr
        self.logger.print_info("descr = {}".format(init_tx[DESC]), CYAN)

        # notes field
        notes = mtx[NOTES] if NOTES in mtx else "{} Load = {}".format(fund_name, mtx[LOAD])
        init_tx[NOTES] = notes
        self.logger.print_info("notes = {}".format(init_tx[NOTES]), CYAN)

        pair_tx = None
        have_pair = False
        if switch:
            self.logger.print_info("Tx is a Switch to OTHER Monarch account.", BLUE)
            # look for switches in this plan type with same company, day, month and opposite gross value
            for itx in self.gnucash_record.plans[plan_type][TRADE]:
                if itx[SWITCH] and itx[FUND].split()[0] == init_tx[FUND].split()[0] and itx[GROSS] == (gross_curr * -1) \
                        and itx[TRADE_DATE] == init_tx[TRADE_DATE] :
                    # ALREADY HAVE THE FIRST ITEM OF THE PAIR
                    have_pair = True
                    pair_tx = itx
                    self.logger.print_info('*** Found the MATCH of a pair ***', YELLOW)
                    break

            if not have_pair:
                # store the tx until we find the matching tx
                self.gnucash_record.plans[plan_type][TRADE].append(init_tx)
                self.logger.print_info('Found the FIRST of a pair...\n', YELLOW)

        return init_tx, pair_tx

    def get_accounts(self, ast_parent:Account, asset_acct_name:str, rev_acct:Account):
        """
        Find the proper Asset and Revenue accounts
        :param      ast_parent: Asset account parent
        :param asset_acct_name: Asset account name
        :param        rev_acct: Revenue account
        :return: Gnucash account, Gnucash account
        """
        self.logger.print_info('get_accounts()', BLUE)
        asset_parent = ast_parent
        # special locations for Trust Revenue and Asset accounts
        if asset_acct_name == TRUST_AST_ACCT:
            asset_parent = self.root_acct.lookup_by_name(TRUST)
            self.logger.print_info("asset_parent = {}".format(asset_parent.GetName()))
            rev_acct = self.root_acct.lookup_by_name(TRUST_REV_ACCT)
            self.logger.print_info("MODIFIED rev_acct = {}".format(rev_acct.GetName()))
        # get the asset account
        asset_acct = asset_parent.lookup_by_name(asset_acct_name)
        if asset_acct is None:
            raise Exception("[164] Could NOT find acct '{}' under parent '{}'"
                            .format(asset_acct_name, asset_parent.GetName()))

        self.logger.print_info("asset_acct = {}".format(asset_acct.GetName()), color=CYAN)
        return asset_acct, rev_acct

    def create_gnc_price_txs(self, mtx:dict, ast_parent:Account, rev_acct:Account):
        """
        Create and load Gnucash prices to the Gnucash PriceDB
        :param        mtx: InvestmentRecord transaction
        :param ast_parent: Asset parent account
        :param   rev_acct: Revenue account
        :return: nil
        """
        self.logger.print_info('create_gnc_price_txs()', BLUE)
        conv_date = dt.strptime(mtx[DATE], "%d-%b-%Y")
        pr_date = dt(conv_date.year, conv_date.month, conv_date.day)
        datestring = pr_date.strftime("%Y-%m-%d")

        fund_name = mtx[FUND]
        if fund_name in MONEY_MKT_FUNDS:
            return

        int_price = int(mtx[PRICE].replace('.', '').replace('$', ''))
        val = GncNumeric(int_price, 10000)
        self.logger.print_info("Adding: {}[{}] @ ${}".format(fund_name, datestring, val))

        pr1 = GncPrice(self.book)
        pr1.begin_edit()
        pr1.set_time64(pr_date)

        asset_acct, rev_acct = self.get_accounts(ast_parent, fund_name, rev_acct)
        comm = asset_acct.GetCommodity()
        self.logger.print_info("Commodity = {}:{}".format(comm.get_namespace(), comm.get_printname()))
        pr1.set_commodity(comm)

        pr1.set_currency(self.currency)
        pr1.set_value(val)
        pr1.set_source_string("user:price")
        pr1.set_typestr('nav')
        pr1.commit_edit()

        if self.mode == PROD:
            self.logger.print_info("Mode = {}: Add Price to DB.".format(self.mode), GREEN)
            self.price_db.add_price(pr1)
        else:
            self.logger.print_info("Mode = {}: ABANDON Prices!\n".format(self.mode), RED)

    def create_gnc_trade_txs(self, tx1:dict, tx2:dict):
        """
        Create and load Gnucash transactions to the Gnucash file
        :param tx1: first transaction
        :param tx2: matching transaction if a switch
        :return: nil
        """
        self.logger.print_info('create_gnc_trade_txs()', BLUE)
        # create a gnucash Tx
        gtx = Transaction(self.book)
        # gets a guid on construction

        gtx.BeginEdit()

        gtx.SetCurrency(self.currency)
        gtx.SetDate(tx1[TRADE_DAY], tx1[TRADE_MTH], tx1[TRADE_YR])
        # self.dbg.print_info("gtx date = {}".format(gtx.GetDate()), BLUE)
        self.logger.print_info("tx1[DESC] = {}".format(tx1[DESC]), YELLOW)
        gtx.SetDescription(tx1[DESC])

        # create the ASSET split for the Tx
        spl_ast = Split(self.book)
        spl_ast.SetParent(gtx)
        # set the account, value, and units of the Asset split
        spl_ast.SetAccount(tx1[ACCT])
        spl_ast.SetValue(GncNumeric(tx1[GROSS], 100))
        spl_ast.SetAmount(GncNumeric(tx1[UNITS], 10000))

        if tx1[SWITCH]:
            # create the second ASSET split for the Tx
            spl_ast2 = Split(self.book)
            spl_ast2.SetParent(gtx)
            # set the Account, Value, and Units of the second ASSET split
            spl_ast2.SetAccount(tx2[ACCT])
            spl_ast2.SetValue(GncNumeric(tx2[GROSS], 100))
            spl_ast2.SetAmount(GncNumeric(tx2[UNITS], 10000))
            # set Actions for the splits
            spl_ast2.SetAction("Buy" if tx1[UNITS] < 0 else "Sell")
            spl_ast.SetAction("Buy" if tx1[UNITS] > 0 else "Sell")
            # combine Notes for the Tx and set Memos for the splits
            gtx.SetNotes(tx1[NOTES] + " | " + tx2[NOTES])
            spl_ast.SetMemo(tx1[NOTES])
            spl_ast2.SetMemo(tx2[NOTES])
        else:
            # the second split is for a REVENUE account
            spl_rev = Split(self.book)
            spl_rev.SetParent(gtx)
            # set the Account, Value and Reconciled of the REVENUE split
            spl_rev.SetAccount(tx1[REVENUE])
            rev_gross = tx1[GROSS] * -1
            # self.dbg.print_info("revenue gross = {}".format(rev_gross))
            spl_rev.SetValue(GncNumeric(rev_gross, 100))
            spl_rev.SetReconcile(CREC)
            # set Notes for the Tx
            gtx.SetNotes(tx1[NOTES])
            # set Action for the ASSET split
            action = FEE if FEE in tx1[DESC] else ("Sell" if tx1[UNITS] < 0 else DIST)
            self.logger.print_info("action = {}".format(action))
            spl_ast.SetAction(action)

        # ROLL BACK if something went wrong and the two splits DO NOT balance
        if not gtx.GetImbalanceValue().zero_p():
            self.logger.print_error("Gnc tx IMBALANCE = {}!! Roll back transaction changes!"
                                    .format(gtx.GetImbalanceValue().to_string()))
            gtx.RollbackEdit()
            return

        if self.mode == PROD:
            self.logger.print_info("Mode = {}: Commit transaction changes.\n".format(self.mode), GREEN)
            gtx.CommitEdit()
        else:
            self.logger.print_info("Mode = {}: Roll back transaction changes!\n".format(self.mode), RED)
            gtx.RollbackEdit()

    def process_monarch_trade(self, mtx:dict, plan_type:str, ast_parent:Account, rev_acct:Account):
        """
        Obtain each Monarch trade as a transaction item, or pair of transactions where required, and forward to Gnucash processing
        :param        mtx: Monarch transaction information
        :param  plan_type: plan names from Configuration.InvestmentRecord
        :param ast_parent: Asset parent account
        :param   rev_acct: Revenue account
        :return: nil
        """
        self.logger.print_info('process_monarch_trade()', BLUE)
        try:
            # get the additional required information from the Monarch json
            tx1, tx2 = self.get_trade_info(mtx, plan_type, ast_parent, rev_acct)

            # just return if there is a matching tx but we don't have it yet
            if tx1[SWITCH] and tx2 is None:
                return

            self.create_gnc_trade_txs(tx1, tx2)

        except Exception as ie:
            self.logger.print_error("process_monarch_trade() EXCEPTION!! '{}'\n".format(str(ie)))

    def create_gnucash_info(self):
        """
        Process each transaction from the Monarch input file to get the required Gnucash information
        :return: nil
        """
        self.logger.print_info("create_gnucash_info()", BLUE)
        self.root_acct = self.book.get_root_account()
        self.root_acct.get_instance()

        if self.domain != TRADE:
            self.price_db = self.book.get_price_db()
            self.price_db.begin_edit()
            self.logger.print_info("self.price_db.begin_edit()", CYAN)

        commod_tab = self.book.get_table()
        self.currency = commod_tab.lookup("ISO4217", "CAD")

        plans = self.monarch_record.get_plans()
        for plan_type in plans:
            self.logger.print_info("\n\t\u0022Plan type = {}\u0022".format(plan_type), YELLOW)

            asset_parent, rev_acct = self.get_asset_revenue_info(plan_type)

            if self.domain != PRICE:
                for mon_tx in plans[plan_type][TRADE]:
                    self.process_monarch_trade(mon_tx, plan_type, asset_parent, rev_acct)

            if self.domain != TRADE:
                for mon_tx in plans[plan_type][PRICE]:
                    self.create_gnc_price_txs(mon_tx, asset_parent, rev_acct)

    def get_asset_revenue_info(self, plan_type:str):
        """
        Get the required asset and/or revenue information from each plan
        :param plan_type: plan names from Configuration.InvestmentRecord
        :return: Gnucash account, Gnucash account: revenue account and asset parent account
        """
        self.logger.print_info("get_asset_revenue_info()", BLUE)
        rev_path = copy.copy(ACCT_PATHS[REVENUE])
        rev_path.append(plan_type)
        ast_parent_path = copy.copy(ACCT_PATHS[ASSET])
        ast_parent_path.append(plan_type)

        pl_owner = self.gnucash_record.get_owner()
        if plan_type != PL_OPEN:
            if pl_owner == '':
                raise Exception("PROBLEM[355]!! Trying to process plan type '{}' but NO Owner value found"
                                " in Tx Collection!!".format(plan_type))
            rev_path.append(ACCT_PATHS[pl_owner])
            ast_parent_path.append(ACCT_PATHS[pl_owner])
        self.logger.print_info("rev_path = {}".format(str(rev_path)))

        rev_acct = self.gnc_util.account_from_path(self.root_acct, rev_path)
        self.logger.print_info("rev_acct = {}".format(rev_acct.GetName()))
        self.logger.print_info("asset_parent_path = {}".format(str(ast_parent_path)))
        asset_parent = self.gnc_util.account_from_path(self.root_acct, ast_parent_path)
        self.logger.print_info("asset_parent = {}".format(asset_parent.GetName()))

        return asset_parent, rev_acct

    # noinspection PyUnboundLocalVariable
    def prepare_session(self):
        """
        initialization needed for a Gnucash session
        :return: message
        """
        self.logger.print_info("prepare_session()", BLUE)
        msg = TEST
        try:
            session = Session(self.gnc_file)
            self.book = session.book

            owner = self.monarch_record.get_owner()
            self.logger.print_info("Owner = {}".format(owner), GREEN)
            self.set_gnc_rec(InvestmentRecord(owner))

            self.create_gnucash_info()

            if self.mode == PROD:
                self.logger.print_info("Mode = {}: COMMIT Price DB edits and Save session.".format(self.mode), GREEN)

                if self.domain != TRADE:
                    self.price_db.commit_edit()

                # only ONE session save for the entire run
                session.save()

            session.end()
            session.destroy()

            msg = self.logger.get_log()

        except Exception as se:
            msg = "prepare_session() EXCEPTION!! '{}'".format(repr(se))
            self.logger.print_error(msg)
            if "session" in locals() and session is not None:
                session.end()
                session.destroy()
            raise se

        return msg

def gnucash_session_main(args:list):
    """
    Take the information from an InvestmentRecord JSON file and produce Gnucash transactions to write to a Gnucash file
    :return: message
    """
    py_name = __file__.split('/')[-1]
    usage = "usage: py36 {} <Monarch copy-text JSON file> <mode: prod|test> [Gnucash file]".format(py_name)
    if len(args) < 3:
        Gnulog.print_text("NOT ENOUGH parameters!", RED)
        Gnulog.print_text(usage, MAGENTA)
        exit(421)

    mon_file = args[0]
    if not osp.isfile(mon_file):
        Gnulog.print_text("File path '{}' does not exist. Exiting...".format(mon_file), RED)
        Gnulog.print_text(usage, GREEN)
        exit(427)
    Gnulog.print_text("\nMonarch file = {}".format(mon_file), GREEN)

    # get Monarch transactions from the Monarch JSON file
    with open(mon_file, 'r') as fp:
        tx_coll = json.load(fp)

    gnc_file = args[1]
    if not osp.isfile(gnc_file):
        Gnulog.print_text("File path '{}' does not exist. Exiting...".format(gnc_file), RED)
        exit(437)
    Gnulog.print_text("\nGnucash file = {}".format(gnc_file), GREEN)

    mode = args[2].upper()

    gncs = GnucashSession(tx_coll, mode, gnc_file, True, BOTH)
    msg = gncs.prepare_session()

    Gnulog.print_text("\n >>> PROGRAM ENDED.", MAGENTA)
    return msg

if __name__ == '__main__':
    import sys
    gnucash_session_main(sys.argv[1:])


# coding: utf-8

from unipath import Path

PROJECT_DIR = Path(__file__).ancestor(3)

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
	('Felipe Coelho', 'fcoelho.9@gmail.com'),
	('Guilherme Gibertoni', 'kuramayoko10@gmail.com'),
	('Cesar Milano', 'cesar.milano@gmail.com')
)

MANAGERS = ADMINS

TIME_ZONE = 'America/Sao_Paulo'
LANGUAGE_CODE = 'pt-BR'

USE_I18N = True
USE_L10N = True
USE_TZ = True

MEDIA_ROOT = PROJECT_DIR.child('media')
MEDIA_URL = '/media/'

STATIC_ROOT = PROJECT_DIR.child('static')
STATIC_URL = '/static/'

SECRET_KEY = 'gwxr4yc-*@85$#9s@uh268y7c2xxad1+#g+n*$hk9j%gihpo2r'

ROOT_URLCONF = 'wict.urls'

INSTALLED_APPS = (
	# Wict apps come first -> select wict templates first!
	'website',
	'submission',
	'review',
	# Django contrib apps
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
	# Thirdy party apps
	'signup',
	'sendfile',
)

MIDDLEWARE_CLASSES = (
	'django.middleware.common.CommonMiddleware',
	'django.contrib.sessions.middleware.SessionMiddleware',
	'django.middleware.csrf.CsrfViewMiddleware',
	'django.contrib.auth.middleware.AuthenticationMiddleware',
	'django.contrib.messages.middleware.MessageMiddleware',
	'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

AUTH_USER_MODEL = 'website.WictUser'
SIGNUP_FORM_CLASS = 'website.forms.UserSignUpForm'

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

ACCOUNT_ACTIVATION_DAYS = 2

LOGIN_REDIRECT_URL = '/'

MAX_ARTICLE_FILE_SIZE = 2 * 1024 * 1024
MAX_ARTICLE_PAGES = 3


from .common import *

# Heroku
import dj_database_url

# ##############  DATABASES
# Heroku settings
DATABASES = {
    'default':  dj_database_url.config(),
}

# # ########################## AWS S3 Private Media Upload
if USE_S3:
    # # ########################## AWS S3 - Settings Variable
    AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
    AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'

   # # ########################## AWS S3 Static files (CSS, JavaScript, Images)
    # # Amazon S3/myBucketName/static/myimage/files
    STATICFILES_LOCATION = 'static'
    STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATICFILES_LOCATION}/'
    # STATIC_ROOT = [os.path.join(BASE_DIR, 'mypage/static'), ]  # Não usar com S3
    STATICFILES_STORAGE = config('AWS_STATICFILES_STORAGE')

    # # ########################## AWS S3 Private Media Upload
    # # Amazon S3/myBucketName/media/myimage/files
    MEDIAFILES_LOCATION = 'media'

    # https://testheroku-assets.s3.amazonaws.com/media/myimage/images/Course_6.png
    AWS_S3_PATH = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'  # 20190822/0724
    MEDIA_URL = f'https://{AWS_S3_PATH}/{MEDIAFILES_LOCATION}/'

    # MEDIA_ROOT = os.path.join(BASE_DIR, 'mypage/media') # Não usar com S3
    DEFAULT_FILE_STORAGE = config('AWS_DEFAULT_FILE_STORAGE')