#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
 @copyright: (c) ALSTOM Grid a GE Company / Power Electronic Systems Stafford.
 This File and any Information or Descriptive Matter set out herein are the
 Confidential and Copyright Property of ALSTOM Power Electronic Systems
 and must not be Disclosed, Loaned, Copied or Used for
 Manufacturing, Tendering or for any other purpose without their written
 permission.

 @note:   SV Checker class
          Following variables needs to be modified based on the file:

          SAMPLES_PER_FRAME: number of samples available for each frame
          START_SV_PACKET: set to 38 if sample values start from address 0x0038 on each frame
                           set to 46 if sample values start from address 0x0040 on each frame
 @author: Ganesh
 @since:  15 Jul 2017
-------------------------------------------------------------------------------
"""

import sys, csv

#UPDATE below variables based
createAllFiles = True
comparisonDict = {13:-5.98,14:-1.99,15:1.6,16:5.0}
SAMPLES_PER_FRAME=8 #6/40
START_SV_PACKET= 38#40/38/46 original

class SVFile:
    def __init__(self, fileName, allResults):
        self._inputFilePtr = open(fileName, "rb")
        if self._inputFilePtr == None:
            sys.exit(0)
        self._offset = 0
        self.csvFile = open(allResults,"w", newline='')
        if self.csvFile == None:
            sys.exit(0)
        else:
            self.csvLogger = csv.writer(self.csvFile, delimiter=',')

        self.WIRESHARK_HEADER_SIZE=264
        self.ETHERNET_HEADER_SIZE=32
        self.SV_TYPE = 35002 #0x88BA
        self.ARP_TYPE = 2054 #0x0806
        self.EAPOL_TYPE = 34958 #888E
        self.IP_TYPE = 2048 #0x0800
        self.SSDP_TYPE = 1900 #0x076C
        self.BROWSER_TYPE=138 #008A
        self.NBNS_SUBTYPE = 137 #0089
        self.ETH_TPID = 33024 #0x8100
        self.DHCP_TYPE = 67 #0x0043
        self.MDNS_TYPE = 5353 #0x14E9
    def read(self, lengthBytes):
        value = self._inputFilePtr.read(lengthBytes)
        self._offset = self._offset + lengthBytes
        if value == b'':
            #End of file, exit
            self.csvFile.close()
            self._inputFilePtr.close()
            sys.exit(0)
        return value
    def skipWireSharkHeader(self):
        self.skip (self.WIRESHARK_HEADER_SIZE)
    def skip (self, count):
        self.read (count)
    def readWord (self):
        return self.read(4)
    def writeCsvHeader(self):
        list1 = ['Frame']
        for i in range(0, SAMPLES_PER_FRAME):
            list1.append('Value')
            list1.append('Quality')
            list1.append('ConvertedValue')
        self.csvLogger.writerow(list1)

    def skipEthernetHeader(self):
        self.skip(self.ETHERNET_HEADER_SIZE)

    def checkFrame(self, franeCount):
        print ("Packet starts at:" + str(self._offset))
        #skip MAC addreesses 2 * 6 = 12 bytes
        self.skip(12)
        #get Ethernet Type
        bytesType = self.read(2)
        type = int.from_bytes(bytesType,'big',signed=False)

        if type == self.IP_TYPE:
            appId = int.from_bytes(self.read(2),'big',signed=False)
            if appId == 17920:
                size = int.from_bytes(self.read(2),'big',signed=False)
                self.skip(size - 2)
                return

            #Not a SV datagram, skip it
            self.skip(20)
            byteSubtype = self.read(2)
            subtype = int.from_bytes(byteSubtype,'big',signed=False)
            if (subtype == self.SSDP_TYPE or subtype == self.BROWSER_TYPE):
                #Next two bytes is the lenght
                sizeBytes = self.read(2)
                size = int.from_bytes(sizeBytes,'big',signed=False)
                print ("SV frame size is:" + str(size))
                self.skip(size - 5)
            elif (subtype == self.NBNS_SUBTYPE):
                #Next two bytes is the lenght
                sizeBytes = self.read(2)
                size = int.from_bytes(sizeBytes,'big',signed=False)
                print ("SV frame size is:" + str(size))
                self.skip(size - 4)
            elif subtype == self.DHCP_TYPE:
                #Next two bytes is the lenght
                sizeBytes = self.read(2)
                size = int.from_bytes(sizeBytes,'big',signed=False)
                print ("SV frame size is:" + str(size))
                self.skip(size - 6)
            elif subtype == self.MDNS_TYPE:
                #Next two bytes is the lenght
                sizeBytes = self.read(2)
                size = int.from_bytes(sizeBytes,'big',signed=False)
                print ("SV frame size is:" + str(size))
                self.skip(30)
                domainName = int.from_bytes(self.read(2),'big',signed=False)
                if domainName == 12:
                    self.skip(size-30-2-4)
                else:
                    self.skip(size-30-2-5)

            else:
                #Next two bytes is the lenght
                sizeBytes = self.read(2)
                size = int.from_bytes(sizeBytes,'big',signed=False)
                print ("SV frame size is:" + str(size))
                self.skip(size - 4)

        elif type == self.ARP_TYPE:
            self.skip(30)

        elif type == self.EAPOL_TYPE:
            self.skip(6)

        elif type == self.SV_TYPE:
            #get the appId
            bytesAppId = self.read(2)
            appId = int.from_bytes(bytesAppId,'big',signed=False)
            print ("APPID is:" + str(appId))
            #SV packet
            #Next two bytes is the lenght
            sizeBytes = self.read(2)
            size = int.from_bytes(sizeBytes,'big',signed=False)
            print ("SV frame size is:" + str(size))
            #skip start of packet:
            self.skip(START_SV_PACKET)
            #self.skip(size - 46 + 28)
            samValueFrameCount = 0
            carryOn = True
            list1=[frameCount]
            while carryOn and samValueFrameCount < SAMPLES_PER_FRAME:
                samValueFrameCount = samValueFrameCount + 1
                value = self.readWord()
                quality = self.readWord()
                if quality is None or value is None:
                    carryOn = False
                    break

                intValue = int.from_bytes(value,'big',signed=True)
                list1.append(intValue)
                intQuality = int.from_bytes(quality,'big',signed=True)
                list1.append(intQuality)
                convertedValue = (intValue * 10) / (2**31)
                list1.append(convertedValue)
            #Log into Results file
            self.csvLogger.writerow(list1)
        else:
            #Not a SV datagram, skip it
            #get the appId
            bytesAppId = self.read(2)
            appId = int.from_bytes(bytesAppId,'big',signed=False)
            print ("APPID is:" + str(appId))
            #SV packet
            #Next two bytes is the lenght
            sizeBytes = self.read(2)
            size = int.from_bytes(sizeBytes,'big',signed=False)
            print ("SV frame size is:" + str(size))
            if size > 0:
                self.skip(size - 2)
            elif size == 0:
                print ("ZERO SIZED DATAGRAM")
            else:
                raise Exception ("Negative packet size")

if __name__ == '__main__':
    fileName = sys.argv[1]
    try:
        allRes = sys.argv[2]
    except Exception as err:
        allRes = "AllResults.csv"
    print (fileName)
    #try:
    svFile = SVFile(fileName,allRes)

    if createAllFiles:
        svFile.writeCsvHeader()

    svFile.skipWireSharkHeader()
    frameCount=0
    while(True):
        svFile.skipEthernetHeader()
        frameCount=frameCount+1
        svFile.checkFrame(frameCount)
        print(frameCount)


from os import getenv
from flask import Flask
from flasgger import Swagger
from jaeger_client import Config
from flask_opentracing import FlaskTracer
from opentracing_instrumentation.client_hooks import install_all_patches
import logging

JAEGER_HOST = getenv('JAEGER_HOST', 'localhost')

FLASK_TRACER = None

def create_app():

    # instantiate the app
    swagger_config = {
        "headers": [
        ],
        "specs": [
            {
                "endpoint": 'swagger',
                "route": '/swagger.json',
                "rule_filter": lambda rule: True,  # all in
                "model_filter": lambda tag: True,  # all in
            }
        ],
        "static_url_path": "/flasgger_static",
        # "static_folder": "static",  # must be set by user
        "specs_route": "/swagger/"
    }

    app = Flask(__name__)
    app.config['SWAGGER'] = {
            "swagger": "3.0",
            'uiversion': "3",
            "info": {
                "title": "BevRand Playlist Api",
                "version": "1.0"

            }
    }
    Swagger(app, config=swagger_config)

    log_level = logging.DEBUG
    logging.getLogger('').handlers = []
    logging.basicConfig(format='%(asctime)s %(message)s', level=log_level)

    config = Config(config={'sampler': {'type': 'const', 'param': 1},
                            'logging': True,
                            'local_agent':
                            # Also, provide a hostname of Jaeger instance to send traces to.
                                {'reporting_host': JAEGER_HOST}},
                    # Service name can be arbitrary string describing this particular web service.
                    service_name="playlist-api")

    jaeger_tracer = config.initialize_tracer()
    tracer = FlaskTracer(jaeger_tracer)
    global FLASK_TRACER
    FLASK_TRACER = tracer
    install_all_patches()

    # set config
    env = getenv('APP_SETTINGS')
    if env is None:
        env = 'Test'
    app_settings = 'api.config.' + env
    app.config.from_object(app_settings)

    # register blueprints
    from api.controllers.frontpage_controller import users_blueprint
    app.register_blueprint(users_blueprint)

    return app


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

u'''
перевести все мерные длины из дюймов(in) в миллиметры(mm). Например: 10in -> 254mm
28147326av 100in 205in\naim in 0in 5IN man
'''

from __future__ import print_function
from sys import stdin, stdout
from string import *

def cs(w):
    return str(int(round(25.4 * int(w[:-2], base=10)))) + 'mm'

def work_ok(w):
    if w[0] in '-+':
        w = w[1:]
    return len(w) > 2 and w[-1] == 'n' and w[-2] =="i" and all(c in digits for c in w[:-2])

for line in stdin:
    words = [w for w in line.strip().split() if len(w.strip()) > 0]
    words = [w for w in words if work_ok(w)]
    if len(words) > 0:
        print(' '.join(str(cs(word)) for word in words))


from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import ContactForm
from django.core.mail import send_mail

# Create your views here.
def home(request):
    return render(request, 'main/index.html')

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            messages = 'Message:'+message+' From:' +name +' E-mail:'+email
            authorization = '369684297@qq.com'
            recipient_list = ['369684297@qq.com']
            send_mail(subject, messages, authorization, recipient_list, fail_silently=False)
            return HttpResponseRedirect('/contact-us/')
    else:
        form = ContactForm()
        return render(request, 'main/contact-us.html', {'form': form})

def about(request):
    return render(request, 'main/about-me.html')


from os import read

from Command import Command, MissionDownlinkCommand

class Command_Parser():
    def __init__(self):
        pass

    def parse(self, read_command):

        # Debug to check ascii code of each char in string
        # print(f"read command is {[ord(c) for c in read_command]}")

        # If empty command
        if len(read_command) == 0:
            return Command("blank")

        list_read = read_command.split(' ')

        if "md" in list_read:
            mission_type = list_read[0]
            start_timestamp = list_read[1]
            num = list_read[2]
            interval = list_read[3]
            down_timestamp = list_read[4]

            try:
                parsed_command = MissionDownlinkCommand(
                    mission_type, num, interval, start_timestamp, down_timestamp)
            except ValueError:
                parsed_command = Command("unknown")

        else:
            parsed_command = Command("unknown")

        return parsed_command


import requests
from bs4 import BeautifulSoup
import time
from multiprocessing import Pool
import os

def download(img, h):
    name = img.split('/')[-1].replace('%', '')
    if os.path.exists('G:\\Pictures\\h\\' + name) and h is True:
        print("The file has existed")
    elif os.path.exists('G:\\Pictures\\yande\\' + name) and h is False:
        print("The file has existed")
    else:
        try:
            imgdata = requests.get(img)
            if not h:
                filepath = 'G:\\Pictures\\yande\\{}'.format(name)
                with open(filepath, 'wb') as code:
                     code.write(imgdata.content)
                code.close()
                print("Download the normal picture.........................ok")
            else:
                filepath = 'G:\\Pictures\\H\\{}'.format(name)
                with open(filepath, 'wb') as code:
                    code.write(imgdata.content)
                code.close()
                print("Download the h picture .........................ok")
        except:
            fp = open('G:\\Pictures\\yande\\yande.log', 'a')
            fp.writelines("[wrong]pic:" + img + "\n")
            fp.close()

def get_pic(pic_url):
    try:
        picData = requests.get(pic_url)
        PicSoup = BeautifulSoup(picData.text, 'lxml')
        PicContent = PicSoup.select('div.sidebar > div:nth-of-type(4) > ul > li')
        ifH = PicSoup.find_all("script", type="text/javascript")[5]
        if '"rating":"e"' in str(ifH):
            h = True
        else:
            h = False
        for pic in PicContent:
            title = pic.text
            if("Image" in title):
                img = pic.select('a')[0].get('href')
            if("Download larger version" in title):
                img = pic.select('a')[0].get('href')
            if ("Download PNG" in title):
                img = pic.select('a')[0].get('href')
        download(img, h)
        fp = open('G:\\Pictures\\yande\\yande.log', 'a')
        fp.writelines(time.asctime(time.localtime(time.time()))+":picture:" + pic_url + "..........................."
                                                                                ".....OK\n")
        fp.close()
    except Exception as e:
        print(str(e))
        fp = open('G:\\Pictures\\yande\\yande.log', 'a')
        fp.writelines(time.asctime(time.localtime(time.time()))+":[wrong-pic-url]:" + pic_url + "\n")
        fp.close()

def get_url(url):
    pic_urls = []
    try:
        urldata = requests.get(url)
    except Exception as e:
        print(str(e))
        fp = open('G:\\Pictures\\yande\\yande.log', 'a')
        fp.writelines(time.asctime(time.localtime(time.time())) + ":[wrong-singeUrl]:" + url + "\n")
        fp.close()
        return
    soup = BeautifulSoup(urldata.text, 'lxml')
    pic_url = soup.select('a.thumb')
    for picHref in pic_url:
        picHref = "https://yande.re" + picHref.get('href')
        pic_urls.append(picHref)
    pool = Pool()
    pool.map(get_pic, pic_urls)
    pool.close()
    pool.join()

def main():
    url = ["https://yande.re/post?page={}".format(str(i)) for i in range(161, 200)]
    for singleurl in url:
        get_url(singleurl)

if __name__ == "__main__":
    main()


#!/bin/python

import sat_parse
import sat_solve

def getSolver(str_expr):
    stree = sat_parse.parse(str_expr)
    return sat_solve.solver(stree)

def printVarNames(ass):
    res = "| "
    for k in ass:
        res += str(k) + " | "

    print(res)

def printLine(ass):
    res = "+"
    for k in ass:
        res += "-" * (len(k) + 2) + "+"
    print(res)

def printAssignment(ass):
    res = "| "
    for k in ass:
        if (ass[k]):
            bnum = "1"
        else:
            bnum = "0"
        res += bnum.rjust(len(k)) + " | "
    print(res)

def printAllModels(str_expr):
    firstFind = True
    for model in getSolver(str_expr).getModel():
        if (firstFind):
            firstFind = False
            printVarNames(model)
            printLine(model)

        printAssignment(model)
    if (firstFind):
        print("Not satisfiable")

if __name__ == "__main__":
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    for i in range(5, len(alphabet)):
        print(i)
        usedAlphabet = alphabet[:i]
        ands = "&" * (len(usedAlphabet) - 1)
        printAllModels(ands + usedAlphabet)


import ezodf
import pprint
from logzero import logger

class ReadSheet:
    def __init__(self, spreadsheet_path):
        self.sheet_path = spreadsheet_path
        self.spreadsheet = None
        logger.debug('Opening spreadsheet %s', self.sheet_path)

    def read_cc_sheet(self):
        # Numberical input = [COLUMN, ROW]
        # Returns dict of CC names in format:
        # {
        #     'bank1: [cc1 name, cc2 name, etc],
        #       ...
        #     'bank8: [cc1 name, cc2 name, etc],
        # }
        # from a specified spreadsheet in .ods format. Use carbonite_cc_name_template.ods.

        logger.debug('Reading rosstalk custom control spreadsheet: %s', self.sheet_path)
        self.spreadsheet = ezodf.opendoc(self.sheet_path)
        sheet = self.spreadsheet.sheets['Sheet1']

        cc_data = {}

        banks = 8
        for bank in range(1, banks+1):
            bank_name = 'bank' + str(bank)
            bank_data = []
            for cc in range(1, 33):
                bank_data.append(sheet[cc, bank].value)

            cc_data.update({bank_name: bank_data})
        logger.debug('Got sheet data: %s', cc_data)
        return cc_data

    def read_lbl_file(self):  # reads a nk .lbl sheet, outputs a dict>list containing names of each input/output
        logger.debug('reading nk lbl sheet: %s', self.sheet_path)

        inputs = []
        outputs = []

        with open(self.sheet_path) as f:
            for line in f.readlines():
                outputs.append(line.split(',')[1])  # outputs
                inputs.append(line.split(',')[3])  # inputs

        io = {
            'inputs': inputs,
            'outputs': outputs
        }

        return io

if __name__ == '__main__':
    pprint.pprint(ReadSheet('2021_05_11.lbl').read_lbl_file())


# Vehicle Telemetry System for Aston University Shell Eco Marathon Team
#
# Rev 9
# To be used with Arduino sketch above v14
#
# Contact:
# Edward Hull
# ed.n.hull@gmail.com
# hulle@aston.ac.uk
# Msc Software Engineering Major Project
# 104308055
#

from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
import time
import pyqtgraph.functions as fn
import serial
import sys

win = None

def display():
    global win
    xMin = 0
    xMax = 60
    yMin = 0
    yMax = 30
    xDelta = 0.02

    app = QtGui.QApplication.instance()
    if app is None:
        pg.setConfigOption( 'background', 'k')
        pg.setConfigOption( 'foreground', 'w')
        app = pg.mkQApp()

    if win is None:
        win = pg.GraphicsWindow(title="Aston University - Shell Eco Marathon")
        win.resize(1600,1200)
    win.clear()

        #win = pg.GraphicsLayoutWidget()
    #win.setBackground( QtGui.QBrush(QtGui.QColor(240,240,240)))
    win.addLabel( "Vehicle Telemetry", row = 1, col = 1, colspan=2, bold=True, size='20pt')
    win.addLabel( "Fuel Cell", row = 1, col = 3, colspan=1, bold=True, size='20pt')

    speed_graph = win.addPlot( row=2, col=1, colspan=2, rowspan=3)
    speed_graph.showGrid( x = True, y = True)
    speed_graph.setTitle( title = "Speed (MPH)")
    speed_graph.setLabel( 'left', 'MPH')
    speed_graph.setLabel( 'bottom', 'Time (Seconds)')
    speed_graph.setXRange( xMin - 0.25, xMax + 0.25)
    speed_graph.showButtons()
    speed_graph.enableAutoRange('y', True)
    speed_graph.enableAutoRange('x', True)
    lr = pg.LinearRegionItem([20,40], movable=True,)
    lr.setZValue(-10)
    speed_graph.addItem(lr)

    average_graph = win.addPlot( row=5, col=1, rowspan=2)
    average_graph.showGrid( x = True, y = True)
    average_graph.setTitle(title = "Average Speed (MPH)")
    average_graph.setLabel( 'left', 'MPH')
    average_graph.setLabel( 'bottom', 'Time')
    average_graph.enableAutoRange( x = True, y = True)
    average_graph.setXRange( xMin - 0.25, xMax + 0.25)
    average_graph.enableAutoRange('y', True)
    average_graph.enableAutoRange('x', True)
    #lr = pg.LinearRegionItem(average_graph.getViewBox().viewRange()[0], movable=True,)
    lr.setZValue(-10)

    dist_graph = win.addPlot( row=5, col=2, rowspan=2)
    dist_graph.showGrid( x = True, y = True)
    dist_graph.setTitle( title = "Distance covered (Meters)")
    dist_graph.setLabel( 'left', 'M')
    dist_graph.setLabel( 'bottom', 'Time')
    dist_graph.enableAutoRange( x = True, y = True)
    dist_graph.setXRange( xMin - 0.25, xMax + 0.25)
    dist_graph.enableAutoRange('y', True)
    dist_graph.enableAutoRange('x', True)

    power_graph = win.addPlot( row=2, col=3, colspan=1)
    power_graph.showGrid( x = True, y = True)
    power_graph.setTitle( title = "Power")
    power_graph.setLabel( 'left', 'Watts')
    power_graph.setLabel( 'bottom', 'Time')
    power_graph.setXRange( xMin - 0.25, xMax + 0.25)
    power_graph.setRange(yRange=(50,1000))
    power_graph.showButtons()
    #power_graph.enableAutoRange('y', True)
    power_graph.enableAutoRange('x', True)

    stackcurrent_graph = win.addPlot( row=3, col=3, colspan=1)
    stackcurrent_graph.showGrid( x = True, y = True)
    stackcurrent_graph.setTitle( title = "Stack Current")
    stackcurrent_graph.setLabel( 'left', 'Amps')
    stackcurrent_graph.setLabel( 'bottom', 'Time')
    stackcurrent_graph.setXRange( xMin - 0.25, xMax + 0.25)
    stackcurrent_graph.setRange(yRange=(10,65))
    stackcurrent_graph.showButtons()
    #stackcurrent_graph.enableAutoRange('y', True)
    stackcurrent_graph.enableAutoRange('x', True)

    stackvoltage_graph = win.addPlot( row=4, col=3, colspan=1)
    stackvoltage_graph.showGrid( x = True, y = True)
    stackvoltage_graph.setTitle( title = "Stack Voltage")
    stackvoltage_graph.setLabel( 'left', 'Volts')
    stackvoltage_graph.setLabel( 'bottom', 'Time')
    stackvoltage_graph.setXRange( xMin - 0.25, xMax + 0.25)
    stackvoltage_graph.setRange(yRange=(25,55))
    stackvoltage_graph.showButtons()
    #stackvoltage_graph.enableAutoRange('y', True)
    stackvoltage_graph.enableAutoRange('x', True)

    stacktemperature_graph = win.addPlot( row=5, col=3, colspan=1)
    stacktemperature_graph.showGrid( x = True, y = True)
    stacktemperature_graph.setTitle( title = "Stack Temperature")
    stacktemperature_graph.setLabel( 'left', 'Celcius')
    stacktemperature_graph.setLabel( 'bottom', 'Time')
    stacktemperature_graph.setXRange( xMin - 0.25, xMax + 0.25)
    stacktemperature_graph.setRange(yRange=(20,55))
    stacktemperature_graph.showButtons()
    #stacktemperature_graph.enableAutoRange('y', True)
    stacktemperature_graph.enableAutoRange('x', True)

    batteryvoltage_graph = win.addPlot( row=6, col=3, colspan=1)
    batteryvoltage_graph.showGrid( x = True, y = True)
    batteryvoltage_graph.setTitle( title = "Battery Voltage")
    batteryvoltage_graph.setLabel( 'left', 'Volts')
    batteryvoltage_graph.setLabel( 'bottom', 'Time')
    batteryvoltage_graph.setXRange( xMin - 0.25, xMax + 0.25)
    batteryvoltage_graph.setRange(yRange=(12,18))
    batteryvoltage_graph.showButtons()
    #batteryvoltage_graph.enableAutoRange('y', True)
    batteryvoltage_graph.enableAutoRange('x', True)

    def updatePlot():
        average_graph.setXRange(*lr.getRegion(), padding=0)
        dist_graph.setXRange(*lr.getRegion(), padding=0)
        power_graph.setXRange(*lr.getRegion(), padding=0)
        stackcurrent_graph.setXRange(*lr.getRegion(), padding=0)
        stackvoltage_graph.setXRange(*lr.getRegion(), padding=0)
        stacktemperature_graph.setXRange(*lr.getRegion(), padding=0)
        batteryvoltage_graph.setXRange(*lr.getRegion(), padding=0)
    def updateRegion():
        lr.setRegion(average_graph.getViewBox().viewRange()[0])

    win.addLabel( "Speed", row = 7, col = 1, colspan=1, bold=False, italic=True, size='12pt', color='3333FF')
    win.addLabel( "Average", row = 8, col = 1, colspan=1, bold=False, italic=True, size='12pt', color='FF1919')
    win.addLabel( "Dist", row = 9, col = 1, colspan=1, bold=False, italic=True, size='12pt', color='00CC00')

    win.addLabel( "Serial device: " + serialDev, row = 7, col = 2, colspan=1, bold=False, italic=False, size='12pt', color='CCFF00')
    win.addLabel( "Fuel Cell Status: ", row = 8, col = 2, colspan=1, bold=False, italic=False, size='12pt', color='CCFF00')
    win.addLabel( "Currently saving to SD card: ", row = 9, col = 2, colspan=1, bold=False, italic=False, size='12pt', color='CCFF00')

    win.addLabel( "Power: ", row = 7, col = 3, colspan=1, bold=False, italic=True, size='12pt', color='CCFF00')
    win.addLabel( "Stack Current: ", row = 8, col = 3, colspan=1, bold=False, italic=True, size='12pt', color='CCFF00')
    win.addLabel( "Stack Voltage: ", row = 9, col = 3, colspan=1, bold=False, italic=True, size='12pt', color='CCFF00')
    win.addLabel( "Stack Temperature: ", row = 10, col = 3, colspan=1, bold=False, italic=True, size='12pt', color='CCFF00')
    win.addLabel( "Battery Voltage: ", row = 11, col = 3, colspan=1, bold=False, italic=True, size='12pt', color='CCFF00')

    millis_array = []
    speed_array = []
    average_array = []
    dist_array = []
    power_array = []
    stackcurrent_array = []
    stackvoltage_array = []
    stacktemperature_array = []
    batteryvoltage_array = []
    ambienttemperature_array = []
    stackstatus_array = []
    incomingDataArray = []
    lastSpeed = 0
    lastAverageSpeed = 0
    lastDistCovered = 0
    lastPower = 0
    lastCurrent = 0
    lastStackVoltage = 0
    lastStackTemperature = 0
    lastBatteryVoltage = 0
    lastAmbientTemperature = 0
    lastStackStatus = 0
    fuelCellStatus = -1
    p = 0
    firstReading = True
    fuelCellStatusOutput = "UNKNOWN"

    while True:
        updatePlot()
        data = ser.readline().rstrip().decode("utf-8")
        if len(data) > 0: # If data has been received

            incomingDataArray = data.split(';')

            # System uptime in milliseconds, distance, speed, averagespeed, Power(watts), Current(amps), Stackvoltage(volts), Stacktemperature (Celcius), Batteryvoltage(volts), AmbientTemperature(Celcius), StackStatus ,SavingToSDCard(True/False),
            if len(incomingDataArray) == 12: # Check to see if data was received in-tact

                #print('Rx data : ' + ', '.join(incomingDataArray))
                if firstReading == True:
                    firstReading = False
                    lr = pg.LinearRegionItem([(float(incomingDataArray[0])/1000)-4,(float(incomingDataArray[0])/1000)+4], movable=True,)

                currentMillis = (float(incomingDataArray[0])/1000)
                millis_array.append(currentMillis)

                ## Attempt to clear graph
                if currentMillis < millis_array[-1] :
                    millis_array[:] = []
                    speed_array[:] = []
                    speed_graph.plot(x=0, y=0, pen=( 0, 0, 255), fillLevel=0, brush=(50,50,200,50))
                    speed_graph.clear()

                lastSpeed = float(incomingDataArray[1])
                #speed_graph.setTitle( title = "Speed (MPH) | Last : " + str(lastSpeed))
                speed_graph.clear()
                speed_graph.addItem(lr)
                speed_array.append(float(incomingDataArray[1]))
                speed_graph.plot(x=millis_array[:p], y=speed_array[:p], pen=( 0, 0, 255), fillLevel=0, brush=(50,50,200,50))
                win.getItem(7,1).setText("Current speed: " + str(lastSpeed) + " mph")

                lastAverageSpeed = float(incomingDataArray[2])
                #average_graph.setTitle(title = "Average Speed (MPH) | Last : " + str(lastAverageSpeed))
                average_array.append(float(incomingDataArray[2]))
                average_graph.clear()
                average_graph.plot( x=millis_array[:p], y=average_array[:p], pen=( 255, 0, 0),fillLevel=0, brush=(200,50,50,50))
                win.getItem(8,1).setText("Moving average speed: " + str(lastAverageSpeed) + " mph")

                lastDistCovered = float(incomingDataArray[3])
                #dist_graph.setTitle( title = "Distance covered (Meters) | Last : " + str(lastDistCovered))
                dist_array.append(float(incomingDataArray[3]))
                dist_graph.clear()
                dist_graph.plot( x=millis_array[:p], y=dist_array[:p], pen=( 0, 255, 0),fillLevel=0, brush=(50,200,50,50))
                win.getItem(9,1).setText("Distance covered: " + str(lastDistCovered) + " meters")

                lastPower = float(incomingDataArray[4])
                power_array.append(float(incomingDataArray[4]))
                power_graph.clear()
                power_graph.plot( x=millis_array[:p], y=power_array[:p], pen=( 55,230,70),fillLevel=0, brush=(55,230,70,50))
                win.getItem(7,3).setText("Power: " + str(lastPower) + "W")

                lastCurrent = float(incomingDataArray[5])
                stackcurrent_array.append(float(incomingDataArray[5]))
                stackcurrent_graph.clear()
                stackcurrent_graph.plot( x=millis_array[:p], y=stackcurrent_array[:p], pen=( 15,125,200),fillLevel=0, brush=(15,125,200,50))
                win.getItem(8,3).setText("Amps: " + str(lastCurrent) + "A")

                lastStackVoltage = float(incomingDataArray[6])
                stackvoltage_array.append(float(incomingDataArray[6]))
                stackvoltage_graph.clear()
                stackvoltage_graph.plot( x=millis_array[:p], y=stackvoltage_array[:p], pen=(205,55,40),fillLevel=0, brush=(205,55,40,50))
                win.getItem(9,3).setText("Volts: " + str(lastStackVoltage) + "v")

                lastStackTemperature = float(incomingDataArray[7])
                stacktemperature_array.append(float(incomingDataArray[7]))
                stacktemperature_graph.clear()
                stacktemperature_graph.plot( x=millis_array[:p], y=stacktemperature_array[:p], pen=(20,65,80),fillLevel=0, brush=(20,65,80,50))
                win.getItem(10,3).setText("Stack Temperature: " + str(lastStackTemperature) + "c")

                lastBatteryVoltage = float(incomingDataArray[8])
                batteryvoltage_array.append(float(incomingDataArray[8]))
                batteryvoltage_graph.clear()
                batteryvoltage_graph.plot( x=millis_array[:p], y=batteryvoltage_array[:p], pen=(255,255,0),fillLevel=0, brush=(50,200,50,50))
                win.getItem(11,3).setText("Battery Voltage: " + str(lastBatteryVoltage) + "v")

                savingToSDCard = incomingDataArray[11]
                if savingToSDCard == '1':
                    savingToSDCard = "Yes"
                else:
                    savingToSDCard = "No"
                win.getItem(9,2).setText("Saving to SD card: " + savingToSDCard)

                fuelCellStatus = incomingDataArray[10]
                if fuelCellStatus == '-1':
                    fuelCellStatusOutput = "UNKNOWN"
                if fuelCellStatus == '0':
                    fuelCellStatusOutput = "OK"
                if fuelCellStatus == '1':
                    fuelCellStatusOutput = "BATTERY LOW"
                if fuelCellStatus == '2':
                    fuelCellStatusOutput = "FC VOLTAGE LOW"
                if fuelCellStatus == '3':
                    fuelCellStatusOutput = "H2% HIGH"
                if fuelCellStatus == '4':
                    fuelCellStatusOutput = "CURRENT HIGH"
                if fuelCellStatus == '5':
                    fuelCellStatusOutput = "TEMPERATURE HIGH"
                if fuelCellStatus == '20':
                    fuelCellStatusOutput = "MANUAL TURN OFF"
                win.getItem(8,2).setText("Fuel Cell Status: " + fuelCellStatusOutput)

                p = p + 1
                #speed_graph.autoRange()
        app.processEvents()

def find_serial():
    passed = len(sys.argv)
    if passed != 2:
        print(passed)
        print('Incorrect number of arguments')
        print('Please pass the serial device as the first argument')
        print('Eg. sudo python3 eco.py /dev/ttyUSB0')
        print('or C:/pythondir/python3.exe eco.py COM1 on Windows')
        sys.exit(1)
    serialDev = str(sys.argv[1])
    return serialDev

def check_serial_device_exists():
	try:
		file = open(serialDev, 'r')
	except IOError:
		print
		print('Could not find/open a serial device at ' + serialDev)
		print('Check file permissions, check radio receiver is plugged in, and check serial device location. Close any existing instances of this application (can accidentally be running with the window closed!)')
		print
		sys.exit(1)

#def get_data():
	#self.data = float(ser.readline().rstrip())
serialDev = find_serial()
print("Using serial device: "+ serialDev)
check_serial_device_exists()
ser = serial.Serial(serialDev, 57600, timeout = 0.1)
display()
exit()


import xml.etree.ElementTree as ET
import nltk
import random
import re
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from itertools import combinations
from nltk.corpus import wordnet as wn
from nltk.translate import bleu
import numpy as np

def checkCorrect(score,ourSentence,correctSentences):
	ourSentence = ourSentence.split()

	highestBleuScore = 0
	for i in correctSentences:
		if i != "":
			correctSentence = i.split()

			bleuScore = nltk.translate.bleu_score.sentence_bleu([correctSentence], ourSentence, weights = [1])

			if bleuScore > highestBleuScore:
				print("correct with Bleu: ", correctSentence, bleuScore)
				highestBleuScore = bleuScore

	return highestBleuScore

def checkAndCleanCorrect(predicateDict, printResults = False):
	i = 0
	subjects = 0
	objects = 0

	correctPredicateDict = {}

	for predicate in predicateDict:
		correctPredicateDict[predicate] = []
		for sentence in predicateDict[predicate]:
			i += 1
			if '$subject$' in sentence:
				subjects += 1
			if '$object$' in sentence:
				objects += 1
			if '$object$' in sentence and '$subject$' in sentence:
				correctPredicateDict[predicate].append(sentence)

	if printResults is True:
		print("documents: ", i)
		print("subjects: ", subjects, round(subjects*100/i, 2))
		print("objects: ", objects, round(objects*100/i, 2))

	return correctPredicateDict

def getDerivatives(word): #not used now
	allForms = []
	synsets = wn.synsets(word)
	# Word not found
	if not synsets:
		return []

    # Get all  lemmas of the word
	lemmas = [l for s in synsets for l in s.lemmas()]

	# Get related forms
	derivationally_related_forms = [l.derivationally_related_forms() for l in lemmas]

	for form in derivationally_related_forms:
		for elem in form:
			if elem.name() not in allForms:
				allForms.append(elem.name())

	return allForms

def rreplace(s, old, new, occurrence):
	li = s.rsplit(old, occurrence)
	return new.join(li)

def replaceObject(Object, sentence):
	return re.sub(Object + '(\s)', '$object$ ', sentence)

def replaceSubject(Subject, sentence):
	return re.sub(Subject + '(\s)', '$subject$ ', sentence)

def replaceToGeneral(sentence, Subject, Object):
	sentence = sentence.lower()
	sentence = re.sub('\.$', ' ', sentence)

	Object = re.sub('"@en', ' ', Object) #Olive oil Potatoes is caused by the @en stuff...

	ObjectWords = Object.split()
	SubjectWords = Subject.split()
	sentenceWords = sentence.split()

	sentence = sentence.replace('u.s', 'united states')
	sentence = sentence.replace('uk', 'united kingdom')

	### FIRST METHOD: Exact replacement
	sentence = replaceSubject(Subject, sentence)
	sentence = replaceObject(Object, sentence)

	### SECOND METHOD: REPLACING LAST COMMA WITH SOMETHING ELSE
	SubjectAnd = rreplace(Subject, ',', ' and', 1)
	ObjectAnd = rreplace(Object, ',', ' and', 1)

	SubjectOr = rreplace(Subject, ',', ' or', 1)
	ObjectOr = rreplace(Object, ',', ' or', 1)

	sentence = replaceSubject(SubjectAnd, sentence)
	sentence = replaceObject(ObjectAnd, sentence)
	sentence = replaceSubject(SubjectOr, sentence)
	sentence = replaceObject(ObjectOr, sentence)

	### THIRD METHOD: Fuzzy replacement
	if '$subject$' not in sentence or '$object$' not in sentence:
		#print(ObjectWords)
		if '$object$' not in sentence:
			fuzzyObject = []
			#loop through all ObjectWords to match words in the sentence
			for ObjectWord in ObjectWords:
				word, score = process.extractOne(ObjectWord, sentenceWords, scorer=fuzz.ratio)
				if score > 80:
					fuzzyObject.append(word)
			#check if anything in this, otherwise it would replace all whitespaces with $object$
			if len(fuzzyObject) > 0:
				sentence = replaceObject(' '.join(fuzzyObject), sentence)

		if '$subject$' not in sentence:
			fuzzySubject = []
			#loop through all SubjectWords to match words in the sentence
			for SubjectWord in SubjectWords:
				word, score = process.extractOne(SubjectWord, sentenceWords, scorer=fuzz.ratio)
				if score > 80:
					fuzzySubject.append(word)

			#check if anything in this, otherwise it would replace all whitespaces with $subject$
			if len(fuzzySubject) > 0:
				sentence = replaceSubject(' '.join(fuzzySubject), sentence)

	#check to find all wrong sentences
	#if '$subject$' not in sentence or '$object$' not in sentence:
		#print(sentence + '\t '+ Object  + '\t '+  Subject)
	#check to find all correct sentences
	#if '$subject$' in sentence and '$object$'  in sentence:
	#	print(sentence + '\t '+ Object  + '\t '+  Subject)
	return sentence

def showPredicateRecall(predicateDict, minimumAmount = 1):
	i = 0
	for predicate in predicateDict:
		if len(predicateDict[predicate]) >= 1:
			i += 1
	print("Out of the {} predicates, {} have at least {} syntactical sentence(s) ".format(len(predicateDict), i, minimumAmount))

def replaceToSpecific(sentence, Subject, Object):
	return sentence.replace('$subject$', Subject).replace('$object$', Object)

def testData(predicateDict):
	bleuScoreList = []

	score = 0
	treeTest = ET.parse('WebNLG/dev/1triples/1triple_allSolutions_Food_dev_challenge.xml')
	rootTest = treeTest.getroot()
	for i in range(20):#range(len(root[0])):
		tripleSet = rootTest[0][i][1][0].text
		Subject   = tripleSet.split('|')[0].strip().lower().replace("_"," ")
		Predicate = tripleSet.split('|')[1].strip()
		Object    = tripleSet.split('|')[2].strip().lower().replace("_"," ").strip("_\"")

		#to obtain the sentences from the XML files
		n = 2
		correctSentences = []
		while True:
			try:
				sentenceFromData = rootTest[0][i][n].text
				sentenceFromData = re.sub('"', ' ', sentenceFromData)
				sentenceFromData = re.sub('\.$', '', sentenceFromData)
				sentenceFromData = re.sub('"@en', ' ', sentenceFromData)
				sentenceFromData = re.sub('\n', ' ', sentenceFromData)
				sentenceFromData = sentenceFromData.strip()
				correctSentences.append(sentenceFromData.lower())
				n += 1
			except:
				break

		#check if the predicate is in the dict
		if Predicate in predicateDict:
			sentence = random.choice(predicateDict[Predicate])
		else:
			sentence = "oops, this sentence couldn't be parsed" #just an ugly message
		# sentence = predicateDict[Predicate][1]
		print("SPO: ", Subject,Predicate, Object)
		print("sentence: ", sentence)
		print("ourSentence: ", replaceToSpecific(sentence,Subject,Object))
		ourSentence = replaceToSpecific(sentence,Subject,Object)

		bleuScore = checkCorrect(score,ourSentence,correctSentences)

		print('-'*50)

		bleuScoreList.append(bleuScore)

	print("average Bleu score ", np.mean(bleuScoreList))

def main():
	tree = ET.parse('WebNLG/train/1triples/1triple_allSolutions_Food_train_challenge.xml')
	root = tree.getroot()
	predicateDict = {}

	for i in range(len(root[0])):

		tripleSet = root[0][i][1][0].text
		Subject   = tripleSet.split('|')[0].strip().lower().replace("_"," ")
		Predicate = tripleSet.split('|')[1].strip()
		Object    = tripleSet.split('|')[2].strip().lower().replace("_"," ").strip("\"")

		lexList = []
		for elem in root[0][i]:
			if elem.tag == 'lex':
				lexList.append(replaceToGeneral(elem.text, Subject, Object))

		if Predicate not in predicateDict:
			predicateDict[Predicate] = lexList
		else:
			for elem in lexList:
				if elem not in predicateDict[Predicate]:
					predicateDict[Predicate].append(elem)
	showChecks = True
	predicateDict = checkAndCleanCorrect(predicateDict, showChecks) #predicateDict, showCorrect Objects and Subjects = False/True
	if showChecks is True:
		showPredicateRecall(predicateDict, 1)

	testData(predicateDict)

if __name__ == '__main__':
	main()


from tkinter import *
from fonction import *
from random import *
from tkinter.messagebox import *
import sys

'''
Pour LEN_GRILLE, si on modifie la valeur, ainsi que la valeur introduite dans init_partie(n) avec n > 4, modifié également les boucles for dans logic.py pour adaptation
'''
LEN_GRILLE = 8
PADDING_GRILLE = 2 # Espace entre les cellules

'''
* Définition des couleurs backgrounds par type de cellules et par valeurs de cellules via l'utilisation de dictionnaires
* Définition de la police d'écriture, sa taille et son type.
* Définition des touches up,down,left,right attribuée à z,s,q,d
'''
FONT = ("Trebuchet", 20, "bold")
KEY_UP = "'z'"
KEY_DOWN = "'s'"
KEY_LEFT = "'q'"
KEY_RIGHT = "'d'"
BG_GRILLE = "#2A251F"
BG_CELLULE_VIDE = "#3F372F"
DICO_BG_CELLULE = {   2:"#FAF1E8", 4:"#DACAAB", 8:"#D3F37A", 16:"#CEF368", \
                            32:"#A8D03C", 64:"#8FB22F", 128:"#3662DB", 256:"#2C51B9", \
                            512:"#8F52F7", 1024:"#7B43DC", 2048:"#DC4343", 4096:"#CA3636", 8192:"#B52727",16384:"#DCD72F",32768:"#BCB500" }
DICO_FG_CELLULE = { 2:"#7B6F62", 4:"#7B6F62", 8:"#7B6F62", 16:"#7B6F62", \
                    32:"#F7F3EE", 64:"#F7F3EE", 128:"#f9f6f2", 256:"#F7F3EE", \
                    512:"#F7F3EE", 1024:"#F7F3EE", 2048:"#F7F3EE", 4096:"#F7F3EE", \
                    8192:"#F7F3EE", 16384:"#F7F3EE", 32768:"#F7F3EE"  }

class Grille2048(Frame):
    def __init__(self):
        '''
        Lancement et initialisation, définition des actions de commandes.
        '''
        Frame.__init__(self)
        self.grid() # Création du gestionnaire de positionnement, découpage en grille.
        self.master.title('Projet S2 32768 : Michel | El Hadad | Merveille | Doutrelon | Nique')
        self.master.bind("<Key>", self.partie)
        self.commands = {   KEY_UP: up, KEY_DOWN: down, KEY_LEFT: left, KEY_RIGHT: right}
        self.cellule_grille = []    #Liste initialiser pour stocker les cellules de la grille
        self.init_interface()
        self.init_grille()
        self.maj_cellule()
        self.mainloop()

    def init_interface(self):
        '''
        Création de la grille, attribution de la couleur de fond + par cellule vide et attribution font+options
        '''
        background = Frame(self, bg=BG_GRILLE)
        background.grid()
        for i in range(LEN_GRILLE):
            rangee_grille = []
            for j in range(LEN_GRILLE):
                case = Frame(background, bg=BG_CELLULE_VIDE)
                case.grid(row=i, column=j, padx=PADDING_GRILLE, pady=PADDING_GRILLE)
                t = Label(master=case, text="", bg=BG_CELLULE_VIDE, justify=CENTER, font=FONT, width=4, height=2)
                t.grid()
                rangee_grille.append(t)
            self.cellule_grille.append(rangee_grille)

    def init_grille(self):
        '''
        init_grille() crée et initialise la grille du 2048 avec 2 cellules de valeur 2 ou 4 au départ.
        '''
        self.grille = init_partie(LEN_GRILLE)
        self.grille=ajouterTuile(self.grille)
        self.grille=ajouterTuile(self.grille)

    def maj_cellule(self):
        '''
        Mise à jour des cellules (couleurs/valeurs)
        '''
        for i in range(LEN_GRILLE):
            for j in range(LEN_GRILLE):
                valeur_cellule = self.grille[i][j]
                if valeur_cellule == 0:
                    self.cellule_grille[i][j].configure(text="", bg=BG_CELLULE_VIDE)
                else:
                    if valeur_cellule <= 8192:
                        self.cellule_grille[i][j].configure(text=str(valeur_cellule), bg=DICO_BG_CELLULE[valeur_cellule], fg=DICO_FG_CELLULE[valeur_cellule])
                    else:
                        if valeur_cellule == 16384:
                            self.cellule_grille[i][j].configure(text='16K', bg=DICO_BG_CELLULE[valeur_cellule], fg=DICO_FG_CELLULE[valeur_cellule])
                        else:
                            self.cellule_grille[i][j].configure(text='32K', bg=DICO_BG_CELLULE[valeur_cellule], fg=DICO_FG_CELLULE[valeur_cellule])

    def partie(self, event):
        '''
        Une touche a été pressée : tests, actions dédiées et statut de la partie en cours
        '''
        commande = repr(event.char)
        if commande in self.commands:
            self.grille,statut_action = self.commands[repr(event.char)](self.grille)
            if statut_action:
                self.grille = ajouterTuile(self.grille)
                self.maj_cellule()
                statut_action = False
                if etat(self.grille)=='Gagné':
                    question = askretrycancel("Rejouer ?","Vous avez gagné ! Bravo ! Voulez vous rejouer ?")
                    if question:
                        self.destroy()
                        partie = Grille2048()
                    else:
                        sys.exit(0)
                if etat(self.grille)=='Perdu':
                    question = askretrycancel("Rejouer ?","Vous avez perdu ! Dommage ! Voulez vous rejouer ?")
                    if question:
                        self.destroy()
                        partie = Grille2048()
                    else:
                        sys.exit(0)

root=Tk()
root.resizable(False,False)

partie = Grille2048()


import itertools

def do_flips(perm, flip):
    for i in range(3):
        if (flip & (1 << i)) > 0:
            yield (perm[i][1], perm[i][0])
        else:
            yield perm[i]

def main():
    sizes = [tuple(sorted(int(x) for x in input().split())) for _ in range(3)]
    target = max(rect[1] for rect in sizes)

    if all(rect[1] == target for rect in sizes) and sum(rect[0] for rect in sizes) == target:
        print('YES')
        return

    for perm in itertools.permutations(sizes):
        for f in range(8):
            res = list(do_flips(perm, f))
            if res[0][0] == target and res[1][1] == res[2][1] and res[0][1] + res[1][1] == target and res[1][0] + res[2][0] == target:
                print('YES')
                return

    print('NO')

main()


import random
import math
import numpy as np
from gurobipy import *
import sys
from enum import Enum
from scipy import stats

### Enumerate experimenting methods

class Methods(Enum):
    BAYES = "Bayes Simple"
    CENTROID = "Mean Transition Probability"
    HOEFF = "Hoeffding"
    HOEFFTIGHT = "Hoeffding Tight"
    EM = "Expectation Maximization"
    INCR_REPLACE_V = "Incrementally Replace Value Function"
    INCR_ADD_V = "Incrementally Add Value Function"
    #For single state-action, KNOWNV is the same as INCR_ADD_V

    NUM_METHODS = 7 #Number of methods

LI_METHODS = [Methods.BAYES, Methods.CENTROID, Methods.HOEFF, Methods.HOEFFTIGHT, Methods.EM,\
                Methods.INCR_REPLACE_V, Methods.INCR_ADD_V]

###Dirichlet Threshold
def compute_bayesian_threshold(points, nominal_point, confidence_level):
    """
    Computes an empirical thresholds from samples from a posterior distriL1 threshold'bution
    Must adjust the confidence level when the MDP has more states
    and actions using the union bound
    """
    assert(abs(np.sum(nominal_point) - 1) < 0.001)
    for p in points:
        assert(abs(np.sum(p) - 1) < 0.001)

    distances = [np.linalg.norm(p - nominal_point, ord = 1) for p in points]
    confidence_rank = math.ceil(len(points) * confidence_level)
    dist = np.partition(distances, confidence_rank)[confidence_rank]

    return dist

###Process Gaussian distribution
def discretize_gaussian(min_value, max_value, mean, std):
    """
    Computes a discrete approximation of the Gaussian distribution. The distribution
    is bounded by min_value and max_value.
    Both bounds are inclusive.
    """
    d = stats.norm(mean, std)
    dist = np.array([d.pdf(v) for v in range(min_value, max_value + 1)])
    # normalize it
    dist /= np.sum(dist)
    return dist

def normal_aposteriori(values, weights, std, prior_mean, prior_std):
    """
    Estimates the aposteriori Gaussian distribution:
    see: https://en.wikipedia.org/wiki/Conjugate_prior#Continuous_distributions

    Assumes that the standard deviation of the demands is known but the
    mean is distributed according to the prior Gaussian distribution. std is the
    standard deviation of the demand (known).

    The parameter weights represents an un-normalized weight on each value.
    """
    n = np.sum(weights)
    sum = np.dot(weights, values)
    precision = (1 / prior_std**2 + n / std**2)
    expected_mean = (prior_mean / prior_std**2 + sum / std**2) / precision
    expected_std = 1/precision
    return expected_mean, expected_std

print(discretize_gaussian(0, 10, 3, 2))

### Apply Linear Program to compute the nominal point & apply quick select to find the uncertainty set with the required confidence
def get_uset(points, nominal_point, conf_rank):
    """
    Sort the points based on the distance from nominal point in ascending order.
    Taking N*confidence will  give the uncertainty set with nearest points

    @param conf_rank: how many points to take
    """

    distances = [( p, np.linalg.norm(p - nominal_point, ord = 1)) for p in points]
    distances.sort(key = lambda x : x[1])
    res_list = np.asarray([distances[i][0] for i in range(conf_rank)])

    if res_list.shape[0]>1:
        res_list = np.squeeze(res_list)

    psi = distances[conf_rank-1][1]
    return res_list, psi

def find_nominal_point(p):
    """
    Find nominal point for the uncertainty set using LP
    """
    num_p = p.shape[0]
    num_d = p.shape[1]
    m = Model("nominal")
    u = m.addVar(name="u", lb=0)

    y = m.addVars(range(num_p*num_d), vtype=GRB.CONTINUOUS, obj=0.0, name="y")
    # new nominal point
    beta = m.addVars(range(num_d), vtype=GRB.CONTINUOUS, obj=0.0, name="beta", lb=0)

    m.setObjective(u, GRB.MINIMIZE)

    for i in range(num_p):
        m.addConstr(u, GRB.GREATER_EQUAL, quicksum(y[i*num_d+j] for j in range(num_d)), "u_"+str(i))

    for i in range(num_p):
        for j in range(num_d):
            m.addConstr(y[i*num_d+j], GRB.GREATER_EQUAL, p[i,j]-beta[j], "c1"+str(i))
            m.addConstr(y[i*num_d+j], GRB.GREATER_EQUAL, beta[j]-p[i,j], "c2"+str(i))

    m.setParam( 'OutputFlag', False )
    m.optimize()

    #print('Obj: %g' % m.objVal)

    #for v in m.getVars():
    #    print('%s %g' % (v.varName, v.x))

    threshold = 0
    for v in m.getVars():
        if v.varName == "u":
            threshold = v.x
            break

    nominal_params = m.getAttr('x', beta)

    nominal_p = []
    for i in range(num_d):
        nominal_p.append(nominal_params[i])

    return nominal_p, threshold#tuple(nominal_p)

### Test EM
if __name__ == "__main__":
    num_points = 100
    confidence = 0.8
    confidence_rank = math.ceil(num_points * confidence)
    x = np.random.rand(num_points,1)*100
    y = np.random.rand(num_points,1)*100
    points = np.squeeze(np.stack((x,y),axis=1))

    num_iter = 20
    nominal_list = []
    psi_list = []

    rand_nominal_pos = np.random.randint(num_points)

    nominal_p = points[rand_nominal_pos]
    print("rand_nominal_pos",rand_nominal_pos,"nominal_p",nominal_p)
    prev_psi = sys.float_info.max
    for i in range(num_iter):
        nominal_list.append(nominal_p)
        u_set, psi = get_uset(points, nominal_p, confidence_rank)

        assert(psi <= prev_psi + 1e-5)

        prev_psi = psi
        psi_list.append(psi)
        nominal_p, _ = find_nominal_point(u_set)

    nominal_list = np.squeeze(nominal_list)

    print("nominal_list",nominal_list)
    print("psi_list",psi_list)

### calculate EM

def calc_EM(points, confidence_level, nominal_p):
    num_iter = 100
    num_count = 0
    nominal_list = []
    psi_list = []

    confidence_rank = math.ceil(len(points) * confidence_level)

    prev_psi = np.inf
    for i in range(num_iter):
        u_set, psi = get_uset(points, nominal_p, confidence_rank)
        if psi >= prev_psi or num_count>=100:
            break

        assert(psi <= prev_psi + 1e-5)

        #print("i",i,"psi",psi)
        num_count += 1
        prev_psi = psi
        psi_list.append(psi)
        nominal_list.append(nominal_p)
        nominal_p, _ = find_nominal_point(u_set)

    if len(nominal_list) > 1:
        nominal_list = np.squeeze(nominal_list)
    #print(nominal_list)
    return nominal_list[-1], psi_list[-1]

def calc_EM_rand(points, confidence_level, nominal_p):
    """
    A randomized version
    """

    new_nominal, new_psi = calc_EM(points, confidence_level, nominal_p)

    for i in range(10):
        next_nominal_p = points[np.random.randint(points.shape[0])]

        next_nominal, next_psi = calc_EM(points, confidence_level, next_nominal_p)
        if(next_psi < new_psi):
            new_psi = next_psi
            new_nominal = next_nominal

    return new_nominal, new_psi

### Construct Uset for known value function
import operator

def construct_uset_known_value_function(transition_points, value_function, confidence):
    """
    Computes the robust return and a threshold that achieves the desired confidence level
    for a single state and action.

    @param transition_points Samples from the posterior distribution of the transition
                             probabilities
    @param value_function Assumed optimal value function
    @param confidence Desired confidence level, such as 0.99
    """
    points = []

    for p in transition_points:
        points.append( (p,p@value_function) )
    points.sort(key=lambda x: x[1])

    conf_rank = math.ceil(len(transition_points)*confidence)
    #print("confidence_rank", conf_rank, "len(trans_points)", len(transition_points), "confidence",confidence,"product",confidence*len(transition_points))
    robust_ret = points[-conf_rank][1]
    robust_th = 0 #np.linalg.norm(points[-int(conf_rank)][0]-points[-int(conf_rank/2)][0], ord=1)
    nominal_point = points[-conf_rank][0]

    return (robust_ret, robust_th, nominal_point)


import sys
from acc import odczyt_z_pliku, zakup, zapis_do_pliku

sciezka = sys.argv[1]      # "3/in.txt"
(odczyt_danych, rejestr, magazyn, stan_konta) = odczyt_z_pliku(sciezka)

linia = "zakup"
id_prod = sys.argv[2]
cena_prod = int(sys.argv[3])
ile_prod = int(sys.argv[4])
(stan_konta, magazyn, rejestr) = zakup(linia, id_prod, cena_prod, ile_prod, stan_konta, magazyn, rejestr)
zapis_do_pliku(sciezka, rejestr)
for x in rejestr:
    print(x)
print("stop")


import parent
import archive

import os

def main():
    p = parent.ParentRoot( 'all', os.getcwd() )
    rp = p.execute()
    orgArchive = rp + '\\dataset\\csv\\openhardwaremonitor'

    arc = archive.Archive(orgArchive)

if __name__ == '__main__':
    main()


# most of this code are from https://github.com/choosehappy/HistoQC
import os
import sys
import numpy
from ast import literal_eval as make_tuple
import skimage
from skimage import io, color, img_as_ubyte, morphology
from skimage.filters import sobel
from skimage.filters import gabor_kernel, frangi, gaussian, median, laplace
from skimage.color import convert_colorspace, rgb2gray, rgb2hsv, separate_stains, hed_from_rgb
from skimage.morphology import remove_small_objects, disk, binary_opening, dilation
from distutils.util import strtobool
import numpy as np
import scipy
from scipy import ndimage as ndi
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier

def getTissueMask(img):
    upper_thresh = .9
    lower_var = 10
    lower_thresh = -float('inf')
    upper_var = float('inf')
    img_var = img.std(axis=2)
    map_var = np.bitwise_and(img_var > lower_var, img_var < upper_var)
    img = color.rgb2gray(img)
    map = np.bitwise_and(img > lower_thresh, img < upper_thresh)
    map = np.bitwise_and(map, map_var)
    map = (map >0)
    #map = ~map
    #map = map.astype(np.uint8)
    return map

def getDarkTissueMask(img):
    upper_thresh = .15
    lower_var = -float('inf')
    lower_thresh = -float('inf')
    upper_var = float('inf')
    img_var = img.std(axis=2)
    map_var = np.bitwise_and(img_var > lower_var, img_var < upper_var)
    img = color.rgb2gray(img)
    map = np.bitwise_and(img > lower_thresh, img < upper_thresh)
    map = np.bitwise_and(map, map_var)
    map = (map >0)
    #map = ~map
    #map = map.astype(np.uint8)
    return map

def getBrightness(img, tmask):
    a = getBrightnessGray(img, tmask)
    b = getBrightnessOtherColor(img, tmask)
    return {**a, **b}

def getBrightnessGray(img, tmask):
    img_g = rgb2gray(img)
    img_gm = img_g[tmask]

    return {'Gray Brightness mean (W)': img_g.mean(),
            'Gray Brightness std (W)':img_g.std(),
            'Gray Brightness mean (T)':img_gm.mean(),
            'Gray Brightness std (T)':img_gm.std()}

def getBrightnessOtherColor(img, tmask):
    a = {}
    #color_spaces = ['RGB', 'HSV', 'RGB CIE', 'XYZ', 'YUV', 'YIQ',
    #                'YPbPr', 'YCbCr']
    color_spaces = ['RGB', 'HSV', 'YUV']
    for color in color_spaces:
        if color != 'RGB':
            img2 = convert_colorspace(img, 'RGB', color)
        else:
            img2 = img
        for chan in range(0, 3):
            vals = img2[:, :, chan]
            vals_t = vals[tmask]
            a[f'{color} {chan+1} Brightness mean (W)'] = vals.mean()
            a[f'{color} {chan+1} Brightness std (W)'] = vals.std()
            a[f'{color} {chan+1} Brightness mean (T)'] = vals_t.mean()
            a[f'{color} {chan+1} Brightness std (T)'] = vals_t.std()

    return a

def getHueSaturation(img, tmask):
    a = {}
    hsv = rgb2hsv(img)

    a[f'Hue mean (W)'] = hsv[:,:,0].mean()
    a[f'Hue std (W)'] = hsv[:,:,0].std()
    a[f'Saturation mean (W)'] = hsv[:,:,1].mean()
    a[f'Saturation std (W)'] = hsv[:,:,1].std()
    a[f'Hue mean (T)'] = hsv[:,:,0][tmask].mean()
    a[f'Hue std (T)'] = hsv[:,:,0][tmask].std()
    a[f'Saturation mean (T)'] = hsv[:,:,1][tmask].mean()
    a[f'Saturation std (T)'] = hsv[:,:,1][tmask].std()

    return a

def getHE(img, tmask):
    a = {}

    stain_matrix = hed_from_rgb
    dimg = separate_stains(img, stain_matrix)

    a[f'Stain H mean (W)'] = dimg[:,:,0].mean()
    a[f'Stain H std (W)'] = dimg[:,:,0].std()
    a[f'Stain E mean (W)'] = dimg[:,:,1].mean()
    a[f'Stain E std (W)'] = dimg[:,:,1].std()
    a[f'Stain H mean (T)'] = dimg[:,:,0][tmask].mean()
    a[f'Stain H std (T)'] = dimg[:,:,0][tmask].std()
    a[f'Stain E mean (T)'] = dimg[:,:,1][tmask].mean()
    a[f'Stain E std (T)'] = dimg[:,:,1][tmask].std()

    return a

def getContrast(img, tmask):
    a = {}

    img = rgb2gray(img)
    sobel_img = sobel(img) ** 2
    tenenGrad_contrast = np.sqrt(np.sum(sobel_img)) / img.size
    max_img = img.max()
    min_img = img.min()
    michelson_contrast = (max_img - min_img) / (max_img + min_img)
    rms_contrast = np.sqrt(pow(img - img.mean(), 2).sum() / img.size)
    a[f'Contrast TenenGrad (W)'] = tenenGrad_contrast
    a[f'Contrast Michelson (W)'] = michelson_contrast
    #a[f'Contrast RMS (W)'] = rms_contrast

    img = img[tmask]
    sobel_img = sobel_img[tmask]
    tenenGrad_contrast = np.sqrt(np.sum(sobel_img)) / img.size
    max_img = img.max()
    min_img = img.min()
    michelson_contrast = (max_img - min_img) / (max_img + min_img)
    rms_contrast = np.sqrt(pow(img - img.mean(), 2).sum() / img.size)
    a[f'Contrast TenenGrad (T)'] = tenenGrad_contrast
    a[f'Contrast Michelson (T)'] = michelson_contrast
    #a[f'Contrast RMS (T)'] = rms_contrast

    return a

def getSmoothness(img, tmask):
    thresh = .01
    kernel_size = 10
    min_object_size = 500
    img = color.rgb2gray(img)
    avg = np.ones((kernel_size, kernel_size)) / (kernel_size**2)
    imf = scipy.signal.convolve2d(img, avg, mode="same")
    mask_flat = abs(imf - img) < thresh
    mask_flat = remove_small_objects(mask_flat, min_size=min_object_size)
    mask_flat = ~remove_small_objects(~mask_flat, min_size=min_object_size)
    ratio = np.sum(mask_flat) / (mask_flat.shape[0]*mask_flat.shape[1])
    a = {}
    a['Smoothness Ratio'] = ratio
    return a

def remove_large_objects(img, max_size):
    # code taken from morphology.remove_small_holes, except switched < with >
    selem = ndi.generate_binary_structure(img.ndim, 1)
    ccs = np.zeros_like(img, dtype=np.int32)
    ndi.label(img, selem, output=ccs)
    component_sizes = np.bincount(ccs.ravel())
    too_big = component_sizes > max_size
    too_big_mask = too_big[ccs]
    img_out = img.copy()
    img_out[too_big_mask] = 0
    return img_out

def getFatlikeTissue(img, tmask):
    a = {}
    kernel_size = 10
    max_keep_size = 1000
    fat_cell_size = 64
    img_reduced = morphology.remove_small_holes(tmask, area_threshold=fat_cell_size)
    img_small = img_reduced & np.invert(tmask)
    img_small = ~morphology.remove_small_holes(~img_small, area_threshold=9)
    mask_dilate = morphology.dilation(img_small, selem=np.ones((kernel_size, kernel_size)))
    mask_dilate_removed = remove_large_objects(mask_dilate, max_keep_size)
    mask_fat = mask_dilate & ~mask_dilate_removed
    mask_fat = (mask_fat * 255) >0
    ratio = np.sum(mask_fat) / (mask_fat.shape[0] * mask_fat.shape[1])
    a = {'Fat Like Tissue Ratio': ratio}
    return a

def compute_features(img, params):
    features = params.get("features", "")
    feats=[]
    for feature in features:
        func = getattr(sys.modules[__name__], f'compute_{feature}')
        feats.append(func(img, params))
    return np.concatenate(feats, axis=2)

def compute_rgb(img, params):
    return img

def compute_laplace(img, params):
    laplace_ksize = int(params.get("laplace_ksize", 3))
    return laplace(rgb2gray(img), ksize=laplace_ksize)[:, :, None]

def compute_lbp(img, params):
    lbp_radius = float(params.get("lbp_radius", 3))
    lbp_points = int(params.get("lbp_points", 24))  # example sets radius * 8
    lbp_method = params.get("lbp_method", "default")
    return local_binary_pattern(rgb2gray(img), P=lbp_points, R=lbp_radius, method=lbp_method)[:, :, None]

def compute_gaussian(img, params):
    gaussian_sigma = int(params.get("gaussian_sigma", 1))
    gaussian_multichan = strtobool(params.get("gaussian_multichan", False))

    if (gaussian_multichan):
        return gaussian(img, sigma=gaussian_sigma, multichannel=gaussian_multichan)
    else:
        return gaussian(rgb2gray(img), sigma=gaussian_sigma)[:, :, None]

def compute_median(img, params):
    median_disk_size = int(params.get("median_disk_size", 3))
    return median(rgb2gray(img), selem=disk(median_disk_size))[:, :, None]

def compute_gabor(img, params):
    if not params["shared_dict"].get("gabor_kernels", False):
        gabor_theta = int(params.get("gabor_theta", 4))
    gabor_sigma = make_tuple(params.get("gabor_sigma", "(1,3)"))
    gabor_frequency = make_tuple(params.get("gabor_frequency", "(0.05, 0.25)"))

    kernels = []
    for theta in range(gabor_theta):
        theta = theta / 4. * np.pi
        for sigma in gabor_sigma:
            for frequency in gabor_frequency:
                kernel = np.real(gabor_kernel(frequency, theta=theta,
                        sigma_x=sigma, sigma_y=sigma))
                kernels.append(kernel)
    params["shared_dict"]["gabor_kernels"] = kernels

    kernels = params["shared_dict"]["gabor_kernels"]
    imgg = rgb2gray(img)
    feats = np.zeros((imgg.shape[0], imgg.shape[1], len(kernels)), dtype=np.double)
    for k, kernel in enumerate(kernels):
        filtered = ndi.convolve(imgg, kernel, mode='wrap')
        feats[:, :, k] = filtered
    return feats

def compute_frangi(img, params):
    frangi_scale_range = make_tuple(params.get("frangi_scale_range", "(1, 10)"))
    frangi_scale_step = float(params.get("frangi_scale_step", 2))
    frangi_beta1 = float(params.get("frangi_beta1", .5))
    frangi_beta2 = float(params.get("frangi_beta2", 15))
    frangi_black_ridges = strtobool(params.get("frangi_black_ridges", "True"))
    feat = frangi(rgb2gray(img), scale_range = frangi_scale_range, scale_step =frangi_scale_step, beta =frangi_beta1, gamma=frangi_beta2, black_ridges  =frangi_black_ridges)
    return feat[:, :, None]  # add singleton dimension

def trainModelPen(example_path, example_mask_path):
    model_vals = []
    model_labels = np.empty([0, 1])
    img = io.imread(example_path)
    params = dict(
                threshold = .5,
                area_threshold = 100,
                features = ['frangi', 'laplace', 'rgb'],
                laplace_ksize = 3,
                frangi_scale_range = '(1,10)',
                frangi_scale_step = 2,
                frangi_beta1 = .5,
                frangi_beta2= 15,
                frangi_black_ridges= 'True',

                gabor_theta= 4,
                gabor_sigma= '(1,3)',
                gabor_frequency= '(0.05, 0.25)',

                lbp_radius= 3,
                lbp_points= 24,
                lbp_method= 'default',

                median_disk_size= 3,
             )
    eximg = compute_features(img, params)
    eximg = eximg.reshape(-1, eximg.shape[2])
    model_vals.append(eximg)
    mask = io.imread(example_mask_path, as_gray=True).reshape(-1,1)
    model_labels = np.vstack((model_labels, mask))

    model_vals = np.vstack(model_vals)
    clf = RandomForestClassifier(n_jobs=-1)
    clf.fit(model_vals, model_labels.ravel())
    return clf

def trainCoverslipEdge(example_path, example_mask_path):
    params = dict(
                area_threshold = 15,
                features =  ['frangi', 'laplace', 'rgb'],
                dilate_kernel_size = 5,
    )
    model_vals = []
    model_labels = np.empty([0, 1])
    img = io.imread(example_path)
    eximg = compute_features(img, params)
    eximg = eximg.reshape(-1, eximg.shape[2])
    model_vals.append(eximg)
    mask = io.imread(example_mask_path, as_gray=True).reshape(-1,1)
    model_labels = np.vstack((model_labels, mask))

    model_vals = np.vstack(model_vals)
    clf = RandomForestClassifier(n_jobs=-1)
    clf.fit(model_vals, model_labels.ravel())
    return clf

def getBlurryRegion(src_img, tmask):
    #img_work_size = 2.5x
    blur_radius = 100
    blur_threshold = .15
    img = rgb2gray(src_img)
    img_laplace = np.abs(skimage.filters.laplace(img))
    mask = skimage.filters.gaussian(img_laplace, sigma=blur_radius) <= blur_threshold
    mask = skimage.transform.resize(mask, src_img.shape, order=0)[:,:,1]
    mask = tmask & (mask >0)
    ratio = np.sum(mask) / mask.size
    a = {'Blurry Region Ratio': ratio}
    return a

def getPenMarking(img, tmask, model):
    params = dict(
                threshold = .5,
                area_threshold = 100,
                features = ['frangi', 'laplace', 'rgb'],
                laplace_ksize = 3,
                frangi_scale_range = '(1,10)',
                frangi_scale_step = 2,
                frangi_beta1 = .5,
                frangi_beta2= 15,
                frangi_black_ridges= 'True',

                gabor_theta= 4,
                gabor_sigma= '(1,3)',
                gabor_frequency= '(0.05, 0.25)',

                lbp_radius= 3,
                lbp_points= 24,
                lbp_method= 'default',

                median_disk_size= 3,
    )
    thresh = float(params.get("threshold", .5))
    clf = model
    feats = compute_features(img, params)
    cal = clf.predict_proba(feats.reshape(-1, feats.shape[2]))
    cal = cal.reshape(img.shape[0], img.shape[1], 2)
    mask = cal[:, :, 1] > thresh
    area_thresh = int(params.get("area_threshold", "5"))
    if area_thresh > 0:
        mask = remove_small_objects(mask, min_size=area_thresh, in_place=True)
    dilate_kernel_size = int(params.get("dilate_kernel_size", "0"))
    if dilate_kernel_size > 0:
        mask = dilation(mask, selem=np.ones((dilate_kernel_size, dilate_kernel_size)))
    mask = tmask & (mask > 0)
    ratio = np.sum(mask)/np.sum(tmask)
    return ratio

def getCoverslipEdge(img, tmask, model):
    params = dict(
                area_threshold = 15,
                features =  ['frangi', 'laplace', 'rgb'],
                dilate_kernel_size = 5,
    )
    thresh = float(params.get("threshold", .5))
    clf = model
    feats = compute_features(img, params)
    cal = clf.predict_proba(feats.reshape(-1, feats.shape[2]))
    cal = cal.reshape(img.shape[0], img.shape[1], 2)
    mask = cal[:, :, 1] > thresh
    area_thresh = int(params.get("area_threshold", "5"))
    if area_thresh > 0:
        mask = remove_small_objects(mask, min_size=area_thresh, in_place=True)
    dilate_kernel_size = int(params.get("dilate_kernel_size", "0"))
    if dilate_kernel_size > 0:
        mask = dilation(mask, selem=np.ones((dilate_kernel_size, dilate_kernel_size)))
    mask = tmask & (mask > 0)
    ratio = np.sum(mask)/np.sum(tmask)
    return ratio


import json
import csv

# enter file path of json file to convert
jsonfile = '/Users/roslynnricard/Google Drive/repo/20191201-143000.json'

# name file with cell serial number
csvfilename = 'SONY_VTC6A_2170_B.csv'

contents = ''
data_parsed = ''
config = ''
tags = ''

def parsejson():

    with open(jsonfile, 'r') as f:
        contents = f.read()

    data_parsed = json.loads(contents)

    # get cell and test details
    cell_type = data_parsed['config']['cell']
    current_sp = data_parsed['config']['discharge_current_A']

    tags = data_parsed['data'][1]['tags']

    #parse json and print to csv
    with open(csvfilename, 'w', newline='') as csvfile:
        fieldnames = ['cell_type','current_sp','time', 'current', 'voltage']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        writer.writeheader()

        for i in range(len(data_parsed['data'])):
            time = data_parsed['data'][i]['time']
            current = data_parsed['data'][i]['fields']['current_a']
            voltage = data_parsed['data'][i]['fields']['voltage_v']
            writer.writerow({'cell_type': cell_type, 'current_sp' : current_sp, 'time': time, 'current' : current, 'voltage' : voltage})

if __name__ == "__main__":
    parsejson()


from ..models import FinAccount

import pytest
from mixer.backend.django import mixer
from django.core.exceptions import ValidationError
from datetime import datetime
pytestmark = pytest.mark.django_db

class TestFinAccount:
    def test_invalid_paid_field(self):
        fin = mixer.blend(FinAccount, paid=50.56, value=20.0)

        with pytest.raises(ValidationError) as call_info:
            fin.clean()

        assert 'The amount paid' \
            ' cannot be greater than the value.' in str(call_info.value)

        fin = mixer.blend(FinAccount, paid=-1, value=10)
        with pytest.raises(ValidationError) as call_info:
            fin.clean_fields()

        assert 'The value must be equal' \
            ' or greater than 0' in str(call_info.value)

    def test_valid_paid_field(self):
        fin = mixer.blend(FinAccount, paid=5.0, value=10)
        try:
            fin.clean()
        except ValidationError:
            pytest.fail('Unexpected ValidationError')

    def test_invalid_value_field(self):
        fin = mixer.blend(FinAccount, paid=0, value=-10)
        with pytest.raises(ValidationError) as call_info:
            fin.clean_fields()

        assert 'The value must be be greater than 0' in str(call_info.value)

        fin = mixer.blend(FinAccount, paid=0, value=0)
        with pytest.raises(ValidationError) as call_info:
            fin.clean_fields()

        assert 'The value must be be greater than 0' in str(call_info.value)

    def test_valid_value_field(self):
        fin = mixer.blend(FinAccount, paid=0, value=1)
        try:
            fin.clean()
        except ValidationError:
            pytest.fail('Unexpected ValidationError')

    def test_balance(self):
        fin = mixer.blend(FinAccount, paid=5, value=10)
        assert fin.balance == 5, 'Balance value should be 5'

    def test_str(self):
        name = 'CTP-123-1/10'
        fin = mixer.blend(FinAccount, description=name)
        assert str(fin) == name

    def test_canceled(self):
        fin = mixer.blend(FinAccount)
        fin.canceled = True

        assert fin.canceled_at.date() == datetime.today().date(), \
            'canceled_at field should be today'

        fin.canceled = False
        assert fin.canceled_at is None, 'canceled_at '\
            'field should be None'


"""empty message

Revision ID: a11b335c4589
Revises: aedf57ef35d3
Create Date: 2021-06-22 21:29:11.066441

"""
from alembic import op
import sqlalchemy as sa

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

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('venue', sa.Column('looking_for_talent', sa.Boolean(), nullable=True))
    op.drop_column('venue', 'looking_for_Talent')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('venue', sa.Column('looking_for_Talent', sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.drop_column('venue', 'looking_for_talent')
    # ### end Alembic commands ###


# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0

from enum import Enum
from typing import (
    Dict, List, Optional,
)

from amundsen_common.models.search import Filter, SearchResponse
from elasticsearch import Elasticsearch
from elasticsearch_dsl import (
    MultiSearch, Q, Search,
)
from elasticsearch_dsl.query import MultiMatch
from elasticsearch_dsl.response import Response
from werkzeug.exceptions import InternalServerError

BOOL_QUERY = 'bool'
WILDCARD_QUERY = 'wildcard'
TERM_QUERY = 'term'
TERMS_QUERY = 'terms'

class Resource(Enum):
    TABLE = 0
    DASHBOARD = 1
    FEATURE = 2
    USER = 3

RESOURCE_STR_MAPPING = {
    'table': Resource.TABLE,
    'dashboard': Resource.DASHBOARD,
    'feature': Resource.FEATURE,
    'user': Resource.USER,
}

class ElasticsearchProxy():
    PRIMARY_ENTITIES = [Resource.TABLE, Resource.DASHBOARD, Resource.FEATURE, Resource.USER]

    # mapping to translate request for table resources
    TABLE_MAPPING = {
        'key': 'key',
        'badges': 'badges',
        'tag': 'tags',
        'schema': 'schema.raw',
        'table': 'name.raw',
        'column': 'column_names.raw',
        'database': 'database.raw',
        'cluster': 'cluster.raw'
    }

    # mapping to translate request for dashboard resources
    DASHBOARD_MAPPING = {
        'group_name': 'group_name.raw',
        'name': 'name.raw',
        'product': 'product',
        'tag': 'tags',
    }

    # mapping to translate request for feature resources
    FEATURE_MAPPING = {
        'key': 'key',
        'feature_group': 'feature_group.raw',
        'feature_name': 'feature_name.raw',
        'entity': 'entity',
        'status': 'status',
        'version': 'version',
        'availability': 'availability.raw',
        'tags': 'tags',
        'badges': 'badges'
    }

    USER_MAPPING = {
        'full_name': 'full_name',
        'first_name': 'first_name',
        'last_name': 'last_name',
        'email': 'email'
    }

    RESOUCE_TO_MAPPING = {
        Resource.TABLE: TABLE_MAPPING,
        Resource.DASHBOARD: DASHBOARD_MAPPING,
        Resource.FEATURE: FEATURE_MAPPING,
        Resource.USER: USER_MAPPING,
    }

    def __init__(self, *,
                 host: str = None,
                 user: str = '',
                 password: str = '',
                 client: Elasticsearch = None) -> None:
        if client:
            self.elasticsearch = client
        else:
            http_auth = (user, password) if user else None
            self.elasticsearch = Elasticsearch(host, http_auth=http_auth)

    def _build_term_query(self, resource: Resource, query_term: str) -> Optional[Q]:
        """
        Builds the query object for the inputed search term
        """
        if not query_term:
            # We don't want to create multi_match query for ""
            # because it will result in no matches even with filters
            return None

        fields = []

        if resource == Resource.TABLE:
            fields = ["display_name^1000",
                      "name.raw^75",
                      "name^5",
                      "schema^3",
                      "description^3",
                      "column_names^2",
                      "column_descriptions",
                      "tags",
                      "badges",
                      "programmatic_descriptions"]
        elif resource == Resource.DASHBOARD:
            fields = ["name.raw^75",
                      "name^7",
                      "group_name.raw^15",
                      "group_name^7",
                      "description^3",
                      "query_names^3",
                      "chart_names^2"]
        elif resource == Resource.FEATURE:
            fields = ["feature_name.raw^25",
                      "feature_name^7",
                      "feature_group.raw^15",
                      "feature_group^7",
                      "version^7",
                      "description^3",
                      "status",
                      "entity",
                      "tags",
                      "badges"]
        elif resource == Resource.USER:
            fields = ["full_name.raw^30",
                      "full_name^5",
                      "first_name.raw^5",
                      "last_name.raw^5",
                      "first_name^3",
                      "last_name^3",
                      "email^3"]
        else:
            # TODO if you don't specify a resource match for all generic fields in the future
            raise ValueError(f"no fields defined for resource {resource}")

        return MultiMatch(query=query_term, fields=fields, type='most_fields')

    def _build_filters(self, resource: Resource, filters: List[Filter]) -> List:
        """
        Builds the query object for all of the filters given in the search request
        """
        mapping = self.RESOUCE_TO_MAPPING.get(resource)

        filter_queries: List = []

        for filter in filters:
            filter_name = mapping.get(filter.name) if mapping is not None \
                and mapping.get(filter.name) is not None else filter.name

            queries_per_term = [Q(WILDCARD_QUERY, **{filter_name: term}) for term in filter.values]

            if filter.operation == 'OR':
                filter_queries.append(Q(BOOL_QUERY, should=queries_per_term, minimum_should_match=1))

            elif filter.operation == 'AND':
                for q in queries_per_term:
                    filter_queries.append(q)

            else:
                msg = f"Invalid operation {filter.operation} for filter {filter_name} with values {filter.values}"
                raise ValueError(msg)

        return filter_queries

    def _build_elasticsearch_query(self, *,
                                   resource: Resource,
                                   query_term: str,
                                   filters: List[Filter]) -> Q:

        term_query = self._build_term_query(resource=resource,
                                            query_term=query_term)
        filters = self._build_filters(resource=resource, filters=filters)

        es_query = None

        if filters and term_query:
            es_query = Q('bool', should=[term_query], filter=filters)
        elif not filters and term_query:
            es_query = Q('bool', should=[term_query])
        elif filters and not term_query:
            es_query = Q('bool', filter=filters)
        else:
            raise ValueError("Invalid search query")

        return es_query

    def _format_response(self, page_index: int,
                         results_per_page: int,
                         responses: List[Response],
                         resource_types: List[Resource]) -> SearchResponse:
        resource_types_str = [r.name.lower() for r in resource_types]
        no_results_for_resource = {
            "results": [],
            "total_results": 0
        }
        results_per_resource = {resource: no_results_for_resource for resource in resource_types_str}

        for r in responses:
            if r.success():
                results_count = r.hits.total.value
                if results_count > 0:
                    resource_type = r.hits.hits[0]._type
                    results = []
                    for search_result in r.hits.hits:
                        # mapping gives all the fields in the response
                        result = {}
                        fields = self.RESOUCE_TO_MAPPING[Resource[resource_type.upper()]]
                        for f in fields.keys():
                            # remove "raw" from mapping value
                            field = fields[f].split('.')[0]
                            result[f] = search_result._source[field]
                        result["search_score"] = search_result._score
                        results.append(result)
                    # replace empty results with actual results
                    results_per_resource[resource_type] = {
                        "results": results,
                        "total_results": results_count
                    }
            else:
                raise InternalServerError(f"Request to Elasticsearch failed: {r.failures}")

        return SearchResponse(msg="Success",
                              page_index=page_index,
                              results_per_page=results_per_page,
                              results=results_per_resource,
                              status_code=200)

    def execute_queries(self, queries: Dict[Resource, Q],
                        page_index: int,
                        results_per_page: int) -> List[Response]:
        multisearch = MultiSearch(using=self.elasticsearch)

        for resource in queries.keys():
            resource_str = resource.name.lower()
            resource_index = f"{resource_str}_search_index"
            query_for_resource = queries.get(resource)
            search = Search(index=resource_index).query(query_for_resource)

            # pagination
            start_from = page_index * results_per_page
            search = search[start_from:results_per_page]

            multisearch = multisearch.add(search)

        return multisearch.execute()

    def search(self, *,
               query_term: str,
               page_index: int,
               results_per_page: int,
               resource_types: List[Resource],
               filters: List[Filter]) -> SearchResponse:
        if resource_types == []:
            # if resource types are not defined then search all resources
            resource_types = self.PRIMARY_ENTITIES

        queries: Dict[Resource, Q] = {}
        for resource in resource_types:
            # build a query for each resource to search
            queries[resource] = self._build_elasticsearch_query(resource=resource,
                                                                query_term=query_term,
                                                                filters=filters)

        responses = self.execute_queries(queries=queries,
                                         page_index=page_index,
                                         results_per_page=results_per_page)

        formatted_response = self._format_response(page_index=page_index,
                                                   results_per_page=results_per_page,
                                                   responses=responses,
                                                   resource_types=resource_types)

        return formatted_response


#!/usr/bin/env python

import sys
from time import time
from psana.detector.Utils import info_parser_arguments
from psana.detector.UtilsEpix10kaCalib import pedestals_calibration, CALIB_REPO_EPIX10KA

import logging
logger = logging.getLogger(__name__)
DICT_NAME_TO_LEVEL = logging._nameToLevel

SCRNAME = sys.argv[0].rsplit('/')[-1]

USAGE = 'Usage:'\
      + '\n  %s -e <experiment> -d <detector> -r <run-number(s)>' % SCRNAME\
      + '\n     [-x <xtc-directory>] [-o <output-result-directory>] [-L <logging-mode>] [...]'\
      + '\nExamples:'\
      + '\n  %s -e ueddaq02 -d epixquad -r27' % SCRNAME\
      + '\n  mpirun -n 5 %s -e ueddaq02 -d epixquad -r27 -o ./work -L DEBUG' % SCRNAME\
      + '\n  %s -e ueddaq02 -d epixquad -r83 -o ./work' % SCRNAME\
      + '\n  %s -e ueddaq02 -d epixquad -r27 -i15 -o ./work -L DEBUG' % SCRNAME\
      + '\n  %s -e rixx45619 -d epixhr -r121' % SCRNAME\
      + '\n\n  Try: %s -h' % SCRNAME

def do_main():

    t0_sec = time()

    parser = argument_parser()
    args = parser.parse_args()
    kwa = vars(args)
    #defs = vars(parser.parse_args([])) # dict of defaults only

    if len(sys.argv)<3: exit('\n%s\n' % USAGE)

    assert args.exp is not None, 'WARNING: option "-e <experiment>" MUST be specified.'
    assert args.det is not None, 'WARNING: option "-d <detector-name>" MUST be specified.'
    assert args.runs is not None, 'WARNING: option "-r <run-number(s)>" MUST be specified.'

    fmt = '[%(levelname).1s] %(name)s %(message)s' if args.logmode=='DEBUG' else '[%(levelname).1s] %(message)s'
    logging.basicConfig(format=fmt, level=DICT_NAME_TO_LEVEL[args.logmode])
    #logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s %(filename)s: %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG)
    #logging.basicConfig(filename='log.txt', filemode='w', format=fmt, level=DICT_NAME_TO_LEVEL[args.logmode])

    logger.debug('%s\nIn epix10ka_pedestals_calibration' % (50*'_'))
    logger.debug('Command line:%s' % ' '.join(sys.argv))
    logger.info(info_parser_arguments(parser))

    pedestals_calibration(**kwa)

    logger.info('DONE, consumed time %.3f sec' % (time() - t0_sec))

def argument_parser():
    from argparse import ArgumentParser

    d_fname   = None # '/cds/data/psdm/ued/ueddaq02/xtc/ueddaq02-r0027-s000-c000.xtc2'
    d_exp     = None # 'ueddaq02'
    d_det     = None # 'epixquad'
    d_runs    = None # 1021 or 1021,1022-1025
    d_nrecs   = 800  # number of records to collect and process
    d_nrecs1  = 200  # number of records to process at 1st stage
    d_idx     = None # 0-15 for epix10ka2m, 0-3 for epix10kaquad
    d_dirxtc  = None # '/cds/data/psdm/ued/ueddaq02/xtc'
    d_dirrepo = CALIB_REPO_EPIX10KA # './myrepo'
    d_usesmd  = True
    d_logmode = 'INFO'
    d_errskip = True
    d_stepnum    = None
    d_stepmax    = 5
    d_evskip     = 100     # number of events to skip in the beginning of each step
    d_events     = 1000    # last event number in the step to process
    d_dirmode    = 0o774
    d_filemode   = 0o664
    d_int_lo     = 1       # lowest  intensity accepted for dark evaluation
    d_int_hi     = 16000   # highest intensity accepted for dark evaluation
    d_intnlo     = 6.0     # intensity ditribution number-of-sigmas low
    d_intnhi     = 6.0     # intensity ditribution number-of-sigmas high
    d_rms_lo     = 0.001   # rms ditribution low
    d_rms_hi     = 16000   # rms ditribution high
    d_rmsnlo     = 6.0     # rms ditribution number-of-sigmas low
    d_rmsnhi     = 6.0     # rms ditribution number-of-sigmas high
    d_fraclm     = 0.1     # allowed fraction limit
    d_fraclo     = 0.05    # fraction of statistics [0,1] below low limit
    d_frachi     = 0.95    # fraction of statistics [0,1] below high limit

    h_fname   = 'input xtc file name, default = %s' % d_fname
    h_exp     = 'experiment name, default = %s' % d_exp
    h_det     = 'detector name, default = %s' % d_det
    h_runs    = 'run number or list of runs e.g. 12,14-18, default = %s' % str(d_runs)
    h_nrecs   = 'number of records to calibrate pedestals, default = %s' % str(d_nrecs)
    h_nrecs1  = 'number of records to process at 1st stage, default = %s' % str(d_nrecs1)
    h_idx     = 'segment index (0-15 for epix10ka2m, 0-3 for quad) or all by default for processing, default = %s' % str(d_idx)
    h_dirxtc  = 'non-default xtc directory, default = %s' % d_dirxtc
    h_dirrepo = 'repository for calibration results, default = %s' % d_dirrepo
    h_usesmd  = 'add "smd" in dataset string, default = %s' % d_usesmd
    h_logmode = 'logging mode, one of %s, default = %s' % (' '.join(DICT_NAME_TO_LEVEL.keys()), d_logmode)
    h_errskip = 'flag to skip errors and keep processing, stop otherwise, default = %s' % d_errskip
    h_stepnum    = 'step number to process or None for all steps, default = %s' % str(d_stepnum)
    h_stepmax    = 'maximum number of steps to process, default = %s' % str(d_stepmax)
    h_evskip     = 'number of events to skip in the beginning of each step, default = %s' % str(d_evskip)
    h_events     = 'number of events to process from the beginning of each step, default = %s' % str(d_events)
    h_dirmode    = 'directory access mode, default = %s' % oct(d_dirmode)
    h_filemode   = 'file access mode, default = %s' % oct(d_filemode)
    h_int_lo     = 'lowest  intensity accepted for dark evaluation, default = %d' % d_int_lo
    h_int_hi     = 'highest intensity accepted for dark evaluation, default = %d' % d_int_hi
    h_intnlo     = 'intensity ditribution number-of-sigmas low, default = %f' % d_intnlo
    h_intnhi     = 'intensity ditribution number-of-sigmas high, default = %f' % d_intnhi
    h_rms_lo     = 'rms ditribution low, default = %f' % d_rms_lo
    h_rms_hi     = 'rms ditribution high, default = %f' % d_rms_hi
    h_rmsnlo     = 'rms ditribution number-of-sigmas low, default = %f' % d_rmsnlo
    h_rmsnhi     = 'rms ditribution number-of-sigmas high, default = %f' % d_rmsnhi
    h_fraclm     = 'allowed fraction limit, default = %f' % d_fraclm
    h_fraclo     = 'fraction of statistics [0,1] below low  limit of the gate, default = %f' % d_fraclo
    h_frachi     = 'fraction of statistics [0,1] below high limit of the gate, default = %f' % d_frachi

    parser = ArgumentParser(description='Proceses dark run xtc data for epix10ka')
    parser.add_argument('-f', '--fname',   default=d_fname,      type=str,   help=h_fname)
    parser.add_argument('-e', '--exp',     default=d_exp,        type=str,   help=h_exp)
    parser.add_argument('-d', '--det',     default=d_det,        type=str,   help=h_det)
    parser.add_argument('-r', '--runs',    default=d_runs,       type=str,   help=h_runs)
    parser.add_argument('-n', '--nrecs',   default=d_nrecs,      type=int,   help=h_nrecs)
    parser.add_argument('--nrecs1',        default=d_nrecs1,     type=int,   help=h_nrecs1)
    parser.add_argument('-i', '--idx',     default=d_idx,        type=int,   help=h_idx)
    parser.add_argument('-x', '--dirxtc',  default=d_dirxtc,     type=str,   help=h_dirxtc)
    parser.add_argument('-o', '--dirrepo', default=d_dirrepo,    type=str,   help=h_dirrepo)
    parser.add_argument('-S', '--usesmd',  action='store_false',             help=h_usesmd)
    parser.add_argument('-L', '--logmode', default=d_logmode,    type=str,   help=h_logmode)
    parser.add_argument('-E', '--errskip', action='store_false',             help=h_errskip)
    parser.add_argument('--stepnum',       default=d_stepnum,    type=int,   help=h_stepnum)
    parser.add_argument('--stepmax',       default=d_stepmax,    type=int,   help=h_stepmax)
    parser.add_argument('--evskip',        default=d_evskip,     type=int,   help=h_evskip)
    parser.add_argument('--events',        default=d_events,     type=int,   help=h_events)
    parser.add_argument('--dirmode',       default=d_dirmode,    type=int,   help=h_dirmode)
    parser.add_argument('--filemode',      default=d_filemode,   type=int,   help=h_filemode)
    parser.add_argument('--int_lo',        default=d_int_lo,     type=int,   help=h_int_lo)
    parser.add_argument('--int_hi',        default=d_int_hi,     type=int,   help=h_int_hi)
    parser.add_argument('--intnlo',        default=d_intnlo,     type=float, help=h_intnlo)
    parser.add_argument('--intnhi',        default=d_intnhi,     type=float, help=h_intnhi)
    parser.add_argument('--rms_lo',        default=d_rms_lo,     type=float, help=h_rms_lo)
    parser.add_argument('--rms_hi',        default=d_rms_hi,     type=float, help=h_rms_hi)
    parser.add_argument('--rmsnlo',        default=d_rmsnlo,     type=float, help=h_rmsnlo)
    parser.add_argument('--rmsnhi',        default=d_rmsnhi,     type=float, help=h_rmsnhi)
    parser.add_argument('--fraclm',        default=d_fraclm,     type=float, help=h_fraclm)
    parser.add_argument('--fraclo',        default=d_fraclo,     type=float, help=h_fraclo)
    parser.add_argument('--frachi',        default=d_frachi,     type=float, help=h_frachi)

    return parser

if __name__ == "__main__":
    do_main()
    exit('End of %s'%SCRNAME)

# EOF


import cv2
from threading import Thread, Lock
from Queue import Custom_Queue as Queue
from ConvertToGrayscale import convertToGrayscale
from ExtractAndDisplay import extractFrames, displayFrames

file = 'clip.mp4'
vidcap = cv2.VideoCapture(file)
length_of_clip = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
frameCounter = 0

def producer(queue, start, end, step):

    for value in range(start, end, step):
        queue.put(value)
    print('Producer finished')

def consumer(queue, count, result, lock):

    local_result = []
    for _ in range(count):
        local_result.append(queue.get())
    with lock:
        result.update(local_result)
    print('Consumer finished')

def main():
    image_queue = Queue(10)
    for i in range(length_of_clip):
        extractFrames(file, image_queue, i)
        convertToGrayscale(file, image_queue)
        displayFrames(image_queue, i, False)

main()


# -*- coding: latin-1 -*-
'''
Aprendizagem por reforço do tipo Q-Learning
'''

#_______________________________________________________________________________
from src.lib.aprend_ref.aprend_ref import AprendRef

class AprendQ(AprendRef):
    def __init__(self, mem_aprend, sel_accao, alfa, gama):
        super(AprendQ, self).__init__(mem_aprend, sel_accao)
        self._alfa = alfa
        self._gama = gama
        # raise NotImplementedError

    def aprender(self, s, a, r, sn):
        an = self._sel_accao.max_accao(sn)  # Próxima accção
        qsa = self._mem_aprend.obter(s, a)  # Valor de q para o par estado (s) acção (a)
        qsnan = self._mem_aprend.obter(sn, an)  # Valor de q para o próximo par estado (sn) acção (an)
        q = qsa + self._alfa * (r + self._gama * qsnan - qsa)   # Fórmula do Q-Learning
        self._mem_aprend.actualizar(s, a, q)    # Actualizar o valor de q para o par estado (s) acção (a)
        # raise NotImplementedError


'''
Created on 13.06.2015

@author: Tobias
'''
from core.database import Database

scripts = {}

def addScript(function,name):
    scripts[name] = function
    result = Database.execute("SELECT COUNT(*) FROM `homeautomation`.`script` WHERE `Name`='" + name + "'")
    print(result)
    if(result[0][0]=='0'):
        print(name)
        Database.execute("INSERT INTO `homeautomation`.`script` (`ID_Script`, `Name`) VALUES (NULL, '" + name + "')")

#def handleInputEvent(inputDeviceID,status=""):

#def handleEvent(event,eventID):

def executeScript(name):
    scripts[name]("Hallo du","","")


import sys
input = sys.stdin.readline

def is_right():
    N = int(input())
    note_1 = set(map(int, input().split()))

    M = int(input())
    note_2 = list(map(int, input().split()))

    for num in note_2:
        if num in note_1:
            print(1)
        else:
            print(0)
    return

T = int(input())
for i in range(T):
    is_right()

"""
풀이
노트 1에 있는 숫자는 중복이 있든 없든 상관 없기 때문에 set로 선언해준다.
그리고 노트 2에 있는 숫자 순서대로 결과를 출력해야하기 때문에 노트 2는 리스트로 선언해준다.
"""


class Footnote(object):
    footnote_type_id = None
    footnote_id = None
    code = None
    description = None
    measure_sid = None

    def __init__(self, footnote_type_id, footnote_id, description, measure_sid = None):
        self.footnote_type_id = footnote_type_id
        self.footnote_id = footnote_id
        self.code = self.footnote_type_id + self.footnote_id
        self.description = description
        self.measure_sid = measure_sid

    def as_dict(self):
        obj_d = {
            'code': self.code,
            'description': self.description,
            'formatted_description': self.description
        }
        return obj_d


class Solution(object):
    def checkSubarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        a=set([nums[0]%k,0])
        S=nums[0]
        print(len(nums))
        for i in range(1,len(nums)):
            # if(i%1000==0):print(i)
            S=(S+nums[i])%k
            if((nums[i]%k==0)&(nums[i-1]%k==0)):
                return True
            if(nums[i]%k==0):
                continue;
            if(S in a):
                return True;
            a.add(S)
        return False


import csv
from dateutil.parser import parse

allTime = []
date = []
time = []
lat = []
lon = []

with open('uber-raw-data-aug-14.csv', 'r') as data:
    data = csv.reader(data, delimiter=',', quotechar='|')
    for row in data:
        allTime.append((''.join(row[0])))
        lat.append((''.join(row[1])))
        lon.append((''.join(row[2])))

#Working time seperator
# for x in range (1, len(allTime)):
#     temp = allTime[x].split(" ")
#     date.append(temp[0])
#     time.append(temp[1])
# print(date)

test = parse(date)
print(test)