from PyQt4 import QtGui, QtCore
from game import Config

class OptionsWindow(QtGui.QWidget):

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

        self.initUI()

    def initUI(self):
        username = QtGui.QLabel('Username')
        self.usernameEdit = QtGui.QLineEdit()
        self.usernameEdit.setText("Unknown")
        board_width = QtGui.QLabel('Width of board')
        self.board_width = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        board_height = QtGui.QLabel('Height of board')
        self.board_height = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        rock_count = QtGui.QLabel('Number of rocks')
        self.rock_count = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        diamond_count = QtGui.QLabel('Number of diamonds')
        self.diamond_count = QtGui.QSlider(QtCore.Qt.Horizontal, self)

        lcd_width = QtGui.QLCDNumber(self)
        lcd_height = QtGui.QLCDNumber(self)
        lcd_rocks = QtGui.QLCDNumber(self)
        lcd_diamonds = QtGui.QLCDNumber(self)

        default = QtGui.QPushButton('Default options')
        save = QtGui.QPushButton('Save')

        save.clicked.connect(self.write_to_file)
        save.clicked.connect(self.close)
        default.clicked.connect(self.write_default_options)
        default.clicked.connect(self.close)

        hbox_username = QtGui.QHBoxLayout()
        hbox_username.addWidget(username)
        hbox_username.addWidget(self.usernameEdit)

        hbox_width = QtGui.QHBoxLayout()
        hbox_width.addWidget(board_width)
        hbox_width.addWidget(lcd_width)

        hbox_height = QtGui.QHBoxLayout()
        hbox_height.addWidget(board_height)
        hbox_height.addWidget(lcd_height)

        hbox_rocks = QtGui.QHBoxLayout()
        hbox_rocks.addWidget(rock_count)
        hbox_rocks.addWidget(lcd_rocks)

        hbox_diamonds = QtGui.QHBoxLayout()
        hbox_diamonds.addWidget(diamond_count)
        hbox_diamonds.addWidget(lcd_diamonds)

        vbox = QtGui.QVBoxLayout()
        vbox.addLayout(hbox_username)
        vbox.addLayout(hbox_width)
        vbox.addWidget(self.board_width)
        vbox.addLayout(hbox_height)
        vbox.addWidget(self.board_height)
        vbox.addLayout(hbox_rocks)
        vbox.addWidget(self.rock_count)
        vbox.addLayout(hbox_diamonds)
        vbox.addWidget(self.diamond_count)

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(default)
        hbox.addWidget(save)

        vbox.addLayout(hbox)

        self.board_width.valueChanged.connect(lcd_width.display)
        self.board_height.valueChanged.connect(lcd_height.display)
        self.rock_count.valueChanged.connect(lcd_rocks.display)
        self.diamond_count.valueChanged.connect(lcd_diamonds.display)

        self.setLayout(vbox)

        self.setGeometry(300, 300, 300, 350)
        self.setWindowTitle('Options')
        self.show()

    def write_to_file(self):
        config = Config.get()

        config.properties.update({
            'username': self.usernameEdit.text(),
            'board_width': self.board_width.value(),
            'board_height': self.board_height.value(),
            'rock_count': self.rock_count.value(),
            'diamond_count': self.diamond_count.value()
        })

        config.save()

    def write_default_options(self):
        Config.get().destroy()

class HelpWindow(QtGui.QWidget):

    def __init__(self):
        super(HelpWindow, self).__init__()
        self.initUI()

    def initUI(self):
        with open('about.html') as f:
            text = f.read()
        label = QtGui.QLabel(self)
        label.setText(text)

        self.setGeometry(250, 100, 800, 600)
        self.setWindowTitle('Help')
        self.show()

class FormWidget(QtGui.QWidget):
    def __init__(self, parent, image_repository):
        super(FormWidget, self).__init__(parent)
        self.image_repository = image_repository
        self.initUI()

    def initUI(self):
        self.pic = QtGui.QLabel(self)
        self.new_game_button = QtGui.QPushButton("New Game")
        self.quit_button = QtGui.QPushButton("Quit")

        self.pic.setPixmap(self.image_repository.get_pixmap('boulder_dash', 500, 500, QtCore.Qt.KeepAspectRatio))
        self.pic.setScaledContents(True)
        self.pic.setAlignment(QtCore.Qt.AlignCenter)

        vbox = QtGui.QVBoxLayout(self)

        vbox.addWidget(self.pic)
        vbox.addWidget(self.new_game_button)
        vbox.addWidget(self.quit_button)

        self.setLayout(vbox)
        self.show()


from sys import maxsize

class Group:

    def __init__(self, name=None, header=None, footer=None, id=None):
        self.name = name
        self.header = header
        self.footer = footer
        self.id = id

    def __repr__(self):
        return "%s:%s" % (self.id, self.name)

    def __eq__(self, other):
        return (self.id is None or other.id is None or self.id == other.id) and self.name == other.name

    def id_or_max(self):
        if self.id:
            return int(self.id)
        else:
            return maxsize

class Contact:
    def __init__(self, userfirstname=None, usermiddlename=None, userlastname=None, nick=None, title=None, company=None, address=None, home=None,
                mobile=None, workphone=None, fax=None, email=None, email2=None, email3=None, homepage=None, birthyear=None, anniversaryyear=None, secondaddres=None,
                homephone=None, notes=None, id=None):
        self.userfirstname = userfirstname
        self.usermiddlename = usermiddlename
        self.userlastname = userlastname
        self.nick = nick
        self.title = title
        self.company = company
        self.address = address
        self.home = home
        self.mobile = mobile
        self.workphone = workphone
        self.fax = fax
        self.email = email
        self.email2 = email2
        self.email3 = email3
        self.homepage = homepage
        self.birthyear = birthyear
        self.anniversaryyear = anniversaryyear
        self.secondaddres = secondaddres
        self.homephone = homephone
        self.notes = notes
        self.id = id

    def __repr__(self):
        return "%s:%s" % (self.id, self.userfirstname)

    def __eq__(self, other):
        return (self.id is None or other.id is None or self.id == other.id) and self.userfirstname == other.userfirstname

    def id_or_maxc(self):
        if self.id:
            return int(self.id)
        else:
            return maxsize


from datetime import datetime
import os
import re
import numpy as np
from lxml import html

def get_datetime(s:str):
    date, time = s.split(', ')
    day, month, year = date.split('.')
    hour, minute = re.split(r'\W', time.split(' ')[0])
    return datetime(int(year), int(month), int(day), int(hour), int(minute), 0, 0).isoformat()

def parse_page(page:bytes):
    # Parse the content
    root = html.fromstring(page.content)

    # xpath stuff
    banner_xpath = '/html/body/div[1]/div/div/div/div'
    successful_xpath = banner_xpath + '/p[1]/strong'
    successful_count = np.int64(root.xpath(successful_xpath)[0].text.replace('.', ''))

    successful_time_xpath = banner_xpath + '//p[1]'
    successful_time_text = root.xpath(successful_time_xpath)[0].text_content()
    if not isinstance(successful_time_text, str):
        raise Exception('Could not get text')
    s = successful_time_text.split(' (')[-1].strip('()')
    successful_time = get_datetime(s)

    paid_out_count_xpath = banner_xpath + '/p[2]/strong'
    paid_out_text = root.xpath(paid_out_count_xpath)[0].text
    if not isinstance(paid_out_text, str):
        raise Exception('Could not get text')
    paid_out_count = np.int64(paid_out_text.replace('.', ''))
    paid_out_sum = np.int64(root.xpath(paid_out_count_xpath)[1].text.replace('.', '').split(' ')[0])

    paid_out_time_xpath = banner_xpath + '//p[2]'
    paid_out_time_text = root.xpath(paid_out_time_xpath)[0].text_content()
    if not isinstance(paid_out_time_text, str):
        raise Exception('Could not get text')
    s = paid_out_time_text.split(' (')[-1].strip('()')
    paid_out_time = get_datetime(s)

    return successful_count, successful_time, paid_out_count, paid_out_sum, paid_out_time

class LogLevel:
    INFO = 'info'
    ERROR = 'error'
class Logger:
    def __init__(self, log_location='../logs/tracker_log.log') -> None:
        self.log_location = log_location

    def log(self, caller:str,  level:LogLevel, message:str):
        # compose the message
        m = f'[{caller} {level}][{datetime.now()}]: {message}\n'

        # create folder if it does not exist
        if not os.path.exists('../logs'):
            os.mkdir('../logs')

        if not os.path.exists(self.log_location):
            with open(self.log_location, 'w') as f:
                f.write(m)

        with open(self.log_location, 'a') as f:
            f.write(m)


#Gabriel AraÃºjo, Victor Prado, Vinicius Fernandes, Wesciley Junio

import numpy as np

x = np.array([10, 11, 12, 13, 14, 15]) #TABELA
fx = np.array([1400, 1900, 2500, 3250, 4200, 5400])

def pos(k) : #POSIÃÃO
    cont=0
    for i in x:
        if i == k:
            return cont
        else: cont = cont + 1

def segunda(a,b):  #SEGUNDA DIVISÃO
    l1 = fx[a]-fx[b]
    l2 = x[a]-x[b]
    return (l1/l2)

def terceira(a,b,c): #TERCEIRA DIVISÃO
    l1 = segunda(a,b) - segunda(b,c)
    l2 = x[a]-x[c]
    return (l1/l2)

def quarta(a,b,c,d): #QUARTA DIVISÃO
    l1 = terceira(a,b,c) - terceira(b,c,d)
    l2 = x[a]-x[d]
    return (l1/l2)

def quinta(a,b,c,d,e): #QUINTA DIVISÃO
    l1 = quarta(a,b,c,d) - quarta(b,c,d,e)
    l2 = x[a]-x[e]
    return (l1/l2)

def sexta(a,b,c,d,e,f): #SEXTA DIVISÃO
    l1 = quinta(a,b,c,d,e) - quinta(b,c,d,e,f)
    l2 = x[a]-x[f]
    return (l1/l2)

def f3(k): #POLINOMIO INTERPOLADOR DE NEWTON DE 3a ORDEM
    b1 = fx[0]
    b2 = segunda(1,0)
    b3 = terceira(2,1,0)
    b4 = quarta(3,2,1,0)

    f3 = b1 + (b2*(k-x[0])) + (b3*(k-x[0])*(k-x[1])) + (b4*(k-x[0])*(k-x[1])*(k-x[2]))
    return f3

def coeficientes(): #CÃLCULO DOS COEFICIENTES
    b1 = fx[0]
    b2 = segunda(1,0)
    b3 = terceira(2,1,0)
    b4 = quarta(3,2,1,0)
    print("\nB1= " + str(b1) + "\nB2=" + str(b2) +"\nB3=" + str(b3) + "\nB4=" + str(b4))

#LETRA A
print("\n")
print("Coeficientes: \n")
coeficientes()

a, b = 0,130

# Insira o valor do incremento:
Dx = 0.2

# Inicia as variáveis
x1, x2 = a, a+Dx
F1, F2 = f3(x1), f3(x2)

# Executa o laço enquanto F1*F2 for maior que zero, ou, quando x1 for maior e igual a b.
while F1*F2 > 0.0:
    if x1 >=b:

        break
    x1, F1 = x2, F2
    x2 = x1 + Dx
    F2 = f3(x2)
else:
    # Imprime os limites do pequeno intervalo de comprimento Dx que contém pelo menos
    # uma raíz da função
    print("\n")
    print("Valor de x está entre: ")
    print(x1, x2)

print("\n")


from ucondb.webapi import UConDBWebClient
import sys, getopt, json

Usage = """
python load_beam_data.py <server URL> <start run> <end run> <output directory>
"""

folder = "public.sp_protodune"
object = "configuration"

server_url, start_run, end_run, out_dir = sys.argv[1:]
start_run = int(start_run)
end_run = int(end_run)

client = UConDBWebClient(server_url)
versions = list(client.lookup_versions(folder, object, key_min=str(start_run), key_max=str(end_run+1)))
print(len(versions), " version received")

version_metas = {}      # version id -> meta

for v in versions:
    k = v.get("key")
    if k is not None:
        k = int(k)              # for ProtoDUNE, key is run number
        if k >= start_run and k <= end_run:
            version_metas[v["id"]] = v
            print("Found run #", k, "   version id=", v["id"])

open("ids.json","w").write(json.dumps(list(version_metas.keys())))

for vid, blob in client.get_versions_data(folder, version_metas.keys()):
    meta = version_metas[vid]
    run_number = int(meta["key"])
    print("run:", run_number, "   blob:", len(blob))
    f = open(out_dir + f"/info_{run_number}.fhicl", "wb")
    f.write(blob)
    f.close()


import pygame
from pygame.sprite import Sprite
from Player import Player
import random

class Ball(Sprite):
	def __init__(self, screen):
		super(Ball,self). __init__()
		self.image = pygame.image.load("soccer_ball2.png")
		self.rect = self.image.get_rect()
		self.x = random.randrange(1, 900)
		self.y = random.randrange(1, 500)
		self.width = 20
		self.height = 20
		self.speed = 0
		self.screen = screen

	def draw_me(self):
		self.screen.blit(self.image, [self.x, self.y])
		self.rect.left = self.x
		self.rect.right = self.x
		self.rect.top = self.y
		self.rect.bottom = self.y

	# def checkCollision(self, sprite1, sprite2):
	# 	col = pygame.sprite.collide_rect(sprite1, sprite2)
	# 	if col == True:
	# 		self.x += 1


import json

from django.shortcuts import render
from django.http import HttpResponse
from django.templatetags.static import static
from django.views.decorators.http import require_GET, require_POST

def home(request):
    context = {
        'name': 'bbamsu211',
        'profile': static('images/profile.jpeg'),
        'content_images': [
            static('images/content-1.jpeg'),
            static('images/content-2.jpeg'),
            static('images/content-3.jpeg')
        ],
        'content': '서울숲 나들이~',
        'like': 100,
        'is_like': False,
        'comments': [
            {
                'id': 1,
                'user': 'pirogramming_official',
                'text': '농땡이 피울 시간에'
            },
            {
                'id': 2,
                'user': 'pirogramming_official',
                'text': '강의 준비나 잘 해오시지요.'
            }
        ]
    }
    return render(request, 'app/home.html', context)

@require_GET
def get_comments_api(request):
    comments = [
        {
            'id': 3,
            'user': 'bbamsu211',
            'text': '죄송합니다,,,'
        },
        {
            'id': 4,
            'user': 'bbamsu211',
            'text': '열심히 준비할게요!'
        },
        {
            'id': 5,
            'user': 'bbamsu211',
            'text': '다음에 또 불러주세요'
        }
    ]

    context = {
        'comments': comments
    }

    return HttpResponse(json.dumps(context), content_type='application/json')

def get_param(request, key, default_value=None):
    request_body = json.loads(request.body.decode('utf-8'))
    return request_body[key] if key in request_body else default_value

@require_POST
def post_comment_api(request):
    comment = get_param(request, 'comment', '')
    user = get_param(request, 'user', '')
    print(comment, user)

    context = {
        'id': 6
    }

    return HttpResponse(json.dumps(context), content_type='application/json')

@require_POST
def post_like_api(request):
    is_like = get_param(request, 'is_like', False)

    if is_like:
        likes = 101
    else:
        likes = 100

    print(is_like, likes)

    context = {
        'likes': likes
    }

    return HttpResponse(json.dumps(context), content_type='application/json')


#Danny Toback and Andre Amirsaleh

import re

def prOne():
    f = open("SocialJusticeMinor.html",'r',encoding='utf-8')
    p = re.compile('([A-Z]{4}(/?))+ [1-3][0-9]{2}')
    s = f.readlines()
    for line in s:
        for t in p.finditer(line):
            print(t.group())
            f.close()
#prOne()

def prTwo():
    f = open("ContactBucknell.html",'r',encoding='utf-8')
    p = re.compile('[0-9]{3}.[0-9]{3}.[0-9]{4}')
    s = f.readlines()
    for line in s:
        for t in p.finditer(line):
            print(t.group())
            f.close()
#prTwo()

def prThree():
    f = open("ContactBucknell.html",'r',encoding='utf-8')
    p = re.compile('[a-z.]+@[a-z.]+')
    s = f.readlines()
    for line in s:
        for t in p.finditer(line):
            print(t.group())
            f.close()
#prThree()

def prFour():
    f = open("ContactBucknell.html",'r',encoding='utf-8')
    p = re.compile('([a-z]+)[.]([a-z]+)(@[a-z.]+)')
    s = f.readlines()
    f1 = open("ContactBucknell2.html", 'w', encoding='utf-8')
    for line in s:
        f1.write(p.sub(r'\2.\1\3', line))
    f.close()
    f1.close()
prFour()

def main():
    while(True):
        choice = int(input("Which Problem are you testing? Enter -1 to exit.\n"))
        if choice == 1:
            prOne()
        elif choice == 2:
            prTwo()
        elif choice == 3:
            prThree()
        elif choice == 4:
            prFour()
            print("File has been updated\n")
        elif choice == -1:
            break
        else:
            print("Please Enter a Number Between 1 and 4\n")

main()


#!/usr/bin/env python
from glob import glob
import json
import logging

def main(**kwargs):
    for fname in glob('coin/*.json'):
        try:
            coin = json.load(open(fname))
        except ValueError as ex:
            logging.error('Error in %s' % fname, exc_info=ex)
        else:
            missing = []
            for key, val in coin.items():
                if val == "?" or val == []:
                    missing.append((key, val))
            if missing:
                print('File: %s' % fname)
                for key, val in missing:
                    print(' * %s: %s' % (key, val))

if __name__ == '__main__':
    main()


import docplex.mp.model as cpx
import itertools
#import pandas
import random
import pandas as pd

# imput parameters
T = 10
P = 12 #max number of players in dataset
set_T = range(1, T+1)   # i in set T
set_P = range(1, P+1)   # j in set P

## Import data
values= {1:[112 for i in range(P)], 2:[116 for i in range(P)], 3:[172 for i in range(P)], 4:[192 for i in range(P)],
5:[116 for i in range(P)], 6:[113 for i in range(P)], 7:[192 for i in range(P)], 8:[142 for i in range(P)],
9:[110 for i in range(P)], 10:[115 for i in range(P)], 11:[152 for i in range(P)], 12:[132 for i in range(P)]} #some sort of  dict of player value projections...where key is player ID in dataset
salaries= {1:[11.2 for i in range(P)], 2:[11.6 for i in range(P)], 3:[17.2 for i in range(P)], 4:[19.2 for i in range(P)],
5:[11.6 for i in range(P)], 6:[11.3 for i in range(P)], 7:[19.2 for i in range(P)], 8:[14.2 for i in range(P)],
9:[11.0 for i in range(P)], 10:[11.5 for i in range(P)], 11:[15.2 for i in range(P)], 12:[13.2 for i in range(P)]} #some sort of dict of player value projections...where key is player ID in dataset
discount_rate = [0.03 for i in range(T)] #discount rate wrt time
Rarita_nationality = [1 for i in range(P)] #indicating wheather playeris raritan national ...wrt player ID indexing
age = [random.randint(17, 40) for i in range(P)]
position = {1:"GK", 2:"GK", 3:"FW", 4:"MF",
5:"MF", 6:"DF", 7:"DF", 8:"MF",
9:"DF", 10:"DF", 11:"MF", 12:"FW"}

V = {(i,j): values[i][j-1] for i in set_T for j in set_P}
W = {(i,j): salaries[i][j-1] for i in set_T for j in set_P}
O = {(i,j): salaries[i][j-1] * 0.1 for i in set_T for j in set_P} #fee received when lending
I = {(i,j): salaries[i][j-1] * 0.1 for i in set_T for j in set_P} #fee paid to borrow
rho = {i: discount_rate[i-1] for i in set_T}
Y_p = {j: Rarita_nationality[j-1] for j in set_P}
A_pt = {(i,j): (age[j-1] + i) for i in set_T for j in set_P}

## Import data
"""values= {1:[112 for i in range(T)], 2:[116 for i in range(T)], 3:[172 for i in range(T)], 4:[192 for i in range(T)],
5:[116 for i in range(T)], 6:[113 for i in range(T)], 7:[192 for i in range(T)], 8:[142 for i in range(T)],
9:[110 for i in range(T)], 10:[115 for i in range(T)], 11:[152 for i in range(T)], 12:[132 for i in range(T)]} #some sort of  dict of player value projections...where key is player ID in dataset
salaries= {1:[11.2 for i in range(T)], 2:[11.6 for i in range(T)], 3:[17.2 for i in range(T)], 4:[19.2 for i in range(T)],
5:[11.6 for i in range(T)], 6:[11.3 for i in range(T)], 7:[19.2 for i in range(T)], 8:[14.2 for i in range(T)],
9:[11.0 for i in range(T)], 10:[11.5 for i in range(T)], 11:[15.2 for i in range(T)], 12:[13.2 for i in range(T)]} #some sort of dict of player value projections...where key is player ID in dataset
discount_rate = [0.03 for i in range(T)] #discount rate wrt time
Rarita_nationality = [1 for i in range(T)] #indicating wheather playeris raritan national ...wrt player ID indexing
age = [random.randint(17, 40) for i in range(T)]"""

# set of possible player positions
R = ['GK', 'DF', 'MF', 'FW']
# max # of player in a team
N_bar = 11
# max GKs
N_GK = 1
# max DFs
N_DF = 4
# max MFs
N_MF = 4
# max FWs
N_FW = 2
# retiring age
A_bar = 40

## Forecasted Revenue figures (times 1...10)
R_0 = 995000000 #doobloons
C_0 = 150000000 # doubloons
R = [R_0 + R_0*0.05 for i in set_T]
## Forecasted Cost figures (times 1...10)
C = [C_0 + C_0*0.05 for i in set_T]
# Budget
B = {i: R[i-1] -C[i-1] for i in set_T}

## model set up
opt_model = cpx.Model(name="Rarita Football Team Composition")

# decision variables

#bool for lending of p at time t
lO_pt = {(i,j): opt_model.binary_var(name="lO_{0}_{1}".format(i,j)) for i in set_T for j in set_P}
#bool for borrowing of p at time t
lI_pt = {(i,j): opt_model.binary_var(name="lI_{0}_{1}".format(i,j)) for i in set_T for j in set_P}
#bool for belonging of p at time t to the team
y_pt = {(i,j): opt_model.binary_var(name="ypt_{0}_{1}".format(i,j)) for i in set_T for j in set_P}

# contraints

# the Raritan players are always owned time 1 contraint(not necessary constraint)
for j in set_P:
    opt_model.add_constraint(Y_p[j] == y_pt[1,j])

#team composition constraints
"""opt_model.add_constraint(N_GK == 2)
opt_model.add_constraint(N_DF >= 8)
opt_model.add_constraint(N_DF <= 10)
opt_model.add_constraint(N_MF >= 8)
opt_model.add_constraint(N_MF <= 10)
opt_model.add_constraint(N_FW >= 3)
opt_model.add_constraint(N_FW <= 4)"""

# Max number of players in a team will always be less that N_bar
constraints2 = {j : opt_model.add_constraint(ct=opt_model.sum(y_pt[i,j] for i in set_T) <= N_bar,
ctname="constraint_{0}".format(j)) for j in set_P}

# number of players at the club, borrowed and lent out are always equal to N_bar
constraints3 = {j : opt_model.add_constraint(sum(y_pt[i,j] + lO_pt[i,j] - lI_pt[i,j] for i in set_T) <= N_bar,
ctname="constraint_{0}".format(j)) for j in set_P}

# only borrow if player is not owned
for i in set_T:
    for j in set_P:
        opt_model.add_constraint(y_pt[i,j] - lO_pt[i,j] >= 0)

# only lent if palyer is owned:
for i in set_T:
    for j in set_P:
        opt_model.add_constraint(y_pt[i,j] + lI_pt[i,j] <= 0)

# no players are considered above A_bar -------------not perfect constrint
"""opt_model.add_constraint(A_pt[i,j] <= A_bar) """

#budget constraint
constraints3 = {j : opt_model.add_constraint(ct=opt_model.sum((I[i,j]*lI_pt[i,j] - O[i,j]*lO_pt[i,j]) for j in set_P) <= B[i],
ctname="constraint_{0}".format(i))for i in set_T}

#sunset value
# S_T = sum(V[T,j] * y_pt[T,j] for j in set_P)

# sunset value greater than 0
opt_model.add_constraint(sum(V[T,j] * y_pt[T,j] for j in set_P) >= 0)

# objective
objective = opt_model.maximize((1/((1+rho[i])**(i-1)) * V[i,j] * y_pt[i,j] + O[i,j] * lO_pt[i,j] - I[i,j] * lI_pt[i,j]
- W[i,j] * (y_pt[i,j] + lI_pt[i,j] - lO_pt[i,j])) + 1/((1+rho[T])**(T-1)) * V[T,j])

# solving
sol = opt_model.solve()
opt_model.print_solution()

opt_df = pd.DataFrame.from_dict(y_pt, orient="index", columns = ["variable_object"])
opt_df.index =  pd.MultiIndex.from_tuples(opt_df.index, names=["column_i", "column_j"])
opt_df.reset_index(inplace=True)
opt_df["solution_value"] = opt_df["variable_object"].apply(lambda item: item.solution_value)

opt_df.drop(columns=["variable_object"], inplace=True)
opt_df.to_csv("./optimization_solution.csv")


import logging
from pprint import pprint
from sys import stdout as STDOUT

# Example 1
class LazyDB(object):
    def __init__(self):
        self.exists = 5

    def __getattr__(self, name):
        value = 'Value for %s' % name
        setattr(self, name, value)
        return value

# Example 2
data = LazyDB()
print('Before:', data.__dict__)
print('foo:   ', data.foo)
print('After: ', data.__dict__)

# Example 3
class LoggingLazyDB(LazyDB):
    def __getattr__(self, name):
        print('Called __getattr__(%s)' % name)
        return super().__getattr__(name)

data = LoggingLazyDB()
print('exists:', data.exists)
print('foo:   ', data.foo)
print('foo:   ', data.foo)

# Example 4
class ValidatingDB(object):
    def __init__(self):
        self.exists = 5

    def __getattribute__(self, name):
        print('Called __getattribute__(%s)' % name)
        try:
            return super().__getattribute__(name)
        except AttributeError:
            value = 'Value for %s' % name
            setattr(self, name, value)
            return value

data = ValidatingDB()
print('exists:', data.exists)
print('foo:   ', data.foo)
print('foo:   ', data.foo)

# Example 5
try:
    class MissingPropertyDB(object):
        def __getattr__(self, name):
            if name == 'bad_name':
                raise AttributeError('%s is missing' % name)
            value = 'Value for %s' % name
            setattr(self, name, value)
            return value

    data = MissingPropertyDB()
    data.foo  # Test this works
    data.bad_name
except:
    logging.exception('Expected')
else:
    assert False

# Example 6
data = LoggingLazyDB()
print('Before:     ', data.__dict__)
print('foo exists: ', hasattr(data, 'foo'))
print('After:      ', data.__dict__)
print('foo exists: ', hasattr(data, 'foo'))

# Example 7
data = ValidatingDB()
print('foo exists: ', hasattr(data, 'foo'))
print('foo exists: ', hasattr(data, 'foo'))

# Example 8
class SavingDB(object):
    def __setattr__(self, name, value):
        # Save some data to the DB log
        super().__setattr__(name, value)

# Example 9
class LoggingSavingDB(SavingDB):
    def __setattr__(self, name, value):
        print('Called __setattr__(%s, %r)' % (name, value))
        super().__setattr__(name, value)

data = LoggingSavingDB()
print('Before: ', data.__dict__)
data.foo = 5
print('After:  ', data.__dict__)
data.foo = 7
print('Finally:', data.__dict__)

# Example 10
class BrokenDictionaryDB(object):
    def __init__(self, data):
        self._data = data

    def __getattribute__(self, name):
        print('Called __getattribute__(%s)' % name)
        return self._data[name]

# Example 11
try:
    data = BrokenDictionaryDB({'foo': 3})
    data.foo
except:
    logging.exception('Expected')
else:
    assert False

# Example 12
class DictionaryDB(object):
    def __init__(self, data):
        self._data = data

    def __getattribute__(self, name):
        data_dict = super().__getattribute__('_data')
        return data_dict[name]

data = DictionaryDB({'foo': 3})
print(data.foo)


#Downloads RDS (data <=2019) Facility data (with origin data) which does not track waste type from this website: https://www2.calrecycle.ca.gov/LGCentral/DisposalReporting/Origin/FacilitySummary

import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import chromedriver_autoinstaller
import time
import glob
import os

chromedriver_autoinstaller.install()
chromeOptions = webdriver.ChromeOptions()
prefs = {"download.default_directory" : "/home/leeld/Downloads/files"}
#change the directory to the whatever you want
chromeOptions.add_experimental_option("prefs",prefs)
#chromedriver = "/usr/bin/chromedriver"
#you need to change the path of the chromedriver depending on your setup (I'm on Lubuntu 20.04)
driver = webdriver.Chrome(options=chromeOptions)
wait = WebDriverWait(driver, 20)

url = "https://www2.calrecycle.ca.gov/LGCentral/DisposalReporting/Origin/FacilitySummary"

driver.get(url)
dropdown = driver.find_element(By.ID, "ReportType")
dropdown.find_element(By.XPATH, "//option[. = 'Jurisdiction of Origin Waste Disposal']").click()
select_el = wait.until(EC.presence_of_element_located((By.XPATH, '//select[@id="SWISNumber"]')))
facilities = select_el.find_elements(By.TAG_NAME, 'option')
total_facilities = len(facilities)

# len - 1 because the 1st option is blank
print(f"Total facilities: {total_facilities - 1}")
btn = driver.find_element(By.XPATH, '//button[@id="SearchButton"]')

for i in range(1, len(facilities)):
    print(f"Clicking Facility - {facilities[i].text}")
    facilities[i].click()
    btn.click()
    time.sleep(2)
driver.close()

#Merge all of the spreadsheets (one for each facility) into one master spreadsheet
os.chdir("/home/leeld/Downloads/files")
extensions = ("*xlsx")
filenames = []  # made 'filename' plural to indicate it's a list

# building list of filenames moved to separate loop
for files in extensions:
    filenames.extend(glob.glob(files))
# getting excel files to be merged
print('File names:', filenames)

# empty data frame for the new output excel file with the merged excel files
outputxlsx = pd.DataFrame()

# for loop to iterate all excel files
for file in filenames:
   # using concat for excel files
   # after reading them with read_excel()
   df = pd.concat(pd.read_excel( file, sheet_name=None), ignore_index=True, sort=False)
   #Clean up unwanted text from spreadsheet
   df = df[~df['Unnamed: 0'].isin(['Jurisdiction or Origin Waste Disposal By Facility'])]
   # appending data of excel files
   outputxlsx = outputxlsx.append( df, ignore_index=True)
print('All spreadsheets merged into one file ("RDS_FacilityReports(origin data).xlsx"')
outputxlsx.to_excel("/home/leeld/Downloads/files/RDS_FacilityReports(origin data).xlsx", index=False)
#Delete data files for each county
for filename in glob.glob("/home/leeld/Downloads/files/FacilitySummary*"):
    os.remove(filename)
print('Deleting data spreadsheets')


#!/usr/bin/env python

"""Tool to test the performances of MariaDB, Galera and CockroachDB with
OpenStack on Grid'5000

Usage:
    juice [-h | --help] [-v | --version] <command> [<args>...]

Options:
    -h --help      Show this help
    -v --version   Show version number

Commands:
    deploy         Claim resources from g5k and configure them
    openstack      Add OpenStack Keystone to the deployment
    rally          Benchmark the Openstack
    stress         Launch sysbench tests (after a deployment)
    emulate        Emulate network using tc
    backup         Backup the environment
    destroy        Destroy all the running dockers (not the resources)
    info           Show information of the actual deployment
    help           Show this help

Run 'juice COMMAND --help' for more information on a command
"""

import os
import logging
import sys
import pprint
import yaml
import json
import operator
import pickle

from docopt import docopt
from enoslib.api import (generate_inventory, emulate_network,
                         validate_network)
from enoslib.task import enostask, _save_env

from utils import (JUICE_PATH, ANSIBLE_PATH, SYMLINK_NAME, doc,
                   doc_lookup, run_ansible, g5k_deploy)

logging.basicConfig(level=logging.DEBUG)

tc = {
    "enable": True,
    "default_delay": "0ms",
    "default_rate": "10gbit",
    "constraints": [{
        "src": "database",
        "dst": "database",
        "delay": "0ms",
        "rate": "10gbit",
        "loss": "0",
        "network": "database_network",
    }],
    "groups": ['database'],
}

######################################################################
## SCAFFOLDING
######################################################################

@doc()
@enostask()
def deploy(conf, provider='g5k', force_deployment=False, xp_name=None,
           tags=['provide', 'inventory', 'scaffold'], env=None,
           **kwargs):
    """
usage: juice deploy [--conf CONFIG_PATH] [--provider PROVIDER]
                    [--force-deployment]
                    [--xp-name NAME] [--tags TAGS...]

Claim resources from PROVIDER and configure them.

Options:
  --conf CONFIG_PATH    Path to the configuration file describing the
                        deployment [default: ./conf.yaml]
  --provider PROVIDER   Provider to target [default: g5k]
  --force-deployment    Force provider to redo the deployment
  --xp-name NAME        NAME of the folder generated by juice for this
                        new deployment.
  --tags TAGS           Only run tasks relative to the specific tags
                        [default: provide inventory scaffold]
    """
    # Read the configuration
    config = {}

    if isinstance(conf, str):
        # Get the config object from a yaml file
        with open(conf) as f:
            config = yaml.load(f)
    elif isinstance(conf, dict):
        # Get the config object from a dict
        config = conf
    else:
        # Data format error
        raise Exception(
            'conf is type {!r} while it should be a yaml file or a dict'.format(type(conf)))

    env['db'] = config.get('database', 'cockroachdb')
    env['monitoring'] = config.get('monitoring', True)
    env['config'] = config

    # Claim resources on Grid'5000
    if 'provide' in tags:
        if provider == 'g5k' and 'g5k' in config:
            env['provider'] = 'g5k'
            updated_env = g5k_deploy(config['g5k'], env=xp_name,
                                     force_deploy=force_deployment)
            env.update(updated_env)
        else:
            raise Exception(
                'The provider {!r} is not supported or it lacks a configuration'.format(provider))

    # Generate the Ansible inventory file
    if 'inventory' in tags:
        env['inventory'] = os.path.join(env['resultdir'], 'hosts')
        generate_inventory(env['roles'] , env['networks'],
                           env['inventory'], check_networks=True)
        _save_env(env)

    # Deploy the resources, requires both g5k and inventory executions
    if 'scaffold' in tags:
        run_ansible('scaffolding.yml', extra_vars={
            'registry':    config['registry'],
            'db':          env['db'],
            'monitoring':  env['monitoring'],
            'enos_action': 'deploy'
            })

@doc()
@enostask()
def backup(backup_dir='current/backup', env=None, **kwargs):
    """
usage: juice backup [--backup-dir DIRECTORY]

Backup the experiment
  --backup-dir DIRECTORY  Backup directory [default: current/backup]
    """
    backup_dir = os.path.abspath(backup_dir)
    os.path.isdir(backup_dir) or os.mkdir(backup_dir)

    extra_vars = {
        "enos_action": "backup",
        "db": env['db'],
        "backup_dir": backup_dir,
        "monitoring": env['monitoring'],
        "rally_nodes": env.get('rally_nodes', [])
    }
    run_ansible('scaffolding.yml', extra_vars=extra_vars)
    run_ansible('openstack.yml', extra_vars=extra_vars)
    run_ansible('rally.yml', extra_vars=extra_vars)

@doc()
@enostask()
def destroy(env=None, hard=False, **kwargs):
    """
usage: juice destroy

Destroy all the running dockers (not destroying the resources), requires g5k
and inventory executions
    """
    extra_vars = {}
    # Call destroy on each component
    extra_vars.update({
        'monitoring': env.get('monitoring', True),
        "db": env.get('db', 'cockroachdb'),
        "rally_nodes": env.get('rally_nodes', []),
        "enos_action": "destroy"
    })
    run_ansible('scaffolding.yml', extra_vars=extra_vars)
    run_ansible('openstack.yml', extra_vars=extra_vars)
    run_ansible('rally.yml', extra_vars=extra_vars)

######################################################################
## Scaffolding ++
######################################################################

@doc()
@enostask()
def openstack(env=None, **kwargs):
    """
usage: juice openstack

Launch OpenStack.
    """
    # Generate inventory
    extra_vars = {
        "db": env['db'],
    }
    # use deploy of each role
    extra_vars.update({"enos_action": "deploy"})
    run_ansible('openstack.yml', extra_vars=extra_vars)

######################################################################
## Stress
######################################################################

@doc()
@enostask()
def stress(env=None, **kwargs):
    """
usage: juice stress

Launch sysbench tests.
    """
    # Generate inventory
    extra_vars = {
        "registry": env["config"]["registry"],
        "db": env.get('db', 'cockroachdb'),
        "enos_action": "stress"
    }
    # use deploy of each role
    run_ansible('stress.yml', extra_vars=extra_vars)

@doc()
@enostask()
def rally(files, directory, high, env=None, **kwargs):
    """
usage: juice rally [--files FILE... | --directory DIRECTORY] [--high]

Benchmark the Openstack

  --files FILE           Files to use for rally scenarios (name must be a path
from rally scenarios folder).
  --directory DIRECTORY  Directory that contains rally scenarios. [default:
keystone]
  --high                 Use high mode or not
    """
    logging.info("Launching rally using scenarios: %s" % (', '.join(files)))
    logging.info("Launching rally using all scenarios in %s directory.",
                 directory)

    database_nodes = [host.address for role, hosts in env['roles'].items()
                                   if role.startswith('database')
                                   for host in hosts]

    # In high mode: runs rally in all database nodes, in light mode:
    # runs rally on one database node. In light mode, we pick the
    # second database node (ie, `database_node[1]`) to not run rally
    # on the same node than the one that contains mariadb.
    rally_nodes = database_nodes if high else database_nodes[1]
    env['rally_nodes'] = rally_nodes

    extra_vars = {
        "rally_nodes": rally_nodes
    }
    if files:
        extra_vars.update({"rally_files": files})
    else:
        extra_vars.update({"rally_directory": directory})

    # use deploy of each role
    extra_vars.update({"enos_action": "deploy"})
    run_ansible('rally.yml', extra_vars=extra_vars)

######################################################################
## Other
######################################################################

@doc(tc)
@enostask()
def emulate(tc=tc, env=None, **kwargs):
    """
usage: juice emulate

Emulate network using: {0}
    """
    inventory = env["inventory"]
    roles = env["roles"]
    logging.info("Emulates using constraints: %s" % tc)
    emulate_network(roles, inventory, tc)
    env["latency"] = tc['constraints'][0]['delay']

@doc()
@enostask()
def validate(env=None, **kwargs):
    """
usage: juice validate

Validate network. Doesn't work for now since there is no flent installed
    """
    inventory = env["inventory"]
    roles = env["roles"]
    validate_network(roles, inventory)

@doc(SYMLINK_NAME)
@enostask()
def info(env, out, **kwargs):
    """
usage: enos info [-e ENV|--env=ENV] [--out=FORMAT]

Show information of the `ENV` deployment.

Options:
  -e ENV --env=ENV         Path to the environment directory. You should use
                           this option when you want to link a
                           specific experiment [default: {0}].
  --out FORMAT             Output the result in either json, pickle or
                           yaml format.
    """
    if not out:
        pprint.pprint(env)
    elif out == 'json':
        print(json.dumps(env, default=operator.attrgetter('__dict__')))
    elif out == 'pickle':
        print(pickle.dumps(env))
    elif out == 'yaml':
        print(yaml.dump(env))
    else:
        print("--out doesn't suppport %s output format" % out)
        print(info.__doc__)

@doc()
def help(**kwargs):
    """
usage: juice help

Show the help message
    """
    print(__doc__)

if __name__ == '__main__':
    args = docopt(__doc__,
                  version='juice version 1.0.0',
                  options_first=True)

    argv = [args['<command>']] + args['<args>']

    doc_lookup(args['<command>'], argv)


class Solution(object):
    def selfDividingNumbers(self, left, right):
        """
        :type left: int
        :type right: int
        :rtype: List[int]
        """
        def isSDN(num):
            for d in str(num):
                if int(d)==0 or num%int(d)!=0:
                    return False
            return True
        out=[]
        for i in range(left, right+1):
            if isSDN(i):
                out.append(i)
        return out


from __future__ import print_function, division, absolute_import
import numpy as np
import scipy.linalg
import warnings
# from ..base import BaseEstimator
# from ..utils import check_iter_of_sequences, array2d
from sklearn.base import TransformerMixin

__all__ = ['tICA']

# -----------------------------------------------------------------------------
# Code
# -----------------------------------------------------------------------------

from sklearn.base import BaseEstimator as SklearnBaseEstimator

class BaseEstimator(SklearnBaseEstimator):
    # http://msmbuilder.org/development/apipatterns.html

    def summarize(self):
        """Return some diagnostic summary statistics about this Markov model"""
        return 'NotImplemented'

def check_iter_of_sequences(sequences, allow_trajectory=False, ndim=2,
                            max_iter=None):
    """Check that ``sequences`` is a iterable of trajectory-like sequences,
    suitable as input to ``fit()`` for estimators following the MSMBuilder
    API.
    Parameters
    ----------
    sequences : object
        The object to check
    allow_trajectory : bool
        Are ``md.Trajectory``s allowed?
    ndim : int
        The expected dimensionality of the sequences
    max_iter : int, optional
        Only check at maximum the first ``max_iter`` entries in ``sequences``.
    """
    value = True
    for i, X in enumerate(sequences):
        if not isinstance(X, np.ndarray):
            if (not allow_trajectory) and isinstance(X, md.Trajectory):
                value = False
                break
        if not isinstance(X, md.Trajectory) and X.ndim != ndim:
            value = False
            break
        if max_iter is not None and i >= max_iter:
            break

    if not value:
        raise ValueError('sequences must be a list of sequences')

def _assert_all_finite(X):
    """Like assert_all_finite, but only for ndarray."""
    X = np.asanyarray(X)
    if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum())
            and not np.isfinite(X).all()):
        raise ValueError("Input contains NaN, infinity"
                         " or a value too large for %r." % X.dtype)

def array2d(X, dtype=None, order=None, copy=False, force_all_finite=True):
    """Returns at least 2-d array with data from X"""
    X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
    if force_all_finite:
        _assert_all_finite(X_2d)
    if X is X_2d and copy:
        X_2d = _safe_copy(X_2d)
    return X_2d

class tICA(BaseEstimator, TransformerMixin):
    """Time-structure Independent Component Analysis (tICA)

    Linear dimensionality reduction using an eigendecomposition of the
    time-lag correlation matrix and covariance matrix of the data and keeping
    only the vectors which decorrelate slowest to project the data into a lower
    dimensional space.

    Parameters
    ----------
    n_components : int, None
        Number of components to keep.
    lag_time : int
        Delay time forward or backward in the input data. The time-lagged
        correlations is computed between datas X[t] and X[t+lag_time].
    shrinkage : float, default=None
        The covariance shrinkage intensity (range 0-1). If shrinkage is not
        specified (the default) it is estimated using an analytic formula
        (the Rao-Blackwellized Ledoit-Wolf estimator) introduced in [5].
    kinetic_mapping : bool, default=False
        If True, weigh the projections by the tICA eigenvalues, yielding
         kinetic distances as described in [6].
    commute_mapping : bool, default=False
        If True, scale/weigh the projections by the sqrt(ti/2), yielding
        commute distance as described in [7].

    Attributes
    ----------
    components_ : array-like, shape (n_components, n_features)
        Components with maximum autocorrelation.
    offset_correlation_ : array-like, shape (n_features, n_features)
        Symmetric time-lagged correlation matrix, :math:`C=E[(x_t)^T x_{t+lag}]`.
    eigenvalues_ : array-like, shape (n_features,)
        Eigenvalues of the tICA generalized eigenproblem, in decreasing
        order.
    eigenvectors_ : array-like, shape (n_components, n_features)
        Eigenvectors of the tICA generalized eigenproblem. The vectors
        give a set of "directions" through configuration space along
        which the system relaxes towards equilibrium. Each eigenvector
        is associated with characteritic timescale
        :math:`- \frac{lag_time}{ln \lambda_i}, where :math:`lambda_i` is
        the corresponding eigenvector. See [2] for more information.
    means_ : array, shape (n_features,)
        The mean of the data along each feature
    n_observations_ : int
        Total number of data points fit by the model. Note that the model
        is "reset" by calling `fit()` with new sequences, whereas
        `partial_fit()` updates the fit with new data, and is suitable for
        online learning.
    n_sequences_ : int
        Total number of sequences fit by the model. Note that the model
        is "reset" by calling `fit()` with new sequences, whereas
        `partial_fit()` updates the fit with new data, and is suitable for
         online learning.
    timescales_ : array-like, shape (n_features,)
        The implied timescales of the tICA model, given by
        -offset / log(eigenvalues)

    Notes
    -----
    This method was introduced originally in [4]_, and has been applied to the
    analysis of molecular dynamics data in [1]_, [2]_, and [3]_. In [1]_ and [2]_,
    tICA was used as a dimensionality reduction technique before fitting
    other kinetic models.

    References
    ----------
    .. [1] Schwantes, Christian R., and Vijay S. Pande. J.
       Chem Theory Comput. 9.4 (2013): 2000-2009.
    .. [2] Perez-Hernandez, Guillermo, et al. J Chem. Phys (2013): 015102.
    .. [3] Naritomi, Yusuke, and Sotaro Fuchigami. J. Chem. Phys. 134.6
       (2011): 065101.
    .. [4] Molgedey, Lutz, and Heinz Georg Schuster. Phys. Rev. Lett. 72.23
       (1994): 3634.
    .. [5] Chen, Yilun, Ami Wiesel, and Alfred O. Hero III. ICASSP (2009)
    .. [6] Noe, F. and Clementi, C. arXiv arXiv:1506.06259 [physics.comp-ph]
           (2015)
    .. [7] Noe, F., Banisch, R., Clementi, C. J. Chem. Theory. Comput(2016).
            doi:10.1021/acs.jctc.6b00762
    """

    def __init__(self, n_components=None, lag_time=1, shrinkage=None,
                 kinetic_mapping=False, commute_mapping=False):
        self.n_components = n_components
        self.lag_time = lag_time
        self.shrinkage = shrinkage
        self.shrinkage_ = None
        self.kinetic_mapping = kinetic_mapping
        self.commute_mapping = commute_mapping
        if self.kinetic_mapping and self.commute_mapping:
            raise ValueError("Can't have both kinetic mapping and "
                             "commute mapping. Please only use one.")
        self.n_features = None
        self.n_observations_ = None
        self.n_sequences_ = None

        self._initialized = False

        # X[:-self.lag_time].T dot X[self.lag_time:]
        self._outer_0_to_T_lagged = None
        # X[:-self.lag_time].sum(axis=0)
        self._sum_0_to_TminusTau = None
        # X[self.lag_time:].sum(axis=0)
        self._sum_tau_to_T = None
        # X[:].sum(axis=0)
        self._sum_0_to_T = None

        # X[:-self.lag_time].T dot X[:-self.lag_time])
        self._outer_0_to_TminusTau = None
        # X[self.lag_time:].T dot X[self.lag_time:]
        self._outer_offset_to_T = None

        # the tICs themselves
        self._components_ = None
        # Cached results of the eigendecompsition
        self._eigenvectors_ = None
        self._eigenvalues_ = None

        # are our current tICs dirty? this indicates that we've updated
        # the model with more data since the last time we computed components_,
        # eigenvalues, eigenvectors, and is set by _fit
        self._is_dirty = True

    def _initialize(self, n_features):
        if self._initialized:
            return

        if self.n_components is None:
            self.n_components = n_features
        self.n_features = n_features
        self.n_observations_ = 0
        self.n_sequences_ = 0
        self._outer_0_to_T_lagged = np.zeros((n_features, n_features))
        self._sum_0_to_TminusTau = np.zeros(n_features)
        self._sum_tau_to_T = np.zeros(n_features)
        self._sum_0_to_T = np.zeros(n_features)
        self._outer_0_to_TminusTau = np.zeros((n_features, n_features))
        self._outer_offset_to_T = np.zeros((n_features, n_features))
        self._initialized = True

    def _solve(self):
        if not self._is_dirty:
            # So, we're not dirty, but someone might have changed
            # n_components
            if len(self._eigenvalues_) >= self.n_components:
                return
            # if we've already solved for enough eigenvectors then
            # we don't need to solve it again

        # just check to make sure we've actually seen some data
        if self.n_observations_ == 0:
            raise RuntimeError('The model must be fit() before use.')

        lhs = self.offset_correlation_
        rhs = self.covariance_

        if not np.allclose(lhs, lhs.T):
            raise RuntimeError('offset correlation matrix is not symmetric')
        if not np.allclose(rhs, rhs.T):
            raise RuntimeError('correlation matrix is not symmetric')

        vals, vecs = scipy.linalg.eigh(lhs, b=rhs,
            eigvals=(self.n_features-self.n_components, self.n_features-1))

        # sort in order of decreasing value
        ind = np.argsort(vals)[::-1]
        vals = vals[ind]
        vecs = vecs[:, ind]

        self._eigenvalues_ = vals
        self._eigenvectors_ = vecs

        self._is_dirty = False

    @property
    def score_(self):
        """Training score of the model, computed as the generalized matrix,
        Rayleigh quotient, the sum of the first `n_components` eigenvalues
        """
        self._solve()
        return self._eigenvalues_[:self.n_components].sum()

    @property
    def eigenvectors_(self):
        self._solve()
        return self._eigenvectors_[:, :self.n_components]

    @property
    def eigenvalues_(self):
        self._solve()
        return self._eigenvalues_[:self.n_components]

    @property
    def timescales_(self):
        self._solve()
        return -1. * self.lag_time / np.log(self._eigenvalues_[:self.n_components])

    @property
    def components_(self):
        return self.eigenvectors_[:, 0:self.n_components].T

    @property
    def means_(self):
        two_N = 2 * (self.n_observations_ - self.lag_time * self.n_sequences_)
        means = (self._sum_0_to_TminusTau + self._sum_tau_to_T) / float(two_N)
        return means

    @property
    def offset_correlation_(self):
        two_N = 2 * (self.n_observations_ - self.lag_time * self.n_sequences_)
        term = (self._outer_0_to_T_lagged + self._outer_0_to_T_lagged.T) / two_N

        means = self.means_
        value = term - np.outer(means, means)
        return value

    @property
    def covariance_(self):
        two_N = 2 * (self.n_observations_ - self.lag_time * self.n_sequences_)
        term = (self._outer_0_to_TminusTau + self._outer_offset_to_T) / two_N
        means = self.means_

        S = term - np.outer(means, means)  # sample covariance matix

        if self.shrinkage is None:
            sigma, self.shrinkage_ = rao_blackwell_ledoit_wolf(S, n=self.n_observations_)
        else:
            self.shrinkage_ = self.shrinkage
            p = self.n_features
            F = (np.trace(S) / p) * np.eye(p)  # shrinkage target
            sigma = (1-self.shrinkage)*S + self.shrinkage*F

        return sigma

    def fit(self, sequences, y=None):
        """Fit the model with a collection of sequences.

        This method is not online.  Any state accumulated from previous calls to
        fit() or partial_fit() will be cleared. For online learning, use
        `partial_fit`.

        Parameters
        ----------
        sequences: list of array-like, each of shape (n_samples_i, n_features)
            Training data, where n_samples_i in the number of samples
            in sequence i and n_features is the number of features.
        y : None
            Ignored

        Returns
        -------
        self : object
            Returns the instance itself.
        """
        self._initialized = False
        #check_iter_of_sequences(sequences, max_iter=3)  # we might be lazy-loading
        for X in sequences:
            self._fit(X)

        if self.n_sequences_ == 0:
            raise ValueError('All sequences were shorter than '
                             'the lag time, %d' % self.lag_time)

        return self

    def partial_fit(self, X):
        """Fit the model with X.

        This method is suitable for online learning. The state of the model
        will be updated with the new data `X`.

        Parameters
        ----------
        X: array-like, shape (n_samples, n_features)
            Training data, where n_samples in the number of samples
            and n_features is the number of features.

        Returns
        -------
        self : object
            Returns the instance itself.
        """
        self._fit(X)
        return self

    def transform(self, sequences):
        """Apply the dimensionality reduction on X.

        Parameters
        ----------
        sequences: list of array-like, each of shape (n_samples_i, n_features)
            Training data, where n_samples_i in the number of samples
            in sequence i and n_features is the number of features.

        Returns
        -------
        sequence_new : list of array-like, each of shape (n_samples_i, n_components)

        """
        #check_iter_of_sequences(sequences, max_iter=3)  # we might be lazy-loading
        sequences_new = []

        for X in sequences:
            X = array2d(X)
            if self.means_ is not None:
                X = X - self.means_
            X_transformed = np.dot(X, self.components_.T)

            if self.kinetic_mapping:
                X_transformed *= self.eigenvalues_

            if self.commute_mapping:
                # thanks to @maxentile and @jchodera for providing/directing to a
                # reference implementation in pyemma
                #(markovmodel/PyEMMA#963)
                # dampening smaller timescales based recommendtion of  [7]
                #
                # some timescales are NaNs and regularized timescales will
                # be negative when they are less than the lag time; all these
                # are set to zero using nan_to_num before returning
                regularized_timescales = 0.5 * self.timescales_ *\
                                         np.tanh( np.pi *((self.timescales_ - self.lag_time)
                                                          /self.lag_time) + 1)
                X_transformed *= np.sqrt(regularized_timescales / 2)
                X_transformed = np.nan_to_num(X_transformed)
            sequences_new.append(X_transformed)

        return sequences_new

    def partial_transform(self, features):
        """Apply the dimensionality reduction on X.

        Parameters
        ----------
        features: array-like, shape (n_samples, n_features)
            Training data, where n_samples in the number of samples
            and n_features is the number of features.  This function
            acts on a single featurized trajectory.

        Returns
        -------
        sequence_new : array-like, shape (n_samples, n_components)
            TICA-projected features

        Notes
        -----
        This function acts on a single featurized trajectory.

        """
        sequences = [features]
        return self.transform(sequences)[0]

    def fit_transform(self, sequences, y=None):
        """Fit the model with X and apply the dimensionality reduction on X.

        This method is not online. Any state accumulated from previous calls to
        `fit()` or `partial_fit()` will be cleared. For online learning, use
        `partial_fit`.

        Parameters
        ----------
        sequences: list of array-like, each of shape (n_samples_i, n_features)
            Training data, where n_samples_i in the number of samples
            in sequence i and n_features is the number of features.
        y : None
            Ignored

        Returns
        -------
        sequence_new : list of array-like, each of shape (n_samples_i, n_components)
        """
        self.fit(sequences)
        return self.transform(sequences)

    def _fit(self, X):
        X = np.asarray(array2d(X), dtype=np.float64)

        if X.shape[1] > X.shape[0]:
            warnings.warn("The number of features (%d) is greater than the length of the data (%d). The covariance matrix is not guaranteed to be positive definite." % (X.shape[1], X.shape[0]))

        self._initialize(X.shape[1])

        # We don't need to scream and shout here. Just ignore this data.
        if not len(X) > self.lag_time:
            warnings.warn("length of data (%d) is too short for the lag time (%d)" % (len(X), self.lag_time))
            return

        self.n_observations_ += X.shape[0]
        self.n_sequences_ += 1

        self._outer_0_to_T_lagged += np.dot(X[:-self.lag_time].T, X[self.lag_time:])
        self._sum_0_to_TminusTau += X[:-self.lag_time].sum(axis=0)
        self._sum_tau_to_T += X[self.lag_time:].sum(axis=0)
        self._sum_0_to_T += X.sum(axis=0)
        self._outer_0_to_TminusTau += np.dot(X[:-self.lag_time].T, X[:-self.lag_time])
        self._outer_offset_to_T += np.dot(X[self.lag_time:].T, X[self.lag_time:])

        self._is_dirty = True

    def score(self, sequences, y=None):
        """Score the model on new data using the generalized matrix Rayleigh quotient

        Parameters
        ----------
        sequences : list of array, each of shape (n_samples_i, n_features)
            Test data. A list of sequences in afeature space, each of which is a 2D
            array of possibily different lengths, but the same number of features.

        Returns
        -------
        gmrq : float
            Generalized matrix Rayleigh quotient. This number indicates how
            well the top ``n_timescales+1`` eigenvectors of this tICA model perform
            as slowly decorrelating collective variables for the new data in
            ``sequences``.

        References
        ----------
        .. [1] McGibbon, R. T. and V. S. Pande, "Variational cross-validation
           of slow dynamical modes in molecular kinetics" J. Chem. Phys. 142,
           124105 (2015)
        """

        assert self._initialized
        V = self.eigenvectors_

        # Note: How do we deal with regularization parameters like gamma
        # here? I'm not sure. Should C and S be estimated using self's
        # regularization parameters?
        m2 = self.__class__(shrinkage=self.shrinkage, n_components=self.n_components, lag_time=self.lag_time)
        for X in sequences:
            m2.partial_fit(X)

        numerator = V.T.dot(m2.offset_correlation_).dot(V)
        denominator = V.T.dot(m2.covariance_).dot(V)

        try:
            trace = np.trace(numerator.dot(np.linalg.inv(denominator)))
        except np.linalg.LinAlgError:
            trace = np.nan
        return trace

    def summarize(self):
        """Some summary information."""
        # force shrinkage to be calculated
        self.covariance_

        return """time-structure based Independent Components Analysis (tICA)
-----------------------------------------------------------
n_components        : {n_components}
shrinkage           : {shrinkage}
lag_time            : {lag_time}
kinetic_mapping     : {kinetic_mapping}

Top 5 timescales :
{timescales}

Top 5 eigenvalues :
{eigenvalues}
""".format(n_components=self.n_components, lag_time=self.lag_time,
           shrinkage=self.shrinkage_, kinetic_mapping=self.kinetic_mapping,
           timescales=self.timescales_[:5], eigenvalues=self.eigenvalues_[:5])

def rao_blackwell_ledoit_wolf(S, n):
    """Rao-Blackwellized Ledoit-Wolf shrinkaged estimator of the covariance
    matrix.

    Parameters
    ----------
    S : array, shape=(n, n)
        Sample covariance matrix (e.g. estimated with np.cov(X.T))
    n : int
        Number of data points.

    Returns
    -------
    sigma : array, shape=(n, n)
    shrinkage : float

    References
    ----------
    .. [1] Chen, Yilun, Ami Wiesel, and Alfred O. Hero III. "Shrinkage
        estimation of high dimensional covariance matrices" ICASSP (2009)
    """
    p = len(S)
    assert S.shape == (p, p)

    alpha = (n-2)/(n*(n+2))
    beta = ((p+1)*n - 2) / (n*(n+2))

    trace_S2 = np.sum(S*S)  # np.trace(S.dot(S))
    U = ((p * trace_S2 / np.trace(S)**2) - 1)
    rho = min(alpha + beta/U, 1)

    F = (np.trace(S) / p) * np.eye(p)
    return (1-rho)*S + rho*F, rho


##graphics dependencies
import tkinter as tk
from tkinter import ttk
from ttkbootstrap.constants import *
import ttkbootstrap as tb

##functional dependencies
import os
from datetime import datetime
import csv
class DraggableTreeview(tb.Treeview):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.SettingsFunctions = None
        self.bind("<Up>", self.move_up)
        self.bind("<Button-1>", self.focus_treeview)
        self.bind("<Down>", self.move_down)

    def move_up(self, event):
        item = self.selection()
        if item:
            index = self.index(item)
            if index > 0:
                self.move(item, '', index - 1)
                self.selection_set(item)
        return 'break'

    def move_down(self, event):
        item = self.selection()
        if item:
            index = self.index(item)
            if index < len(self.get_children()) - 1:
                self.move(item, '', index + 1)
                self.selection_set(item)
        return 'break'
    def focus_treeview(self, event):
        self.focus_set()

    def set_settings_functions(self, SettingsFunctions):
        self.SettingsFunctions = SettingsFunctions


algoritm = [ "C4.5" , "k - means" , "Метод опорных векторов" , "Apriori" ,
"EM" , "PageRank" , "AdaBoost", "kNN" , "Наивный байесовский классификатор" , "CART" ]
x = len(algoritm)

f = open("algoritm.csv", "w+")

for i in range(1, x):
    f.writelines(str(i) + " " + algoritm[i] + "\n")

f.close()


from rest_framework.routers import DefaultRouter
from .viewsset import admin_images_viewsets, Profile_viewset, Messages, users, admin_info_viewsets

router = DefaultRouter()
router.register('images', admin_images_viewsets, basename='images')
router.register('extra', admin_info_viewsets, basename='extra')
router.register('profile', Profile_viewset, basename='profile')
router.register('users', users, basename='users')
router.register('messages', Messages, basename='messages')

urlpatterns = router.urls


import logging

logger = logging.getLogger("download_tool")

APPEND_FAIL_MSG = """
Unable to append component to download error message while handling a download error.
"""

def download_error_handler(fpath, *args):
    err_str = ""
    for arg in args:
        err_str = append_err_comp(err_str, arg)

    with open(fpath, "a") as f:
        f.write(err_str + "\n")

def append_err_comp(msg, comp):
    try:
        return msg + str(comp) + "\t"

    except (ValueError, TypeError):
        logger.exception(APPEND_FAIL_MSG)


import pandas as pd
from datetime import datetime,date
import xlsxwriter
import datetime as dt
import numpy as np
import PySimpleGUI as sg
import traceback
import os

def my_function(filePath,filePath_INT,filePath2):

    filePath = filePath.strip("u202a")
    df=df2=df3=df4=df5=pd.read_excel (r'{}'.format(filePath))

    filePath_INT=filePath_INT.strip("u202a")
    df_int= pd.read_excel (r'{}'.format(filePath_INT))

    #--------------------------------------------------------------Dataframe Acumulados----------------------------------------------------------------
    df = df.rename(columns={'createdAtDate': 'fecha' })
    df['fecha'] = pd.to_datetime(df['fecha']).dt.date
    # condition0 = df['patient_address_city'] == 'Arecibo'
    # df = df[condition0]
    df = df.groupby(['fecha']).caseType.value_counts().unstack(fill_value=0)
    sum_column = df["Confirmed"] + df["Probable"] + df["Suspected"]
    df["Total"] = sum_column

    df['Acumulativo(Confirmado)'] = df['Confirmed'].cumsum()
    df = df.rename(columns={'Confirmed': 'Confirmado','Suspected': 'Sospechoso' })

    #----------------------------------Dataframe hospitalizados-----------------------------------------------------------------------------------------------
    df2['patient_birthDate'] = pd.to_datetime(df2['patient_birthDate']).dt.date
    condition = df2['isCurrentlyHospitalized'] == True
    new_dataframe = df2[condition]
    df2 =new_dataframe.filter(["patient_birthDate","patient_sex", "patient_address_city","caseType","caseStatus"])
    ref_date = dt.datetime.now()
    df2['age'] = df2['patient_birthDate'].apply(lambda x: len(pd.date_range(start = x, end = ref_date, freq = 'Y')))
    df2 = df2[["patient_birthDate", "age","patient_sex", "patient_address_city","caseType","caseStatus"]]
    df2 = df2.rename(columns={'patient_birthDate': 'DOB','age': 'EDAD','patient_sex':'Genero','patient_address_city':'Ciudad','caseType':'Tipo','caseStatus':'Estado' })
    df2['Reportado']=np.nan

    #---------------------------------Dataframe Viajeros-----------------------------------------------------------------------------------------
    df3['patient_birthDate'] = pd.to_datetime(df3['patient_birthDate']).dt.date
    df3.fillna(0, inplace = True)
    condition = df3['traveledDuringLast14Days'] == True
    df3 = df3[condition]
    df3 =df3.filter(["caseId","patient_birthDate","patient_sex", "patient_address_city","caseType","caseStatus"])
    ref_date = dt.datetime.now()
    df3['age'] = df3['patient_birthDate'].apply(lambda x: len(pd.date_range(start = x, end = ref_date, freq = 'Y')))
    df3 = df3[["caseId","patient_birthDate", "age","patient_sex", "patient_address_city","caseType","caseStatus"]]
    df3 = df3.rename(columns={'patient_birthDate': 'DOB','age': 'EDAD','patient_sex':'Genero','patient_address_city':'Ciudad','caseType':'Tipo','caseStatus':'Estado' })
    df3['Reportado']=np.nan

    #---------------------------------------------------Dataframe GIS---------------------------------------------------------------------------
    df4.fillna(0, inplace = True)
    ref_date = dt.datetime.now()
    df4['age'] = df4['patient_birthDate'].apply(lambda x: len(pd.date_range(start = x, end = ref_date, freq = 'Y')))
    df4 =df4.filter(["patient_birthDate","age","patient_sex", "patient_address_city","caseType","caseStatus"])
    df4 = df4.rename(columns={'patient_birthDate': 'Fecha de nacimiento','age': 'EDAD','patient_sex':'Genero','patient_address_city':'Ciudad','caseType':'Tipo','caseStatus':'Estado' })
    df4['Reportado']=np.nan

    #--------------------------------------------------Dataframe Incidencia-----------------------------------------------------------------------------------
    column_names2 =[  'Fecha',
                    'Casos positivos (PCR)',
                    '14 Dias',
                    'Habitantes en el pueblo',
                    'x 100,000'
    ]
    df6 = pd.DataFrame(columns = column_names2)

    day = dt.datetime.today().strftime("%m/%d/%Y")
    df_last_14 = df['Confirmado'].tail(14).sum()
    amount = 14
    habitantes = 81966
    incidencia = ((df_last_14/amount)/habitantes)*100000

    new_row = {'Fecha':day, 'Casos positivos (PCR)': df_last_14, '14 Dias':amount,'Habitantes en el pueblo': habitantes, 'x 100,000':incidencia}
    df6 = df6.append(new_row, ignore_index=True)
    #--------------------------------DATAFRAME OFICIAL---------------------------------------------------------------------------------------------
    column_names =[  'Día del reporte',
                    'Tasa de incidencia',
                    'Tasa de positividad (últimos 14 días)',
                    'Hospitalizados',
                    'Viajeros',
                    'Muertes',
                    'Confirmados acumulados',
                    'Confirmados adicionales',
                    'Probables acumulados',
                    'Probables adicionales',
                    'Sospechoso Acumulados',
                    'Sospechoso adicionales',
                    'Cerrados acumulados',
                    'Entrevistas realizadas',
                    'Contactos identificados',
                    'Sintomático',
                    'Asintomático',
                    'Hombres',
                    'Mujeres',
                    'Casos activos',
                    'Hospitalizados Activos',
                    'Viajeros Activos']
    df_Oficial = pd.DataFrame(columns = column_names)

    dia= dt.datetime.today().strftime("%m/%d/%Y")
    tasa = incidencia
    hosp = df5.shape[0] - df5.lastHospitalizedDate.str.contains(r'0001-01-01T00:00:00Z').sum()
    death = df5.patient_deceased.sum()
    confirmed = df5.caseType.str.contains(r'Confirmed').sum()
    sus = df5.caseType.str.contains(r'Suspected').sum()
    prob = df5.caseType.str.contains(r'Probable').sum()
    close = df5.caseStatus.str.contains(r'Closed').sum()
    contacts  = df5['numberOfExposedPositiveContacts'].sum()
    boy = df5.patient_sex.str.contains(r'Male').sum()
    girl = df5.patient_sex.str.contains(r'Female').sum()
    status = df5.caseStatus.str.contains(r'Active').sum()
    Hosp_status = df5.isCurrentlyHospitalized.sum()
    travel = df5.traveledDuringLast14Days.sum()

    #-Reads from second file(interview DATASET)_
    entrevistas  = df_int.interview_preInterview_correctPerson.str.contains(r'Yes',r'Yes Guardian').sum()
    temp = df_int.drop_duplicates(subset='patientId', keep="first")                 #Remueve dublicados y lo asigna a un dataframe nuevo
    symptoms= temp.interview_pastSymptoms_hasSymptoms.str.contains(r'Symptomatic').sum()
    asymptoma = temp.interview_pastSymptoms_hasSymptoms.str.contains(r'Asymptomatic').sum()

    new_row = {'Día del reporte':dia,'Tasa de incidencia':tasa , 'Hospitalizados': hosp, 'Muertes': death, 'Confirmados acumulados':confirmed,'Sospechoso Acumulados': sus,
    'Probables acumulados':prob, 'Cerrados acumulados':close, 'Entrevistas realizadas':entrevistas, 'Contactos identificados':contacts, 'Sintomático':symptoms, 'Asintomático':asymptoma, 'Hombres': boy,'Mujeres': girl, 'Mujeres': girl, 'Casos activos': status, 'Hospitalizados Activos':Hosp_status, 'Viajeros Activos':travel}

    df_Oficial = df_Oficial.append(new_row, ignore_index=True)

    #-------------------------------------------------------------------------------------------------------------------------------------------
    writer = pd.ExcelWriter(r'{}.xlsx'.format(filePath2), engine='xlsxwriter')

    # Position the dataframes in the worksheet.
    df.to_excel(writer, sheet_name='Acumulados')  # Default position, cell A1.
    df4.to_excel(writer, sheet_name='Gis',index=False)
    df2.to_excel(writer, sheet_name='Hozpitalizados',index=False)
    df3.to_excel(writer, sheet_name='Viajeros',index=False)
    df_Oficial.to_excel(writer, sheet_name='Oficial',index=False)
    df6.to_excel(writer, sheet_name='Incidencia',index=False)

    writer.save()

def main():

    sg.theme("DarkTeal2")

    layout = [
            [sg.T("")],
            [sg.Text("Choose a casesDataset file: "), sg.Input(), sg.FileBrowse(key="-IN-")],
            [sg.Text("Choose a interviewsDataset file: "),sg.Input(), sg.FileBrowse(key="-IN2-")],
            [sg.Text("Save As: "),sg.Input(), sg.FileSaveAs(key="-OUT-")],
            [sg.Button("Submit")]
            ]

    window = sg.Window('My File Browser', layout, size=(800,250))

    try:
        while True:
            event, values = window.read()

            if event == sg.WIN_CLOSED or event=="Exit":
                break
            if event == "Submit":
                for i in range(30):
                    sg.PopupAnimated(sg.DEFAULT_BASE64_LOADING_GIF, message='Please Wait...', background_color="white", text_color='black',time_between_frames=100)
                my_function(values['-IN-'],values['-IN2-'],values['-OUT-'])
                sg.PopupAnimated(None)

        window.close()

    except Exception as e:
        tb = traceback.format_exc()
        sg.Print(f'An error happened.  Here is the info:', e, tb)
        sg.popup_error(f'AN EXCEPTION OCCURRED!', e, tb)

if __name__ == "__main__":
                    main()


m = int(input())
n = int(input())
prime_num_list = [2, 3]
for num in range(4, n+1):
    for p_num in prime_num_list:
        if num % p_num == 0:
            break
    else:
        prime_num_list.append(num)

answer_list = []
for num in range(m, n+1):
    for p_num in prime_num_list:
        if num == p_num:
            answer_list.append(num)
        if num % p_num == 0 or num < p_num:
            break
    else:
        answer_list.append(num)

if len(answer_list) == 0:
    print("-1")
else:
    print(sum(answer_list))
    print(min(answer_list))


#!/usr/bin/env python
# log event for arduino yun RouterReset

from datetime import datetime, timedelta
import os
import sys
import updateWeb

# function to log time/event
def logEvent (directory):
    now = datetime.today()

    # command-line argument: status (startup/up/down)
    status = sys.argv[1] if len(sys.argv)>1 else 'startup'

    logfile = os.path.join(directory, now.strftime('log_%Y-%m.txt'))
    lastlog_file = os.path.join(directory, '.lastlog.txt')
    lastlog_status = status # default: no change

    if os.path.exists(lastlog_file):
        lastlog = open(lastlog_file).readlines()
        lastlog_time = datetime.strptime(lastlog[0].strip(), '%Y-%m-%d %H:%M:%S')
        lastlog_status = lastlog[1].strip()

    # does log file exist?
    logfile_not_new = os.path.exists(logfile)

    # add to log
    with open(logfile, 'at') as f:
        output = '%-10s %-8s %-7s' % (now.strftime('%Y-%m-%d'),
                                    now.strftime('%H:%M:%S'), status)
        if status == "startup":
            output += '; connected to ' + getSSID()

        if (status != 'startup' and status != lastlog_status):
            output += (' (was %-4s ' % lastlog_status +
                       strfdelta(now - lastlog_time)) + ')'
        f.write(output + '\n')

    # update 'last log'
    if status != 'startup' and (not os.path.exists(lastlog_file) or status != lastlog_status):
        with open(lastlog_file, 'wt') as f:
            f.write(now.strftime('%Y-%m-%d %H:%M:%S') + '\n')
            f.write(status + '\n')
    if status == 'startup' and os.path.exists(lastlog_file):
        os.remove(lastlog_file)

    # if it was a new log file, re-build web page:
    if not logfile_not_new:
        updateWeb.updateWeb(directory)

# function for formatting change in time
def strfdelta(tdelta):
    hours, rem = divmod(tdelta.seconds, 3600)
    hours += tdelta.days * 24
    minutes, seconds = divmod(rem, 60)
    return("%d:%02d:%02d" % (hours, minutes, seconds))

# function to get SSID
def getSSID():
    return os.popen('iwconfig wlan0 | grep ESSID').readline().strip().split('"')[-2]

if __name__ == '__main__':
    logEvent('/mnt/sd/arduino/www')