import os
import tempfile

import maya.cmds as cmds

import py_tasker.tasks
import collections

LOG = py_tasker.tasks.get_task_logger(__name__)
TEMP_DIR = os.path.join(tempfile.gettempdir(), 'dragonfly')

def run(params, rig):

    rig_name = rig['rig']
    geo_grp = rig['geoGroup']
    lod_dict = collections.OrderedDict()

    for lod in params['lods']:
        name_lod = lod['lodName']
        geo_lod = [cmds.ls(x, long=False)[0] for x in lod['geo']]
        lod_dict[name_lod] = geo_lod

    if lod_dict:
        lod_grp = create_lod_groups(lod_dict)
        if cmds.objExists(geo_grp):
            if not cmds.listRelatives(lod_grp, parent=True):
                cmds.parent(lod_grp, geo_grp)

def create_lod_groups(lod_dict, name='LOD_grp'):
    """Creates lod group and subgroups from dictionary data

    Args:
        lod_dict = <LOD_name> : [<mesh_list>]
        name = Name of main LOD group

    Returns:
        Main LOD top group

    Example:
        my_lod_dict = collections.OrderedDict()
        my_lod_dict['LOD0'] = ['CH_MoorishIdol_LOD0_SM', 'CH_MoorishIdolFin_LOD0_SM']
        my_lod_dict['LOD1'] = ['CH_MoorishIdol_LOD1_SM', 'CH_MoorishIdolFin_LOD1_SM']
        create_lod_groups(my_lod_dict)
    """
    geo_lod_list = list()
    cmds.select(clear=True)
    for lod, lod_geo in lod_dict.items():
        for geo in lod_geo:
            if cmds.listRelatives(geo, parent=True):
                cmds.parent(geo, world=True)
        geo_lod_list.append(lod_geo[0])

    if geo_lod_list:
        cmds.select(geo_lod_list)
        cmds.LevelOfDetailGroup()
        lod_grp = cmds.rename(cmds.ls(selection=True)[0], name)
        for lod, lod_geo in lod_dict.items():
            if len(lod_geo) > 1:
                lod_parent = cmds.listRelatives(lod_geo[0], parent=True)
                if lod_parent:
                    cmds.parent(lod_geo[1:], lod_parent[0])
        return lod_grp


from machine import Pin, Timer

notificationLed = Pin(18, Pin.OUT) # Use GP13
button = Pin(28, Pin.IN, Pin.PULL_DOWN) # Use GP18

notificationLed.value(0)
timer=Timer(-1) # init timer with id=-1

timeInMiliseconds = 5000 # global variable

def set_timer(miliseconds):
    print('set timer')
    timer.init(period=miliseconds, mode=Timer.ONE_SHOT, callback=push_notification)

def push_notification(timer):
    print('set LED')
    timer.init(period=500, mode=Timer.PERIODIC, callback=lambda t:notificationLed.value(not notificationLed.value()))

def debounce(pin):
    # Start or replace a timer for 200ms, and trigger on_pressed.
    timer.init(mode=Timer.ONE_SHOT, period=200, callback=on_pressed)

def on_pressed(change):
    print('button pressed')
    notificationLed.value(0)
    set_timer(timeInMiliseconds)

# Register an interrupt on falling button input.
button.irq(handler=debounce, trigger=Pin.IRQ_FALLING)

set_timer(timeInMiliseconds)


from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout

import instructions

name = ""
age = 7
p1,p2,p3 = 0,0,0

class Window1(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.text = Label(text = instructions.txt_instruction, color =(0.5, 0.5, 0.5, 1))
        self.mainLayout = BoxLayout(orientation = 'vertical')
        self.nameLayout = BoxLayout()
        self.ageLayout = BoxLayout()
        self.textName = Label(text = "Введите ім'я:")
        self.textAge = Label(text = 'Введіть ваш вік:')
        self.inputName = TextInput()
        self.inputAge = TextInput()
        self.nameLayout.add_widget(self.textName)
        self.nameLayout.add_widget(self.inputName)
        self.ageLayout.add_widget(self.textAge)
        self.ageLayout.add_widget(self.inputAge)

        self.button = Button(text = 'Почати')
        self.button.on_press = self.triger

        self.mainLayout.add_widget(self.text)
        self.mainLayout.add_widget(self.nameLayout)
        self.mainLayout.add_widget(self.ageLayout)
        self.mainLayout.add_widget(self.button)

        self.add_widget(self.mainLayout)

    def triger(self):
        global name
        global age
        name = self.inputName.text
        age = self.inputAge.text
        age = self.checkpoint(age)
        if age:
            if age > 6:
                self.manager.current = '. . .'
            else:
                self.textAge.text = "Введіть число більше ніж 6"

    def checkpoint(self, value):
        try:
            value = int(value)
            return value
        except:
            self.textAge.text = "Введіть число"

class Ruffie(App):
    def build(self):
        build=ScreenManager()
        build.add_widget(Window1(name = 'Valera'))
        return build

app=Ruffie()
app.run()


from flask import Blueprint, render_template, request

# Blueprint에서 template_folder를 지정하면
# 지정한 폴더에서 html 파일을 찾는다.
# Blueprint에서 사용하는 모든 html파일이 같은 폴더에 있을 경우
# test()함수에서 경로 설정 없이 파일이름만 쓸 수 있음
blue200 = Blueprint('blue2',__name__, template_folder='view/sub2')

@blue200.route('/test3')
def test3():
    #template_folder를 지정했으므로 파일 이름만
    html = render_template('test3.html')
    return html

@blue200.route('/test4')
def test4():
    html = render_template('test4.html')
    return html


"""
Implements stitching, validation and filtering functions.
"""

import copy
import itertools
import re

import networkx as nx

import stitcher

def _find_nodes(graph, tzpe):
    """
    Find nodes of a certain type in a graph.
    """
    res = []
    for node, values in graph.nodes(data=True):
        if values[stitcher.TYPE_ATTR] == tzpe:
            res.append(node)
    return res

def my_filter(container, edge_list, conditions):
    """
    Default filter which scans the candidate edges and eliminates those
    candidates which do not adhere the conditions. Following conditions are
    available:

    attributes - the target node e.g. needs to have a certain attribute
    composition - two nodes need to e.g. have same/different/shared attributes
        for the target nodes.

    :param edge_list: the candidate edge list as created by stitch().
    :param conditions: dictionary containing the conditions.
    :return: The filtered dict with possible edges.
    """
    if conditions is None:
        return edge_list
    if 'attributes' in conditions:
        for condition in conditions['attributes']:
            cond = condition[0]
            para1 = condition[1][0]
            para2 = condition[1][1]
            if cond == 'eq':
                _eq_attr_filter(container, para1, para2, edge_list)
            elif cond == 'neq':
                _neq_attr_filter(container, para1, para2, edge_list)
            elif cond == 'lg':
                _lg_attr_filter(container, para1, para2, edge_list)
            elif cond == 'lt':
                _lt_attr_filter(container, para1, para2, edge_list)
            elif cond == 'regex':
                _regex_attr_filter(container, para1, para2, edge_list)
    if 'compositions' in conditions:
        for condition in conditions['compositions']:
            cond = condition[0]
            para1 = condition[1][0]
            para2 = condition[1][1]
            if cond == 'same':
                _same_filter(para1, para2, edge_list)
            elif cond == 'diff':
                _diff_filter(para1, para2, edge_list)
            elif cond == 'share':
                _share_attr(container, para1, para2, edge_list)
            elif cond == 'nshare':
                _nshare_attr(container, para1, para2, edge_list)
    return edge_list

def _eq_attr_filter(container, node, condition, candidate_list):
    """
    Filter on attributes needed on target node.
    """
    for candidate in list(candidate_list.keys()):
        attrn = condition[0]
        attrv = condition[1]
        for src, trg in candidate_list[candidate]:
            if src == node and attrn not in container.nodes[trg]:
                candidate_list.pop(candidate)
                break
            if src == node and attrn in container.nodes[trg] \
                    and attrv != container.nodes[trg][attrn]:
                candidate_list.pop(candidate)
                break

def _neq_attr_filter(container, node, condition, candidate_list):
    """
    Filter on attributes unequal to requested value.
    """
    for candidate in list(candidate_list.keys()):
        attrn = condition[0]
        attrv = condition[1]
        for src, trg in candidate_list[candidate]:
            if src == node and attrn in container.nodes[trg] \
                    and attrv == container.nodes[trg][attrn]:
                candidate_list.pop(candidate)
                break

def _lg_attr_filter(container, node, condition, candidate_list):
    """
    Filter on attributes larger than requested value.
    """
    for candidate in list(candidate_list.keys()):
        attrn = condition[0]
        attrv = condition[1]
        for src, trg in candidate_list[candidate]:
            if src == node and attrn not in container.nodes[trg]:
                candidate_list.pop(candidate)
                break
            if src == node and attrn in container.nodes[trg] \
                    and container.nodes[trg][attrn] <= attrv:
                candidate_list.pop(candidate)
                break

def _lt_attr_filter(container, node, condition, candidate_list):
    """
    Filter on attributes less than requested value.
    """
    for candidate in list(candidate_list.keys()):
        attrn = condition[0]
        attrv = condition[1]
        for src, trg in candidate_list[candidate]:
            if src == node and attrn not in container.nodes[trg]:
                candidate_list.pop(candidate)
                break
            if src == node and attrn in container.nodes[trg] \
                    and attrv < container.nodes[trg][attrn]:
                candidate_list.pop(candidate)
                break

def _regex_attr_filter(container, node, condition, candidate_list):
    """
    Filter on attributes which match an regex.
    """
    for candidate in list(candidate_list.keys()):
        attrn = condition[0]
        regex = condition[1]
        for src, trg in candidate_list[candidate]:
            if src == node and attrn not in container.nodes[trg]:
                candidate_list.pop(candidate)
                break
            if src == node and attrn in container.nodes[trg] \
                    and not re.search(regex, container.nodes[trg][attrn]):
                candidate_list.pop(candidate)
                break

def _same_filter(node1, node2, candidate_list):
    """
    Filter out candidates which do not adhere the same target composition
    request.
    """
    for candidate in list(candidate_list.keys()):
        n1_trg = ''
        n2_trg = ''
        for src, trg in candidate_list[candidate]:
            if n1_trg == '' and src == node1:
                n1_trg = trg
            elif n1_trg != '' and src == node2:
                if trg != n1_trg:
                    candidate_list.pop(candidate)
                    break
            if n2_trg == '' and src == node2:
                n2_trg = trg
            elif n2_trg != '' and src == node1:
                if trg != n2_trg:
                    candidate_list.pop(candidate)
                    break

def _diff_filter(node1, node2, candidate_list):
    """
    Filter out candidates which do not adhere the different target composition
    request.
    """
    for candidate in list(candidate_list.keys()):
        n1_trg = ''
        n2_trg = ''
        for src, trg in candidate_list[candidate]:
            if n1_trg == '' and src == node1:
                n1_trg = trg
            elif n1_trg != '' and src == node2:
                if trg == n1_trg:
                    candidate_list.pop(candidate)
                    break
            if n2_trg == '' and src == node2:
                n2_trg = trg
            elif n2_trg != '' and src == node1:
                if trg == n2_trg:
                    candidate_list.pop(candidate)
                    break

def _share_attr(container, attrn, nlist, candidate_list):
    """
    Filter out candidates which do not adhere the request that all target nodes
    stitched to in the nlist share the same attribute value for a given
    attribute name.
    """
    for candidate in list(candidate_list.keys()):
        attrv = ''
        for src, trg in candidate_list[candidate]:
            if attrn not in container.nodes[trg]:
                candidate_list.pop(candidate)
                break
            elif src in nlist and attrv == '':
                attrv = container.nodes[trg][attrn]
            elif src in nlist and container.nodes[trg][attrn] != attrv:
                candidate_list.pop(candidate)
                break

def _nshare_attr(container, attrn, nlist, candidate_list):
    """
    Filter out candidates which do not adhere the request that all target nodes
    stitched to in the nlist do not share the same attribute value for a given
    attribute name.
    """
    for candidate in list(candidate_list.keys()):
        attrv = ''
        for src, trg in candidate_list[candidate]:
            if attrn not in container.nodes[trg]:
                candidate_list.pop(candidate)
                break
            elif src in nlist and attrv == '':
                attrv = container.nodes[trg][attrn]
            elif src in nlist and container.nodes[trg][attrn] == attrv:
                candidate_list.pop(candidate)
                break

class GlobalStitcher(stitcher.Stitcher):
    """
    Base stitcher with the functions which need to be implemented.
    """

    def stitch(self, container, request, conditions=None,
               candidate_filter=my_filter):
        """
        Stitch a request graph into an existing graph container. Returns a set
        of possible options.

        :param container: A graph describing the existing container with
            ranks.
        :param request: A graph describing the request.
        :param conditions: Dictionary with conditions - e.g. node a & b need
            to be related to node c.
        :param candidate_filter: Function which allows for filtering useless
            options upfront.
        :return: The resulting graphs(s).
        """
        res = []
        # TODO: optimize this using concurrency & parallelism

        # 1. find possible mappings
        tmp = {}
        for node, attr in request.nodes(data=True):
            if attr[stitcher.TYPE_ATTR] in self.rels:
                candidates = _find_nodes(container,
                                         self.rels[attr[stitcher.TYPE_ATTR]])
                for candidate in candidates:
                    if node not in tmp:
                        tmp[node] = [candidate]
                    else:
                        tmp[node].append(candidate)

        # 2. find candidates
        # dictionary so we have hashed keys (--> speed)
        candidate_edges = {}
        keys = list(tmp.keys())
        per = [tmp[key] for key in keys]

        for edge_list in itertools.product(*per):
            j = 0
            edges = []
            for item in edge_list:
                edges.append((keys[j], item))
                j += 1
            if edges:
                candidate_edges[str(edges)] = edges

        # 3. (optional step): filter
        candidate_edges = candidate_filter(container, candidate_edges,
                                           conditions)

        # 4. create candidate containers
        tmp_graph = nx.union(container, request)
        for item in list(candidate_edges.values()):
            candidate_graph = copy.deepcopy(tmp_graph)  # faster graph copy
            # candidate_graph = tmp_graph.copy()
            for src, trg in item:
                candidate_graph.add_edge(src, trg)
            res.append(candidate_graph)
        return res


"""empty message

Revision ID: af22d4993983
Revises:
Create Date: 2022-07-24 15:46:17.555519

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'af22d4993983'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('users',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('fullname', sa.String(), nullable=True),
    sa.Column('email', sa.String(), nullable=True),
    sa.Column('password', sa.String(), nullable=False),
    sa.Column('date_employed', sa.Date(), nullable=False),
    sa.Column('access_level', sa.Integer(), nullable=False),
    sa.Column('task_load', sa.Integer(), nullable=True),
    sa.Column('success_ratio', sa.Float(), nullable=True),
    sa.Column('score', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=False)
    op.create_index(op.f('ix_users_fullname'), 'users', ['fullname'], unique=False)
    op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
    op.create_table('tasks',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('title', sa.String(), nullable=True),
    sa.Column('description', sa.String(), nullable=True),
    sa.Column('price', sa.Float(), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('is_completed', sa.Boolean(), nullable=True),
    sa.Column('time_to_complete', sa.Time(), nullable=True),
    sa.Column('datetime_received', sa.DateTime(), nullable=True),
    sa.Column('datetime_completed', sa.DateTime(), nullable=True),
    sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_tasks_id'), 'tasks', ['id'], unique=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_tasks_id'), table_name='tasks')
    op.drop_table('tasks')
    op.drop_index(op.f('ix_users_id'), table_name='users')
    op.drop_index(op.f('ix_users_fullname'), table_name='users')
    op.drop_index(op.f('ix_users_email'), table_name='users')
    op.drop_table('users')
    # ### end Alembic commands ###


"""
Test the CoNLL data loader.
"""
import os

import torch
from torch.utils.data import DataLoader

from nsr.utils.conll_dataset import count_conll_vocab, compute_f1, ConllDataset

def test_count_conll_vocab(shared_datadir):
    char_counter, label_counter = count_conll_vocab(
        os.path.join(shared_datadir, "conll_sample.txt"))

    assert len(label_counter) == 4
    assert label_counter["O"] == 4
    assert label_counter["B-PER"] == 3
    assert label_counter["I-PER"] == 1
    assert label_counter["B-LOC"] == 1

    assert len(char_counter) == 20
    assert char_counter["o"] == 4
    assert char_counter["e"] == 3
    assert char_counter["h"] == 3
    assert char_counter["i"] == 1
    assert char_counter["é"] == 1

def test_conll_dataset(shared_datadir, dummy_vocabs):
    """Test the CoNLL dataset loader for single examples.
    """
    token_vocab, char_vocab, label_vocab = dummy_vocabs
    assert len(token_vocab) == 6 + 2  # plus 2 special tokens
    assert len(char_vocab) == 26 * 2 + 2
    assert len(label_vocab) == 5 + 2
    dataset = ConllDataset(os.path.join(shared_datadir, "conll_sample.txt"),
                           token_vocab, char_vocab, label_vocab)
    assert len(dataset) == 3

    # Note: The index order in the Vocab is random due to Counter
    # We only do sanity checks: same string mapped to the same index
    tokens_0, chars_0, labels_0 = \
        dataset[0]["tokens"], dataset[0]["token_chars"], dataset[0]["labels"]
    tokens_1, chars_1, labels_1 = \
        dataset[1]["tokens"], dataset[1]["token_chars"], dataset[1]["labels"]
    tokens_2, chars_2, labels_2 = \
        dataset[2]["tokens"], dataset[2]["token_chars"], dataset[2]["labels"]

    assert len(tokens_0) == len(chars_0) == len(labels_0) == 5
    assert len(tokens_1) == len(chars_1) == len(labels_1) == 3
    assert len(tokens_2) == len(chars_2) == len(labels_2) == 1

    assert tokens_0.tolist() == [5, 6, 7, 2, 0]  # "London" is unknown
    assert tokens_1.tolist() == [6, 4, 3]
    assert tokens_2.tolist() == [0]

    assert chars_0[0].tolist() == [17, 32, 47, 32, 45]  # "Peter"
    assert chars_1[2].tolist() == [35, 28, 43, 43, 52]  # "happy"
    assert chars_1[0][0] != chars_1[1][1]  # "S" v.s. "s"
    assert chars_2[0][6] == 0  # character "é" is unknown
    # Repeated token "Such"
    assert chars_0[1].tolist() == chars_1[0].tolist() == [20, 48, 30, 35]

    assert labels_0.tolist() == [3, 5, 6, 6, 2]
    assert labels_1.tolist() == [3, 6, 6]
    assert labels_2.tolist() == [3]

def test_write_conll_prediction(shared_datadir, dummy_vocabs):
    token_vocab, char_vocab, label_vocab = dummy_vocabs
    dataset = ConllDataset(os.path.join(shared_datadir, "conll_sample.txt"),
                           token_vocab, char_vocab, label_vocab)

    tokens = torch.tensor([
        [5, 6, 7, 2, 0], [6, 4, 3, 1, 1], [0, 1, 1, 1, 1]
    ])
    labels = torch.tensor([
        [3, 5, 6, 6, 2], [3, 6, 6, 1, 1], [3, 1, 1, 1, 1]
    ])
    predictions = torch.tensor([
        [3, 5, 6, 6, 2], [6, 6, 6, 1, 1], [5, 1, 1, 1, 1]
    ])

    assert dataset.write_prediction(tokens, labels, predictions) == \
        "peter B-PER B-PER\n" \
        "such I-PER I-PER\n" \
        "won O O\n" \
        "at O O\n" \
        "<unk> B-LOC B-LOC\n\n" \
        "such B-PER O\n" \
        "is O O\n" \
        "happy O O\n\n" \
        "<unk> B-PER I-PER\n\n"

def test_compute_conll_f1(shared_datadir):
    prediction_dump = \
        "peter B-PER B-PER\n" \
        "such I-PER I-PER\n" \
        "won O O\n" \
        "at O O\n" \
        "<unk> B-LOC B-LOC\n\n" \
        "such B-PER O\n" \
        "is O O\n" \
        "happy O O\n\n" \
        "<unk> B-PER I-PER\n\n"
    # 4 entities: TP 3, FN 1 FP 0
    f1 = compute_f1(prediction_dump,
                    os.path.join(shared_datadir, "conlleval.pl"))
    assert abs(f1 - 2 * 100 * 75 / (100 + 75)) < 1e-2


from setuptools import setup

__author__ = 'Ambrose J. Carr'
__version__ = '0.0.1'

setup(name='simpleseq',
      version=__version__,
      description='simple single-cell sequencing tools',
      author='Ambrose J. Carr',
      author_email='mail@ambrosejcarr.com',
      package_dir={'': 'src'},
      packages=['simpleseq'],
      install_requires=[
          'numpy>=1.10.0',
          'pandas>=0.16.0',
          'matplotlib>=1.5.0',
          'seaborn',
          'regex',
          'boto3',
          'requests'],
      scripts=['src/scripts/merge_annotations',
               'src/scripts/extract_test_fastq',
               'src/scripts/align',
               'src/scripts/align_basespace',
               'src/scripts/align_s3',
               'src/scripts/count_molecules',
               'src/scripts/post_process_mars_seq',
               'src/scripts/rmt_distribution',
               'src/scripts/rmt_distribution_mars']
      )


import random
import pygame
import pygame.mixer
import os
import ntpath
from tkinter import Button,Tk,Frame,TOP,Label,Listbox,CENTER,END

pygame.mixer.init()
root=Tk()
root.geometry("1600x800+0+0")
root.configure(background="white")
Tops=Frame(root,width=1350,height=50,bd=8,bg="black")
Tops.pack(side=TOP)

lblinfo=Label(Tops,font=('Blackadder ITC',40,'bold'),text="Music Player",bd=10,fg="red")
lblinfo.grid(row=0,column=0)
list=[]
list5=[]
for rt, dirs, files in os.walk('D:/INNOVATIVE/songs'):
    for file in files:
        if file.endswith('.mp3'):
            list.append(os.path.join(rt,file))
txtdisplay=Listbox(root,height=23,width=38,bd=16,font=('arial',15,'bold'),fg="green",bg="black")
txtdisplay.place(relx=0.7,rely=0.6,anchor=CENTER)

i=0
for name in list:
    list5.append(ntpath.basename(name))
    txtdisplay.insert(END,list5[i])
    i+=1
index=0
def next():

    global index
    index+=1
    if index==len(list):
        btn5['state']='disabled'
        pygame.mixer.music.stop()
        txtdisplay.itemconfig(index-1, {'fg': 'green'})
        index=0

    else:
        txtdisplay.itemconfig(index-1, {'fg': 'green'})
        txtdisplay.itemconfig(index, {'fg': 'red'})
        pygame.mixer.music.load(list[index])
        pygame.mixer.music.play()
def stop():

    pygame.mixer.music.stop()
def pause():
    pygame.mixer.music.pause()
def unpause():
    pygame.mixer.music.unpause()
def previous():
    global index
    index-=1
    if index==-1:
        pygame.mixer.music.stop()
        txtdisplay.itemconfig(index+1, {'fg': 'green'})
        index=0
    else:
        txtdisplay.itemconfig(index, {'fg': 'red'})
        txtdisplay.itemconfig(index+1, {'fg': 'green'})
        pygame.mixer.music.load(list[index])
        pygame.mixer.music.play()
def play():
    global index
    btn5['state']='normal'
    txtdisplay.itemconfig(index, {'fg': 'red'})
    pygame.mixer.music.load(list[index])
    pygame.mixer.music.play()
def exit1():
    exit()
    return
btn6=Button(root,text="play",fg="powder blue",padx=10,pady=10,bd=4,width=10,bg="blue",font=('Brush Script MT',15,'bold'),command=play)
btn6.place(relx=0.1,rely=0.3,anchor=CENTER)
btn5=Button(root,text="next",fg="powder blue",bg="blue",padx=10,pady=10,bd=4,width=10,state="normal",font=('Brush Script MT',15,'bold'),command=next)
btn5.place(relx=0.3,rely=0.3,anchor=CENTER)
btn1=Button(root,text="stop",fg="powder blue",bg="red",padx=10,pady=10,bd=4,width=10,font=('Brush Script MT',15,'bold'),command=stop)
btn1.place(relx=0.2,rely=0.45,anchor=CENTER)
btn2=Button(root,text="pause",fg="powder blue",bg="blue",padx=10,pady=10,bd=4,width=10,font=('Brush Script MT',15,'bold'),command=pause)
btn2.place(relx=0.1,rely=0.6,anchor=CENTER)
btn3=Button(root,text="unpause",fg="powder blue",bg="blue",padx=10,pady=10,bd=4,width=10,font=('Brush Script MT',15,'bold'),command=unpause)
btn3.place(relx=0.3,rely=0.6,anchor=CENTER)
btn4=Button(root,text="previous",fg="powder blue",bg="blue",padx=10,pady=10,bd=4,width=10,font=('Brush Script MT',15,'bold'),command=previous)
btn4.place(relx=0.1,rely=0.8,anchor=CENTER)
btn7=Button(root,text="Exit",fg="powder blue",bg="blue",padx=10,pady=10,bd=4,width=10,font=('Brush Script MT',15,'bold'),command=exit)
btn7.place(relx=0.3,rely=0.8,anchor=CENTER)
root.mainloop()


# writing error records to a file

# ErrorRecordWriter class
class ErrorRecordWriter:

    # ErrorRecordWriter init
    def __init__(self, filePath, separator, batch_info):
        self.filePath = filePath
        self.separator = separator
        self.batch_info = batch_info

    # ErrorRecordWriter writeerrorrecords function
    def writeerrorrecords_file(self, errorrecords):
        #print(errorrecords)
        for rule in errorrecords:
            file = open(self.filePath+"_"+str(rule), "w")
            for line in errorrecords[rule]:
                str1 = ''
                for word in line:
                    str1 = str1+'\''+str(word)+'\','
                file.write(str1[:len(str1)-1]+'\n')
        file.close()

    def writeerrorrecords(self, error_records):
        #print(error_records)
        postgres_conn = self.batch_info['postgres_conn']
        for rule in error_records:
            failed_records = error_records[rule]
            if len(failed_records) > 1:
                self.batch_info['rule_id'] = rule
                postgres_conn.insert_error_records(self.batch_info, failed_records)

    # ErrorRecordWriter writefailedrules function
    def writefailedrules_file(self, failedrules):
        file = open(self.filePath, "w+")
        for rule in failedrules:
            file.write(str(rule)+','+failedrules[rule][2]+','+failedrules[rule][4]+'\n')
        file.close()

    def writefailedrules(self, rule_records):
        #print(error_records)
        postgres_conn = self.batch_info['postgres_conn']
        for rule in rule_records:
            rule_record = rule_records[rule]
            self.batch_info['rule_id'] = rule
            postgres_conn.insert_rule_records(self.batch_info, rule_record)


from multiprocessing import Process, Queue
import serial
import time
import timeit
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import optimize as opt
import numpy as np
from math import pi
import itertools
from functools import partial

WRITE = False
offsets = offsets = [0, -4, -4.5, -4.5]
amplitude_weights = [1, 1, 1, 1]

f = 40000
c = 340
wavelength = c/f
k = 2*pi/wavelength
pi_over_180 = pi / 180

spacing = 0.0105
spacing_over_c = spacing / c

def convertToInt(array):
    # return [int.from_bytes(array[2*i:2*i+1], byteorder='little') \
            # for i in range((int)(bytes_per_array/2))]
    new_array = []
    for a in zip(array[::2], array[1::2]):
        new_array.append(int.from_bytes(a, byteorder='little'))
    return new_array

def max_rolling1(a, window,axis =1):
        shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
        strides = a.strides + (a.strides[-1],)
        rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
        return np.max(rolling,axis=axis)

def modulated_sine(x, *pars):
    try:
        if len(pars) == 1:
            pars = pars[0]
        f, phi, p0, p1, p2, offset = pars
    except ValueError:
        print(pars)
        raise
    local_aplitude = (p0 + p1*x + p2*x**2)
    return local_aplitude*np.sin(2*pi*f*x + phi) + offset

def fit_data(x, y, window_size):
    t1 = x
    sensor = y
    fit_window = window_size
    fit_sensor = lambda x: 0
    r = 0
    par, _ = opt.curve_fit(
        modulated_sine,
        t1[0:2*fit_window] - 0.5*fit_window*4,
        sensor[0:2*fit_window],
        [40000*1e-6, 0, 11, 0.1, 0.1, 1700],
        maxfev = 1000
    )
    temp = lambda x, pars=par, r=r, fit_window=fit_window: ((r)*fit_window*4 < x) * (x < (r+1)*fit_window*4) * modulated_sine(x-(r+0.5)*fit_window*4, pars)
    temp2 = lambda x, f=fit_sensor, t=temp: f(x) + t(x)
    fit_sensor = temp2

    for r in range(1, int(len(x)/fit_window)-1):
        try:
            par, _ = opt.curve_fit(
                modulated_sine,
                t1[int((r-0.7)*fit_window):int((r+1.7)*fit_window)] - (r+0.5)*fit_window*4,
                sensor[int((r-0.7)*fit_window):int((r+1.7)*fit_window)],
                [40000*1e-6, 0.1, 1, 0.1, 0.01, 1700],
                maxfev=1000
            )
        except RuntimeError:
            par = [0, 0, 0, 0, 0, 0]
        if r == int(1600/fit_window):
            print(par[0])
        temp = lambda x, pars=par, r=r, fit_window=fit_window: ((r)*fit_window*4 < x) * (x < (r+1)*fit_window*4) * modulated_sine(x-(r+0.5)*fit_window*4, pars)
        temp2 = lambda x, f=fit_sensor, t=temp: f(x) + t(x)
        fit_sensor = temp2
    return fit_sensor

def plot_2d(waveforms, delta_theta=60):
    # sin(m_angle*pi/180.)*k*m_spacing
    NUM_RECEIVERS = len(waveforms)
    num_samples = len(waveforms[0])

    times = [np.linspace(i, num_samples*4 + i, num_samples) for i in range(NUM_RECEIVERS)]

    fit_window = 23

    start_time = timeit.default_timer()

    fit_sensors = []

    for t, w in zip(times, waveforms):
        fit_sensors.append(fit_data(t[50:-500], w[50:-500], fit_window))

    elapsed = timeit.default_timer() - start_time
    print("########\nFits took {} ms".format(elapsed*1e3))
    start_time = timeit.default_timer()

    theta = np.arange(-delta_theta/2, delta_theta/2, 0.8)
    rho   = np.arange(0.23, 0.37, 0.001)

    timeDiff = np.sin(theta*pi_over_180)*spacing_over_c

    window_size = 17 # sollte ungerade sein
    rho_plot = rho[int(window_size/2):-int(window_size/2)]
    timeDistance = 2e6 * rho / 340

    z_plot = []
    for t_ in timeDiff:
        # timeDiff = np.sin(t_*pi_over_180)*spacing_over_c
        values = np.zeros(len(timeDistance))
        for i in range(NUM_RECEIVERS):
            values += amplitude_weights[i]*fit_sensors[i](offsets[i]+timeDistance-i*1e6*t_)

        values = np.abs(values)
        z_plot.append(max_rolling1(values, window_size))

    z_plot = np.array(z_plot)
    z_min = z_plot.min()
    z_max = z_plot.max()
    z_plot -= z_min
    z_plot /= z_max
    z_plot = np.exp(z_plot)

    elapsed = timeit.default_timer() - start_time
    print("Digital scan took {} ms".format(elapsed*1e3))

    return theta, rho_plot, z_plot

def handle_arduino_output(queue, delta_theta=60):
    with serial.Serial(port='COM4', baudrate=115200, timeout=5.0) as arduino:
        filesWritten = 0
        while True:

            # align to starting pattern
            count = 0
            pattern = [1, 200, 31, 41]
            patternPosition = 0
            while True:
                value = arduino.read(1)[0]
                if value == pattern[patternPosition]:
                    count += 1
                else:
                    count = 0
                    patternPosition = 0
                if count > 24:
                    # print("Found {} {} in a row".format(count, pattern[patternPosition]))
                    patternPosition += 1
                    count = 0
                    if patternPosition == len(pattern):
                        break

            try:
                message = arduino.readline()
                print(message.decode("utf-8"))

                bytes_per_array = int.from_bytes(arduino.read(4), byteorder='little')
                num_arrays      = int.from_bytes(arduino.read(4), byteorder='little')
                print("Bytes per array: {}".format(bytes_per_array))
                start_time = timeit.default_timer()
                arrays = []
                for i in range(num_arrays):
                    arrays.append(arduino.read(bytes_per_array))
                elapsed = timeit.default_timer() - start_time

                print("Timed the serial read. Elapsed time: {:2.3f} ms".format(elapsed * 1000))

                start_time = time.perf_counter_ns()
                for i in range(num_arrays):
                    arrays[i] = convertToInt(arrays[i])

                elapsed = time.perf_counter_ns() - start_time

                if filesWritten < 5 and WRITE:
                    with open('waveforms/0deg_waveform_{}'.format(filesWritten), 'w') as f:
                        for i in range(len(arrays[0])):
                            for j in range(len(arrays)):
                                f.write("{} ".format(arrays[j][i]))
                            f.write("\n")
                    filesWritten += 1

                theta, rho_plot, z_plot = plot_2d(arrays, delta_theta)
                # queue.put((arrays[0][:-1000:2], theta, rho_plot, z_plot,))
                queue.put((0, theta, rho_plot, z_plot,))
                # queue.put((arrays[0][:-1500], 0, 0, 0,))

                message = arduino.readline()
                print(message.decode("utf-8"))
                print("\n")

            except UnicodeDecodeError:
                pass

def make_frame(delta_theta, queue, ax1, ax2):
    array, theta, rho_plot, z_plot = queue.get(timeout=5.0)

    colormap = plt.get_cmap('inferno')
    z_min = z_plot.min()
    z_max = z_plot.max()
    norm = mpl.colors.Normalize(z_min, z_max)
    ax1.clear()
    ax1.set_thetamin(-delta_theta/2)
    ax1.set_thetamax(delta_theta/2)
    ax1.set_rmin(0.2)
    ax1.set_theta_offset(pi/2)

    for t, values in zip(theta, z_plot):
        ax1.scatter([-t*pi/180]*len(rho_plot), rho_plot, c=values, s=6, cmap=colormap, norm=norm, linewidths=0)

    # xarr = range(len(array))
    # ax2.clear()
    # ax2.plot(xarr, array)

def main():
    delta_theta = 60

    queue = Queue()
    arduino_process = Process(target=handle_arduino_output, args=(queue,delta_theta,))
    arduino_process.daemon = True
    arduino_process.start()

    fig = plt.figure()
    ax1 = plt.subplot(1, 1, 1, polar=True)
    # ax2 = plt.subplot(1, 2, 2)
    next_frame = partial(make_frame, queue=queue, ax1=ax1, ax2=None)

    ani = animation.FuncAnimation(fig, next_frame, itertools.repeat(60), interval=10, save_count=1)

    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    main()


import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd

def plot_clusters(data):
    x, y, cluster = zip(*data)
    plt.scatter(x, y, c = cluster, cmap=cm.Dark2)
    plt.title("Clustering, k = {}".format(len(np.unique(cluster))))
    plt.xlabel("x1")
    plt.ylabel("x2")
    plt.show()

def plot_sse(data):
    k, sse = zip(*data.items())
    plt.plot(k, sse)
    plt.title("Sum of Squared Error")
    plt.xlabel("k")
    plt.ylabel("SSE")
    plt.show()

def plot_linear(x, y):
    # Plot outputs
    plt.plot(x, y, color='blue', linewidth=3)

    plt.xticks(())
    plt.yticks(())

    plt.show()

def plot_roc(title, label, proba):
    """Plots ROC curve

    Arguments:
        label {np.ndarray} -- true label
        proba {np.ndarray} -- predicted probabilites of class membership
    """
    rates = []

    pair = pd.concat((pd.DataFrame(proba), pd.DataFrame(label)), axis=1)
    pair.columns = ("proba", "target")
    pair_sorted = pair.sort_values(pair.columns[0], ascending=False)
    matrix = pair_sorted.values
    for i in matrix:
        thresh = i[0]
        rates.append(_calc_rates(matrix, thresh))

    r = pd.DataFrame(rates)
    plt.plot(r[1].values, r[0].values)
    plt.ylim([0,1])
    plt.xlim([0,1])
    plt.xticks(np.arange(0, 1.1, 0.1))
    plt.yticks(np.arange(0,1.1, 0.1))
    plt.title(title)
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive')
    plt.show()

# Helper Functions

def _calc_rates(matrix, thresh):
    """Calculates true positive rate and false positive rate for a given threshold

    Arguments:
        matrix {np.ndarray} -- true labels and predicted probabilities
        thresh {float} -- threshold for a round of ROC construction

    Returns:
        [float, float] -- true positive rate, false positive rate
    """

    tp = 0
    fp = 0
    tn = 0
    fn = 0
    n = len(matrix)
    for i in matrix:
        pred = 1 if i[0] >= thresh else 0
        if pred == 1:
            if i[1] == 1:
                tp += 1
            else:
                fp += 1
        else:
            if i[1] == 0:
                tn += 1
            else:
                fn += 1
    tpr = tp / (tp+fn)
    fpr = fp / (fp + tn)
    return tpr, fpr


# coding: utf-8
"""
Script:  pnt_stats.py
Author:  Dan.Patterson@carleton.ca
Modified: 2016-07-07
Purpose:
:  return properties for xy point arrays
:Useage
:  xy a 2D array of x,y coordinates
:  f = 'pnt_10.txt'
:  np.savetxt(f, xy, fmt='%10i',delimiter=',')
:  np.loadtxt(f, delimiter=',')
:
:Notes
:  np.median  numpy.lib.function_base
:  np.mean    numpy.core.fromnumeric
:  np.min     ...
:  np.max     ...
:  np.ptp     ...
:  np.std     ...
:  np.var     ...
:  std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False)
:  see _methods, all except median are delivered as methods as well
:  ie a.mean(axis=0) = np.mean(a, axis=0) etc
"""
import numpy as np
import sys
import os

script = sys.argv[0]

def stats_xy(a, prn=True):
    """Data properties for 2D point/xy objects
    :Requires
    :--------
    :  The data should represent point objects in 2D.
    :  ie. a.shape: (n,2), a.ndim: 2
    :Returns
    :-------
    :  General statistics, including extent values from which extent
    :  points can be formed.
    :Notes:
    :  It should be obvious that the 'result' list contains the methods
    :  to use if single values of a statistic are needed.
    :  - array construction below, querying follows
    :  - r[r['stat']=='mean']
    :      array([('mean', [300053.9, 5025068.3])],
    :      dtype=[('Stat', '<U5'), ('XY', '<f8', (2,))])
    """
    if (a.ndim != 2):
        frmt ="{}: expects a 2D array... here are the docs\n\n{}"
        print(frmt.format(stats_xy.__name__, stats_xy.__doc__))
        return None
    stat = "mean, median, min, max, ptp, std, var"
    names = [ s.strip() for s in stat.split(",") ]
    result = [np.mean(a, axis=0), np.median(a, axis=0),
              np.min(a, axis=0), np.max(a, axis=0), np.ptp(a, axis=0),
              np.std(a, axis=0, dtype=np.float64, ddof=0),
              np.var(a, axis=0, dtype=np.float64, ddof=0)
              ]
    r = list(zip(names, result))
    L, B = result[2]; R, T = result[3]
    frmt = "\nArray properties... N={}".format(len(a))
    frmt += "\n  L {}  B {}\n R  {}  T {}\n".format(L, B, R, T)
    frmt += "\n".join(['{!s:<8} {!s:<16}'.format(i,j) for i,j in r])
    if prn:
        print(frmt)
    else:
        dt = [('stat', 'U8'),("XY", "<f8", (2,))]
        r = np.asarray(r, dtype=dt)
        return r
    # ----

if __name__=="__main__":
    """using demo data"""
    path = sys.argv[0]
    f = os.path.dirname(path)+'/pnt_10.txt'
    a = np.loadtxt(f, delimiter=',')
    r = stats_xy(a, prn=True)
"""
sample data as an option to the file
    300078,   5025070
    300074,   5025099
    300086,   5025076
    300045,   5025089
    300015,   5025039
    300018,   5025074
    300062,   5025073
    300051,   5025023
    300061,   5025088
    300049,   5025052
"""


import discord
from numpy.core.numeric import NaN
import pandas_datareader as web
import datetime as dt
from datetime import timedelta
import os
from dotenv import load_dotenv
import pandas as pd

load_dotenv()

client = discord.Client() # starts the discord client.

AUTH_TOKEN = os.getenv('AUTH_TOKEN')
SHEET_ID_CRYPTO_BUY = os.getenv('SHEET_ID_CRYPTO_BUY')

mins = 5 #how many minutes between refreshes

lastRefresh = dt.datetime.now()

@client.event
async def on_message(message):
    global lastRefresh
    if message.content.startswith('!status'):
        timeDelta = dt.datetime.now() - lastRefresh
        msg = "Online! Last price check was " + str(timeDelta.seconds / 60) + " minutes ago"
        #TODO: fix this so that it rounds properly
        await message.channel.send(msg)
    #TODO: make this be more universal (!price {symbol}), where symbol is either a crypto converted or a stock
    # also make the message be "BTC: $56,900".
    if message.content.startswith('!priceBTC'):
        await message.channel.send(getPrice('BTC-USD'))
    if message.content.startswith('!priceETH'):
        await message.channel.send(getPrice('ETH-USD'))
    # Ideas for more commands:
    # help commander to list commands
    # timing to tell us how often it fetches new data
    # history, which shows history of price alerts
    # we can also make this bot give us real-time data on BTC, ETH, etc pricing if we want.

    #TODO: make it so it can ONLY send messages if used in the right channel!

# We call this function every 5 minutes
# for now, it is just for crypto buy tables. I will eventually expand it to US markets (VTI and VOO), plus crypto sell tables
from discord.ext import commands, tasks
@tasks.loop(seconds=60*mins)
async def check_crypto_buy_tables():

    btc_price = getPrice('BTC-USD')
    eth_price = getPrice('ETH-USD')

    # We will do the same for VTI and VOO in the future. For now, however, we will focus on Crypto.

    sheet_id = SHEET_ID_CRYPTO_BUY
    sheet_name = "Buy_Tables"
    url = f"https://docs.google.com/spreadsheets/d/{sheet_id}/gviz/tq?tqx=out:csv&sheet={sheet_name}"

    buyCSV = pd.read_csv(url)

    #print(pd.read_csv(url))
    def createBuyEntries(csv):
        listOfBuyEntriesBtc = []
        # step 1: find out how to get all BTC prices
        btc_prices = csv.iloc[:, 0]
        # step 2: find out how to get all BTC fulfillments
        btc_fulfillments = csv.iloc[:, 3]
        # step 3: combine into one list
        for i in range(len(btc_prices)):
            listOfBuyEntriesBtc.append([btc_prices[i], btc_fulfillments[i]])
        # step 4: repeat for ETH
        listOfBuyEntriesEth = []

        eth_prices = csv.iloc[:, 5]

        eth_fulfillments = csv.iloc[:, 8]

        for i in range(len(eth_prices)):
            listOfBuyEntriesEth.append([eth_prices[i], eth_fulfillments[i]])

        return listOfBuyEntriesBtc, listOfBuyEntriesEth

    listOfBtcEntries, listOfEthEntries = createBuyEntries(buyCSV)

    # now, we iterate through each list and check the following things:
    # (1): is price greater than or equal to current price?
    # (2): is fulfilled NO
    #print("test", listOfBtcEntries)
    for x in listOfBtcEntries:
        if str(x[0]) ==  "nan":
            continue
        new_x = x[0]
        new_x = new_x[1:].replace(",", "")
        #print(new_x, btc_price, x[1])
        if float(new_x) >= float(btc_price) and x[1] == "NO":
            channel = client.get_channel(911349581667790889)
            format_str = "BTC is currently at " + str(btc_price) + ", which is below one of the table entry's price ceiling of " + str(x[0])
            await channel.send(format_str)

    for x in listOfEthEntries:
        if str(x[0]) ==  "nan":
            continue
        new_x = x[0]
        new_x = new_x[1:].replace(",", "")
        if float(new_x) >= float(eth_price) and x[1] == "NO":
            channel = client.get_channel(911349581667790889)
            format_str = "ETH is currently at " + str(eth_price) + ", which is below one of the table entry's price ceiling of " + str(x[0])
            await channel.send(format_str)
    global lastRefresh
    lastRefresh = dt.datetime.now()

#TODO ASAP: make a sell table version which should b super simple
#we should make dummy data first though if we dont have the actual table made lol

# works for BTC-USD and VOO
def getPrice(asset_name):
    start = dt.datetime.now() - timedelta(days = 1)
    #print(start)
    end = dt.datetime.now()
    asset = web.DataReader(asset_name, 'yahoo', start, end)

    #print(asset) # the price we want is today's "close".
    price = asset.iloc[len(asset)-1][3]
    #print(price)

    return price

@client.event
async def on_ready():
    print(f'Successful Launch!!! {client.user}')
    check_crypto_buy_tables.start()

client.run(AUTH_TOKEN) # Pull Auth Token from above


import ftplib
import random
import torch
import torch.nn as nn
from torch.utils.data import DataLoader

import torch.nn.functional as F

from tqdm import tqdm
import wandb

from sklearn import metrics
from scipy.optimize import brentq
from scipy.interpolate import interp1d

from datasets import TestDataset

GPU = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
CPU = "cpu"

class Tester:

    def __init__(self, model, dataset:TestDataset, batch_size):

        self.model = model
        self.dataset = dataset
        self.loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=0)

    def prepareEmbedding(self):
        data_dict = self.dataset.getAllFeature()
        self.embs = {}

        for audio_id, features in tqdm(data_dict.items(), desc="getting embeddings"):

            #ft = features.to(GPU)
            self.model(features)

            emb = self.model.getEmbedding() # 2차원 데이터
            emb = torch.sum(emb, dim=0)# 여러개의 feature들의 임베딩 누적값, 각 요소가 커도 38정도
            self.embs[audio_id] = emb.to(CPU)

    def idListToEmbListTensor(self, id_list):
        """
        [
            [ embedding 1],
            [ embedding 2],
            ...
        ]
        """
        result = []

        for audio_id in id_list:
            result.append(self.embs[audio_id])

        return torch.stack(result, dim=0)

    def getEER(self, labels, cos_sims):
        labels = labels.to(CPU)
        cos_sims = cos_sims.to(CPU)
        fpr, tpr, _ = metrics.roc_curve(labels, cos_sims, pos_label=1)
        eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.)
        return eer

    def test(self, epoch):

        self.model.eval()

        self.prepareEmbedding()

        sims = []
        labels = []

        for audio_id1, audio_id2, label in tqdm(self.loader, desc="testing"):

            embs1 = self.idListToEmbListTensor(audio_id1).to(GPU) # 2차원 [id, node_idx]
            embs2 = self.idListToEmbListTensor(audio_id2).to(GPU)

            sim = F.cosine_similarity(embs1, embs2, dim = 1).to(CPU) # 1차원 형태
            #print(sim)
            sims.append(sim)
            labels.append(label)

        sims = torch.concat(sims, dim = 0)
        labels = torch.concat(labels, dim = 0)
        eer = self.getEER(labels, sims)
        print(f"epoch: {epoch}, EER: {eer}")
        wandb.log({"EER by epoch" : eer})


import datetime

from django.db.models.functions import Coalesce
from django.utils.translation import gettext_lazy as _
from django_filters.rest_framework import FilterSet, filters
from rest_framework.filters import OrderingFilter

from leasing.models import CollectionCourtDecision, CollectionLetter, CollectionNote
from leasing.models.invoice import InvoiceNote, InvoiceRow, InvoiceSet
from leasing.models.land_use_agreement import (
    LandUseAgreementInvoice,
    LandUseAgreementInvoiceRow,
    LandUseAgreementInvoiceSet,
)

from .models import Comment, Contact, Decision, District, Index, Invoice, Lease

class CoalesceOrderingFilter(OrderingFilter):
    """Ordering filter that supports defining coalescent fields

    Coalescent fields are configured by adding a new attribute coalesce_ordering to the view.

    Example:

    ordering_fields = ('names',)
    coalesce_ordering = {"names": ("business_name", "last_name")}

    The coalesce field must be set in the views "ordering_fields" attribute. '__all__' will not work.
    """

    def filter_queryset(self, request, queryset, view):
        ordering = self.get_ordering(request, queryset, view)

        if ordering:
            if hasattr(view, "coalesce_ordering"):
                for ordering_term in ordering:
                    ordering_term = ordering_term.lstrip("-")

                    if ordering_term in view.coalesce_ordering:
                        kwargs = {
                            ordering_term: Coalesce(
                                *view.coalesce_ordering[ordering_term]
                            )
                        }
                        queryset = queryset.annotate(**kwargs)

            return queryset.order_by(*ordering)

        return queryset

class CollectionCourtDecisionFilter(FilterSet):
    lease = filters.NumberFilter()

    class Meta:
        model = CollectionCourtDecision
        fields = ["lease"]

class CollectionLetterFilter(FilterSet):
    lease = filters.NumberFilter()

    class Meta:
        model = CollectionLetter
        fields = ["lease"]

class CollectionNoteFilter(FilterSet):
    lease = filters.NumberFilter()

    class Meta:
        model = CollectionNote
        fields = ["lease", "user"]

class CommentFilter(FilterSet):
    lease = filters.NumberFilter()

    class Meta:
        model = Comment
        fields = ["lease", "user", "topic"]

class ContactFilter(FilterSet):
    class Meta:
        model = Contact
        fields = [
            "id",
            "type",
            "first_name",
            "last_name",
            "name",
            "business_id",
            "national_identification_number",
            "sap_customer_number",
            "partner_code",
            "is_lessor",
        ]

class DecisionFilter(FilterSet):
    lease = filters.NumberFilter()
    reference_number = filters.CharFilter(lookup_expr="contains")

    class Meta:
        model = Decision
        fields = [
            "lease",
            "reference_number",
            "decision_maker",
            "decision_date",
            "type",
        ]

class DistrictFilter(FilterSet):
    class Meta:
        model = District
        fields = ["municipality", "identifier"]

class IndexFilter(FilterSet):
    class Meta:
        model = Index
        fields = ["year", "month"]

class InvoiceFilter(FilterSet):
    lease = filters.NumberFilter()
    going_to_sap = filters.BooleanFilter(
        method="filter_going_to_sap", label=_("Going to SAP")
    )

    class Meta:
        model = Invoice
        fields = ["lease", "state", "type"]

    def filter_going_to_sap(self, queryset, name, value):
        if value:
            return queryset.filter(
                due_date__gte=datetime.date.today(), sent_to_sap_at__isnull=True
            )
        return queryset

class InvoiceNoteFilter(FilterSet):
    lease = filters.NumberFilter()

    class Meta:
        model = InvoiceNote
        fields = ["lease"]

class InvoiceSetFilter(FilterSet):
    lease = filters.NumberFilter()

    class Meta:
        model = InvoiceSet
        fields = ["lease"]

class InvoiceRowFilter(FilterSet):
    invoice = filters.NumberFilter()

    class Meta:
        model = InvoiceRow
        fields = ["invoice"]

class LeaseFilter(FilterSet):
    class Meta:
        model = Lease
        fields = ["type", "municipality", "district"]

class LandUseAgreementInvoiceFilter(FilterSet):
    land_use_agreement = filters.NumberFilter()
    going_to_sap = filters.BooleanFilter(
        method="filter_going_to_sap", label=_("Going to SAP")
    )

    class Meta:
        model = LandUseAgreementInvoice
        fields = ["land_use_agreement", "state", "type"]

    def filter_going_to_sap(self, queryset, name, value):
        if value:
            return queryset.filter(
                due_date__gte=datetime.date.today(), sent_to_sap_at__isnull=True
            )
        return queryset

class LandUseAgreementInvoiceSetFilter(FilterSet):
    land_use_agreement = filters.NumberFilter()

    class Meta:
        model = LandUseAgreementInvoiceSet
        fields = ["land_use_agreement"]

class LandUseAgreementInvoiceRowFilter(FilterSet):
    invoice = filters.NumberFilter()

    class Meta:
        model = LandUseAgreementInvoiceRow
        fields = ["invoice"]


import csv, io
from django.shortcuts import render
from django.db.models import Q
import datetime
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.http import HttpResponse
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView,
    )

import django_filters
from django_filters import DateFilter
from django_filters.filters import DateFromToRangeFilter, DateRangeFilter

from .models import Post
from .filters import BillFilter, SummariesFilter
from .forms import PostForm

#go into home template when you need to change the fields of the db
def home(request):
    myFilter = BillFilter()

    context = {
        'posts': Post.objects.all(),
    }
    return render(request, 'SubmitData/home.html', context)

class PostListView(LoginRequiredMixin, ListView):
    model = Post
    template_name = 'SubmitData/home.html'
    context_object_name = 'posts'
    #ordering = ['-date_entered']

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = BillFilter(self.request.GET, queryset=self.get_queryset())
        return context

    def get_queryset(self):#only show logged in users' data
        #return self.model.objects.all().filter(author=self.request.user, is_paid=True)
        return self.model.objects.all().filter(author=self.request.user).order_by('-due_date')

class PostDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):
    model = Post

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

#CreateView handles all sending to db. It takes from the Post model and the fields are what is shown
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    #fields = ['title', 'company_name', 'account_number', 'statement_date', 'due_date', 'amount', 'payment_method',
    #'is_paid', 'payment_method', 'is_paid', 'previous_balance', 'minimum_payment', 'payments', 'adjustment',
    #'credit', 'late_fees', 'interest_charges']
    form_class = PostForm

    def form_valid(self, form):
        form.instance.author = self.request.user #sets author to logged in user
        return super().form_valid(form)

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'company_name', 'account_number', 'statement_date', 'due_date', 'amount', 'payment_method',
    'is_paid', 'payment_method', 'is_paid', 'previous_balance','minimum_payment', 'payments', 'adjustment',
     'credit', 'late_fees', 'interest_charges']

    def form_valid(self, form):
        form.instance.author = self.request.user #sets author to logged in user
        return super().form_valid(form)

    #the function that UserPassesTestMixin uses to stop them from updating posts that are not theirs
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = '/' #home page redirect when finished

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class IsPaidView(LoginRequiredMixin, ListView):
    model = Post
    template_name = 'SubmitData/not_paid.html'
    context_object_name = 'posts'
    ordering = ['-date_entered']

    def get_queryset(self):#only show logged in users' data
        #return self.model.objects.all().filter(Q(author=self.request.user, due_date__gte=datetime.date.today(), is_paid=False) | Q(author=self.request.user, is_paid=False)) #is_paid=False,
        return self.model.objects.all().filter(Q(author=self.request.user, due_date__gte=datetime.date.today(), is_paid=False)| Q(author=self.request.user, is_paid=False)) #| Q(author=self.request.user, is_paid=False))

class YearlyMonthlySummaryView(LoginRequiredMixin, ListView):
    model = Post
    template_name = 'SubmitData/summaries.html'
    context_object_name = 'posts'
    ordering = ['-due_date']

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['summary'] = SummariesFilter(self.request.GET, queryset=self.get_queryset())
        return context

def BillStatement(request):
    return render(request, 'SubmitData/billstatement.html', {'title':'About'})

def BillExport(request):

    items = Post.objects.all().filter(author=request.user)
    #export_user = Post.objects.filter(author=request.user)

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="billable_bill_data.csv"'

    writer = csv.writer(response, delimiter=',')
    writer.writerow(['title', 'company_name', 'account_number', 'statement_date', 'due_date', 'date_entered',
    'amount', 'is_paid', 'payment_method', 'previous_balance', 'minimum_payment', 'payments', 'credit', 'adjustment',
    'late_fees', 'interest_charges'])

    for obj in items:
        writer.writerow([obj.title, obj.company_name, obj.account_number, obj.statement_date, obj.due_date, obj.date_entered,
    obj.amount, obj.is_paid, obj.payment_method, obj.previous_balance, obj.minimum_payment, obj.payments, obj.credit, obj.adjustment,
    obj.late_fees, obj.interest_charges])

    return response


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 11:51:14 2019

@author: apple
"""
import pandas as pd
import numpy as np
import math
from gurobipy import Model,GRB,quicksum
import csv

def optModel(roomdata, S, E, A, B, G, SR=None):
    roomsIndex = list(range(0,len(roomdata.iloc[:,0])))
    m = Model('Rooms')
    x = m.addVars(roomsIndex,name="x",vtype=GRB.BINARY)
    d = m.addVar(0, name="d", vtype=GRB.CONTINUOUS)
    DearDaniel = 7
    m.setParam("TIME_LIMIT", 45)

    #E = data.iloc[3,10]
    #A = data.iloc[4,10]
    #B = data.iloc[5,10]
    #G = data.iloc[6,10]
    #S = data.iloc[2,10]
    if SR is None:
        SR = 1800
    #Available rooms
    """x<= enddate & x>=startdate"""
    BoolInd = np.array([x>=float(startdate) for x in [float(a) for a in roomdata.columns.tolist()[11:]]])
    BoolInd2 = np.array([x<=float(enddate) for x in [float(a) for a in roomdata.columns.tolist()[11:]]])
    DateHeaders = [i+11 for i, x in enumerate(BoolInd&BoolInd2) if x]
    #print(IntInd)

    OccupiedRooms = roomdata.iloc[:, DateHeaders]
    OccupiedRoomsBool = np.sum(OccupiedRooms, axis=1)==1
    print(OccupiedRoomsBool)
    #print(OccupiedRooms)

    Orooms = roomdata.loc[OccupiedRoomsBool, :].index.values.tolist()
    Arooms = roomdata.loc[[not(a) for a in OccupiedRoomsBool],:]
    AroomsIndex = Arooms.index.values.tolist()
    print(Orooms)

    #Available rooms

    e = [0,1,2,40,41,42,43,44,106,107, 108, 109, 143, 23, 24,87]
    a = [39, 122, 123]
    b = [102,103,104,105,137,138,139]
    g = np.setdiff1d(roomsIndex,e+a+b)

    m.setObjective((quicksum(x[i] * roomdata.iloc[i,2] for i in roomsIndex))+ DearDaniel*d ,GRB.MINIMIZE)
    #space requirment
    #m.addConstr(quicksum(x[i] * data.iloc[i,1] for i in roomsIndex)>= S)
    #no occupied room
    m.addConstr(sum(x[i] for i in Orooms) == 0)
    #Exhibit hall is provided while requested
    m.addConstr(sum(x[i] for i in e)>= E)
    #Auditorium is provided while requested
    m.addConstr(sum(x[i] for i in a)>= A)
    #Ballroom is provided while requested
    m.addConstr(sum(x[i] for i in b)>= B)
    #Meeting Rooms
    m.addConstr(sum(x[i] for i in g)>= G)
    #if E is selected, Meeting room in that can't be selected
    m.addConstr((x[2]*(x[4]+x[5]+x[3]))==0)
    m.addConstr((x[40]*(x[46]+x[47]+x[45]))==0)
    m.addConstr((x[106]*(x[112]+x[113]+x[110]+x[111]))==0)
    m.addConstr(x[142]*(x[13]+x[14])==0)
    m.addConstr(x[78]*(x[79]+x[80])==0)
    m.addConstr(x[94]*(x[95]+x[96])==0)
    #Min SQFT
    m.addConstrs(x[i] == 0 for i in roomsIndex if roomdata.iloc[i,1] < SR)
    #distance stuff
    pRooms = [(Arooms.iloc[i,7],Arooms.iloc[i,8],Arooms.iloc[i,9],Arooms.iloc[i,10]) for i in range(len(AroomsIndex))]
    Sum = 0
    distMat = np.empty([len(Arooms), len(Arooms)])
    i = 0
    while i < len(Arooms):
        room1 = pRooms[i]
        j = i
        while j < len(Arooms):
            room2 = pRooms[j]
            adiff = [((room1[k] - room2[k])**2) for k in range(4)]
            dist = math.sqrt(sum(adiff))
            distMat[i][j] = dist
            distMat[j][i] = dist
            Sum += dist
            j+=1
        i+=1

    #distance calculation
    m.addConstr(d == sum([((x[i]*x[j]) * distMat[i][j]) for i in range(len(AroomsIndex)) for j in range(len(AroomsIndex))]))
    m.optimize()

    if m.status == GRB.Status.OPTIMAL or m.status == GRB.Status.TIME_LIMIT:
        x_sol = m.getAttr('x', x)
        chosenroom = []
        chosenbuild = []
        sumsqft = 0
        sumcost=0
        for i in roomsIndex:
            if round(x_sol[i])>= 1:
                chosenroom.append(roomdata.iloc[i,0])
                chosenbuild.append(roomdata.iloc[i,3])
                sumsqft = sumsqft + roomdata.iloc[i,1]
                sumcost = sumcost + roomdata.iloc[i,2]
#        #Chosen is the list of room selected
#
        for i in range(len(chosenbuild)):
            if chosenbuild[i] == 0:
               chosenbuild[i] = "A"
            elif chosenbuild[i]== 200:
               chosenbuild[i] = "B"
            else:
               chosenbuild[i] = "C"
        chosenbuild = set(chosenbuild)
    else:
    	sumcost = 0
    	chosenroom = []
#        print(chosenbuild)
#       if len(chosenroom) == 1:
#            print('{} is selected.'.format(chosenroom[0]))
#        else :
#           print('{} are selected.'.format(tuple(chosenroom)))
#        print('the sqft is {}'.format(sumsqft))
#        print('The room cost is {}'.format(sumcost))
#        print('The total cost is {}'.format(m.objVal))
    m.reset()
    return [sumcost, chosenroom]

if __name__ == "__main__":
	eventdata = pd.read_csv('TestData_v2.csv', index_col=0, header=0)
	roomdata = pd.read_csv('RoomInfo.csv', index_col=0, header=0)
	roomdata = roomdata[:143]
	csvOut = [['Cost', 'Rooms']]
	for i in range(0, len(eventdata)):
		startdate = eventdata.iloc[i, 3]
		enddate = eventdata.iloc[i, 4]
		optOut = optModel(roomdata, eventdata.iloc[i, 5], eventdata.iloc[i, 6], eventdata.iloc[i, 7], eventdata.iloc[i, 8], eventdata.iloc[i, 9], eventdata.iloc[i, 10])
		csvOut = csvOut + [optOut]

		BoolInd = np.array([x>=float(startdate) for x in [float(a) for a in roomdata.columns.tolist()[11:]]])
		BoolInd2 = np.array([x<=float(enddate) for x in [float(a) for a in roomdata.columns.tolist()[11:]]])
		IntInd = [i+11 for i, x in enumerate(BoolInd&BoolInd2) if x]
		print(IntInd)
		for a in optOut[1]:
			val = [a is b for b in roomdata.iloc[:, 0]]
			roomInd = [a for a, i in enumerate(val) if i]
			roomdata.iloc[roomInd, IntInd] = 1

	roomdata.to_csv('justforme.csv')
	with open('NewDataRoomsSelected.csv','w', newline="") as out:
		csv_out = csv.writer(out)
		for a in csvOut:
			csv_out.writerow(a)

    #if S> upper bound, return all the room


import os
import numpy as np
import sys
#This is your Project Root
sys.path.append(r"../..")
from pushkin.definition import ROOT_DIR

with open(ROOT_DIR+"/data/Subtasks_BD/twitter-2016train-BD.txt", "r") as f1, \
        open(ROOT_DIR+"/data/Subtasks_BD/twitter-2015testBD.txt", "r") as f2, \
        open(ROOT_DIR+"/data/Subtasks_BD/twitter-2016dev-BD.txt", "r") as f3:
    rawData1,rawData2,rawData3 = f1.read(),f2.read(),f3.read()

def arrangeDic(data):
    temArray = []
    lineData = data.split("\n")
    for line in lineData:
        attrData = line.split("\t")
        for item in attrData:
            if item == '':
                attrData.remove('')
        temArray.append(attrData)
    # print (temArray)
    return temArray

arrangeDic(rawData1)

temArray = []
lineData = rawData1.split("\n")
for line in lineData:
    attrData = line.split("\t")
    temArray.append(attrData)

# print (temArray)

list = [['a','a','a'],['b','b','b'],['c','c','c'],['a','a','a'],['b','b','b'],['c','c','c'],['a','a','a'],['b','b','b'],['c','c','c']]
dic = {'a' : 4, 'b' : 3}
a = [('jurassic world', 89), ('ac/dc', 91), ('fleetwood mac', 92), ('bob marley', 92), ('magic mike xxl', 92), ('eric church', 93)]

for item in a :
    print (item[0])
    print (1)

# print (list)
# print (dic)

keyList = []
targetList = []
for key,value in dic.items():
    keyList.append(key)
for item in list:
    if item[1] in keyList:
        targetList.append(item)
# print ("target",targetList)


import sqlite3 as SQL
from cttlib import *
import datetime
import argparse
import sys
from configparser import ConfigParser
import os
import getpass
from syslog import syslog

#syslog argv
logme = ' '.join(sys.argv)
syslog(logme)

check_nolocal()
con = SQL.connect('ctt.sqlite')
date = datetime.datetime.now().isoformat() #ISO8601
user = os.environ.get("SUDO_USER")
if user is None:
    user = getpass.getuser()	#if not run via sudo
updatedby = user
UserGroup = GetUserGroup(usersdict, user)
groupsList = GetGroups(usersdict, user)
checkdb(date)
config = ConfigParser()
config.read('ctt.ini')
defaults = config['DEFAULTS']
severity = defaults['severity']
issuestatus = defaults['issuestatus']
issuetype = defaults['issuetype']
assignedto = defaults['assignedto']
attach_location = defaults['attach_location']
cluster = defaults['cluster']
strict_node_match = defaults['strict_node_match'] #Only used when --open unless strict_node_match_auto is True. False is off, comma delimeted list of nodes for on
pbs_enforcement = defaults['pbs_enforcement'] #with False, will not resume or offline nodes in pbs

try: #??????
    if not sys.argv[1]:
        show_help()
except IndexError:  #??????
    show_help()

if '--auto' in sys.argv[1]:
    run_auto(date,severity,assignedto,updatedby,cluster,UserGroup)
    exit(0)

elif '--attach' in sys.argv[1]:
    # ./ctt.py --attach 1020 /tmp/ipmi_sdr_list.out
    import ntpath
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--attach', action='store', dest='attachment', nargs=2, required=True)
    args = parser.parse_args()

    if args.attachment[0] and args.attachment[1]:
        create_attachment(args.attachment[0],args.attachment[1],attach_location,date,updatedby)
        update_issue(args.attachment[0], 'updatedby', updatedby)
        update_issue(args.attachment[0], 'updatedtime', date)
        filename = ntpath.basename(args.attachment[1])
        log_history(args.attachment[0], date, updatedby, 'Attached file: %s/%s/%s.%s' % (attach_location, args.attachment[0], date[0:16], filename))
        comment_issue(args.attachment[0], date, updatedby, 'Attached file: %s/%s/%s.%s' % (attach_location, args.attachment[0], date[0:16], filename), UserGroup)
        view_tracker_update(args.attachment[0],UserGroup)
    exit(0)

elif '--list' in sys.argv[1]:
    # ./ctt.py --list           # Shows all open
    # ./ctt.py --list -s closed	# Options: open, closed, deleted
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--list', action='store_true', dest='listvalue', default=True, required=True)
    parser.add_argument('-s', action='store', dest='statusvalue', choices=('open', 'closed', 'deleted', 'all'), required=False)
    parser.add_argument('-v', action='store_true', dest='verbosevalue', default=False, required=False)
    parser.add_argument('-vv', action='store_true', dest='vverbosevalue', default=False, required=False)
    args = parser.parse_args()

    if not args.statusvalue:
        args.statusvalue = 'open'
    if args.verbosevalue is True:
        get_issues_v(args.statusvalue)
        exit(0)
    if args.vverbosevalue is True:
        get_issues_vv(args.statusvalue)
        exit(0)
    else:
        get_issues(args.statusvalue)
        exit(0)

elif '--show' in sys.argv[1]:   #We want to see deleted issues as well!!!, FIX
    # ./ctt.py --show 1045
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--show', action='store', dest='issuenumber', nargs=1, required=True)
    parser.add_argument('-d', action='store_true', default=False)
    args = parser.parse_args()

    if args.issuenumber[0]:
        get_issue_full(args.issuenumber[0])

    if args.d is True:
        get_history(args.issuenumber[0])

    view_tracker_update(args.issuenumber[0],UserGroup)

elif '--update' in sys.argv[1]:
    # ./ctt.py --update 1039 -s 1 -c cheyenne -n r1i1n1 -t 689725 -a casg
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--update', action='store', dest='issuenumber', nargs=1, required=True)
    parser.add_argument('-s','--severity', action='store', dest='severityvalue', choices=('1','2','3','4'), required=False)
    parser.add_argument('-c','--cluster', action='store', dest='clustervalue', required=False)
    parser.add_argument('-n','--node', action='store', dest='nodevalue', required=False)
    parser.add_argument('-t','--ticket', action='store', dest='ticketvalue', required=False)
    parser.add_argument('-a','--assign', action='store', dest='assignedtovalue', required=False)
    parser.add_argument('-i','--issuetitle', action='store', dest='issuetitlevalue', required=False)
    parser.add_argument('-d','--description', action='store', dest='descvalue', required=False)
    parser.add_argument('-x', '--type', action='store', dest='typevalue', choices=('h','h!', 's', 't', 'u', 'o'), required=False)
    args = parser.parse_args()

    issue_list = args.issuenumber[0].split(',')
    for cttissue in issue_list:

        if args.typevalue:
            try:
                if cttissue:
                    if args.typevalue == 'h!':
                        #print(cttissue)
                        add_siblings(cttissue,date,updatedby)
                        args.typevalue = 'h'
                    update_issue(cttissue, 'issuetype', args.typevalue)	# 1009 issuetype {hardware,software,test,unknown,other}
                    update_issue(cttissue, 'updatedby', updatedby)
                    update_issue(cttissue, 'updatedtime', date)
                    view_tracker_new(cttissue,UserGroup,viewnotices)
                    log_history(cttissue,date,updatedby,'updated issue type to: %s' % (args.typevalue))
            except IndexError:
                parser.print_help()

        if args.issuetitlevalue:
            test_arg_size(args.issuetitlevalue,what='issue title',maxchars=100)
            try:
                if cttissue:
                    update_issue(cttissue, 'issuetitle', args.issuetitlevalue)
                    update_issue(cttissue, 'updatedby', updatedby)
                    update_issue(cttissue, 'updatedtime', date)
                    view_tracker_new(cttissue,UserGroup,viewnotices)
                    log_history(cttissue,date,updatedby,'updated issue title to: %s' % (args.issuetitlevalue))
            except IndexError:
                parser.print_help()

        if args.descvalue:
            test_arg_size(args.descvalue,what='issue description',maxchars=4000)
            try:
                if cttissue:
                    update_issue(cttissue, 'issuedescription', args.descvalue)
                    update_issue(cttissue, 'updatedby', updatedby)
                    update_issue(cttissue, 'updatedtime', date)
                    view_tracker_new(cttissue,UserGroup,viewnotices)
                    log_history(cttissue,date,updatedby,'updated issue description to: %s' % (args.descvalue))
            except IndexError:
                parser.print_help()

        if args.severityvalue:
            try:
                if cttissue:
                    update_issue(cttissue, 'severity', args.severityvalue)
                    update_issue(cttissue, 'updatedby', updatedby)
                    update_issue(cttissue, 'updatedtime', date)
                    view_tracker_new(cttissue,UserGroup,viewnotices)
                    log_history(cttissue,date,updatedby,'updated issue severity to: %s' % (args.severityvalue))
            except IndexError:
                parser.print_help()

        if args.clustervalue:
            try:
                if cttissue:
                    update_issue(cttissue, 'cluster', args.clustervalue)
                    update_issue(cttissue, 'updatedby', updatedby)
                    update_issue(cttissue, 'updatedtime', date)
                    view_tracker_new(cttissue,UserGroup,viewnotices)
                    log_history(cttissue,date,updatedby,'updated cluster to: %s' % (args.clustervalue))
            except IndexError:
                parser.print_help()

        if args.nodevalue:
            try:
                if cttissue:
                    update_issue(cttissue, 'node', args.nodevalue)
                    update_issue(cttissue, 'updatedby', updatedby)
                    update_issue(cttissue, 'updatedtime', date)
                    view_tracker_new(cttissue,UserGroup,viewnotices)
                    log_history(cttissue,date,updatedby,'updated node to: %s' % (args.nodevalue))
            except IndexError:
                parser.print_help()

        if args.assignedtovalue in groupsList:
            try:
                if cttissue:
                    update_issue(cttissue, 'assignedto', args.assignedtovalue)
                    update_issue(cttissue, 'updatedby', updatedby)
                    update_issue(cttissue, 'updatedtime', date)
                    view_tracker_new(cttissue,UserGroup,viewnotices)
                    log_history(cttissue,date,updatedby,'assigned issue to: %s' % (args.assignedtovalue))
            except IndexError:
                parser.print_help()
        elif args.assignedtovalue != None:
            print("Assign to group \"%s\" is not a valid users group, Exiting!" % (args.assignedtovalue))

        if args.ticketvalue:
            try:
                if cttissue:
                    update_ticket(cttissue, args.ticketvalue)
                    update_issue(cttissue, 'updatedby', updatedby)
                    update_issue(cttissue, 'updatedtime', date)
                    view_tracker_new(cttissue,UserGroup,viewnotices)
                    log_history(cttissue,date,updatedby,'toggled ticket: %s' % (args.ticketvalue))
            except IndexError:
                parser.print_help()

elif '--comment' in sys.argv[1]:
    # ./ctt.py --comment 12390,12011 "Need an update"
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--comment', action='store', dest='comment', nargs=2, required=True)
    args = parser.parse_args()

    if args.comment[0] and args.comment[1]:
        issue_list = args.comment[0].split(',')
        for cttissue in issue_list:
            test_arg_size(args.comment[1],what='comment',maxchars=500)
            comment_issue(cttissue, date, updatedby, args.comment[1],UserGroup)
            update_issue(cttissue, 'updatedby', updatedby)
            update_issue(cttissue, 'updatedtime', date)
            log_history(cttissue, date, updatedby, 'commented issue with: %s' % (args.comment[1]))

elif '--delete' in sys.argv[1]:	#make where must be 'admin' to delete
    # ./ctt.py --delete 10101 "Duplicate issue"
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--delete', action='store', dest='deletevalue', nargs=2, required=True) #NEED TO FIX DELETE
    args = parser.parse_args()

    if args.deletevalue[0] and args.deletevalue[1]:
        test_arg_size(args.deletevalue[1],what='comment',maxchars=500)
        comment_issue(args.deletevalue[0], date, updatedby, args.deletevalue[1],UserGroup)
        delete_issue(args.deletevalue[0])
        update_issue(args.deletevalue[0], 'updatedby', updatedby)
        update_issue(args.deletevalue[0], 'updatedtime', date)
        log_history(args.deletevalue[0],date,updatedby,'deleted issue: %s' % (args.deletevalue[1]))

elif '--close' in sys.argv[1]:
    # ./ctt.py --close 1028,1044 "Issue resolved"
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--close', action='store', dest='closevalue', nargs=2, required=True)
    args = parser.parse_args()

    if args.closevalue[0] and args.closevalue[1]:
        issue_list = args.closevalue[0].split(',')
        for cttissue in issue_list:
            test_arg_size(args.closevalue[1],what='comment',maxchars=500)
            comment_issue(cttissue, date, updatedby, args.closevalue[1],UserGroup)
            update_issue(cttissue, 'updatedby', updatedby)
            update_issue(cttissue, 'updatedtime', date)
            close_issue(cttissue, date, updatedby)
            log_history(cttissue, date, updatedby, 'closed issue: %s' % (args.closevalue[1]))

elif '--reopen' in sys.argv[1]:
    # ./ctt.py --reopen 10282,10122 "Accidental close"
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--reopen', action='store', dest='reopenvalue', nargs=2, required=True)
    args = parser.parse_args()

    if args.reopenvalue[0] and args.reopenvalue[1]:
        issue_list = args.reopenvalue[0].split(',')
        for cttissue in issue_list:
            test_arg_size(args.reopenvalue[1],what='comment',maxchars=500)
            comment_issue(cttissue, date, updatedby, args.reopenvalue[1],UserGroup)
            update_issue(cttissue, 'updatedby', updatedby)
            update_issue(cttissue, 'updatedtime', date)
            update_issue(cttissue, 'status', 'open')
            log_history(cttissue, date, updatedby, 'reopened issue: %s' % (args.reopenvalue[1]))
            if pbs_enforcement == 'False':
                print("pbs_enforcement is False. Not draining nodes")
            else:
                pbs_drain(cttissue,date,updatedby,get_hostname(cttissue))

elif '--open' in sys.argv[1]:
    # ./ctt.py --open "Failed dimm on r1i1n1" "Description here" -c cheyenne -s 1 -n r1i1n1,r1i1n10 -a casg
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--open', action='store', dest='openvalue', nargs='+', required=True)
    parser.add_argument('-s','--severity', action='store', dest='severityvalue', required=False)
    parser.add_argument('-c','--cluster', action='store', dest='clustervalue', required=False)
    parser.add_argument('-n','--node', action='store', dest='nodevalue', required=True)
    parser.add_argument('-a','--assign', action='store', dest='assignedtovalue', required=False)
    parser.add_argument('-t', '--ticket', action='store', dest='ticketvalue', required=False)
    parser.add_argument('-x', '--type', action='store', dest='typevalue', choices=('h', 's', 't', 'u', 'o'), required=False)
    args = parser.parse_args()

    if strict_node_match is not False:
        if not (args.nodevalue in strict_node_match):
            print("Can not find %s in strict_node_match, Exiting!" % (args.nodevalue))
            exit()

    if args.assignedtovalue:
        assignedto = args.assignedtovalue
    if not args.ticketvalue:
        args.ticketvalue = '---'
    if not args.typevalue:
        args.typevalue = issuetype
    if not args.severityvalue:
        args.severityvalue = severity
    if not args.clustervalue:
        args.clustervalue = cluster

    if args.openvalue[0] and args.openvalue[1]:
        print(args.nodevalue)
        node_list = args.nodevalue.split(',')
        for node in node_list:
            test_arg_size(args.openvalue[0],what='issue title',maxchars=100)
            test_arg_size(args.openvalue[1],what='issue description',maxchars=4000)
            cttissue = new_issue(date, args.severityvalue, args.ticketvalue, 'open', \
                                 args.clustervalue, node, args.openvalue[0], \
                                 args.openvalue[1], assignedto, updatedby, \
                                 updatedby, args.typevalue, 'unknown', date,UserGroup)
            log_history(cttissue, date, updatedby, 'new issue')

elif '--help' in sys.argv[1] or '-h' in sys.argv[1]:
    show_help()

elif '--stats' in sys.argv[1]:
    from cttstats import *

    # ./ctt.py --stats -n casper15  # ./ctt.py --stats -c
    parser = argparse.ArgumentParser(add_help=False, description="Cluster Ticket Tracker Version 1.0.0")
    parser.add_argument('--stats', action='store_true', required=True)
    parser.add_argument('-n','--node', action='store', dest='nodevalue', required=False)
    parser.add_argument('-c','--counts', action='store_true', dest='countsvalue', required=False)
    args = parser.parse_args()

    if args.countsvalue:
        run_stats_counts()
        exit(0)

    if args.nodevalue:
        run_stats_node(args.nodevalue)
        exit(0)

else:
    show_help()


# boj 10844

# N 이 주어질 때 , 길이가 N인 계단 수가 총 몇 개 있는지 구하시오

# 입력 첫째 줄에 N이 주어진다. 1 =< N < 100

# 출력 첫째 줄에 정답을 1_000_000_000으로 나눈 나머지를 출력

MOD = 1_000_000_000

cache = [[0] * 10 for _ in range(101)]
for j in range(1, 10):
    cache[1][j] = 1

for i in range(2, 101):
    for j in range(10):
        if j > 0:
            cache[i][j] += cache[i - 1][j - 1]
            cache[i][j] %= MOD
        if j < 9:
            cache[i][j] += cache[i - 1][j + 1]
            cache[i][j] %= MOD

ans = 0
N = int(input())
for j in range(10):
    ans += cache[N][j]
    ans %= MOD

print(ans)


from app import db
from app.models import T111_FAMILLE_CONTRAT_DIVALTO
import os
import json

def initialisation_T111():
    print('\033[34m * Initialisation table T101 - FAMILLE CONTRAT...\033[0m')
    try:
        data = load_data_from_json()
        insert_data_to_db(data)
        print('\033[32m *** TABLE T101 synchronisée ***\033[0m')
    except Exception as error:  # Ajout du type d'exception et utilisation de 'Exception'
        print('\033[91m ** Erreur lors de l\'initialisation de la table T101 - FAMILLE CONTRAT:\033[0m', error)

def load_data_from_json():
    file_path = "../../ressources/input/EQUIV_ISA_DIVALTO/T119_Categorie_client.json"
    basedir = os.path.abspath(os.path.dirname(__file__))
    file_path = os.path.join(basedir, '../../ressources/input/EQUIV_ISA_DIVALTO/T101_FAMILLE_CONTRAT.json')
    with open(file_path, 'r') as file:
        data = json.load(file)
    return data

def insert_data_to_db(data):
    for item in data:
        new_entry = T111_FAMILLE_CONTRAT_DIVALTO(
            DOSSIER = item['DOSSIER'],
            FAMILLECONTRAT = item['FAMILLECONTRAT'],
            EQUIV_ISFACT_CodeTypeCONTRAT = item['EQUIV_ISFACT_CodeTypeCONTRAT'],
            NUMERONOTE = item['NUMERONOTE'],
            LIBELLE_TABLE_FAMILLECONTRAT = item['LIBELLE_TABLE_FAMILLECONTRAT'],
            CONTRATTYP = item['CONTRATTYP'],
            DATEFINVALID = item['DATEFINVALID'],
            STRUCTUREREFERENCECONTRAT = item['STRUCTUREREFERENCECONTRAT'],
            CRMUPDATEDH = item['CRMUPDATEDH'],
        )
        db.session.add(new_entry)

    db.session.commit()


import numpy as np
from sklearn.metrics import confusion_matrix, mean_squared_error
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import itertools
import code
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc, precision_recall_fscore_support
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
from sklearn.decomposition import PCA
from scipy import interp
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score, StratifiedKFold, train_test_split
from itertools import cycle
import math
import numpy as Math
from numpy import genfromtxt

def plotHistogram(x,xlabel,ylabel,title):
    plt.hist(x, normed=False, bins=10)
    mean = round(np.mean(x))
    min = np.min(x)
    max = np.max(x)
    std = np.round(np.std(x),3)
    plt.text(2000,50, "Mean="+str(mean) + "\n" + "Min="+str(min) + "\n" + "Max="+str(max) + "\n" + "Std="+str(std))
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    plt.show()

def plot2d(X, y, title):
	fig = plt.figure(figsize=(6,6))
	fig.suptitle(title, fontsize=20)
	ax = fig.add_subplot(111)
	ax.set_xlabel("n1",fontsize=12)
	ax.set_ylabel("n2",fontsize=12)
	ax.grid(True,linestyle='-',color='0.75')
	colors = ['r','g','b','black','white','c','m','y','#CCB974','#77BEDB']

	for i in np.unique(y):
		ax.scatter(X[np.where([y==i])[1], 0], X[np.where([y==i])[1], 1], c=colors[i-1], marker='o')

	ax.set_xlabel('n1')
	ax.set_ylabel('n2')

	plt.show()

def load_csv(file_path, delimiter):
    X = genfromtxt(file_path, delimiter=delimiter)
    return X

def round_keep_sum(cm, decimals=2):
	rcm = np.round(cm, decimals)
	for i in range(rcm.shape[0]):
		column = rcm[i,:]
		error = 1 - np.sum(column)
		sr = 10**(-decimals)
		n = int(round(error / sr))
		for _,j in sorted(((cm[i,j] - rcm[i,j], j) for j in range(cm.shape[1])), reverse=n>0)[:abs(n)]:
			rcm[i,j] += math.copysign(0.01, n)
	return rcm

# def plotNiceConfusionMatrix(y_test, y_pred, class_names):
# 	# Compute confusion matrix
# 	cnf_matrix = confusion_matrix(y_test, y_pred)
# 	np.set_printoptions(precision=2)
#
# 	# Plot non-normalized confusion matrix
# 	fig = plt.figure()
# 	conf_M(cnf_matrix, classes=class_names, title='Confusion matrix, without normalization')
# 	fig.set_tight_layout(True)
#
# 	plt.show()

def plotBothConfusionMatrices(y_test, y_pred, class_names):
	# Compute confusion matrix
	cnf_matrix = confusion_matrix(y_test, y_pred)
	# Plot non-normalized confusion matrix
	fig = plt.figure()
	conf_M2(cnf_matrix, classes=class_names, title='Confusion matrix')
	fig.set_tight_layout(True)
	# plt.show()
	return fig

# This function loads the data into X and y,
# outputs the feature names, the label dictionary, m and n

def loadnumpy(filename):
	array = np.load(filename)
	return array

def addOffset(X):
	X = np.c_[np.ones((X.shape[0],1)), X]
	return X

def normalize(DATA):
	for i in range(DATA.shape[1]):
		DATA[:,i] = (DATA[:,i] - np.mean(DATA[:,i]))/(np.max(DATA[:,i])-np.min(DATA[:,i])+.001)
	return DATA

def rms(y_true, y_pred):
	return mean_squared_error(y_true, y_pred, sample_weight=None, multioutput='uniform_average')

# def plotConfusionMatrix(y, pred):
# 	n_labels = len(np.unique(y))
# 	matrix = np.zeros([n_labels+1,n_labels+1])
# 	matrix[0,1:] = np.unique(y)
# 	matrix[1:,0] = np.unique(y)
# 	matrix[1:,1:] = confusion_matrix(y.astype(int), pred.astype(int))
# 	print(matrix)

def round_keep_sum(cm, decimals=2):
	rcm = np.round(cm, decimals)
	for i in range(rcm.shape[0]):
		column = rcm[i,:]
		error = 1 - np.sum(column)
		sr = 10**(-decimals)
		n = int(round(error / sr))
		for _,j in sorted(((cm[i,j] - rcm[i,j], j) for j in range(cm.shape[1])), reverse=n>0)[:abs(n)]:
			rcm[i,j] += math.copysign(0.01, n)
	return rcm

def conf_M(cm):
    cmap=plt.cm.Blues
    classes = ["mytotic", "healthy"]
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)
    print('Confusion matrix')
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j], horizontalalignment="center", color="black")
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()


#Uses python3

import sys

sys.setrecursionlimit(200000)

def dfs(nodes, node):
    node["visited"] = True
    for neighbour_index in node["neighbours"]:
        neighbour = nodes[neighbour_index]
        if not neighbour["visited"]:
            dfs(nodes, neighbour)

def number_of_strongly_connected_components(adj):
    result = 0
    #write your code here
    nodes = list(({ "visited": False, "neighbours": neighbours, "index": index } for index, neighbours in enumerate(adj)))
    for node in nodes:
        if not node["visited"]:
            result += 1
            dfs(nodes, node)

    return result

if __name__ == '__main__':
    input = sys.stdin.read()
    data = list(map(int, input.split()))
    n, m = data[0:2]
    data = data[2:]
    edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
    adj = [[] for _ in range(n)]
    for (a, b) in edges:
        adj[a - 1].append(b - 1)
    print(number_of_strongly_connected_components(adj))


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^login/$', views.userLogin, name='login'),
    url(r'^logout/$', views.userLogout, name='logout'),
    url(r'^register/$', views.userRegister, name='signup'),
    url(r'^profile/$', views.userProfile, name='userprofile'),
    url(r'^editprofile/$', views.userProfileEdit, name='editprofile'),
    url(r'^deleteaccount/$', views.deleteUserAccount, name='deleteaccount'),
]


from pathlib import Path
import re
import os

files_path = Path('/Users/natal/Documents/Cakap Intermediate Business English')

for file in files_path.iterdir():
    directory = file.parent
    extention = file.suffix

    name = file.stem

    folder_name = re.split(r'\.', name)[0]
    new_path = files_path.joinpath(folder_name)

    if not new_path.exists():
        new_path.mkdir()

    new_file_path = new_path.joinpath(f'{name}{extention}')
    file.replace(new_file_path)


# -*- coding: utf-8 -*-
from datetime import datetime
from time import sleep
from typing import Any
from airflow.exceptions import AirflowException
from airflow.models.baseoperator import BaseOperator
from airflow.providers.apache.livy.hooks.livy import BatchState, LivyHook

class SparkSubmitOperator(BaseOperator):
    """
    Livy Rest Api를 통해 pyspark script를 batch형식의 Spark Job을 driver에 전달한다.
    기존 LivyOperator에서 Customize 한 내용
        - spark job 종료시 바로 batch 정보 삭제하는 함수 삭제 안하도록 수정
        - 단시간 안에 Retry할때 배치 이름 중복되는 현상 방지하는 로직 추가
        - Spark Config는 Spark Script안에서 정의하도록 Operator Parameter 제거

    * Parameters *
    file_name: Spark Cluster 내에 위치한 파일 위치
    livy_conn_id: Airflow Spark Driver Node Connection
    polling_interval: Livy Server에서 Spark Job의 Batch State 확인 시간
    delete_session: Spark Job 종료후 세션 정보 삭제 여부
    """

    def __init__(
        self,
        file_name: str,
        livy_conn_id: str,
        polling_interval: int = 15,
        delete_session: bool = False,
        **kwargs: Any,
    ) -> None:

        self.file_name = file_name
        self._livy_conn_id = livy_conn_id
        self._polling_interval = polling_interval
        self.delete_session = delete_session
        self._livy_hook: LivyHook = None
        super().__init__(**kwargs)

    def get_hook(self) -> LivyHook:
        self._livy_hook = LivyHook(livy_conn_id=self._livy_conn_id)
        return self._livy_hook

    def execute(self, context) -> Any:

        # 배치 이름이 겹치는 오류 방지
        post_fix = datetime.now().strftime("%Y%m%d-%H%M%S")

        batch_name = f"<{self.file_name}>-spark_job-{post_fix}"

        remote_file_path = f"/home/ec2-user/spark-data/{self.file_name}"

        livy_hook = self.get_hook()

        self._batch_id = livy_hook.post_batch(
            name=batch_name, file=f"file:{remote_file_path}"
        )

        # 배치 성공여부 확인 후 종료
        self.poll_for_termination(self._batch_id)

        # 세션 삭제
        if self.delete_session and self._batch_id is not None:
            livy_hook.delete_batch(self._batch_id)

    def poll_for_termination(self, batch_id) -> None:
        """spark job의 성공여부를 체크 후 세션을 종료한다"""
        livy_hook = self.get_hook()
        state = livy_hook.get_batch_state(batch_id)

        while state not in livy_hook.TERMINAL_STATES:
            self.log.debug(
                f"Batch with id {batch_id} is in state: {state.value}"
            )

            # status check(기본 15초)
            sleep(self._polling_interval)

            state = livy_hook.get_batch_state(batch_id)

        self.log.info(
            f"Batch with id {batch_id} terminated with state: {state.value}"
        )
        livy_hook.dump_batch_logs(batch_id)

        if state != BatchState.SUCCESS:
            raise AirflowException(f"Batch {batch_id} did not succeed")


# -*- coding: utf-8 -*-

from sklearn.datasets import fetch_openml
mnist = fetch_openml('mnist_784', version=1, cache=True)

X = mnist.data/255
y = mnist.target

import matplotlib.pyplot as plt
plt.imshow(X[0].reshape(28,28), cmap='gray')
plt.show()
print("이미지 레이블 : {}".format(y[0]))

import torch
from torch.utils.data import TensorDataset, DataLoader
from sklearn.model_selection import train_test_split

X_train,X_test, y_train,y_test = train_test_split(X,y, test_size=1/7, random_state=0)
X_train = torch.Tensor(X_train)
X_test = torch.Tensor(X_test)
y_train = torch.LongTensor(list(map(int, y_train)))
y_test = torch.LongTensor(list(map(int, y_test)))

ds_train = TensorDataset(X_train, y_train)
ds_test = TensorDataset(X_test, y_test)

loader_train = DataLoader(ds_train, batch_size = 64, shuffle=True)
loader_test = DataLoader(ds_test, batch_size=64, shuffle=False)

from torch import nn
model =  nn.Sequential()
model.add_module('fc1', nn.Linear(28*28*1, 100))
model.add_module('relu1', nn.ReLU())
model.add_module('fc2', nn.Linear(100,100))
model.add_module('relu2', nn.ReLU())
model.add_module('fc3', nn.Linear(100,100))

from torch import optim
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)

def train(epoch):
    model.train()
    for data, targets in loader_train:
        optimizer.zero_grad()
        outputs =  model(data)
        loss = loss_fn(outputs, targets)
        loss.backward()
        optimizer.step()
    print('에 포크 {}: 완료'.format(epoch))

def test(head):
    model.eval()
    correct = 0
    with torch.no_grad():
        for data, targets in loader_test:
            outputs =  model(data)
            _, predicted = torch.max(outputs.data,1)
            correct += predicted.eq(targets.data.wiew_as(predicted)).sum()
        data_num = len(loader_test.dataset)
        print('{}정확도: {}/{}({:.0ㄹ}%)'.format(head, correct, data_num, 100.*correct/data_num))

test('시작')
for epoch in range(3):
    train(epoch)
    test('학습중')

test('학습후')

index = 10
model.eval()
data = X_test[index]
output = model(data)
print('{}번째 학습데이터의 테스트 결과 : {}'.format(index,output))
_,  predicted = torch.max(output.data,0)
print('{}번째 데이터의 예측 : {}'.format(index, predicted))
X_test_show = (X_test[index]).numpy()
plt.imshow(X_test_show.reshape(28,28), cmap='gray')
print(' 실제 레이블: {}'.format(y_test[index]))


__author__ = 'roir'
from rest_framework import serializers
from GameUser import GameUserSerializer
from jsonfield import JSONField

class ShassAro():

    def __init__(self, goals, participants, shassaro_ip, docker_server_ip, docker_id, docker_name):
        self.goals = goals
        self.participants = participants
        self.shassaro_ip = shassaro_ip
        self.docker_server_ip = docker_server_ip
        self.docker_id = docker_id
        self.docker_name = docker_name

class ListFieldSerializer(serializers.ListField):
    child = serializers.CharField()

class ShassaroSerializer(serializers.Serializer):
        goals = ListFieldSerializer()
        participants = GameUserSerializer()
        shassaro_ip = serializers.CharField()
        docker_server_ip = serializers.CharField()
        docker_id = serializers.CharField()
        docker_name = serializers.CharField()