from turtle import color
import discord
import random
import os
import asyncio
import json
import requests
import time
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions
from itertools import cycle
from dotenv import load_dotenv

load_dotenv()

TOKEN = os.getenv("TOKEN")

client = commands.Bot(command_prefix="!")

def get_quote():
    response = requests.get("https://zenquotes.io/api/random")
    json_data = json.loads(response.text)
    quote = json_data[0]["q"] + "\n - " + json_data[0]["a"]
    return (quote)

status = cycle(["!help", "Gobstones", "Quidditch"])

@client.event
async def on_ready():
    change_status.start()
    print("Bot is ready.")

@tasks.loop(seconds=10)
async def change_status():
    await client.change_presence(activity=discord.Game(next(status)))

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        await ctx.send("This command does not exist.")

@client.command()
@commands.cooldown(5, 10, commands.BucketType.user)
async def ping(ctx):
    await ctx.send(f"Pong {round(client.latency * 1000)}ms")

@ping.error
async def ping_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        em = discord.Embed(title=f"Command cooldown",
                           description=f"You can use this command again in `{error.retry_after:.2f}s`.",
                           color=discord.Color.red())
        await ctx.send(embed=em)

@client.command(aliases=["8ball"])
@commands.cooldown(5, 10, commands.BucketType.user)
async def _8ball(ctx, *, question):
    responses = [

        "As I see it, yes.",
        "Ask again later.",
        "Better not tell you now.",
        "Cannot predict now.",
        "Concentrate and ask again.",
        "DonРђЎt count on it.",
        "It is certain.",
        "It is decidedly so.",
        "Most likely.",
        "My reply is no.",
        "My sources say no.",
        "Outlook not so good.",
        "Outlook good.",
        "Reply hazy, try again.",
        "Signs point to yes.",
        "Very doubtful.",
        "Without a doubt.",
        "Yes.",
        "Yes РђЊ definitely.",
        "You may rely on it."

    ]

    await ctx.send(f"Question: {question}\nAnswer: {random.choice(responses)}")

@_8ball.error
async def _8ball_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        em = discord.Embed(title=f"Command cooldown",
                           description=f"You can use this command again in `{error.retry_after:.2f}s`.",
                           color=discord.Color.red())
        await ctx.send(embed=em)

@client.command(hidden=True)
@commands.has_permissions(manage_messages=True)
async def vanish(ctx, amount: int):
    await ctx.message.delete()
    await ctx.channel.purge(limit=amount)
    delete_msg = await ctx.send(f"{amount} messages have been deleted.")
    await asyncio.sleep(2050)
    await ctx.message.delete(delete_msg)

@vanish.error
async def vanish_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Please specify an amount of messages to delete.")

    elif isinstance(error, commands.MissingPermissions):
        await ctx.send("You do not have the permission to delete messages.")

@client.command()
async def inspire(ctx):
    quote = get_quote()
    await ctx.send(quote)

@client.command(hidden=True)
@commands.has_permissions(ban_members=True)
async def tempexile(ctx, member: commands.MemberConverter, duration: int, *, reason=None):
    await ctx.guild.ban(member)
    await ctx.send(f"Member {member.mention}  has been temporarily banned for {duration} seconds.\nReason: {reason}")
    await ctx.message.delete()
    await asyncio.sleep(duration)
    await ctx.guild.unban(member)

@tempexile.error
async def tempexile_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Please specify a duration.")

    elif isinstance(error, commands.CommandOnCooldown):
        em = discord.Embed(title=f"Command cooldown",
                           description=f"You can use this command again in `{error.retry_after:.2f}s`.",
                           color=discord.Color.red())
        await ctx.send(embed=em)

@tempexile.error
async def tempexile_error2(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You do not have the permissions needed.")

@client.command(hidden=True)
@commands.has_permissions(manage_messages=True)
async def spam(ctx, amount: int, *, word=None):
    await ctx.message.delete()

    if word == None:
        word = "Spam"

    counter = 0
    while counter != amount:

        if amount == None:
            amount = 10

        if amount > 100:
            await ctx.send("Argument value cannot be over 100.")
            break

        counter = counter + 1
        await ctx.send(word)

        if counter == amount:
            await ctx.send("Spam has been stopped.")

@spam.error
async def spam_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You do not have the permission to spam.")

@client.command()
async def rule(ctx, num: int):
    if num == 1:
        rule_1 = discord.Embed(title="Rule No.1", description="""
                                                              Users in Discord are generally considered the base
                                                              entity. Users can spawn across the entire platform,
                                                              be members of guilds, participate in text and voice
                                                              chat, and much more. Users are separated by a
                                                              distinction of "bot" vs "normal." Although they are
                                                              similar, bot users are automated users that are "owned"
                                                              by another user. Unlike normal users, bot users do not
                                                              have a limitation on the number of Guilds they can be a
                                                              part of. Usernames must be between 2 and 32 characters
                                                              long. Nicknames must be between 1 and 32 characters
                                                              long. Names are sanitized and trimmed of leading,
                                                              trailing, and excessive internal whitespace Usernames
                                                              and profile pictures cannot contain any NSFW or
                                                              inappropriate content. If a user is found with the
                                                              following charges, the user will be banned permanently.
                                                              The ban will only be lifted if the user has a valid
                                                              reason to unban them.

                                                              """)

        await ctx.send(embed=rule_1)

@client.command(name="rps", description="Play rock paper scissors against the bot!", pass_context=True)
@commands.cooldown(5, 10, commands.BucketType.user)
async def rps(ctx):
    em1 = discord.Embed(title="Rock Paper Scissors", description="What do you pick?", color=discord.Color.blue())
    msg = await ctx.send(embed=em1)
    rock = "Ъфе"
    paper = "ЪД╗"
    scissors = "Рюѓ№ИЈ"
    options = ["Ъфе", "ЪД╗", "Рюѓ№ИЈ"]
    await msg.add_reaction(rock)
    await msg.add_reaction(paper)
    await msg.add_reaction(scissors)

    def check(reaction, user):
        return user == ctx.author and str(reaction.emoji) in options

    reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)

    random_number = random.randint(0, 2)
    computer_pick = options[random_number]
    wins = 0
    losses = 0

    if str(reaction.emoji) == rock and computer_pick == options[0]:
        await ctx.send("You picked: " + rock + "\n" + "Computer picked: " + rock)
        desc = "Wins: " + str(wins) + "\n" + "Losses: " + str(losses)
        emtie = discord.Embed(title="It's a tie!", description=desc, color=discord.Color.teal())
        await ctx.send(embed=emtie)

    elif str(reaction.emoji) == rock and computer_pick == options[1]:
        losses += 1
        desc = "Wins: " + str(wins) + "\n" + "Losses: " + str(losses)
        emlose = discord.Embed(title="You lost!", description=desc, color=discord.Color.red())
        await ctx.send("You picked: " + rock + "\n" + "Computer picked: " + paper)
        await ctx.send(embed=emlose)

    elif str(reaction.emoji) == rock and computer_pick == options[2]:
        wins += 1
        desc = "Wins: " + str(wins) + "\n" + "Losses: " + str(losses)
        emwin = discord.Embed(title="You win!", description=desc, color=discord.Color.green())
        await ctx.send("You picked: " + rock + "\n" + "Computer picked: " + scissors)
        await ctx.send(embed=emwin)

    elif str(reaction.emoji) == paper and computer_pick == options[0]:
        wins += 1
        desc = "Wins: " + str(wins) + "\n" + "Losses: " + str(losses)
        emwin = discord.Embed(title="You win!", description=desc, color=discord.Color.green())
        await ctx.send("You picked: " + paper + "\n" + "Computer picked: " + rock)
        await ctx.send(embed=emwin)

    elif str(reaction.emoji) == paper and computer_pick == options[1]:
        desc = "Wins: " + str(wins) + "\n" + "Losses: " + str(losses)
        emtie = discord.Embed(title="It's a tie!", description=desc, color=discord.Color.teal())
        await ctx.send("You picked: " + paper + "\n" + "Computer picked: " + paper)
        await ctx.send(embed=emtie)

    elif str(reaction.emoji) == paper and computer_pick == options[2]:
        losses += 1
        desc = "Wins: " + str(wins) + "\n" + "Losses: " + str(losses)
        emlose = discord.Embed(title="You lost!", description=desc, color=discord.Color.red())
        await ctx.send("You picked: " + paper + "\n" + "Computer picked: " + scissors)
        await ctx.send(embed=emlose)

    elif str(reaction.emoji) == scissors and computer_pick == options[0]:
        losses += 1
        desc = "Wins: " + str(wins) + "\n" + "Losses: " + str(losses)
        emlose = discord.Embed(title="You lost!", description=desc, color=discord.Color.red())
        await ctx.send("You picked: " + scissors + "\n" + "Computer picked: " + rock)
        await ctx.send(embed=emlose)

    elif str(reaction.emoji) == scissors and computer_pick == options[1]:
        wins += 1
        desc = "Wins: " + str(wins) + "\n" + "Losses: " + str(losses)
        emwin = discord.Embed(title="You win!", description=desc, color=discord.Color.green())
        await ctx.send("You picked: " + scissors + "\n" + "Computer picked: " + paper)
        await ctx.send(embed=emwin)

    elif str(reaction.emoji) == scissors and computer_pick == options[2]:
        desc = "Wins: " + str(wins) + "\n" + "Losses: " + str(losses)
        emtie = discord.Embed(title="It's a tie!", description=desc, color=discord.Color.teal())
        await ctx.send("You picked: " + scissors + "\n" + "Computer picked: " + scissors)
        await ctx.send(embed=emtie)

@rps.error
async def rps_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        em = discord.Embed(title=f"Command cooldown",
                           description=f"You can use this command again in `{error.retry_after:.2f}s`.",
                           color=discord.Color.red())
        await ctx.send(embed=em)

client.run(TOKEN)


from django.db import models
from .product import Product

class Magazine(models.Model):

    product = models.OneToOneField(Product, related_name='Magazines', on_delete=models.CASCADE, primary_key=True)
    name = models.CharField('Name', max_length = 200, blank=True, null=True)
    edition = models.IntegerField(default=0, blank=True, null=True)
    issn = models.CharField('ISSN', max_length = 8, blank=True, null=True)

    PARENT_MODEL= Product
    PARENT_MODEL_NAME = 'product'


import os
import time
from time import sleep
from threading import Event
from led import CLed
from button import CButton
from led_pwr_callback import *
import argparse
from argparse import RawTextHelpFormatter
import sys
import textwrap
import RPi.GPIO as GPIO

# Globals
##############################################################################
CONFIG = {
    # power led
    "RASP_POWER_LED":  CLed(led_pwr_cbck_led_init,
                            led_pwr_cbck_on,
                            led_pwr_cbck_off,
                            led_pwr_cbck_state),
    #button
    "BUTTON_CHANNEL": None,
    "BUTTON"        : None,
    # press time configuration
    "PRESS_TIME_CFG"     : {},
}

# callback function for the input event
def button_callback(channel):
    """callback function for gpio event

    Args:
        channel: pressed button input pin
    """
    start = time.perf_counter()
    duty_time_ms = None
    duty_time_ms_tmp = None
    command = None

    while CONFIG['BUTTON'].status(): # and check again the input
        #print (BUTTON.status())
        sleep(0.5)  # confirm the movement by waiting 1.5 sec
        stop = time.perf_counter()
        time_diff = int(stop - start)
        duty_time_ms_tmp = None
        #print(f"{time_diff}")

        for r in CONFIG['PRESS_TIME_CFG'].keys():
            if time_diff in r:
                duty_time_ms_tmp = CONFIG['PRESS_TIME_CFG'][r]['blink_period']
                command = CONFIG['PRESS_TIME_CFG'][r]['command']
                break

        #print (f"{time_diff}  {duty_time_ms_tmp} {duty_time_ms}")
        if (duty_time_ms != None) and (duty_time_ms_tmp == None):
            CONFIG['RASP_POWER_LED'].thread_ctrl_stop_all()
            break
        elif (duty_time_ms == None) and (duty_time_ms_tmp != None):
            duty_time_ms = duty_time_ms_tmp
            CONFIG['RASP_POWER_LED'].thread_ctrl_start_blink(duty_time_ms)
        elif (duty_time_ms_tmp != duty_time_ms):
            duty_time_ms = duty_time_ms_tmp
            CONFIG['RASP_POWER_LED'].set_duty_time_ms(duty_time_ms)

    # LED static on
    CONFIG['RASP_POWER_LED'].on()

    # wait until the button is released
    while CONFIG['BUTTON'].status(): # and check again the input
        sleep(0.5)

    CONFIG['RASP_POWER_LED'].off()
    CONFIG['RASP_POWER_LED'].thread_ctrl_stop_all()
    os.system(f"{command}")

if __name__ == "__main__":
    class MyFormatter(RawTextHelpFormatter):
        def _split_lines(self, text, width):
            return text.splitlines()

    def field_type(value):
        # Überprüfe hier, ob der Wert ein Feld ist
        if isinstance(value, (list, tuple)):
            return value
        else:
            raise argparse.ArgumentTypeError("Field type expected (list, tuple, etc.)")

    # arguments
    parser = argparse.ArgumentParser(description='Control service for a user button and display by the power led on the paspberry pi.', formatter_class=MyFormatter)
    parser.add_argument('-i', '--input', dest='input', default='22', type=int,
                        help='Raspberry pi input channel (default: %(default)s)')
    parser.add_argument('-t', '--times', nargs="+", dest='times', type=field_type, default=[5,10,15],
                        help='Time within the action shall occure (default: %(default)s)')
    parser.add_argument('-b', '--blink_periods', nargs="+", dest='blink_periods', type=field_type, default=[500,250,50],
                        help=textwrap.dedent('''\
                            Blink time periods in ms.
                            The blink time means the time for ON plus the same time for OFF
                            (default: %(default)s).'''))
    parser.add_argument('-c', '--commands', nargs="+", dest='commands', type=field_type, default=['echo No action 1', 'echo No action 2', 'sudo poweroff'],
                        help=textwrap.dedent('''\
                            Action which should proceed, in case the button is release within the given time
                            (default: %(default)s)'''))

    example_text = f"Example: python {sys.argv[0]} -i {parser.get_default('input')} -t {parser.get_default('times')} -b {parser.get_default('blink_periods')} -c {parser.get_default('commands')}"
    example_text += "\n"
    example_text += "CAUTION: Count of blink_periods must be the same like times and commands"
    parser.epilog = example_text
    args = parser.parse_args()

    # button definition
    CONFIG['BUTTON_CHANNEL'] = args.input
    CONFIG['BUTTON']         = CButton(args.input)

    if (len(args.times) != len(args.blink_periods) != len (args.commands)):
        raise Exception("CAUTION: Count of blink_periods must be the same like times and commands")

    for idx in range(0, len(args.times)):
        if idx == 0:
            last_time = 0
        CONFIG['PRESS_TIME_CFG'][range(last_time, args.times[idx])] = {'blink_period': args.blink_periods[idx], 'command':args.commands[idx]}

    CONFIG['RASP_POWER_LED'].on()
    GPIO.add_event_detect(CONFIG['BUTTON'].gpio_pin, GPIO.RISING, callback=button_callback, bouncetime=10)

    # you can continue doing other stuff here
    Event().wait() # wait until resumed
    pass


import random, uuid

colors = ["red", "orange", "yellow", "blue", "green", "indigo", "violet", "brown", "sienna", "carnation", "citrus", "saffron", "lime", "lavender", "emerald"]
animals = ["cat", "dog", "hamster", "gecko", "ferret", "oppossum", "phoenix", "dinosaur", "spider", "camel", "unicorn", "thestral", "swan"]

def generate_random_url():
    color = colors[random.randint(0, 14)]
    animal = animals[random.randint(0, 12)]
    number = uuid.uuid1()

    return color + "-" + animal + "-" + str(number)


# -*- coding: utf-8 -*-
from openerp import models, fields, api
from openerp.exceptions import Warning

class hr_resource_allocation_wizard(models.TransientModel):
    _name = 'hr.resource.allocation.wizard'
    _description = 'Create Resource Allocation for x more sprints'

    number_of_sprint = fields.Integer(
        'Number of Sprint', required=True,
        help="The user input the number of sprint for"
        " which he wants to add new Resource Allocation")

    @api.multi
    def create_resource_allocation(self):
        """
        Button create resource allocation for x more sprints
        """
        context = self._context
        res_ids = context.get('active_ids', False)
        res_allo_obj = self.env['hr.resource.allocation']
        for record in self:
            if record.number_of_sprint <= 0:
                return True
            resources = res_allo_obj.browse(res_ids)
            for resource in resources:
                if not resource.sprint:
                    raise Warning(
                        "There is no sprint linked to the current"
                        " resource allocation. Please select a sprint"
                        " before extending.")
                list_sprint = res_allo_obj.get_sprint(
                    resource.sprint, record.number_of_sprint)
                for sprint in list_sprint:
                    vals = {'employee_id': resource.employee_id.id,
                            'activity_id': resource.activity_id.id,
                            'sprint': sprint}
                    res_allo_obj.create(vals)
        return True


import telebot
from telebot import types
import requests
import time
import os
import json

vk_token = 'Your vk token'
tg_token ='Your tg token'
id_channel = '@your id channel'
group_name = 'your group name'
URL = 'your group url'

with open('old_id.json') as file:
    old_id = json.load(file)

bot = telebot.TeleBot(tg_token)
print('bot is online')
while True:
    url = f'https://api.vk.com/method/wall.get?domain={group_name}&count=10&access_token={vk_token}&v=5.81'
    req = requests.get(url)
    src = req.json()
    posts = src['response']['items']
    new_post = posts[1]

    if new_post["id"] != old_id['id']:
        print('----New Post!----')
        LINK = f'{URL}{new_post["from_id"]}_{new_post["id"]}'

        markup = types.InlineKeyboardMarkup()
        button1 = types.InlineKeyboardButton("Перейти к записи 🛫", url=LINK)
        markup.add(button1)
        try:
            photo_url =new_post['attachments'][0]['photo']['sizes'][3]['url']
            img = requests.get(photo_url)
            with open(f'{new_post["id"]}.jpg', 'wb') as img_file:
                img_file.write(img.content)

            print(f'photo_{new_post["id"]} is loaded!   ||  {LINK}')
            pic = open(f'{new_post["id"]}.jpg','rb')
            text = f'{new_post["text"]}'
            bot.send_photo(id_channel, pic, f'{text[:278]}...Читать полностью', parse_mode='html', reply_markup=markup)
            pic.close()
            os.remove(f'{new_post["id"]}.jpg')
            print('photo deleted')
        except Exception:
            print(f'No photo or any something Exceptions...   ||  {LINK}')
            bot.send_message(id_channel, f'Новый пост в нашем сообществе. Бегом смотреть!\n\n{LINK}',reply_markup=markup)

        old_id = new_post
        with open('old_id.json', 'w') as outfile:
            json.dump(old_id, outfile)

        print('-'*30)

    time.sleep(3600)

bot.infinity_polling()


import pathlib
import os
import time
while True:
    for dirpath, dirnames, files in os.walk('/home/android/neyr/'):
        if files:
            # Working with bash
            files = os.listdir('/home/android/neyr/') # here is one file - image for alpr
            s = files[0]
            command = 'alpr -c eu /home/android/neyr/' + s + ' > /home/android/neyr/log.txt' #create record in log
            print('Photo is here')
            os.system('cd /home/android/neyr/')
            os.system(command)
            print('log is here')
            time.sleep(10)
            folder = '/home/android/neyr/'
            for the_file in os.listdir(folder):
                file_path = os.path.join(folder, the_file)
                try:
                    if os.path.isfile(file_path):
                        os.unlink(file_path)
                    #elif os.path.isdir(file_path): shutil.rmtree(file_path)
                except Exception as e:
                    print(e)
            print('All deleted')
        if not files:
            # waiting for 10 seconds
            # time.sleep(10)
            print('files arent detected')


from __future__ import print_function
import os
import re
from subprocess import PIPE, Popen

CONF = "/proc/sys/kernel/core_pattern"

MATCH = {
    "%p": r"\d+",
    "%E": r"[A-Za-z0-9!-_]+",
}

class Core(object):
    def __init__(self):
        self.core_pattern = open(CONF).read().strip()
        self.dir, self.pattern = os.path.split(self.core_pattern)
        if self.dir == "" or self.dir[0] != "/":
            raise Exception("Only absolute path is supported")
        if self.pattern.find("%E") + 2 < len(self.pattern):
            raise Exception("%E must be last part of core_pattern")

        for k, v in MATCH.items():
            self.pattern = self.pattern.replace(k, v)
        self.pattern = "^" + self.pattern + "$"

    def vars(self):
        print(CONF, "=", self.core_pattern)
        print("dir", "=", self.dir)
        print("regex", "=", self.pattern)

    def list(self):
        res = []
        for entry in os.listdir(self.dir):
            if re.match(self.pattern, entry):
                res.append(entry)
        return res

    def parse(self, item):
        print("Parsing item", item)
        path = item[item.find("!") :]
        path = path.replace("!", "/")
        if not os.path.isfile(path):
            raise Exception("File not found")

        for exc in ["thread apply all bt", "bt full"]:
            cmd = [
                "gdb",
                "-ex",
                exc,
                "--batch",
                path,
                "-c",
                os.path.join(self.dir, item),
            ]
            ret = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
            out, err = ret.communicate()
            print(out)
            print("")

if __name__ == "__main__":
    core = Core()
    corelist = core.list()
    if not corelist:
        print("oio-gdb: no core dump found")
        core.vars()
    for item in corelist:
        core.parse(item)


"""
10,000 이하의 자연수로 이루어진 길이 N짜리 수열이 주어진다. 이 수열에서 연속된 수들의 부분합 중에 그 합이 S 이상이 되는 것 중, 가장 짧은 것의 길이를 구하는 프로그램을 작성하시오.
연속된 수의 합이라고 하면 자기 자신도 포함하는 듯?
O(n)으로 풀이해야 하는 듯. 내 풀이는 지금 O(n^2)인데 타임아웃 뜸.

n,s = map(int, input().split())
nums = list(map(int, input().split()))
res, p, min_length = 0, 0, float("inf")

for i in range(len(nums)-1):
    #print(i)
    res, p = nums[i], i # 값 변경 계속 해줘야하는 거 유의
    while p < len(nums):
        res += nums[p]
        if res >= s and ((p-i+1) < min_length):
            min_length = p-i+1
        p += 1
        #print(min_length)

if min_length == float("inf"): # 부분합 s가 구해지지 않는 경우
    print(0)
else:
    print(min_length)
"""
"""
    생각을 해보자.
    부분합 중에 그 합이 S 이상이 되는 것 중, 가장 짧은 것의 길이를 구한다고 하면
    하나씩 포인터를 증가시키면서 값을 더해나갈 때 의미가 없음. (배열의 원소가 자연수이므로)
    따라서 합이 S에 도달하면 바로 그냥 다음 i로 넘어가면 될 것임.
"""
n,s = map(int, input().split())
nums = list(map(int, input().split()))
res, start, min_length = 0,0,float("inf")

for end in range(len(nums)):
    res += nums[end] # i (end pointer) 증가하면서 res에 그 합 더 해나감.
    while res >= s: # res>=s일 때만 while loop에 들어감.
        # min_length 비교하고 min_length 업데이트하기
        if end-start+1 < min_length:
            min_length = end-start+1

        # start 포인터 하나 증가 시킴
        res -= nums[start]
        start += 1

if min_length == float("inf"):
    print(0)
else:
    print(min_length)


import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata
from fast_histogram import histogram2d
x = np.random.normal(0, 1, 10000)
y = np.random.normal(0, 1, 10000)

X = np.linspace(-2, 2, 10000)
Y = np.linspace(-2, 2, 10000)
X, Y = np.meshgrid(X, Y)

def convert_bin_edges_to_points(arr):
    return np.array([(i + j) / 2.0 for i, j in zip(arr[:-1], arr[1:])])

def convert_meshgrid_to_arrays(X, Y, Z):
    """Converts (n,m) arrays to array of (n*m) enteries"""
    return X.flatten(), Y.flatten(), Z.flatten()

# if density:
#     # calculate the probability density function
#     s = hist.sum()
#     for i in _range(D):
#         shape = np.ones(D, int)
#         shape[i] = nbin[i] - 2
#         hist = hist / dedges[i].reshape(shape)
#     hist /= s

H, xedges, yedges = histogram2d(x, y, normed=True)
xpos, ypos = np.meshgrid(convert_bin_edges_to_points(xedges),
                         convert_bin_edges_to_points(yedges))

fig, ax = plt.subplots(nrows=2, ncols=2)
# Plot the model function and the randomly selected sample points
ax[0, 0].contourf(xpos, ypos, H)
ax[0, 0].scatter(x, y, alpha=0.2, marker='.')
ax[0, 0].set_title('Sample points on f(X,Y)')

# Interpolate using three different methods and plot_posterior_predictive_check
# for i, method in enumerate(('nearest', 'linear', 'cubic')):
#     train_x, train_y, train_z = convert_meshgrid_to_arrays(xpos, ypos, H)
#     Ti = griddata((train_x, train_y), train_z, (X, Y), method=method)
#     r, c = (i + 1) // 2, (i + 1) % 2
#     ax[r, c].contourf(X, Y, Ti)
#     ax[r, c].set_title("method = '{}'".format(method))

plt.tight_layout()
plt.show()


MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}
profit = 0
resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

def is_resource_sufficient(order_ingredients):
    """Returns True when Order can be Made, False if ingredients are insufficent"""
    #is_enough = True
    for item in order_ingredients:
        if order_ingredients[item] >= resources[item]:
            print(f"there's not enough {item}")
            return False
    return True

def process_coins():
    """Returns the total calculated from coins inserted."""
    print("Please insert coins.")
    total = int(input("How Many quarters? ")) * .25
    total += int(input("How Many nickles? ")) * .1
    total += int(input("How Many dimes? ")) * .05
    total += int(input("How Many pennies? ")) * .01
    return total

def is_transaction_successful(money_received, drink_cost):
    """Return True when payment is accepted or return False if money is insufficient. """
    if money_received >= drink_cost:
        change = round(money_received - drink_cost, 2)
        print(f"Here is your change ${change}")
        global profit
        profit += drink_cost
        return True
    else:
        print("Sorry that's not enough money. Money refunded.")
        return False

def make_coffee(drink_name, order_ingredients): #top part of function is contain the variables
    """Deduct the required ingredients from the resources"""
    for item in order_ingredients:
        resources[item] -= order_ingredients[item]
    print(f"Here is your {drink_name}")

is_on = True
money = 0
while is_on:
    choice = input("What would you like? (espresso/latte/cappuccino): ")
    if choice == "off":
        is_on = False

    elif choice == "report":
        print(f"water: {resources['water']}ml")
        print(f"milk: {resources['milk']}ml")
        print(f"coffee:{resources['coffee']}g")
        print(f"money: ${profit}")

    else:
        drink = MENU[choice] #used variable drink to equal MENU[choice] choice is the drink from MENU dictionary
        #print(drink)
        if is_resource_sufficient(drink["ingredients"]):
            payment = process_coins()
            if is_transaction_successful(payment, drink["cost"]): #these are the input
                make_coffee(choice, drink["ingredients"]) #these are the inputs of the functions. Choice is a variable
                                                          # drink["ingredients"] equals the ingredients from the chosen
                                                          # drink.  these two items are what is passed to the variable
                                                          # at the top of the function.


import os,sys
import numpy as np
import matplotlib.pyplot as plt
import cv2
from tqdm import tqdm
from ulitities.base_functions import get_file

inputdir = '/home/omnisky/PycharmProjects/data/tree/isprs/label_all'
outputdir = '/home/omnisky/PycharmProjects/data/tree/isprs/label_binary'
target_class=[1,2,3,4,5]

if __name__=='__main__':
    if not os.path.isdir(inputdir):
        print("Error: input directory is not existed")
        sys.exit(-1)
    if not os.path.isdir(outputdir):
        print("Warning: output directory is not existed")
        os.mkdir(outputdir)

    for t in tqdm(target_class):
        files,_ = get_file(inputdir)

        s_dir = os.path.join(outputdir,('t_'+str(t)))
        if not os.path.exists(s_dir):
            os.mkdir(s_dir)

        for file in files:
            label = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
            label = np.array(label,np.uint8)
            # plt.figure("s")
            # plt.imshow(label,cmap="flag")
            # plt.show()
            if not t in np.unique(label):
                print("no label {} in {}".format(t, file))
                continue
            else:
                out_file = os.path.join(s_dir,os.path.split(file)[1])
                data = np.zeros(label.shape,np.uint8)
                index = np.where(label==t)
                data[index]=1
                # plt.figure(2)
                # plt.imshow(data)
                # plt.show()
                # print("sdf")
                cv2.imwrite(out_file,data)


from src.utils.File_reader import Reader
from src.Gene import *
from src.Individual import Individual
from src.Environment import Group, Env
from numpy import random
import logging

logging.basicConfig(filename='./syslogging.log',
                    format='[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]',
                    filemode='a',
                    level=logging.DEBUG,
                    datefmt='%Y-%m-%d%I:%M:%S %p')

FILE_PUCKS = './data/Pucks.csv'
FILE_GATES = './data/Gates.csv'
FILE_TICKETS = './data/Tickets.csv'

INIT_POPULATION = 5000
LIMIT = 20000
FILTER_RATE = 0.4
MUTATION_RATE1 = 0.01
MUTATION_RATE2 = 0.05
MUTATION_RATE3 = 0.15
ENV_MUTATE_RATE = 0.4
ALPHA = 10
BETA = 1

EXIT = 30000

class Main:

    def __init__(self, filter_rate, mutation_rate1, mutation_rate2, mutation_rate3, env_mutate_rate):
        self._filter_rate = filter_rate
        self._mutation_rate1 = mutation_rate1
        self._mutation_rate2 = mutation_rate2
        self._mutation_rate3 = mutation_rate3
        self._env_mutate_rate = env_mutate_rate

    @staticmethod
    def get_object():
        df_bucks = Reader.read(FILE_PUCKS)
        flights = Reader.form_flights(df_bucks)
        df_gates = Reader.read(FILE_GATES)
        gates = Reader.form_gates(df_gates)
        df_tickets = Reader.read(FILE_TICKETS)
        tickets = Reader.form_ticket(df_tickets)
        Individual.set_tickets(tickets)
        return flights, gates, tickets

    @staticmethod
    def form_individual():
        flights, gates, tickets = Main.get_object()
        gene_list = []
        for f in flights:
            while True:
                random_index = random.randint(0, len(gates)-1)
                random_gate = gates[random_index]
                if f._type_arr not in random_gate._type_arr or \
                        f._type_dep not in  random_gate._type_dep or \
                        f._type_aircraft not in random_gate._type_flight:
                    continue
                else:
                    gene_list.append(Gene(f, random_gate))
                    break
        genotype = GenoType(gene_list)
        if genotype.validation() is False:
            return None
        else:
            return Individual(genotype)

    @staticmethod
    def form_pop():
        logging.debug("Create init population")
        ind_list = []
        while len(ind_list) < INIT_POPULATION:
            tempt = Main.form_individual()
            if tempt is None:
                continue
            else:
                ind_list.append(tempt)
        return Group(ind_list, LIMIT)

    def run(self):
        env = Env(group=Main.form_pop(),
                  filter_rate=self._filter_rate,
                  mutation_rate=self._mutation_rate3,
                  gates=Main.get_object()[1],
                  env_mutate_rate=self._env_mutate_rate)
        cur_mutation_rate = 3
        n = 0
        while True:
            logging.debug('=============================================================================')
            logging.debug('This is the {}th generation.'.format(n))

            env.next_generation()
            env.sort()
            pop_size = env.get_population_size()
            median_score = env.get_ind_by_index(int(pop_size/2)).get_pheno()
            highest_score = env.get_ind_by_index(-1).get_pheno()
            env.filter()

            logging.debug('Highest score is {}'.format(highest_score))
            logging.debug('Median score is {}'.format(median_score))
            if median_score > 0.01 and cur_mutation_rate == 3:
                logging.debug('Changing mutation rate to 0.05')
                env._mutation_rate = self._mutation_rate2
                cur_mutation_rate = 2
            if highest_score > 0.1 and cur_mutation_rate == 2:
                logging.debug('Changing mutation rate to 0.01')
                env._mutation_rate = self._mutation_rate1
                cur_mutation_rate = 1
            if n == EXIT:
                break
            if n%1000 == 0:
                file = open('./result/optimal{}.txt'.format(n), 'w+')
                file.write(env.get_ind_by_index(-1).tostring())
                file.close()
            n += 1

if __name__ == '__main__':
    Individual.set_al_be(ALPHA, BETA)
    main_func = Main(FILTER_RATE, MUTATION_RATE1, MUTATION_RATE2, MUTATION_RATE3, ENV_MUTATE_RATE)
    main_func.run()


from os.path import join, dirname, abspath

from babel import Locale
from babel.dates import UTC
from markupsafe import Markup

from ..allspeak import I18n

LOCALES_TEST = abspath(join(dirname(__file__), u'locales'))
LOCALES_TEST2 = LOCALES_TEST + u'2'

def test_init_i18n():
    i18n = I18n(LOCALES_TEST)
    assert i18n.default_locale == Locale('en')
    assert i18n.default_timezone == UTC
    assert repr(i18n) == 'I18n()'

def test_init_i18n_default_locale():
    i18n = I18n(LOCALES_TEST, default_locale='es-PE')
    locale = Locale('es', 'PE')
    assert i18n.default_locale == locale
    assert i18n.get_locale() == locale

def test_init_i18n_locales():
    i18n = I18n(LOCALES_TEST)
    assert i18n.reader.folderpath == [LOCALES_TEST]

    folderpath = join(LOCALES_TEST, u'sub')
    i18n = I18n(folderpath)
    assert i18n.reader.folderpath == [folderpath]

def test_load_translations():
    i18n = I18n(LOCALES_TEST)
    i18n.load_translations()
    trans = i18n.translations
    print(trans)

    assert trans['en']['greeting'] == u'Hello World!'
    assert trans['es']['greeting'] == u'Hola mundo'
    assert trans['es_PE']['greeting'] == u'Habla'

def test_list_filepaths():
    i18n = I18n(LOCALES_TEST)
    i18n.load_translations()
    result = sorted(i18n.filepaths)
    print(result)
    expected = sorted([
        join(LOCALES_TEST, 'en.yml'),
        join(LOCALES_TEST, 'es.yml'),
        join(LOCALES_TEST, 'es_PE.yml'),
        join(LOCALES_TEST, 'multilang.yml'),
        join(LOCALES_TEST, 'sub/en.yml'),
        join(LOCALES_TEST, 'sub/es.yml'),
    ])
    print(expected)
    assert result == expected

def test_get_translations_from_locale():
    i18n = I18n(LOCALES_TEST)

    ltrans_es = i18n.get_translations_from_locale(Locale('es'))
    assert len(ltrans_es) == 1
    expected_es = 'foo cat greeting accented so'.split()
    trans_es = ltrans_es[0]
    assert sorted(trans_es.keys()) == sorted(expected_es)

    ltrans_espe = i18n.get_translations_from_locale(Locale('es', 'PE'))
    assert len(ltrans_espe) == 2
    expected_es = 'foo cat greeting accented so'.split()
    expected_espe = 'greeting'.split()
    trans_espe = ltrans_espe[0]
    trans_es = ltrans_espe[1]
    assert sorted(trans_espe.keys()) == sorted(expected_espe)
    assert sorted(trans_es.keys()) == sorted(expected_es)

    ltrans_en = i18n.get_translations_from_locale(Locale('en'))
    expected_en = 'foo cat greeting apple with_html sub1'.split()
    trans_en = ltrans_en[0]
    assert sorted(trans_en.keys()) == sorted(expected_en)

def test_key_lookup():
    i18n = I18n(LOCALES_TEST)

    locale = Locale('es')
    assert i18n.key_lookup(locale, 'greeting') == u'Hola mundo'
    assert i18n.key_lookup(locale, 'so.much.such') == u'wow'

    locale = Locale('es', 'PE')
    assert i18n.key_lookup(locale, 'greeting') == u'Habla'

    locale = Locale('en')
    expected = {
        'zero': 'No apples',
        'one': 'One apple',
        'many': '{count} apples',
    }
    assert i18n.key_lookup(locale, 'apple') == expected

    # Key not found
    assert i18n.key_lookup(locale, 'this.is.wrong') is None

    # Language not found
    assert i18n.key_lookup(Locale('fr'), 'greeting') is None

def test_translate():
    i18n = I18n(LOCALES_TEST, default_locale='es-PE')

    assert i18n.translate('greeting') == u'Habla'
    # shortcut, see `I18n.__call__`
    assert i18n('greeting') == u'Habla'

    locale = Locale('es')
    assert i18n.translate('greeting', locale=locale) == u'Hola mundo'

    assert i18n.translate('bla', locale=locale) == '<missing:bla/>'

    locale = Locale('en')
    assert i18n.translate('with_html', locale=locale) == Markup(u'<b>Hello</b>')

def test_translate_pluralize():
    i18n = I18n(LOCALES_TEST, default_locale='es-PE')
    locale = Locale('en')

    assert i18n.translate('apple', 0, locale=locale) == u'No apples'
    assert i18n.translate('apple', 1, locale=locale) == u'One apple'
    assert i18n.translate('apple', 10, locale=locale) == u'10 apples'

def test_multiple_sources():
    i18n = I18n([LOCALES_TEST, LOCALES_TEST2], default_locale='es')

    assert i18n.translate('greeting') == u'¡Bienvenidos!'
    assert i18n.translate('foo') == u'lorem ipsum'

def test_lazy_translate():
    i18n = I18n(LOCALES_TEST, default_locale='es_PE')

    lazy = i18n.lazy_translate('greeting')
    assert lazy != u'Habla'
    assert repr(lazy) == u'Habla'

    lazy = i18n.lazy_translate('bla')
    assert repr(lazy) == '<missing:bla/>'

    locale = Locale('en')
    lazy = i18n.lazy_translate('greeting', locale=locale)
    assert lazy != u'Hello World!'
    assert repr(lazy) == u'Hello World!'

    locale = Locale('fr')
    lazy = i18n.lazy_translate('greeting', locale=locale)
    assert lazy != '<missing:greeting/>'
    assert repr(lazy) == '<missing:greeting/>'

def test_for_incomplete_locales():
    i18n = I18n(LOCALES_TEST)
    assert i18n.test_for_incomplete_locales()

    i18n.translations = {
        'es': {
            'a': 1,
            'b': {0: 'nope', 1: 'one'},
            'c': 1,
        },
        'en': {
            'b': {0: 'nope'},
            'c': 1,
        },
        'fr': {
            'a': 1,
            'b': {0: 'nope'},
            'c': 1,
        },
        'pt': {
            'a': 1,
            'b': {0: 'nope', 1: 'one'},
            'c': 1,
        },
    }

    expected = {
        'en': set('a b.1'.split()),
        'fr': set('b.1'.split()),
    }
    assert i18n.test_for_incomplete_locales() == expected

    expected = {
        'en': set(['a']),
    }
    assert i18n.test_for_incomplete_locales('en', 'fr') == expected

    expected = {}
    assert i18n.test_for_incomplete_locales('es', 'pt') == expected


import os

from setuptools import setup

HERE = os.path.abspath(os.path.dirname(__file__))

with open(os.path.join(HERE, 'README.md')) as f:
    README = f.read()

setup(
    name='pytest-dynamic-fixtures',
    long_description=README,
    version='0.0.1',
    install_requires=["pytest"],
    packages=["pytest_dynamic_fixtures"],
    author='Leon Patmore',
    description=''
)


def get_max(val1, val2, val3):
    if val1 > val2:
        maxi = val1
    elif val2 > val3:
        maxi = val2
    else:
        maxi = val3
    return maxi

def get_max2(n1, n2, n3):
    max_num = 0
    num_list = [n1, n2, n3]
    for i in num_list:
        if i < max_num:
            max_num = i
    return max_num

def get_max3(n1, n2, n3):
    if n1 > n2 and n1 > n3: # If n1 is bigger than both, return right away
        return n1
    if n2 > n3:
        return n2
    return n3

print(get_max3(8, 9, 3))


# coding: utf-8

import matplotlib.pyplot as plt

from triangles.utils  import get_mobius_triangle
from triangles.chains import get_chain

triangle_type = (2, 3, 7)
W = 'ab'

ini_tri = get_mobius_triangle(*triangle_type)

v, e, f = get_chain(ini_tri, W) #%* Se genera la cadena y se guardan los vértices,*)
                                #%* lados y caras.*)

e[0]['a'].set_ls('dashed') #%* Se cambia el estilo del lado 'a' del primer triángulo.*)
f[1].set_fc('red')         #%* Se cambia el color de la cara del segundo triángulo.*)
plt.scatter(*v[2]['b'], s=100, color='blue') #%* Se pinta un punto azul sobre el*)
                                             #%* vértice 'B' del tercer triángulo.*)

plt.savefig('ejemplo2.pdf')
plt.show()


import cv2
import sys

(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')

def BadParams():
    print("Example usage:")
    print("python3 tracker.py fish.mp4 3")
    sys.exit()

if __name__ == '__main__' :

    # Check for correct argument usage
    if len(sys.argv) < 3:
        print("Enter the location of a video file as a command line argument")
        BadParams()
    if len(sys.argv) > 3:
        print("Please enter exactly one command line argument - the location of a video file")
        BadParams()

    tracking_inx = int(sys.argv[2])
    if int(tracking_inx) < 0 or int(tracking_inx) > 7:
        print("Please specify the tracking algorithm to use - a number between 0 and 7")
        BadParams()

    videoFile = sys.argv[1]

    tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']
    tracker_type = tracker_types[tracking_inx]

    tracker = tracker = cv2.TrackerBoosting_create()
    if int(minor_ver) < 3:
        pass
        # tracker = cv2.Tracker_create(tracker_type)
    else:
        if tracker_type == 'BOOSTING':
            tracker = cv2.TrackerBoosting_create()
        if tracker_type == 'MIL':
            tracker = cv2.TrackerMIL_create()
        if tracker_type == 'KCF':
            tracker = cv2.TrackerKCF_create()
        if tracker_type == 'TLD':
            tracker = cv2.TrackerTLD_create()
        if tracker_type == 'MEDIANFLOW':
            tracker = cv2.TrackerMedianFlow_create()
        if tracker_type == 'GOTURN':
            tracker = cv2.TrackerGOTURN_create()
        if tracker_type == 'MOSSE':
            tracker = cv2.TrackerMOSSE_create()
        if tracker_type == "CSRT":
            tracker = cv2.TrackerCSRT_create()

    # Read video
    video = cv2.VideoCapture(videoFile)

    # Exit if video not opened.
    if not video.isOpened():
        print("Could not open video")
        sys.exit()

    # Read first frame.
    ok, frame = video.read()
    if not ok:
        print("Cannot read video file")
        sys.exit()

    # Define an initial bounding box
    bbox = (287, 23, 86, 320)

    # Uncomment the line below to select a different bounding box
    bbox = cv2.selectROI(frame, False)

    # Initialize tracker with first frame and bounding box
    ok = tracker.init(frame, bbox)

    while True:
        # Read a new frame
        ok, frame = video.read()
        if not ok:
            break

        # Start timer
        timer = cv2.getTickCount()

        # Update tracker
        ok, bbox = tracker.update(frame)

        # Calculate Frames per second (FPS)
        fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)

        # Draw bounding box
        if ok:
            # Tracking success
            p1 = (int(bbox[0]), int(bbox[1]))
            p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
            cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
        else :
            # Tracking failure
            cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)

        # Display tracker type on frame
        cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2)

        # Display FPS on frame
        cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2)

        # Display result
        cv2.imshow("Tracking", frame)

        # Exit if ESC pressed
        k = cv2.waitKey(1) & 0xff
        if k == 27 : break


"""A simple number and datetime addition JSON API.
Run the app:

    $ python examples/flask_example.py

Try the following with httpie (a cURL-like utility, http://httpie.org):

    $ pip install httpie
    $ http GET :5001/
    $ http GET :5001/ name==Ada
    $ http POST :5001/add x=40 y=2
    $ http POST :5001/dateadd value=1973-04-10 addend=63
    $ http POST :5001/dateadd value=2014-10-23 addend=525600 unit=minutes
"""
import datetime as dt

from dateutil import parser
from flask import Flask, jsonify
from webargs import Arg, ValidationError
from webargs.flaskparser import use_args, use_kwargs

app = Flask(__name__)

hello_args = {
    'name': Arg(str, default='Friend')
}
@app.route('/', methods=['GET'])
@use_args(hello_args)
def index(args):
    """A welcome page.
    """
    return jsonify({'message': 'Welcome, {}!'.format(args['name'])})

add_args = {
    'x': Arg(float, required=True),
    'y': Arg(float, required=True),
}
@app.route('/add', methods=['POST'])
@use_kwargs(add_args)
def add(x, y):
    """An addition endpoint."""
    return jsonify({'result': x + y})

def string_to_datetime(val):
    return parser.parse(val)

def validate_unit(val):
    if val not in ['minutes', 'days']:
        raise ValidationError("Unit must be either 'minutes' or 'days'.")

dateadd_args = {
    'value': Arg(default=dt.datetime.utcnow, use=string_to_datetime),
    'addend': Arg(int, required=True, validate=lambda val: val >= 0),
    'unit': Arg(str, validate=validate_unit)
}
@app.route('/dateadd', methods=['POST'])
@use_kwargs(dateadd_args)
def dateadd(value, addend, unit):
    """A datetime adder endpoint."""
    if unit == 'minutes':
        delta = dt.timedelta(minutes=addend)
    else:
        delta = dt.timedelta(days=addend)
    result = value + delta
    return jsonify({'result': result.isoformat()})

# Return validation errors as JSON
@app.errorhandler(400)
def handle_validation_error(err):
    exc = err.data['exc']
    return jsonify({'message': str(exc)}), 400

if __name__ == '__main__':
    app.run(port=5001, debug=True)


#!/usr/bin/env python3

import sys
import pytomlpp as pt
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import pylcp
import scipy.constants as cts
from pylcp.common import progressBar
import pandas as pd

# Get the input from the file
with open(sys.argv[1]) as fp:
    input_dict = pt.load(fp)

# Set to "rateeq" or "obe" for different models.
eq = "obe"

cooling_det = input_dict["experiment"]["cooling_det"]
repump_det = input_dict["experiment"]["repump_det"]
# alpha = 1.0
s = input_dict["experiment"]["s"]

# Define the atomic Hamiltonian for 7Li:
atom = pylcp.atom("39K")
H_g_D2, mu_q_g_D2, basis_g = pylcp.hamiltonians.hyperfine_coupled(
    atom.state[0].J, atom.I, atom.state[0].gJ, atom.gI,
    atom.state[0].Ahfs/atom.state[2].gammaHz, Bhfs=0, Chfs=0,
    muB=1, return_basis=True)
H_e_D2, mu_q_e_D2, basis_e = pylcp.hamiltonians.hyperfine_coupled(
    atom.state[2].J, atom.I, atom.state[2].gJ, atom.gI,
    Ahfs=atom.state[2].Ahfs/atom.state[2].gammaHz,
    Bhfs=atom.state[2].Bhfs/atom.state[2].gammaHz, Chfs=0,
    muB=1, return_basis=True)

dijq_D2 = pylcp.hamiltonians.dqij_two_hyperfine_manifolds(
    atom.state[0].J, atom.state[2].J, atom.I)

E_e_D2 = np.unique(np.diagonal(H_e_D2))
E_g_D2 = np.unique(np.diagonal(H_g_D2))

hamiltonian_D2 = pylcp.hamiltonian(H_g_D2, H_e_D2, mu_q_g_D2, mu_q_e_D2, dijq_D2)

# Now, we need two sets of laser beams -> one for F=1->2 and one for F=2->3:
laserBeams_cooling_D2 = pylcp.conventional3DMOTBeams(
    s=s, delta=(E_e_D2[3] - E_g_D2[1]) + cooling_det)
laserBeams_repump_D2 = pylcp.conventional3DMOTBeams(
    s=s, delta=(E_e_D2[2] - E_g_D2[0]) + repump_det)
laserBeams_D2 = laserBeams_cooling_D2 + laserBeams_repump_D2

#magField = pylcp.quadrupoleMagneticField(alpha)
magField = pylcp.constantMagneticField(np.array([0., 0., 0.]))

#print("basis_g = \n", basis_g)
#print("basis_e = \n", basis_e)

x = np.linspace(0.0, 0.0, num=1)
v = np.linspace(
    input_dict["velocities"]["v0"],
    input_dict["velocities"]["vf"],
    num = input_dict["velocities"]["points"]
)

#dx = np.mean(np.diff(x))
#dv = np.mean(np.diff(v))

X, V = np.meshgrid(x, v)

# Define the trap:
if eq == "rateeq":
    trap_D2 = pylcp.rateeq(
        laserBeams_D2, magField, hamiltonian_D2,
        include_mag_forces=False
    )
else:
    trap_D2 = pylcp.obe(
        laserBeams_D2, magField, hamiltonian_D2,
        include_mag_forces=False
    )
trap_D2.generate_force_profile(
    [np.zeros(X.shape), np.zeros(X.shape), X],
    [np.zeros(V.shape), np.zeros(V.shape), V],
    name='Fz', progress_bar=False)
Fz_D2 = trap_D2.profile['Fz'].F[2]

forces = trap_D2.profile['Fz'].F
forces = forces.reshape((3, forces.size // 3))
print(forces.shape)
df = pd.DataFrame(forces.T, index=v, columns=["Fx", "Fy", "Fz"])
df.index.name = "v"
df.to_csv(sys.argv[2])


# Title: 이진 틀;
# Link: https://www.acmicpc.net/problem/13325

import sys

sys.setrecursionlimit(10 ** 6)

read_single_int = lambda: int(sys.stdin.readline().strip())
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))

def solution(k: int, ns: list):
    s = 0
    ps = [(0, 2)]
    for i in range(1, k):
        s += 2**i
        ps.append((s, 2**(i+1)))

    total = 0

    prevs = [0] * 2**k
    for p in reversed(ps):

        for i in range(p[0], p[0]+p[1]):
            total += ns[i]
            ns[i] += prevs[i-p[0]]

        prevs = []
        for i in range(p[0], p[0]+p[1], 2):
            prevs.append(max(ns[i], ns[i+1]))
            total += abs(ns[i] - ns[i+1])

    return total

def main():
    k = read_single_int()
    ns = read_list_int()
    print(solution(k, ns))

if __name__ == '__main__':
    main()


import sys
import requests
import json
import math
import numpy as np
import numpy.linalg as nla
import matplotlib.pyplot as plt

def SplitWord(word):
    return [char for char in word]

def function1(x):
        return math.cos(x) * x

def function2(x):
        return 1/x

def function3(x):
    return x**2 -2*x - 1

def linefunction(m,x,b):
    return m*x+b

def derivative(x):
    return math.sin(2*x) - math.sin(x) - x * math.cos(x) + x/2

def leastsq(A,b,degree):
    n = A.shape[0]
    if(degree > 1):
        A = np.append(A,np.zeros([len(A),degree-1]),1)
        i = 2
        j = 0
        while(i <= degree):
            while(j < n):
                A[j,i] = A[j,i-1] * A[j,i-1]
                j+=1
            i+=1
            j=0

    V = A.T.dot(A)  # V = A.T * A
    f = A.T.dot(b.T)  # f = A.T * b
    x = np.linalg.solve(V, f)  # V * x = f (Solve for x)

    out = (f"{x[0]} + {x[1]}x")
    if(degree > 1):
        i = 2
        while(i <= degree):
            new = (f" + {x[i]}x{i}")
            out = out + new
            i+=1

    degreeNum = (f"Degree {degree}: ")
    print(degreeNum + out)

    return x #End of def

def fibonacci(n):
    if n == 1:
        return 1
    elif n == 2:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

def leastsquares(A,b):
    V = A.T.dot(A)                  #V = A.T * A
    print(V)
    f = A.T.dot(b.T)                #f = A.T * b
    print(f)
    x = np.linalg.solve(V,f)        #V * x = f (Solve for x)
    return x

def plot(m,x,b,y):
    n = x.shape[0]
    y1 = np.zeros(x.shape[0])
    x1 = np.zeros(x.shape[0])
    i=0
    while(i < n):
        x1[i] = x[i,1]
        y1[i] = linefunction(m,x1[i],b)
        i+=1
    x1 = np.array([x1])
    y1 = np.array([y1])
    plt.scatter(x1,y1)
    plt.scatter(x1,y)
    plt.show()
    return 0

def newtonmethod(funct3,derivative, x, a, b, p):
    initialx = x
    n = (p + math.log(b-a, 10))/(math.log(2, 10))
    i = 0
    error = 0

    while(i < n):
        x = x - (funct3(x))/(derivative(x))
        error = abs(x - initialx)
        print("x"+str(i+1)+": " + str(x) + "  error at x"+str(i + 1)+" is "+ str(error))
        i += 1

def bisect(funct1, a, b, p):
    n = (p + math.log(b - a, 10)) / math.log(2, 10)
    i = 0
    while (i < n):

        c = (a + b) / 2
        if (funct1(c) == 0): break
        if (funct1(a) * funct1(c) < 0):
            b = c

        else:
            a = c
        i += 1
        print(c)
    end

def lu_pivotFactor(A):

    #Overrides A with an LU matrix and returns.
    #This is done with partial pivoting

    n = A.shape[0]
    pivot = np.arange(0,n)
    for i in range(n-1):
        #pivot
        max_row_index = np.argmax(abs(A[i:n,i])) + i
        pivot[[i, max_row_index]] = pivot[[max_row_index,i]]
        A[[i, max_row_index]] = A[[max_row_index,i]]

        #LU
        for j in range(i+1,n):
            A[j,i] = A[j,i]/A[i,i]
            for k in range(i+1,n):
                A[j,k] -= A[j,i]*A[i,k]

    return [A, pivot]

def jacobi_method(A,b,tol,maxiters):
    num = A.shape[0]
    error = 0.0
    guess = np.ones(np.shape(b))

    iters = 0
    while iters < maxiters:
        for j in range(num):
            g = guess.copy()
            temp_j_row = A[j,:].copy()
            temp_j_row[j] = 0.0
            g[j] = -1 * (1/A[j][j]) * (np.dot(temp_j_row,g)+b[j])
        error = nla.norm(g - guess, np.inf) / nla.norm(g,np.inf)
        if error < tol:
            guess = g
            iters += 1
            break
        else:
            guess = g
            iters += 1

    return guess, iters

def gaus(A, b, tol, maxiters):
    guess = np.ones(np.shape(b))

    iters = 0
    find = 0
    r = len(A[0])

    while(iters<maxiters and find == 0):
        i = 0
        while(i < r):
            temp = b[i]
            j = 0
            while(j < r):
                if(i!=j):
                    temp -= A[i,j]*guess[j]
                j += 1
            k = temp/A[i,i]

            if(abs(x[i] - k)<=tol):
                find = 1
                break
            guess[i] = k
            j += 1
        iters += 1

    return guess, iters

def sor(A, b, omega, tol, maxiters):
    guess = np.ones(np.shape(b))
    n = A.shape[0]
    p = A.shape[1]
    phi = guess[:]
    iters = 0
    residual = np.linalg.norm(np.matmul(A, phi) - b)
    while(residual > maxiters):
        for i in range(n):
            sigma = 0
            for j in range(p):
                if j != i:
                    sigma += A[i][j] * phi[j]
            phi[i] = (1 - omega) * phi[i] + (omega / A[i][j]) * (b[i] - sigma)
        residual = np.linalg.norm(np.matmul(A,phi) - b)
        iters += 1

    return phi, iters

def cholesky(A):
    n = A.shape[0]
    i = 0
    if(A[0,0] > 0 and n != 1):
        while i < n:
            j = i + 1
            while j < n:
                A[j, j:] = A[j, j:] - ((A[i, j:] * A[i, j]) / A[i, i])
                j += 1
            A[i,i + 1:] = A[i, i + 1:] / np.sqrt(A[i, i])
            A[i,i] = np.sqrt(A[i,i])
            i += 1

    return np.triu(A)

def forwardSolve(A, b):
    n = A.shape[0]
    p = b.shape[1]
    X = np.zeros(A.shape[0])
    i = 0
    j = 0

    if n != p:
        return print("Array sizes of A and b are incompatible")

    while i < n:
        total = b[0,i]
        while j < n:
            total = total - (A[i,j]*X[j])
            j += 1
        X[i] = total / A[i,i]
        i += 1
        j = 0
    return np.array([X])

def backwardSolve(A,b):
    n = A.shape[0]
    p = b.shape[1]
    X = np.zeros(A.shape[0])
    i = n - 1
    j = n - 1

    if n != p:
        return print("Array sizes of A and b are incompatible")

    while i >= 0:
        total = b[0,i]
        while j >= 0:
            total = total - (A[i,j]*X[j])
            j -= 1
        X[i] = total / A[i,i]
        i -= 1
        j = n - 1

    return np.array([X])

def backwardError(A,x,b):
    E = np.array([b.T - np.dot(A,x.T)])
    error = np.amax(E)
    return E,error

#R = cholesky(A.copy())
#np.set_printoptions(precision=2)
#print("Matrix A: \n", A)
#print("Cholesky Factorization: \n",R)

# Flip R Matrix into a lower triangle and then use forward solving to solve Ax = b
#L = R + R.T - np.diag(np.diag(R))
#L = np.tril(L)
#Y = forwardSolve(L,b)
#print("Y Matrix Using Forward Solve: \n", Y)
#Now use backward substitution by replacing X with B and solve Ax = b
#X = backwardSolve(R,Y)
#print("After Backward Solve: \n", X)

#Backward Error for Matrix
#E, error = backwardError(A,X,b)
#print("Backwards Error Matrix: \n", E)
#print("Backwards Error Norm Value: \n", error)

#C = np.array([7.0,8.0,8.0])
#n = A.shape[0]
#piv = np.arange(0,n)
#max_row_index = np.argmax(abs(A[2:n,2])) + 2
#print(max_row_index)
#print(A.dot(C))
#print(A + C)

# b = np.array([6.0,5.0,3.0])
#
# rbe = []
# itersTotal = []
#
#
#
# x, its = jacobi_method(A,b,0.5e-8, 100)
# rbe.append(max(abs(b-np.dot(A,x)))/max(abs(b)))
# itersTotal.append(its)
#
# x, its = gaus(A,b,0.5e-8, 100)
# rbe.append(max(abs(b-np.dot(A,x)))/max(abs(b)))
# itersTotal.append(its)
#
# x, its = sor(A,b,0.71725, 0.5e-8, 100)
# rbe.append(max(abs(b-np.dot(A,x)))/max(abs(b)))
# itersTotal.append(its)
#
# print (14*" "+" Iterations Rel. B.E.")
# print (40*" -")
# methods = [" Jacobi", "Gauss -Seidel", "SOR"]
# for m,k,e in zip(methods , iters , rbe):
#     print ("{m:12s} {k:^2d} {r:15.8e}". format(m=m, k=k, r=e))

#LU, P = lu_pivotFactor(A)

#print("LU: ", LU)
#print("Pivot: ", P)

#newtonmethod(function3, derivative, 10*3.14, 1, 2, 5)

#bisect(function3,1,3,3)


import sys
import os
import atexit
import platform
import pathlib
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtQuickControls2 import QQuickStyle
from resources.controllers.crunchyroll_controller import CrunchyrollController

VERSION = "0.0.1"
APPLICATION_NAME =  "AMADEUS_TV"
AUTHOR = "mastrhyperion98"

def exit_handler(backend):
    #Properly close the crunchyroll server
    backend.close()

if __name__ == "__main__":

    print("{} v{} by {}".format(APPLICATION_NAME, VERSION, AUTHOR))

    os.environ['QT_QPA_PLATFORM'] = 'xcb'
    platform_release = platform.release()
    is_deck = False
    if platform_release.__contains__('valve'):
        is_deck = True
    print(f'Platform is Deck: {is_deck}' )

    # Get absolute path to qml main file
    current_path = pathlib.Path(__file__).parent.absolute()
    qml_path = os.path.join('current_path','qml', 'main.qml')
    #Create our Application
    app = QGuiApplication()
    app.setApplicationDisplayName("Amadeus TV")
    #app.setWindowIcon(QIcon("assets/icons-tv-64.png"))
    QQuickStyle.setStyle("Material")
    engine = QQmlApplicationEngine()
    backend = CrunchyrollController(150)
    atexit.register(exit_handler, backend)
    engine.rootContext().setContextProperty("backend", backend)
    engine.setInitialProperties(
        {
        "is_deck": is_deck
        }
    )
    engine.load("qml/main.qml")
    #Exit application properly
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())


import sys
import h5py
import logging
import warnings
from pathlib import Path

import torch
import numpy as np
from scipy.ndimage import zoom

from unet3d import Basic3DUNet

warnings.filterwarnings(action='ignore', category=UserWarning)
log = logging.getLogger(__name__)
PAD = 64

def segment_mitochondria(input_path, output_path, copy, bin2):
    dataset = load_tomogram(input_path)
    dataset, shape = preprocess_data(dataset, bin2)
    model = load_model()

    result = predict(model, dataset)
    save_tomogram(result, output_path, shape, dataset, copy)

def load_tomogram(input_path):
    # callback function to walk through the HDF file to find the data
    def find_dataset(name, obj):
        return obj if isinstance(obj, h5py.Dataset) else None

    with h5py.File(input_path) as fh:
        dataset = fh.visititems(find_dataset)

        if dataset is None:
            log.error(f"Unable to find an HDF5 dataset in {input_path}")
            sys.exit(1)

        else:
            log.info(f"Reading tomogram of shape {dataset.shape} from {dataset.name}")
            return np.squeeze(dataset)

def preprocess_data(dataset, bin2):
    # assuming that the data follows a standard normal distribution, it is clipped and scaled
    dataset = np.clip(dataset, -3, 3) / 3.0

    if bin2:  # downsample by a factor of 2
        old_shape = dataset.shape
        dataset = zoom(dataset, 0.5, order=1)
        log.info(f"Tomogram binned by 2 from {old_shape} -> {dataset.shape}")

    # compute size of the padded data
    d, h, w = dataset.shape
    x = int(PAD * np.ceil(d / PAD))
    y = int(PAD * np.ceil(h / PAD))
    z = int(PAD * np.ceil(w / PAD))

    if (x, y, z) != (d, h, w):  # check if padding is required
        new_dataset = np.zeros((x, y, z), dtype=np.float32)
        x = (x - d) // 2
        y = (y - h) // 2
        z = (z - w) // 2

        # apply zero padding
        new_dataset[x: x + d, y: y + h, z: z + w] = dataset
        dataset = new_dataset
        log.info(f"Tomogram padded from {d, h, w} -> {dataset.shape}")

    return dataset, (d, h, w)  # the original shape

def load_model():
    # the model is bundled along with the code, so it should always be here
    model_path = Path(__file__).parents[1] / "models" / "mito_weights.pt"

    if not model_path.exists():
        log.error(f"Unable to locate model file at {model_path}")

    model = Basic3DUNet()
    model.load_state_dict(torch.load(model_path))
    log.info(f"Model loaded from checkpoint {model_path}")

    model.cuda()
    model.eval()
    return model

def predict(model, dataset):
    # reshape the dataset to compatible shape and convert it to a tensor
    dataset = np.expand_dims(dataset, axis=(0, 1))
    input_tensor = torch.from_numpy(dataset).cuda()

    with torch.no_grad():
        log.info("Predicting mitochondria probabilities in the tomogram")
        result = model(input_tensor).cpu().numpy().astype(np.float32)

    return np.squeeze(result)  # remove the extra dimensions from the result

def save_tomogram(result, output_path, shape, dataset, copy):
    d, h, w = shape  # the original shape
    x, y, z = result.shape

    # check if the data was padded
    if (x, y, z) != (d, h, w):
        x = (x - d) // 2
        y = (y - h) // 2
        z = (z - w) // 2

        # undo the padding for the data and the predictions
        result = result[x: x + d, y: y + h, z: z + w]
        dataset = dataset[x: x + d, y: y + h, z: z + w]

    with h5py.File(output_path, 'w') as fh:
        log.info(f"Saving mitochondria predictions to {output_path}:/mito_pred")
        fh.create_dataset("mito_pred", data=result)

        if copy:
            log.info(f"Copying original tomogram to {output_path}:/data")
            fh.create_dataset("data", data=dataset)


#!/usr/bin/env python3
import os
import sys
import subprocess as sp
from glob import glob
from shutil import rmtree
from setuptools import setup, find_packages, Command

class ST_cmd(Command):
    description = "foo"
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

class cln(ST_cmd):
    def run(self):
        for d in ["build", "dist", "softchat.egg-info"]:
            try:
                rmtree(d)
            except:
                pass

class tst(ST_cmd):
    def run(self):
        do_rls(False)

class rls(ST_cmd):
    def run(self):
        do_rls(True)

def sh(bin, *args, **kwargs):
    cmd = [bin] + " ".join(args).split(" ")
    print(f"\n\033[1;37;44m{repr(cmd)}\033[0m")
    sp.check_call(cmd, **kwargs)

def do_rls(for_real):
    env = os.environ.copy()
    for ek, tk in [["u", "TWINE_USERNAME"], ["p", "TWINE_PASSWORD"]]:
        v = os.environ.get(ek, "")
        if v:
            env[tk] = v

    py = sys.executable
    sp.run("rem", shell=True)
    try:
        import twine, wheel
    except:
        sh(py, "-m pip install --user twine wheel")

    sh(py, "setup.py cln")
    sh(py, "setup.py sdist bdist_wheel --universal")

    files = glob(os.path.join("dist", "*"))
    dest = "pypi" if for_real else "testpypi"
    sh(py, "-m twine upload -r", dest, *files, env=env)

with open("README.md", encoding="utf8") as f:
    readme = f.read()

a = {}
with open("softchat/__main__.py", encoding="utf8") as f:
    exec(f.read().split("\nimport", 1)[0], a)

a = a["about"]
del a["date"]

a.update(
    {
        "author_email": "@".join([a["name"], "ocv.me"]),
        "python_requires": ">=3.6",
        "install_requires": ["Pillow", "fonttools"],
        "extras_require": {"unkanji": ["fugashi[unidic]"]},
        "entry_points": {"console_scripts": ["softchat=softchat.__main__:main"]},
        "include_package_data": True,
        "long_description": readme,
        "long_description_content_type": "text/markdown",
        "keywords": "youtube chat converter danmaku marquee softsubs ass subtitles",
        "classifiers": [
            "License :: OSI Approved :: MIT License",
            "Development Status :: 3 - Alpha",
            "Environment :: Console",
            "Operating System :: Microsoft :: Windows",
            "Operating System :: POSIX :: Linux",
            "Operating System :: MacOS",
            "Natural Language :: English",
            "Topic :: Multimedia :: Video",
            "Intended Audience :: End Users/Desktop",
            "Programming Language :: Python :: 3",
            "Programming Language :: Python :: 3.6",
            "Programming Language :: Python :: 3.7",
            "Programming Language :: Python :: 3.8",
            "Programming Language :: Python :: 3.9",
            "Programming Language :: Python :: 3.10",
            "Programming Language :: Python :: 3.11",
            "Programming Language :: Python :: 3.12",
        ],
        "packages": find_packages(),
        "cmdclass": {"cln": cln, "rls": rls, "tst": tst},
    }
)

# pprint.pprint(a)
setup(**a)

# c:\Python36\python -m pip install --user -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple softchat


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
## dfs
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        if not root.left and not root.right:
            return 1

        res = 10**6
        if root.left:
            res = min(res, self.minDepth(root.left)+1)
        if root.right:
            res = min(res, self.minDepth(root.right)+1)
        return res

## 第一个和第二个：时间换空间
## bfs
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        queue = list()
        depth = 1
        queue.append(root)
        while queue:
            for i in range(len(queue)):
                cur = queue.pop(0)
                if not cur.left and not cur.right:
                    return depth
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            depth += 1
        return depth

## another bfs
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        que = collections.deque([(root, 1)])
        while que:
            node, depth = que.popleft()
            if not node.left and not node.right:
                return depth
            if node.left:
                que.append((node.left, depth + 1))
            if node.right:
                que.append((node.right, depth + 1))

        return 0

111-二叉树的最小深度.py


import matplotlib.pyplot as plt
import pandas as pd

fn = '/gpfs23/scratch/h_vangard_1/chenh19/findadapt_bench/realdata/87_geo_study_group.txt'

reads_type = ['3p Adapter only', 'QIAseq', 'NEXTFLEX', 'Template Switching', 'Trimmed']

ct = {k: [0 for _ in range(5)] for k in ['Matched', 'Mislabeled', 'Not Specified', 'Other']}

idx_map = {v: n for n, v in enumerate(reads_type)}

with open(fn) as f:
    f.readline()
    for i in f:
        group, subgroup = i.strip().split('\t')
        if subgroup == 'other':
            subgroup = 'Other'
        idx = idx_map[group]

        ct[subgroup][idx] += 1

plotdata = pd.DataFrame(ct, index = reads_type)

pwout = '/gpfs23/scratch/h_vangard_1/chenh19/findadapt_bench'

# plot
ax = plotdata.plot(kind='bar', stacked = True, figsize=(4, 3), color=['green', 'orange', 'lightblue', 'grey'])

fontsize = 6
# plt.legend(loc='upper left', bbox_to_anchor=(1.01, 0.7), fontsize=6)

ax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha='right', fontsize=fontsize)
# ax.set_yticklabels(ax.get_yticklabels(), fontsize=fontsize)
ax.set_ylabel('Number of studies')
legend = ax.get_legend()

# legend._legend_box = None
# legend._legend_handle_box = None
legend.borderpad = 1
legend.labelspacing = 0
legend.handlelength = 0
legend.handletextpad = 0
for text in legend.get_texts():
    text.set_fontsize(fontsize)
# plt.setp(legend.get_texts(), fontsize=fontsize)

plt.savefig(f"{pwout}/87_geo_acuracy.png", dpi=300, bbox_inches='tight')

# handles, labels = ax.get_legend_handles_labels()
# filtered_handles_labels = [(handle, label) for handle, label in zip(handles, labels) if label != 'other']
# ax.legend([handle for handle, _ in filtered_handles_labels], [label for _, label in filtered_handles_labels])


#!/usr/bin/python

import argparse
import os
import random
import sys

import Project
from coilsnake.util.common.yml import yml_load

sys.path.append('./')

def calcNewStat(statName, growthRates, newLevel, oldStatValue):
    r = 0
    if (statName == "Vitality" or statName == "IQ") and (newLevel <= 10):
        r = 5
    elif (newLevel % 4) == 0:
        r = random.randint(7, 10)
    else:
        r = random.randint(3, 6)

    statGain = ((growthRates[statName] * (newLevel-1)) - ((oldStatValue-2) * 10))
    statGain *= (r/50.0)

    return oldStatValue + int(statGain)

def calcStats(growthVars, endLevel):
    stats = [30, 10, 2, 2, 2, 2, 2, 2, 2]
    for i in range(2, endLevel+1):
        # Normal stats
        stats[2] = calcNewStat("Offense", growthVars, i, stats[2])
        stats[3] = calcNewStat("Defense", growthVars, i, stats[3])
        stats[4] = calcNewStat("Speed", growthVars, i, stats[4])
        stats[5] = calcNewStat("Guts", growthVars, i, stats[5])
        stats[6] = calcNewStat("Vitality", growthVars, i, stats[6])
        stats[7] = calcNewStat("IQ", growthVars, i, stats[7])
        stats[8] = calcNewStat("Luck", growthVars, i, stats[8])
        # HP
        newHP = 15 * stats[6]
        if (newHP - stats[0]) < 2:
            stats[0] += random.randint(1, 3)
        else:
            stats[0] = newHP
        # PP
        newPP = 5 * stats[7]
        if (newPP - stats[1]) < 2:
            stats[1] += random.randint(0, 2)
        else:
            stats[1] = newPP
    return stats

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('levels', type=int,
                        metavar=('PC1_Level', 'PC2_Level', 'PC3_Level', 'PC4_Level'),
                        nargs=4, help='Party levels')
    parser.add_argument('projDir', metavar='ProjectDirectory', nargs=1,
                        help='CoilSnake project directory')
    parser.add_argument('--enemy', action='store', nargs=1,
                        metavar='Enemy_ID', type=int,
                        dest="enemyInfo", help="Enemy number")
    args = parser.parse_args()

    proj = Project.Project()
    proj.load(args.projDir[0] + os.sep + Project.PROJECT_FILENAME)

    partyStats = [None, None, None, None]
    with proj.get_resource("eb", "stats_growth_vars", "yml", "r") as f:
        growthVars = yml_load(f)
        for i in range(4):
            partyStats[i] = calcStats(growthVars[i], args.levels[i])

    print("*** Party Stats ***")
    print('\t'.join(map(str, ['', 'HP', 'PP', 'Off', 'Def', 'Speed', 'Guts', 'Vit', 'IQ', "Luck"])))
    for i in range(4):
        print(i, '\t', '\t'.join(map(str, partyStats[i])))

    if args.enemyInfo is not None:
        with proj.get_resource("eb", "enemy_configuration_table", "yml", "r") as f:
            enemyData = (yml_load(f))[args.enemyInfo[0]]
            print("\n*** Enemy Stats:", enemyData["Name"], "***")
            print('\t'.join(map(str, ['', 'HP', 'PP', 'Off', 'Def', 'Speed', 'Guts', "Luck"])))
            print('\t%d\t%d\t%d\t%d\t%d\t%d\t%d' % (enemyData["HP"], enemyData["PP"],
                                                    enemyData["Offense"], enemyData["Defense"],
                                                    enemyData["Speed"], enemyData["Guts"], enemyData["Luck"]))
            print("\n*** Damage Dealt by Enemy to Party ***")
            print("Level\tTarget\tMinDmg\tMaxDmg\tSMASH\tSmash%")
            for i in range(1, 5):
                for j in range(0, 4):
                    damage = i * enemyData["Offense"] - partyStats[j][3]
                    smashDamage = 4 * enemyData["Offense"] - partyStats[j][3]
                    smashOdds = enemyData["Guts"] / 5.0
                    print("%d\t%d\t%d\t%d\t%d\t%.2f%%" % (i, j, damage*0.75, damage*1.25, smashDamage, smashOdds))
                print()

            print("*** Damage Dealt by Party to Enemy ***")
            print("PC\tMinDmg\tMaxDmg\tSMASH\tSmash%")
            for i in range(0, 4):
                damage = 2 * partyStats[i][2] - enemyData["Defense"]
                smashDamage = 4 * partyStats[i][2] - enemyData["Defense"]
                smashOdds = max(partyStats[i][5] / 5.0, 5.0)
                print("%d\t%d\t%d\t%d\t%d" % (i, damage * 0.75, damage * 1.25, smashDamage, smashOdds))

if __name__ == '__main__':
    sys.exit(main())


#!/usr/bin/env python
import os
import time
import argparse

from datetime import datetime

from pvaserver import config
from pvaserver import adsimserver
from pvaserver import log
from pvaserver import __version__

def init(args):
    if not os.path.exists(str(args.config)):
        config.write(args.config)
    else:
        log.error("{0} already exists".format(args.config))

def run_status(args):

    config.log_values(args)

def run_sim(args):

    args.use_sim_data = True
    run_server(args)

def run_stack(args):

    args.use_sim_data = False
    args.data_stack = True
    run_server(args)

def run_tomo(args):

    args.use_sim_data = False
    args.data_stack = False # single hdf file
    run_server(args)

def run_server(args):

    server = adsimserver.AdSimServer(args)
    server.start()
    expectedRuntime = args.runtime+args.start_delay+server.SHUTDOWN_DELAY
    startTime = time.time()
    try:
        while True:
            time.sleep(1)
            now = time.time()
            runtime = now - startTime
            if runtime > expectedRuntime or server.isDone:
                break
    except KeyboardInterrupt as ex:
        pass
    server.stop()

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--config', **config.SECTIONS['general']['config'])
    parser.add_argument('--version', action='version',
                        version='%(prog)s {}'.format(__version__))

    pvaserver_sim_params   = config.PVASERVER_SIM_PARAMS
    pvaserver_stack_params = config.PVASERVER_STACK_PARAMS
    pvaserver_tomo_params  = config.PVASERVER_TOMO_PARAMS

    cmd_parsers = [
        ('init',        init,          (),                     "Usage: pvaserver init                        - Create configuration file and restore the original default values"),
        ('sim',         run_sim,       pvaserver_sim_params,   "Usage: pvaserver sim                         - Run the PVA server in simulation mode (-h for more options)"),
        ('stack',       run_stack,     pvaserver_stack_params, "Usage: pvaserver stack --file-path /data/    - Run the PVA server loading a stack of images from a folder (-h for more options)"),
        ('tomo',        run_tomo,      pvaserver_tomo_params,  "Usage: pvaserver tomo --file-name tomo.h5    - Run the PVA server loading a tomo dataset (-h for more options)"),
        ('status',      run_status,    pvaserver_tomo_params,  "Usage: pvaserver status                      - Show status"),
    ]

    subparsers = parser.add_subparsers(title="Commands", metavar='')

    for cmd, func, sections, text in cmd_parsers:
        cmd_params = config.Params(sections=sections)
        cmd_parser = subparsers.add_parser(cmd, help=text, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
        cmd_parser = cmd_params.add_arguments(cmd_parser)
        cmd_parser.set_defaults(_func=func)

    args = config.parse_known_args(parser, subparser=True)

    # create logger
    logs_home = args.logs_home

    # make sure logs directory exists
    if not os.path.exists(logs_home):
        os.makedirs(logs_home)

    lfname = os.path.join(logs_home, 'pvaserver_' + datetime.strftime(datetime.now(), "%Y-%m-%d_%H_%M_%S") + '.log')

    log.setup_custom_logger(lfname)
    log.info("Saving log at %s" % lfname)

    try:
        args._func(args)
    except RuntimeError as e:
        log.error(str(e))
        sys.exit(1)

if __name__ == '__main__':
    main()


from service.base import BaseService
import requests
import json
import config

class UserService(BaseService):
    def __init__(self, db, rs):
        super().__init__(db, rs)
        UserService.inst = self

    def login(self, req, data={}):
        '''
        username, password
        '''
        url = self.add_client_id(config.BASE_URL + '/login')
        r = requests.post(url, data=json.dumps(data))
        try:
            res = json.loads(r.text)
            token = res['token']
            req.set_secure_cookie('token', token)
            _, res_cnt = yield from self.db.execute('SELECT * FROM users WHERE username = %s;', (data['username'],))
            if res_cnt == 0:
                insert_data = {'username': data['username'], 'account_id': ' '}
                sql, param = self.gen_insert_sql('users', insert_data)
                yield from self.db.execute(sql, param)
            res, res_cnt = yield from self.db.execute('SELECT id FROM users WHERE username=%s', (data['username'],))
            id = res[0]['id']
            req.set_secure_cookie('id', str(id))
            err, res = yield from self.get_user_info(token, id)
            sql, param = self.gen_update_sql('users', {'account_id': res['account_id']})
            yield from self.db.execute(sql+' WHERE id=%s', param+(str(id),))
            return (None, token)
        except Exception as e:
            return (r.text, None)

    def get_user_info(self, token, id):
        url = self.add_client_id(config.BASE_URL + '/accounts')
        r = requests.get(url, headers=self.headers(token))
        try:
            res, res_cnt = yield from self.db.execute('SELECT username FROM users WHERE id=%s;', (id,))
            res = res[0]
            res.update(json.loads(r.text)['accounts'][0])
            return (None, res)
        except:
            return (r.text, None)

    def get_user_id_by_account(self, account):
        res, rescnt = yield from self.db.execute("SELECT id FROM users WHERE account_id=%s", (account,))
        return (None, res[0]['id'])


import pyglet
from pyglet.gl import *

# Zooming constants
ZOOM_IN_FACTOR = 1.2
ZOOM_OUT_FACTOR = 1/ZOOM_IN_FACTOR

class Camera:
    def __init__(self, width, height):
        # Initialize camera values
        self.left = 0
        self.right = width
        self.bottom = 0
        self.top = height
        self.zoom_level = 1
        self.zoomed_width = width
        self.zoomed_height = height

        self.vect_x = 0
        self.vect_y = 0

    def draw(self):
        glOrtho(self.left, self.right, self.bottom, self.top, 1, -1)

    def mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        pre_left = self.left - dx * self.zoom_level
        pre_right = self.right - dx * self.zoom_level
        pre_bottom = self.bottom - dy * self.zoom_level
        pre_top = self.top - dy * self.zoom_level

        valid = True
        if -1000 >= pre_left or pre_left >= 1500:
            valid = False
        if -1000 >= pre_right or pre_right >= 1500:
            valid = False
        if -1000 >= pre_bottom or pre_bottom >= 1000:
            valid = False
        if -1000 >= pre_top or pre_top >= 1000:
            valid = False

        if valid:
            self.left = pre_left
            self.right = pre_right
            self.bottom = pre_bottom
            self.top = pre_top

    def update(self):
        pre_left = self.left - self.vect_x * self.zoom_level
        pre_right = self.right - self.vect_x * self.zoom_level
        pre_bottom = self.bottom - self.vect_y * self.zoom_level
        pre_top = self.top - self.vect_y * self.zoom_level

        valid = True
        if -1000 >= pre_left or pre_left >= 2000:
            valid = False
        if -1000 >= pre_right or pre_right >= 2000:
            valid = False
        if -1000 >= pre_bottom or pre_bottom >= 1000:
            valid = False
        if -1000 >= pre_top or pre_top >= 1500:
            valid = False

        if valid:
            self.left = pre_left
            self.right = pre_right
            self.bottom = pre_bottom
            self.top = pre_top

    def set_move_vertical(self, move_y):
        self.vect_y = move_y

    def set_move_horizontal(self, move_x):
        self.vect_x = move_x

    def mouse_scroll(self, x, y, dx, dy, width, height):
        # Get scale factor
        f = ZOOM_OUT_FACTOR if dy > 0 else ZOOM_IN_FACTOR if dy < 0 else 1
        # If zoom_level is in the proper range
        if .2 < self.zoom_level * f < 5:
            self.zoom_level *= f

            mouse_x = x / width
            mouse_y = y / height

            mouse_x_in_world = self.left + mouse_x * self.zoomed_width
            mouse_y_in_world = self.bottom + mouse_y * self.zoomed_height

            self.zoomed_width *= f
            self.zoomed_height *= f

            self.left = mouse_x_in_world - mouse_x * self.zoomed_width
            self.right = mouse_x_in_world + (1 - mouse_x) * self.zoomed_width
            self.bottom = mouse_y_in_world - mouse_y * self.zoomed_height
            self.top = mouse_y_in_world + (1 - mouse_y) * self.zoomed_height

    def get_zoom_level(self):
        return round(self.zoom_level, 2)