import random, time
import RPi.GPIO as GPIO

# set GPIO to broadcom system
GPIO.setmode(GPIO.BCM)

# set pins
LED_RED = 18
LED_GREEN = 27
LED_BLUE = 17

# set pins to output
GPIO.setup(LED_RED, GPIO.OUT)
GPIO.setup(LED_GREEN, GPIO.OUT)
GPIO.setup(LED_BLUE, GPIO.OUT)

Freq = 100 #Mhz

# set LED colors to initial duty cycle of 0 (off)
RED = GPIO.PWM(LED_RED, Freq)
RED.start(0)
GREEN = GPIO.PWM(LED_GREEN, Freq)
GREEN.start(0)
BLUE = GPIO.PWM(LED_BLUE, Freq)
BLUE.start(0)

def color(R, G, B, on_time):

    RED.ChangeDutyCycle(R)
    GREEN.ChangeDutyCycle(G)
    BLUE.ChangeDutyCycle(B)
    time.sleep(on_time)

def cycle_through_colors():
    print("Light it up")
    print("R G B\n------------")
    for runcount in range(0,2):
        for x in range(0,2):
            for y in range(0,2):
                for z in range(0,2):
                    print(x, y, z)
                    for i in range(0, 101):
                        color((x*i),(y*i),(z*i), .02)

def main():
    print("setting up the light config")
    print("starting the lights")
    print("Stage 1: Cycle through the colors")
    cycle_through_colors()
    GPIO.cleanup()

main()


from dataclasses import dataclass, field
from typing import Any, Callable, Optional, Type, Mapping, AbstractSet

from grongier.dacite.cache import Cache
from grongier.dacite.frozen_dict import FrozenDict

@dataclass
class Config:
    type_hooks: Mapping[Type, Callable[[Any], Any]] = field(default_factory=dict)
    cast: AbstractSet[Type] = field(default_factory=frozenset)
    forward_references: Optional[Mapping[str, Any]] = None
    check_types: bool = True
    strict: bool = False
    strict_unions_match: bool = False
    cache: Cache = Cache()

    def __post_init__(self):
        self.type_hooks = FrozenDict(self.type_hooks)
        self.cast = frozenset(self.cast)
        self.forward_references = FrozenDict(self.forward_references) if self.forward_references else None


from game import Game
import pygame
from player import Player
import sys
from os import environ
from utility import black
from config import Config
from datetime import datetime

if __name__ == "__main__":

    num_games = 1
    games = []
    for i in range(num_games):
        games.append(Game())
    active_game = 0
    draw_all = False

    environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (30, 30)
    pygame.init()
    screen = pygame.display.set_mode((Config.field_width, Config.field_height))
    pygame.font.init()
    myfont = pygame.font.SysFont(Game.game_over_text_font, Game.game_over_text_size)
    screen.fill(0)
    frameend = datetime.now()
    frametimes = [0.001] * 101
    last_framerate_update = datetime.now()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    games[active_game].player_left.speed_y = - Config.player_speed
                elif event.key == pygame.K_s:
                    games[active_game].player_left.speed_y = Config.player_speed
                if event.key == pygame.K_UP:
                    games[active_game].player_right.speed_y = - Config.player_speed
                elif event.key == pygame.K_DOWN:
                    games[active_game].player_right.speed_y = Config.player_speed

                if event.key == pygame.K_RIGHT:
                    active_game += 1
                    active_game %= num_games
                elif event.key == pygame.K_LEFT:
                    active_game -= 1
                    active_game %= num_games

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_w or event.key == pygame.K_s:
                    games[active_game].player_left.speed_y = 0
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    games[active_game].player_right.speed_y = 0

        screen.fill(black)
        for game in games:
            game.update_all()
            if draw_all:
                game.draw_all(screen)
        if not draw_all:
            games[active_game].draw_all(screen)

        pygame.display.update()
        if len(frametimes) > 100:
            frametimes = frametimes[-100:-1]

        frametimes.append((datetime.now() - frameend).total_seconds())
        frameend = datetime.now()
        if (datetime.now() - last_framerate_update).total_seconds() > 0.5:
            pygame.display.set_caption("Active game: %d/%d Player 1: %d Player 2: %d Framerate: %f" % (active_game+1,
                                                                                num_games,
                                                                         games[active_game].player_left.score,
                                                                         games[active_game].player_right.score,
                                                                         1/(sum(frametimes)/len(frametimes))))
            last_framerate_update = datetime.now()


import serial
from flask import request
from flask_api import FlaskAPI, status

app = FlaskAPI(__name__)
ready = "ready"
port_name = "/dev/cu.usbmodem143201"

def send_str_to_arduino(msg):
    with serial.Serial(port_name, 9600) as ser:
        print("Waiting for arduino...")
        ch = ser.read(len(ready))
        print("Arduino: " + ch.decode())
        msg = msg.ljust(32)
        msg = msg[:32] + "\n"
        print("Message: <", msg.encode(), ">")
        ser.write(msg.encode())
        return msg

@app.route("/api/version")
def version():
    return {"name": "send text to serial", "verison": "0.1"}

@app.route("/api/sendser", methods=["Post"])
def send_ser():
    msg = request.data.get("msg", "")
    if not msg:
        return "", status.HTTP_204_NO_CONTENT
    print(msg)
    sent = send_str_to_arduino(msg)
    return {"sent": sent}, status.HTTP_201_CREATED

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9001, debug=True)


import os
from typing import Union
import kachery_cloud as kcl
from .Figure import Figure

class MultiTimeseries:
    def __init__(self, *, label: str) -> None:
        self._label = label
        self._panels = []
    def add_panel(self, figure: Figure, *, relative_height: Union[float, None]=None):
        self._panels.append({
            'figure': figure,
            'relative_height': relative_height
        })
    def get_composite_figure(self):
        panels = []
        for p in self._panels:
            fig0: Figure = p['figure']
            v = {
                'type': fig0.data['type'],
                'label': fig0.label,
                'figureDataUri': _upload_data_and_return_uri(fig0.get_serialized_figure_data())
            }
            if p['relative_height'] is not None:
                v['relativeHeight'] = p['relative_height']
            panels.append(v)
        data = {
            'type': 'MultiTimeseries',
            'panels': panels
        }
        return Figure(data=data, label=self._label)

def _upload_data_and_return_uri(data):
    data_uri = kcl.store_json(data)
    return data_uri


from collections import Counter
class Solution(object):
    def countCharacters(self, words, chars):
        """
        :type words: List[str]
        :type chars: str
        :rtype: int
        """
        count = Counter(chars)
        ans=0

        for word in words:
            tempCount = count.copy()
            for c in word:
                tempCount[c] -= 1

                if tempCount[c] < 0:
                    ans -= len(word)
                    break
            ans += len(word)
        return ans


from django.shortcuts import render
from django.db.models import Avg, Count
from django.contrib.auth.models import User
from django.http import HttpResponse
from .models import Rater, Rating, Movie

# Create your views here.
def all_movies(request):
    movies = Movie.objects.all()
    return render(request,
            'review/movies.html',
            {'movies': movies})

def rater_detail(request):
    raters = Rater.objects.all()
    return render(request,
                    'review/rater_detail.html',
                    {'raters':raters})

def show_rater(request, rater_id):
    rater = Rater.objects.get(pk=rater_id)
    ratings = Rating.objects.filter(rater_id=rater.id)
    return render(request,
                  'review/rater_ratings.html',
                  {'ratings': ratings,
                    'rater': rater,
                  })

def top_movies(request):
    popular_movies = Movie.objects.annotate(num_ratings=Count('rating')) \
                                  .filter(num_ratings__gte=50)

    movies = popular_movies.annotate(Avg('rating__rating')) \
                           .order_by('-rating__rating__avg')[:20]

    return render(request,
                  'review/top_movies.html',
                  {'movies': movies})

def profile_info(request, user_id):
    movie_user = User.objects.get(pk=user_id)
    return render(request, 'review/profile.html',
                            {'movie_user': movie_user})


import os

import numpy as np
import pickle
import config
import sys

import run_experiments as run
import compute as comp

def get_results(para_setup):
    name_string = '%s-' * len(para_setup)  # % para_setup
    name_string = name_string[:-1]
    folder_name = config.home_path + config.interim_result_path
    file_name = folder_name + name_string % tuple(para_setup)
    new_file_name = file_name.replace("'", "").replace('"', '') + '.dat'
    try:
        with open(new_file_name, 'rb') as f:
            results = pickle.load(f)

    except FileNotFoundError:
        print('failed ', new_file_name)
        return None

    return results

def get_counts(para_setup):
    results = get_results(para_setup)

    if results is not None:
        metrics_dict = calculate_metrics(results, para_setup)
        return metrics_dict
    else:
        return None

def _get_match_score(true_link, pred_link):
    if true_link == "" or pred_link == "": return 0
    count = 0
    # If left edgemark is correct add 1
    if true_link[0] == pred_link[0]:
        count += 1
    # If right edgemark is correct add 1
    if true_link[2] == pred_link[2]:
        count += 1
    return count

def get_system_nodes(graphs, n_sys_nodes):
    return graphs[:, :n_sys_nodes, :n_sys_nodes, :]

def calculate_metrics(results, para_setup, boot_samples=200):
    match_func = np.vectorize(_get_match_score, otypes=[int])

    true_graphs = results['true_graphs']
    n_realizations, N, N, max_lag = true_graphs.shape
    experiment, sample_size, nb_domains, n_sys_nodes, L, K_time, K_space, frac_observed, \
        functional_form, ci_test, pc_alpha, taumax, nb_repeats = para_setup

    def get_masks(n_nodes, n_sys_nodes=1, n_obs_context_nodes=0):
        cross_mask = np.repeat(np.identity(n_nodes).reshape((n_nodes, n_nodes, 1)) == False, max_lag, axis=2).astype(
            'bool')
        cross_mask[range(n_nodes), range(n_nodes), 0] = False
        contemp_cross_mask_tril = np.zeros((n_nodes, n_nodes, max_lag)).astype('bool')
        contemp_cross_mask_tril[:, :, 0] = np.tril(np.ones((n_nodes, n_nodes)), k=-1).astype('bool')

        system_mask = np.repeat(np.identity(n_nodes).reshape((n_nodes, n_nodes, 1)) == False, max_lag, axis=2).astype(
            'bool')
        system_mask[:n_sys_nodes, :n_sys_nodes, :max_lag] = False
        if n_nodes > n_sys_nodes + n_obs_context_nodes:
            # dummies exist
            system_mask[n_sys_nodes + n_obs_context_nodes:, :, range(max_lag)] = False
            system_mask[:, n_sys_nodes + n_obs_context_nodes:, range(max_lag)] = False
        system_mask[n_sys_nodes:, n_sys_nodes:, range(max_lag)] = False

        any_mask = np.ones((n_nodes, n_nodes, max_lag)).astype('bool')
        any_mask[:, :, 0] = contemp_cross_mask_tril[:, :, 0]
        contemp_cross_mask_tril = np.repeat(contemp_cross_mask_tril.reshape((1, n_nodes, n_nodes, max_lag)),
                                            n_realizations, axis=0)
        any_mask = np.repeat(any_mask.reshape((1, n_nodes, n_nodes, max_lag)), n_realizations, axis=0)
        system_mask = np.repeat(system_mask.reshape((1, n_nodes, n_nodes, max_lag)), n_realizations, axis=0)
        return cross_mask, any_mask, contemp_cross_mask_tril, system_mask

    metrics_dict = dict()

    for suffix in ['_jpcmci', '_expr_context_only', '_expr_context_and_dummy', '_dummy', '_system_only']:
        suffix2 = '_sys_nodes'
        cross_mask, any_mask, contemp_cross_mask_tril, _ = get_masks(n_sys_nodes)
        comp_graphs = get_system_nodes(true_graphs, n_sys_nodes)
        pred_graphs = np.array([results['res' + suffix][i]['graph'] for i in range(n_realizations)])
        pred_graphs = get_system_nodes(pred_graphs, n_sys_nodes)
        mask = any_mask

        computation_time = results['comptime' + suffix]

        if suffix == '_jpcmci':
            print("comp_graphs",comp_graphs)
            print("pred_graphs", pred_graphs)

        nom = ((comp_graphs == "") * (pred_graphs != "") * mask).sum(axis=(1, 2, 3))
        metrics_dict['adj_fpr' + suffix + suffix2] = (
            nom.reshape(n_realizations),
            ((comp_graphs == "") * mask).sum(axis=(1, 2, 3)).reshape(n_realizations))
        metrics_dict['adj_tpr' + suffix + suffix2] = (
            ((comp_graphs != "") * (pred_graphs != "") * mask).sum(axis=(1, 2, 3)).reshape(n_realizations),
            ((comp_graphs != "") * mask).sum(axis=(1, 2, 3)).reshape(n_realizations))

        metrics_dict['adj_precision' + suffix + suffix2] = (
            ((comp_graphs != "") * (pred_graphs != "") * mask).sum(axis=(1, 2, 3)).reshape(n_realizations),
            ((pred_graphs != "") * mask).sum(axis=(1, 2, 3)).reshape(n_realizations))
        metrics_dict['adj_recall' + suffix + suffix2] = (
            ((comp_graphs != "") * (pred_graphs != "") * mask).sum(axis=(1, 2, 3)).reshape(n_realizations),
            ((comp_graphs != "") * mask).sum(axis=(1, 2, 3)).reshape(n_realizations))

        metrics_dict['edgemarks_precision' + suffix + suffix2] = (
            (match_func(comp_graphs, pred_graphs) * mask).sum(axis=(1, 2, 3)).reshape(n_realizations),
            2. * ((pred_graphs != "") * mask).sum(axis=(1, 2, 3)).reshape(n_realizations))
        metrics_dict['edgemarks_recall' + suffix + suffix2] = (
            (match_func(comp_graphs, pred_graphs) * mask).sum(axis=(1, 2, 3)).reshape(n_realizations),
            2. * ((comp_graphs != "") * mask).sum(axis=(1, 2, 3)).reshape(n_realizations))

        metrics_dict['computation_time' + suffix + suffix2] = (
            np.mean(np.array(computation_time)), np.percentile(np.array(computation_time), [5, 95]))

    for met in metrics_dict.keys():
        if 'computation_time' not in met:
            numerator, denominator = metrics_dict[met]
            metric_boot = np.zeros(boot_samples)
            for b in range(boot_samples):
                # Store the unsampled values in b=0
                rand = np.random.randint(0, n_realizations, n_realizations)
                metric_boot[b] = numerator[rand].sum() / denominator[rand].sum()

            metrics_dict[met] = (numerator.sum() / denominator.sum(), metric_boot.std())

    return metrics_dict

def calculate_all_metrics(all_configurations):
    for conf in all_configurations:
        config_string = str(conf[1]).replace(',', '').replace('"', '')
        foldername = config.home_path + config.interim_result_path
        if not os.path.exists(foldername):
            os.makedirs(foldername)
        file_name = foldername + config_string
        file_name_metrics_cleaned = file_name.replace("'", "").replace('"', '') + '_metrics.dat'

        para_setup = comp.unpack_params((config_string, ""))
        metrics = get_counts(para_setup)
        if metrics is not None:
            for metric in metrics:
                file = open(file_name_metrics_cleaned, 'wb')
                pickle.dump(metrics, file, protocol=-1)
                file.close()

if __name__ == '__main__':
    exp_type = run.parse_arguments(sys.argv)
    all_configurations, mypath = run.generate_configs(exp_type)

    calculate_all_metrics(all_configurations)


from django.conf.urls import include, url

from django.contrib import admin
admin.autodiscover()

from serve.views import bulkview,subprojectview,mapprojects,indexview,collectionview,collectioninsert,no_objection
urlpatterns = [
    url(r'^search/', indexview, name='index'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^projectin/',collectioninsert),
    url(r'^projectlist/',collectionview),
    url(r'^subprojectlist/',subprojectview),
    url(r'^subprojectin/',mapprojects),
    url(r'^insert/',no_objection),
    url(r'^insertBulk/',bulkinsert),
    url(r'^getbulk/',bulkview)
]


# -*- coding: utf-8 -*-
"""
Created on Wed Jan  6 09:53:54 2021

@author: franc
"""

import pyfirmata2 as pyfirmata
import time

#%% Fonctions nécessaires pour la lecture du thermocouple

class thermocouple:

    def __init__(self,board,miso,cs,sclk):

        self.board = board

        self.miso = self.board.get_pin("d:{}:i".format(miso))
        self.cs   = self.board.get_pin("d:{}:o".format(cs))
        self.sclk = self.board.get_pin("d:{}:o".format(sclk))

        time.sleep(1)
        self.cs.write(1)
        time.sleep(1)

    def read(self):

        time.sleep(100/1000)
        self.cs.write(0)
        time.sleep(100/1000)

        bit_array = ""
        for i in range(16-3):
            self.sclk.write(0)
            time.sleep(24/1000)

            bit_array = bit_array + str( self.miso.read()*1 )

            self.sclk.write(1)
            time.sleep(1/1000)

        self.cs.write(1)
        time.sleep(100/1000)

        return int(bit_array[1:],2)/4


import discord
import asyncio
import aiohttp
import os
import re
import random
import json

def parseReplys(reply):
    regex = r"\$\{([\w\ ]+)\}"
    parsed = reply
    matches = re.finditer(regex, reply, re.MULTILINE)
    if not matches:
        return parsed

    for i in matches:
        com = i.group(1).split()
        if com[0] == "rand":
            if len(com) >= 3:
                result = random.randint(int(com[1]), int(com[2]))
                parsed = parsed.replace(i.group(), str(result), 1)
        else:
            parsed = parsed.replace(i.group(), "\"ERROR\"")

    return parsed

async def asyncDereInfoSend(message, userID):
    async with aiohttp.ClientSession() as session:
        async with session.get("https://deresute.me/{}/json".format(userID)) as resp:
            userData = await resp.json()
            if "api_error" in userData:
                await message.channel.send("api error : " + str(userData["api_error"]))
            elif "name" in userData:
                await message.channel.send(userData["name"] + " " + str(userData["level"]) + " " + userData["comment"])
            else:
                await message.channel.send("Wrong response. Contact developer.")

class discordClient(discord.Client):
    async def on_ready(self):
        print("Bot logged on as", self.user)

    async def on_message(self, message):
        # We don't need to respond to ourselves
        if message.author == self.user:
            return

        splitedMessage = message.content.split(' ')
        # All commands start with mirei
        if (splitedMessage[0] == "mirei") & (len(splitedMessage) > 1):
            # For test ping
            if splitedMessage[1] == "test":
                await message.channel.send("test pong")
            # CGSS user info
            elif splitedMessage[1] == "info":
                # Process game info asyncronously to prevent programme from hogging
                async with message.channel.typing():
                    await asyncDereInfoSend(message, splitedMessage[2])
            else:
                if splitedMessage[1] in staticReplys:
                    if "image" in staticReplys[splitedMessage[1]]:
                        await message.channel.send(content = parseReplys(staticReplys[splitedMessage[1]]["reply"]),
                                                   file = discord.File(staticReplys[splitedMessage[1]]["image"]))
                    else:
                        await message.channel.send(parseReplys(staticReplys[splitedMessage[1]]["reply"]))
                else:
                    await message.channel.send("그런 거 없다")

try:
    with open("./staticReplys.json", 'r') as file:
        staticReplys = json.load(file)
        file.close()
except FileNotFoundError:
    print("Need to make staticReplys.json")
    raise SystemExit()

bot = discordClient()
bot.run(os.environ["DISCORDBOT_TOKEN"])


from testsuite.base_fs import BaseFilesystem
from testfixtures import log_capture
from testsuite import config
from core.sessions import SessionURL
from core import modules
from core import messages
import subprocess
import datetime
import logging
import os

class FileCheck(BaseFilesystem):

    def setUp(self):
        session = SessionURL(self.url, self.password, volatile = True)
        modules.load_modules(session)

        # Create the folder tree
        self.folders_abs, self.folders_rel =  self.populate_folders()
        self.files_abs, self.files_rel = self.populate_files(
                                self.folders_abs,
                                [ 'executable', 'writable', 'write-executable', 'readable' ]
                            )

        # Change mode of the first file to 777
        self.check_call(
            config.cmd_env_chmod_s_s % ('0777', self.files_abs[0]),
            shell=True)

        # Get the epoch timestamp of file[0]
        self.files_times = [
            int(subprocess.check_output(
                config.cmd_env_stat_time_modif_epoch_s % (self.files_abs[0]),
                shell=True))
        ]

        # Change mode of the forth file to -r--r--r-- 0444 read
        self.check_call(
            config.cmd_env_chmod_s_s % ('0444', self.files_abs[3]),
            shell=True)

        # Change mode of the forth folder to --wx-wx-wx 0333 write & execute
        self.check_call(
            config.cmd_env_chmod_s_s % ('0333', self.folders_abs[3]),
            shell=True)

        self.run_argv = modules.loaded['file_check'].run_argv

    def tearDown(self):

        # Reset recursively all the permissions to 0777
        self.check_call(
            config.cmd_env_chmod_s_s % ('-R 0777', self.folders_abs[0]),
            shell=True)

        for folder in reversed(self.folders_abs):

            self.check_call(
                config.cmd_env_remove_s % (self.files_abs.pop()),
                shell=True)

            self.check_call(
                config.cmd_env_rmdir_s % (folder),
                shell=True)

    def test_check(self):

        # Some check on a file just readable
        self.assertTrue(self.run_argv([ self.files_rel[3], 'exists']))
        self.assertTrue(self.run_argv([ self.files_rel[3], 'readable']))
        self.assertTrue(self.run_argv([ self.files_rel[3], 'file']))
        self.assertFalse(self.run_argv([ self.files_rel[3], 'executable']))
        self.assertFalse(self.run_argv([ self.files_rel[3], 'writable']))
        self.assertFalse(self.run_argv([ self.files_rel[3], 'dir']))

        # Some check on an unexistant file
        self.assertFalse(self.run_argv(['BOGUS', 'exists']))
        self.assertFalse(self.run_argv(['BOGUS', 'readable']))
        self.assertFalse(self.run_argv(['BOGUS', 'file']))
        self.assertFalse(self.run_argv(['BOGUS', 'executable']))
        self.assertFalse(self.run_argv(['BOGUS', 'writable']))
        self.assertFalse(self.run_argv(['BOGUS', 'dir']))

        # Some check on a folder with jsut x & w
        self.assertTrue(self.run_argv([ self.folders_rel[3], 'exists']))
        self.assertFalse(self.run_argv([ self.folders_rel[3], 'readable']))
        self.assertFalse(self.run_argv([ self.folders_rel[3], 'file']))
        self.assertTrue(self.run_argv([ self.folders_rel[3], 'executable']))
        self.assertTrue(self.run_argv([ self.folders_rel[3], 'writable']))
        self.assertTrue(self.run_argv([ self.folders_rel[3], 'dir']))

        # Save the human readable remote file[0] timestamp
        rdatetime = datetime.datetime.fromtimestamp(float(self.files_times[0])).strftime('%Y-%m-%d')

        self.assertTrue(self.run_argv([ self.files_rel[0], 'exists']))
        self.assertTrue(self.run_argv([ self.files_rel[0], 'readable']))
        self.assertTrue(self.run_argv([ self.files_rel[0], 'file']))
        self.assertFalse(self.run_argv([ self.files_rel[0], 'dir']))
        self.assertTrue(self.run_argv([ self.files_rel[0], 'executable']))
        self.assertTrue(self.run_argv([ self.files_rel[0], 'writable']))
        self.assertEqual(self.run_argv([ self.files_rel[0], 'size']), 1)
        self.assertEqual(self.run_argv([ self.files_rel[0], 'md5']), 'c4ca4238a0b923820dcc509a6f75849b')
        self.assertAlmostEqual(self.run_argv([ self.files_rel[0], 'time']), self.files_times[0], delta = 20)
        self.assertEqual(self.run_argv([ self.files_rel[0], 'datetime']).split(' ')[0], rdatetime)


# https://leetcode.com/problems/lru-cache/

class LRUCache:
    class ListNode:
        def __init__(self, key, val, prev=None, next=None) -> None:
            self.key = key
            self.val = val
            self.prev = prev
            self.next = next

    def __init__(self, capacity: int):
        self.cacheHead = None
        self.cacheTail = None
        self.capacity = capacity
        self.noOfItems = 0
        self.keys = {}

    def get(self, key: int) -> int:
        value = -1
        if key in self.keys:
            node = self.keys[key]
            value = node.val
            if node.next:
                if node.prev:
                    node.prev.next = node.next
                else:
                    self.cacheHead = self.cacheHead.next
                node.next.prev = node.prev
                self.cacheTail.next = node
                node.prev = self.cacheTail
                node.next = None
                self.cacheTail = self.cacheTail.next
        return value

    def put(self, key: int, value: int) -> None:
        if key in self.keys:
            self.keys[key].val = value
            node = self.keys[key]
            if node.next:
                if node.prev:
                    node.prev.next = node.next
                else:
                    self.cacheHead = self.cacheHead.next
                node.next.prev = node.prev
                self.cacheTail.next = node
                node.prev = self.cacheTail
                node.next = None
                self.cacheTail = self.cacheTail.next
            return

        if self.noOfItems == 0:
            self.cacheHead = self.ListNode(key, value)
            self.cacheTail = self.cacheHead
            self.keys[key] = self.cacheHead
            self.noOfItems = self.noOfItems + 1
            return

        if self.noOfItems == self.capacity:
            del self.keys[self.cacheHead.key]
            self.cacheHead = self.cacheHead.next
            if not self.cacheHead:
                self.noOfItems = 0
                self.cacheTail = None
                self.put(key, value)
                return
            else:
                self.cacheHead.prev = None
        else:
            self.noOfItems = self.noOfItems + 1
        node = self.ListNode(key, value, self.cacheTail, None)
        self.keys[key] = node
        self.cacheTail.next = node
        self.cacheTail = self.cacheTail.next

    def display(self):
        print('-'*30)
        node = self.cacheHead
        while node:
            print(node.val, end=' ')
            node = node.next

        print()

        node = self.cacheTail
        while node:
            print(node.val, end=' ')
            node = node.prev
        print()
        print('-'*30)

# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

cache = LRUCache(5)
cache.put(1, 1)
cache.put(2, 2)
cache.put(3, 3)
cache.put(4, 4)
cache.put(5, 5)
cache.display()
print('Get', cache.get(1))
cache.display()
print('Put', 6)
cache.put(6, 6)
cache.display()
print('Get', cache.get(5))
cache.display()
print('Put', 7)
cache.put(7, 7)
cache.display()

print('*'*30)
cache = LRUCache(1)
cache.put(2, 1)
print(cache.get(2))
cache.display()

print('*'*30)
cache = LRUCache(1)
cache.put(2, 1)
print(cache.get(2))
cache.display()
cache.put(3, 2)
print(cache.get(2))
print(cache.get(3))

print('*'*30)
cache = LRUCache(2)
cache.put(2, 1)
cache.put(1, 1)
cache.put(2, 3)
cache.put(4, 1)
cache.display()
print(cache.get(1))
print(cache.get(2))
cache.display()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from models import Users

import json
import os
import example as e
################################################################
vi_adjids=[]
vi_adjgraphids=[]
vi_graph=[]
vi_cord_list=[]

def adjlist_generate(r):
    del vi_graph[:]
    del vi_cord_list[:]
    del vi_adjids[:]
    del vi_adjgraphids[:]

    for i in range(len(r.nodes_in_box)):
        nd=r.queryNode(r.nodes_in_box[i])
        vi_cord_list.append(nd.lon)
        vi_cord_list.append(nd.lat)
        vi_adjids.append(int(nd.id))

        mi=[]
        temp=[]
        for j in range(len(nd.adjPtr)):
            md=r.queryNode2(nd.adj[j],nd.adjPtr[j])
            mi.append(md.lon)
            mi.append(md.lat)
            temp.append(int(md.id))

        vi_graph.append(mi)
        vi_adjgraphids.append(temp)

def AStar_tocord(r):
    del vi_cord_list[:]
    for i in range(len(r.path) ):
        nd=r.queryNode(r.path[i])
        vi_cord_list.append(nd.lon)
        vi_cord_list.append(nd.lat)

# r=e.rtree(422399792)
# print(r.root)
# r.boundingBox(77.1780,77.2652,28.5985,28.6424,4)
# print(r.nodes_in_box )

################################################################

#for page initial loading
@csrf_exempt
def req(request):

    response = {'list': [], 'adjlist': [] }
    r=e.rtree(422399792)

    maxLat = 28.9689998626709
    maxLong = 77.73299407958984
    minLat = 28.18301010131836
    minLong = 76.69200134277344

    r.boundingBox(minLong,maxLong,minLat,maxLat,1)
    adjlist_generate(r)

    i=0;
    # module_dir = os.path.dirname(__file__)  # get current directory
    # file_path = os.path.join(module_dir, 'data.txt')
    list1=[]
    # with open(file_path) as fp:
    #     for line in fp:
    #         i+=1
    #         # if(i%300000!=0):#change here for no. of nodes.
    #         #     continue;

    #         words = line.split(" ")
    #         #loc = {'lat':float(words[0]),  'lon': float(words[1]) }
    #         list1.append(float(words[0]))
    #         list1.append(float(words[1]))

    #         if(i==100):#change here for no. of nodes.
    #             break;

    #print list1
    #print(request.POST.get('search_name'))
    #list1 = ['physics', 'chemistry', 1997, 2000];
    print(len(vi_cord_list))
    print(len(vi_graph))
    # print(vi_adjids)
    # print(vi_adjgraphids)
    # count=0
    # for i in xrange(0, len(vi_adjids)-1):
    #     print(vi_adjids[i], vi_adjids[i+1])
    #     i+=1
    #     count=0
    #     for i in xrange(0, len(vi_adjgraphids)-1):

    #response['list']=vi_cord_list
    #response['adjlist']=vi_graph

    #JsonResponse(response)

    context = {'list': vi_cord_list, 'adjlist': vi_graph, 'vi_adjids':vi_adjids, 'vi_adjgraphids':vi_adjgraphids }
    #context = {'list': vi_cord_list}

    return render(request, 'view1.html', context)

    #return JsonResponse({'foo':'bar'})

################################################################

#for  returning list of prefix
@csrf_exempt
def return_list(request):
    print("request param= ", request.POST.get("search"))
    prefix=request.POST.get("search")
    typeOfReq=int(request.POST.get("type"))

    response = {'way_names': [], 'way_ids': [],'node_names': [], 'node_ids': [],  }
    way_names = []
    way_ids = []
    node_names = []
    node_ids = []

    t=e.trie()
    #w=t.search_trie("Hapur Road")
    st=str(prefix)
    #print ("st=", st);

    if(typeOfReq==1):
        t.display_prefix(st,len(st),0)
        for i in t.list:
            #print (i)
            way_ids.append(int(i))
        for i in t.prefix:
            #print (i)
            way_names.append(i)

    t.display_prefix_node(st,len(st),0)
    for i in t.list:
        #print (i)
        node_ids.append(int(i))
    for i in t.prefix:
        #print (i)
        node_names.append(i)

    t.close()
    response['way_names']=way_names
    response['way_ids']=way_ids
    response['node_names']=node_names
    response['node_ids']=node_ids

    #print response
    #print JsonResponse(response)

    #print(t.list[0])
    #print(t.prefix[0])

    return JsonResponse(response)
################################################################

#for returning info of selected name.
@csrf_exempt
def data(request):
    way_list=[]    #longlat list
    dlist=[]   #delimiter list
    node_list=[]
    response = {'way_list': [], 'dlist': [], 'node_list':[], 'type': "none"}

    name=request.POST.get("name")
    Type=request.POST.get("type")

    t=e.trie()
    if(Type=="nodes"):
        print("nodes inside")
        response['type']=Type
        n=t.search_trie_node(name)
        if(n.nodeptr >= 0):
            t.node_with_nodeid(n.nodeptr)
            for i in t.lat_list:
                node_list.append(float(i))

    elif(Type=="ways"):
        print("ways inside")

        response['type']=Type
        w=t.search_trie(name)
        #print("w=",w.getid())
        #print("w=",w.wayptr)
        if(w.wayptr >= 0):
            t.node_with_wayid(w.wayptr)
            for i in t.lat_list:
                #print (i)
                way_list.append(float(i))
            for i in t.delimiter_list:
                #print (i)
                dlist.append(float(i))

    # print("lat=", t.lat_list, "\ndlist=", t.delimiter_list)
    # print("nodelist", node_list)

    #response['long']=t.long_list

    response['way_list']=way_list
    response['dlist']=dlist
    response['node_list']=node_list

    t.close()
    return JsonResponse(response)

################################################################

#for returning rtree.
@csrf_exempt
def rtree(request):

    admin_level=int(request.POST.get("admin_level"))
    minLat=float(request.POST.get("minLat"))
    minLong=float(request.POST.get("minLon"))
    maxLat=float(request.POST.get("maxLat"))
    maxLong=float(request.POST.get("maxLon"))

    print("rtree",admin_level, minLat, minLong,maxLat, maxLong)

    response = {'list': [], 'adjlist': [] }
    r=e.rtree(422399792)
    r.boundingBox(minLong,maxLong,minLat,maxLat,admin_level)
    adjlist_generate(r)

    # print(len(vi_cord_list))
    # print(len(vi_graph))
    response['list']=vi_cord_list
    response['adjlist']=vi_graph

    r.close()
    #JsonResponse(response)
    #context = {'list': vi_cord_list, 'adjlist': vi_graph}
    #context = {'list': vi_cord_list}

    #return render(request, 'view1.html', context)
    return JsonResponse(response)

################################################################

# def nearestNode(Lat, Lon):
#     response = {'id': -1}

#     # Lat=float(request.POST.get("Lat"))
#     # Lon=float(request.POST.get("Lon"))
#     # print("nearestNode", Lat, Lon)
#     nearestId=r.nearestNode2( Lon,Lat)
#     print("nearestId", nearestId)
#     response['id']=nearestId
#     //return JsonResponse(response)

################################################################

#for returning shortest path.
@csrf_exempt
def astar(request):
    r=e.rtree(422399792)
    response = {'list':[]}

    typeOfAstar=int(request.POST.get("type"))

    if(typeOfAstar==1): #point pick on map
        Lat1=float(request.POST.get("Lat1"))
        Lon1=float(request.POST.get("Lon1"))
        Lat2=float(request.POST.get("Lat2"))
        Lon2=float(request.POST.get("Lon2"))
        nearestId1=r.nearestNode2( Lon1,Lat1)
        nearestId2=r.nearestNode2( Lon2,Lat2)

        print("astar", Lat1, Lon1, Lat2, Lon2, "near", nearestId1,nearestId2 )

        r.AStar(nearestId1,nearestId2)
        AStar_tocord(r)
        response['list']=vi_cord_list
        print("vi_cord_list=", vi_cord_list)

        r.close()
        return JsonResponse(response)

    elif(typeOfAstar==2):  #by name search
        srcId=long(float(request.POST.get("srcId")))
        dstId=long(float(request.POST.get("dstId")))
        print("astar, type2", srcId, dstId)

        r.AStar(srcId,dstId)
        AStar_tocord(r)
        response['list']=vi_cord_list
        print("vi_cord_list=", vi_cord_list)

        r.close()
        return JsonResponse(response)

##################extras#####################################
def index(request):
    return HttpResponse("Hello, world")

def detail(request, id):
    return HttpResponse("You're looking at question %s." % id)

def results(request, id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % id)

def vote(request, id):
    return HttpResponse("You're voting on question %s." % id)

################################################################


def add(*num):
    s = 0
    for i in num:
        s += i
    print(s)

add(3, 4, 5)

def add2(**kwargs):
    for k, v in kwargs.items():
        print(k, v)

add2(name="Oscar")


import os, os.path, sys
import h5py
import numpy as np
import pickle as pkl
from configs_genre import gen_config as genre_config
from configs_gender import gen_config as gender_config
from configs_year import gen_config as year_config
from models.ann import Classifier
from models.cnn import CNNClassifier
from feature_extractor import FeatureExtractor
from sklearn.utils.extmath import softmax
from utils import parse_csv_list_file

def load_models(task):
    if task.startswith('Year'):
        cfgs_1, nn_cfgs_1 = year_config(task, 'ann', 'decade')
        cfgs_2, nn_cfgs_2 = year_config(task, 'cnn', 'decade')
    elif task.startswith('Genre'):
        cfgs_1, nn_cfgs_1 = genre_config(task, 'ann')
        cfgs_2, nn_cfgs_2 = genre_config(task, 'cnn')
    elif task.startswith('Gender'):
        cfgs_1, nn_cfgs_1 = gender_config(task, 'ann')
        cfgs_2, nn_cfgs_2 = gender_config(task, 'cnn')

    ann = Classifier(nn_cfgs_1, log_dir=None)
    ann.restore('%s-%d' %(nn_cfgs_1['tf_sess_path'], cfgs_1['n_iters']))
    cnn = CNNClassifier(nn_cfgs_2, log_dir=None)
    cnn.restore('%s-%d' %(nn_cfgs_2['tf_sess_path'], cfgs_2['n_iters']))
    return ann, cnn

def init_ft(task):
    if task.startswith('Year'):
        cfgs, nn_cfgs = year_config(task, 'ann', 'decade')
    elif task.startswith('Genre'):
        cfgs, nn_cfgs = genre_config(task, 'ann')
    elif task.startswith('Gender'):
        cfgs, nn_cfgs = gender_config(task, 'ann')

    ft1 = FeatureExtractor(cfgs['feature_list'], cfgs['feature_pool'], cfgs['l2_norm'], cfgs['sr'], 1, cfgs['stride'])
    ft2 = FeatureExtractor(['melspectrogram'], 'none', cfgs['l2_norm'], cfgs['sr'], 3, cfgs['stride'])
    return ft1, ft2

def get_utils(task):
    if task.startswith('Year'):
        cfgs, nn_cfgs = year_config(task, 'ann', 'decade')
    elif task.startswith('Genre'):
        cfgs, nn_cfgs = genre_config(task, 'ann')
    elif task.startswith('Gender'):
        cfgs, nn_cfgs = gender_config(task, 'ann')
    _, cls_to_id, id_to_cls = parse_csv_list_file(cfgs['train_list_fname'])
    ann_mean = np.load('means/mean_%s_%s.npy' %(task,'ann'))
    cnn_mean = np.load('means/mean_%s_%s.npy' %(task,'cnn'))
    return cls_to_id, id_to_cls, ann_mean, cnn_mean

def build_label_map_year2decade(cls_to_id):
    new_cls_to_id = dict({})
    new_id_to_cls = dict({})
    old_to_new_ids = dict({})
    counter = 0
    years = cls_to_id.keys()
    years = sorted(years)
    for year in years:
        decade = '%d0s' %int(np.floor(int(year) / 10))
        if decade not in new_cls_to_id:
            new_cls_to_id[decade] = counter # '19x0s' -> 0 ...
            new_id_to_cls[counter] = decade # 0 -> '19x0s'
            counter += 1
        old_to_new_ids[cls_to_id[year]] = new_cls_to_id[decade]
    num_ids = len(new_id_to_cls.keys())
    return old_to_new_ids, new_id_to_cls, num_ids

def sum_score(scores):
    sum_scores = scores.sum(axis=0)
    final_pred = np.argmax(sum_scores)
    return final_pred

def ensemble(scores1, scores2):
    ss1 = scores1.sum(axis=0).reshape([1,-1])
    ss2 = scores2.sum(axis=0).reshape([1,-1])
    ss1 = softmax(ss1)
    ss2 = softmax(ss2)
    final_scores = ss1 + ss2
    final_pred = np.argmax(final_scores)
    return final_pred

def predict_genre(feat1, feat2, ann, cnn, cls_to_id, id_to_cls, mean1, mean2):
    # ann
    preds1, scores1 = ann.predict(feat1 - mean1)
    final_pred1 = sum_score(scores1)
    # cnn
    preds2, scores2 = cnn.predict(feat2 - mean2)
    final_pred2 = sum_score(scores2)
    # ensemble
    ensemble_pred = ensemble(scores1, scores2)

    print('--------------Genre Prediction--------------')
    print('FeatureExtraction1: %s' %id_to_cls[final_pred1])
    print('FeatureExtraction2: %s' %id_to_cls[final_pred2])
    print('Ensemble: %s' %id_to_cls[ensemble_pred])

def predict_gender(feat1, feat2, ann, cnn, cls_to_id, id_to_cls, mean1, mean2):
    # ann
    preds1, scores1 = ann.predict(feat1 - mean1)
    final_pred1 = sum_score(scores1)
    # cnn
    preds2, scores2 = cnn.predict(feat2 - mean2)
    final_pred2 = sum_score(scores2)
    # ensemble
    ensemble_pred = ensemble(scores1, scores2)

    print('--------------Gender Prediction--------------')
    print('FeatureExtraction1: %s' %id_to_cls[final_pred1])
    print('FeatureExtraction2: %s' %id_to_cls[final_pred2])
    print('Ensemble: %s' %id_to_cls[ensemble_pred])

def predict_year(feat1, feat2, ann, cnn, cls_to_id, id_to_cls, mean1, mean2):
    # ann
    preds1, scores1 = ann.predict(feat1 - mean1)
    final_pred1 = sum_score(scores1)
    # cnn
    preds2, scores2 = cnn.predict(feat2 - mean2)
    final_pred2 = sum_score(scores2)
    # ensemble
    ensemble_pred = ensemble(scores1, scores2)

    print('--------------Year Prediction--------------')
    print('FeatureExtraction1: %s (%s)' %(id_to_cls[final_pred1], id_to_cls[final_pred1]))
    print('FeatureExtraction2: %s (%s)' %(id_to_cls[final_pred2], id_to_cls[final_pred2]))
    print('Ensemble: %s (%s)' %(id_to_cls[ensemble_pred], id_to_cls[ensemble_pred]))

if __name__ == '__main__':
    len(sys.argv) == 2, 'Path to folder containing the songs need to be provided'
    song_folder = sys.argv[1]
    # ./data/6th Nov/genre/songs

    genre_ann, genre_cnn = load_models('Genre_fold_1')
    genre_cls_to_id, genre_id_to_cls, genre_ann_mean, genre_cnn_mean = get_utils('Genre_fold_1')
    ft1, ft2 = init_ft('Genre_fold_1')

    gender_ann, gender_cnn = load_models('Gender_fold_1')
    gender_cls_to_id, gender_id_to_cls, gender_ann_mean, gender_cnn_mean = get_utils('Gender_fold_1')

    year_ann, year_cnn = load_models('Year_fold_1')
    year_cls_to_id, year_id_to_cls, year_ann_mean, year_cnn_mean = get_utils('Year_fold_1')
    year_cls_to_id, year_id_to_cls, _ = build_label_map_year2decade(year_cls_to_id)

    filenames = os.listdir(song_folder)
    for fname in filenames:
        fname = fname.strip()
        if not fname.endswith('.mp3'):
            continue
        print('--------------------------------------------')
        print(fname)
        print('Extracting Feature 1 ...')
        feat1 = ft1.extract_feature(os.path.join(song_folder, fname))
        print('Extracting Feature 2 ...')
        feat2 = ft2.extract_spectrogram(os.path.join(song_folder, fname))

        print('Done.')
        predict_genre(feat1, feat2, genre_ann, genre_cnn, genre_cls_to_id, genre_id_to_cls, genre_ann_mean, genre_cnn_mean)
        predict_gender(feat1, feat2, gender_ann, gender_cnn, gender_cls_to_id, gender_id_to_cls, gender_ann_mean, gender_cnn_mean)
        predict_year(feat1, feat2, year_ann, year_cnn, year_cls_to_id, year_id_to_cls, year_ann_mean, year_cnn_mean)
        input("Press Enter to continue...")


from datetime import datetime, timedelta
from io import BytesIO
from PIL import Image
from ebedke.utils.date import on_workdays, days_lower
from ebedke.utils.utils import ocr_image, pattern_slice
from ebedke.utils import facebook
from ebedke.utils.text import skip_empty_lines
from ebedke.pluginmanager import EbedkePlugin

FB_PAGE = "https://www.facebook.com/pg/kerovaetelbar/posts/"
FB_ID = "582373908553561"

@on_workdays
def get_menu(today):
    is_this_week = lambda date: datetime.strptime(date, '%Y-%m-%dT%H:%M:%S%z').date() >= today.date() - timedelta(days=7)
    menu_filter = lambda post: is_this_week(post['created_time']) and "heti menü" in post['message'].lower()
    image = facebook.get_post_attached_image(FB_ID, menu_filter)
    if image:
        image = Image.open(BytesIO(image)).convert('L')
        f = BytesIO()
        image.save(f, format="png", optimize=True)
        menu = ocr_image(f).splitlines()
        if not menu:
            return []

        menu = pattern_slice(menu, [days_lower[today.weekday()]], days_lower + ['desszert', "890"], inclusive=False)
        menu = skip_empty_lines(menu, dropwords=["shutt", "stock", "wow", "awesi"])
    else:
        return []

    return menu

plugin = EbedkePlugin(
    enabled=True,
    groups=["corvin"],
    name='Kerova',
    id='kv',
    url=FB_PAGE,
    downloader=get_menu,
    ttl=timedelta(hours=23),
    cards=[],
    coord=(47.486746, 19.079615)
)