import time
import sys
import threading

from neopixel import NeoPixel
from .tools import cmath

from .animations import *

class AnimatorController():
    def __init__(self,
                pixels: NeoPixel,
                animation: str = "sunrise",
                update_rate: int = 60):

        super(AnimatorController, self)
        self._stop = threading.Event()

        self._pixels = pixels

        self.FPS = update_rate

        self._update_time = (1.0/update_rate)
        self._running = False
        self._animation = self.__get_animation(animation)
        self._interlace = False

        self._thread = threading.Thread(target=self.__update)
        self._thread.daemon = True

        self._thread.setName("Update pixels Cycle")

    def run(self):
        """ Start the animator controller routine"""
        try:
            self._running = True
            self._thread.start()
        except (KeyboardInterrupt, SystemExit):
            print ('\n! Received keyboard interrupt, quitting threads.\n')

    def stop(self):
        """ Stop the animator controller routine"""
        self._running = False
        self._thread.join()

    def __update(self):
        """ Update the state of animation and draw it into pixels"""

        self._animation.start()
        while self._running:
            if not self._animation.loop and self._animation.done:
                self.stop()
                break

            # Starting the execution cycle
            start_cycle_time = time.process_time()

            delta_time = 1.0 / self.FPS
            self._animation.update(delta_time)
            self._pixels.show()

            # Ending the execution cycle
            end_cycle_time = time.process_time()

            cycle_time = (end_cycle_time - start_cycle_time)
            self.__calc_FPS(cycle_time + self.__wait_next_update(cycle_time))
            self.__print_FPS()

    def __wait_next_update(self, cycle_time):
        """
        Wait for next update cycle if the executation cycle was executed quicker
        than refresh rate
        """
        waitTime = cmath.clamp(self._update_time - cycle_time)

        if(waitTime > 0):
            time.sleep(waitTime)

        return waitTime

    def __calc_FPS(self, cycle_time):
        """ Calculate the 'Frames' per second """
        self.FPS = int(1.0/cycle_time)

    def __print_FPS(self):
        """ Print the FPS in console """
        sys.stdout.write(f"\rFPS: {self.FPS}")
        sys.stdout.flush()

    def __get_animation(self, animation: str):
        animations_list = {
            "fire"          : FireAnimation(self._pixels),
            "fade"          : FadeAnimation(self._pixels),
            "pingpong"      : PingPongAnimation(self._pixels),
            "test"          : TestColorsAnimation(self._pixels),
            "rainbow"       : RainbowPerlinAnimation(self._pixels),
            "rainbowwheel"  : RainbowWheelAnimation(self._pixels),
            "sunrise"       : SunriseAnimation(self._pixels)
        }

        return animations_list[str.lower(animation)]


from sqlalchemy import Column, Integer, String, Text, DateTime, Float, Boolean, PickleType, Boolean
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class ProjectKey(Base):
    '''This is Project Keys sample Data model class.'''

    __tablename__ = "tProjectKeys"
    __table_args__ = {"schema":"KnowHow.dbo"}

    id = Column(Integer, primary_key=True, nullable=False)
    webKey = Column(Text, nullable=False)
    mobileKey = Column(Text, nullable=True)
    projectID = Column(Integer, nullable=True)
    createdBy = Column(Integer, nullable=True)
    createdOn = Column(DateTime, nullable=True)
    modifiedBy = Column(Integer, nullable=True)
    modifiedOn = Column(DateTime, nullable=True)
    isActive = Column(Boolean, nullable=True)

    def __repr__(self):
        return '<Project model {}>'.format(self.id)


#!/usr/bin/env python

import os
import sys
import json
import re

sys.path.append(os.path.join(os.environ['REPO_DIR'], 'utilities'))
from metadata import *
from utilities2015 import *

import argparse

parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description='Align consecutive images. Possible bad alignment pairs are written into a separate file.')

parser.add_argument("output_dir", type=str, help="output dir. Files for each pairwise transform are stored in sub-folder <currImageName>_to_<prevImageName>.")
parser.add_argument("kwargs_str", type=str, help="json-encoded list of dict (keyworded inputs). Each dict entry has four keys: prev_fp (previous image file path), curr_fp (current image file path).")
parser.add_argument("-p", "--param_fp", type=str, help="elastix parameter file path", default=None)
parser.add_argument("-r", help="re-generate even if already exists", action='store_true')

args = parser.parse_args()

output_dir = args.output_dir
kwargs_str = json.loads(args.kwargs_str)
param_fp = args.param_fp
regenerate = args.r

if param_fp is None:
    param_fp = os.path.join(os.environ['REPO_DIR'], 'preprocess', 'parameters', "Parameters_Rigid_MutualInfo.txt")

failed_pairs = []

for kwarg in kwargs_str:

    prev_img_name = kwarg['prev_img_name']
    curr_img_name = kwarg['curr_img_name']
    prev_fp = kwarg['prev_fp']
    curr_fp = kwarg['curr_fp']

    output_subdir = os.path.join(output_dir, curr_img_name + '_to_' + prev_img_name)

    if os.path.exists(output_subdir) and 'TransformParameters.0.txt' in os.listdir(output_subdir):
        sys.stderr.write('Result for aligning %s to %s already exists.\n' % (curr_img_name, prev_img_name))
        if not regenerate:
            sys.stderr.write('Skip.\n' % (curr_img_name, prev_img_name))
            continue

    execute_command('rm -rf \"%s\"' % output_subdir)
    create_if_not_exists(output_subdir)

    ret = execute_command('%(elastix_bin)s -f \"%(fixed_fp)s\" -m \"%(moving_fp)s\" -out \"%(output_subdir)s\" -p \"%(param_fp)s\"' % \
            {'elastix_bin': ELASTIX_BIN,
            'param_fp': param_fp,
            'output_subdir': output_subdir,
            'fixed_fp': prev_fp,
            'moving_fp': curr_fp
            })

    if ret == 1:
        failed_pairs.append((prev_img_name, curr_img_name))
    else:
        with open(os.path.join(output_subdir, 'elastix.log'), 'r') as f:
            t = f.read()
            g = re.search("Final metric value  = (.*?)\n", t)
            assert g is not None
            metric = float(g.groups()[0])
            sys.stderr.write("Metric = %.2f\n" % metric)

import subprocess
hostname = subprocess.check_output("hostname", shell=True).strip()

if len(failed_pairs) > 0:
    with open(os.path.join(output_dir, 'intra_stack_alignment_failed_pairs_%s.txt' % (hostname.split('.')[0])), 'w') as f:
        for pf, cf in failed_pairs:
            f.write(pf + ' ' + cf + '\n')


import numpy as np
from six.moves import range
import splinart as spl

img_size, channels = 1000, 4
img = np.ones((img_size, img_size, channels), dtype=np.float32)

nb_circles = 10
theta_circles = []
path_circles = []
color_circles = []
for i in range(nb_circles):
    radius = .1 + np.random.random()*.1
    center = .2 + np.random.random(2)*.6
    theta, path = spl.circle(center, radius, npoints=75)
    theta_circles.append(theta)
    path_circles.append(path)
    color = np.random.random(4)*.3
    color[-1] = 1.
    color_circles.append(color)

def xs_func():
    nsamples = 500
    return (np.random.random() + 2 * np.pi * np.linspace(0, 1, nsamples))%(2*np.pi)

for i in range(nb_circles):
    img1 = np.ones_like(img)
    spl.update_img(img1, path_circles[i], xs_func, nrep=1000, scale_value=.00005, x=theta_circles[i], color=color_circles[i])
    mask = img1 < 1.
    img[mask] += img1[mask]

spl.save_img(img, './output', 'circles.png')


from tensorflow.python import keras

from keras import models
from keras import layers
# need slurm
# Keras with data augmentation

model = models.Sequential()
#search for 128 to correct, change channel number, but check
#clone the paths on the crc, and dont change the paths
#add additional models to see if it makes sense, search "keras sequencial"
#calibration
#Tenserflow for questions
model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(128,128,3)))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64, (3,3), activation='relu'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(128, (3,3), activation='relu'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(128, (3,3), activation='relu'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Flatten())
model.add(layers.Dropout(0.2))
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

print(model.summary())

from keras import optimizers

model.compile(loss='binary_crossentropy',
  optimizer=optimizers.RMSprop(lr=1e-5),
  metrics=['acc'])

import os
#change paths
train_dir = 'o4images/train'
validation_dir = 'o4images/validation'
test_dir = 'o4images/test'

train_o4neg_dir = os.path.join(train_dir, 'o4neg')
train_o4pos_dir = os.path.join(train_dir, 'o4pos')
train_size = len(os.listdir(train_o4pos_dir)) + len(os.listdir(train_o4neg_dir))

analysis_name = 'o4counter_wAug_5.1'

batch_size = 200
epochs = 100

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
  rescale=1./255,
  rotation_range=90,
  horizontal_flip=True,
  fill_mode='nearest')
#check out rescale and what it does
validation_datagen = ImageDataGenerator(
  rescale=1./255)

train_generator = train_datagen.flow_from_directory(
  train_dir,
  #Need to crop all to same size, add smaller
  target_size=(128,128),
  batch_size=batch_size,
  class_mode='binary')

validation_generator = validation_datagen.flow_from_directory(
  validation_dir,
  target_size=(128,128),
  batch_size=batch_size,
  class_mode='binary')

history = model.fit_generator(
  train_generator,
  steps_per_epoch=int(5*train_size/batch_size), # oversample 5x
  epochs=epochs,
  validation_data=validation_generator,
  validation_steps=50)

model.save(analysis_name + '.h5')

acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']

# output results as csv
import csv
filename = 'results_' + analysis_name + '.csv'
with open(filename,'w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['acc','val_acc','loss','val_loss'])
    for i in range(len(history.history['acc'])):
        w.writerow([acc[i], val_acc[i], loss[i], val_loss[i]])

# Evaluate model
test_datagen = ImageDataGenerator(rescale=1./255)

test_generator = test_datagen.flow_from_directory(
  test_dir,
  target_size=(128,128),
  batch_size=20,
  class_mode='binary')

test_loss, test_acc = model.evaluate_generator(test_generator, steps=50)
print('test acc:', test_acc)


"""
The Simplified Path Finding Problem
Given an N  N×N matrix of blocks with a source upper left block, we want to find a path from the source to the destination(the lower right block). We can only move downwards and to the right. Also a path is given by 11 and a wall is given by 00.

{
    { 1 , 0 , 1, 0 , 0},
    { 1 , 1 , 0, 1 , 0},
    { 0 , 1 , 0, 1 , 0},
    { 0 , 1 , 0, 0 , 0},
    { 1 , 1 , 1, 1 , 1}
}

maze = [
    [ 1 , 0 , 1, 0 , 0],
    [ 1 , 1 , 0, 1 , 0],
    [ 0 , 1 , 0, 1 , 0],
    [ 0 , 1 , 0, 0 , 0],
    [ 1 , 1 , 1, 1 , 1]
]

base case: we have arrived at the end (n, n -> 4,4)

if we have arrived at the end of the grid,
    return true
else:
    start at 0,0
    check right
        see if right is equal to 0
    check down
        see if it is equal to 0

movements: downwards, rights
upper left block: 0,0
lower right block: n - 1,n - 1
"""

def solveMaze(MAZE, pos, N):

    # base case: we have arrived at the end
    if pos == (N - 1, N - 1):
        print("we have arrived at the end!")
        return True

    x,y = pos
    #check right

    y,x = pos
    #check down

    # else try looking right and below to see
    return False

if __name__ == '__main__':
    MAZE = [
    [ 1 , 0 , 1, 0 , 0],
    [ 1 , 1 , 0, 1 , 0],
    [ 0 , 1 , 0, 1 , 0],
    [ 0 , 1 , 0, 0 , 0],
    [ 1 , 1 , 1, 1 , 1]
    ]

    solveMaze(MAZE,(0,0), 5)


import discord
import json
import typing
import aiohttp
import discord_slash as interactions
import random
import asyncio
from discord_slash import cog_ext
from discord.ext import commands

class Fun(commands.Cog):
    """Fun Commands!"""

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        with open("./HexaBot/HexaBot/misc/assets/embed.json") as embedfile:
            self.embed = json.load(embedfile)
        with open("./HexaBot/HexaBot/misc/lines/8ball.json") as eightballfile:
            self.eightballl = json.load(eightballfile)
        with open("./HexaBot/HexaBot/misc/lines/gay.json") as gayfile:
            self.gay = json.load(gayfile)
        with open("./HexaBot/HexaBot/misc/lines/hug.json") as hugfile:
            self.hugg = json.load(hugfile)
        with open("./HexaBot/HexaBot/misc/lines/kill.json") as killfile:
            self.killl = json.load(killfile)

    def uwufy(self, sentence: str):
        uwu = sentence.lower()
        uwu = uwu.replace("l", "w")
        uwu = uwu.replace("r", "w")
        uwu = uwu.replace("th", "d")
        uwu = uwu.replace("ove", "uv")
        return f"{uwu}, uwu *rawr* XD!"

    async def cat(self, ctx: typing.Union[commands.Context, interactions.SlashContext]):
        async with aiohttp.ClientSession() as session:
            async with session.get("https://api.thecatapi.com/v1/images/search/") as response:
                cat = await response.json()
                catpic = cat[0]["url"]

        e = discord.Embed(title="Random Cat (from TheCatAPI by Aden)", color=int(self.embed["color"], 16), description="Check out TheCatAPI [here](https://thecatapi.com)!")
        e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
        e.set_image(url=catpic)
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        await ctx.send(embed=e)

    @commands.command(name="cat")
    async def dpycat(self, ctx: commands.Context):
        """Shows a random image of a cat."""

        await ctx.trigger_typing()
        await self.cat(ctx)

    @cog_ext.cog_subcommand(base="animals", name="cat", description="Fun - Shows a random image of a cat.")
    async def slashanimalscat(self, ctx: interactions.SlashContext):
        await self.cat(ctx)

    async def dog(self, ctx: typing.Union[commands.Context, interactions.SlashContext]):
        async with aiohttp.ClientSession() as session:
            async with session.get("https://api.thedogapi.com/v1/images/search/") as response:
                dog = await response.json()
                dogpic = dog[0]["url"]

        e = discord.Embed(title="Random Dog (from TheDogAPI by Aden)", color=int(self.embed["color"], 16), description="Check out TheDogAPI [here](https://thedogapi.com)!")
        e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
        e.set_image(url=dogpic)
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        await ctx.send(embed=e)

    @commands.command(name="dog")
    async def dpydog(self, ctx: commands.Context):
        """Shows a random image of a dog."""

        await ctx.trigger_typing()
        await self.dog(ctx)

    @cog_ext.cog_subcommand(base="animals", name="dog", description="Fun - Shows a random image of a dog.")
    async def slashanimalsdog(self, ctx: interactions.SlashContext):
        await self.dog(ctx)

    async def fox(self, ctx: typing.Union[commands.Context, interactions.SlashContext]):
        async with aiohttp.ClientSession() as session:
            async with session.get("https://randomfox.ca/floof/") as response:
                fox = await response.json()
                foxpic = fox["image"]

        e = discord.Embed(title="Random Fox (from Random Fox by xinitrc)", color=int(self.embed["color"], 16), description="Check out Random Fox [here](https://randomfox.ca)!")
        e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
        e.set_image(url=foxpic)
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        await ctx.send(embed=e)

    @commands.command(name="fox")
    async def dpyfox(self, ctx: commands.Context):
        """Shows a random image of a fox."""

        await ctx.trigger_typing()
        await self.fox(ctx)

    @cog_ext.cog_subcommand(base="animals", name="fox", description="Fun - Shows a random image of a fox.")
    async def slashfox(self, ctx: interactions.SlashContext):
        await self.fox(ctx)

    @commands.command(name="say")
    async def dpysay(self, ctx: commands.Context):
        """Please use the Slash Command version, over at `/say`."""

        await ctx.send("Please use the Slash Command version, over at `/say`.")

    @cog_ext.cog_slash(name="say", description="Fun - The Bot will say what you tell it to.", options=[
        interactions.utils.manage_commands.create_option("message", "What you want the Bot to say.", 3, True),
        interactions.utils.manage_commands.create_option("anonymous", "Whether you want the message author to be anonymous or not.", 5, False),
        interactions.utils.manage_commands.create_option("uwu", "Wud you wike youw message to wook wike a fuwwy wwote it?", 5, False),
        interactions.utils.manage_commands.create_option("user", "The User you want to \"impersonate\".", 6, False)
    ])
    async def slashsay(self, ctx: interactions.SlashContext, message: str, anonymous: bool=False, uwu: bool=False, user: discord.Member=None):
        if anonymous:
            avatar = await self.bot.user.avatar.read()
            webhook = await ctx.channel.create_webhook(name="Anonymous", avatar=avatar, reason="Say command.")
        elif user is None:
            avatar = await ctx.author.avatar.read()
            webhook = await ctx.channel.create_webhook(name=ctx.author.name, avatar=avatar, reason="Say command.")
        else:
            avatar = await user.avatar.read()
            webhook = await ctx.channel.create_webhook(name=user.name, avatar=avatar, reason="Say command.")

        if uwu:
            await webhook.send(self.uwufy(message))
        else:
            await webhook.send(message)

        slashbug = await ctx.send("e")
        await slashbug.delete()

        await webhook.delete()

    async def eightball(self, ctx: typing.Union[commands.Context, interactions.SlashContext], question: str):
        balllineint = random.randint(0, 4)
        ballline = self.eightballl[str(balllineint)]

        e = discord.Embed(title="Magic 8 Ball", color=int(self.embed["color"], 16))
        e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
        e.add_field(name="Your Question", value=f"{question}", inline=False)
        e.add_field(name="The 8 Ball's Answer", value=f"{ballline}", inline=False)
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        await ctx.send(embed=e)

    @commands.command(name="8ball")
    async def dpy8ball(self, ctx: commands.Context, *, question: str):
        """Seek an answer from the Magic 8 Ball."""

        await self.eightball(ctx, question)

    @cog_ext.cog_slash(name="8ball", description="Fun - Seek an answer from the Magic 8 Ball.", options=[
        interactions.utils.manage_commands.create_option("question", "Your question for the Magic 8 Ball.", 3, True)
    ])
    async def slash8ball(self, ctx: interactions.SlashContext, question: str):
        await self.eightball(ctx, question)

    async def gaypercent(self, ctx: typing.Union[commands.Context, interactions.SlashContext], thing: str=None):
        gay = random.randint(0, 100)
        supergay = random.randint(1, 10)

        def makeline(jsonline):
            halfpoint = self.gay[jsonline].replace("thing", thing)
            gayliner = halfpoint.replace("gaypercent", f"{gay}%")
            return gayliner

        def line():
            if gay == 0:
                gayline = makeline("0")
            elif gay <= 25:
                gayline = makeline("1to25")
            elif gay <= 50:
                gayline = makeline("26to50")
            elif gay <= 75:
                gayline = makeline("51to75")
            elif gay <= 99:
                gayline = makeline("76to99")
            elif gay == 100:
                gayline = makeline("100")
            elif gay > 100:
                gayline = makeline("over100")
            return gayline

        if thing is None:
            thing = ctx.author.mention

            if supergay == 8:
                gay = gay * 10

            gayline = line()
        else:
            try:
                gayid = int(thing)
            except:
                if supergay == 8:
                    gay = gay * 10

                gayline = line()
            else:
                thing = self.bot.fetch_user(gayid)

                if supergay == 8:
                    gay = gay * 10

                gayline = line()

        e = discord.Embed(title="Gay Percentage", color=int(self.embed["color"], 16), description=f"{gayline}")
        e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        await ctx.send(embed=e)

    @commands.command(name="gaypercent")
    async def dpygay(self, ctx: commands.Context, *, thing: str=None):
        """Wanna find out how gay something is? This command is for you."""

        await self.gaypercent(ctx, thing)

    @cog_ext.cog_slash(name="gaypercent", description="Fun - Wanna find out how gay something is? This command is for you.", options=[
        interactions.utils.manage_commands.create_option("thing", "What you want to find the gayness of.", 3, False)
    ])
    async def slashgay(self, ctx: interactions.SlashContext, thing: str=None):
        await self.gaypercent(ctx, thing)

    async def hug(self, ctx: typing.Union[commands.Context, interactions.SlashContext], member: discord.Member, message: str=None):
        huglineint = random.randint(0, 9)
        halfpoint = self.hugg[str(huglineint)].replace("author", ctx.author.mention)
        hugline = halfpoint.replace("member", member.mention)

        e = discord.Embed(title="Hug", color=int(self.embed["color"], 16), description=f"{hugline}")
        e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
        if message is not None:
            e.add_field(name=f"{ctx.author.name} included a message! They said...", value=f"{message}", inline=False)
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        await ctx.send(embed=e)

    @commands.command(name="hug")
    async def dpyhug(self, ctx: commands.Context, member: discord.Member, message: str=None):
        """Hugs the Member you want."""

        await self.hug(ctx, member, message)
        await ctx.message.delete()

    @cog_ext.cog_slash(name="hug", description="Fun - Hugs the Member you want.", options=[
        interactions.utils.manage_commands.create_option("member", "The Member to hug.", 6, True),
        interactions.utils.manage_commands.create_option("message", "A message to add.", 3, False)
    ])
    async def slashhug(self, ctx: interactions.SlashContext, member: discord.Member, message: str=None):
        await self.hug(ctx, member, message)

    async def kill(self, ctx: typing.Union[commands.Context, interactions.SlashContext], member: discord.Member):
        killlineint = random.randint(0, 4)
        halfpoint = self.killl[str(killlineint)].replace("author", ctx.author.mention)
        killline = halfpoint.replace("member", member.mention)

        e = discord.Embed(title="Murder", color=int(self.embed["color"], 16), description=f"{killline}")
        e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        await ctx.send(embed=e)

    @commands.command(name="kill")
    async def dpykill(self, ctx: commands.Context, member: discord.Member):
        """Kills the Member you want."""

        await self.kill(ctx, member)

    @cog_ext.cog_slash(name="kill", description="Fun - Kills the Member you want.", options=[
        interactions.utils.manage_commands.create_option("member", "The Member to kill.", 6, True)
    ])
    async def slashkill(self, ctx: interactions.SlashContext, member: discord.Member):
        await self.kill(ctx, member)

    @commands.command(name="poll")
    async def dpypoll(self, ctx: commands.Context):
        """Please use the Slash Command version, over at `/poll`."""

        await ctx.send("Please use the Slash Command version, over at `/poll`.")

    @cog_ext.cog_slash(name="poll", description="Fun - Create a poll. Currently only supports two options.", options=[
        interactions.utils.manage_commands.create_option("name", "The poll's name.", 3, True),
        interactions.utils.manage_commands.create_option("option1", "The first option to vote on.", 3, True),
        interactions.utils.manage_commands.create_option("option2", "The second option to vote on.", 3, True)
    ])
    async def slashpoll(self, ctx: interactions.SlashContext, name: str, option1: str, option2: str):
        vote1 = 0
        vote2 = 0

        e = discord.Embed(title=f"Poll: {name}", color=int(self.embed["color"], 16), description=f"**Poll by {ctx.author.mention}.**\nThink and choose.")
        e.set_author(name=self.embed["author"], icon_url=self.embed["icon"])
        e.add_field(name=option1, value=f"{vote1} | 0%")
        e.add_field(name=option2, value=f"{vote2} | 0%")
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        poll = await ctx.send(embed=e, components=[
            interactions.utils.manage_components.create_actionrow(
                interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.blue, "1st Option", None, "opt1"),
                interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.blue, "2nd Option", None, "opt2")
            )
        ])

        while 0 == 0:
            waitfor: interactions.ComponentContext = await interactions.utils.manage_components.wait_for_component(self.bot, poll, ["opt1", "opt2"])
            e.clear_fields()
            if waitfor.custom_id == "opt1":
                vote1 += 1
            elif waitfor.custom_id == "opt2":
                vote2 += 1
            operation1 = round((vote1 * 100) / (vote1 + vote2), 1)
            operation2 = round((vote2 * 100) / (vote1 + vote2), 1)
            if str(operation1).endswith(".0"):
                operation1 = round(operation1)
            if str(operation2).endswith(".0"):
                operation2 = round(operation2)
            e.add_field(name=option1, value=f"{vote1} | {operation1}")
            e.add_field(name=option2, value=f"{vote2} | {operation2}")
            await waitfor.edit_origin(embed=e)

    @commands.command(name="calculator")
    async def dpycalculator(self, ctx: commands.Context):
        """Please use the Slash Command version, over at `/calculator`."""

        await ctx.send("Please use the Slash Command version, over at `/calculator`.")

    @cog_ext.cog_slash(name="calculator", description="Fun - Calculate.")
    async def slashcalculator(self, ctx: interactions.SlashContext):
        string = ""

        actionrow1 = interactions.utils.manage_components.create_actionrow(
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "7", None, "7"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "8", None, "8"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "9", None, "9"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.blue, "+", None, "+"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.red, "Close", None, "exit")
        )
        actionrow2 = interactions.utils.manage_components.create_actionrow(
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "4", None, "4"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "5", None, "5"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "6", None, "6"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.blue, "-", None, "-"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.red, "←", None, "back")
        )
        actionrow3 = interactions.utils.manage_components.create_actionrow(
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "1", None, "1"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "2", None, "2"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "3", None, "3"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.blue, "*", None, "*"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.red, "Clear", None, "clear")
        )
        actionrow4 = interactions.utils.manage_components.create_actionrow(
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "00", None, "00"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, "0", None, "0"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.grey, ".", None, "."),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.blue, "/", None, "/"),
            interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.green, "=", None, "=")
        )

        components = [actionrow1, actionrow2, actionrow3, actionrow4]

        e = discord.Embed(title=f"{ctx.author.name}'s Calculator", color=int(self.embed["color"], 16), description="```\n \n```")
        e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        calculatormessage = await ctx.send(embed=e, components=components)

        async def check1(string):
            try:
                if string.split("|")[-2] == "+":
                    return False
                elif string.split("|")[-2] == "-":
                    return False
                elif string.split("|")[-2] == "*":
                    return False
                elif string.split("|")[-2] == "/":
                    return False
            except:
                return True
            else:
                return False

        async def check2(string):
            try:
                if string.split("|")[-2] == "+":
                    return False
                elif string.split("|")[-2] == "-":
                    return False
                elif string.split("|")[-2] == "*":
                    return False
                elif string.split("|")[-2] == "/":
                    return False
                elif "+" in string.split("|"):
                    return False
                elif "-" in string.split("|"):
                    return False
                elif "*" in string.split("|"):
                    return False
                elif "/" in string.split("|"):
                    return False
            except:
                return True
            else:
                return False

        while 0 == 0:
            waitfor: interactions.ComponentContext = await interactions.utils.manage_components.wait_for_component(self.bot, calculatormessage, ["00", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-", "*", "/", "=", "exit", "back", "clear"])
            if waitfor.author.id == ctx.author.id:
                try:
                    int(waitfor.custom_id)
                except:
                    if waitfor.custom_id == "exit":
                        e.description = "```\nThis Calculator has been closed.\n```"

                        symbols = ["+", "-", "*", "/"]
                        stuff = ["exit", "back", "clear"]
                        for actionrow in components:
                            for i in range(5):
                                style = None
                                try:
                                    int(actionrow[i].custom_id)
                                except:
                                    if actionrow[i].custom_id in symbols:
                                        style = interactions.utils.manage_components.ButtonStyle.blurple
                                    elif actionrow[i].custom_id in stuff:
                                        style = interactions.utils.manage_components.ButtonStyle.red
                                    elif actionrow[i].custom_id == "=":
                                        style = interactions.utils.manage_components.ButtonStyle.green
                                    elif actionrow[i].custom_id == ".":
                                        style = interactions.utils.manage_components.ButtonStyle.grey
                                else:
                                    style = interactions.utils.manage_components.ButtonStyle.grey
                                actionrow[i] = interactions.utils.manage_components.create_button(style, actionrow[i].label, None, actionrow[i].custom_id, None, True)
                        await waitfor.edit_origin(embed=e, components=components)

                        await waitfor.send("Calculator closed.", hidden=True)
                        break
                    elif waitfor.custom_id == "back":
                        stringx = list(string).pop()
                        string = ""
                        for character in stringx:
                            string += character
                        stringe = string.replace("|", "")
                        e.description = f"```\n{stringe}\n```"
                        await waitfor.edit_origin(embed=e)
                    elif waitfor.custom_id == "clear":
                        string = ""
                        e.description = f"```\n \n```"
                        await waitfor.edit_origin(embed=e)
                    elif waitfor.custom_id == "=":
                        stringx = string.split("|")
                        operation = 0
                        if stringx[1] == "+":
                            operation = float(stringx[0]) + float(stringx[2])
                        elif stringx[1] == "-":
                            operation = float(stringx[0]) - float(stringx[2])
                        elif stringx[1] == "*":
                            operation = float(stringx[0]) * float(stringx[2])
                        elif stringx[1] == "/":
                            operation = float(stringx[0]) / float(stringx[2])
                        if str(operation).endswith(".0"):
                            operation = int(operation)
                        string = f"{operation}"
                        e.description = f"```\n{string}\n```"
                        await waitfor.edit_origin(embed=e)
                    elif waitfor.custom_id == "+":
                        if await check2(string):
                            string += "|+|"
                            stringe = string.replace("|", "")
                            e.description = f"```\n{stringe}\n```"
                            await waitfor.edit_origin(embed=e)
                        else:
                            await waitfor.send("**This interaction failed.**", hidden=True)
                    elif waitfor.custom_id == "-":
                        if await check2(string):
                            string += "|-|"
                            stringe = string.replace("|", "")
                            e.description = f"```\n{stringe}\n```"
                            await waitfor.edit_origin(embed=e)
                        else:
                            await waitfor.send("**This interaction failed.**", hidden=True)
                    elif waitfor.custom_id == "*":
                        if await check2(string):
                            string += "|*|"
                            stringe = string.replace("|", "")
                            e.description = f"```\n{stringe}\n```"
                            await waitfor.edit_origin(embed=e)
                        else:
                            await waitfor.send("**This interaction failed.**", hidden=True)
                    elif waitfor.custom_id == "/":
                        if await check2(string):
                            string += "|/|"
                            stringe = string.replace("|", "")
                            e.description = f"```\n{stringe}\n```"
                            await waitfor.edit_origin(embed=e)
                        else:
                            await waitfor.send("**This interaction failed.**", hidden=True)
                    elif waitfor.custom_id == ".":
                        if check1(string):
                            string += waitfor.custom_id
                            e.description = f"```\n{string}\n```"
                            await waitfor.edit_origin(embed=e)
                        else:
                            await waitfor.send("**This interaction failed.**", hidden=True)
                else:
                    string += waitfor.custom_id
                    stringe = string.replace("|", "")
                    e.description = f"```\n{stringe}\n```"
                    await waitfor.edit_origin(embed=e)

    async def hack(self, ctx: typing.Union[commands.Context, interactions.SlashContext], user: discord.Member):
        hacking = await ctx.send("<a:aLoading:833070225334206504> **Getting logins...**")
        await asyncio.sleep(1.0)
        await hacking.edit(content="<:Yes:833293078197829642> **Logins deciphered. Select what to hack below.**")

        e = discord.Embed(title=f"Hack {user.name}", color=int(self.embed["color"], 16), description=f"**Hacking {user.name} ready.**")
        e.set_author(name=self.embed["author"], icon_url=self.embed["icon"])
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        hackmessage = await hacking.reply(embed=e, components=[
            interactions.utils.manage_components.create_actionrow(
                interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.blue, "Hack Discord", None, custom_id="discord"),
                interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.red, "Hack YouTube", None, custom_id="youtube"),
                interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.green, "Hack Twitter", None, custom_id="twitter")
            )
        ])

        waitfor: interactions.ComponentContext = await interactions.utils.manage_components.wait_for_component(self.bot, hackmessage, ["discord", "youtube", "twitter"])
        if waitfor.author_id == ctx.author.id:
            avatar = await user.avatar_url.read()
            webhook = await ctx.channel.create_webhook(name=user.name, avatar=avatar, reason="Hack command")
            if waitfor.custom_id == "discord":
                await webhook.send("I got hacked, oh fuck.")
                await webhook.send(f"FUCK! {ctx.author} HACKED ME!")
                e.description = "**DISCORD HACKED!**"
            elif waitfor.custom_id == "youtube":
                await webhook.send("I just posted a video!\nhttps://youtu.be/Blh2FCAIIgk")
                e.description = "**YOUTUBE HACKED!**"
            elif waitfor.custom_id == "twitter":
                await webhook.send("I just tweeted!\nhttps://twitter.com/WeAreHexaCode/status/1430575263566467079")
                e.description = "**TWITTER HACKED!**"
            await waitfor.edit_origin(embed=e)
            await webhook.delete()

    @commands.command(name="hack")
    async def dpyhack(self, ctx: commands.Context, user: discord.Member):
        """Hack a Member (100% real)!"""

        await self.hack(ctx, user)

    @cog_ext.cog_slash(name="hack", description="Fun - Hack a Member (100% real)!", options=[
        interactions.utils.manage_commands.create_option("user", "Who to hack.", 6, True)
    ])
    async def slashhack(self, ctx: interactions.SlashContext, user: discord.Member):
        await self.hack(ctx, user)

    @commands.command(name="game")
    async def dpygame(self, ctx: commands.Context):
        """Please use the Slash Command version, over at `/game <subcommand>`."""

        await ctx.send("Please use the Slash Command version, over at `/game <subcommand>`.")

    @cog_ext.cog_subcommand(base="discord", subcommand_group="game", name="play", description="Fun - Play a Discord Game in a Voice Channel!", options=[
        interactions.utils.manage_commands.create_option("game", "The Discord Game to play.", 3, True, choices=[
            interactions.utils.manage_commands.create_choice("755827207812677713", "Poker Night"),
            interactions.utils.manage_commands.create_choice("832012774040141894", "Chess in the Park"),
            interactions.utils.manage_commands.create_choice("755600276941176913", "YouTube Together"),
            interactions.utils.manage_commands.create_choice("773336526917861400", "Betrayal.io"),
            interactions.utils.manage_commands.create_choice("814288819477020702", "Fishington.io")
        ])
    ])
    async def slashdiscordgameplay(self, ctx: interactions.SlashContext, game: str):
        async def playgame(channel: discord.VoiceChannel):
            invite = await channel.create_invite(target_type=discord.InviteTarget.embedded_application, target_application_id=int(game), reason="Play Discord Game Command.")

            gamex = ""
            if game == "755827207812677713":
                gamex = "Poker Night"
            elif game == "832012774040141894":
                gamex = "Chess in the Park"
            elif game == "755600276941176913":
                gamex = "YouTube Together"
            elif game == "773336526917861400":
                gamex = "Betrayal.io"
            elif game == "814288819477020702":
                gamex = "Fishington.io"

            e = discord.Embed(title=f"Play {gamex}!", color=int(self.embed["color"], 16), description=f"Click the Button below to play {gamex} in the {channel.name} Voice Channel!")
            e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
            e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
            await ctx.send(embed=e, components=[
                interactions.utils.manage_components.create_actionrow(
                    interactions.utils.manage_components.create_button(interactions.utils.manage_components.ButtonStyle.URL, f"Play {gamex}!", None, None, invite.url)
                )
            ])

        voicestatus = ctx.author.voice

        if voicestatus is None:
            await ctx.send("Please join a Voice Channel and run the command again.", hidden=True)
        else:
            await playgame(voicestatus.channel)

    @cog_ext.cog_subcommand(base="discord", subcommand_group="game", name="info", description="Fun - Get info about Discord Games", options=[
        interactions.utils.manage_commands.create_option("game", "The Discord Game to get information about.", 3, True, choices=[
            interactions.utils.manage_commands.create_choice("Discord Games", "Discord Games (in general)"),
            interactions.utils.manage_commands.create_choice("Poker Night", "Poker Night"),
            interactions.utils.manage_commands.create_choice("Chess in the Park", "Chess in the Park"),
            interactions.utils.manage_commands.create_choice("YouTube Together", "YouTube Together"),
            interactions.utils.manage_commands.create_choice("Betrayal.io", "Betrayal.io"),
            interactions.utils.manage_commands.create_choice("Fishington.io", "Fishington.io")
        ])
    ])
    async def slashgameinfo(self, ctx: interactions.SlashContext, game: str):
        if game != "Discord Games":
            gameid = 0
            if game == "Poker Night":
                gameid = 755827207812677713
            elif game == "Chess in the Park":
                gameid = 832012774040141894
            elif game == "YouTube Together":
                gameid = 755600276941176913
            elif game == "Betrayal.io":
                gameid = 773336526917861400
            elif game == "Fishington.io":
                gameid = 814288819477020702

        gamedesc = ""
        if game == "Discord Games":
            gamedesc = "**Discord Games** are a **Beta** Discord feature, released **randomly** in some servers. There are six in total."
        elif game == "Poker Night":
            gamedesc = "Play poker with your friends in your favourite Discord server thanks to **Poker Night**. This was the first game released.\n**According to Discord themselves, *Poker Night* should only be played by people older than 18.**"
        elif game == "Chess in the Park":
            gamedesc = "Play a nice game of chess in a chill park with **Chess in the Park**. This game is the latest released."
        elif game == "YouTube Together":
            gamedesc = "Watch YouTube videos with all your friends thanks to **YouTube Together**!"
        elif game == "Betrayal.io":
            gamedesc = "**Among Us**, but in Discord."
        elif game == "Fishington.io":
            gamedesc = "**Animal Crossing** Fishing-Only Demo."

        e = discord.Embed(title=f"About {game}", color=int(self.embed["color"], 16))
        e.set_author(name=self.embed["author"] + "Fun", icon_url=self.embed["icon"])
        if game != "Discord Games":
            e.add_field(name="Name", value=f"{game}")
            e.add_field(name="ID", value=f"{gameid}")
        e.add_field(name="Description", value=f"{gamedesc}")
        e.set_footer(text=self.embed["footer"], icon_url=self.embed["icon"])
        await ctx.send(embed=e)

def setup(bot: commands.Bot):
    bot.add_cog(Fun(bot))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 22 16:14:51 2021

@author: madhavrai
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 14 14:27:05 2021

@author: madhavrai
"""
import requests

import cryptocompare
from web3 import Web3
import math

def get_price(symbol , token):
    symbol = symbol.upper()
    a = cryptocompare.get_price(symbol, currency=token)
    return float(a[symbol][token])

def buy_token2(amountToken1=0 , amountToken2=0, token1 = "USDC" , token2="ETH"):
  token1 = token1.upper()

  token2= token2.upper()

  token_map = {"USDC":["0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", 6], "USDT" : ["0xdac17f958d2ee523a2206206994597c13d831ec7",6] , "WBTC":["0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",8],"ETH":["0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",18]}

  decimals_1 = token_map[token1][1]

  address_1 = token_map[token1][0]

  decimals_2 = token_map[token2][1]

  address_2 = token_map[token2][0]
  amount = amountToken1
  price = get_price(token2,token1)
  print(price)
  if amountToken2>0:
    amount = amount + amountToken2*price

  amount = str(int(amount*10**decimals_1))

  r= requests.get('https://api.1inch.exchange/v3.0/1/quote?fromTokenAddress=' + address_1 + "&toTokenAddress="  + address_2 +  "&amount=" + amount).json()

  if token2!="ETH":
    token2 = float(r["toTokenAmount"]) - float(r["estimatedGas"]*10**(decimals_2-9))*get_price("ETH",token2)
  else:
    token2 = float(r["toTokenAmount"]) - float(r["estimatedGas"]*10**9)

  token1 = float(r["fromTokenAmount"])

  executed_price = token1*10**(decimals_2-decimals_1)/token2
  print(address_1)

  slippage = (1-price/executed_price)*100
  implied_volatility_daily = 5

  implied_volatility_30s = implied_volatility_daily/math.sqrt(2880)
  estimated_slippage_percent = slippage + 0.5*implied_volatility_30s
  print(estimated_slippage_percent)
  safe_slippage_percent = slippage + 6*implied_volatility_30s

  tx = get_transaction(amount , safe_slippage_percent , "buy" ,address_1 , address_2 )

  return estimated_slippage_percent, tx

def get_transaction(amount,slippage, side,address_1, address_2):
    print(slippage)

    slippage = round(slippage,3)
    #public_adress = os.environ.get("public-key")
    print(amount)
    public_adress ='0x73bceb1cd57c711feac4224d062b0f6ff338501e'#largest eth wallet added for testing purposes(can comment out public_adress = os.environ.get("public-key"))
    link = 'https://api.1inch.exchange/v3.0/1/swap?fromTokenAddress=' + address_1 + "&toTokenAddress=" + address_2  + "&amount=" + str(amount) + "&fromAddress=" + public_adress + "&slippage=" + str(slippage)
    print(link)

    r = requests.get(link)

    return r.json()

def execute_transaction(tx):
  w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/699154aa8e20430a9e615fd70f98d5cd'))

  connected = w3.isConnected()

  print(connected)

  public_adress = os.environ.get("public-key")

  private_key = os.environ.get("private-key")

  adress1 = Web3.toChecksumAddress(public_adress)

  adress2 = Web3.toChecksumAddress(tx["to"])

  nonce = w3.eth.getTransactionCount(adress1)

  print(nonce)

  tx["nonce"] = nonce

  tx["value"] = int(tx["value"])

  tx["gasPrice"] = int(tx["gasPrice"])
  tx["to"] = adress2

  signed_tx = w3.eth.account.signTransaction(tx,private_key)

  print(signed_tx)

  tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)

  return "done"

slippage, tx = buy_token2(token1="eth" , token2 = "usdc" , amountToken2 = 100000)

#a = execute_transaction(tx)

#0.5 rights side of the bell curve


import collections
import enum
import itertools
import queue

import intcode

class Robot:
    class MoveCommand(enum.IntEnum):
        NORTH = 1
        SOUTH = 2
        WEST = 3
        EAST = 4

        def opposite(self):
            if self == self.NORTH:
                return self.SOUTH
            elif self == self.SOUTH:
                return self.NORTH
            elif self == self.WEST:
                return self.EAST
            elif self == self.EAST:
                return self.WEST

    class Status(enum.IntEnum):
        WALL = 0
        MOVED = 1
        MOVED_OXYGEN = 2

    program = intcode.read_program('input.txt')

    def __init__(self):
        self.thread, self.input_queue, self.output_queue, _ = \
            intcode.intcode(self.program)

    def move(self, direction: MoveCommand) -> Status:
        self.input_queue.put(direction.value)
        return self.Status(self.output_queue.get())

class Cell(enum.Enum):
    UNKNOWN = enum.auto()
    EMPTY = enum.auto()
    WALL = enum.auto()
    OXYGEN = enum.auto()

# adapted from
# https://www.laurentluce.com/posts/solving-mazes-using-python-simple-recursivity-and-a-search/
def explore():
    grid = collections.defaultdict(
        lambda: collections.defaultdict(
            lambda: Cell.UNKNOWN))

    robot = Robot()

    oxygen_location = None

    def search(x, y, move_command=None):
        nonlocal oxygen_location

        cell = grid[y][x]
        if cell != Cell.UNKNOWN:
            return

        # Try to move into the cell
        if move_command:
            robot_status = robot.move(move_command)

            if robot_status == Robot.Status.WALL:
                grid[y][x] = Cell.WALL
                return

            if robot_status == Robot.Status.MOVED:
                grid[y][x] = Cell.EMPTY
            elif robot_status == Robot.Status.MOVED_OXYGEN:
                grid[y][x] = Cell.OXYGEN
                oxygen_location = (x, y)

        # explore neighbors
        search(x, y+1, Robot.MoveCommand.NORTH)
        search(x, y-1, Robot.MoveCommand.SOUTH)
        search(x-1, y, Robot.MoveCommand.WEST)
        search(x+1, y, Robot.MoveCommand.EAST)

        # Leave the cell
        if move_command:
            robot_status = robot.move(move_command.opposite())
            assert(robot_status == Robot.Status.MOVED)

    search(0, 0)
    return grid, oxygen_location

# explore the entire maze
board, oxygen_location = explore()

# adapted from
# https://www.redblobgames.com/pathfinding/a-star/implementation.html#python-astar
def heuristic(a, b):
    x1, y1 = a
    x2, y2 = b
    return abs(x1 - x2) + abs(y1 - y2)

def neighbors(board, location):
    x, y = location
    for x_, y_ in ((x, y+1), (x, y-1), (x-1, y), (x+1, y)):
        cell = board[y_][x_]
        if cell == Cell.EMPTY or cell == Cell.OXYGEN:
            yield (x_, y_)

def a_star_search(board, start, goal):
    frontier = queue.PriorityQueue()
    frontier.put(start, 0)
    came_from = {}
    cost_so_far = {}
    came_from[start] = None
    cost_so_far[start] = 0

    while not frontier.empty():
        current = frontier.get()

        if current == goal:
            return cost_so_far[goal]

        for next_ in neighbors(board, current):
            new_cost = cost_so_far[current] + 1
            if next_ not in cost_so_far or new_cost < cost_so_far[next_]:
                cost_so_far[next_] = new_cost
                priority = new_cost + heuristic(goal, next_)
                frontier.put(next_, priority)
                came_from[next_] = current

# use A* to determine the shortest path from (0, 0) to the oxygen system
print(a_star_search(board, (0, 0), oxygen_location))


from pygame import *

init()
# we only need a screen to get access to the events
# screen line creates a screen we can draw onto
# display.set_mode opens up a game window and sets the window to the size you want it to be
#display.set_mode((width, height))
screen = display.set_mode((640, 480)) # tuple - an array/list that cant be changed
display.set_caption("Graphics") # .set_caption("Text") changes caption on top of the window

endProgram = False

while not endProgram:
    # pygame event loop
    for e in event.get():
        if e.type == QUIT: # this event is called whenever the window is exited
            endProgram = True
    # draw stuff
    # screen.fill((red,green,blue))
    # value for each amount of red/green/blue can go from 0 - 254
    screen.fill((100,100,200)) # fills the screen with a single colour
    # rectangle
    # draw.rect(surface, colour, rectangle, thickness)
    # rectangle is a tuple (X,Y,Width, Height)
    draw.rect(screen, (255,0,0), (10,10,100,100), 4) # outline of rectangle
    # fill rectangle
    # leaving thickness out will make the program assume you want the full colour
    draw.rect(screen, (255,0,0), (200,10,100,100)) # full rectangle
    # circle
    # draw.ellipse(surface, colour, rectangle, thickness)
    # the rectangle is where the circle will be inside of
    draw.ellipse(screen, (0,255,0), (10, 200, 80, 80) , 4)
    # circle
    draw.ellipse(screen, (0,255,0), (200, 200, 80, 80))
    # update the screen
    # display.update() draws all the shapes from memory
    display.update()


#!/bin/env python
#-*- coding:UTF-8 -*-

import csv

def dataReader(filename):
    with open(filename, 'rb') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            #print(row['first_name'], row['last_name'])
            print (
                    row['date'],
                    row['code'].strip('\''),
                    #row['name'].decode('GB18030'),
                    #row['name'].decode('GB2312'),
                    row['name'],
                    row['TCLOSE'],
                    row['HIGH'],
                    row['LOW'],
                    row['TOPEN'],
                    row['LCLOSE'],
                    row['CHG'],
                    row['PCHG'],
                    row['TURNOVER'],
                    row['VOTURNOVER'],
                    row['VATURNOVER'],
                    row['TCAP'],
                    row['MCAP'])

#date,code,name,TCLOSE,HIGH,LOW,TOPEN,LCLOSE,CHG,PCHG,TURNOVER,VOTURNOVER,VATURNOVER,TCAP,MCAP
if __name__ == '__main__':

    file='datadir/300370.csv'
    dataReader(file)


#!/usr/bin/env python3

# pylint: disable = bad-whitespace
# pylint: disable = invalid-name
# pylint: disable = missing-docstring
# pylint: disable = pointless-string-statement

# -------------
# UnitTests2.py
# -------------

# https://docs.python.org/3/library/unittest.html
# https://docs.python.org/3/library/unittest.html#assert-methods

from unittest import main, TestCase

def cycle_length (n: int) -> int :
    assert n > 0
    c = 1
    while n > 1 :
        if (n % 2) == 0 :
            n = (n // 2)
        else :
            n = (3 * n) + 1
        c += 1
    assert c > 0
    return c

class MyUnitTests (TestCase) :
    def test1 (self) :
        self.assertEqual(cycle_length( 1), 1)

    def test2 (self) :
        self.assertEqual(cycle_length( 5), 5)

    def test3 (self) :
        self.assertEqual(cycle_length(10), 7)

if __name__ == "__main__" : # pragma: no cover
    main()

""" #pragma: no cover
% UnitTests2T.py
.F.
======================================================================
FAIL: test2 (__main__.MyUnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "UnitTests2.py", line 34, in test2
    self.assertEqual(cycle_length( 5), 5)
AssertionError: 6 != 5

----------------------------------------------------------------------
Ran 3 tests in 0.001s

FAILED (failures=1)
"""


from StartPage import StartPage
import LearningMenu
from playsound import playsound
from UserManager import UserManager
from WordManager import WordManager
from pygame import *
import threading
import TestMenu
import CardMenu
from time import sleep

try:
    import Tkinter as tk
except:
    import tkinter as tk

class ProjectMain(tk.Tk,UserManager,WordManager): #Tk를 상속받아서 생성

    def __init__(self):
        tk.Tk.__init__(self)
        UserManager.__init__(self)
        WordManager.__init__(self)
        self.init_gui()
        mixer.init()
        self.wordread()
        self.word_img()
        self.background_music=mixer.Sound("C:/english-learning-program/sound/01. The Alphabet Song.mp3")
        self.background_music.set_volume(0.2)
        self.click=mixer.Sound("C:/english-learning-program/sound/click_sound1.mp3")
        self.click.set_volume(0.5)
        self.music=True
        self._frame=None
        self.switch_frame(StartPage) #프레임 변경을 위함

    def init_gui(self): #Tk 이름 설정 및 꾸미기
        self.geometry("1000x800") #1000x800 크기
        self.resizable(width=False, height=False) #화면 고정
        self.title("english learning program") #타이틀 설정
        self.iconbitmap('C:/english-learning-program/image/symbol.ico') #좌측 맨끝 아이콘 설정

    def switch_frame(self,frame_class):
        new_frame=frame_class(self)

        if self._frame is not None:
            self._frame.destroy()

        self._frame=new_frame
        self._frame.pack()

    def write_notKnow(self,update): #아는것 추가,틀린것 삭제

        if update is not None:
            self.delete_notKnowInfo(update)
            self.insert_knowInfo(update)
            self.set_user()

    def insert_info(self,know,notknow):
        try:
            self.insert_knowInfo(know)
            self.insert_notknowInfo(notknow)
            self.set_user()
        except:
            pass

    def write_user(self):
        self.insert_user()

    def write_info_know(self,suc_num):
        self.insert_knowInfo(suc_num)
        self.set_user()

    def write_info_notKnow(self,wrong_num):
        self.insert_notknowInfo_int(wrong_num)
        self.set_user()

    def click_sound(self,sound):
        if sound==True:
            self.click.play()
            sound=False

    # def card_back_sound(self):
    #     mixer.music.load("C:/english-learning-program/sound/card_sound.mp3")
    #     mixer.music.play()

    def music_sound(self):
        self.background_music.play(-1)

    def stop_sound(self):
        self.background_music.stop()

    def exit_(self):
        sound=True
        self.click_sound(sound)
        print("종료됩니다")
        self.destroy()

        exit()

python_project=ProjectMain()

python_project.mainloop()


# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
mahsulotlar = ['un', "yog'", "sovun", 'tuxum', 'piyoz','kartoshka', 'olma', 'banan', 'uzum', 'qovun']
savat = []
for n in range(5):
    savat.append(input(f"Savatga {n+1}-mahsulotni qo'shing: "))
bor_mahsulotlar = []
mavjud_emas = []
for mahsulot in savat:
    if mahsulot in mahsulotlar:
        bor_mahsulotlar.append(mahsulot)
    else:
        mavjud_emas.append(mahsulot)
if mavjud_emas:
 print("Do'konimizda quyidagi mahsulotlar yo'q:")
 for mahsulot in mavjud_emas:
    print(mahsulot)
 if bor_mahsulotlar:
    print("Siz so'ragan maxsulotlar ro'yxati")
    for mahsulot in bor_mahsulotlar:
        print(mahsulot)
else:
  print("Siz so'ragan barcha mahsulotlar do'konimizda bor")
  for mahsulot in bor_mahsulotlar:
      print(mahsulot)
  print(" Xaridingiz uchun raxmat!")


#!/usr/bin/env python
# Four spaces as indentation [no tabs]

from player import Player
from util import *

# ==========================================
# Player Minimax
# ==========================================

class MinimaxPlayer(Player):

    # ------------------------------------------
    # Initialize
    # ------------------------------------------

    def __init__(self, symbol):
        super(MinimaxPlayer, self).__init__(symbol)

    # ------------------------------------------
    # Get next move
    # ------------------------------------------

    def get_next_move(self, board):
        (next_move, _) = self.minimax(2, board, self.me())
        return next_move

    def minimax(self, level, board, player):
        next_move  = None
        best_score = -99999 if player == self.me() else 99999

        cells = find_empty_cells(board)

        if level == 0:
            (score, wins) = self.score(board)

            for x in cells:
                if x not in wins:
                    return (x, score)

            return (cells[0], score)

        for x in cells:
            _cells    = board[:]
            _cells[x] = player

            inverse_player = self.me() if player == self.opp() else self.opp()

            (_, score) = self.minimax(level - 1, _cells, inverse_player)

            if player == self.me():
                if score > best_score:
                    best_score = score
                    next_move = x

            elif player == self.opp():
                score = score * -1

                if score < best_score:
                    best_score = score
                    next_move = x

        return (next_move, best_score)

    def score(self, board):
        score = 1
        move_win = []

        for i in board:
            (winner, move) = find_winner(board)

            if winner != None:
                move_win.append(i)

                if len(move_win) == 1:
                    score = 1
                elif len(move_win) == 2:
                    score = 10
                else:
                    score = 100

                if winner != self.me():
                    score = score * -1

        return (score, move_win)


# -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 16:06:15 2018

@author: xigu
"""

# -*- coding: utf-8 -*-
"""
Created on Wed Feb  7 08:06:43 2018

@author: xigu
"""

# In[1]:

import numpy as np
import pandas as pd
import statsmodels.api as sm
import time

from collections import Counter
from dateutil import relativedelta
from matplotlib import pyplot as plt

# In[]:

########################################################################
##
##
##  Utility Functions
##
##
########################################################################

##
## To print out the model's predictability
def print_score(model, x, y):
    print(model)
    print('Score : ', model.score(x, y))

## Check Delinquencies. Categorize delinquencies into Good and Serious Delinquency
##
## i.e.
## For Pattern 'C1C', dismiss the delinquency and consider as good payment
## For Pattern '1234', consider as serious Delinquency

def Modify_Delinquency(df, column_name):
    data = df[column_name].values
    for i in range(df.shape[0]):
        if (data[i].isdigit()):
            data[i] = 'DQ'
        elif (data[i] == 'O'):
            data[i] = 'D'
    return data

##  Deprecated Method
##  Buckets need to be economically reasonable
##
##  Date: Feb 7th, 2018
##
##  Convert numerical to Categorical

# =============================================================================
# def convert_to_categorical(df, columns, num_buckets):
#     cols=[]
#     for col in columns:
#         print(col)
#         df[col] = df[col].astype(float)
#         #df[col] = pd.qcut(df[col].rank(method='first'), num_buckets, labels=False)
#         df[col] = pd.qcut(df[col], num_buckets)
#         col_dummy = pd.get_dummies(df[col], prefix=col)
#         cols=cols+list(col_dummy.columns)
#         df = pd.concat([df, col_dummy], axis=1)
#
#     return df, cols
#
# =============================================================================

##  Latest Method
##

##
## Convert numerical to Categorical
def check_numerical(df, col):
    df[col] = df[col].astype(float)
    return df[col]

# In[]:
########################################################################
##
##  Read Data
##
##  <null> data has been cleaned
##
##
########################################################################
cols_regression = [
    'Status',
    'Housing Status',
    'Grade',
    'Original Loan Balance',
    'Interest Rate',
    'Payment-To-Income',
    'Original FICO',
    'EHUPUS',
    'Age',
    'Pre-Loan DTI',
    'Next Status'
]

data_regression = pd.read_csv('data_regression_20180305.csv', usecols=cols_regression)
data_regression = data_regression.replace(['<null>'], 0)

# In[]:
#

housing_status = data_regression['Housing Status']
housing_status_numerical = pd.get_dummies(housing_status)
grade = data_regression['Grade']
grade[grade == 'B'] = 'A'
grade_cols = pd.get_dummies(grade)
data_regression = pd.concat([data_regression, housing_status_numerical], axis=1)
data_regression = pd.concat([data_regression, grade_cols], axis=1)

# In[]:

########################################################################
##
##
##  Buckets Definition
##
##
########################################################################
cols_numerical = [
    'Original Loan Balance',
    'Interest Rate',
    'Payment-To-Income',
    'Original FICO',
    #    'EHUPUS'
    'Pre-Loan DTI',
    'Age'
]
y_col = 'Next Status'
status_col = 'Status'
for col in cols_numerical:
    data_regression[col] = check_numerical(data_regression.copy(), col)

buckets = {}
buckets['Original Loan Balance'] = [0, 8000, 15000, 20000, 1e10]
buckets['Interest Rate'] = [0, 0.2, 0.25, 0.3, 0.35, 1e10]
buckets['Payment-To-Income'] = [0, 0.05, 0.10, 0.15, 1e10]
buckets['Original FICO'] = [0, 600, 650, 700, 750, 1e10]
buckets['Pre-Loan DTI'] = [0, 0.25, 0.5, 0.75, 1e10]
buckets['Age'] = list(np.arange(36)) + [10e6]

data_regression_clean = data_regression.copy()

cols = list(housing_status_numerical.columns) + list(grade_cols.columns)
for col in cols_numerical:
    data_regression_clean[col] = pd.cut(data_regression[col], bins=buckets[col], include_lowest=True)
    col_dummy = pd.get_dummies(data_regression_clean[col], prefix=col)
    cols = cols + list(col_dummy.columns)
    data_regression_clean = pd.concat([data_regression_clean, col_dummy], axis=1)

y_status = Modify_Delinquency(data_regression_clean.copy(), y_col)
data_regression_clean[y_col] = y_status
x_status = Modify_Delinquency(data_regression_clean.copy(), status_col)
data_regression_clean[status_col] = x_status

current_name = 'Current'
curr_status_dummy = pd.get_dummies(data_regression_clean[status_col], prefix=current_name)
curr_status_cols = [current_name + '_DQ', current_name + '_C']
x_cols = cols + curr_status_cols
data_regression_clean = pd.concat([data_regression_clean, curr_status_dummy[curr_status_cols]], axis=1)

# In[]:
########################################################################
##
##
##  Count Occurences
##
##
########################################################################
print(Counter(y_status))

# In[]:
# def Classification(df, y_col, identifier, curr_status):
#    y_values = (df[y_col]==identifier).astype(int)
#    df[curr_status] = 0
#    Current_status = (df[y_col]==identifier).astype(int)
#    df[curr_status][:-1] = Current_status[1:]
#
#    index = df[df[y_col]==identifier].index
#    df[y_col] = y_values
#    df.loc[index][curr_status] = 1
#    return df

def Classification(df, col, identifier):
    indicator = (df[col].values == identifier).astype(int)

    return indicator

# In[]:
########################################################################
##
##  Logistic Regression
##  Setting Hyper Parameters
##
########################################################################

alpha = 0.75

status = ['C', 'P', 'D', 'DQ']
y_names = ['To_' + s for s in status]

# In[]:
for i, s in enumerate(status):
    data_regression_clean[y_names[i]] = Classification(data_regression_clean.copy(), y_col, s)
drop_index = data_regression_clean.loc[data_regression_clean['Status'].isin(['D', 'P'])].index
data_regression_clean = data_regression_clean.drop(drop_index)

# In[]:
########################################################################
##
##  Logistic Regression
##  Setting Hyper Functions
##
########################################################################

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

def logistic_regression(X_train, y_train, X_test, y_test, intercept):
    start = time.time()
    lr = LogisticRegression(fit_intercept=intercept, C=1e15).fit(X_train, y_train)
    print("--- %s seconds ---" % (time.time() - start))
    print_score(lr, X_test, y_test)
    return lr

def split_test_train(X, y, train_size=0.75):
    X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=train_size)
    return X_train, X_test, y_train, y_test

def regression_results(df, y_name, x_cols, alpha):
    X_train, X_test, y_train, y_test = split_test_train(df[x_cols], df[y_name], train_size=alpha)
    result = logistic_regression(X_train, y_train, X_test, y_test, True)

    return result

# In[]:
########################################################################
##
##  Logistic Regression
##
########################################################################

regression_ = {}
for y_name in y_names:
    regression_[y_name] = regression_results(data_regression_clean, y_name, x_cols, alpha)

# In[]:
########################################################################
##
##  Output Results
##
########################################################################
data_path = 'Data/'

for y_name in y_names:
    result = regression_[y_name]
    intcpt = result.intercept_
    coefs = np.squeeze(result.coef_)
    coeffs = pd.DataFrame(np.concatenate((intcpt, coefs))).T
    coeffs.columns = ['Intercept'] + x_cols
    coeffs.to_csv(data_path + y_name + '.csv')

# In[]:
########################################################################
##
##
##  Validation On the Original Dataset
##
##
########################################################################
validation = {}
for y_name in y_names:
    validation[y_name] = regression_[y_name].score(data_regression_clean[x_cols], data_regression_clean[y_name])


from telegram import Bot, Update
from telegram.ext import (Updater, CommandHandler, MessageHandler,Filters)
from echo.config import TG_TOKEN,TG_API_URL

def do_start(bot:Bot, update:Update):
    bot.send_message(
        chat_id=update.message.chat_id,
        text="Привет, ответь чтонибудь"
    )

def do_echo(bot:Bot, update:Update):
    chat_id = update.message.chat_id
    text = "Ваш id = {}\n\n{}".format(chat_id, update.message.text )
    bot.send_message(
        chat_id=chat_id,
        text=text,
    )

def main():
    bot = Bot(token=TG_TOKEN, base_url=TG_API_URL)
    updater = Updater(bot=bot)

    start_handler = CommandHandler(
        "start", do_start
    )
    message_handler= MessageHandler(Filters.text, do_echo)

    updater.dispatcher.add_handler(start_handler)
    updater.dispatcher.add_handler(message_handler)

    updater.start_polling()
    updater.idle()

if __name__=="__main__":
    main()


from conn_suc import ConnSuc
from conn_cen import Conexion
from logger_base import logger
from querys import Query

class obtenerQuery:

    @classmethod
    def resCen(cls):
        cursor = Conexion.obtenerCursor()
        cursor.execute(Query.solDep())
        registros = cursor.fetchall()
        registrosCen = []
        for registro in registros:
            registrosCen.append(registros)
        return registrosCen

    @classmethod
    def resSuc(cls):
        cursores = ConnSuc.obtenerCursor()
        #server =  ConnSuc.server()
        registrosSuc = []
        for u in cursores:
            u.execute(Query.solDep())
            registros = u.fetchall()
            if registros == ():
                pass
            else:
                print('\n\n')
                registrosSuc.append(registros)
        return registrosSuc

if __name__ == '__main__':
    #logger.info(ConnSuc.obtenerCursor())
    uno = obtenerQuery.resCen()
    print('\n\n')
    dos = obtenerQuery.resSuc()
    print(uno)
    print('----------------------------------------------------')
    print(dos)


# Copyright (C) 2012, Jesper Friis, SINTEF
# (see accompanying license files for ASE).
"""Module to read and write atoms EON reactant.con files.

See http://theory.cm.utexas.edu/eon/index.html for a description of EON.
"""
import os
from warnings import warn
from glob import glob

import numpy as np

from ase.atoms import Atoms
from ase.constraints import FixAtoms
from ase.lattice.spacegroup.cell import cellpar_to_cell, cell_to_cellpar
from ase.parallel import paropen

def read_reactant_con(fileobj):
    """Reads an EON reactant.con file.  If *fileobj* is the name of a
    "states" directory created by EON, all the structures will be read."""
    if isinstance(fileobj, str):
        if (os.path.isdir(fileobj)):
            return read_states(fileobj)
        else:
            f = open(fileobj)
    else:
        f = fileobj

    comment = f.readline().strip()
    f.readline()  # 0.0000 TIME  (??)
    cell_lengths = f.readline().split()
    cell_angles = f.readline().split()
    cellpar = [float(x) for x in cell_lengths + cell_angles]
    f.readline()  # 0 0     (??)
    f.readline()  # 0 0 0   (??)
    ntypes = int(f.readline())  # number of atom types
    natoms = [int(n) for n in f.readline().split()]
    atommasses = [float(m) for m in f.readline().split()]

    symbols = []
    coords = []
    masses = []
    fixed = []
    for n in range(ntypes):
        symbol = f.readline().strip()
        symbols.extend([symbol]*natoms[n])
        f.readline() # Coordinates of Component n
        for i in range(natoms[n]):
            row = f.readline().split()
            coords.append([float(x) for x in row[:3]])
            masses.extend([atommasses[n]]*natoms[n])
            fixed.append(bool(int(row[3])))

    if isinstance(fileobj, str):
        f.close()

    atoms = Atoms(symbols=symbols,
                  positions=coords,
                  masses=masses,
                  cell=cellpar_to_cell(cellpar),
                  constraint=FixAtoms(mask=fixed),
                  info=dict(comment=comment))

    return atoms

def read_states(states_dir):
    """Read structures stored by EON in the states directory *states_dir*."""
    subdirs = glob(os.path.join(states_dir, '[0123456789]*'))
    subdirs.sort(key=lambda d: int(os.path.basename(d)))
    images = [read_reactant_con(os.path.join(subdir, 'reactant.con'))
              for subdir in subdirs]
    return images

def write_reactant_con(fileobj, images):
    """Writes structure to EON reactant.con file
    Multiple snapshots are not allowed."""
    if isinstance(fileobj, str):
        f = paropen(fileobj, 'w')
    else:
        f = fileobj

    if isinstance(images, Atoms):
        atoms = images
    elif len(images) == 1:
        atoms = images[0]
    else:
        raise ValueError('Can only write one configuration to EON '
                         'reactant.con file')

    out = []
    out.append(atoms.info.get('comment', 'Generated by ASE'))
    out.append('0.0000 TIME')  # ??

    a, b, c, alpha, beta, gamma = cell_to_cellpar(atoms.cell)
    out.append('%-10.6f  %-10.6f  %-10.6f' % (a, b, c))
    out.append('%-10.6f  %-10.6f  %-10.6f' % (alpha, beta, gamma))

    out.append('0 0')    # ??
    out.append('0 0 0')  # ??

    symbols = atoms.get_chemical_symbols()
    massdict = dict(zip(symbols, atoms.get_masses()))
    atomtypes = sorted(massdict.keys())
    atommasses = [massdict[at] for at in atomtypes]
    natoms = [symbols.count(at) for at in atomtypes]
    ntypes = len(atomtypes)

    out.append(str(ntypes))
    out.append(' '.join([str(n) for n in natoms]))
    out.append(' '.join([str(n) for n in atommasses]))

    for n in range(ntypes):
        fixed = np.array([False] * len(atoms))
        out.append(atomtypes[n])
        out.append('Coordinates of Component %d' % (n + 1))
        indices = [i for i, at in enumerate(symbols) if at == atomtypes[n]]
        a = atoms[indices]
        coords = a.positions
        for c in a.constraints:
            if not isinstance(c, FixAtoms):
                warn('Only FixAtoms constraints are supported by con files. '
                     'Dropping %r', c)
                continue
            if c.index.dtype.kind == 'b':
                fixed = np.array(c.index, dtype=int)
            else:
                fixed = np.zeros((natoms[n], ), dtype=int)
                for i in c.index:
                    fixed[i] = 1
        for i, (xyz, fix) in enumerate(zip(coords, fixed)):
            out.append('%10.5f %10.5f %10.5f  %d     %d' %
                       (tuple(xyz) + (fix, i)))

    f.write('\n'.join(out))

    if isinstance(fileobj, str):
        f.close()


from newspaper import Article

b = open("links.txt","r+")
#A new article from TOI
i = 0
fileno = 1001
while i<195:
    z = b.readline()
    i+=1
    if z.find("https://timesofindia.indiatimes.com/sports/cricket/") == -1:
        continue
        # print(z)
    print(str(fileno)+"-----\n")
    z = z[:len(z)-1]
    print(z)
    url = z

    #For different language newspaper refer above table
    toi_article = Article(url, language="en") # en for English
    name = "article"+str(fileno)+".txt"
    file = open(name,"w")
    #To download the article
    toi_article.download()

    #To parse the article
    toi_article.parse()

    #To perform natural language processing ie..nlp
    toi_article.nlp()

    #To extract title
    print("Article's Title:")
    print(toi_article.title)
    file.write(toi_article.title)
    file.write('\n')

    print("n")

    #To extract text
    print("Article's Text:")
    print(toi_article.text)
    print("n")

    file.write(toi_article.text)

    #To extract summary
    print("Article's Summary:")
    print(toi_article.summary)
    print("n")

    #To extract keywords
    print("Article's Keywords:")
    print(toi_article.keywords)
    fileno += 1


"""Locate all grasslands above 2000m within 300m of a stream."""
import logging
LOGGER = logging.getLogger('grasslands_demo')
logging.basicConfig(level=logging.INFO)

from osgeo import gdal
import pygeoprocessing

# First, let's determine the stream network.
# To do this, we need to mosaic the DEM and reproject to the local projection

import os

OUTPUT_DIR = '/shared/grasslands_demo'
if not os.path.exists(OUTPUT_DIR):
    os.makedirs(OUTPUT_DIR)

north_dem = '/data/N38W120.tif'
south_dem = '/data/N37W120.tif'

joined_dem = os.path.join(OUTPUT_DIR, 'joined_dem.tif')

yosemite_vector = '/data/yosemite.shp'
LOGGER.info('Starting union of DEMs')

import numpy
def _merge_dems(north_block, south_block):
    valid_mask = (north_block != -1) | (south_block != -1)
    out_matrix = numpy.empty(north_block.shape)
    out_matrix[:] = -1
    out_matrix[valid_mask] = numpy.maximum(north_block[valid_mask],
                                           south_block[valid_mask])
    return out_matrix

LOGGER.info('Merging DEMs')
pygeoprocessing.vectorize_datasets(
    dataset_uri_list=[north_dem, south_dem],
    dataset_pixel_op=_merge_dems,
    dataset_out_uri=joined_dem,
    datatype_out=gdal.GDT_Int16,
    nodata_out=-1.0,
    # We could calculate projected units by hand, but this is more convenient.
    pixel_size_out=30.0,
    bounding_box_mode='union',
    vectorize_op=False,
    aoi_uri=yosemite_vector,
)

# Next we need to calculate the slope layer.
LOGGER.info('Calculating slope')
slope_raster = os.path.join(OUTPUT_DIR, 'slope.tif')
pygeoprocessing.calculate_slope(
    dem_dataset_uri=joined_dem,
    slope_uri=slope_raster)

# OK!  Now we add it all together with a call to vectorize_datasets
LOGGER.info('Finding high-elevation, steep grasslands')
lulc = '/data/landcover.tif'

# segfault if I do this: gdal.Open(lulc).GetRasterBand(1).GetNoDataValue()
lulc_nodata = pygeoprocessing.get_nodata_from_uri(lulc)
dem_nodata = pygeoprocessing.get_nodata_from_uri(joined_dem)
slope_nodata = pygeoprocessing.get_nodata_from_uri(slope_raster)

out_nodata = -1
def _find_grasslands(lulc_blk, dem_blk, slope_blk):
    # All blocks will be the same dimensions

    # Create a mask of invalid pixels due to nodata values
    valid_mask = ((lulc_blk != lulc_nodata) &
                  (dem_blk != dem_nodata) &
                  (slope_blk!= slope_nodata))

    # grasslands are lulc code 10
    matching_grasslands = ((lulc_blk[valid_mask] == 10) &
                           (slope_blk[valid_mask] >= 45) &
                           (dem_blk[valid_mask] >= 2000))

    out_block = numpy.empty(lulc_blk.shape)
    out_block[:] = 0
    out_block[~valid_mask] = out_nodata
    out_block[valid_mask] = matching_grasslands
    return out_block

def _find_grasslands_pixels(lulc_pixel, dem_pixel, slope_pixel):
    if any(lulc_pixel == lulc_nodata,
           dem_pixel == dem_nodata,
           slope_pixel == slope_nodata):
        return out_nodata
    elif all(lulc_pixel == 10,
             slope_pixel >= 20,
             dem_pixel >= 2000):
        return 1
    return 0

pygeoprocessing.vectorize_datasets(
    dataset_uri_list=[lulc, joined_dem, slope_raster],
    dataset_pixel_op=_find_grasslands,
    dataset_out_uri=os.path.join(OUTPUT_DIR, 'high_elev_steep_grasslands.tif'),
    datatype_out=gdal.GDT_Int16,
    nodata_out=out_nodata,
    # We could calculate projected units by hand, but this is more convenient.
    pixel_size_out=pygeoprocessing.get_cell_size_from_uri(joined_dem),
    bounding_box_mode='intersection',
    vectorize_op=False,  # we
    aoi_uri=yosemite_vector)


# Author: Xinshuo Weng
# email: xinshuo.weng@gmail.com
import math
import numpy as np
from PIL import Image

from xinshuo_python import *

def imagecoor2cartesian(pts, debug=True):
	'''
	change the coordinate system from image coordinate system to normal cartesian system, basically reverse the y coordinate

	parameter:
		pts:	a single point (list, tuple, numpy array) or a 2 x N numpy array representing a set of points

	return:
		pts:	a tuple if only single point comes in or a 2 x N numpy array
	'''
	return cartesian2imagecoor(pts, debug=debug)

def cartesian2imagecoor(pts, debug=True):
	'''
	change the coordinate system from normal cartesian system back to image coordinate system, basically reverse the y coordinate

	parameter:
		pts:	a single point (list, tuple, numpy array) or a 2 x N numpy array representing a set of points

	return:
		pts:	a tuple if only single point comes in or a 2 x N numpy array
	'''
	if debug:
		assert is2dpts(pts) or (isnparray(pts) and pts.shape[0] == 2 and pts.shape[1] > 0), 'point is not correct'

	if is2dpts(pts):
		if isnparray(pts):
			pts = np.reshape(pts, (2, ))
		return (pts[0], -pts[1])
	else:
		pts[1, :] = -pts[1, :]
		return pts

def imagecoor2cartesian_center(image_shape, debug=True):
	'''
	given an image shape, return 2 functions which change the original image coordinate to centered cartesian coordinate system
	basically the origin is in the center of the image

	for example:
		if the image shape is (480, 640) and the top left point is (0, 0), after passing throught forward_map function, it returns (-320, 240)
		for the bottom right point (639, 479), it returns (319, -239)
	'''
	if debug:
		assert (istuple(image_shape) or islist(image_shape) or isnparray(image_shape)) and np.array(image_shape).size == 2, 'input image shape is not correct'

	width = image_shape[1]
	height = image_shape[0]

	def forward_map(pts, debug=True):
		if debug:
			assert is2dpts(pts), 'input 2d point is not correct'
			assert pts[0] >= 0 and pts[0] < width and isinteger(pts[0]), 'x coordinate is out of range %d should in [%d, %d)' % (pts[0], 0, width)
			assert pts[1] >= 0 and pts[1] < height and isinteger(pts[1]), 'y coordinate is out of range %d shoud in [%d, %d)' % (pts[1], 0, height)

		car_pts = imagecoor2cartesian(pts, debug=debug)
		car_pts = np.array(car_pts)
		car_pts[0] += -width/2		# shift x axis half length of width to the right
		car_pts[1] += height/2		# shigt y axis hald length of height downside
		return (car_pts[0], car_pts[1])

	def backward_map(pts, debug=True):
		if debug:
			assert is2dpts(pts), 'input 2d point is not correct'
			assert is2dpts(pts), 'input 2d point is not correct'
			assert pts[0] >= -width/2 and pts[0] < width/2 and isinteger(pts[0]), 'x coordinate is out of range %d should in [%d, %d)' % (pts[0], -width/2, width/2)
			assert pts[1] > -height/2 and pts[1] <= height/2 and isinteger(pts[1]), 'y coordinate is out of range %d shoud in (%d, %d]' % (pts[1], -height/2, height/2)

		pts = np.array(pts)
		pts[0] += width/2
		pts[1] += -height/2
		img_pts = cartesian2imagecoor(pts, debug=debug)
		return img_pts

	return forward_map, backward_map

def generate_mean_image(images_dir, save_path, debug=True, vis=False):
	'''
	this function generates the mean image over all images. It assume the image has the same size

	parameters:
			images_dir: 		path to all images
	'''
	if debug:
		assert is_path_exists(images_dir), 'the image path is not existing at %s' % images_dir
		assert is_path_exists_or_creable(save_path), 'the path for saving is not correct: %s' % save_path

	print('loading image data from %s' % images_dir)
	imagelist, num_images = load_list_from_folders(images_dir, ext_filter=['png', 'jpg', 'jpeg'], depth=None)
	print('{} images loaded'.format(num_images))

	# load the first image to see the image size
	img = Image.open(imagelist[0]).convert('L')
	width, height = img.size

	image_blob = np.zeros((height, width, num_images), dtype='float32')
	count = 0
	for image_path in imagelist:
		print('generating sharpness: processing %d/%d' % (count+1, num_images))
		img = Image.open(image_path).convert('L')
		image_blob[:, :, count] = np.asarray(img, dtype='float32') / 255
		count += 1

	mean_im = np.mean(image_blob, axis=2)
	visualize_image(mean_im, debug=debug, vis=vis, save=True, save_path=save_path)

def pil2cv_colorimage(pil_image, debug=True, vis=False):
	'''
	this function converts a PIL image to a cv2 image, which has RGB and BGR format respectively
	'''
	if debug:
		assert ispilimage(pil_image), 'the input image is not a PIL image'

	cv_image = np.array(pil_image)
	cv_image = cv_image[:, :, ::-1].copy() 			# convert RGB to BGR

	return cv_image

def chw2hwc_npimage(np_image, debug=True):
	'''
	this function transpose the channels of a numpy image from C x H x W to H x W x C
	'''
	if debug:
		assert isnparray(np_image), 'the input is not a numpy'
		assert np_image.ndim == 3 and np_image.shape[0] == 3, 'the input numpy image does not have a good dimension: {}'.format(np_image.shape)

	return np.transpose(np_image, (1, 2, 0))

def	unnormalize_npimage(np_image, debug=True):
	'''
	un-normalize a numpy image and scale it to [0, 255], uint8
	'''
	if debug:
		assert isnpimage_dimension(np_image), 'the input numpy image is not correct: {}'.format(np_image.shape)

	min_val = np.min(np_image)
	max_val = np.max(np_image)
	if math.isnan(min_val) or math.isnan(max_val):			# with nan
		assert False, 'the input image has nan'
	elif min_val == max_val:								# all same
		np_image.fill(0)
	else:													# normal case
		np_image = np_image - min_val
		np_image = np_image / (max_val - min_val)
		np_image = np_image * 255.
		if debug:
			assert np.min(np_image) == 0 and np.max(np_image) == 255, 'the value range is not right [%f, %f]' % (min_val, max_val)

	np_image = np_image.astype('uint8')

	return np_image

def concatenate_grid(image_list, im_size=[1600, 2560], grid_size=None, edge_factor=0.99, debug=True):
	'''
	concatenate a list of images automatically

	parameters:
		image_list: 		a list of numpy array
		im_size:			a tuple or list of numpy array for [H, W]
		edge_factor:		the margin between images after concatenation, bigger, the edge is smaller, [0, 1]
	'''
	if debug:
		assert islist(image_list) and all(ispilimage(image_tmp) for image_tmp in image_list), 'the input is not a list of image'
		assert issize(im_size), 'the input image size is not correct'
		if grid_size is not None:
			assert issize(grid_size), 'the input grid size is not correct'

	num_images = len(image_list)

	if grid_size is None:
		num_rows = int(np.sqrt(num_images))
		num_cols = int(np.ceil(num_images * 1.0 / num_rows))
	else:
		num_rows = grid_size[0]
		num_cols = grid_size[1]

	window_height = im_size[0]
	window_width = im_size[1]

	grid_height = int(window_height / num_rows)
	grid_width  = int(window_width  / num_cols)
	im_height   = int(grid_height   * edge_factor)
	im_width 	= int(grid_width 	 * edge_factor)
	im_channel 	= 3

	# concatenate
	image_merged = np.zeros((window_height, window_width, im_channel), dtype='uint8')
	for image_index in range(num_images):
		image_tmp = image_list[image_index]
		image_tmp = image_tmp.resize((im_width, im_height), Image.ANTIALIAS)
		image_tmp = image_tmp.convert('RGB')

		rows_index = int(np.ceil((image_index+1.0) / num_cols))			# 1-indexed
		cols_index = image_index+1 - (rows_index - 1) * num_cols	# 1-indexed
		rows_start = 1 + (rows_index - 1) * grid_height				# 1-indexed
		rows_end   = rows_start + im_height							# 1-indexed
		cols_start = 1 + (cols_index - 1) * grid_width				# 1-indexed
		cols_end   = cols_start + im_width							# 1-indexed

		image_merged[rows_start:rows_end, cols_start : cols_end, :] = np.array(image_tmp)

	return image_merged

# def crop_pts()


import pandas as pd
import numpy as np

def get_cholesky(array):
    """Get cholesky lower triangle matrix.

    Parameters
    ----------
    array: pd.DataFrame or np.array

    Returns
    -------
    array
    """
    return np.linalg.cholesky(array)

def generate_random_returns(n_days, symbol_ids = [1], mu = 1e-4, sigma = 1e-2, start = '20010101'):
    """Generate random returns normally distributed.

    Parameters
    ----------
    n_days: int

    symbol_ids: list

    mu: float

    sigma: float

    start: str, Datetime-like

    Returns
    -------
    pd.DataFrame
    """
    n_sids = len(symbol_ids)

    returns = mu + sigma * np.random.randn(n_days, n_sids)

    # Wrap in Dataframe
    dates = pd.date_range(start = start, freq = 'B', periods=n_days)
    returns_df = pd.DataFrame(data = returns, index = dates, columns=symbol_ids)

    return returns_df

def _generate_random_ints(n_sids):
    """Generate a list of random integers.

    Parameters
    ----------
    n_sids: int

    Returns
    -------
    list

    Notes
    -----
    Might contain duplicates.
    """
    symbol_ids = []

    for _ in range(n_sids):

        symbol_ids.append(np.random.randint(low = 1, high = n_sids * 100))

    return symbol_ids

def generate_random_symbols(n_sids):
    """Generate unique random symbol ids.

    Parameters
    ----------
    n_sids: int

    Returns
    -------
    list
    """
    symbol_ids = []

    while len(symbol_ids) != n_sids:

        symbol_ids = _generate_random_ints(n_sids = n_sids)
        symbol_ids = list(set(symbol_ids))
        symbol_ids = sorted(symbol_ids)

    return symbol_ids