"""
RECONSTRUCT multiples files (of pairs) of pulses (at different separations)
AND (optionally) calibrate energies AND (optionally) calculate Energy
resolutions (FWHM)

python recon_resol.py

1) reconstruct energies
2) (optionally) calibrate energies IF input gain scale coefficientes
    are provided
3) (optionally) produce json files with fwhm values pre/post calibration

!!!!!!! Things to review every time it is run (they can change):
        =======================================================
        ** Check resultsDir (nodetSP in case secondaries are not detected,
                           gainScale in case results are for gain scale curves)

        ** SINCE NEWSIMULATIONS (Feb2018): library is always the jitter one
        although applied to non-jitter simulations(bagplots)
"""

# ----IMPORT MODULES --------------
from __future__ import print_function
import os
import math
import shlex
import shutil
# import sys
import tempfile
import json
import sixtevars
from astropy.io import fits
from subprocess import check_call
from reconstruct import reconstruct
from convertEnergies import convertEnergies
import xml.etree.ElementTree as ET

# ----GLOBAL VARIABLES -------------
cwd = os.getcwd()
tmpDir = tempfile.mkdtemp()
print(tmpDir)
# input("stop here")
os.environ["PFILES"] = tmpDir + ":" + os.environ["PFILES"]
os.environ["HEADASNOQUERY"] = ""
os.environ["HEADASPROMPT"] = "/dev/null/"

#
# --------- Read input parameters and PROCESS simulations -----------------
#
if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
            description='Reconstruct (and calibrate) (and get ener resol)',
            prog='recon_resol')

    parser.add_argument('--pixName', required=True,
                        help='Extension name in the FITS pixel definition file\
                        (SPA*, LPA1*, LPA2*, LPA3*)')
    parser.add_argument('--labelLib', required=True,
                        help='Label identifying the library (monolib,\
                        multilib, multilibOF, fixedlib, fixedlib2,...)')
    parser.add_argument('--libTmpl', default='LONG',
                        choices=['SHORT', 'LONG'],
                        help='Label identifying the library for the templates:\
                        SHORT or LONG')
    parser.add_argument('--samprate', default="",
                        choices=['', 'samprate2', 'samprate4'],
                        help="baseline, half_baseline, quarter baseline")
    parser.add_argument('--jitter', default="",
                        choices=['', 'jitter', 'jitter_M82_040'],
                        help="no jitter, jitter, M82_040")
    parser.add_argument('--noise', default="",
                        choices=['', 'nonoise'],
                        help="noisy, nonoise")
    parser.add_argument('--decimation', type=int, default=1,
                        help='xifusim decimation factor')
    parser.add_argument('--monoEnergy1', required=True,
                        help='Monochromatic energy (keV) of\
                        input primary simulated pulses')
    parser.add_argument('--monoEnergy2', default="0",
                        help='Monochromatic energy (keV) of\
                        input secondary simulated pulse')
    parser.add_argument('--reconMethod', default='OPTFILT',
                        help='Energy reconstruction Method (OPTFILT,\
                        OPTFILTNMnnnn, WEIGHT, WEIGHTN, I2R, I2RNMnnnn,\
                        I2RALL, I2RNOL, I2RFITTED)')
    parser.add_argument('--filterLength', type=int, default=0,
                        help='filter length for reconstruction')
    parser.add_argument('--nsamples', type=int,
                        help='noise length samples', required=True)
    parser.add_argument('--pulseLength', type=int, required=True,
                        help='pulse length for reconstruction')
    parser.add_argument('--nSimPulses', type=int, required=True,
                        help='pulses in simulations (to locate filenames)')
    parser.add_argument('--nSimPulsesLib', type=int, required=True,
                        help='pulses used to build the library')
    parser.add_argument('--fdomain', default='T',
                        choices=['F', 'T'],
                        help='Optimal Filtering domain (F(req) or T(ime))\
                        [default %(default)s]')
    parser.add_argument('--tstartPulse1', type=int, default=0,
                        help='Start sample for first pulse\
                        [default %(default)s]')
    parser.add_argument('--tstartPulse2', type=int, default=0,
                        help='Start sample for second pulse\
                        [default %(default)s]')
    parser.add_argument('--coeffsFile', default='',
                        help='file with polynomial fit coefficients from\
                        R script polyfit2bias.R')
    parser.add_argument('--detMethod', default='AD',
                        choices=['AD', 'STC'])
    parser.add_argument('--detSP', default=1, type=int,
                        help='are Secondaries to be detected (1:yes; 0:no)')
    parser.add_argument('--resultsDir', default="",
                        help='directory for resulting evt and json files\
                        (from ..../PAIRS/eresol+pixName) tipically\
                        "nodetSP", "detSP" or "gainScale" or ""')
    parser.add_argument('--separations', nargs='+',
                        help='spaced list of separations between\
                        Prim & Sec pulses', default="")
    parser.add_argument('--bbfb', default="",
                        choices=['', 'bbfb', 'bbfb_NewPar', 'bbfb_040',
                                 'bbfb_040_ct', 'fll'], help="dobbfb=n, dobbfb=y")
    parser.add_argument('--Lc', default="",
                        help="Inductance over critical value")
    parser.add_argument('--preBuffer', default=0, type=int,
                        help="preBuffer value for optimal filters")
    parser.add_argument('--Ifit', default=0, type=float,
                        help="Fitted constant for the I2RFITTED expression")
    parser.add_argument('--B0', default=0, type=int,
                        help="B0 (baseline subtraction; B0>0) of \
                        F0 (B0=0) optimal filter")
    parser.add_argument('--LbT', default="0",
                        help="Time (s) to average baseline")
    parser.add_argument('--Sum0Filt', default=0, type=int,
                        help="Optimal Filter SUM shoud be 0? (0=NO; 1=YES)")
    parser.add_argument('--lags', default=1, type=int,
                        help="Do parabola fit if lags=1")
    parser.add_argument('--ct', default="",
                        choices=['', 'ct', 'fit'],
                        help="Filters central part replaced by constant? or\
                        filters derived from largest 8192?")
    inargs = parser.parse_args()

    # print("array=",inargs.array)

    # rename input parameters
    pixName = inargs.pixName
    labelLib = inargs.labelLib
    samprate = inargs.samprate
    jitter = inargs.jitter
    noise = inargs.noise
    bbfb = inargs.bbfb
    Lc = inargs.Lc
    dcmt = inargs.decimation
    mono1EkeV = inargs.monoEnergy1
    mono2EkeV = inargs.monoEnergy2
    reconMethod = inargs.reconMethod
    filterLength = inargs.filterLength
    nsamples = inargs.nsamples
    pulseLength = inargs.pulseLength
    nSimPulses = inargs.nSimPulses
    fdomain = inargs.fdomain
    detMethod = inargs.detMethod
    tstartPulse1 = inargs.tstartPulse1
    tstartPulse2 = inargs.tstartPulse2
    nSimPulsesLib = inargs.nSimPulsesLib
    coeffsFile = inargs.coeffsFile
    libTmpl = inargs.libTmpl
    resultsDir = inargs.resultsDir
    sepsStr = inargs.separations
    detSP = inargs.detSP
    pB = inargs.preBuffer
    Ifit = inargs.Ifit
    LbT = inargs.LbT
    s0 = inargs.Sum0Filt
    lags = inargs.lags
    filterct = inargs.ct
    B0 = inargs.B0

    # general definitions
    EURECAdir = "/dataj6/ceballos/INSTRUMEN/EURECA/"
    ERESOLdir = EURECAdir + "/ERESOL/"
    xifusim = "xifusim" + pixName
    simDir = ERESOLdir + "PAIRS/" + xifusim
    resultsDir = resultsDir.rstrip('\\')
    resultsDir = resultsDir.lstrip('\\')
    if ("gainScale" in resultsDir) or ("base" in resultsDir):
        simDir += "/" + resultsDir
    outDir = ERESOLdir + "PAIRS/eresol" + pixName + "/" + resultsDir
    classAries = ["primaries", "secondaries", "all"]
    if tstartPulse2 == 0:
        classAries = ["all"]

    idxsmp = sixtevars.sampids.index(samprate)
    separation = sixtevars.separations[idxsmp]
    if sepsStr == "":
        sepsStr = [separation]

    # read grading info
    XMLtree = ET.parse(sixtevars.XMLsixte)
    if bbfb == "fll":
        XMLtree = ET.parse(sixtevars.XMLfll)
    XMLroot = XMLtree.getroot()
    for key in XMLroot.findall('grading'):
        num = key.get('num')
        if num == "1":
            invalid = key.get('pre')
            Hres = key.get('post')
            factor = sixtevars.sampfreqs[idxsmp]/sixtevars.sampfreqs[0]
            Hres = int(int(Hres) * factor)
            invalid = int(int(invalid) * factor)

    # to be able to use shorter filters or long filter shortened in FWHM curve
    Hres = min(filterLength, pulseLength)

    print("Hres=", Hres)
    print("filterLength=", filterLength)
    print("pulseLength=", pulseLength)

    # 1) Reconstruct energies
    # ------------------------
    smprtStr, jitterStr, noiseStr, bbfbStr, LcStr, pBStr, IfitStr, LbTStr, \
        s0Str, lagsStr, ctStr, B0str, evtFile, eresolFile = \
        reconstruct(pixName, labelLib, samprate, jitter, dcmt,
                          noise, bbfb, Lc, mono1EkeV, mono2EkeV, reconMethod,
                          filterLength, nsamples, pulseLength, nSimPulses,
                          fdomain, detMethod, tstartPulse1, tstartPulse2,
                          nSimPulsesLib, coeffsFile, libTmpl, simDir, outDir,
                          detSP, pB, Ifit, LbT, s0, lags, filterct, B0, sepsStr)

    # 2) Calibrate (AND/OR) extract Energy resolution info to .json files
    # --------------------------------------------------------------------
    # ---- if calibration parameters are provided:
    #              calculate corrected energies
    #              calculate FWHM, BIAS (calib)
    # ---- if not, calculate only FWMH and BIAS (recons)

    #  define/initialize structure to save all output data

    data = []  # list of dictionaries (one per pulses separation)
    for sep12 in sepsStr:
        dictSep = dict()
        dictBiasErecons = dict()
        dictBiasEreal = dict()
        dictFwhmErecons = dict()
        dictFwhmEreal = dict()
        dictFwhmErealErr = dict()

        print("=============================================")
        print("EXTRACTING FWHMs.........................")
        print("Working in:", outDir)
        print("Setting evtFile: ", evtFile)
        print("Setting eresolFile: ", eresolFile)
        print("=============================================")

        # --------------------------------------------------------------
        # EVENT file processing to calculate FWHM (only for Hres pulses)
        # ---------------------------------------------------------------
        rootEvt = os.path.splitext(evtFile)[0]

        for aries in classAries:  # PRIMARIES / SECONDARIES / ALL
            print("Working with:", aries, "\n")
            if "aries" in aries:  # PRIMARIES // SECONDARIES
                evt = rootEvt + "_" + aries + ".fits"
                if os.path.isfile(evt):
                    os.remove(evt)
            elif aries == "all":
                # evt = evtFile
                evt = rootEvt + "_HR.fits"

            # use only rows with GRADE1==Hres && GRADE2>invalid (Hres pulses)
            try:
                monoEeV = float(mono1EkeV) * 1000.
                if aries == "primaries":
                    comm = "fselect infile=" + evtFile + " outfile=" + evt + \
                           " expr='#ROW%2!=0 && GRADE1==" + str(Hres) +\
                           " && GRADE2>" + str(invalid) + "' clobber=yes"
                elif aries == "secondaries":
                    comm = "fselect infile=" + evtFile + " outfile=" + evt + \
                           " expr='#ROW%2==0 && GRADE1==" + str(Hres) +\
                           " && GRADE2>" + str(invalid) + "' clobber=yes"
                    monoEeV = float(mono2EkeV) * 1000.
                else:
                    # comm = "fselect infile=" + evtFile + " outfile=" + evt +\
                    #       " expr='GRADE1==" + str(Hres) + \
                    #       " && GRADE2>" + str(invalid) + "' clobber=yes"
                    comm = "fselect infile=" + evtFile + " outfile=" + evt +\
                           " expr='GRADE1>=" + str(Hres) + \
                           " && GRADE2>=" + str(Hres) + "' clobber=yes"
                print("Running:", comm)
                args = shlex.split(comm)
                check_call(args, stdout=open(os.devnull, 'wb'))

            except RuntimeError:
                print("Error selecting PRIM/SEC events in evtfile ", evt)
                print(comm)
                os.chdir(cwd)
                shutil.rmtree(tmpDir)
                raise

            # FWHM & BIAS for Erecons
            # read Erecons (SIGNAL) column in numpy array (in keV)
            fpre = fits.open(evt, memmap=True)
            nrows = fpre[1].header["NAXIS2"]
            assert nrows > 0, "Empty evt file (%s): nrows=0 " % evt
            ftab = fpre[1].data
            SIGNALmean = ftab['SIGNAL'].mean()
            SIGNALsigma = ftab['SIGNAL'].std()
            fpre.close()
            del fpre[1].data

            fwhmEreal = 0
            fwhmEreal_err = 0
            biasEreal = 0

            print("evt, SIGNALsigma=", evt, SIGNALsigma)

            fwhm = SIGNALsigma * 2.35 * 1000.
            print("evt, fwhm=", evt, fwhm)

            # FWHM for reconstructed events in eV:
            fwhmErecons = '{0:0.5f}'.format(fwhm)
            # EBIAS = <Erecons> - monoEeV
            bias = SIGNALmean * 1000. - monoEeV
            biasErecons = '{0:0.5f}'.format(bias)
            # print("SIGNALmean=", SIGNALmean)
            # print("monoEeV=", monoEeV)
            # print("biasErecons=", biasErecons, "\n")

            # calculate calibrated energies if polyfit coeffs are provided and
            # previous fwhm is not NaN (some NULL Eners)
            # FWHM only calculated for those pulses reconstructed with HRes
            # if any(a != 0 for a in coeffs) and not math.isnan(fwhm):

            if coeffsFile and not math.isnan(fwhm):
                print("=============================================")
                print("CALIBRATING ENERGIES.........................")
                print("=============================================")

                with open(coeffsFile, "rt") as f:
                    fileCont = f.read()   # JSON file
                    if 'surface' in fileCont:
                        ftype = "surface"
                    elif fileCont[0] == '{':
                        ftype = 'json'
                    else:
                        ftype = 'poly'

                if ftype == 'poly':
                    evtcalib = evt.replace(".fits", ".calib1D")
                    eresolFile = eresolFile.replace(".json", ".json1D")
                elif ftype == 'surface':
                    evtcalib = evt.replace(".fits", ".calib2D")
                    eresolFile = eresolFile.replace(".json", ".json2D")
                elif ftype == 'json':
                    evtcalib = evt.replace(".fits", ".calibItr")
                    eresolFile = eresolFile.replace(".json", ".jsonItr")
                else:
                    raise ValueError("Incorrect Coeffs file type")

                # locate coefficients in coeffs table
                # ------------------------------------
                alias = ("pL" + str(pulseLength) + "_" + detMethod + "_" +
                         fdomain + "_" + labelLib + "_" +
                         reconMethod + str(filterLength) + pBStr + IfitStr + LbTStr +
                         smprtStr + jitterStr + noiseStr + bbfbStr +
                         LcStr + s0Str + lagsStr + ctStr)
                # alias = ("pL" + str(pulseLength) + "_" + detMethod + "_" +
                #         fdomain + "_" + labelLib + "_" +
                #         reconMethod + str(filterLength) + pBStr + IfitStr +
                #         smprtStr + jitterStr + noiseStr + bbfbStr +
                #         LcStr + s0Str + "_base100")
                if "NM" in reconMethod:
                    alias = ("pL" + str(pulseLength) + "_" + detMethod + "_" +
                             fdomain + "_" + labelLib + "_" +
                             reconMethod.split("NM")[0] + str(filterLength) +
                             "NM" + reconMethod.split("NM")[1] + LbTStr +
                             smprtStr + jitterStr + noiseStr + bbfbStr + LcStr)
                # unchecked option...
                # if 'fixedlib' in labelLib and 'OF' not in labelLib:
                #    alias = (detMethod + "_" + labelLib + "OF_" + "_" +
                #             reconMethod + str(pulseLength) + smprtStr +
                #             jitterStr + noiseStr + bbfbStr)
                print("Using alias=", alias)
                convertEnergies(evt, evtcalib, coeffsFile, alias)

                fcal = fits.open(evtcalib, memmap=True)
                nrows = fcal[1].header["NAXIS2"]
                assert nrows > 0, "Empty file (%s): nrows=0 " % evtcalib

                fcaltab = fcal[1].data
                ErealKeVmean = fcaltab['SIGNAL'].mean()
                ErealKeVsigma = fcaltab['SIGNAL'].std()
                fcal.close()
                del fcal[1].data

                print("=============================================")
                print("EXTRACTING corrected FWHMs...................")
                print("=============================================")
                print("Output eresolFile: ", eresolFile, "\n")

                fwhm = ErealKeVsigma * 2.35 * 1000.
                fwhm_err = fwhm / math.sqrt(2 * nrows - 2)
                bias = ErealKeVmean * 1000. - monoEeV
                # FWHM for reconstructed PRIMARIES in eV:
                fwhmEreal = '{0:0.5f}'.format(fwhm)
                fwhmEreal_err = '{0:0.5f}'.format(fwhm_err)
                biasEreal = '{0:0.5f}'.format(bias)
                # print("bias=", bias, "\n")
                # print("...biasEreal=", biasEreal, "\n")

            # write FWHM, BIAS values to dictionary for PRIM/SEC/ALL
            dictFwhmErecons[aries] = fwhmErecons
            dictFwhmEreal[aries] = fwhmEreal
            dictFwhmErealErr[aries] = fwhmEreal_err
            dictBiasErecons[aries] = biasErecons
            dictBiasEreal[aries] = biasEreal
            # END of PRIM & SEC & ALL

        # write data for given separation to a dictionary
        dictSep["separation"] = sep12
        dictSep["fwhmErecons"] = dictFwhmErecons
        dictSep["biasErecons"] = dictBiasErecons
        dictSep["fwhmEreal"] = dictFwhmEreal
        dictSep["biasEreal"] = dictBiasEreal
        dictSep["fwhmEreal_err"] = dictFwhmErealErr

        # save dictionary to list of dictionaries "data"
        data.append(dictSep)

    # Dump total data to JSON file
    feresol = open(eresolFile, 'w')

    json.dump(obj=data, fp=feresol, sort_keys=True)
    feresol.close()
    os.chdir(cwd)
    shutil.rmtree(tmpDir)


#install_twisted_rector must be called before importing the reactor
from kivy.support import install_twisted_reactor
install_twisted_reactor()

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.core.audio import SoundLoader

from twisted.internet import reactor, protocol

import json

Builder.load_file('./main.kv')

connection = None
disconnect_pointer = None
current_screen = None
username = None

def disconnect():
    global connection
    global disconnect_pointer
    if disconnect_pointer is not None:
        disconnect_pointer.disconnect()
        connection = None

def send_message(msg):
     if msg and connection:
        connection.write(str(msg))

def get_message(data):
    if data:
        #current_screen.get_message(data)
        msgs = data.split(",")
        for msg in msgs:
            if msg == "":
                continue
            msg=json.loads(msg)
            current_screen.get_message(msg["data"])

class LoginScreen(Screen):

    def on_enter(self):
        self.ids.message.text = ""
        global current_screen
        current_screen = self
        global connection
        if connection is None:
            self.connect()

    def connect(self):
        global disconnect_pointer
        self.print_message("connecting to server")
        disconnect_pointer = reactor.connectTCP('localhost', 10000, EchoFactory(self))

    def on_connection(self, _connection):
        global connection
        self.print_message("connected succesfully!")
        connection = _connection

    def login(self, uname, password):
        global username
        username = uname
        msg = {"u":uname,
               "p":password}
        send_message(json.dumps(msg))

    def get_message(self, msg):
        if msg == "OK":
            sm.current = "Main"
        else:
            self.print_message(msg)

    def print_message(self, msg):
        if msg == None:
            self.ids.message.text +="msg is none \n"
            return
        self.ids.message.text += msg + "\n"

class MainScreen(Screen):
    fromx = None
    fromy = None

    def on_enter(self):
        self.ids.message.text = ""
        global current_screen
        current_screen = self
        global username
        self.print_message("Welcome, "+username)

    def get_message(self, msg):
        self.print_message("playing: "+msg)
        sound = SoundLoader.load("audio/"+msg)
        if sound:
            #print("Sound found at %s" % sound.source)
            #print("Sound is %.3f seconds" % sound.length)
            sound.play()

    def print_message(self, msg):
        self.ids.message.text += msg + "\n"

    def on_touch_down(self, touch):
        if touch.x < 20 and touch.y < 20:
            send_message("logout")
            disconnect()
            sm.current = "Login"
        else:
            self.fromx = touch.x
            self.fromy = touch.y

    def on_touch_up(self, touch):
        xdiff = self.fromx-touch.x
        ydiff = self.fromy-touch.y
        walkdir = None
        maxVar = 30
        minDist = 50
        if(-maxVar < xdiff < maxVar):
            if(ydiff > minDist):
                walkdir ="down"
            elif(ydiff < -minDist):
                walkdir ="up"
        elif(-maxVar < ydiff < maxVar):
            if(xdiff > minDist):
                walkdir = "left"
            elif(xdiff < -minDist):
                walkdir = "right"
        if walkdir:
            send_message(walkdir)

class EchoClient(protocol.Protocol):
    def connectionMade(self):
        self.factory.app.on_connection(self.transport)

    def dataReceived(self, data):
        get_message(data)

class EchoFactory(protocol.ClientFactory):
    protocol = EchoClient
    def __init__(self, app):
        self.app = app

    def clientConnectionLost(self, conn, reason):
        self.app.print_message("connection lost")

    def clientConnectionFailed(self, conn, reason):
        self.app.print_message("connection failed")

sm = ScreenManager()
sm.add_widget(LoginScreen(name='Login'))
sm.add_widget(MainScreen(name='Main'))

class MyApp(App):

    def build(self):
        return sm

if __name__ == '__main__':
    MyApp().run()


#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved

import torch
import torch.nn as nn

from .common import GradSampleHooks_test

class GroupNorm_test(GradSampleHooks_test):
    """
    We only test the case with ``affine=True`` here, because it is the only case that will actually
    compute a gradient. There is no grad_sample from this module otherwise.
    """

    def test_3d_input_one_group_affine(self):
        N, C, H, W = 32, 16, 8, 10
        x = torch.randn([N, C, H, W])
        norm = nn.GroupNorm(num_groups=1, num_channels=C, affine=True)
        self.run_test(x, norm, batch_first=True)

    def test_3d_input_four_groups_affine(self):
        N, C, H, W = 32, 16, 8, 10
        x = torch.randn([N, C, H, W])
        norm = nn.GroupNorm(num_groups=4, num_channels=C, affine=True)
        self.run_test(x, norm, batch_first=True)

    def test_3d_input_C_groups_affine(self):
        N, C, H, W = 32, 16, 8, 10
        x = torch.randn([N, C, H, W])
        norm = nn.GroupNorm(num_groups=C, num_channels=C, affine=True)
        self.run_test(x, norm, batch_first=True)


from rest_framework import status
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from student import models
from student import serializers

@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
@authentication_classes([BasicAuthentication])
@permission_classes([IsAuthenticated])
def student_api(request, pk=None):
    if request.method == 'GET':
        # id = request.data.get('id')
        id = pk
        if id is not None:
            student = models.Student.objects.get(id=id)
            serializer = serializers.StudentSerializer(student)
            return Response(serializer.data)

        student = models.Student.objects.all()
        serializer = serializers.StudentSerializer(student, many=True)
        return Response(serializer.data)

    if request.method == 'POST':
        serializer = serializers.StudentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'msg': 'Student Created'}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    if request.method == 'PUT':
        # id = request.data.get('id')
        id = pk
        student = models.Student.objects.get(id=id)
        serializer = serializers.StudentSerializer(student, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'msg': 'Complete Student Updated'})
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    if request.method == 'PATCH':
        # id = request.data.get('id')
        id = pk
        student = models.Student.objects.get(id=id)
        serializer = serializers.StudentSerializer(student, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({'msg': 'Partial Student Updated'})
        return Response(serializer.errors)

    if request.method == 'DELETE':
        # id = request.data.get('id')
        id = pk
        student = models.Student.objects.get(id=id)
        student.delete()
        return Response({'msg': 'Student Deleted'})


from recon.core.module import BaseModule
from recon.mixins.resolver import ResolverMixin
from recon.mixins.threads import ThreadingMixin
import instaloader

class Module(BaseModule, ResolverMixin, ThreadingMixin):

    meta = {
        'name': 'Instagram Taggers',
        'author': 'Mike Jewell (@mikejewell)',
        'version': '1.0',
        'description': 'Retrieves all users who have tagged an Instagram account.',
        'dependencies': ['instaloader'],
        'required_keys': ['instagram_account'],
        'comments': (
            'Before using this module, you need to run `instaloader --login your_username` and then set instagram_account to your_username.',
        ),
        'query': "SELECT DISTINCT username FROM profiles WHERE username IS NOT NULL AND resource LIKE 'Instagram' COLLATE NOCASE",
    }

    def module_run(self, usernames):
        account = self.keys.get('instagram_account')
        L = instaloader.Instaloader()
        L.load_session_from_file(account)

        for username in usernames:
            profile = instaloader.Profile.from_username(L.context, username)
            for tagged_posts in profile.get_tagged_posts():
                self.insert_profiles(
                    username=tagged_posts.owner_username,
                    resource='Instagram',
                    category='social',
                    url='https://www.instagram.com/%s' % tagged_posts.owner_username,
                    notes=username)


#-*- coding: utf8 -*-
from django import forms
from .models import *
from django_countries.widgets import CountrySelectWidget
from tinymce.widgets import TinyMCE
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
import datetime

class CommentForm(forms.ModelForm):
	class Meta:
		model = PostComment
		fields = ['text_body']
		widgets = {
			'text_body': forms.Textarea(attrs={'placeholder': 'Send your comment', 'style':'resize:none;'}),
		}
		labels = {
			'text_body': '',
		}

class UserRegisterForm(UserCreationForm):
	class Meta:
		model = User
		fields = UserCreationForm.Meta.fields + ('email',)

class UserLoginForm(AuthenticationForm):
	class Meta:
		model = User

class UserProfileChangeForm(forms.ModelForm):
	class Meta:
		model = UserProfile
		fields = ['avatar','birthday','about','gender','country']
		widgets = {
			'birthday': forms.SelectDateWidget(years=range(1900,datetime.date.today().year)),
			'about': forms.Textarea(attrs={'rows':3,'style':'resize:vertical'}),
			'country': CountrySelectWidget()
		}


import torch
from torch import nn

CONV_SIZE = 100

# AUTOENCODER

def conv_out_size(in_size, padd, dial, kernel, stride):
    return int((in_size + 2 * padd - dial * (kernel - 1) - 1) / stride + 1)

def trans_conv_out_size(in_size, padd, dial, kernel, stride, out_padding):
    return (in_size - 1) + stride - 2 * padd + dial * (kernel - 1) + out_padding + 1

class AutoencoderIn(nn.Module):

    def __init__(self, samples: int, features: int, latent_size: int, device):
        self.device = device
        super(AutoencoderIn, self).__init__()

        '''
        self.conv = nn.Sequential(
            nn.Conv2d(in_channels=1, out_channels=32, kernel_size=5, padding=2, stride=2),
            nn.BatchNorm2d(32),
            nn.LeakyReLU(0.2),

            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2, stride=2),
            nn.BatchNorm2d(64),
            nn.LeakyReLU(0.2),

            nn.Conv2d(in_channels=64, out_channels=8, kernel_size=5, padding=2, stride=2),
            nn.BatchNorm2d(8),
            nn.LeakyReLU(0.2),

            nn.Conv2d(in_channels=8, out_channels=1, kernel_size=5, padding=2, stride=2),
            nn.BatchNorm2d(1),
            nn.LeakyReLU(0.2),
        ).to(device=device)
        '''

        self.conv = nn.Sequential(
            nn.Conv2d(in_channels=1, out_channels=CONV_SIZE, kernel_size=(1, features), padding=0),
            nn.BatchNorm2d(CONV_SIZE),
            nn.LeakyReLU(0.2),
            nn.Conv2d(in_channels=CONV_SIZE, out_channels=CONV_SIZE, kernel_size=(1, 1), padding=0),
            nn.BatchNorm2d(CONV_SIZE),
            nn.LeakyReLU(0.2),
        ).to(device=device)

        '''
        in_h_size = samples
        for i in range(4):
            in_h_size = conv_out_size(
                in_size=in_h_size,
                padd=2,
                dial=1,
                kernel=5,
                stride=2
            )

        in_w_size = features
        for i in range(4):
            in_w_size = conv_out_size(
                in_size=in_w_size,
                padd=2,
                dial=1,
                kernel=5,
                stride=2
            )
'''
        in_linear_size = samples * CONV_SIZE

        hidden_1_size = int(in_linear_size - (in_linear_size - latent_size) / 3)
        hidden_2_size = int(in_linear_size - 3 * (in_linear_size - latent_size) / 4)
        # hidden_2_size = int(in_linear_size - 6 * (in_linear_size - out) / 8)

        self.net = nn.Sequential(
            nn.Linear(in_features=in_linear_size, out_features=hidden_2_size, bias=True),
            nn.Sigmoid()
            # nn.LeakyReLU(0.2),
            # nn.Linear(in_features=hidden_1_size, out_features=hidden_2_size, bias=True),
            # nn.ReLU(),
            # nn.Linear(in_features=hidden_1_size, out_features=hidden_2_size, bias=True),
            # nn.Sigmoid(),
        ).to(device=device)

        self.mu = nn.Linear(hidden_2_size, latent_size).to(device=device)
        self.var = nn.Linear(hidden_2_size, latent_size).to(device=device)

    def forward(self, x: torch.Tensor):
        x = x.unsqueeze(dim=1)
        x = self.conv(x)
        x = x.flatten(start_dim=1)
        x = self.net(x)

        lat_mu = self.mu(x)
        lat_ver = self.var(x)

        return lat_mu, lat_ver

class AutoencoderOut(nn.Module):

    def __init__(self, latent_size: int, samples: int, features: int, device):
        self.device = device
        super(AutoencoderOut, self).__init__()

        self.samples = samples
        self.features = features

        '''
        self.out_h_size = samples
        for i in range(4):
            self.out_h_size = conv_out_size(
                in_size=self.out_h_size,
                padd=2,
                dial=1,
                kernel=5,
                stride=2
            )

        self.out_w_size = features
        for i in range(4):
            self.out_w_size = conv_out_size(
                in_size=self.out_w_size,
                padd=2,
                dial=1,
                kernel=5,
                stride=2,
            )
        '''

        out_linear_size = samples * CONV_SIZE

        hidden_1_size = int(out_linear_size - 3 * (out_linear_size - latent_size) / 4)

        self.net = nn.Sequential(
            nn.Linear(in_features=latent_size, out_features=hidden_1_size, bias=True),
            # nn.BatchNorm1d(latent_size*hidden_1_size),
            # nn.LeakyReLU(0.2),
            nn.Sigmoid(),
            nn.Linear(in_features=hidden_1_size, out_features=out_linear_size, bias=True),
            # nn.LeakyReLU(0.2),
        ).to(device=device)

        # (400, 325) -> output_paddings = (1, 0), 1, (1, 0), (1, 0)
        # (300, 325) -> output_paddings = (1, 0), (0, 1), (1, 0), (1, 0)

        '''
        self.conv = nn.Sequential(
            nn.ConvTranspose2d(in_channels=1, out_channels=8, kernel_size=5, padding=2, stride=2, output_padding=(1, 0)),
            nn.BatchNorm2d(8),
            nn.LeakyReLU(0.2),

            nn.ConvTranspose2d(in_channels=8, out_channels=64, kernel_size=5, padding=2, stride=2, output_padding=(0, 1)),
            nn.BatchNorm2d(64),
            nn.LeakyReLU(0.2),

            nn.ConvTranspose2d(in_channels=64, out_channels=32, kernel_size=5, padding=2, stride=2, output_padding=(1, 0)),
            nn.BatchNorm2d(32),
            nn.LeakyReLU(0.2),

            nn.ConvTranspose2d(in_channels=32, out_channels=1, kernel_size=5, padding=2, stride=2, output_padding=(1, 0)),
            nn.BatchNorm2d(1),
            nn.LeakyReLU(0.2),

        ).to(device=device)
        '''

        self.conv = nn.Sequential(
            nn.ConvTranspose2d(
                in_channels=CONV_SIZE, out_channels=CONV_SIZE, kernel_size=(1, 1), padding=0
            ),
            nn.BatchNorm2d(CONV_SIZE),
            nn.LeakyReLU(0.2),
            nn.ConvTranspose2d(
                in_channels=CONV_SIZE, out_channels=1, kernel_size=(1, features), padding=0
            ),
        ).to(device=device)

    def forward(self, x: torch.Tensor):
        batch_size = len(x)
        #        x = torch.zeros(size=x.size()).cuda()

        x = self.net(x)
        x = x.reshape(shape=(batch_size, CONV_SIZE, self.samples, 1))
        x = self.conv(x)

        # x = self.conv_out.forward(input=x, output_size=[-1, 1, self.samples, self.features],),

        return x.squeeze()

class Autoencoder(nn.Module):
    def __init__(self, auto_in: AutoencoderIn, auto_out: AutoencoderOut):
        super(Autoencoder, self).__init__()

        self.auto_in = auto_in
        self.auto_out = auto_out

    def forward(self, x: torch.Tensor):
        lat_mu, lat_var = self.auto_in(x)

        std = torch.exp(lat_var / 2)
        eps = torch.randn_like(std)
        lat_vec = eps.mul(std).add_(lat_mu)

        out = self.auto_out(lat_vec)
        return out, lat_mu, lat_var

    @staticmethod
    def create(samples: int, features: int, latent: int, device):
        auto_in = AutoencoderIn(samples=samples, features=features, latent_size=latent, device=device)
        auto_out = AutoencoderOut(latent_size=latent, samples=samples, features=features, device=device)

        return [auto_in, auto_out]


import matplotlib.pyplot as plt
import numpy as np

with plt.xkcd():
    fig = plt.figure(figsize=(5,5))
    ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    plt.xticks([])
    plt.yticks([])
    x = np.linspace(0, 2, 1000)
    plt.plot(x, x ** 2)
    plt.title("Ideal Life")
    plt.xlabel("Age")
    plt.ylabel("Money,Knowledge,Handsomeness")
    plt.annotate('ME', xy=(1, 1), xytext=(0.5, 2), arrowprops=dict(facecolor='red', shrink=0.08))
    plt.show()


#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import tempfile
import unittest

from antlir.config import load_repo_config
from antlir.fs_utils import Path
from antlir.subvol_utils import TempSubvolumes
from antlir.tests.flavor_helpers import render_flavor
from antlir.tests.layer_resource import layer_resource_subvol
from antlir.tests.subvol_helpers import render_subvol

from ..compiler import build_image, parse_args

def _test_feature_target(feature_target):
    return (
        "//antlir/compiler/test_images:"
        + feature_target
        + "_IF_YOU_REFER_TO_THIS_RULE_YOUR_DEPENDENCIES_WILL_BE_BROKEN"
    )

class AddRemoveConflictTestCase(unittest.TestCase):
    def setUp(self):
        # More output for easier debugging
        unittest.util._MAX_LENGTH = 12345
        self.maxDiff = 12345

    def test_check_layers(self):
        meta = {
            ".meta": [
                "(Dir)",
                {
                    "flavor": [render_flavor()],
                    "private": [
                        "(Dir)",
                        {
                            "opts": [
                                "(Dir)",
                                {"artifacts_may_require_repo": ["(File d2)"]},
                            ]
                        },
                    ],
                },
            ]
        }
        # The parent has a couple of directories.
        self.assertEqual(
            ["(Dir)", {"a": ["(Dir)", {"b": ["(Dir)", {}]}], **meta}],
            render_subvol(layer_resource_subvol(__package__, "parent")),
        )
        # The child is near-empty because the `remove_paths` cleaned it up.
        self.assertEqual(
            ["(Dir)", {**meta}],
            render_subvol(layer_resource_subvol(__package__, "child")),
        )

    def test_conflict(self):
        with TempSubvolumes() as tmp_subvols, (
            tempfile.NamedTemporaryFile()
        ) as tf, Path.resource(
            __package__, "feature_both", exe=False
        ) as feature_both, Path.resource(
            __package__, "feature_add", exe=False
        ) as feature_add, Path.resource(
            __package__, "feature_remove", exe=False
        ) as feature_remove, self.assertRaisesRegex(
            # Removes get built before adds; a conflict means nothing to remove
            AssertionError,
            "Path does not exist",
        ):
            # Write the targets_and_outputs file
            tf.write(
                Path.json_dumps(
                    {
                        _test_feature_target(
                            "feature_addremove_conflict_add"
                        ): feature_add,
                        _test_feature_target(
                            "feature_addremove_conflict_remove"
                        ): feature_remove,
                    }
                ).encode()
            )
            tf.seek(0)

            subvol = tmp_subvols.external_command_will_create("test_conflict")
            # We cannot make this an `image.layer` target, since Buck
            # doesn't (yet) have a nice story for testing targets whose
            # builds are SUPPOSED to fail.
            build_image(
                parse_args(
                    [
                        "--subvolumes-dir",
                        subvol.path().dirname(),
                        "--subvolume-rel-path",
                        subvol.path().basename(),
                        "--child-layer-target",
                        "unused",
                        f"--child-feature-json={feature_both}",
                        "--targets-and-outputs",
                        tf.name,
                        "--flavor",
                        load_repo_config().flavor_default,
                    ]
                )
            )


from django.core.exceptions import ValidationError

import graphene
from graphene_django import DjangoObjectType

from app.timetables.models import Weekday
from .utils import get_errors, get_object, load_object

class WeekdayNode(DjangoObjectType):
    original_id = graphene.Int()

    class Meta:
        model = Weekday
        filter_fields = {
            'name': ['icontains']
        }
        filter_order_by = ['name', '-name']
        interfaces = (graphene.relay.Node,)

    def resolve_original_id(self, args, context, info):
        return self.id

class CreateWeekday(graphene.relay.ClientIDMutation):
    weekday = graphene.Field(WeekdayNode)
    errors = graphene.List(graphene.String)

    class Input:
        name = graphene.String(required=True)

    @classmethod
    def mutate_and_get_payload(cls, input, context, info):
        try:
            weekday = Weekday(
                name=input.get('name')
            )
            weekday.full_clean()
            weekday.save()
            return cls(weekday=weekday)
        except ValidationError as e:
            return cls(weekday=None, errors=get_errors(e))

class UpdateWeekday(graphene.relay.ClientIDMutation):
    weekday = graphene.Field(WeekdayNode)
    errors = graphene.List(graphene.String)

    class Input:
        id = graphene.String(required=True)
        name = graphene.String(required=True)

    @classmethod
    def mutate_and_get_payload(cls, input, context, info):
        weekday = get_object(Weekday, input.get('id'))
        weekday = load_object(weekday, input)
        try:
            if weekday:
                weekday.full_clean()
                weekday.save()
            return cls(weekday=weekday)
        except ValidationError as e:
            return cls(weekday=weekday, errors=get_errors(e))

class DeleteWeekday(graphene.relay.ClientIDMutation):
    weekday = graphene.Field(WeekdayNode)
    deleted = graphene.Boolean()

    class Input:
        id = graphene.String(required=True)

    @classmethod
    def mutate_and_get_payload(cls, input, context, info):
        try:
            weekday = get_object(Weekday, input.get('id'))
            weekday.delete()
            return cls(deleted=True, weekday=weekday)
        except:
            return cls(deleted=False, weekday=None)


import matplotlib.pyplot as plt
import numpy as np

import cv2

fig, ax = plt.subplots()
ax.set_title('a simple figure')
ax.set_ylim(0, 1.1)
ax.set_xlim(0, 10)
# plt.ion()
lines = []
for ind in range(5):
    y = np.random.rand(3)
    line = ax.plot(y, lw=2)
    lines.append(line)

line = lines[0]

while True:

    y = np.random.rand(3)
    line[0].set_data([0, 1, 2], y)
    fig.canvas.draw()
    X = np.array(fig.canvas.renderer._renderer)
    cv2.imshow('X', X)
    ch = cv2.waitKey(10) & 0xff
    if ch == 27:
        exit()


from django.db import models
from tinymce.models import HTMLField
from user.models import User

# Create your models here.
# 動的にデータベースのコラムを増やせるか。ユーザの入力をシステムの変数でキャプチャして利用する。すると、ユーザからの入力から独立してシステムを構築できる。システムとして提供するものはステートレスでいいんだ。
class Tag(models.Model):
    tag_name = models.CharField(
        unique=True,
        max_length=100,
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return self.tag_name

class Log(models.Model):
    committing_user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        verbose_name='user who comitted',
    )
    committed_date = models.DateTimeField(
        verbose_name='committed date',
    )
    logtitle = models.CharField(
        verbose_name='title',
        max_length=100,
    )
    text = HTMLField()
    attach = models.FileField(
        verbose_name="attached file",
        upload_to="attached/",
        blank=True,
    )
    tags = models.ManyToManyField(
        Tag,
        blank=True,
        verbose_name='関連づけられたタグ',
    )

    def __str__(self):
        return self.logtitle

class UserCustomNote(models.Model):
    title = models.CharField(
        max_length=100,
    )
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        verbose_name='your account',
    )
    created_date = models.DateTimeField(
        verbose_name='latest update'
    )
    custom_log = models.ManyToManyField(
        Log,
        verbose_name='your customed log',
    )
    own_memo = models.TextField(
        verbose_name='your original memo',
    )

    def __str__(self):
        return self.user


'''
    Model from 'SOUND EVENT DETECTION USING WEAKLY LABELLED SEMI-SUPERVISED DATA WITH GCRNNS, VAT AND SELF-ADAPTIVE LABEL REFINEMENT'
'''
from keras.models import Model
from keras.layers import Dense,Input,Flatten,Conv2D,BatchNormalization,Activation,MaxPooling2D
from keras.layers import Dropout, Lambda, GlobalAveragePooling2D, Reshape, CuDNNGRU, CuDNNLSTM, TimeDistributed
import keras.utils
import keras.backend as K
import numpy as np
import tensorflow as tf

ASC_CLASS=10
DROPOUT=0.5

class GCNN_GRU(object):

    def __init__(self, filters=64, lstm=False, attention=False):
        self.filters = filters
        self.lstm = lstm
        self.attention = attention
    def __call__(self, x):

        for depth in range(4):
            filters=self.filters
            x=Conv2D(filters=filters,
                    kernel_size=3, padding='same',
                    data_format='channels_last',
                    kernel_initializer='glorot_uniform')(x)
            x=BatchNormalization(axis=-1)(x)

            y=Conv2D(filters=filters,
                    kernel_size=3, padding='same',
                    data_format='channels_last',
                    kernel_initializer='glorot_uniform')(x)
            y=BatchNormalization(axis=-1)(y)
            y=Activation('sigmoid')(y)

            x=Lambda(lambda x: tf.multiply(x[0],x[1]))([x,y])

            x=MaxPooling2D(pool_size=(2,1), data_format='channels_last')(x)
            x=Dropout(rate=DROPOUT)(x)

        x=Lambda(lambda x: tf.transpose(x, perm=[0, 2, 1, 3]))(x)

        # (500//8, 40, 64)
        shp=K.int_shape(x)
        x = Reshape((shp[1], shp[2] * shp[3]))(x)

        # (500//8, 40x64)
        if self.lstm is False:
            y=CuDNNGRU(units=64,
                       return_sequences=True, stateful=False,
                       kernel_initializer='glorot_uniform', recurrent_initializer='identity',
                       bias_initializer='zeros',
                       go_backwards=False)(x)
            z=CuDNNGRU(units=64,
                       return_sequences=True, stateful=False,
                       kernel_initializer='glorot_uniform', recurrent_initializer='identity',
                       bias_initializer='zeros',
                       go_backwards=True)(x)
        elif self.lstm is True:
            y=CuDNNLSTM(units=64,
                        return_sequences=True, stateful=False,
                        kernel_initializer='glorot_uniform', recurrent_initializer='identity',
                        bias_initializer='zeros',
                        go_backwards=False)(x)
            z=CuDNNLSTM(units=64,
                        return_sequences=True, stateful=False,
                        kernel_initializer='glorot_uniform', recurrent_initializer='identity',
                        bias_initializer='zeros',
                        go_backwards=True)(x)

        # concat tensors
        x = Lambda(lambda x: tf.concat([x[0],x[1]], axis=1))([y,z])

        # attention
        if self.attention is True:
            x=Lambda(lambda x: tf.expand_dims(x, -1))(x)
            x=SelfAttention(x, output_filters=10)
            x=BatchNormalization(axis=-1)(x)
            x=GaussianNoise(0.3)(x)
            x=GlobalAveragePooling2D(data_format='channels_last')(x)
        else:
            # (500//8, 128)
            y=TimeDistributed(Dense(ASC_CLASS, activation='sigmoid'))(x)
            z=TimeDistributed(Dense(ASC_CLASS, activation='softmax'))(x)
            # (500//8, 10)
            x=Lambda(lambda x: tf.multiply(x[0], x[1]))([y,z])
            x=Lambda(lambda x: tf.reduce_mean(x, axis=1))(x)

        output=Activation('softmax')(x)

        return output


import speech_recognition as sr
import subprocess
while True:
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("I'm listening . . . ")
        audio = r.listen(source)
        try:
            text = r.recognize_google(audio)
            print(format(text))
            if(text == "stop"):
                break
            else:
                if text == "open downloads" or text == "see my downloads":
                    subprocess.check_output("Downloads.bat")
                    break

                elif text == "open Torrent folder" or text == "open my movies folder":
                    subprocess.check_output("BiglyBt.bat")
                    break

                elif text == "open my project" or text == "project folder":
                    subprocess.check_output("Project.bat")
                    break

                else:
                    print("Not match with given instruction")

        except:
            print("I can't recognize you voice, Sir")


import sys
from typing import final
from PyQt5 import QtCore, QtWidgets
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import mplcursors
import os

matplotlib.use('Qt5Agg')

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from mpl_toolkits import mplot3d
from custom_dialog import CustomDialog
from PyQt5.QtCore import pyqtSlot
from singleton import Database
from main_processing import MainProcessing

from custom_dialog import CustomDialog
from PyQt5 import QtGui
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (
    QApplication,
    QMainWindow,
    QWidget,
    QTabWidget,
    QDialog,
    QVBoxLayout,
    QHBoxLayout,
    QLineEdit,
    QLabel,
    QDialogButtonBox,
    QPushButton,
    QTextEdit,
    QComboBox,
    QRadioButton,
)

class MainTab(QWidget):
    """
    Pantalla Principal de la app donde se visualiza
    la rir 3D
    """

    def __init__(self):
        super().__init__()

        layout = QHBoxLayout()
        layout_vertical_main = QVBoxLayout()
        layout_vertical_graph = QVBoxLayout()

        #Infromación para cargar de la medición
        button = QtWidgets.QPushButton("Añadir Medición")
        button.clicked.connect(self.button_clicked)
        button.setMaximumWidth(150)
        layout_vertical_main.addWidget(button)

        label = QLabel("Nombre de la Medición")
        layout_vertical_main.addWidget(label)

        self.nombre_medicion = QLineEdit()
        layout_vertical_main.addWidget(self.nombre_medicion)

        label = QLabel("Fuente")
        layout_vertical_main.addWidget(label)

        self.fuente = QLineEdit()
        layout_vertical_main.addWidget(self.fuente)

        label = QLabel("Punto de Medición")
        layout_vertical_main.addWidget(label)

        self.punto_medicion = QLineEdit()
        layout_vertical_main.addWidget(self.punto_medicion)

        label = QLabel("Frecuencia de Muestreo")
        layout_vertical_main.addWidget(label)

        self.frecuencia_muestreo = QLineEdit()
        layout_vertical_main.addWidget(self.frecuencia_muestreo)

        label = QLabel("Longitud del Sweep")
        layout_vertical_main.addWidget(label)

        self.long_sweep = QLineEdit()
        layout_vertical_main.addWidget(self.long_sweep)

        label = QLabel("Descripción")
        layout_vertical_main.addWidget(label)

        self.descripcion = QTextEdit()
        layout_vertical_main.addWidget(self.descripcion)

        #Botones para elegir configuración
        buttons_layout = QVBoxLayout()
        radio_button_layout = QHBoxLayout()

        self.integration_window_size = 1 * (10 ** -3)
        self.tamaño_ventana = QLabel("Tamaño de la ventana de integración: ")
        buttons_layout.addWidget(self.tamaño_ventana)

        self.b1 = QRadioButton("1 ms")
        self.b1.setChecked(True)
        self.b1.toggled.connect(lambda: self.integration_time_selection(self.b1))
        radio_button_layout.addWidget(self.b1)

        self.b2 = QRadioButton("5 ms")
        self.b2.toggled.connect(lambda: self.integration_time_selection(self.b2))
        radio_button_layout.addWidget(self.b2)

        self.b3 = QRadioButton("10 ms")
        self.b3.toggled.connect(lambda: self.integration_time_selection(self.b3))
        radio_button_layout.addWidget(self.b3)

        buttons_layout.addLayout(radio_button_layout)
        layout_vertical_main.addLayout(buttons_layout)

        self.number_of_windows = 256
        self.cantidad_ventanas_text = QLabel("Ingrese la cantidad de ventanas de integración: ")
        self.cantidad_ventanas_dialog = QLineEdit()
        self.cantidad_ventanas_dialog.setMaximumWidth(75)

        layout_vertical_main.addWidget(self.cantidad_ventanas_text)
        layout_vertical_main.addWidget(self.cantidad_ventanas_dialog)

        self.umbral = 0
        self.umbral_text = QLabel("Ingrese el umbral en dB: ")
        self.umbral_dialog = QLineEdit()
        self.umbral_dialog.setMaximumWidth(75)

        final_button_layout = QHBoxLayout()

        layout_vertical_main.addWidget(self.umbral_text)
        layout_vertical_main.addWidget(self.umbral_dialog)

        graph_button = QPushButton("Graficar")
        graph_button.setMaximumWidth(150)
        graph_button.clicked.connect(self.graficar)

        export_data_button = QPushButton("Exportar Datos")
        export_data_button.setMaximumWidth(150)
        export_data_button.clicked.connect(self.export_data)

        final_button_layout.addWidget(graph_button)
        final_button_layout.addWidget(export_data_button)

        #layout_vertical_main.addWidget(graph_button)
        layout_vertical_main.addLayout(final_button_layout)

        #Canvas para gráficos
        self.plot_3D = FigureCanvas(plt.Figure(figsize = (7, 6)))
        layout_vertical_graph.addWidget(self.plot_3D)

        self.insert_ax_3D()
        mplcursors.cursor(hover=True)

        self.plot_canalw = FigureCanvas(plt.Figure(figsize = (7, 5)))
        self.insert_ax()

        layout_vertical_graph.addWidget(self.plot_canalw)

        layout.addLayout(layout_vertical_main)
        layout.addLayout(layout_vertical_graph)

        self.setLayout(layout)

    def insert_ax_3D(self):

        self.axes = self.plot_3D.figure.add_subplot(projection = '3d')
        self.cax = self.plot_3D.figure.add_axes([0.85, 0.25, 0.03, 0.5])
        self.axes.set_title("Análisis 3D ")
        self.axes.set_xlabel('X')
        self.axes.set_ylabel('Y')
        self.axes.set_zlabel('Z')
        self.axes.grid(False)
        self.axes.view_init(90, 90)

    def insert_ax(self):

        self.ax = self.plot_canalw.figure.subplots()
        self.ax.set_title("Canal W")
        self.ax.set_xlabel("Tiempo [ms]")
        self.ax.set_ylabel("Amplitud")
        self.ax.grid(True)
        self.line = None

    def button_clicked(self, s):

        print("click", s)
        dlg = CustomDialog(self)
        dlg.exec_()

    def integration_time_selection(self, b):

        if b.text() == "1 ms":
            if b.isChecked() == True:
                self.integration_window_size = 1 * (10 ** -3)
            else:
                pass

        if b.text() == "5 ms":
            if b.isChecked() == True:
                self.integration_window_size = 5 * (10 ** -3)
            else:
                pass

        if b.text() == "10 ms":
            if b.isChecked() == True:
                self.integration_window_size = 10 * (10 ** -3)
            else:
                pass

    def graficar(self):

        datos = Database()
        ambi = datos.get()

        integration_window_size = self.integration_window_size
        try:
            self.umbral = int(self.umbral_dialog.text())
        except:
            pass

        try:
            self.number_of_windows = int(self.cantidad_ventanas_dialog.text())
        except:
            pass

        LB = ambi[0]
        LF = ambi[1]
        RB = ambi[2]
        RF = ambi[3]
        Fs = ambi[4]

        BLD = LB
        FLU = LF
        BRU = RB
        FRD = RF

        time = np.linspace(0, len(BLD) / Fs, num=len(BLD))

        señal = MainProcessing(BLD, FLU, BRU, FRD, time, Fs, integration_window_size)
        W, X, Y, Z = señal.A_to_B()
        I, az, el = señal.intensity(W, X, Y, Z)
        I_gr,az_gr,el_gr, time_tr = señal.find_peaks(I, az, el)

        I_dB = señal.intensity2dB(I_gr)
        I_dB_th = señal.threshold(I_dB, self.umbral)

        I_dB_th = I_dB_th[0:self.number_of_windows]
        I_norm = señal.normalization(I_dB_th)
        el_gr = el_gr[0:len(I_norm)]
        az_gr = az_gr[0:len(I_norm)]
        time_tr = time_tr[0:len(I_norm)]
        x,y,z = señal.polar2cart(I_norm,az_gr,el_gr)

        self.axes.cla()
        self.cax.clear()

        c = time_tr
        img = self.axes.scatter(x, y, z, c=c, marker=".", linewidths=1, cmap=plt.plasma())

        for i in range(0, len(x)):
            x_val, y_val, z_val = x[i], y[i], z[i]
            if i == 0:
                self.axes.plot([0, x_val], [0, y_val], zs=[0, z_val], color=img.to_rgba(c[i]), linewidth=7)
            elif i > 0:
                self.axes.plot([0, x_val], [0, y_val], zs=[0, z_val], color=img.to_rgba(c[i]), linewidth=2)

        self.save_image()

        cbar = self.plot_3D.figure.colorbar(img, pad = 0.25, use_gridspec = True, cax = self.cax)
        cbar.set_label("Tiempo [ms]")

        self.plot_3D.draw()

        self.line = self.ax.plot(time, W, color='b')
        self.plot_canalw.draw()

        self.data = señal.table(time_tr,I_dB_th,az_gr,el_gr)

    def save_image(self):
        self.axes.axis("off")
        self.axes.set_title("")
        self.cax.axis("off")
        self.plot_3D.figure.savefig('./RIR_3D.png', transparent = True)
        self.axes.axis("on")
        self.axes.set_title("Análisis 3D")
        self.cax.axis("on")

    def export_data(self):

        nombre = self.nombre_medicion.text()
        self.data['Nombre medición'] = nombre

        fuente = self.fuente.text()
        self.data['Fuente'] = fuente

        punto_medicion = self.punto_medicion.text()
        self.data['Punto de Medición'] = punto_medicion

        frecuencia_muestreo = self.frecuencia_muestreo.text()
        self.data['Frecuencia de Muestreo'] = frecuencia_muestreo

        longitud_sweep = self.long_sweep.text()
        self.data['Longitud del Sweep'] = longitud_sweep

        descripcion = self.descripcion.toPlainText()
        self.data['Descripción'] = descripcion

        self.data.to_excel('./Datos_rir.xlsx')


#!/usr/bin/python3
""" holds class State"""
from models.state import State
from flask import jsonify, abort, request, Response, make_response
from models import storage
from api.v1.views import app_views

@app_views.route('/states',
                 methods=['GET'],
                 strict_slashes=False,
                 defaults={'state_id': 0})
@app_views.route('/states/<state_id>', methods=['GET'], strict_slashes=False)
def get_states(state_id):
    dic = storage.all(State)
    ids = "State." + str(state_id)
    if (state_id == 0):
        state_list = []
        for k, v in dic.items():
            state_list.append(v.to_dict())
        return jsonify(state_list)
    elif (ids not in dic.keys()):
        abort(404)
    else:
        return jsonify(dic[ids].to_dict())

@app_views.route('/states/<state_id>',
                 methods=['DELETE'],
                 strict_slashes=False)
def delete_states(state_id):
    dic = storage.all(State)
    ids = "State." + str(state_id)
    if (ids not in dic.keys()):
        abort(404)
    else:
        storage.delete(dic[ids])
        storage.save()
        return jsonify({})

@app_views.route('/states', methods=['POST'], strict_slashes=False)
def post_states():
    try:
        json = request.get_json()
    except:
        return make_response(jsonify({'error': "Not a JSON"}), 400)
    if json is None:
        return make_response(jsonify({'error': "Not a JSON"}), 400)
    if ('name' not in json.keys()):
        return make_response(jsonify({'error': "Missing name"}), 400)
    obj = State(**json)
    storage.new(obj)
    storage.save()
    return make_response(jsonify(obj.to_dict()), 201)

@app_views.route('/states/<state_id>', methods=['PUT'], strict_slashes=False)
def update_states(state_id):
    try:
        json = request.get_json()
    except:
        return make_response(jsonify({'error': "Not a JSON"}), 400)
    if json is None:
        return make_response(jsonify({'error': "Not a JSON"}), 400)
    dic = storage.all(State)
    ids = "State." + str(state_id)
    if (ids not in dic.keys()):
        abort(404)
    else:
        for k, v in json.items():
            if (k != 'id' and k != 'created_at' and k != "updated_at"):
                setattr(dic[ids], k, v)
        storage.save()
        return make_response(jsonify(dic[ids].to_dict()), 200)


"""
Simple client to connect with server
"""
import socket
import argparse
import sys
import logging
import os.path
from xml.etree import ElementTree as ET

class MiniBotnetClient:
    """
    MiniBotnetClient class
    """
    _logger = logging.getLogger(__name__)
    _my_socket = None
    _port = None
    _host = None
    _list_of_actions_to_perform = ('echo', 'python')

    def __init__(self, arguments):
        logging.basicConfig(
            level=arguments.log_level.upper(),
            stream=sys.stdout,
            format="%(asctime)s - %(levelname)s - %(message)s")

        self._port = arguments.port
        self._host = arguments.host_address

    def connect_to_server(self):
        """
        Connecting to server
        """
        self._my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self._logger.info("Connecting to host...")

        try:
            self._my_socket.connect((self._host, self._port))
        except Exception as exception:
            logging.error("Bind failed. Error: %s", exception)
            raise exception

        self._logger.info("Connected to host '%s' on port '%s'.",
                          self._host,
                          self._port)
        self._logger.debug("Connected on socket: %s", self._my_socket)

    def send_message_to_server(self, message):
        """
        Sending message as sting to host
        """
        self._logger.info("Message sended to host (%s): %s",
                          self._host,
                          message)
        self._my_socket.send(str.encode(message))

    def _parse_xml_to_string(self, path_to_xml):
        if os.path.exists(path_to_xml):
            self._logger.info("File to send: %s", path_to_xml)
            tree = ET.parse(path_to_xml)
            root = tree.getroot()
            xml_content_as_string = ET.tostring(root,
                                                encoding='utf8',
                                                method='xml').decode("utf-8")
            self._logger.debug("XML to send: %s", xml_content_as_string)
            return xml_content_as_string
        else:
            self._logger.info("File %s does not exist!", path_to_xml)
            raise IOError

    def send_xml_to_server(self, path_to_xml):
        """
        Parse xml from path to string and send it to host
        """
        xml_to_send = self._parse_xml_to_string(path_to_xml)
        self._my_socket.send(str.encode("xml %s" % xml_to_send))

def _get_parser():
    parser = argparse.ArgumentParser(description="Mini botnet")
    parser.add_argument("-a",
                        "--host_address",
                        required=False,
                        default="127.0.0.1",
                        action="store",
                        type=str,
                        help="Host")

    parser.add_argument("-p",
                        "--port",
                        required=False,
                        default="1336",
                        action="store",
                        type=int,
                        help="Port")

    parser.add_argument("-x",
                        "--xml_path",
                        required=False,
                        default="tmp/temp_xml.xml",
                        action="store",
                        type=str,
                        help="Path to XML")

    parser.add_argument("-l",
                        "--log_level",
                        required=False,
                        default="DEBUG",
                        action="store",
                        type=str,
                        help="Log lvl")

    return parser

def main(command_line_arguments):
    """
    Main function
    """
    parser = _get_parser()
    arguments = parser.parse_args(args=command_line_arguments[1:])

    mbc = MiniBotnetClient(arguments)

    try:
        mbc.connect_to_server()
        mbc.send_message_to_server("echo moja pierwsza wiadomosc")
        mbc.send_xml_to_server(arguments.xml_path)
    except IOError as ioerror:
        logging.error("Exception: %s", ioerror)

if __name__ == "__main__":
    main(sys.argv)


import pandas as pd
import unittest
import stockmarket
from datetime import datetime, timedelta

class TestStockMarket(unittest.TestCase):

    def test_calc_divYield(self):
        # Tests for Type = Common
        stocksData = pd.DataFrame({"Stock Market": ["JOE"], "Type": ["Common"],
                                   "Last Dividend": [18], "Fixed Dividend": [""],
                                   "Par Value": [120]})
        result = stockmarket.calc_divYield(stocksData, 12)
        self.assertEqual(result.iloc[0]["Dividend Yield"], "150%")

        # Tests for Type == Preferred
        stocksData = pd.DataFrame({"Stock Market": ["GIN"], "Type": ["Preferred"],
                                   "Last Dividend": [18], "Fixed Dividend": ["8%"],
                                   "Par Value": [120]})
        result = stockmarket.calc_divYield(stocksData, 12)
        self.assertEqual(result.iloc[0]["Dividend Yield"], "80%")

    def test_calc_PERatio(self):
        stocksData = pd.DataFrame({"Stock Market": ["JOE"], "Type": ["Common"],
                                   "Last Dividend": [11], "Fixed Dividend": [""],
                                   "Par Value": [120]})
        result = stockmarket.calc_PERatio(stocksData, 65)
        self.assertEqual(result.iloc[0]["P/E Ratio"], 5.91)

    def test_calc_VWSP(self):
        # Generate test data
        dttime = [dttime for dttime in range(24, 0, -6)]
        timestamp = [(datetime.now() - timedelta(minutes=dt)) \
                    .strftime("%m/%d/%Y %H:%M:%S") for dt in dttime]
        trades = pd.DataFrame({"Stock Market": ["TEA", "TEA", "GIN"],
                               "Timestamp": [timestamp[0], timestamp[1], timestamp[2]],
                               "Quantity of Shares": [25, 12, 7],
                               "BUY/SELL": ["BUY", "SELL", "BUY"],
                               "Price": [22, 24, 19]})
        result = stockmarket.calc_VWSP(trades)
        self.assertEqual(len(result), 1)
        self.assertEqual(result.iloc[0]["Volume Weighted Stock Price"], 19.0)

    def test_calc_AllShareIndex(self):
        # Generate test data
        dttime = [dttime for dttime in range(24, 0, -6)]
        timestamp = [(datetime.now() - timedelta(minutes=dt)) \
                    .strftime("%m/%d/%Y %H:%M:%S") for dt in dttime]
        trades = pd.DataFrame({"Stock Market": ["TEA", "TEA", "GIN"],
                               "Timestamp": [timestamp[0], timestamp[1], timestamp[2]],
                               "Quantity of Shares": [25, 12, 7],
                               "BUY/SELL": ["BUY", "SELL", "BUY"],
                               "Price": [22, 24, 19]})
        result = stockmarket.calc_AllShareIndex(trades)
        self.assertEqual(result, 21.57)

    def test_save_trade(self):
        trades = pd.DataFrame({"Stock Market": [], "Timestamp": [], "Quantity of Shares": [], "BUY/SELL": [], "Price": []})
        result = stockmarket.save_trade(trades, "JOE", "10/07/2019 08:00:00", 21, "BUY", 11)
        self.assertEqual(len(result), 1)

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


#!/usr/bin/env python3
"""Dear Ken, after today class, I am more comfortable with coding this program.
Although I have a trouble passing the test, I feel like I have learnt a lot
from coding this. I was hoping to get some credits form handing in still
as I have been working really hard for this."""

import argparse
import os
import sys
import Bio
import random
from Bio import SeqIO
import re

# --------------------------------------------------
def get_args():
    """Get command-line arguments"""

    parser = argparse.ArgumentParser(
        description='Filter SwissPort file for keywords, taxa',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('FILE',
                        metavar='FILE',
                        type=argparse.FileType('r'),
                        help='Swiss file')

    parser.add_argument('-k',
                        '--keyword',
                        metavar='keyword',
                        type=str,
                        required=True,
                        nargs='+',
                        help='Keyword to take')

    parser.add_argument('-s',
                        '--skiptaxa',
                        metavar='[taxa [taxa ...]]',
                        type=str,
                        nargs='*',
                        help='Taxa to skip')

    parser.add_argument('-o',
                        '--outfile',
                        metavar='FILE',
                        type=str,
                        default='out.fa',
                        help='Output filename')

    return parser.parse_args()

# --------------------------------------------------
def main():
    """Make a jazz noise here"""

    args = get_args()
    keyword = set(map(str.lower, args.keyword))
    skip_taxa = set(map(str.lower, args.skiptaxa or []))
    num_skipped = 0
    num_taken = 0

    out_fh = open(args.outfile, "wt")

    for rec in SeqIO.parse(args.FILE, 'swiss'):
        annot = rec.annotations

        if skip_taxa and 'taxonomy' in annot:
            taxa = set(map(str.lower, annot['taxonomy']))
            if skip_taxa.intersection(taxa):
                num_skipped += 1
                continue

        keywords = annot.get('keywords')

        if keywords:
            keywords = set(map(str.lower, keywords))
            if keyword.intersection(keywords):
                num_taken += 1
                SeqIO.write(rec, out_fh, 'fasta')
            else:
                num_skipped += 1

    out_fh.close()

    print(f'Done, skipped {num_skipped} and took {num_taken}.'
          f' See output in "{args.outfile}".')

# --------------------------------------------------
if __name__ == '__main__':
    main()


import tkinter as tk
from tkinter import ttk
import math
import statistics
import matplotlib.pyplot as pt
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

class MainApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(MainPage)

    def switch_frame(self, frame_class):
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

    def get_mainPage(self, page_class):
            return self.frames[page_class]

def dataGenerator():
    listRol = orderingList()
    #print(listRol)
    groupValue = groupingData(listRol)
    #print(groupValue)
    dictClasses = creatingClasses(listRol, groupValue)
    #print(dictClasses)
    measuredValues = measuring(listRol)
    #print(measuredValues)
    displayingData(listRol, groupValue, dictClasses, measuredValues)

def orderingList():
    orderedList = inputTextVar.get()
    orderedList = [int(i) for i in orderedList.split()]
    orderedList.sort()
    return orderedList

def groupingData(list):
    amplitudeClass = list[-1] - list[0]
    kClass = round(1 + (3.22 * math.log(len(list), 10)))
    hClass = round(amplitudeClass / kClass)
    groupArray = {
        "A": amplitudeClass,
        "K": kClass,
        "H": hClass
    }
    return groupArray

def creatingClasses(list, groupData):
    i = 0
    y=0
    extra = 0
    resultingArray = {}
    fiCounter = 0
    facCounter = 0
    startingClassValue = 0
    finishingClassValue = 0
    totalxifi = 0
    totalxi2fi = 0
    while True:
        tmpString = "class"+ str(i+1)
        tmpString = {tmpString : ""}
        resultingArray.update(tmpString)
        tmpString = "class"+ str(i+1)
        resultingArray[str(tmpString)] = {'startingValue' : '','finishingValue' : '', 'fi' : '', 'fac' : '', 'xi' : '', 'xifi' : '', 'xi2' : '', 'xi2fi' : ''}
        startingClassValue = list[0]+y
        finishingClassValue = list[0] + (y+groupData["H"])

        resultingArray[str(tmpString)]['startingValue'] = startingClassValue
        resultingArray[str(tmpString)]['finishingValue'] = finishingClassValue
        for item in range(len(list)):
            if list[0] + y + extra <= list[item] <= list[0]+ (y+(groupData["H"]-1)):
                fiCounter+=1
            if (i == (groupData["K"] - 1) and (list[item] == list[0]+ (y+(groupData["H"])))):
                fiCounter+=1
        resultingArray[str(tmpString)]["fi"] = fiCounter

        facCounter = facCounter + fiCounter
        resultingArray[str(tmpString)]["fac"] = facCounter

        xi = (resultingArray[str(tmpString)]["startingValue"] + resultingArray[str(tmpString)]["finishingValue"]) / 2
        resultingArray[str(tmpString)]['xi'] = xi

        xifi = xi * fiCounter
        resultingArray[str(tmpString)]["xifi"] = xifi

        xi2 = xi**2
        resultingArray[str(tmpString)]["xi2"] = xi2

        xi2fi = xi2 * fiCounter
        resultingArray[str(tmpString)]["xi2fi"] = xi2fi

        totalxifi = totalxifi + xifi
        totalxi2fi = totalxi2fi + xi2fi

        extra = 0
        y+=groupData["H"]
        i += 1
        fiCounter = 0
        if (i == (groupData["K"] )):
            break

    return resultingArray

def measuring(list):
    measures = {'mean': '', 'median': '', 'mode': '', 'variance': '', 'standardDeviation': ''}
    measures["mean"] = round(statistics.mean(list), 2)
    measures["median"] = round(statistics.median(list), 2)
    try:
        measures["mode"] = round(statistics.mode(list), 2)
    except statistics.StatisticsError:
        measures["mode"] = "Amodal"
    measures["variance"] = round(statistics.variance(list), 2)
    measures["standardDeviation"] = round(statistics.stdev(list), 2)
    return measures

def displayingData(rol, preGroupValues, groups, resultMeasuredValues):
    class PageOne(tk.Frame):
        def __init__(self, master):
            tk.Frame.__init__(self, master)
            master.geometry("650x500")
            heading = tk.Label(self,text="Dados processados", bg="green", fg="white", width="100", height="3", font="20")
            heading.pack()
            bottomFrame = tk.Frame(self)
            bottomFrame.pack(side="bottom")

            tmpString = "Valor da média = "+ str(resultMeasuredValues["mean"])
            tk.Label(self,text=tmpString).pack()
            tmpString= "Valor da mediana = "+ str(resultMeasuredValues["median"])
            tk.Label(self,text=tmpString).pack()
            tmpString= "Valor da moda = "+ str(resultMeasuredValues["mode"])
            tk.Label(self,text=tmpString).pack()
            tmpString= "Valor da variância = "+ str(resultMeasuredValues["variance"])
            tk.Label(self,text=tmpString).pack()
            tmpString= "Valor do desvio padrão = "+ str(resultMeasuredValues["standardDeviation"])
            tk.Label(self,text=tmpString).pack()

            tk.Button(bottomFrame, text="Visualizar histograma e tabela",
            command=lambda: master.switch_frame(PageTwo)).pack(side="left")
            tk.Button(bottomFrame, text="Retornar para a tela inicial",
                      command=lambda: master.switch_frame(MainPage)).pack()
    app.switch_frame(PageOne)
    class PageTwo(tk.Frame):
        def __init__(self, master):
            tk.Frame.__init__(self, master)
            master.geometry("650x500")
            heading = tk.Label(self,text="Histograma", bg="green", fg="white", width="100", height="3", font="20")
            heading.pack()
            bottomFrame = tk.Frame(self)
            bottomFrame.pack(side="bottom")

            tk.Button(bottomFrame, text="Retornar para as medidas",
                      command=lambda: master.switch_frame(PageOne)).pack(side="left")
            tk.Button(bottomFrame, text="Retornar para a tela inicial",
                      command=lambda: master.switch_frame(MainPage)).pack(side="left")
            tk.Button(bottomFrame, text="Visualizar a tabela dos grupos",
                      command=lambda: master.switch_frame(PageThree)).pack(side="right")
            f = Figure(figsize=(5,4), dpi=100)
            a = f.add_subplot(111)

            x=[groups["class1"]["startingValue"]]
            y=[0,]

            i=0

            while True:
                tmpString = "class" + str(i+1)
                y.append(groups[str(tmpString)]["fi"])
                x.append(groups[str(tmpString)]["xi"])

                i+=1
                if (i == (preGroupValues["K"])):
                    break
            x.append(groups[str(tmpString)]["finishingValue"])
            y.append(0)
            a.hist(rol, bins=preGroupValues["K"], edgecolor="black")
            a.plot(x,y, color="red")

            canvas = FigureCanvasTkAgg(f,self)
            a.set_title("Histograma de classes")
            a.set_xlabel("Classes")
            a.set_ylabel("Frequência")
            canvas.draw()
            canvas.get_tk_widget().pack()

    class PageThree(tk.Frame):
        def __init__(self, master):
            tk.Frame.__init__(self, master)
            heading = tk.Label(self,text="Tabela de grupos", bg="green", fg="white", width="1000", height="3", font="20")
            heading.pack()
            bottomFrame = tk.Frame(self)
            bottomFrame.pack(side="bottom")

            cols = ('Valor inicial', 'Valor final', 'fi', 'fac', 'xi', 'xifi', 'xi²', 'xi²fi')
            listBox = ttk.Treeview(self, columns=cols, show='headings')
            for col in cols:
                listBox.heading(col, text=col)
            listBox.pack()

            for i in (groups):
                for y in (groups[i]):
                    listBox.insert("", "end", values=(groups[i].get("startingValue"), groups[i].get("finishingValue"), groups[i].get("fi"), groups[i].get("fac"), groups[i].get("xi"),groups[i].get("xifi"),groups[i].get("xi2"),groups[i].get("xi2fi")))
                    break

            w, h = app.winfo_screenwidth(), app.winfo_screenheight()
            app.geometry("%dx%d+0+0" % (w, h))

            tk.Button(bottomFrame, text="Retornar para as medidas",
                      command=lambda: master.switch_frame(PageOne)).pack(side="left")
            tk.Button(bottomFrame, text="Retornar para a tela inicial",
                      command=lambda: master.switch_frame(MainPage)).pack(side="left")
            tk.Button(bottomFrame, text="Retornar para o histograma",
                      command=lambda: master.switch_frame(PageTwo)).pack(side="right")

def clearEntry():
    inputTextEntry.delete(0, 'end')

class MainPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        master.geometry("650x500")
        self.winfo_toplevel().title("Calculadora estatística")
        heading = tk.Label(self,text="Bem-vindo", bg="green", fg="white", width="100", height="3", font="20")
        heading.pack()

        inputText = tk.Label(self,text="Insira os números desejados separados por espaços. Ex: '5 10 15 100 200 6'")
        inputText.pack()
        global inputTextVar; inputTextVar = tk.StringVar()

        global inputTextEntry; inputTextEntry = tk.Entry(self,textvariable = inputTextVar, width="100")

        inputTextEntry.pack()

        generateDataButton = tk.Button(self,text="Gerar", width="85", command=dataGenerator)
        generateDataButton.pack()

        ClearInputEntry = tk.Button(self,text="Limpar", width="85", command=clearEntry)
        ClearInputEntry.pack()

if __name__ == "__main__":
    app = MainApp()
    app.mainloop()


"""App"""

import logging
import sys

from django.apps import AppConfig

logger = logging.getLogger(__name__)

class CamerasConfig(AppConfig):
    """App Config"""

    name = 'vision_on_edge.cameras'

    def ready(self):
        """App ready

        Import signals and create some demo objects.
        """

        if 'runserver' in sys.argv:
            # pylint: disable=C0415
            from .models import Camera
            from ..locations.models import Location
            # pylint: enable=C0415

            logger.info("App ready ready while running server")

            create_demo = True

            if create_demo:
                logger.info("Creating a demo camera object.")
                # Demo Location should be created already
                demo_locations = Location.objects.filter(is_demo=True)
                if not demo_locations.exists():
                    return
                Camera.objects.update_or_create(
                    name="Demo Video",
                    is_demo=True,
                    defaults={
                        'rtsp': 'sample_video/video.mp4',
                        'area': "",
                        'location': demo_locations.first()
                    })

                logger.info("Creating demo objects... end")

            logger.info("App ready end while running server")


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer

#Carregando a base de dados de treino e teste
treino = pd.read_csv('train.csv')
teste = pd.read_csv('test.csv')

#Array de colunas que nao existem no teste
colunasInexistentesTest = []

#Buscando as colunas que existem no treino mais nao existem no teste
for coluna in treino.columns:
    result = list(filter(lambda x:  x==coluna ,teste.columns))
    if not result:
        colunasInexistentesTest.append(coluna)

#Linha da nota de matematica
del(colunasInexistentesTest[69])

#Plotagem dos dados e suas correlacoes
corr = treino.corr()
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(corr,cmap='coolwarm', vmin=-1, vmax=1)
fig.colorbar(cax)
ticks = np.arange(0,len(treino.columns),1)
ax.set_xticks(ticks)
plt.xticks(rotation=90)
ax.set_yticks(ticks)
ax.set_xticklabels(treino.columns)
ax.set_yticklabels(treino.columns)
plt.show()

#Apagando as colunas de treino que nao existem no teste e outras que nao tem correlacao com a target
treino = treino.drop(colunasInexistentesTest, axis=1)
colunasNaoImportantes = ["NU_INSCRICAO","SG_UF_RESIDENCIA", "CO_PROVA_CN", "CO_PROVA_CH",
                         "CO_PROVA_LC", "CO_PROVA_MT", "Q027",  "CO_UF_RESIDENCIA", "NU_IDADE",
                         "TP_COR_RACA", "TP_NACIONALIDADE", "TP_ST_CONCLUSAO", "TP_ANO_CONCLUIU",
                         "TP_ESCOLA", "TP_ENSINO", "TP_DEPENDENCIA_ADM_ESC", "IN_BAIXA_VISAO",
                         "IN_CEGUEIRA", "IN_SURDEZ", "IN_DISLEXIA", "IN_DISCALCULIA", "IN_SABATISTA",
                         "IN_GESTANTE","IN_IDOSO", "TP_PRESENCA_CN", "TP_PRESENCA_CH", "TP_PRESENCA_LC",
                         "TP_LINGUA", "TP_STATUS_REDACAO"]
for k in colunasNaoImportantes:
    treino = treino.drop(k, axis=1)
    teste = teste.drop(k, axis=1)

#Remocao dos valores faltantes
#teste
row = list(teste.isnull().any(axis=1))
idxx = [i for i, j in enumerate(row) if j is True]
teste = teste.drop(idxx)

#Nvalores faltantes, substituindo por -1
imputer = SimpleImputer(strategy='constant', fill_value = -1)
treino = imputer.fit_transform(treino)
treino = pd.DataFrame(data = treino)

#Transformando colunas categoricas em numericas
ct = ColumnTransformer(transformers = [('encoder', OneHotEncoder(), [0, 12,13,14,15,16,17,18])], remainder='passthrough')
treino = ct.fit_transform(treino)
treino = pd.DataFrame(data = treino)
treino.rename(columns = {54: "NU_MT"}, inplace=True)

ct2 = ColumnTransformer(transformers = [('encoder', OneHotEncoder(), [0, 11,12,13,14,15,16,17])], remainder='passthrough')
teste = ct2.fit_transform(teste)
teste = pd.DataFrame(data = teste)

#Parametrizacao
copia = treino['NU_MT']
treino["NU_NOTA_MT"] = copia
treino = treino.drop('NU_MT', axis=1)
base = treino
_, a = base.shape
atributos = base.iloc[:, 0:a - 1].values
classe = base.iloc[:, a - 1].values

#Faz o treinamento com regressao linear
regressor = LinearRegression()
regressor.fit(atributos, classe)

#Predicao do arquivo de teste
resultados = regressor.predict(teste)


import json
import os
import sys
import requests

def abort(message):
    print('Error:{}'.format(message))
    sys.exit(1)

def shaping_text(text):
    # ファイル名に使えない文字を除外
    invalid_chars = u'\\/:*?"<>|'
    for invalid_char in invalid_chars:
        shaping_text = text.replace(invalid_char, u'')
    return shaping_text

def get(url, params, headers):
    get_query = requests.get(url, params=params, proxies=proxies, headers=headers)
    return get_query

def print_response(query_data, title=''):
    c = query_data.status_code
    h = query_data.headers
    print('{} Response={}, Detail={}'.format(title,c,h))

# エラーコード出たときの処理
def assert_response(query_data, title=''):
    error_code = query_data.status_code
    h = query_data.headers
    if error_code < 200 or error_code > 299:
        error_message = '{} Response={}, Detail={2}'.format(title,c,h)
        print(error_message)

class Article:
    def __init__(self, response_data):
        self._title      = response_data['title']
        self._html_body  = response_data['rendered_body']
        self._md_body    = response_data['body']
        self._tags       = response_data['tags']
        self._created_at = response_data['created_at']
        self._updated_at = response_data['updated_at']
        self._url        = response_data['url']
        user             = response_data['user']
        self._userid     = user['id']
        self._username   = user['name']

    def save_as_markdown(self):
        title = shaping_text(self._title)
        body  = self._md_body
        filename = '{}.md'.format(title)
        fullpath = os.path.join(MYDIR, filename)
        with open(fullpath, 'w') as f:
            f.write(body)

MYDIR = os.path.abspath(os.path.dirname(__file__)) + '/QiitaArticles'

headers = {
    'content-type'  : 'application/json',
    'charset'       : 'utf-8',
    'Authorization' : 'Bearer {0}'.format('token')
}

url = 'https://qiita.com/api/v2/authenticated_user/items'
params = {
    'page'     : 1,
    'per_page' : 100,
}

qiita_article_data = get(url, params, headers)
assert_response(qiita_article_data)
print_response(qiita_article_data)

items = qiita_article_data.json()
print('{} entries.'.format(len(items)))
for i, item in enumerate(items):
    print('{} saving...'.format(i+1, len(items)))
    article = Article(item)
    article.save_as_markdown()


# coding: utf-8
import skvideo.io
import numpy as np
from PIL import Image
import os
import json

def extract_video_frame(video_file_path="/disk/ZhiJiang_VideoQA_Pytorch/data/processed/video/", extract_image_path="/disk/video_qa_B_40/"):
    """
    extract video frames to images
    """
    split_dict = {}
    if not os.path.exists(extract_image_path):
        os.mkdir(extract_image_path)
    files = os.listdir(video_file_path)
    a = len(files)
    b = 1
    for f in files:
        try:
            split_dict[f.split('.mp4')[0]] = []
            video_data = skvideo.io.vread(os.path.join(video_file_path ,f))
            length = len(video_data)
            j = 1
            for i in list(list(np.linspace(0, length-1, num=40, endpoint=True, retstep=False, dtype=np.int64))):
                img = Image.fromarray(video_data[i])
                img.save(os.path.join(extract_image_path, f.split(".mp4")[0] + "_" + str(j) + ".png"), "PNG")
                split_dict[f.split('.mp4')[0]].append(f.split(".mp4")[0] + "_" + str(j) + ".png")
                j += 1
            print(str(b) + "/" + str(a))
            b += 1

        except ValueError:
            print(f)

    json.dump(split_dict, open('../data/processed/video_img_split.json', 'w'))

if __name__ == '__main__':
    extract_video_frame()


import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go

import numpy as np

app = dash.Dash()

x = np.linspace(0, 2, num=100)

app.layout = html.Div(
    [
        dcc.Graph(id='graph'),
        dcc.Slider(id='scale', value=x[0], min= min(x), max = max(x), step=x[1]-x[0])
    ]
)

@app.callback(Output('graph','figure'),[Input('scale','value')])
def update(until):
    y = - x * np.log(x)

    xx, yy = x[x<until], y[x<until]

    return {
        'data': [   go.Scatter(x=x,y=y),
                    go.Scatter(x=xx,y=yy, fill='tozeroy')
                ],
        'layout' : go.Layout(
            xaxis={'title': 't'},
            yaxis={'title': 'magnitude'}
        )
    }

if __name__ == '__main__':
    app.run_server()