import asyncio
import logging
import random
from datetime import timedelta
from json.decoder import JSONDecodeError

import async_timeout
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from h11 import Data
from homeassistant import core
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.exceptions import IntegrationError
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.discovery import async_load_platform
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import (DataUpdateCoordinator,
                                                      UpdateFailed)

from .const import DOMAIN, GW_ID, GW_IP, NAME, PLATFORMS, TAP_ID
from .linktap_local import LinktapLocal

_LOGGER = logging.getLogger(__name__)

async def async_setup(_hass, _config):
    return True

async def async_setup_entry(hass: core.HomeAssistant, entry: ConfigEntry)-> bool:
    """Set up the platform."""

    gw_ip = entry.data.get(GW_IP)

    linker = LinktapLocal()
    linker.set_ip(gw_ip)
    try:
        gw_id = await linker.get_gw_id()
    except JSONDecodeError:
        try:
            await asyncio.sleep(random.randint(1,3))
            gw_id = await linker.get_gw_id()
        except JSONDecodeError:
            await asyncio.sleep(random.randint(1,3))
            gw_id = await linker.get_gw_id()

    _LOGGER.debug(f"Found GW_ID: {gw_id}")

    gateway_config = await linker.get_gw_config(gw_id)
    if "end_dev" not in gateway_config:
        raise IntegrationError("Linktap Gateway needs to be updated")

    devices = {
        "devs": gateway_config["end_dev"],
        "names": gateway_config["dev_name"],
    }
    _LOGGER.debug(f"Found devices: {devices}")

    coordinator_conf = {
        GW_IP: gw_ip,
        GW_ID: gw_id,
    }
    counter = 0
    tap_list = []
    for tap_id in devices["devs"]:
        coordinator = LinktapCoordinator(hass, linker, coordinator_conf, tap_id)
        device_name = devices["names"][counter]
        tap_list.append({
            NAME: device_name,
            TAP_ID: tap_id,
            GW_IP: gw_ip,
            "coordinator": coordinator
        })
        counter = counter + 1
        await coordinator.async_config_entry_first_refresh()
        _LOGGER.debug(f"Coordinator has synced for {tap_id}")
    _LOGGER.debug(f"List of Taps: {tap_list}")

    vol_unit = gateway_config["vol_unit"]
    _LOGGER.debug(f"Setting volume unit to {vol_unit}")

    conf = {
        GW_IP: gw_ip,
        GW_ID: gw_id,
        "taps": tap_list,
        "vol_unit": vol_unit,
    }

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {"conf": conf}
    _LOGGER.debug(hass.data[DOMAIN])
    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
    # Reload entry when its updated.
    entry.async_on_unload(entry.add_update_listener(async_reload_entry))

    return True

async def async_unload_entry(hass: core.HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a component config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)
    return unload_ok

async def async_remove_config_entry_device(hass: core.HomeAssistant, entry: ConfigEntry, device) -> bool:
    device_registry(hass).async_remove_device(device.id)
    return True

class LinktapCoordinator(DataUpdateCoordinator):
    def __init__(self, hass, linker, conf, tap_id):
        super().__init__(
            hass,
            _LOGGER,
            name=DOMAIN,
            update_interval=timedelta(seconds=13),
        )
        self.tap_api = linker
        self.conf = conf
        self.hass = hass
        self.tap_id = tap_id

    def get_gw_id(self):
        return self.conf[GW_ID]

    #def get_vol_unit(self):
    #    return self.conf["vol_unit"]

    async def _async_update_data(self):
        """Fetch data from API endpoint.

        This is the place to pre-process the data to lookup tables
        so entities can quickly look up their data.
        """

        #tap_id = self.conf["taps"][TAP_ID]
        gw_id = self.conf[GW_ID]

        try:
            # Note: asyncio.TimeoutError and aiohttp.ClientError are already
            # handled by the data update coordinator.
            async with async_timeout.timeout(10):
                return await self.tap_api.fetch_data(gw_id, self.tap_id)
        except:# ApiAuthError as err:
            await asyncio.sleep(random.randint(1,3))
            async with async_timeout.timeout(10):
                return await self.tap_api.fetch_data(gw_id, self.tap_id)
            # Raising ConfigEntryAuthFailed will cancel future updates
            # and start a config flow with SOURCE_REAUTH (async_step_reauth)
        #    raise ConfigEntryAuthFailed from err
        #except ApiError as err:
        #    raise UpdateFailed(f"Error communicating with API: {err}")

async def async_reload_entry(hass: core.HomeAssistant, entry: ConfigEntry) -> None:
    """Reload the config entry when it changed."""
    await hass.config_entries.async_reload(entry.entry_id)


#
# [77] Combinations
#
# https://leetcode.com/problems/combinations/description/
#
# algorithms
# Medium (40.85%)
# Total Accepted:    136.3K
# Total Submissions: 333.7K
# Testcase Example:  '4\n2'
#
#
# Given two integers n and k, return all possible combinations of k numbers out
# of 1 ... n.
#
#
# For example,
# If n = 4 and k = 2, a solution is:
#
#
#
# [
#  [2,4],
#  [3,4],
#  [2,3],
#  [1,2],
#  [1,3],
#  [1,4],
# ]
#
#
class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        # O(2^n)
        res = []
        self.backtracking(n,k,res,[], 1)
        return res
    def backtracking(self,n,k,res,temp,start):
        if k == 0:
            res.append(list(temp))
        for i in range(start, n+1):
            temp.append(i)
            self.backtracking(n,k-1,res,temp,i+1)
            temp.pop()


from eos.tests import TestBase
from eos.types import Fit, Character, Slot, Module, Ship, User, State, Drone, Implant, Booster, Hardpoint, DamagePattern
from eos import db
import eos.db.saveddata.queries
import sqlalchemy.orm
from copy import deepcopy
from itertools import count

class Test(TestBase):
    def setUp(self):
        TestBase.setUp(self)
        self.m = Module(db.getItem("Heat Sink I"))

    def test_tankNumbers(self):
        f = Fit()
        f.ship = Ship(db.getItem("Erebus"))
        f.modules.append(Module(db.getItem("Small Shield Booster II")))
        f.modules.append(Module(db.getItem("Small Armor Repairer II")))
        f.modules.append(Module(db.getItem("Small Hull Repairer II")))
        f.modules.append(Module(db.getItem("Damage Control II")))
        f.damagePattern = DamagePattern(25, 25, 25, 25)
        for m in f.modules:
            m.state = State.ACTIVE
        f.calculateModifiedAttributes()

        self.assertEquals(len(f.effectiveTank), len(f.tank))
        for k in f.effectiveTank.iterkeys():
            self.assertGreater(f.effectiveTank[k], f.tank[k])

        self.assertEquals(len(f.effectiveSustainableTank), len(f.sustainableTank))
        for k in f.effectiveSustainableTank.iterkeys():
            self.assertGreater(f.effectiveSustainableTank[k], f.sustainableTank[k])

    def test_addDrain(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.addDrain(5, 500, 0)
        self.assertEquals(f.capUsed, 100000)

    def test_setCharacter(self):
        f = Fit()
        f.character = Character("Testety")

    def test_addNotAModule(self):
        try:
            self.f.addModule(1302)
        except:
            return
        self.fail("Added an invalid module, was expecting a ValueError")

    def test_addValidModule(self):
        f = Fit()
        f.modules.append(self.m)

    def test_importEft(self):
        f = Fit.importEft('''[Rifter, Test]
                             Salvager I
                             Hobgoblin I x4''')

        self.assertEquals(f.name, "Test")
        self.assertEquals(f.ship.item.name, "Rifter")
        self.assertEquals(f.modules[0].item.name, "Salvager I")
        self.assertEquals(f.drones[0].amount, 4)
        self.assertEquals(f.drones[0].item.name, "Hobgoblin I")

    def test_importXml(self):
        fits = Fit.importXml('''<?xml version="1.0" ?>
                            <fittings>
                                <fitting name="Test">
                                    <description value=""/>
                                    <shipType value="Rifter"/>
                                    <hardware slot="hi slot 0" type="Salvager II"/>
                                </fitting>
                            </fittings>''')

        f = fits[0]
        self.assertEquals(f.name, "Test")
        self.assertEquals(f.ship.item.name, "Rifter")
        self.assertEquals(f.modules[0].item.name, "Salvager II")

    def test_removeModuleNotExists(self):
        f = Fit()
        self.assertRaises(ValueError, f.modules.remove, self.m)

    def test_removeModuleExists(self):
        f = Fit()
        f.modules.append(self.m)
        f.modules.remove(self.m)

    def test_removeInvalidModule(self):
        f = Fit()
        self.assertRaises(ValueError, f.modules.remove, 1302)

    def test_setShip(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))

    def test_extraAttributesClear(self):
        f = Fit()
        f.extraAttributes["cloaked"] = True
        f.clear()
        self.assertEqual(f.extraAttributes["cloaked"], False)

    def test_databaseConsistency(self):
        oldSession = db.saveddata_session
        oldSession.commit()
        try:
            f = Fit()
            f.ship = Ship(db.getItem("Rifter"))
            f.name = "test fit 1"
            u = User("fittest", "testy", False)
            f.owner = u

            f2 = Fit()
            f2.ship = Ship(db.getItem("Thrasher"))
            f2.name = "test fit 2"
            f2.owner = u
            db.saveddata_session.add(f)
            db.saveddata_session.add(f2)
            db.saveddata_session.flush()

            f.projectedFits.append(f2)

            #Hack our way through changing the session temporarly
            oldSession = eos.db.saveddata.queries.saveddata_session
            eos.db.saveddata.queries.saveddata_session = sqlalchemy.orm.sessionmaker(bind=db.saveddata_engine)()

            newf = db.getFit(f.ID)

            self.assertNotEquals(id(newf), id(f))
            self.assertEquals(f.name, newf.name)
            for fit in newf.projectedFits:
                self.assertNotEqual(id(fit), id(f2))
                self.assertEquals(f2.name, fit.name)

        except:
            db.saveddata_session.rollback()
            raise
        finally:
            #Undo our hack as to not fuck up anything
            eos.db.saveddata.queries.saveddata_session = oldSession

    def test_projectedFit(self):
        f1 = Fit()
        f1.ship = Ship(db.getItem("Rifter"))
        f2 = Fit()
        m1 = Module(db.getItem("Stasis Webifier I"))
        m2 = Module(db.getItem("Stasis Webifier I"))
        m1.state = State.ACTIVE
        m2.state = State.ACTIVE
        f2.modules.append(m1)
        f2.modules.append(m2)
        f1.projectedFits.append(f2)
        f1.calculateModifiedAttributes()
        self.assertAlmostEquals(99.800, f1.ship.getModifiedItemAttr("maxVelocity"), 3)

    def test_projectSelf(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        m1 = Module(db.getItem("Stasis Webifier I"))
        m2 = Module(db.getItem("Stasis Webifier I"))
        m1.state = State.ACTIVE
        m2.state = State.ACTIVE
        f.modules.append(m1)
        f.modules.append(m2)
        f.projectedFits.append(f)
        f.calculateModifiedAttributes()
        self.assertAlmostEquals(99.800, f.ship.getModifiedItemAttr("maxVelocity"), 3)

    def test_capacitorNoMods(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        self.assertEquals(f.capStable, True)
        self.assertAlmostEquals(f.capState, 100, 1)

    def test_capacitorUnstable(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        m = Module(db.getItem("100MN Afterburner I"))
        m.state = State.ACTIVE
        f.modules.append(m)
        self.assertFalse(f.capStable)
        self.assertTrue(f.capState < 15)

    def test_capacitorSingleCycleKill(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        for _ in xrange(5):
            m = Module(db.getItem("100MN Afterburner I"))
            m.state = State.ACTIVE
            f.modules.append(m)

        self.assertFalse(f.capStable)
        self.assertEquals(f.capState, 0)

    def test_copy(self):
        f = Fit()
        f.name = "Testety"
        f.character = Character("TEST")
        f.owner = User("moo")
        testm = Module(db.getItem("Heat Sink I"))
        f.modules.append(testm)
        tests = Ship(db.getItem("Rifter"))

        f.ship = tests

        testpm = Module(db.getItem("Stasis Webifier I"))
        f.projectedModules.append(testpm)

        testd = Drone(db.getItem("Hobgoblin I"))
        f.drones.append(testd)

        testi = Implant(db.getItem("Halo Omega"))
        f.implants.append(testi)

        testb = Booster(db.getItem("Strong Drop Booster"))
        f.boosters.append(testb)

        testpd = Drone(db.getItem("Warrior TP-300"))
        f.projectedDrones.append(testpd)

        testpf = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.name = "Projected"
        f.projectedFits.append(testpf)

        newf = deepcopy(f)
        self.assertEquals(newf.name, "%s copy" % f.name)
        self.assertEquals(newf.character, f.character)
        self.assertEquals(newf.owner, f.owner)

        newm = newf.modules[0]
        self.assertNotEquals(id(newm), id(testm))
        self.assertEquals(len(newf.modules), len(f.modules))

        newpm = newf.projectedModules[0]
        self.assertNotEquals(id(newpm), id(testpm))
        self.assertEquals(len(newf.projectedModules), len(f.projectedModules))

        newd = newf.drones[0]
        self.assertNotEquals(id(newd), id(testd))
        self.assertEquals(len(newf.drones), len(f.drones))

        newb = newf.boosters[0]
        self.assertNotEquals(id(newb), id(testb))
        self.assertEquals(len(newf.boosters), len(f.boosters))

        newi = newf.implants[0]
        self.assertNotEquals(id(newi), id(testi))
        self.assertEquals(len(newf.implants), len(f.implants))

        newpd = newf.projectedDrones[0]
        self.assertNotEquals(id(newpd), id(testpd))
        self.assertEquals(len(newf.projectedDrones), len(f.projectedDrones))

        newpm = newf.projectedModules[0]
        self.assertNotEquals(id(newpm), id(testpm))
        self.assertEquals(len(newf.projectedModules), len(f.projectedModules))

        newpf = newf.projectedFits[0]
        self.assertEquals(id(newpf), id(testpf))
        self.assertEquals(len(newf.projectedFits), len(f.projectedFits))

    def test_repperSustainability(self):
        f = Fit()
        f.ship = Ship(db.getItem("Raven"))
        m = Module(db.getItem("Small Shield Booster I"))
        m.state = State.ACTIVE
        f.modules.append(m)
        f.calculateModifiedAttributes()
        s = f.calculateSustainableTank()
        self.assertEquals(s["armorRepair"], f.extraAttributes["armorRepair"])

    def test_zeroSustainable(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        for i in count(1):
            if i == 5: break
            m = Module(db.getItem("Heavy Energy Neutralizer I"))
            m.state = State.ACTIVE
            f.modules.append(m)

        m = Module(db.getItem("Small Shield Booster I"))
        m.state = State.ACTIVE
        f.modules.append(m)
        f.calculateModifiedAttributes()
        s = f.calculateSustainableTank()
        self.assertEquals(s["armorRepair"], 0)

    def test_sustainabilityConsistency(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        for i in count(1):
            if i == 3: break
            m = Module(db.getItem("Small Shield Booster I"))
            m.state = State.ACTIVE
            f.modules.append(m)

        f.calculateModifiedAttributes()
        s = f.sustainableTank
        self.assertAlmostEquals(s["shieldRepair"], 3.8, 1)

    def test_capCalcs(self):
        f = Fit()
        f.ship = Ship(db.getItem("Reaper"))
        f.ship.itemModifiedAttributes["capacitorCapacity"] = 125.0
        f.ship.itemModifiedAttributes["rechargeRate"] = 93250
        m = Module(db.getItem("Small Shield Booster I"))
        m.state = State.ACTIVE
        f.modules.append(m)
        self.assertAlmostEquals(f.capState, 14.0, 1)

    def test_weaponDPS(self):
        f = Fit()
        m = Module(db.getItem("Heavy Modulated Energy Beam I"))
        m.state = State.ACTIVE
        m.charge = db.getItem("Multifrequency M")
        f.modules.append(m)
        expected = 0
        for type in ("emDamage", "thermalDamage", "kineticDamage", "explosiveDamage"):
            expected += m.getModifiedChargeAttr(type)

        expected *= m.getModifiedItemAttr("damageMultiplier") / (m.getModifiedItemAttr("speed") / 1000.0)
        self.assertAlmostEquals(f.weaponDPS, expected)

    def test_weaponVolley(self):
        f = Fit()
        m = Module(db.getItem("Heavy Modulated Energy Beam I"))
        m.state = State.ACTIVE
        m.charge = db.getItem("Multifrequency M")
        f.modules.append(m)
        expected = 0
        for type in ("emDamage", "thermalDamage", "kineticDamage", "explosiveDamage"):
            expected += m.getModifiedChargeAttr(type)

        expected *= m.getModifiedItemAttr("damageMultiplier")
        self.assertAlmostEquals(f.weaponVolley, expected)

    def test_droneDPS(self):
        f = Fit()
        d = Drone(db.getItem("Hammerhead II"))
        d.active = True
        d.amount = 3
        d.amountActive = 3
        f.drones.append(d)
        expected = 0
        for type in ("emDamage", "thermalDamage", "kineticDamage", "explosiveDamage"):
            expected += d.getModifiedItemAttr(type)

        expected *= d.getModifiedItemAttr("damageMultiplier") / (d.getModifiedItemAttr("speed") / 1000.0)
        self.assertAlmostEquals(f.droneDPS, expected * 3)

    def test_missileDroneDPS(self):
        f = Fit()
        d = Drone(db.getItem("Cyclops"))
        d.active = True
        d.amount = 2
        d.amountActive = 2
        f.drones.append(d)
        expected = 0
        for type in ("emDamage", "thermalDamage", "kineticDamage", "explosiveDamage"):
            expected += d.getModifiedChargeAttr(type)

        expected /= d.getModifiedItemAttr("missileLaunchDuration") / 1000.0
        self.assertAlmostEquals(f.droneDPS, expected * 2)

    def test_hardpointCount(self):
        f = Fit()
        f.modules.append(Module(db.getItem("Heavy Modulated Energy Beam I")))
        f.modules.append(Module(db.getItem("Standard Missile Launcher I")))
        f.modules.append(Module(db.getItem("Salvager I")))
        self.assertEquals(f.getHardpointsUsed(Hardpoint.MISSILE), 1)
        self.assertEquals(f.getHardpointsUsed(Hardpoint.TURRET), 1)

    def test_fill(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.fill()
        self.assertEquals(len(f.modules), 13)

    def test_fillT3(self):
        f = Fit()
        f.ship = Ship(db.getItem("Tengu"))
        f.modules.append(Module(db.getItem("Tengu Defensive - Adaptive Shielding")))
        f.clear()
        f.calculateModifiedAttributes()
        f.fill()
        self.assertEquals(len(f.modules), 10)

    def test_fillTooMuchDummies(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        for _ in xrange(5):
            f.modules.append(Module.buildEmpty(Slot.LOW))

        f.fill()
        self.assertEquals(len(f.modules), 13)

    def test_fillOrdering(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.fill()
        for i, mod in enumerate(f.modules):
            self.assertEquals(i, mod.position)

    def test_getSlotsUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.modules.append(Module(db.getItem("Salvager I")))
        f.fill()
        self.assertEquals(f.getSlotsUsed(Slot.HIGH), 1)

    def test_getCalibrationUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.modules.append(Module(db.getItem("Large Trimark Armor Pump I")))
        self.assertEquals(f.calibrationUsed, 50)

    def test_pgUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.modules.append(Module(db.getItem("Salvager I")))
        self.assertEquals(f.pgUsed, 1)

    def test_cpuUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.modules.append(Module(db.getItem("Salvager I")))
        self.assertEquals(f.cpuUsed, 20)

    def test_droneBandwidthUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        d = Drone(db.getItem("Hobgoblin I"))
        d.amount = 1
        d.amountActive = 1
        f.drones.append(d)
        self.assertEquals(f.droneBandwidthUsed, 5)

    def test_droneBayUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.drones.appendItem(db.getItem("Hobgoblin I"))
        self.assertEquals(f.droneBayUsed, 5)

    def test_addRemoveFit(self):
        f = Fit()
        rifter = db.getItem("Rifter")
        f.ship = Ship(rifter)
        f.fill()
        db.saveddata_session.add(f)
        db.saveddata_session.flush()
        db.saveddata_session.delete(f)
        db.saveddata_session.flush()

    def test_removeDrone(self):
        f = Fit()
        gob = db.getItem("Hobgoblin I")
        f.drones.appendItem(gob)
        f.drones.removeItem(gob, 1)

    def test_scanStr(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        self.assertEquals("Ladar", f.scanType)


import argparse

from abc import abstractmethod

from git_fzf.lib.utils.shell import run

from .InteractiveCommand import InteractiveCommand

class InteractiveDiffLikeCommand(InteractiveCommand):
    def __init__(self):
        super().__init__(
            no_candidates_message="you do not have any files to diff",
            enable_multi_select=True,
        )

        self.parser = argparse.ArgumentParser()
        self.parser.add_argument("--staged", "--cached", action="store_true")
        self.parser.set_defaults(staged=False)
        self.args = self.parser.parse_args()

        self.flags = {
            "get_candidates": [
                "--name-only",
                "--relative",
            ],
            "affect_selected": [],
        }

        if self.args.staged:
            self.flags.get("get_candidates").append("--staged")
            self.flags.get("affect_selected").append("--staged")

    def get_candidates(self):
        return run(
            f"git diff {' '.join(self.flags.get('get_candidates'))}",
            capture_output=True,
        ).splitlines()

    @abstractmethod
    def affect_selected(self):
        raise NotImplementedError


from django.urls import path

from . import views

app_name = 'emousic'

urlpatterns = [
    path('', views.index, name='index'),
    path('index', views.index, name='index'),
    path('get_moodtags/', views.get_moodtags, name='get_moodtags'),
    path('rdf', views.rdf, name='rdf'),
    path('wildwebmidi.data', views.read_wildwebmidi, name='read_wildwebmidi')
]


def visit_BitVecConcat(self, expression, *operands):
        """ concat( extract(k1, 0, a), extract(sizeof(a)-k1, k1, a))  ==> a
            concat( extract(k1, beg, a), extract(end, k1, a))  ==> extract(beg, end, a)
        """
        op = expression.operands[0]

        value = None
        end = None
        begining = None
        for o in operands:
            # If found a non BitVecExtract, do not apply
            if not isinstance(o, BitVecExtract):
                return None
            # Set the value for the first item
            if value is None:
                value = o.value
                begining = o.begining
                end = o.end
            else:
                # If concat of extracts of different values do not apply
                if value is not o.value:
                    return None
                # If concat of non contiguous extracs do not apply
                if begining != o.end + 1:
                    return None
                # update begining variable
                begining = o.begining

        if value is not None:
            if end + 1 == value.size and begining == 0:
                return value
            else:
                return BitVecExtract(value, begining, end - begining + 1, taint=expression.taint)


from random import randint, choice

from enemies.knight import KnightEnemy
from enemies.necromancer import NecromancerEnemy
from enemies.skeleton import SkeletonEnemy, SkeletonSpearman, SkeletonWarrior
from enemies.zombie import ZombieEnemy

ENEMIES = {
    'skeleton': lambda position, player: SkeletonEnemy('skeleton', randint(1, 5), 30, {
        'attack': 0.8,
        'endurance': 10,
        'weaknesses': ['light'],
        'type': ['dark'],
        'xp': 5,
        'actions': {
            'attack': .5,
            'strong_attack': .3,
            'bleeding_attack': .2
        },
    }, position, player),
    'necromancer': lambda position, player: NecromancerEnemy('necromancer', randint(20, 30), 100, {
        'attack': 2,
        'endurance': 20,
        'weaknesses': [],
        'type': ['light'],
        'xp': 50,
        'actions': {
            'attack': .95,
            'magic': .05,
        },
    }, position, player),
    'knight': lambda position, player: KnightEnemy('knight', randint(5, 20), 30, {
        'attack': 2,
        'endurance': 10,
        'weaknesses': ['dark'],
        'type': ['light'],
        'xp': 7,
        'actions': {
            'attack': .8,
            'buff': .1,
            'debuff_attack': .1
        },
    }, position, player),
    'zombie': lambda position, player: ZombieEnemy('zombie', randint(10, 15), 25, {
        'attack': 4,
        'endurance': 2,
        'weaknesses': ['fire'],
        'type': ['dark'],
        'xp': 15,
        'actions': {
            'attack': .7,
            'heal': .3
        },
    }, position, player),
    'SkeletonSpearman': lambda position, player: SkeletonSpearman('Spearman', randint(5, 15), 50, {
        'attack': 1.2,
        'endurance': 10,
        'miss': 0.2,
        'weaknesses': ['light'],
        'type': ['dark', 'physical'],
        'xp': 7,
        'actions': {
            'attack': .5,
            'strong_attack': .3,
            'bleeding_attack': .2
        },
    }, position, player),
    'SkeletonWarrior': lambda position, player: SkeletonWarrior('Warrior', randint(10, 20), 50, {
        'attack': 1.5,
        'manaburn': 2,
        'endurance': 10,
        'miss': 0.25,
        'weaknesses': ['light'],
        'type': ['dark', 'physical'],
        'xp': 10,
        'actions': {
            'attack': .5,
            'strong_attack': .3,
            'bleeding_attack': .2
        },
    }, position, player)
}

def get_enemy_pattern(level_enemy_name, player_lvl):
    if level_enemy_name == 'skeleton':
        if player_lvl < 2:
            return ['skeleton']
        if player_lvl < 4:
            return choice((['skeleton'], ['skeleton'] * 2))
        if player_lvl < 6:
            return choice((['skeleton'] * 2, ['skeleton'] * 3, ['SkeletonSpearman']))
        if player_lvl < 9:
            return choice((['skeleton'] * 3, ['SkeletonSpearman'], ['skeleton', 'SkeletonSpearman']))
        if player_lvl < 11:
            return choice((['SkeletonSpearman', 'skeleton'], ['SkeletonWarrior']))
        if player_lvl < 13:
            return choice((['SkeletonSpearman', 'skeleton', 'skeleton'], ['SkeletonWarrior', 'skeleton']))
        return choice(
            (['SkeletonSpearman', 'SkeletonSpearman', 'SkeletonWarrior'], ['SkeletonWarrior', 'skeleton', 'SkeletonSpearman']))
    if level_enemy_name == 'zombie':
        return choice((['zombie'], ['zombie'] * 2))
    if level_enemy_name == 'knight':
        return choice((['knight'] * 2, ['knight'] * 3, ['knight'] * 4))
    return [level_enemy_name]


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

""" Handler of result view

"""

from lib.record import recordFactory

IMP_MOD = "from %s.%s import %s"

class Handler(object):

    def __init__(self, judge_no):
        self.judge_no = judge_no
        self.conn = recordFactory.init().get_connection()

    def arrange(self, result):
        result = {}
        contest_no = result["contest_no"]
        cls_name = self.__extract_contest_cls(contest_no)
        mods = self.__make_imp_string(cls_name)
        for mod in mods:
            exec(mod)
        loader = Loader(contest_no)
        targets = loader.load()
        calc = Calculation(contest_no)
        rank = calc.calculate(targets)
        result["rank"] = rank
        viewer = Viewer(contest_no)
        result["template"] = viewer.template
        return result

    def __extract_contest_cls(contest_no):
        """ must fix to load from database """
        return "OBO"

    def __make_imp_string(cls_name):
        mods = []
        cls_list = ["Calculation", "Loader", "Viewer"]
        for cls in cls_list:
            cls = IMP_MOD % (cls_name.upper(), cls.lower(), cls)
            mods.append(cls)
        return mods


from dllist import DoubleLinkedList

class Dictionary(object):
    def __init__(self, num_buckets=256):
        """Initializes a Map with the given number of buckets."""
        # save to init List
        # make buckets which has  List

        self.num_buckets = num_buckets
        self.map = DoubleLinkedList()
        for i in range(num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        """Given a key this will create a number and then convert it to
        an index for the aMap's buckets."""
        # return HASH value that was made by key
        return hash(key) % self.num_buckets

    def get_bucket(self, key):
        """Given a key, find the bucket where it would go."""

        # return bucket index
        # using HASH

        idx = self.hash_key(key)
        bucket = self.map.get(idx)
        return bucket

    def get_slot(self, key, default=None):
        """
        Returns either the bucket and node for a slot, or None, None
        """
        #point out the bucket
         # bucket ok ?
         #  search bucket
         #   if find  return ( bucket, node)
         #  not found  return ( bucket, next-node)
         #
         # bucket not Ok
         #
        slot = self.get_bucket(key)

        s_num = slot.count()
        for i in range(s_num):

            val = slot.get(i)
            if (val[0] == key):
                return slot, val
                break;

        return slot, None

    def get(self, key, default=None):
        """Gets the value in a bucket for the given key, or the default."""
        # get node
        # return value  or   node ( node == None)
        slot, node = self.get_slot(key)
        if (node):
            print("__Get_Val=", node[1])
            return node[1]
        else:
            return default

    def set(self, key, value):
        """Sets the key to the value, replacing any existing value."""

        # get bucket, node
        #  if node ?   ( key was found)
        #   change value

        #  node == None ( do not have key)

        slot, node = self.get_slot(key)
        if (node):
            node[1] = value
        else:
            slot.push([key, value])

    def delete(self, key):
        """Deletes the given key from the Map."""
        # get bucket
        # search node
        # detach from List

        #slot, val = self.get_slot(key)
        slot = self.get_bucket(key)
        if (slot):

            bfound = False
            node = slot.begin
            while (node):
                if (node.value[0] == key):
                    print("will be Deleted ", node.value[0], node.value[1])
                    bfound = True
                    break
                node = node.next

            if bfound:
                slot.detach_node(node)

    def list(self):
        """Prints out what's in the Map."""

        print("__________list of dictionary______")

        for i in range(self.num_buckets):
            bucket = self.map.get(i)

            cnt = bucket.count()
            for j in range(cnt):

                node = bucket.get(j)
                print("KEY=", node[0], "VALUE=", node[1])


import sys
import room_mqttAdapter
import room_sensorManager
import room_config
import time

class RoomDevice():
    def __init__(self):
        self.mqttAdater = room_mqttAdapter.RoomMQTTAdater()
        self.sensorManager = room_sensorManager.RoomSensorManager()
        print("START")
        self.__start()
        pass

    def __start(self):
        while True:
            time.sleep(5)
            temperature, humidity = self.sensorManager.getData()
            self.mqttAdater.sendData(
                room_config.room_idx, temperature, humidity)
            print("SEND DATA - "+str(room_config.room_idx) +
                  " ("+str(temperature)+","+str(humidity)+")")

if __name__ == '__main__':
    device = RoomDevice()


import operator

p = '/Users/telliott/Dropbox/'
p += 'Github/Python3Intro/data/'

# https://norvig.com/ngrams/
# words with frequency counts
fn = p + "count_1w.txt"
with open(fn) as fh:
    data = fh.read()
norvig = data.strip().split('\n')

D = dict()
for e in norvig:
    w,count = e.strip().split()
    if len(w) == 5:
        D[w] = count

fn = p + 'sgb-words.txt'
with open(fn) as fh:
    data = fh.read()
knuth = data.strip().split('\n')

L = list()
discard = list()

for w in knuth:
    if w in D:
        count = D[w]
        L.append((w,int(count)))

# print(len(L),len(discard))
# 5215 542

L.sort(key=operator.itemgetter(1)) # by count
L.reverse()
for w,count in L:
    print(w)


# -*- coding: utf-8 -*-
"""
Created on Sun Oct 14 17:43:35 2018

@author: Windows 7
"""
import numpy as np
from sympy import *

def Christoffel(d,g,ginverse):
    christoffel = [[[[]for k in range(d)] for j in range(d)] for i in range(d)]
    christoffel = [[[[]for k in range(d)] for j in range(d)] for i in range(d)]
    for n in range(d):
        for a in range(d):
            for b in range(d):
                summation=0.0
                for i in range(d):
                    summation= summation+ginverse[n][i]*(diff(g[i][a],x[b])+diff(g[i][b],x[a])-diff(g[a][b],x[i]))
                christoffel[n][a][b]=summation/2
    for n in range(0,d):
        for a in range(0,d):
            for b in range(0,d):
                M= print("christoffel[",x[n],",",x[a],",",x[b],"]=", simplify(christoffel[n][a][b]))
    return M

d=3
r,theta, phi= symbols('r theta phi')
x=np.array([r,theta, phi])
g00 = 1
g11 = r**2
g22 = r**2*sin(theta)**2
g=np.array([[g00,0,0],[0,g11,0],[0,0,g22]])
ginverse = np.array([[np.reciprocal(g00),0,0],[0,np.reciprocal(g11),0],[0,0,np.reciprocal(g22)]])

print(Christoffel(d,g,ginverse))


from rle.explainers.logistic_regression_explainer import LogisticRegressionExplainer
from rle.samplers.gaussian_exponential_sampler import GaussianExponentialSampler
from rle.depicters.depicter_bar_weights import DepicterBarWeights
from sklearn.model_selection import train_test_split
from rle.explanation.robust_explanation import RobustExplanation
from sklearn.ensemble import RandomForestClassifier
import sklearn.datasets as datasets
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

sns.set_style("whitegrid")
plt.rc('text', usetex=True)
plt.rc('font', family='serif')

def same_side(p1, p2, a, b):
    cp1 = np.cross(b - a, p1 - a)
    cp2 = np.cross(b - a, p2 - a)
    if np.inner(cp1, cp2) >= 0:
        return True
    else:
        return False

def inside_triangle(p, a, b, c):
    if same_side(p, a, b, c) and same_side(p, b, a, c) and same_side(p, c, a, b):
        return True
    else:
        return False

# Initializes double triangle dataset
X = np.random.rand(5000, 2)
triangle = np.array([[0.4, 0.4], [0.6, 0.6], [0.01, 0.99]])
decision = np.array([0.27, 0.64])
y = np.array(list(map(lambda x: int(x[1] < x[0] or inside_triangle(x, triangle[0], triangle[1], triangle[2])), X)))

# Plots classified data (Random Forest)
X_train, X_test, y_train, y_test = train_test_split(X, y)
rf = RandomForestClassifier(n_estimators=100)
rf.fit(X_train, y_train)

dest = "./imgs/test_logistic_regression_robust_explanation_3.pdf"
# Initializes explainer
exp = RobustExplanation(X_train, ["F1", "F2"], None,
                        y_train, "Label", None,
                        model=RandomForestClassifier(n_estimators=100),
                        explainer=LogisticRegressionExplainer,
                        sampler=GaussianExponentialSampler,
                        depicter=DepicterBarWeights)

exp.sample_explain_depict(decision, 5, num_samples=5000, measure_min=0.005, measure_max=0.5, number_eval=500, dest=dest)


import numpy as np

COMET_MODEL = "wmt20-comet-da"
COMET_BATCH_SIZE = 64

BLEURT_BATCH_SIZE = 64

def comet(hyps, refs, srcs, comet_dir=None):
    from comet import download_model, load_from_checkpoint

    # download comet and load
    comet_path = download_model(COMET_MODEL, comet_dir)
    comet_model = load_from_checkpoint(comet_path)
    comet_input = [
        {"src": src, "mt": mt, "ref": ref} for src, mt, ref in zip(srcs, hyps, refs)
    ]
    # sentence-level and corpus-level COMET
    return comet_model.predict(
        comet_input, batch_size=COMET_BATCH_SIZE, sort_by_mtlen=True
    )

def bleurt(hyps, refs, srcs=None, bleurt_dir=None):
    from bleurt import score

    bleurt_scorer = score.LengthBatchingBleurtScorer(bleurt_dir)
    bleurt_scores = bleurt_scorer.score(
        references=refs, candidates=hyps, batch_size=BLEURT_BATCH_SIZE
    )
    assert type(bleurt_scores) == list
    return bleurt_scores, np.array(bleurt_scores).mean()

def bleu(hyps, refs, srcs=None):
    import sacrebleu

    sentence_scores = [
        sacrebleu.sentence_bleu(ref, [hyp]).score for hyp, ref in zip(hyps, refs)
    ]
    corpus_score = sacrebleu.corpus_bleu(refs, [hyps]).score
    return sentence_scores, corpus_score


import asyncio
import os

import discord
import youtube_dl
from discord.ext import commands
from pathlib import Path

from bot.music import Queue, Song

# 20 minutes, in seconds
DURATION_CEILING = 20 * 60

DURATION_CEILING_STRING = '20mins'

SONGS_PER_PAGE = 10

def set_str_len(s: str, length: int):
    '''Adds whitespace or trims string to enforce a specific size'''

    return s.ljust(length)[:length]

class Music(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        self.music_queues = {}
        self.voice_clients = {}

    @commands.command()
    async def play(self, ctx: commands.Context, url: str, *args: str):
        '''Adds a song to the queue either by YouTube URL or YouTube Search.'''

        music_queue = self.music_queues.get(ctx.guild, None)
        voice = self.voice_clients.get(ctx.guild)

        if music_queue is None:
            music_queue = Queue()
            self.music_queues[ctx.guild] = music_queue

        try:
            channel = ctx.message.author.voice.channel
        except:
            await ctx.send("You're not connected to a voice channel.")
            return

        if voice is not None and not self.client_in_same_channel(ctx.message.author, ctx.guild):
            await ctx.send("You're not in my voice channel.")
            return

        if not url.startswith('https://'):
            url = f'ytsearch1:{url} {" ".join(args)}'

        song = Song(url, ctx.author)
        valid_song, song_err = self.song_error_check(song)

        if not valid_song:
            await ctx.send(song_err)
            return

        if voice is None or not voice.is_connected():
            self.voice_clients[ctx.guild] = await channel.connect()

        music_queue.append(song)
        await ctx.send(f'Queued song: {song.title}')

        await self.play_all_songs(ctx.guild)

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def stop(self, ctx: commands.Context):
        '''Admin command that stops playback of music and clears out the music queue.'''

        voice = self.voice_clients.get(ctx.guild)
        queue = self.music_queues.get(ctx.guild)

        if self.client_in_same_channel(ctx.message.author, ctx.guild):
            voice.stop()
            queue.clear()
            self.voice_clients[ctx.guild] = None
            await ctx.send("Stopping playback")
            await voice.disconnect()
        else:
            await ctx.send("You're not in a voice channel with me.")

    @commands.command()
    async def skip(self, ctx: commands.Context):
        '''Puts in your vote to skip the currently played song.'''
        voice = self.voice_clients.get(ctx.guild)

        if not self.client_in_same_channel(ctx.message.author, ctx.guild):
            await ctx.send("You're not in a voice channel with me.")
        elif voice is None or not voice.is_playing():
            await ctx.send("I'm not playing a song right now.")
        else:
            voice.stop()

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def fskip(self, ctx: commands.Context):
        '''Admin command that forces skipping of the currently playing song.'''

        voice = self.voice_clients.get(ctx.guild)

        if not self.client_in_same_channel(ctx.message.author, ctx.guild):
            await ctx.send("You're not in a voice channel with me.")
        elif voice is None or not voice.is_playing():
            await ctx.send("I'm not playing a song right now.")
        else:
            voice.stop()

    @commands.command()
    async def songinfo(self, ctx: commands.Context, song_index: int = 0):
        '''Print out more information on the song currently playing.'''

        queue = self.music_queues.get(ctx.guild)

        if song_index not in range(len(queue)+1):
            await ctx.send("A song does not exist at that index in the queue.")
            return

        embed = queue.get_embed(song_index)
        await ctx.send(embed=embed)

    @commands.command()
    async def remove(self, ctx: commands.Context, song_id: int = None):
        '''Removes the last song you requested from the queue, or a specific song if queue position specified.'''

        if not self.client_in_same_channel(ctx.message.author, ctx.guild):
            await ctx.send("You're not in a voice channel with me.")
            return

        if song_id is None:
            queue = self.music_queues.get(ctx.guild)

            for index, song in reversed(list(enumerate(queue))):
                if ctx.author.id == song.requested_by_id:
                    queue.pop(index)
                    await ctx.send(f'Song "{song.title}" removed from queue.')
                    return
        else:
            queue = self.music_queues.get(ctx.guild)

            try:
                song = queue[song_id-1]
            except IndexError:
                await ctx.send('An invalid index was provided.')
                return

            if ctx.author.id == song.requested_by_id:
                queue.pop(song_id-1)
                await ctx.send(f'Song {song.title} removed from queue.')
            else:
                await ctx.send('You cannot remove a song requested by someone else.')

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def fremove(self, ctx: commands.Context, song_id: int = None):
        '''Admin command to forcibly remove a song from the queue by it's position.'''

        queue = self.music_queues.get(ctx.guild)

        if not self.client_in_same_channel(ctx.message.author, ctx.guild):
            await ctx.send('You\'re not in a voice channel with me.')
            return

        if song_id is None or 0:
            await ctx.send('You need to specify a song by it\'s queue index.')
            return

        try:
            song = queue[song_id-1]
        except IndexError:
            await ctx.send('A song does not exist at this queue index.')
            return

        queue.pop(song_id-1)
        await ctx.send(f'Removed {song.title} from the queue.')
        return

    @commands.command()
    async def queue(self, ctx: commands.Context, page: int = 1):
        '''Prints out a specified page of the music queue, defaults to first page.'''

        queue = self.music_queues.get(ctx.guild)

        if not self.client_in_same_channel(ctx.message.author, ctx.guild):
            await ctx.send('You\'re not in a voice channel with me.')
            return

        if not len(queue):
            await ctx.send('I don\'t have anything in my queue right now.')
            return

        if len(queue) < SONGS_PER_PAGE*(page-1):
            await ctx.send('I don\'t have that many pages in my queue.')
            return

        to_send = f'```\n    {set_str_len("Song", 66)}{set_str_len("Uploader", 36)}Requested By\n'

        for pos, song in enumerate(queue[:SONGS_PER_PAGE*page], start=SONGS_PER_PAGE*(page-1)):
            title = set_str_len(song.title, 65)
            uploader = set_str_len(song.uploader, 35)
            requested_by = song.requested_by_username
            to_send += f'{set_str_len(f"{pos+1})",4)}{title}|{uploader}|{requested_by}\n'

        await ctx.send(to_send + '```')

    async def play_all_songs(self, guild: discord.Guild):
        queue = self.music_queues.get(guild)

        # Play next song until queue is empty
        while len(queue) > 0:
            await self.wait_for_end_of_song(guild)

            song = queue.next_song()

            await self.play_song(guild, song)

        # Disconnect after song queue is empty
        await self.inactivity_disconnect(guild)

    async def play_song(self, guild: discord.Guild, song: Song):
        '''Downloads and starts playing a YouTube video's audio.'''

        audio_dir = os.path.join('.', 'audio')
        audio_path = os.path.join(audio_dir, f'{guild.id}.mp3')
        voice = self.voice_clients.get(guild)

        queue = self.music_queues.get(guild)
        ydl_opts = {
            'format': 'bestaudio/best',
            'noplaylist': True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
            'outtmpl': audio_path
        }

        Path(audio_dir).mkdir(parents=True, exist_ok=True)

        try:
            os.remove(audio_path)
        except OSError:
            pass

        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            try:
                ydl.download([f'{song.url}'])
            except:
                await self.play_all_songs(guild)
                print('Error downloading song. Skipping.')
                return

        voice.play(discord.FFmpegPCMAudio(audio_path))
        queue.clear_skip_votes()

    async def wait_for_end_of_song(self, guild: discord.Guild):
        voice = self.voice_clients.get(guild)
        while voice.is_playing():
            await asyncio.sleep(1)

    async def inactivity_disconnect(self, guild: discord.Guild):
        '''If a song is not played for 5 minutes, automatically disconnects bot from server.'''

        voice = self.voice_clients.get(guild)
        queue = self.music_queues.get(guild)
        last_song = queue.current_song

        await asyncio.sleep(300)
        if queue.current_song == last_song:
            await voice.disconnect()

    def client_in_same_channel(self, author: discord.Member, guild: discord.Guild):
        '''Checks to see if a client is in the same channel as the bot.'''

        voice = self.voice_clients.get(guild)

        try:
            channel = author.voice.channel
        except AttributeError:
            return False

        return voice is not None and voice.is_connected() and channel == voice.channel

    @staticmethod
    def song_error_check(song: Song):
        ''' Checks song properties to ensure that the song is both valid and doesn't match any filtered properties'''

        if song.url is None:
            return False, 'Invalid URL provided or no video found.'

        if song.get('is_live', True):
            return False, 'Invalid video - either live stream or unsupported website.'

        if song.duration_raw > DURATION_CEILING:
            return False, f'Video is too long. Keep it under {DURATION_CEILING_STRING}.'

        return True, None

def setup(bot):
    bot.add_cog(Music(bot))


"""
Implementation of "Attention is All You Need"
"""

import torch
import torch.nn as nn

from onmt.decoders.decoder import DecoderBase
from onmt.modules import MultiHeadedAttention, AverageAttention
from onmt.modules.position_ffn import PositionwiseFeedForward
from onmt.utils.misc import sequence_mask

class TransformerDecoderLayer(nn.Module):
    """
    Args:
      d_model (int): the dimension of keys/values/queries in
          :class:`MultiHeadedAttention`, also the input size of
          the first-layer of the :class:`PositionwiseFeedForward`.
      heads (int): the number of heads for MultiHeadedAttention.
      d_ff (int): the second-layer of the :class:`PositionwiseFeedForward`.
      dropout (float): dropout probability.
      self_attn_type (string): type of self-attention scaled-dot, average
    """

    def __init__(self, d_model, heads, d_ff, dropout, attention_dropout,
                 self_attn_type="scaled-dot", max_relative_positions=0,
                 aan_useffn=False, full_context_alignment=False,
                 alignment_heads=None):
        super(TransformerDecoderLayer, self).__init__()

        if self_attn_type == "scaled-dot":
            self.self_attn = MultiHeadedAttention(
                heads, d_model, dropout=dropout,
                max_relative_positions=max_relative_positions)
        elif self_attn_type == "average":
            self.self_attn = AverageAttention(d_model,
                                              dropout=attention_dropout,
                                              aan_useffn=aan_useffn)

        self.context_attn = MultiHeadedAttention(
            heads, d_model, dropout=attention_dropout)
        self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout)
        self.layer_norm_1 = nn.LayerNorm(d_model, eps=1e-6)
        self.layer_norm_2 = nn.LayerNorm(d_model, eps=1e-6)
        self.drop = nn.Dropout(dropout)
        self.full_context_alignment = full_context_alignment
        self.alignment_heads = alignment_heads

    def forward(self, *args, **kwargs):
        """ Extend _forward for (possibly) multiple decoder pass:
        1. Always a default (future masked) decoder forward pass,
        2. Possibly a second future aware decoder pass for joint learn
            full context alignement.

        Args:
            * All arguments of _forward.
            with_align (bool): whether return alignment attention.

        Returns:
            (FloatTensor, FloatTensor, FloatTensor or None):

            * output ``(batch_size, 1, model_dim)``
            * top_attn ``(batch_size, 1, src_len)``
            * attn_align ``(batch_size, 1, src_len)`` or None
        """
        with_align = kwargs.pop('with_align', False)
        output, attns = self._forward(*args, **kwargs)
        top_attn = attns[:, 0, :, :].contiguous()
        attn_align = None
        if with_align:
            if self.full_context_alignment:
                # return _, (B, Q_len, K_len)
                _, attns = self._forward(*args, **kwargs, future=True)

            if self.alignment_heads is not None:
                attns = attns[:, :self.alignment_heads, :, :].contiguous()
            # layer average attention across heads, get ``(B, Q, K)``
            # Case 1: no full_context, no align heads -> layer avg baseline
            # Case 2: no full_context, 1 align heads -> guided align
            # Case 3: full_context, 1 align heads -> full cte guided align
            attn_align = attns.mean(dim=1)
        return output, top_attn, attn_align

    def _forward(self, inputs, memory_bank, src_pad_mask, tgt_pad_mask,
                 layer_cache=None, step=None, future=False):
        """ A naive forward pass for transformer decoder.
        # TODO: change 1 to T as T could be 1 or tgt_len
        Args:
            inputs (FloatTensor): ``(batch_size, 1, model_dim)``
            memory_bank (FloatTensor): ``(batch_size, src_len, model_dim)``
            src_pad_mask (LongTensor): ``(batch_size, 1, src_len)``
            tgt_pad_mask (LongTensor): ``(batch_size, 1, 1)``

        Returns:
            (FloatTensor, FloatTensor):

            * output ``(batch_size, 1, model_dim)``
            * attns ``(batch_size, head, 1, src_len)``

        """
        dec_mask = None

        if step is None:
            tgt_len = tgt_pad_mask.size(-1)
            if not future:  # apply future_mask, result mask in (B, T, T)
                future_mask = torch.ones(
                    [tgt_len, tgt_len],
                    device=tgt_pad_mask.device,
                    dtype=torch.uint8)
                future_mask = future_mask.triu_(1).view(1, tgt_len, tgt_len)
                # BoolTensor was introduced in pytorch 1.2
                try:
                    future_mask = future_mask.bool()
                except AttributeError:
                    pass
                dec_mask = torch.gt(tgt_pad_mask + future_mask, 0)
            else:  # only mask padding, result mask in (B, 1, T)
                dec_mask = tgt_pad_mask

        input_norm = self.layer_norm_1(inputs)

        if isinstance(self.self_attn, MultiHeadedAttention):
            query, _ = self.self_attn(input_norm, input_norm, input_norm,
                                      mask=dec_mask,
                                      layer_cache=layer_cache,
                                      attn_type="self")
        elif isinstance(self.self_attn, AverageAttention):
            query, _ = self.self_attn(input_norm, mask=dec_mask,
                                      layer_cache=layer_cache, step=step)

        query = self.drop(query) + inputs

        query_norm = self.layer_norm_2(query)
        mid, attns = self.context_attn(memory_bank, memory_bank, query_norm,
                                       mask=src_pad_mask,
                                       layer_cache=layer_cache,
                                       attn_type="context")
        output = self.feed_forward(self.drop(mid) + query)

        return output, attns

    def update_dropout(self, dropout, attention_dropout):
        self.self_attn.update_dropout(attention_dropout)
        self.context_attn.update_dropout(attention_dropout)
        self.feed_forward.update_dropout(dropout)
        self.drop.p = dropout

class TransformerDecoder(DecoderBase):
    """The Transformer decoder from "Attention is All You Need".
    :cite:`DBLP:journals/corr/VaswaniSPUJGKP17`

    .. mermaid::

       graph BT
          A[input]
          B[multi-head self-attn]
          BB[multi-head src-attn]
          C[feed forward]
          O[output]
          A --> B
          B --> BB
          BB --> C
          C --> O

    Args:
       num_layers (int): number of encoder layers.
       d_model (int): size of the model
       heads (int): number of heads
       d_ff (int): size of the inner FF layer
       copy_attn (bool): if using a separate copy attention
       self_attn_type (str): type of self-attention scaled-dot, average
       dropout (float): dropout parameters
       embeddings (onmt.modules.Embeddings):
          embeddings to use, should have positional encodings
    """

    def __init__(self, num_layers, d_model, heads, d_ff,
                 copy_attn, self_attn_type, dropout, attention_dropout,
                 embeddings, max_relative_positions, aan_useffn,
                 full_context_alignment, alignment_layer,
                 alignment_heads=None):
        super(TransformerDecoder, self).__init__()

        self.embeddings = embeddings

        # Decoder State
        self.state = {}

        self.transformer_layers = nn.ModuleList(
            [TransformerDecoderLayer(d_model, heads, d_ff, dropout,
             attention_dropout, self_attn_type=self_attn_type,
             max_relative_positions=max_relative_positions,
             aan_useffn=aan_useffn,
             full_context_alignment=full_context_alignment,
             alignment_heads=alignment_heads)
             for i in range(num_layers)])

        # previously, there was a GlobalAttention module here for copy
        # attention. But it was never actually used -- the "copy" attention
        # just reuses the context attention.
        self._copy = copy_attn
        self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)

        self.alignment_layer = alignment_layer

    @classmethod
    def from_opt(cls, opt, embeddings):
        """Alternate constructor."""
        return cls(
            opt.dec_layers,
            opt.dec_rnn_size,
            opt.heads,
            opt.transformer_ff,
            opt.copy_attn,
            opt.self_attn_type,
            opt.dropout[0] if type(opt.dropout) is list else opt.dropout,
            opt.attention_dropout[0] if type(opt.attention_dropout)
            is list else opt.dropout,
            embeddings,
            opt.max_relative_positions,
            opt.aan_useffn,
            opt.full_context_alignment,
            opt.alignment_layer,
            alignment_heads=opt.alignment_heads)

    def init_state(self, src, memory_bank, enc_hidden):
        """Initialize decoder state."""
        self.state["src"] = src
        self.state["cache"] = None

    def map_state(self, fn):
        def _recursive_map(struct, batch_dim=0):
            for k, v in struct.items():
                if v is not None:
                    if isinstance(v, dict):
                        _recursive_map(v)
                    else:
                        struct[k] = fn(v, batch_dim)

        self.state["src"] = fn(self.state["src"], 1)
        if self.state["cache"] is not None:
            _recursive_map(self.state["cache"])

    def detach_state(self):
        self.state["src"] = self.state["src"].detach()

    def forward(self, tgt, memory_bank, step=None, **kwargs):
        """Decode, possibly stepwise."""
        if step == 0:
            self._init_cache(memory_bank)

        tgt_words = tgt[:, :, 0].transpose(0, 1)

        emb = self.embeddings(tgt, step=step)
        assert emb.dim() == 3  # len x batch x embedding_dim

        output = emb.transpose(0, 1).contiguous()
        src_memory_bank = memory_bank.transpose(0, 1).contiguous()

        pad_idx = self.embeddings.word_padding_idx
        src_lens = kwargs["memory_lengths"]
        src_max_len = self.state["src"].shape[0]
        src_pad_mask = ~sequence_mask(src_lens, src_max_len).unsqueeze(1)
        tgt_pad_mask = tgt_words.data.eq(pad_idx).unsqueeze(1)  # [B, 1, T_tgt]

        with_align = kwargs.pop('with_align', False)
        attn_aligns = []

        for i, layer in enumerate(self.transformer_layers):
            layer_cache = self.state["cache"]["layer_{}".format(i)] \
                if step is not None else None
            output, attn, attn_align = layer(
                output,
                src_memory_bank,
                src_pad_mask,
                tgt_pad_mask,
                layer_cache=layer_cache,
                step=step,
                with_align=with_align)
            if attn_align is not None:
                attn_aligns.append(attn_align)

        output = self.layer_norm(output)
        dec_outs = output.transpose(0, 1).contiguous()
        attn = attn.transpose(0, 1).contiguous()

        attns = {"std": attn}
        if self._copy:
            attns["copy"] = attn
        if with_align:
            attns["align"] = attn_aligns[self.alignment_layer]  # `(B, Q, K)`
            # attns["align"] = torch.stack(attn_aligns, 0).mean(0)  # All avg

        # TODO change the way attns is returned dict => list or tuple (onnx)
        return dec_outs, attns

    def _init_cache(self, memory_bank):
        self.state["cache"] = {}
        batch_size = memory_bank.size(1)
        depth = memory_bank.size(-1)

        for i, layer in enumerate(self.transformer_layers):
            layer_cache = {"memory_keys": None, "memory_values": None}
            if isinstance(layer.self_attn, AverageAttention):
                layer_cache["prev_g"] = torch.zeros((batch_size, 1, depth),
                                                    device=memory_bank.device)
            else:
                layer_cache["self_keys"] = None
                layer_cache["self_values"] = None
            self.state["cache"]["layer_{}".format(i)] = layer_cache

    def update_dropout(self, dropout, attention_dropout):
        self.embeddings.update_dropout(dropout)
        for layer in self.transformer_layers:
            layer.update_dropout(dropout, attention_dropout)


import math
# 에라토스테네스의 체: 특정한 수의 범위 안에 존재하는 모든 소수를 찾아야 할 때 사용
n = 1000    # 2부터 1,000까지의 모든 수에 대하여 소수 판별
array = [True for i in range(n+1)]   # 처음에는 모든 수가 소수인 것으로 초기화(True)

# 에레타소테네스의 체 알고리즘
for i in range(2, int(math.sqrt(n))+1):      # 2부터 n의 제곱근까지의 모든 수를 확인하며
    if array[i]:    # i가 소수인 경우 (남은 수 인 경우)
        # i를 제외한 i의 모든 배수를 지우기
        j = 2
        while i*j <= n:
            array[i*j] =  False
            j += 1

# 모든 소수 출력
for i in range(2, n+1):
    if array[i]:
        print(i, end = ' ')

에라토스테네스의체.py


def cf_dictionary_from_pairs(pairs):
        """
        Creates a CFDictionaryRef object from a list of 2-element tuples
        representing the key and value. Each key should be a CFStringRef and each
        value some sort of CF* type.

        :param pairs:
            A list of 2-element tuples

        :return:
            A CFDictionaryRef
        """

        length = len(pairs)
        keys = []
        values = []
        for pair in pairs:
            key, value = pair
            keys.append(key)
            values.append(value)
        keys = (CFStringRef * length)(*keys)
        values = (CFTypeRef * length)(*values)
        return CoreFoundation.CFDictionaryCreate(
            CoreFoundation.kCFAllocatorDefault,
            _cast_pointer_p(byref(keys)),
            _cast_pointer_p(byref(values)),
            length,
            kCFTypeDictionaryKeyCallBacks,
            kCFTypeDictionaryValueCallBacks
        )


import pandas as pd
import time
from selenium.webdriver import Chrome
from selenium import webdriver
import json
driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver")
browser = Chrome()
url = "https://www.instagram.com/"

def recent_posts(username):
    """With the input of an account page, scrape the 25 most recent posts urls"""
    url = "https://www.instagram.com/" + username + "/"
    browser = Chrome()
    browser.get(url)
    post = 'https://www.instagram.com/p/'
    post_links = []
    #xpath_comment = '//*[@id="react-root"]/section/main/div/header/section/ul/li[1]/a/span'
    #comment = browser.find_element_by_xpath(xpath_comment)
    #comment = comment.text
    #num_of_posts = int(comment)
    while len(post_links) < 150:
        links = [a.get_attribute('href') for a in browser.find_elements_by_tag_name('a')]
        for link in links:
            if post in link and link not in post_links:
                post_links.append(link)
        scroll_down = "window.scrollTo(0, document.body.scrollHeight);"
        browser.execute_script(scroll_down)
        time.sleep(10)
    else:
        return post_links

def insta_details(urls):
    """Take a post url and return post details"""
    browser = Chrome()
    post_details = []
    for link in urls:
        browser.get(link)
        xpath_comment = '//*[@id="react-root"]/section/main/div/div[1]/article/div[2]/div[1]/ul/div/li/div/div/div[2]/span'
        try:
            comment = browser.find_element_by_xpath(xpath_comment)
            comment = comment.text
            post_details.append(comment)
        except:
            continue

        time.sleep(10)
    return post_details

posts = insta_details(recent_posts('username'))
print(posts)
with open("username.json", "w") as write_file:
    json.dump(posts, write_file)


import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
import pdb

__all__ = [
    'Mlp',
    'Attention',
    'TransformerBlock',
    'LayerNorm',
]

class Mlp(nn.Module):
    def __init__(self, in_dim, hid_dim=None, out_dim=None, act=nn.GELU, drop=0.):
        super().__init__()
        out_dim = out_dim or in_dim
        hid_dim = hid_dim or in_dim
        self.fc1 = nn.Linear(in_dim, hid_dim)
        self.act = act()
        self.fc2 = nn.Linear(hid_dim, out_dim)
        self.drop = nn.Dropout(drop)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.drop(x)

        return x

class PreNorm(nn.Module):
    def __init__(self, dim, fn):
        super().__init__()
        self.norm = nn.LayerNorm(dim)
        self.fn = fn
    def forward(self, x, **kwargs):
        return self.fn(self.norm(x), **kwargs)

class Attention(nn.Module):
    def __init__(self, dim, heads, dim_head, attn_drop=0., proj_drop=0.):
        super().__init__()

        inner_dim = dim_head * heads

        self.heads = heads
        self.scale = dim_head ** -0.5

        self.to_qkv = nn.Linear(dim, inner_dim*3, bias=False)

        self.to_out = nn.Linear(inner_dim, dim)

        self.proj_drop = nn.Dropout(proj_drop)

    def rearrange1(self, x, heads):
        # rearrange is not supported by pytorch2.0 torch.compile
        # 'b l (heads dim_head) -> b heads l dim_head'
        b, l, n = x.shape
        dim_head = int(n / heads)
        x = x.view(b, l, heads, dim_head).contiguous()
        x = x.permute(0, 2, 1, 3).contiguous()

        return x

    def rearrange2(self, x):
         # 'b heads l dim_head -> b l (dim_head heads)')
         b, heads, l, dim_head = x.shape
         x = x.permute(0, 2, 1, 3).contiguous()
         x = x.view(b, l, -1).contiguous()

         return x

    def forward(self, x):
        # x: B, L, C.   Batch, sequence length, dim
        # 'b l (heads dim_head) -> b heads l dim_head',
        q, k, v = self.to_qkv(x).chunk(3, dim=-1)

        #q, k, v = map(lambda t: rearrange(t, 'b l (heads dim_head) -> b heads l dim_head', heads=self.heads), [q, k, v])
        q, k, v = map(lambda t: self.rearrange1(t, heads=self.heads), [q, k, v])

        attn = torch.einsum('bhid,bhjd->bhij', q, k) * self.scale

        attn = F.softmax(attn, dim=-1)

        attned = torch.einsum('bhij,bhjd->bhid', attn, v)
        #attned = rearrange(attned, 'b heads l dim_head -> b l (dim_head heads)')
        attned = self.rearrange2(attned)

        attned = self.to_out(attned)

        return attned

class TransformerBlock(nn.Module):
    def __init__(self, dim, depth, heads, dim_head, mlp_dim, attn_drop=0., proj_drop=0.):
        super().__init__()

        self.layers = nn.ModuleList([])

        for i in range(depth):
            self.layers.append(nn.ModuleList([
                PreNorm(dim, Attention(dim, heads, dim_head, attn_drop, proj_drop)),
                PreNorm(dim, Mlp(dim, mlp_dim, dim, drop=proj_drop))
                ]))
    def forward(self, x):

        for attn, ffn in self.layers:
            x = attn(x) + x
            x = ffn(x) + x

        return x

class LayerNorm(nn.Module):
    r""" LayerNorm that supports two data formats: channels_last (default) or channels_first.
    The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
    shape (batch_size, height, width, channels) while channels_first corresponds to inputs
    with shape (batch_size, channels, height, width).
    """

    def __init__(self, normalized_shape, eps=1e-5, data_format="channels_first"):
        super().__init__()

        self.weight = nn.Parameter(torch.ones(normalized_shape))
        self.bias = nn.Parameter(torch.zeros(normalized_shape))
        self.eps = eps
        self.data_format = data_format

        if self.data_format not in ["channels_last", "channels_first"]:
            raise NotImplementedError
        self.normalized_shape = (normalized_shape, )

    def forward(self, x):

        if self.data_format == "channels_last":
            return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)

        elif self.data_format == "channels_first":
            u = x.mean(1, keepdim=True)
            s = (x - u).pow(2).mean(1, keepdim=True)
            x = (x - u) / torch.sqrt(s + self.eps)
            x = self.weight[None, :, None, None, None] * x + self.bias[None, :, None, None, None]
            return x


import uuid
from unittest.mock import MagicMock

from django.urls import reverse_lazy

from rest_framework.test import APIClient

from libs.testing.constants import OK

def get_url():
    """Get url for `getting setup intent`."""
    return reverse_lazy('v1:subscribe-get-setup-intent')

def test_get_setup_intent(api_client: APIClient, mocker):
    """Test `get_setup_intent` API method."""
    expected_secret = str(uuid.uuid4())
    mocker.patch(
        'djstripe.models.SetupIntent._api_create',
        return_value=MagicMock(client_secret=expected_secret)
    )

    url = get_url()
    response = api_client.get(url)

    assert response.status_code == OK
    assert response.data['client_secret'] == expected_secret


# Helper function to find the length of the cycle
def find_cycle_length(slow):
  # Find the length of the cycle
  start = slow
  current = slow.next
  cycle_length = 1
  while current != start:
    current = current.next
    cycle_length += 1
  return cycle_length

# Function to check if a linked list contains a cycle
def contains_cycle(head):
  # Handle the case of an empty linked list
  if head == None:
    return False

  # Initialize the "hare" and "tortoise" pointers
  hare = head
  tortoise = head

  # Loop until the hare catches up to the tortoise or the linked list ends
  while hare != None and hare.next != None:
    hare = hare.next.next
    tortoise = tortoise.next

    # If the hare and tortoise meet, there is a cycle
    if hare == tortoise:
      # Find the length of the cycle
      cycle_length = find_cycle_length(tortoise)

      # Return True to indicate that a cycle was found
      return True

  # If the hare reaches the end of the linked list, there is no cycle
  return False

def find_center(lst):
	if (lst == None): return None
	slowpointer = lst # still the first node
	fastpointer = lst # still the first node

	while(fastpointer != None):
		fastpointer = fastpointer.next
		if(fastpointer != None):
			fastpointer.next
			slowpointer.next
	return slowpointer

def detectCycle(list):
	if list == None: return False
	slowpointer = list
	fastpointer = list

	while(fastpointer != None):
		fastpointer = fastpointer.next.next
		slowpointer = slowpointer.next
		if fastpointer == slowpointer: return True
	return False


from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Base, Pokemon, Stat, Move, User

engine = create_engine('sqlite:///pokemon.db')
Base.metadata.create_all(bind=engine)

Session = sessionmaker(bind=engine)
session = Session()

session.query(Pokemon).delete()
session.query(Move).delete()
session.query(Stat).delete()
session.query(User).delete()

p1 = Pokemon(name='Bulbasaur', type='Grass')
p1.moves = [Move(name='Vine Whip'), Move(name='Razor Leaf'), Move(name='Tackle'), Move(name='Leech Seed')]
p1.stats = [Stat(name='ATTACK', value=2), Stat(name='DEFENSE', value=4)]

p2= Pokemon(name='Squirtle', type='Water')
p2.moves = [Move(name='Bubblebeam'), Move(name='Tackle'), Move(name='Headbutt'), Move(name='Surf')]
p2.stats = [Stat(name='ATTACK', value=3), Stat(name='DEFENSE', value=3)]

p3 = Pokemon(name='Charmander', type='Fire')
p3.moves = [Move(name='Ember'), Move(name='Scratch'), Move(name='Tackle'), Move(name='Fire Punch')]
p3.stats = [Stat(name='ATTACK', value=4), Stat(name='DEFENSE', value=2)]

# p4 = Pokemon(name='Pikachu', type='Electric')
# p4.moves = [Move(name='Thunderbolt'), Move(name='Quick Attack'), Move(name='Iron Tail'), Move(name='Volt Tackle')]
# p4.stats = [Stat(name='ATTACK', value=4), Stat(name='DEFENSE', value=4)]

p5 = Pokemon(name='Chikorita', type='Grass')
p5.moves = [Move(name='Vine Whip'), Move(name='Tackle'), Move(name='Grass Knot'), Move(name='Energy Ball')]
p5.stats = [Stat(name='ATTACK', value=2), Stat(name='DEFENSE', value=4)]

p6 = Pokemon(name='Totodile', type='Water')
p6.moves = [Move(name='Scratch'), Move(name='Water Gun'), Move(name='Aqua Jet'), Move(name='Crunch')]
p6.stats = [Stat(name='ATTACK', value=3), Stat(name='DEFENSE', value=3)]

p7 = Pokemon(name='Cyndaquil', type='Fire')
p7.moves = [Move(name='Ember'), Move(name='Tackle'), Move(name='Flamethrower'), Move(name='Flame Charge')]
p7.stats = [Stat(name='ATTACK', value=5), Stat(name='DEFENSE', value=1)]

p8 = Pokemon(name='Treecko', type='Grass')
p8.moves = [Move(name='Pound'), Move(name='Bullet Seed'), Move(name='Aerial Ace'), Move(name='Grass Knot')]
p8.stats = [Stat(name='ATTACK', value=3), Stat(name='DEFENSE', value=3)]

p9 = Pokemon(name='Torchic', type='Fire')
p9.moves = [Move(name='Ember'), Move(name='Scratch'), Move(name='Flame Charge'), Move(name='Flamethrower')]
p9.stats = [Stat(name='ATTACK', value=4), Stat(name='DEFENSE', value=2)]

p10 = Pokemon(name='Mudkip', type='Water')
p10.moves = [Move(name='Tackle'), Move(name='Water Gun'), Move(name='Sludge'), Move(name='Dig')]
p10.stats = [Stat(name='ATTACK', value=3), Stat(name='DEFENSE', value=3)]

p11 = Pokemon(name='Turtwig', type='Grass')
p11.moves = [Move(name='Razor Leaf'), Move(name='Tackle'), Move(name='Seed Bomb'), Move(name='Body Slam')]
p11.stats = [Stat(name='ATTACK', value=3), Stat(name='DEFENSE', value=3)]

p12 = Pokemon(name='Piplup', type='Water')
p12.moves = [Move(name='Pound'), Move(name='Bubble'), Move(name='Drill Peck'), Move(name='Icy Wind')]
p12.stats = [Stat(name='ATTACK', value=2), Stat(name='DEFENSE', value=4)]

p13 = Pokemon(name='Chimchar', type='Fire')
p13.moves = [Move(name='Ember'), Move(name='Scratch'), Move(name='Flame Wheel'), Move(name='Flame Charge')]
p13.stats = [Stat(name='ATTACK', value=5), Stat(name='DEFENSE', value=1)]

p14 = Pokemon(name='Snivy', type='Grass')
p14.moves = [Move(name='Vine Whip'), Move(name='Tackle'), Move(name='Wrap'), Move(name='Seed Bomb')]
p14.stats = [Stat(name='ATTACK', value=3), Stat(name='DEFENSE', value=3)]

p15 = Pokemon(name='Oshawott', type='Water')
p15.moves = [Move(name='Tackle'), Move(name='Water Gun'), Move(name='Night Slash'), Move(name='Aqua Tail')]
p15.stats = [Stat(name='ATTACK', value=2), Stat(name='DEFENSE', value=4)]

p16 = Pokemon(name='Tepig', type='Fire')
p16.moves = [Move(name='Ember'), Move(name='Tackle'), Move(name='Flamethrower'), Move(name='Body Slam')]
p16.stats = [Stat(name='ATTACK', value=4), Stat(name='DEFENSE', value=2)]

p17 = Pokemon(name='Chespin', type='Grass')
p17.moves = [Move(name='Vine Whip'), Move(name='Take Down'), Move(name='Seed Bomb'), Move(name='Gyro Ball')]
p17.stats = [Stat(name='ATTACK', value=2), Stat(name='DEFENSE', value=4)]

p18 = Pokemon(name='Froakie', type='Water')
p18.moves = [Move(name='Pound'), Move(name='Bubble'), Move(name='Water Pulse'), Move(name='Surf')]
p18.stats = [Stat(name='ATTACK', value=3), Stat(name='DEFENSE', value=3)]

p19 = Pokemon(name='Fennekin', type='Fire')
p19.moves = [Move(name='Ember'), Move(name='Scratch'), Move(name='Flamethrower'), Move(name='Flame Charge')]
p19.stats = [Stat(name='ATTACK', value=4), Stat(name='DEFENSE', value=2)]

p20 = Pokemon(name='Rowlet', type='Grass')
p20.moves = [Move(name='Razor Leaf'), Move(name='Tackle'), Move(name='Seed Bomb'), Move(name='Energy Ball')]
p20.stats = [Stat(name='ATTACK', value=1), Stat(name='DEFENSE', value=5)]

p21 = Pokemon(name='Popplio', type='Water')
p21.moves = [Move(name='Pound'), Move(name='Water Gun'), Move(name='Aqua Jet'), Move(name='Water Pulse')]
p21.stats = [Stat(name='ATTACK', value=3), Stat(name='DEFENSE', value=3)]

p22 = Pokemon(name='Litten', type='Fire')
p22.moves = [Move(name='Ember'), Move(name='Scratch'), Move(name='Flamethrower'), Move(name='Flame Charge')]
p22.stats = [Stat(name='ATTACK', value=4), Stat(name='DEFENSE', value=2)]

u1 = User("1234")
u2 = User("5678")

session.add_all([u1, u2])
session.add_all([p1,p2,p3,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,p21,p22])
session.commit()


"""
数字 n 代表生成括号的对数，请你设计一个函数，用于能够生成所有可能的并且 有效的 括号组合。

示例 1：

输入：n = 3
输出：["((()))","(()())","(())()","()(())","()()()"]
示例 2：

输入：n = 1
输出：["()"]

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""

class Solution:
    def generateParenthesis(self, n: int) -> [str]:
        if n == 0:
            return [""]
        elif n == 1:
            return ["()"]
        elif n == 2:
            return ["()()", "(())"]
        result = []
        for i in range(n):
            j = n - 1 - i
            temp1 = self.generateParenthesis(i)
            temp2 = self.generateParenthesis(j)
            result.extend(["(%s)%s" % (p, q) for p in temp1 for q in temp2])
        return result

if __name__ == "__main__":
    print(Solution().generateParenthesis(3))
    print(Solution().generateParenthesis(4))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('store', '0005_items_cloud_d_it_id'),
    ]

    operations = [
        migrations.RenameField(
            model_name='cloud_users',
            old_name='cloud_users',
            new_name='cloud_user',
        ),
        migrations.AddField(
            model_name='cloud_users',
            name='pk_cu',
            field=models.IntegerField(default=0, max_length=11),
            preserve_default=False,
        ),
    ]


from django.contrib.auth.models import User
from django import forms

from torch.idea.models import Idea

def make_IdeaForm(user):

    class IdeaForm(forms.ModelForm):
        title = forms.CharField(
            label='What do you want to call your idea?',
            required=True,
            max_length=200,
            widget=forms.TextInput(attrs={
                'placeholder': 'I think it would be a good idea if Elkhart...',
                'class': 'input-xxlarge title-input',
                'type': 'text',
            }),
        )
        description = forms.CharField(
            required=True,
            label='Why should people like your idea?',
            widget=forms.Textarea(attrs={
                'placeholder': 'The reason we should do this is...',
                'class': 'input-xxlarge description-input',
                'type': 'text',
                'rows': '2',
            }),
        )

        def clean(self, *args, **kwargs):
            result = super(IdeaForm, self).clean(*args, **kwargs)
            if not isinstance(user, User):
                raise forms.ValidationError('This field is required.')
            return result

        def save(self, *args, **kwargs):
            self.instance.author = user
            return super(IdeaForm, self).save(*args, **kwargs)

        class Meta:
            model = Idea
            exclude = ('author')
    return IdeaForm


# Calculates the smallest integer that can be the length of a cathetus of exactly 47,547 different integer sided right-angled triangles

from functools import reduce
import operator

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return factors

max = 50
primes = []
sieve = [True] * max
for i in range(2, max):
	if sieve[i]:
		primes.append(i)
		for j in range(i * i, max, i):
			sieve[j] = False

n = 47547
P = prime_factors(2*n+1)[::-1]
print(reduce(operator.mul,[primes[P.index(p)]**((p-1)//2) for p in P[1:]],2**((P[0]+1)//2)))


import rdflib
import urllib.request
import ssl
from SPARQLWrapper import SPARQLWrapper, JSON

sparql = SPARQLWrapper("http://192.168.31.230:7200/repositories/0531-0610")

query = """
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX yourNamespace: <yourNamespaceURI>

SELECT ?property ?value
WHERE {
  ?subject ?property ?value .
}
"""

# Set the SPARQL query and return format
sparql.setQuery(query)
sparql.setReturnFormat(JSON)

# Execute the SPARQL query
results = sparql.query().convert()

# Process the query results
for result in results["results"]["bindings"]:
    property_name = result["property"]["value"]
    value = result["value"]["value"]
    print(f"Property: {property_name} | Value: {value}")


import webbrowser, sys, pyperclip

sys.argv # ['mapit.py','Rua do Conde de Redondo','91B', '1150-103 Lisboa', 'Portugal']

# Check if command Line argurments were passed
if len(sys.argv) > 1:
    # ['mapit.py','Rua do Conde de Redondo','91B', '1150-103 Lisboa', 'Portugal']
    address = ' '.join(sys.argv[1:])
else:
    address = pyperclip.paste()

# https://www.google.fr/maps/place/Le+Wagon+Lisbon+Coding+Bootcamp/@38.7260907,-9.1476757,17z/data=!3m1!4b1!4m5!3m4!1s0xd19351a74f8e2a3:0x779f5b9fe8faf6a7!8m2!3d38.7260865!4d-9.145487
webbrowser.open('https://www.google.fr/maps/place/' + address)

Automate The Boring Stuff/section12/mapit.py


import os

import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import pearsonr

from decoders import get_R2
from main import Evaluation

result_path = './results/'
kin_file = 'indy_20170124_01_kin_test.npy'
kin_pred_file = 'indy_20170124_01_kin_pred.npy'
decoder = ['Linear', 'KF', 'DNN', 'LSTM']

n_motion = 6

kin = []
kin_pred = []

kin.append(np.load(result_path + decoder[0] + '/' + kin_file))
kin.append(np.load(result_path + decoder[1] + '/' + kin_file))
kin.append(np.load(result_path + decoder[2] + '/' + kin_file))
kin.append(np.load(result_path + decoder[3] + '/' + kin_file))

kin_pred.append(np.load(result_path + 'Linear/' + kin_pred_file))
kin_pred.append(np.load(result_path + 'KF/' + kin_pred_file))
kin_pred.append(np.load(result_path + 'DNN/' + kin_pred_file))
kin_pred.append(np.load(result_path + 'LSTM/' + kin_pred_file))

all_cc = np.zeros((len(kin), n_motion))
all_r2 = np.zeros(all_cc.shape)

for i in range(len(kin)):
    r2 = get_R2(kin[i], kin_pred[i])
    for MoBin in range(n_motion):
        all_r2[i, MoBin] = r2[MoBin]

        r, p = pearsonr(kin[i][:, MoBin], kin_pred[i][:, MoBin])
        all_cc[i, MoBin] = r

# # Plot all cc
# Evaluation(result_path, all_cc, decoder)
# np.save(os.path.join(result_path, 'all_cc.npy'), all_cc)

# Plot all r2
a = 0.7
colors = ['C' + str(i) for i in range(len(kin))]
x = range(len(kin))

plt.figure(figsize=(12, 8))
plt.subplot(2, 3, 1)
plt.bar(x, all_r2[:, 0], alpha=a, color=colors)
plt.xlabel('x_pos')
plt.ylabel('R^2')

plt.subplot(2, 3, 2)
plt.bar(x, all_r2[:, 2], alpha=a, color=colors)
# for i in range(len(kin)):
#     plt.bar(x[i], all_r2[i, 2], alpha=a, color=colors[i], label=decoder[i])
plt.xlabel('x_vel')

plt.subplot(2, 3, 3)
# plt.bar(x, all_r2[:, 4], alpha=a, color=colors)
for i in range(len(kin)):
    plt.bar(x[i], all_r2[i, 4], alpha=a, color=colors[i], label=decoder[i])
plt.xlabel('x_acc')
plt.legend()

plt.subplot(2, 3, 4)
plt.bar(x, all_r2[:, 1], alpha=a, color=colors)
plt.xlabel('y_pos')

plt.subplot(2, 3, 5)
plt.bar(x, all_r2[:, 3], alpha=a, color=colors)
plt.xlabel('y_vel')

plt.subplot(2, 3, 6)
plt.bar(x, all_r2[:, 5], alpha=a, color=colors)
plt.xlabel('y_acc')

plt.savefig(result_path + '/all_r2.png', dpi=600)
plt.show()
np.save(os.path.join(result_path, 'all_r2.npy'), all_r2)


import pandas as pd
import numpy as np
import multiprocessing as mp

def getTaggedPoints(csv_path, additional_params=[]):
    df = pd.read_csv(csv_path)
    tagged_points = []
    lat_key, lng_key, id_key = '', '', ''
    for key in list(df):
        key_lower = key.lower()
        if lat_key == '':
            if 'lat' in key_lower or key_lower == 'latitude' or 'features__geometry__coordinates__002' in key_lower or key_lower == 'x':
                lat_key = key
        if lng_key == '':
            if 'lon' in key_lower or key_lower == 'longitude' or 'features__geometry__coordinates__001' in key_lower or key_lower == 'y':
                lng_key = key
        if id_key == '':
            if 'id' in key_lower[-2:] or ' id' in key_lower:
                id_key = key
        else:
            pass

    for i in range(len(df)):
        # Appends a tuple of (id, (lat, lng)) to the list of points
        tagged_point = ()
        if np.isnan(df[lat_key][i]) or np.isnan(df[lng_key][i]):
            tagged_point += ((0.0, 0.0), "no data", )
        else:
            coors = (df[lat_key][i], df[lng_key][i])
            if id_key == '':
               id = str(i)
            else:
               id = str(df[id_key][i])
            tagged_point += (coors, id, )
            if additional_params != []:
                for param in additional_params:
                    if df[param][i] == 'nan':
                        tagged_point += ("no data", )
                    else:
                        tagged_point += (df[param][i], )
        tagged_points.append( tagged_point )

    return tagged_points

def makeUpdatedCsv(data, column_names, infile, outfile):
    df = pd.read_csv(infile)
    i = 0
    while i < len(column_names):
        col_name = column_names[i]
        column_data = []
        for j in range(len(data)):
            column_data.append(data[j][i])
        df[col_name] = column_data
        i += 1
    df.to_csv(outfile)


def write(
        self,
        mi_cmd_to_write,
        timeout_sec=DEFAULT_GDB_TIMEOUT_SEC,
        raise_error_on_timeout=True,
        read_response=True,
    ):
        """Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec.

        Args:
            mi_cmd_to_write (str or list): String to write to gdb. If list, it is joined by newlines.
            timeout_sec (float): Maximum number of seconds to wait for response before exiting. Must be >= 0.
            raise_error_on_timeout (bool): If read_response is True, raise error if no response is received
            read_response (bool): Block and read response. If there is a separate thread running,
            this can be false, and the reading thread read the output.
        Returns:
            List of parsed gdb responses if read_response is True, otherwise []
        Raises:
            NoGdbProcessError if there is no gdb subprocess running
            TypeError if mi_cmd_to_write is not valid
        """
        self.verify_valid_gdb_subprocess()
        if timeout_sec < 0:
            self.logger.warning("timeout_sec was negative, replacing with 0")
            timeout_sec = 0

        # Ensure proper type of the mi command
        if type(mi_cmd_to_write) in [str, unicode]:
            pass
        elif type(mi_cmd_to_write) == list:
            mi_cmd_to_write = "\n".join(mi_cmd_to_write)
        else:
            raise TypeError(
                "The gdb mi command must a be str or list. Got "
                + str(type(mi_cmd_to_write))
            )

        self.logger.debug("writing: %s", mi_cmd_to_write)

        if not mi_cmd_to_write.endswith("\n"):
            mi_cmd_to_write_nl = mi_cmd_to_write + "\n"
        else:
            mi_cmd_to_write_nl = mi_cmd_to_write

        if USING_WINDOWS:
            # select not implemented in windows for pipes
            # assume it's always ready
            outputready = [self.stdin_fileno]
        else:
            _, outputready, _ = select.select([], self.write_list, [], timeout_sec)
        for fileno in outputready:
            if fileno == self.stdin_fileno:
                # ready to write
                self.gdb_process.stdin.write(mi_cmd_to_write_nl.encode())
                # don't forget to flush for Python3, otherwise gdb won't realize there is data
                # to evaluate, and we won't get a response
                self.gdb_process.stdin.flush()
            else:
                self.logger.error("got unexpected fileno %d" % fileno)

        if read_response is True:
            return self.get_gdb_response(
                timeout_sec=timeout_sec, raise_error_on_timeout=raise_error_on_timeout
            )

        else:
            return []


import os.path
import pickle
import socket
from pathlib import Path
from googleapiclient.discovery import build

from server.settings import default_scopes, default_service_files_path
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow

class GMailService:
    def __init__(self, files_path, scopes=None, force_reset=False, save_things=True):
        self.files_path = Path(files_path)

        self.service_creds_path = str(self.files_path / "credentials.json")
        self.token_path = str(self.files_path / "token.pickle")
        self.service_path = str(self.files_path / "service.pickle")

        self.scopes = scopes
        self.force_reset = force_reset
        self.save_things = save_things

        self._create()

    def _create(self):
        """Gets token and returns service for it."""
        creds = self._get_token()
        service = self._build_service(creds)

        return service

    def _get_token(self):
        if self._check_token_ready() and not self.force_reset:
            token_creds = self._load_token()
        else:
            token_creds = self._create_token()

        return token_creds

    def _check_token_ready(self, ):
        if os.path.isfile(self.token_path):
            token = self._load_token()
            token_refreshable = not token.expired or token.expred and token.refresh_token
            if token.valid and token_refreshable:
                return True

        else:
            return False

    def _load_token(self, ):
        token_creds = self._pickle_load(self.token_path)

        if token_creds.expired and token_creds.refresh_token:
            token_creds.refresh(Request())

        return token_creds

    def _create_token(self):
        assert self.scopes is not None, \
            "if new token is created, you should provide scopes for it in ServiceCreator init."

        flow = InstalledAppFlow.from_client_secrets_file(self.service_creds_path, self.scopes)
        token_creds = flow.run_local_server(port=0)

        if self.save_things:
            self._pickle_save(token_creds, self.token_path)

        return token_creds

    def _pickle_save(self, obj, path):
        with open(path, "wb") as file:
            pickle.dump(obj, file)

    def _pickle_load(self, path):
        with open(path, "rb") as file:
            obj = pickle.load(file)

        return obj

    def _build_service(self, token_creds):
        socket.setdefaulttimeout(1000)  # fixing problem with socket.timeout during build

        if os.path.isfile(self.service_path) and not self.force_reset:
            service = self._pickle_load(self.service_path)
        else:
            service = self._create_service(token_creds)

        return service

    def _create_service(self, token_creds):
        service = build('gmail', 'v1', credentials=token_creds)

        if self.save_things:
            self._pickle_save(service, self.service_path)

        return service

def get_default_gmail_service():
    default_service_creator = GMailService(default_service_files_path, default_scopes)
    return default_service_creator

if __name__ == "__main__":
    service = get_default_gmail_service()
    print(service)
    gmail_users = service.users()
    print(gmail_users)
    users_labels = gmail_users.labels()
    results = users_labels.list(userId='me').execute()

    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])