#!/usr/bin/env python

'''
 Author: Yue Liu
 Usage: python action_spectra.py
 Description:
 - action input file must be named with "ExportedData.csv"
 - powerscan files must be started with "PS" and ended with "CSV", e.g. "PS10030432.CSV"
 - output file is the relative intensities of each fragment to total ions(fragements + parent ions) and corrected by relative power scan energies
'''

import csv,time,glob

ACT = 'ExportedData.csv'
PSE = 'PS*.CSV'
OUT = 'OUT'+time.strftime('%m%d%H%M%S',time.localtime(time.time()))+'.csv'

def mymode(s):
    unq_s = list(set(s))
    n = [s.count(unq_s[i]) for i in range(len(unq_s))]
    index_unq = n.index(max(n))
    return unq_s[index_unq]

def action():
    with open(ACT,'r') as fa:
        rfa = csv.reader(fa)
        data = [row for row in rfa]
    ions = [x[6:] for x in data[0][5:] if bool(x)]
    print('Reminder: Find Ions m/z: %s, the last one is taken as the parent ion' % ions)
    n_ions = len(ions)
# find first positions of all wavelengths in data
    x_wl = data[1][1]
    wl = [float(x_wl)]
    mark_row=[1]
    for p_row, row in enumerate(data[1:]):
        if row[1]!= x_wl:
            mark_row.append(p_row+1)
            x_wl = row[1]
            wl.append(float(x_wl))
    mark_row.append(len(data))
# tell if the wavelength is in ascending order. sometimes the first wavelength is not reasonable
    if wl[0]>wl[1]:
        wl.pop(0)
        mark_row.pop(0)
    scans = [mark_row[i+1]-mark_row[i] for i in range(len(mark_row)-1)]
# check scan-number of every wavelength based on the mode of all scans; count the last 100 scans for the 1st wavelength or the first 100 scans for the last wavelength if the default scan number is 100 and more than 100 scans found for these two wavelength
    scan = mymode(scans)
    for i_x, x in enumerate(scans):
        if x > scan:
            if i_x == 0:
                mark_row[i_x] = mark_row[i_x+1]-scan
            elif i_x == len(scans)-1:
                mark_row[i_x+1] = mark_row[i_x]+scan
            print('Reminder: %s scans found for %snm, count %s-%sth lines (%s scans)' % (x,data[mark_row[i_x]][1],mark_row[i_x]+1,mark_row[i_x+1],scan))
        elif x < scan:
            print('Warning: only find %s scans for %snm!' % (x,data[mark_row[i_x]][1]))
# calculate the average intensities of all monitored charged substances at every wavelength; (wavelength, ion1, ion2, ..., ionN,total-ions)
    ave_action=[]
    totions = []
    for i,mark in enumerate(mark_row[0:-1]):
        tmp = []
        for j in range(5,5+n_ions):
            s = 0
            for t_data in data[mark:mark_row[i+1]]:
                s += float(t_data[j])
            tmp.append(s/(mark_row[i+1]-mark))
        totions.append(sum(tmp))
        ave_action.append(tmp)
    return ions,wl,ave_action,totions

def PSenergy(wl):
    energy=[]
    fps = glob.glob(PSE)
    if bool(fps):
        print('Reminder: PS files are %s' % fps)
    else:
        raise SystemExit('Error: PowerScan Files (PS*.CSV) Not Found!')
    for f in fps:
        with open(f,'r') as fo:
            readfo = csv.reader(fo)
            rows = [line for line in readfo]
        column1 = [float(x[0]) for x in rows]
        if column1 != wl:
            raise SystemExit('Error: %s(%s-%snm) Not Match Wavelength in %s(%s-%snm)' % (f,column1[0],column1[-1],ACT,wl[0],wl[-1]))
        column2 = [float(x[1]) for x in rows]
        energy.append(column2)
    n_ps = len(energy)
    n_wl = len(wl)
    ave_ps = [0]*n_wl
    for i in range(n_wl):
        for j in range(n_ps):
            ave_ps[i] += energy[j][i]
        ave_ps[i] /= n_ps
    maxps = max(ave_ps)
    return [x/maxps for x in ave_ps]

def wrout(ps,ave_ions,tot,wl,ions):
    mI = []
    for i in range(len(wl)):
        tI=[x/tot[i]/ps[i] for x in ave_ions[i]]
        tI.pop(-1)
        tI_tot=sum(tI)
        tI.append(tI_tot)
        tI.insert(0,wl[i])
        mI.append(tI)
    title=['m/z '+x for x in ions[0:-1]]
    title.append('all fragments')
    title.insert(0,'wavelength(nm)')
    with open(OUT,'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(title)
        writer.writerows(mI)

def main_script():
    try:
        ions,wl,ave_int,tot_int = action()
        mod_ps = PSenergy(wl)
        wrout(mod_ps,ave_int,tot_int,wl,ions)
        print('**\\(^O^)/**Please Check %s: relative intensities to total ions and corrected by laser power!' % OUT)
    except IOError:
        raise SystemExit('%s Not Found!' % ACT)

if __name__=='__main__':
    main_script()


"""frame.py – Draws the selected frame sized to a given sheet and fills in the fields"""

import logging
import sys
from sqlalchemy import select, and_
from flatland.database.flatlanddb import FlatlandDB as fdb
from collections import namedtuple
from flatland.datatypes.geometry_types import Position, Rect_Size, Alignment, HorizAlign, VertAlign
from flatland.node_subsystem.canvas import points_in_mm
from flatland.text.text_block import TextBlock
import math
from flatland.sheet_subsystem.resource import resource_locator
from flatland.sheet_subsystem.titleblock_placement import draw_titleblock
from typing import TYPE_CHECKING, Dict

if TYPE_CHECKING:
    from flatland.node_subsystem.canvas import Canvas

DataBox = namedtuple('_Databox', 'metadata content position size alignment style')
FieldPlacement = namedtuple('_FieldPlacement', 'metadata position max_area')

class Frame:
    """
    On any serious project it is not adequate to generate model diagrams absent any metadata such as
    authors, dates, revision numbers, copyright notices, organization logos and so forth.
    A Frame represents a pattern of Fields and/or a Title Block Pattern on the surface area defined by
    a Sheet. The lower left corner placements of each Frame element (Field or Scaled Title Block) are
    customized to fit the dimensions of a given Sheet.

        Attributes

        - Name (str) -- Size independent name of the Frame such as 'Open Source Engineer' or 'Architect'
        - Canvas (obj) -- Canvas has selected a Sheet which determines Frame sizing
        - metadata (dict) -- <Metadata> : <Content>, such as 'Title' : 'Sheet Subsystem Class Diagram'
        - Open_fields (list) -- Open field metadata label and positional info loaded from flatland database
        - Databoxes (dict) -- All Databox data loaded from flatland database (See named tuple above)
    """

    def __init__(self, name: str, presentation: str, canvas: 'Canvas', metadata: Dict[str, str]):
        """
        Constructor

        :param name: Size independent name of the Frame such as 'Open Source Engineer' or 'Architect'
        :param canvas: Canvas has selected the Sheet which determines sizing
        :param presentation: They Frame's Presentation (determines all styling of Frame content)
        :param metadata: Text and images to display in the Frame
        """
        self.logger = logging.getLogger(__name__)
        self.Name = name
        self.Canvas = canvas
        self.Orientation = canvas.Orientation
        self.metadata = metadata
        self.Open_fields = []
        self.Databoxes = {}

        # Create a Layer where we'll draw all of the Frame contents

        self.logger.info('Creating Frame Layer')
        drawing_type_name = ' '.join([name, self.Canvas.Sheet.Size_group, 'frame'])  # e.g. "OS Engineer large frame"
        # Whereas a diagram's drawing type is something like 'xUML Class Diagram',
        # the Frame's drawing type name systematically incorporates both purpose and Sheet Size Group
        # That's because a model element like a class or state is typically drawn the same size regardless
        # of sheet size. Frame's, on the other hand are more likely to change proportions with large sheet size
        # differences.  That said, there is nothing preventing us from doing the same for diagram layers on a case by
        # case basis. So an 'xUML Class Diagram tiny' could certainly be defined by us or a user in the future
        self.Layer = self.Canvas.Tablet.add_layer(
            name='frame', presentation=presentation, drawing_type=drawing_type_name
        )  # We're gonna be drawing metadata and title block borders all over this thing.

        # If there is a title block cplace specified for this Frame, get the name of the pattern
        tb_placement_t = fdb.MetaData.tables['Title Block Placement']
        f = and_(
            (tb_placement_t.c['Frame'] == self.Name),
            (tb_placement_t.c['Sheet'] == self.Canvas.Sheet.Name),
            (tb_placement_t.c['Orientation'] == self.Orientation),
        )
        query = select([tb_placement_t.c['Title block pattern']]).select_from(tb_placement_t).where(f)
        row = fdb.Connection.execute(query).fetchone()
        # Nothing says "I'm a serious engineer or architect" more than a fancy bordered title block on your Frame,
        # but it is optional
        self.Title_block_pattern = None if not row else row[0]

        # If a Title Block Pattern is specified, let's gather all the Data Box content from the flatland database
        if self.Title_block_pattern:
            self.logger.info('Assembling title block pattern on frame')
            # Assemble a text block for each Data Box containing the Metadata Text Content
            # We'll register that text block with the Layer for rendering
            # Image (Resource) content is not supported within a Title Block Pattern, so we assume only text content
            # If any non-text Resources were mistakenly specified by the user, we will ignore them
            boxplace_t = fdb.MetaData.tables['Box Placement']  # Box positions and sizes, scaled for our Frame
            databox_t = fdb.MetaData.tables['Data Box']  # Alignment and style of text within box
            boxline_t = fdb.MetaData.tables['Box Text Line']  # Vertical ordering of metadata within a Data Box
            # s = select (row criteria), p = project (columns), j = join, q = query
            s = and_(
                (boxplace_t.c.Frame == self.Name),
                (boxplace_t.c.Sheet == self.Canvas.Sheet.Name),
                (boxplace_t.c.Orientation == self.Orientation),
                (boxplace_t.c['Title block pattern'] == self.Title_block_pattern),
            )
            p = [databox_t.c.ID, boxplace_t.c.X, boxplace_t.c.Y, boxplace_t.c.Width, boxplace_t.c.Height,
                 databox_t.c['H align'], databox_t.c['V align'], databox_t.c.Style,
                 boxline_t.c.Box, boxline_t.c.Order, boxline_t.c.Metadata]
            j = databox_t.join(
                boxplace_t,
                and_((databox_t.c.Pattern == boxplace_t.c['Title block pattern']), (databox_t.c.ID == boxplace_t.c.Box))
            ).join(
                boxline_t,
                and_((databox_t.c.Pattern == boxline_t.c['Title block pattern']), (databox_t.c.ID == boxline_t.c.Box))
            )
            q = select(p).select_from(j).where(s).order_by(boxplace_t.c.Box, boxline_t.c.Order)
            rows = fdb.Connection.execute(q).fetchall()
            # Populate our Databoxes dictionary from the row data we just fetched
            for r in rows:
                if r.Box in self.Databoxes:
                    # The Data Box was recorded with an initial text line, so this must be an additional line
                    try:
                        # Extract the user supplied metadata value for this Data Box
                        metadata_value = metadata[r.Metadata][0]
                    except KeyError:
                        self.logger.error(f"No metadata value supplied for: {r.Metadata}")
                        sys.exit(1)
                    self.Databoxes[r.Box].content.append(metadata_value)
                else:
                    # Rows are ordered by Data Box, so if the box id is new, we create an initial dictioary entry
                    # With level 1
                    self.Databoxes[r.Box] = DataBox(
                        content=[metadata[r.Metadata][0]],  # Text to render:  Leon Starr, mint.flatland.td.1, etc
                        position=Position(r.X, r.Y),  # Lower left corner of the Data Box
                        size=Rect_Size(height=r.Height, width=r.Width),
                        style=r.Style,  # Style of text inside this box such as: Block body, Block title, etc
                        metadata=r.Metadata,  # Name of data item: Author, Document ID, etc
                        # Finally, how text is aligned inside this box
                        alignment=Alignment(vertical=VertAlign[r['V align']], horizontal=HorizAlign[r['H align']])
                    )
            # All done with the title block Metacontent. We'll unwind all this when we render to our Layer

        # Gather the Open Field content (other text and graphics scattered around the Frame)
        self.logger.info('Assembling open fields on frame')
        open_field_t = fdb.MetaData.tables['Open Field']
        s = and_(
            (open_field_t.c['Frame'] == self.Name),
            (open_field_t.c['Sheet'] == self.Canvas.Sheet.Name),
            (open_field_t.c['Orientation'] == self.Orientation),
        )
        q = select([open_field_t]).where(s)
        rows = fdb.Connection.execute(q).fetchall()
        for r in rows:
            p = Position(round(r['x position'] * points_in_mm, 2), round(r['y position'] * points_in_mm, 2))
            ma = Rect_Size(round(r['max height'] * points_in_mm, 2), round(r['max width'] * points_in_mm, 2))
            self.Open_fields.append(
                FieldPlacement(metadata=r.Metadata, position=p, max_area=ma)
            )
        # All done with the Open Fields. Much easier to compute than Boxed Fields!

        # Now let's register all text and graphics for everything in our Frame on its Layer
        self.render()

    def render(self):
        """Draw the Frame on its Layer"""
        self.logger.info('Rendering frame')

        # Fill each open field
        for f in self.Open_fields:
            asset = 'Open ' + f.metadata.lower()
            content, isresource = self.metadata.get(f.metadata, (None, None))
            # If there is no data supplied to fill in the field, just leave it blank and move on
            if content and isresource:
                # Key into resource locator using this size and orientation delimited by an underscore
                rsize = '_'.join([content, self.Canvas.Sheet.Size_group, self.Canvas.Orientation])
                # Get the full path to the resource (image) using the rsize
                rloc = resource_locator.get(rsize)
                if rloc:
                    self.Layer.add_image(resource_path=rloc, lower_left=f.position, size=f.max_area)
                else:
                    self.logger.warning(
                        f"Couldn't find file for: [{content}] in your flatland resource directory. "
                        f"Default resource location is in ~/.flatland"
                    )
            elif content:  # Text content
                # Content is a line of text to print directly
                self.Layer.add_text_line(
                    asset=asset,
                    lower_left=f.position,
                    text=content,
                )

        if self.Title_block_pattern:
            # Draw the title block box borders
            draw_titleblock(frame=self.Name, sheet=self.Canvas.Sheet, orientation=self.Orientation, layer=self.Layer)

            # Get the margins to pad the Data Box content
            # The same margins are applied to each Data Box in the same Scaled Title Block
            # So we are looking only for one pair of h,v margin values to use throughout
            scaledtb_t = fdb.MetaData.tables['Scaled Title Block']
            s = and_(
                (scaledtb_t.c['Title block pattern'] == self.Title_block_pattern),
                (scaledtb_t.c['Sheet size group'] == self.Canvas.Sheet.Size_group),
            )
            p = [scaledtb_t.c['Margin H'], scaledtb_t.c['Margin V']]
            q = select(p).where(s)
            row = fdb.Connection.execute(q).fetchone()
            assert row, f"No Title Block Placement for frame: {self.Name}"
            h_margin, v_margin = row

            # Render all the box fields
            for k, v in self.Databoxes.items():
                # compute lower left corner position
                # Layer asset is composed from the data box style and its size group
                block_size = self.Layer.text_block_size(asset=v.style, text_block=v.content)
                # When there is a single line of text in a Data Box that is longer than the Box width,
                # we will wrap it as necessary. Especially useful for a long title in the title box
                # For multiple line boxes, this feature is not yet (or ever) supported
                padded_box_width = round(v.size.width - h_margin * 2, 2)
                content = v.content
                if len(v.content) == 1 and block_size.width > padded_box_width:
                    lines_to_wrap = math.ceil(block_size.width / padded_box_width)  # Round up to nearest int
                    content = TextBlock(v.content[0], wrap=lines_to_wrap).text
                    block_size = self.Layer.text_block_size(asset=v.style, text_block=content)
                # For now we will just let any exessive line length in multi field Data Boxes
                # overrun the title block boundary, since it is not so obvious how to recover automatically
                # User correction is more likely to yield a satisfactory outcome
                # They can either use more box fields, use shorter lines of text, change the size of
                # the Title Block Pattern or just create one that is larger and use that
                xpos = v.position.x + h_margin
                ypos = v.position.y + v_margin + round((v.size.height - block_size.height) / 2, 2)
                self.Layer.add_text_block(
                    asset=v.style, lower_left=Position(xpos, ypos), text=content, align=v.alignment.horizontal
                )


# -*- coding: utf-8 -*-

import re
import inspect
import copy
from math import ceil

from flask import request, jsonify
from flask.ext.classy import FlaskView, route
from marshmallow.utils import is_collection

class Pagination(object):

    def __init__(self, iterable, page, per_page):
        iterable = list(iterable)
        self.total = len(iterable)
        offset = (page-1) * per_page
        limit = min(offset+per_page, self.total)
        self.items = iterable[offset:limit]
        self.page = page
        self.per_page = per_page

    @property
    def pages(self):
        if self.per_page == 0:
            pages = 0
        else:
            pages = int(ceil(self.total / float(self.per_page)))
        return pages

def uncamel(name):
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

class ResourceApi(FlaskView):
    trailing_slash = False
    endpoint_prefix = 'api'
    route_prefix = '/api'
    name_suffix = 'Api'
    obj = None

    @classmethod
    def build_route_name(cls, method_name):
        parts = []
        if hasattr(cls, 'endpoint_prefix') and cls.endpoint_prefix is not None:
            parts.append(cls.endpoint_prefix)
        parts.append(cls.get_basic_name())
        if method_name:
            parts.append(method_name)
        return '.'.join(parts)

    @classmethod
    def get_basic_name(cls):
        return uncamel(re.sub('(.)({})'.format(cls.name_suffix),
                              r'\1', cls.__name__))

    @classmethod
    def register(cls, app, route_base=None, subdomain=None, route_prefix=None,
                 trailing_slash=None):
        super(ResourceApi, cls).register(app, route_base=route_base,
                           subdomain=subdomain, route_prefix=route_prefix,
                           trailing_slash=trailing_slash)

        isnested = lambda o: isinstance(o, NestedApi)

        members = inspect.getmembers(cls, predicate=isnested)
        for name, value in members:
            nested_cls = value.nested_cls
            value.register(name, app, cls)

class NestedApi(object):

    def __init__(self, nested_cls, pk_name='pk', pk_converter='any',
                 getter='get_obj'):
        self.nested_cls = nested_cls
        self.pk_name = pk_name
        self.pk_converter = pk_converter
        self.getter = getter

    def register(self, attr_name, app, parent):
        """
        This is a lazy implementation to register nested api, by the moment
        this fits well for this project.
        """
        prefix_parts = []
        class cls(self.nested_cls):
            pass
        cls.__name__ = self.nested_cls.__name__

        getter = parent.__dict__.get(self.getter, None)
        if not getter or not isinstance(getter, classmethod):
            raise ValueError("Parent class ({}) must define '{}' as "
                    "classmethod".format(parent.__name__, self.getter))

        if parent.route_prefix:
            prefix_parts.append(parent.route_prefix)
        if parent.get_route_base():
            prefix_parts.append(parent.get_route_base())

        route_parts = [
            '<{}:{}>'.format(self.pk_converter, self.pk_name),
            attr_name,
        ]

        # change endpoint prefix for registration
        cls.endpoint_prefix = parent.build_route_name(None)

        cls.register(app, route_prefix='/'.join(prefix_parts),
                     route_base='/'.join(route_parts))

        def before_request(nested, name, **kwargs):
            pk = request.view_args.pop(self.pk_name, None)
            nested.obj = getattr(parent, self.getter)(pk)
            if hasattr(nested, 'orig_before_request'):
                return nested.orig_before_request(name, **request.view_args)

        if hasattr(cls, 'before_request'):
            cls.orig_before_request = cls.before_request
        cls.before_request = before_request
        cls.parent = parent

def build_result(query, schema):

    if is_collection(query):
        if hasattr(query, 'paginate') and callable(query.paginate):
            result = query.paginate(request.page, request.per_page)
        else:
            result = Pagination(query, request.page, request.per_page)

        out = {
            'num_results': result.total,
            'page': result.page,
            'num_pages': result.pages,
        }
        items = result.items

    else:
        items = query

    if request.select or request.omit:
        schema = copy.copy(schema)
        if list(request.select)[0]:
            schema.only = request.select.intersection(schema.fields.keys())
        if list(request.omit)[0]:
            only_set = set(schema.only or schema.fields.keys())
            schema.only = only_set.difference(request.omit)

        if schema.only:
            schema.only.add('id')

    if is_collection(items):
        out['objects'] = schema.dump(items, many=True).data
    else:
        out = schema.dump(items, many=False).data

    return jsonify(out)


import discord
from dice import diceroll as die
import sys
import asyncio
import random
from getfleethealth import hullhealth as hull
from getfleethealth import shieldhealth as shield
from getfleethealth import hullshipname as hullname
from getfleethealth import shieldregen as regen
from getfleethealth import verify as verify
from getfleethealth import shielddamage as shielddamage
from getfleethealth import hulldamage as hulldamage
from getfleethealth import damresist as damresist
from pve import botgroupcreation as bgc

dirr = sys.path[0]

def nonzero(lis):
    ran = random.choice(lis)
    while ran == 0:
        ran = random.choice(lis)
    if ran != 0:
        return ran

game_over = False
async def battle(authorusername, message, guildid, client, u1id, channelid, username, movetext):
    channel = client.get_channel(channelid)
    playerone = authorusername
    playertwo = message.replace("!battle ", '')
    userid = playertwo.replace(">", '').replace("<@!", "").replace("<@", "").replace("!", "")
    usertwo = await client.fetch_user(int(userid))
    poneshdamage = []
    ponehulldamage = []
    ptwoshdamage = []
    ptwohulldamage = []
    hullvals = []
    shieldvals = []
    hullvalstwo = []
    shieldvalstwo = []
    playeronedefeat = []
    playertwodefeat = []
    initshieldspone = []
    initshieldsptwo = []
    try:
        playertwoname = hullname(dirr, userid, guildid)
        name = hullname(dirr, u1id, guildid)
        initplayeroneembed=discord.Embed(title=playerone+"'s Units:", description=f'Units: {len(name)}', color=discord.Color.red())
    except Exception as e:
    	print(e)
    	await channel.send("Have both players made a group? Cancelling battle.")
    	return True
    for a in range(0, len(name)): # Player one
        try:
            p1name = name[a].replace("\n", "")
            poneshdamage.append(float(shielddamage(dirr, p1name, guildid))) # Player one collective fleet shield, and below it hull damage
            ponehulldamage.append(float(hulldamage(dirr, p1name, guildid)))
            hullvals.append(float(hull(dirr, username, p1name, guildid)))
            shieldvals.append(float(shield(dirr, username, p1name, guildid)))
            initshieldspone = shieldvals
            initplayeroneembed.add_field(name=name[a].replace("\n", ''), value="- " + "🛡: "+str(shieldvals[a])+ "\n" +" "+"❤:"+str(hullvals[a]), inline=True)
        except Exception as e:
            print(e)
            await channel.send(f"{playerone}, something went wrong with your group. Try remaking your fleet and check your spelling. Cancelling battle.")
            return True
        p1sd = poneshdamage
        p1hd = ponehulldamage

    await channel.send(embed=initplayeroneembed)
    await channel.send("------------------------")
    initplayertwoembed=discord.Embed(title=usertwo.display_name+"'s Units:", description=f'Units: {len(playertwoname)}', color=discord.Color.blue())
    for d in range(0, len(playertwoname)): # Player two
        try:
            p2name = playertwoname[d].replace("\n", "")
            ptwoshdamage.append(float(shielddamage(dirr, p2name, guildid))) # Player two collective fleet shield, and below it hull damage
            ptwohulldamage.append(float(hulldamage(dirr, p2name, guildid)))
            shieldvalstwo.append(float(shield(dirr, userid, p2name, guildid)))
            hullvalstwo.append(float(hull(dirr, userid, p2name, guildid)))
            initshieldsptwo = shieldvalstwo
            initplayertwoembed.add_field(name=playertwoname[d].replace("\n", ''), value="- " + "🛡: "+str(shieldvalstwo[d])+ "\n" +"- " +"❤: "+str(hullvalstwo[d]), inline=True)
        except:
            await channel.send(f"{usertwo.display_name}, something went wrong with your group. Try remaking your group and checking the exact spelling of the units you're using. Cancelling battle")
            return True
        p2sd = ptwoshdamage
        p2hd = ptwohulldamage
    await channel.send(embed=initplayertwoembed)
    roundnum = 0
    while not game_over: # Battle code starts here now that data is compiled
        roundnum += 1
        roundembed=discord.Embed(title="Round: "+str(roundnum), description='', color=0x00ff00)
        await channel.send(embed=roundembed)
        msg = await channel.send(usertwo.display_name+movetext)
        await msg.add_reaction("🔫")
        def check(reaction, user):
            return user == usertwo and str(reaction.emoji) == "🔫"
        try:
            turn = await client.wait_for('reaction_add', check=check, timeout=1800)
        except asyncio.TimeoutError:
            await channel.send("Battle has not continued in 30 minutes, battle concluding")
            await msg.clear_reaction("🔫")
            await msg.edit(content=msg.content + " (Reaction removed, battled ended due to inactivity).")
            return True
        shipembed=discord.Embed(title=playerone+"'s Ships:", description=f'Units alive last turn: {len(name) - len(playeronedefeat)}', color=discord.Color.red())
        for c in range(0, len(name)): # Player one gets attacked
            p1name = name[c].replace("\n", "")
            ptworoll = die(0, 100)
            if ptworoll == 0:
                shieldvals[c] -= 0
                hullvals[c] -= 0
                shieldvals[c] += float(regen(dirr, username, p1name, guildid))
                shipembed.add_field(name=name[c], value="- " + "🛡: " + str(round(shieldvals[c], 0))+ "\n" +"- " +"❤: " + str(round(hullvals[c], 0)), inline=True)
            else:
                shieldvals[c] += float(regen(dirr, username, p1name, guildid))
                shieldvals[c] -= (ptworoll + nonzero(p2sd)) / (len(name)/2) #/ float(damresist(dirr, username, p1name, guildid))
                if float(shieldvals[c]) <= 0:
                    shieldvals[c] = 0
                    hullvals[c] -= (ptworoll + nonzero(p2hd)) / (len(name)/2) #/ float(damresist(dirr, username, p1name, guildid))
                    if int(hullvals[c]) < 0:
                        hullvals[c] = 0
                        shipembed.add_field(name=p1name.capitalize(), value="- " + "🛡: "+str(round(shieldvals[c], 0))+ "\n" +"- " +"❤: "+str(round(hullvals[c], 0))+ "\n" +"- " +"Status: Defeated", inline=True)
                        if f"s {c} " not in playeronedefeat:
                            playeronedefeat.append(f"s {c}")
                            p1sd[c] = 0
                            p1hd[c] = 0
                        if len(playeronedefeat) == len(name):
                            await msg.clear_reaction("🔫")
                            await msg.edit(content=msg.content + " (Reaction removed, turn passed).")
                            endembed=discord.Embed(title="Defeat", description='', color=discord.Color.red())
                            endembed.add_field(name=playerone + "! " + "Your fleet has been defeated", value='You have lost the battle.', inline=True)
                            await channel.send(embed=endembed)
                            return True
                    else:
                        shipembed.add_field(name=p1name.capitalize(), value="- " + "🛡: "+str(round(shieldvals[c], 0))+ "\n" +"- " +"❤: "+str(round(hullvals[c], 0)), inline=True)
                else:
                    if shieldvals[c] > initshieldspone[c]:
                        shieldvals[c] = initshieldspone[c]
                    shipembed.add_field(name=name[c].replace("\n", '').capitalize(), value="- " + "🛡: "+str(round(shieldvals[c], 0))+ "\n" +"- " +"❤: "+str(round(hullvals[c], 0)), inline=True)
        await channel.send(embed=shipembed) # Sends message into discord with damage done to player one's ship.
        await msg.clear_reaction("🔫")
        await msg.edit(content=msg.content + " (Reaction removed, turn passed).")

        msg = await channel.send(playerone+movetext) # Start of player one's turn
        await msg.add_reaction("🔫")
        def check(reaction, user):
            return user == username and str(reaction.emoji) == "🔫"
        try:
            turntwo = await client.wait_for('reaction_add', check=check, timeout=1800)
        except asyncio.TimeoutError:
            await channel.send("Battle has not continued in 30 minutes, battle concluding.")
            await msg.clear_reaction("🔫")
            await msg.edit(content=msg.content + " (Reaction removed, battled ended due to inactivity).")
            return True
        shipembed=discord.Embed(title=usertwo.display_name+"'s Ships:", description=f'Units alive last turn: {len(playertwoname)- len(playertwodefeat)}', color=discord.Color.blue())
        for c in range(0, len(playertwoname)): # Player two gets attacked
            poneroll = die(0, 100)
            p2name = playertwoname[c].replace("\n", "")
            if poneroll == 0:
                shieldvalstwo[c] -= 0
                hullvalstwo[c] -= 0
                shieldvalstwo[c] += float(regen(dirr, usertwo.id, p2name, guildid))
                shipembed.add_field(name=p2name.capitalize(), value="- " + "🛡: "+str(round(shieldvalstwo[c], 0))+ "\n" +"- " +"❤: "+str(round(hullvalstwo[c], 0)), inline=True)
            else:
                shieldvalstwo[c] -= (poneroll + nonzero(p1sd)) / (len(playertwoname)/2) #/ float(damresist(dirr, usertwo.id, p2name, guildid))
                shieldvalstwo[c] += float(regen(dirr, usertwo.id, p2name, guildid))
                if float(shieldvalstwo[c]) <= 0:
                    shieldvalstwo[c] = 0
                    hullvalstwo[c] -= (poneroll + nonzero(p1hd)) / (len(playertwoname)/2)  #/ float(damresist(dirr, usertwo.id, p2name, guildid))
                    if float(hullvalstwo[c]) < 0:
                        hullvalstwo[c] = 0
                        shipembed.add_field(name=playertwoname[c].replace("\n", '').capitalize(), value="- " + "🛡: "+str(round(shieldvalstwo[c], 0))+ "\n" +"- " +"❤: "+str(round(hullvalstwo[c], 0))+ "\n" +"- " +"Status: Defeated", inline=True)
                        if f"s {c}" not in playertwodefeat:
                            playertwodefeat.append(f"s {c}")
                            p2sd[c] = 0
                            p2hd[c] = 0
                        if len(playertwodefeat) == len(playertwoname):
                            await msg.clear_reaction("🔫")
                            await msg.edit(content=msg.content + " (Reaction removed, turn passed).")
                            endembed=discord.Embed(title="Defeat", description='', color=discord.Color.blue())
                            endembed.add_field(name=usertwo.display_name + "! " + "Your fleet has been defeated", value='You have lost the battle.', inline=True)
                            await channel.send(embed=endembed)
                            return True
                    else:
                        shipembed.add_field(name=playertwoname[c].replace("\n", '').capitalize(), value="- " + "🛡: "+str(round(shieldvalstwo[c], 0))+ "\n" +"- " +"❤: "+str(round(hullvalstwo[c], 0)), inline=True)
                else:
                    if shieldvalstwo[c] > initshieldsptwo[c]:
                        shieldvalstwo[c] = initshieldsptwo[c]
                    shipembed.add_field(name=playertwoname[c].replace("\n", '').capitalize(), value="- " + "🛡: "+str(round(shieldvalstwo[c], 0))+ "\n" +"- " +"❤: "+str(round(hullvalstwo[c], 0)), inline=True)
        await channel.send(embed=shipembed) # Sends message into discord with damage done to player two's ship.
        await msg.clear_reaction("🔫")
        await msg.edit(content=msg.content + " (Reaction removed, turn passed).")


from tasksbase import *

__package__ = "allrobotpy"

from .hal import _tasks as hal_tasks
from .halsim_ds_socket import _tasks as halsim_ds_socket_tasks
from .halsim_gui import _tasks as halsim_gui_tasks
from .halsim_ws import _tasks as halsim_ws_tasks
from .ntcore import _tasks as ntcore_tasks
from .romi import _tasks as romi_tasks
from .wpilib import _tasks as wpilib_tasks
from .wpimath import _tasks as wpimath_tasks
from .wpinet import _tasks as wpinet_tasks
from .wpiutil import _tasks as wpiutil_tasks

everything = [
    hal_tasks,
    halsim_ds_socket_tasks,
    halsim_gui_tasks,
    halsim_ws_tasks,
    ntcore_tasks,
    romi_tasks,
    wpilib_tasks,
    wpimath_tasks,
    wpinet_tasks,
    wpiutil_tasks,
]

namespace = Collection()

for module in everything:
    namespace.add_collection(
        Collection.from_module(module, name=module.__package__.split(".")[-1])
    )

allow_dot_subdir_commands(namespace)

@task(pre=[t.develop for t in everything])
def develop(ctx: Context):
    ...

@task(pre=[t.build_wheel for t in everything])
def build_wheel(ctx: Context):
    ...

@task(pre=[t.test for t in everything])
def test(ctx: Context):
    ...

@task(pre=[build_wheel, test])
def build_and_test(ctx: Context):
    ...

@task(pre=[t.clean for t in everything])
def clean(ctx: Context):
    ...

@task
def generate_github_actions(ctx: Context):
    generate_github_actions_()

@task
def python(ctx: Context):
    subprocess.run("python", cwd=Path(ctx.cwd, "nothing/").resolve())

namespace.add_task(develop)  # type: ignore
namespace.add_task(build_wheel)  # type: ignore
namespace.add_task(test)  # type: ignore
namespace.add_task(build_and_test)  # type: ignore
namespace.add_task(clean)  # type: ignore
namespace.add_task(generate_github_actions)  # type: ignore
namespace.add_task(python)  # type: ignore

namespace.configure(
    {
        "python": sys.executable,
        "parallel": True,
        # "parallel": False,
        "cc_launcher": "ccache",
        # "cc_launcher": "",
        "macos_target": "11",
        "strip_libpython": True,
        # "skip_installed_deps": True,
        "skip_installed_deps": False,
        # "no_generation": True,
        "no_generation": False,
        "run": {
            # "hide": "both",
            # "hide": False,
            "echo": True
        },
    }
)


import sqlite3
import time
import tkinter
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkcalendar import DateEntry
from tkinter import messagebox
import receipt_backend

class Receipt(tk.Frame):
    def __init__(self, master=None, **kw):
        super().__init__(master, **kw)
        self.master = master
        self.pack()

        self.RECEIPT = StringVar()
        self.Student_Name = StringVar()
        self.Admission = StringVar()
        self.Date = StringVar()
        self.Branch = StringVar()
        self.Semester = StringVar()
        self.Total_amount = StringVar()
        self.Paid = StringVar()
        self.Balance = StringVar()

        self.create_frame()
        self.create_label()
        self.create_entry()
        self.create_scroll_bar()
        self.create_button()
        self.display()

    def OneSelected(self, event):
        global id
        try:
            self.curItem = self.receipt_table.focus()
            self.contents = (self.receipt_table.item(self.curItem))
            self.selecteditem = self.contents['values']
            self.id = self.selecteditem[0]

            self.RECEIPT.set('')
            self.RECEIPT.set(self.selecteditem[1])

            self.Student_Name.set('')
            self.Student_Name.set(self.selecteditem[2])

            self.Admission.set('')
            self.Admission.set(self.selecteditem[3])

            self.Date.set('')
            self.Date.set(self.selecteditem[4])

            self.Branch.set('')
            self.Branch.set(self.selecteditem[5])

            self.Semester.set('')
            self.Semester.set(self.selecteditem[6])

            self.Total_amount.set('')
            self.Total_amount.set(self.selecteditem[7])

            self.Paid.set('')
            self.Paid.set(self.selecteditem[8])

            self.Balance.set('')
            self.Balance.set(self.selecteditem[9])
        except IndexError:
            tkinter.messagebox.showwarning('', 'Please Select A Something !', icon="warning")

    def Save(self):
        if self.RECEIPT.get() == "" or self.Student_Name.get() == "" or self.Admission.get() == "" or \
                self.Date.get() == "" or self.Branch.get() == "" or self.Semester.get() == "" or \
                self.Total_amount.get() == "" or self.Paid.get() == "":
            tkinter.messagebox.showwarning('', 'Please Complete The Required Field', icon="warning")
        else:
            receipt_backend.insert(self.RECEIPT.get(), self.Student_Name.get(), self.Admission.get(),
                                   self.Date.get(), self.Branch.get(), self.Semester.get(),
                                   self.Total_amount.get(), self.Paid.get(), self.Balance.get())
            tkinter.messagebox.showinfo("Success", "Receipt Saved Successfully")

    def Update(self):
        self.receipt_table.delete(*self.receipt_table.get_children())
        self.conn = sqlite3.connect('UE.db')
        self.cur = self.conn.cursor()
        self.cur.execute("UPDATE `fee` SET `receipts` = ?, `name` = ?, `admin` =?, `date` = ?,  "
                         "`branch` = ?, `semester` = ?, `total` = ?, `paid` = ?, "
                         "`due` = ? WHERE `id` = ?",
                         (str(self.RECEIPT.get()), str(self.Student_Name.get()),
                          str(self.Admission.get()), str(self.Date.get()),
                          str(self.Branch.get()), str(self.Semester.get()),
                          str(self.Total_amount.get()), str(self.Paid.get()),
                          str(self.Balance.get()), str(id)))
        self.conn.commit()
        self.cur.execute("SELECT * FROM `fee` ORDER BY `name` ASC")
        self.fetch = self.cur.fetchall()
        for data in self.fetch:
            self.receipt_table.insert('', 'end', values=(data))
        self.cur.close()
        self.conn.close()

    def display(self):
        if len(receipt_backend.view()) != 0:
            self.receipt_table.delete(*self.receipt_table.get_children())
            for row in receipt_backend.view():
                self.receipt_table.insert('', END, values=row)

    def Reset(self):
        self.RECEIPT.set('')
        self.Student_Name.set('')
        self.Admission.set('')
        self.Branch.set('')
        self.Semester.set('')
        self.Paid.set('')
        self.Balance.set('')

    def delete(self):
        if not self.receipt_table.selection():
            result = tkinter.messagebox.showwarning('', 'Please Select Something First!', icon="warning")
        else:
            result = tkinter.messagebox.askquestion('', 'Are you sure you want to delete this record?', icon="warning")
            if result == 'yes':
                self.curItem = self.receipt_table.focus()
                self.contents = (self.receipt_table.item(self.curItem))
                self.selecteditem = self.contents['values']
                self.receipt_table.delete(self.curItem)
                self.conn = sqlite3.connect("UE.db")
                self.cursor = self.conn.cursor()
                self.cursor.execute("DELETE FROM `fee` WHERE `id` = %d" % self.selecteditem[0])
                self.conn.commit()
                self.cursor.close()
                self.conn.close()

    def Receipt(self):
        self.display_receipt.delete('1.0', END)
        self.display_receipt.insert(END, '\t\tRECEIPT' + '\n\n')
        self.display_receipt.insert(
            END, '\tReceipt No.\t      :' + self.RECEIPT.get() + '\n')
        self.display_receipt.insert(END, '\tStudent Name  :' +
                                    self.Student_Name.get() + '\n')
        self.display_receipt.insert(END, '\tAdmission No.\t:' +
                                    self.Admission.get() + '\n')
        self.display_receipt.insert(
            END, '\tDate\t          : ' + self.Date.get() + '\n')
        self.display_receipt.insert(
            END, '\tBranch\t          :' + self.Branch.get() + '\n')
        self.display_receipt.insert(
            END, '\tSemester \t        :' + self.Semester.get() + '\n\n')

        try:
            x1 = int(self.Total_amount.get())
            x2 = int(self.Paid.get())
            x3 = int(x1 - x2)

            self.display_receipt.insert(END, '\tTotal Amount  :' + str(x1) + '\n')
            self.display_receipt.insert(END, '\tPaid Amount   :' + str(x2) + '\n')
            self.display_receipt.insert(END, '\tBalance\t         :' + str(x3) + '\n')
            self.Balance.set(x3)
        except ValueError:
            pass

    def exit(self):
        Exit = tkinter.messagebox.askyesno("Logout System", "Confirm, if you want to Exit")
        if Exit > 0:
            self.master.destroy()
            return

    # -------------------------------- Frames -------------------------------------------------------
    def create_frame(self):
        global frame_title
        global Frame_2
        global Frame_3

        frame_title = Frame(self.master, bg="aquamarine4", bd=10, relief=SUNKEN)
        frame_title.pack()
        self.Main_Frame = LabelFrame(self.master, font=('Courier', 15, 'bold'),
                                     bg='aquamarine4', bd=15, fg='White', relief='ridge')
        self.Main_Frame.place(x=10, y=80, width=1330, height=350)

        self.Frame_1 = LabelFrame(self.master,
                                  font=('Courier', 15, 'bold'),
                                  relief='ridge', bd=10, bg='aquamarine4', fg='White', text='INFORMATION')
        self.Frame_1.place(x=35, y=105, width=700, height=300)

        self.Frame_2 = LabelFrame(self.master,
                                  font=('Courier', 15, 'bold'),
                                  relief='ridge', bd=10, fg='White', bg='aquamarine4', text='FEE RECEIPT')
        self.Frame_2.place(x=770, y=105, width=550, height=300)

        self.Frame_3 = LabelFrame(self.master, width=1180, height=70, font=('Courier', 10, 'bold'),
                                  bg='aquamarine4', relief='ridge', bd=13, fg='White')
        self.Frame_3.place(x=75, y=665)

        self.Frame_4 = LabelFrame(self.master, font=('Courier', 10, 'bold'),
                                  bg='aquamarine4', relief='ridge', bd=13, fg='White')
        self.Frame_4.place(x=22, y=450, width=1300, height=200)

    # -------------------------------- Labels -------------------------------------------------------
    def create_label(self):
        label_title1 = Label(frame_title, text='FEE REPORT', font=('Courier', 20, 'bold'),
                             bg='aquamarine4', fg='White').pack()

        self.label_Receipt = Label(self.Frame_1, text='Receipt No', font=('Courier', 16), bg='aquamarine4',
                                   fg='White')
        self.label_Receipt.place(x=10, y=20)

        self.Student_name_label = Label(self.Frame_1, text='Student Name', font=('Courier', 16), bg='aquamarine4',
                                        fg='White')
        self.Student_name_label.place(x=10, y=60)

        self.label_Admission = Label(self.Frame_1, text='Admission No', font=('Courier', 16), bg='aquamarine4',
                                     fg='White')
        self.label_Admission.place(x=10, y=100)

        self.Date_label = Label(self.Frame_1, text='Date', font=('Courier', 16), bg='aquamarine4',
                                fg='White')
        self.Date_label.place(x=10, y=140)

        self.Branch_label = Label(self.Frame_1, text='Branch', font=('Courier', 16), bg='aquamarine4',
                                  fg='White')
        self.Branch_label.place(x=10, y=180)

        self.Semester_label = Label(self.Frame_1, text='Session', font=('Courier', 16), bg='aquamarine4',
                                    fg='White')
        self.Semester_label.place(x=10, y=220)

        self.TOTAL_AMOUNT_label = Label(self.Frame_1, text='TOTAL AMOUNT', font=('Courier', 16), bg='aquamarine4',
                                        fg='White')
        self.TOTAL_AMOUNT_label.place(x=375, y=100)

        self.PAID_label = Label(self.Frame_1, text='PAID AMOUNT', font=('Courier', 16), bg='aquamarine4',
                                fg='White')
        self.PAID_label.place(x=375, y=140)

        self.BALANCE_label = Label(self.Frame_1, text='BALANCE', font=('Courier', 16), bg='aquamarine4',
                                   fg='White')
        self.BALANCE_label.place(x=375, y=180)

    # -------------------------------- Entry -------------------------------------------------------
    def create_entry(self):
        self.Entry_receipt = Entry(self.Frame_1, font=('arial', 10), textvariable=self.RECEIPT)
        self.Entry_receipt.focus()
        self.Entry_receipt.place(x=190, y=20)

        self.Entry_StudentName = Entry(self.Frame_1, font=('arial', 10), textvariable=self.Student_Name)
        self.Entry_StudentName.place(x=190, y=60)

        self.Entry_Admission = Entry(self.Frame_1, font=('arial', 10), textvariable=self.Admission)
        self.Entry_Admission.place(x=190, y=100)

        self.Entry_date = DateEntry(self.Frame_1, font=('arial', 12), date_pattern='dd/mm/yyyy', textvariable=self.Date)
        self.Entry_date.place(x=190, y=140, width=145)

        self.Entry_branch = ttk.Combobox(self.Frame_1, values=(' ', 'Computer Science', 'Science Of Education',
                                                               'Business Management'),
                                         font=('arial', 10), width=21, textvariable=self.Branch)
        self.Entry_branch.place(x=190, y=180, width=145)

        self.Entry_semester = ttk.Combobox(self.Frame_1, values=(' ', 'FIRST', 'SECOND'),
                                           font=('arial', 10), textvariable=self.Semester)
        self.Entry_semester.place(x=190, y=220, width=145)

        self.Entry_total_amount = Entry(self.Frame_1, font=('arial', 12), bg='Azure2', textvariable=self.Total_amount,
                                        state='readonly')
        self.Entry_total_amount.place(x=540, y=100, width=100, height=25)
        self.Total_amount.set(24000)

        self.Entry_paid = Entry(self.Frame_1, font=('arial', 12), bg='Azure2', textvariable=self.Paid)
        self.Entry_paid.place(x=540, y=140, width=100, height=25)
        self.Paid.set(0.0)

        self.Entry_balance = Entry(self.Frame_1, font=('arial', 12), bg='Azure2', textvariable=self.Balance, )
        self.Entry_balance.place(x=540, y=180, width=100, height=25)
        self.Balance.set(0.0)

    # -------------------------------- Scroll Bar And Text -------------------------------------------------------
    def create_scroll_bar(self):
        global receipt_table
        global display_receipt

        self.x_scroll = Scrollbar(self.Frame_4, orient=HORIZONTAL)
        self.y_scroll = Scrollbar(self.Frame_4, orient=VERTICAL)
        self.receipt_table = tkinter.ttk.Treeview(self.Frame_4,
                                                  column=('No', 'receipt_no', 'student_name', 'admission_no', 'date',
                                                          'branch', 'semester', 'total_amount', 'paid_amount'),
                                                  xscrollcommand=self.x_scroll.set, yscrollcommand=self.y_scroll.set)

        self.x_scroll.pack(side=BOTTOM, fill=X)
        self.y_scroll.pack(side=RIGHT, fill=Y)
        self.x_scroll.config(command=self.receipt_table.xview)
        self.y_scroll.config(command=self.receipt_table.yview)

        self.receipt_table.heading('receipt_no', text='Receipt No')
        self.receipt_table.heading('student_name', text='Student Name')
        self.receipt_table.heading('admission_no', text='Admission No')
        self.receipt_table.heading('date', text='Date')
        self.receipt_table.heading('branch', text='Branch')
        self.receipt_table.heading('semester', text='Semester')
        self.receipt_table.heading('total_amount', text='Total Amount')
        self.receipt_table.heading('paid_amount', text='Paid Amount')
        self.receipt_table.heading('No', text='No')
        self.receipt_table['show'] = 'headings'
        self.receipt_table.column('receipt_no', width=70)
        self.receipt_table.column('No', width=30)
        self.receipt_table.pack(fill=BOTH, expand=1)
        self.receipt_table.bind('<Double-Button-1>', self.OneSelected)

        self.display_receipt = Text(self.Frame_2, font=('arial', 14, 'bold'), bg='Azure2')
        self.display_receipt.place(x=0, y=0, width=530, height=265)

    # -------------------------------- Button -------------------------------------------------------

    def create_button(self):
        self.button_save = Button(self.Frame_3, text="SAVE", font=('Courier', 15, 'bold'), bg='aquamarine4', fg="White",
                                  width=12, command=self.Save)
        self.button_save.place(x=5, y=2)
        self.button_save.config(activebackground="#41B77F", relief=RAISED)

        self.button_display = Button(self.Frame_3, text='DISPLAY', font=('Courier', 15, 'bold'), bg='aquamarine4',
                                     fg="White", width=12, command=self.display)
        self.button_display.place(x=170, y=2)
        self.button_display.config(activebackground="#41B77F", relief=RAISED)

        self.button_reset = Button(self.Frame_3, text='RESET', font=('Courier', 15, 'bold'), bg='aquamarine4',
                                   fg="White", width=12, command=self.Reset)
        self.button_reset.place(x=335, y=2)
        self.button_reset.config(activebackground="#41B77F", relief=RAISED)

        self.button_update = Button(self.Frame_3, text='UPDATE', font=('Courier', 15, 'bold'), bg='aquamarine4',
                                    fg="White", width=12, command=self.Update)
        self.button_update.place(x=500, y=2)
        self.button_update.config(activebackground="#41B77F", relief=RAISED)

        self.button_delete = Button(self.Frame_3, text='DELETE', font=('Courier', 15, 'bold'), bg='aquamarine4',
                                    fg="White", width=12, command=self.delete)
        self.button_delete.place(x=665, y=2)
        self.button_delete.config(activebackground="#41B77F", relief=RAISED)

        self.button_receipt = Button(self.Frame_3, text='RECEIPT', font=('Courier', 15, 'bold'), bg='aquamarine4',
                                     fg="White", width=12, command=self.Receipt)
        self.button_receipt.place(x=830, y=2)
        self.button_receipt.config(activebackground="#41B77F", relief=RAISED)

        self.button_exit = Button(self.Frame_3, text='EXIT', font=('Courier', 15, 'bold'), bg='aquamarine4',
                                  fg="White", width=12, command=self.exit)
        self.button_exit.place(x=995, y=2)
        self.button_exit.config(activebackground="#41B77F", relief=RAISED)

        self.localtime = time.asctime(time.localtime(time.time()))
        self.lbl_time = Label(self.master, text=self.localtime, fg="white", font=("Courier", 16), bg="aquamarine4")
        self.lbl_time.place(x=1017, y=50)

root = tk.Tk()
root.geometry("1350x750")
root.resizable(False, False)
root.title("Université Espoir")
root.iconbitmap("logo1.ICO")
root.config(background="aquamarine4")

app = Receipt(master=root)
app.mainloop()


import os
import struct
import numpy as np

import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F

## Network structure
class myNetwork(nn.Module):
    def __init__(self):
        super(myNetwork,self).__init__()
        self.fc = nn.Sequential(nn.Linear(3,64),
                                    nn.ReLU(inplace=True),
                                    nn.Linear(64,16),
                                    nn.ReLU(inplace=True),
                                    nn.Linear(16,1))

    def forward(self, data_input):
        out = self.fc(data_input)
        return out

## Data folders
class myTrainFolder(torch.utils.data.Dataset):
    def __init__(self, data_file, gt_file, training=True):
        dataset = self._read_data(data_file)
        gt = self._read_gt(gt_file)
        n = dataset.shape[0]
        assert n==gt.shape[0]
        if training:
            self.dataset = dataset[:int(n*0.8),:]
            self.gt = gt[:int(n*0.8)]
        else:
            self.dataset = dataset[int(n*0.8):,:]
            self.gt = gt[int(n*0.8):]

    def _read_data(self, file_name):
        with open(file_name, 'r') as f1:
            content = f1.read()
            content = content.split('\n')[1:-1]
            content = ('\t'.join(content)).split('\t')
            out = np.array([float(a) for a in content])
            return out.reshape([-1, 3])

    def _read_gt(self, file_name):
        with open(file_name, 'r') as f1:
            content = f1.read()
            content = content.split('\n')[1:-1]
            content = ('\t'.join(content)).split('\t')
            out = np.array([float(a) for a in content])
            return out

    def __getitem__(self, index):
        data = torch.from_numpy(self.dataset[index]).type(torch.float)
        gt = torch.tensor(self.gt[index]).type(torch.float)
        return data, gt

    def __len__(self):
        return self.dataset.shape[0]

class myTestFolder(torch.utils.data.Dataset):
    def __init__(self, data_file):
        self.dataset = self._read_data(data_file)

    def _read_data(self, file_name):
        with open(file_name, 'r') as f1:
            content = f1.read()
            content = content.split('\n')[1:-1]
            content = ('\t'.join(content)).split('\t')
            out = np.array([float(a) for a in content])
            return out.reshape([-1, 3])

    def __getitem__(self, index):
        data = torch.from_numpy(self.dataset[index]).type(torch.float)
        return data

    def __len__(self):
        return self.dataset.shape[0]

## result writer
def write_result(file_name, result):
    with open(file_name, 'w') as f1:
        f1.write('y\n')
        for row in range(len(result)):
            f1.write(str(result[row]) + '\n')


##### wrappers #####
# - - - - - - - - - - -
# Source file for bare wrapper functions. Source:
# https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/
#
# To run the test case, execute something like
#   `python -m src.wrappers`
# in the terminal.
# ------------------------------------------------------------------------------

# %% Imports
# ------------------------------------------------------------------------------

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras as keras

from .masked_keras import MaskedModel, StaticMaskedModel, TrackableMaskedModel

# ------------------------------------------------------------------------------

# %% Utils
# ------------------------------------------------------------------------------

def mean_rel_diff(x1, x2):
    """Mean-Relative Difference between to tensors of arbitrary shape
    """
    ## Calculating the mean magnitude for each element
    means = ( np.abs(x1) + np.abs(x2) ) / 2.
    ## Replacing nans with infs (means=0 where diffs=0)
    means[means==0] = np.inf
    ## Calculating the absolute differences
    diffs = np.abs(x1 - x2)
    ## Calculaing relative (to mean magnitude) absolute differences
    rel_diffs = diffs / means

    return np.mean(rel_diffs)

def normalize_img_data(X: np.ndarray) -> np.ndarray:
    """Img-Preprocessing
    """
    X = X.astype(np.float32) / 255.
    X = np.expand_dims(X, -1)
    return X

def load_mnist(n_test_data: int=60000):
    """MNist loading and preprocessing
    """
    (X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
    assert X_train.shape == (60000, 28, 28)
    assert X_test.shape  == (10000, 28, 28)
    assert y_train.shape == (60000,)
    assert y_test.shape  == (10000,)
    num_classes = 10
    assert set(np.unique(y_train)) == set(np.arange(num_classes))

    if n_test_data > 60000:
        print("Requested more training data than possible. Getting maximum 60k.")
        n_test_data = 60000

    ## Preprocessing
    X_train = normalize_img_data(X_train)[:n_test_data]
    X_test  = normalize_img_data(X_test)

    ## Shuffeling
    shuffler = np.random.permutation(len(y_train))
    X_train = X_train[shuffler]
    y_train = y_train[shuffler]

    ## Reshaping
    y_train = keras.utils.to_categorical(y_train, num_classes)[:n_test_data]
    y_test  = keras.utils.to_categorical(y_test, num_classes)

    return (X_train, y_train), (X_test, y_test)

def model_accuracy(model, X, y):
    """Accuracy Macro
    """
    y_pred = model(X)
    y_pred = tf.cast(tf.argmax(y_pred, axis=1), tf.int32)
    y      = tf.cast(tf.argmax(y, axis=1), tf.int32)
    return tf.reduce_mean(tf.cast(y_pred == y, tf.float32)).numpy()

def random_batch(X, y, batch_size=128):
    """Generates random batches from data
    """
    idx = np.random.randint(len(X), size=batch_size)
    return X[idx], y[idx]

def non_random_batch(X, y, n, batch_size=128):
    """Generates deterministic batches from data (for reproducability).
    """
    n_max = X.shape[0] // batch_size
    n = n%n_max
    X_batch = X[n*batch_size : (n+1)*batch_size]
    y_batch = y[n*batch_size : (n+1)*batch_size]
    return X_batch, y_batch

## ProsPr Scores:
#  These would be the last necessairy steps to calculate the scores if the
#  calculation of meta gradients and / or streaming product would work.
# ------------------------------------------------------------------------------

def compute_prospr_scores(
    Jvps: list[np.ndarray],
    model: MaskedModel,
    X_train: np.ndarray,
    y_train: np.ndarray,
    loss_fn: keras.losses.Loss,
    prune_sg_lr: float=0.1):

    ## Final Prune Factor (maybe switch X_train, y_train to X_batch, y_batch ~ last batch)
    with tf.GradientTape() as tape:
        y_pred = model(X_train, training=True)
        loss = loss_fn(y_train, y_pred)
    final_prune_gradients = tape.gradient(loss, model.proper_weights)
    for w, g in zip(model.proper_weights, final_prune_gradients):
        w.assign(w - prune_sg_lr * g) # Final Update step

    meta_gradients = []
    for Jvp, g_prune in zip(Jvps, final_prune_gradients):
        meta_gradients.append(Jvp * g_prune)

    ## Generate Saliency Scores
    denominator = 0
    for meta_g in meta_gradients:
        denominator += tf.reduce_sum(meta_g)
    scores = []
    for meta_g in meta_gradients:
        scores.append(tf.abs(meta_g / denominator))

    return scores

def compute_prospr_scores_unmasked_model(
    Jvps: list[np.ndarray],
    model: keras.Model,
    X_train: np.ndarray,
    y_train: np.ndarray,
    loss_fn: keras.losses.Loss,
    prune_sg_lr: float=0.1):

    ## Final Prune Factor (maybe switch X_train, y_train to X_batch, y_batch ~ last batch)
    with tf.GradientTape() as tape:
        y_pred = model(X_train, training=True)
        loss = loss_fn(y_train, y_pred)
    final_prune_gradients = tape.gradient(loss, model.trainable_weights)
    for w, g in zip(model.trainable_weights, final_prune_gradients):
        w.assign(w - prune_sg_lr * g) # Final Update step

    meta_gradients = []
    for Jvp, g_prune in zip(Jvps, final_prune_gradients):
        meta_gradients.append(Jvp * g_prune)

    ## Generate Saliency Scores
    denominator = 0
    for meta_g in meta_gradients:
        denominator += tf.reduce_sum(meta_g)
    scores = []
    for meta_g in meta_gradients:
        scores.append(tf.abs(meta_g / denominator))

    return scores

def compute_prospr_scores_from_meta_g(meta_gradients: list[np.ndarray]):

    ## Generate Saliency Scores
    denominator = 0
    for meta_g in meta_gradients:
        denominator += tf.reduce_sum(meta_g)
    scores = []
    for meta_g in meta_gradients:
        scores.append(tf.abs(meta_g / denominator))

    return scores

## Pruning Mask Generators
# ------------------------------------------------------------------------------

def generate_total_pruning_mask(
    scores,
    keep_top: float=0.2):
    """Generates total (not layer-wise) pruning masks from scores.
    """
    if isinstance(scores[0], tf.Tensor):
        flattened_scores = np.concatenate([
            score.numpy().flatten() for score in scores
        ])
    if isinstance(scores[0], np.ndarray):
        flattened_scores = np.concatenate([
            score.flatten() for score in scores
        ])
    quantile = np.quantile(flattened_scores, q=1-keep_top)

    masks = []
    for score in scores:
        mask = tf.cast(score > quantile, dtype=tf.int16)
        masks.append(mask.numpy())

    return masks

def generate_pruning_mask(
    scores,
    sparsity: float=0.8,
    dtype=tf.float32):
    """Generates layer-wise pruning masks from scores.
    """
    if isinstance(scores[0], tf.Tensor):
        scores = [score.numpy() for score in scores]
    masks = []
    for score in scores:
        score_flat = score.flatten()
        quantile = np.quantile(
            score_flat,
            q=np.clip(sparsity, a_min=0., a_max=1.))
        mask = tf.cast(score > quantile, dtype=dtype).numpy()
        masks.append(mask)

    return masks

def generate_random_pruning_mask( ## Layer-wise RANDOM pruning
    weight_shapes: list[tf.TensorShape],
    sparsity: float=0.8):
    """Generates layer-wise random pruning masks.
    """
    masks = []
    for shp in weight_shapes:
        n_params_weights = shp.num_elements()
        p0 = np.clip(sparsity, a_min=0., a_max=1.)
        p1 = np.clip(1. - p0, a_min=0., a_max=1.)
        n0 = int(np.round(p0 * n_params_weights, 0))
        n1 = int(np.round(p1 * n_params_weights, 0))

        choices = n0*[0] + n1*[1]

        if n0 + n1 > n_params_weights:
            drop_choice = np.random.choice(2, size=1, p=[p1, p0])
            choices.remove(drop_choice)

        if n0 + n1 < n_params_weights:
            additional_choice = np.random.choice(2, size=1, p=[p0, p1])
            choices.append(additional_choice)

        assert len(choices) == n_params_weights, "Number of choices not correct."

        if np.all(np.array(choices) == 0):
            choices[0] = 1

        mask = np.random.permutation(choices)
        masks.append(np.reshape(mask, shp))

    return masks

# ------------------------------------------------------------------------------


# settings.py

from langchain.callbacks.base import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler

def init_settings(retriever, llm, chain):
    retriever.search_kwargs['distance_metric'] = 'cos'
    retriever.search_kwargs['fetch_k'] = 10
    retriever.search_kwargs['maximal_marginal_relevance'] = True
    retriever.search_kwargs['k'] = 10

    llm.model_name = 'gpt-3.5-turbo'
    llm.temperature = 0
    llm.streaming = True
    llm.callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
    llm.verbose = True

    chain.max_tokens_limit = 4096
    chain.return_source_documents = True

    return retriever, llm, chain


import string
from chatFun import greeting, response, read_json, stemSentence

# read file, json is imported as a dict {intent:response}
my_dict = read_json("depresie.json")

# break dict in sentences and responses
sent_tokens = [k for (k, v) in my_dict.items()]
responses = [v for (k, v) in my_dict.items()]

# Remove punctuation marks from sentences
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
sent_tokens = [sent.translate(remove_punct_dict) for sent in sent_tokens]

print(stemSentence(sent_tokens[1]))

flag = True
print("ROBO: Ma numesc ROBO. Voi raspunde intrebarilor despre depresie. Daca vrei sa iesi scrie pa")
while flag:
    user_response = input()
    user_response = user_response.lower()
    if user_response != 'pa':
        if greeting(user_response) is not None:
            print("ROBO: " + greeting(user_response))
        else:
            print("ROBO: ", end="")
            print(response(user_response, sent_tokens, responses))
            sent_tokens.remove(user_response)
    else:
        flag = False
        print("ROBO: Sanatate!")


from pytube import YouTube

# Define function to download video from YouTube with the highest resolution using the pytube library.
def Down(giv_link):
    youtubeObject = YouTube(giv_link)
    youtubeObject = youtubeObject.streams.get_highest_resolution()
    try:
        youtubeObject.download()
    except:
        print("An error has occurred")
    print("Download is completed successfully")

giv_link = input("Paste the link of the YouTube video you want to download: ")
# Calls the download funtion and downloads input URL to home directory, in the folder.
Down(giv_link)


"""
test_objects.py
Unit tests for Game and GameObject methods.
"""
# Python standard library

# Third-party modules
import pytest

# Local modules
from objects import GameBoard, Ship
from enums import Directions

@pytest.fixture(scope="function")
def gameboard() -> GameBoard:
    """
    Fixture for creating an empty GameBoard object with size 2x2
    """
    gameboard = GameBoard(1, 1)

    yield gameboard

@pytest.fixture(scope="session")
def ship() -> Ship:
    """
    Fixture for creating a ship object that can scan and move
    """
    ship = Ship(
        scan_radius=1,
        movement_speed=1,
        actions=("movement", "sensors"),
        formal_name="MCRN Donnager",
        phrase_key="pytest_ship",
    )

    yield ship

def test_move(gameboard: GameBoard, ship: Ship):

    """
    Tests objects get moved and information for both player and board get updated successfully
    """

    gameboard.add_ship_to_board(ship, (0, 0))

    assert ship.coordinates == (0, 0)
    assert (0, 0) in gameboard.occupied_squares.keys()

    gameboard.move_object(ship, (1, 1))
    assert ship.coordinates == (1, 1)
    assert (1, 1) in gameboard.occupied_squares.keys()
    assert (0, 0) not in gameboard.occupied_squares.keys()

# This is kind of gross, but we want a second ship fixture with different names/phrase keys for test_scan.
newship = ship

def test_scan(gameboard: GameBoard, ship: ship, newship: ship, capfd: pytest.fixture):
    """
    Add another ship to the board and run the scan function.
    Check the output matches what is expected.
    """
    newship.formal_name = "USS Reliant"
    newship.phrase_key = "pytest_scan_target"
    print(ship.name)

    gameboard.add_ship_to_board(ship, (0, 0))
    gameboard.add_ship_to_board(newship, (0, 1))

    ship.scan(gameboard.occupied_squares)
    out, err = capfd.readouterr()
    EXPECTED_SCAN_OUTPUT = '\nTarget: USS Reliant detected. This object is 1 sectors from here.\nTarget: MCRN Donnager detected. This object is 0 sectors from here.\n'
    assert out == EXPECTED_SCAN_OUTPUT

def test_calculate_updated_location_and_validate(gameboard: GameBoard):

    """
    Tests movement direction and validation logic.
    """
    direction = Directions.EAST
    location = (0, 0)
    speed = 1

    new_location = gameboard.calculate_updated_location_and_validate(
        location, (direction, speed)
    )

    assert new_location != (0, 1)

    # This is a movement off the board and should return None.
    direction = Directions.WEST
    new_location = gameboard.calculate_updated_location_and_validate(
        location, (direction, speed)
    )
    assert new_location is None

def test_add_ship_to_board(gameboard, ship):

    """
    Tests that randomly adding ships will fill up the board
    Also tests that adding ship to full board or occupied square will fail as expected
    """

    for _ in range(0, 4):
        gameboard.add_ship_to_board(ship)

    # The board should now be fully occupied.
    assert len(gameboard.occupied_squares.keys()) == gameboard.total_squares

    # Adding with no location should fail to get a random square
    with pytest.raises(RuntimeError):
        gameboard.add_ship_to_board(ship)

    with pytest.raises(ValueError):
        gameboard.add_ship_to_board(ship, (0, 0))


"""
    1. Have a function that creates a list of 20 random integers between 1 and 100
    (Assign them dynamically, store the list in a variable.)

    2. Have a function get a number from the user that is between 1 and 100
    (validate to ensure a number between 1 and 100 was entered instead of text or
    something out of range using a try and except statement).

    3. Pass both the list and the user's number to a function and have it display
    all numbers in the list that is greater than the user's number. If there are not any,
    display a message that explains there are no numbers in the list greater than the entered number.
"""
import random

"""
    Calls all the functions necessary for the program.
"""

def main():
    rand = random_list()
    user_number = get_user_number()
    number_compare(rand, user_number)

"""
    Creates a list of 20 random integers between 1 and 100. Returns the list.
"""

def random_list():
    rand_list = []
    for i in range(1, 21):
        rand_list.append(random.randint(1, 100))
    return rand_list

"""
    Gets a number from the user. Validates to make sure they entered a number between 1 and 100.
"""

def get_user_number():
    while True:
        try:
            num = int(input("Please enter a number between 1 and 100. "))
            if (num < 1) or (num > 100):
                print("Your number is not between 1 and 100.")
            else:
                return num
        except ValueError:
            print("Error, not a number.")

"""
    Takes a list of numbers and another number. Compares the two and prints out all the numbers in the list that are
    greater than the other number. If there aren't any, prints out that there aren't any.
"""

def number_compare(number_list, input_number):
    count = 0
    for num in number_list:
        if num > input_number:
            count += 1
            print(num)
    if count == 0:
        print("There weren't any numbers greater in the list than what was entered.")

main()


from typing import Any, Callable, Tuple, Optional, Union, Iterable, Dict, Text

import jax
import jax.numpy as jnp
import flax.linen as nn

TF_LAYERNORM_EPSILON = 1e-12 # BERT layer norm
InitializerType = Callable[[jnp.ndarray, Iterable[int], jnp.dtype], jnp.ndarray]

def bert_masking(inputs,
                 nospecial_tokens,
                 mask_token,
                 pad_token: int = -1,
                 mask_condition: Optional[jnp.ndarray] = None,
                 mask_rate: float = 0.15,
                 mask_token_proportion: float = 0.8,
                 random_token_proportion: float = 0.1):
  """Preprocess inputs following BERT.

  First chooses mask_rate of the token positions at random for prediction.
  Among them, mask_token_proportion of them will be replaced with mask_token.
  random_token_proportion of them will be replaced with randomly sampled tokens.
  Others will remain the same.

  Args:
    inputs: [batch, sequence_length] input tokens.
    nospecial_tokens: jnp.ndarray. Set of tokens usable for replacing (not
      include special tokens such as pad, mask, bos, etc.)
    mask_token: Int ID for mask token.
    pad_token: Int ID for PAD token.
    mask_condition: An optional extra condition on which tokens can be masked.
    mask_rate: Proportion of tokens to mask out.
    mask_token_proportion: Replace this proportion of chosen positions with
      MASK.
    random_token_proportion: Replace this proportion of chosen positions with
      randomly sampled tokens

  Returns:
    Tuple of [batch, sequence_length] masked_inputs, inputs, mask_weights.
  """
  # Clamps mask_rate into [epsilon, 1].
  mask_rate = jnp.clip(mask_rate, 1e-6, 1)

  total = random_token_proportion + mask_token_proportion
  if total < 0 or total > 1:
    raise ValueError('Sum of random proportion and mask proportion must be'
                     ' in [0, 1] range.')
  targets = inputs

  rng = jax.random.PRNGKey(jnp.sum(inputs))

  # Gets positions to leave untouched.
  is_pad = inputs == pad_token

  # If we have an extra condition on what can be masked,
  # mark those as pad tokens
  if mask_condition is not None:
    is_pad = jnp.logical_and(is_pad, jnp.logical_not(mask_condition))

  lens = jnp.sum(~is_pad, axis=-1)
  # Obtains the ceiling of the lens to make sure we can mask at least one token.
  mask_lens = jax.lax.ceil(lens * mask_rate).astype(jnp.int32)
  # Positions to mask.
  rng, subrng = jax.random.split(rng)
  # Randomly generates the mask score uniformly.
  should_mask = jax.random.uniform(subrng, shape=inputs.shape)
  # Doesn't mask out padding.
  should_mask = jnp.where(is_pad, 2., should_mask)
  sorted_should_mask = jnp.sort(should_mask, axis=-1)

  # Obtains the cutoff score for the mask lens.
  cut_off = jnp.take_along_axis(
      sorted_should_mask,
      jnp.expand_dims(mask_lens - 1, 1).astype(jnp.int32),
      axis=-1)
  cut_off = jnp.repeat(cut_off, inputs.shape[1], axis=1)

  # Scores smaller than the cutoff will be masked.
  should_mask = jnp.where(should_mask <= cut_off, 1., 0.)

  # Generate full array of random tokens.
  rng, subrng = jax.random.split(rng)
  random_ids = jax.random.randint(
      subrng, inputs.shape, minval=0, maxval=len(nospecial_tokens))

  fullrandom = nospecial_tokens[random_ids]
  # Full array of MASK tokens
  fullmask = jnp.full_like(inputs, mask_token)

  # Build up masked array by selecting from inputs/fullmask/fullrandom.
  rand = jax.random.uniform(rng, shape=inputs.shape)
  masked_inputs = inputs
  # Remaining probability mass stays original values after MASK and RANDOM.
  # MASK tokens.
  tokens_to_mask = rand < mask_token_proportion

  masked_inputs = jnp.where(tokens_to_mask, fullmask, masked_inputs)
  # Random tokens.
  masked_inputs = jnp.where(
      jnp.logical_and(rand >= mask_token_proportion,
                      rand < mask_token_proportion + random_token_proportion),
      fullrandom, masked_inputs)

  # Only replace positions where `should_mask`
  masked_inputs = jnp.where(should_mask, masked_inputs, inputs)
  weights = should_mask

  return dict(masked_inputs=masked_inputs, targets=targets, weights=weights)

def truncated_normal(stddev: Union[float, jnp.ndarray], dtype=jnp.float32):

  def init(key: jnp.ndarray, shape: Iterable[int], dtype: jnp.dtype = dtype):
    return jax.random.truncated_normal(
        key=key, lower=-2, upper=2, shape=shape, dtype=dtype) * stddev

  return init

class Bias(nn.Module):
  """Adds a (learned) bias to the input.

  Similar to hk.Bias (cf. google3/third_party/py/haiku/_src/bias.py).

  Attributes:
    dtype: the dtype of the computation (default: float32).
    bias_init: initializer function for the bias.
  """
  dtype: Any = jnp.float32
  bias_init: Callable[[Any, Tuple[int], Any], Any] = nn.initializers.zeros

  @nn.compact
  def __call__(self, inputs: jnp.ndarray) -> jnp.ndarray:
    """Applies a linear transformation to the inputs along the last dimension.

    Args:
      inputs: The nd-array to be transformed.

    Returns:
      The transformed input.
    """
    inputs = jnp.asarray(inputs, self.dtype)

    bias_shape = inputs.shape[-1]
    bias = self.param('bias', self.bias_init, bias_shape)
    bias = jnp.asarray(bias, self.dtype)
    bias = jnp.broadcast_to(bias, inputs.shape)

    return inputs + bias

class BertAttention(nn.Module):
  """BERT attention layer that is part of each BERT layer."""
  hidden_size: int
  hidden_dropout_prob: float
  num_attention_heads: int
  attention_probs_dropout_prob: float
  hidden_dropout_prob: float
  initializer_fn: InitializerType

  @nn.compact
  def __call__(self, layer_input: jnp.ndarray, input_mask: jnp.ndarray,
               deterministic: bool) -> jnp.ndarray:
    attention_mask = nn.make_attention_mask(input_mask, input_mask)
    attention_output = nn.attention.SelfAttention(
        num_heads=self.num_attention_heads,
        qkv_features=self.hidden_size,
        dropout_rate=self.attention_probs_dropout_prob,
        deterministic=deterministic,
        kernel_init=self.initializer_fn,
        bias_init=jax.nn.initializers.zeros,
        name='self_attention',
    )(layer_input, attention_mask)

    attention_output = nn.Dropout(rate=self.hidden_dropout_prob)(
        attention_output, deterministic=deterministic)
    attention_output = nn.LayerNorm(
        epsilon=TF_LAYERNORM_EPSILON, name='attention_output_ln')(
            attention_output + layer_input)

    return attention_output

class BertMlp(nn.Module):
  """BERT MLP layer that is part of each BERT layer."""
  hidden_size: int
  hidden_dropout_prob: float
  intermediate_size: int
  initializer_fn: InitializerType

  @nn.compact
  def __call__(self, attention_output: jnp.ndarray,
               deterministic: bool) -> jnp.ndarray:
    # Bert intermediate layer.
    intermediate_output = nn.Dense(
        features=self.intermediate_size,
        kernel_init=self.initializer_fn,
        name='intermediate_output')(
            attention_output)
    intermediate_output = jax.nn.gelu(intermediate_output)

    # Bert output layer.
    layer_output = nn.Dense(
        features=self.hidden_size,
        kernel_init=self.initializer_fn,
        name='layer_output')(
            intermediate_output)
    layer_output = nn.Dropout(rate=self.hidden_dropout_prob)(
        layer_output, deterministic=deterministic)
    layer_output = nn.LayerNorm(
        epsilon=TF_LAYERNORM_EPSILON, name='layer_output_ln')(
            layer_output + attention_output)

    return layer_output

class BertLayer(nn.Module):
  """A single Bert layer."""
  intermediate_size: int
  hidden_size: int
  hidden_dropout_prob: float
  num_attention_heads: int
  attention_probs_dropout_prob: float
  initializer_fn: InitializerType

  @nn.compact
  def __call__(self, layer_input: jnp.ndarray, input_mask: jnp.ndarray,
               deterministic: bool) -> jnp.ndarray:
    attention_output = BertAttention(
        hidden_size=self.hidden_size,
        hidden_dropout_prob=self.hidden_dropout_prob,
        num_attention_heads=self.num_attention_heads,
        attention_probs_dropout_prob=self.attention_probs_dropout_prob,
        initializer_fn=self.initializer_fn,
        name='Attention_0')(
            layer_input=layer_input,
            input_mask=input_mask,
            deterministic=deterministic)

    layer_output = BertMlp(
        hidden_size=self.hidden_size,
        hidden_dropout_prob=self.hidden_dropout_prob,
        intermediate_size=self.intermediate_size,
        initializer_fn=self.initializer_fn,
        name='Mlp_0')(
            attention_output=attention_output, deterministic=deterministic)

    return layer_output

class BertEmbed(nn.Module):
  """Embeds Bert-style."""
  embedding_size: int
  hidden_dropout_prob: float
  vocab_size: int
  max_position_embeddings: int
  initializer_fn: InitializerType
  hidden_size: Optional[int] = None

  @nn.compact
  def __call__(self, input_ids: jnp.ndarray,
               deterministic: bool) -> Tuple[jnp.ndarray, jnp.ndarray]:
    seq_length = input_ids.shape[-1]
    position_ids = jnp.arange(seq_length)[None, :]

    word_embedder = nn.Embed(
        num_embeddings=self.vocab_size,
        features=self.embedding_size,
        embedding_init=self.initializer_fn,
        name='word_embeddings')
    word_embeddings = word_embedder(input_ids)
    position_embeddings = nn.Embed(
        num_embeddings=self.max_position_embeddings,
        features=self.embedding_size,
        embedding_init=self.initializer_fn,
        name='position_embeddings')(
            position_ids)

    input_embeddings = nn.LayerNorm(
        epsilon=TF_LAYERNORM_EPSILON, name='embeddings_ln')(
            word_embeddings + position_embeddings)
    if self.hidden_size:
      input_embeddings = nn.Dense(
          features=self.hidden_size,
          kernel_init=self.initializer_fn,
          name='emb_hidden_mapping')(
              input_embeddings)
    input_embeddings = nn.Dropout(rate=self.hidden_dropout_prob)(
        input_embeddings, deterministic=deterministic)

    return input_embeddings

class BertMlmLayer(nn.Module):
  """Bert layer for masked token prediction."""
  hidden_size: int
  initializer_fn: InitializerType

  @nn.compact
  def __call__(self, last_layer: jnp.ndarray,
               embeddings: jnp.ndarray) -> jnp.ndarray:
    mlm_hidden = nn.Dense(
        features=self.hidden_size,
        kernel_init=self.initializer_fn,
        name='mlm_dense')(
            last_layer)
    mlm_hidden = jax.nn.gelu(mlm_hidden)
    mlm_hidden = nn.LayerNorm(
        epsilon=TF_LAYERNORM_EPSILON, name='mlm_ln')(
            mlm_hidden)
    output_weights = jnp.transpose(embeddings)
    logits = jnp.matmul(mlm_hidden, output_weights)
    logits = Bias(name='mlm_bias')(logits)
    return logits

class Bert(nn.Module):
  """BERT as a Flax module."""
  vocab_size: int
  hidden_size: int = 768
  num_hidden_layers: int = 12
  num_attention_heads: int = 12
  intermediate_size: int = 3072
  hidden_dropout_prob: float = 0.1
  attention_probs_dropout_prob: float = 0.1
  max_position_embeddings: int = 512
  initializer_range: float = 0.02
  pad_token_id: int = -1

  @nn.compact
  def __call__(self,
               input_ids: jnp.ndarray,
               deterministic: bool = True) -> Dict[Text, jnp.ndarray]:
    # We assume that all pad tokens should be masked out.
    input_ids = input_ids.astype('int32')
    input_embeddings = BertEmbed(
        embedding_size=self.hidden_size,
        hidden_dropout_prob=self.hidden_dropout_prob,
        vocab_size=self.vocab_size,
        max_position_embeddings=self.max_position_embeddings,
        initializer_fn=truncated_normal(self.initializer_range),
        name='Embed_0')(
            input_ids=input_ids, deterministic=deterministic)

    # Stack BERT layers.
    layer_input = input_embeddings
    for i in range(self.num_hidden_layers):
      layer_output = BertLayer(
          intermediate_size=self.intermediate_size,
          hidden_size=self.hidden_size,
          hidden_dropout_prob=self.hidden_dropout_prob,
          num_attention_heads=self.num_attention_heads,
          attention_probs_dropout_prob=self.attention_probs_dropout_prob,
          initializer_fn=truncated_normal(self.initializer_range),
          name=f'TransformerLayer_{i}')(
              layer_input=layer_input,
              input_mask=jnp.ones_like(input_ids, dtype=jnp.int32),
              deterministic=deterministic)
      layer_input = layer_output

    word_embedding_matrix = self.variables['params']['Embed_0'][
        'word_embeddings']['embedding']
    logits = BertMlmLayer(
        hidden_size=self.hidden_size,
        initializer_fn=truncated_normal(self.initializer_range),
        name='MlmLayer_0')(
            last_layer=layer_output, embeddings=word_embedding_matrix)

    return logits


from __future__ import annotations

import re
from collections.abc import Mapping

from pipenv.exceptions import PipenvUsageError
from pipenv.patched.pip._vendor.urllib3.util import parse_url
from pipenv.utils.constants import MYPY_RUNNING

from .internet import create_mirror_source, is_pypi_url

if MYPY_RUNNING:
    from typing import List, Optional, Union  # noqa

    from pipenv.project import Project, TSource  # noqa

def prepare_pip_source_args(sources, pip_args=None):
    if pip_args is None:
        pip_args = []
    if sources:
        # Add the source to pip.
        package_url = sources[0].get("url")
        if not package_url:
            raise PipenvUsageError("[[source]] section does not contain a URL.")
        pip_args.extend(["-i", package_url])
        # Trust the host if it's not verified.
        if not sources[0].get("verify_ssl", True):
            url_parts = parse_url(package_url)
            url_port = f":{url_parts.port}" if url_parts.port else ""
            pip_args.extend(["--trusted-host", f"{url_parts.host}{url_port}"])
        # Add additional sources as extra indexes.
        if len(sources) > 1:
            for source in sources[1:]:
                url = source.get("url")
                if not url:  # not harmless, just don't continue
                    continue
                pip_args.extend(["--extra-index-url", url])
                # Trust the host if it's not verified.
                if not source.get("verify_ssl", True):
                    url_parts = parse_url(url)
                    url_port = f":{url_parts.port}" if url_parts.port else ""
                    pip_args.extend(["--trusted-host", f"{url_parts.host}{url_port}"])
    return pip_args

def get_project_index(
    project: Project,
    index: str | TSource | None = None,
    trusted_hosts: list[str] | None = None,
) -> TSource:
    from pipenv.project import SourceNotFound

    if trusted_hosts is None:
        trusted_hosts = []
    if isinstance(index, Mapping):
        return project.find_source(index.get("url"))
    try:
        source = project.find_source(index)
    except SourceNotFound:
        index_url = parse_url(index)
        src_name = project.src_name_from_url(index)
        verify_ssl = index_url.host not in trusted_hosts
        source = {"url": index, "verify_ssl": verify_ssl, "name": src_name}
    return source

def get_source_list(
    project: Project,
    index: str | TSource | None = None,
    extra_indexes: str | list[str] | None = None,
    trusted_hosts: list[str] | None = None,
    pypi_mirror: str | None = None,
) -> list[TSource]:
    sources = project.sources[:]
    if index:
        sources.append(get_project_index(project, index))
    if extra_indexes:
        if isinstance(extra_indexes, str):
            extra_indexes = [extra_indexes]

        for source in extra_indexes:
            extra_src = get_project_index(project, source)
            if not sources or extra_src["url"] != sources[0]["url"]:
                sources.append(extra_src)

        for source in project.sources:
            if not sources or source["url"] != sources[0]["url"]:
                sources.append(source)

    if pypi_mirror:
        sources = [
            create_mirror_source(pypi_mirror, source["name"])
            if is_pypi_url(source["url"])
            else source
            for source in sources
        ]
    return sources

def parse_indexes(line, strict=False):
    from argparse import ArgumentParser

    comment_re = re.compile(r"(?:^|\s+)#.*$")
    line = comment_re.sub("", line)
    parser = ArgumentParser("indexes", allow_abbrev=False)
    parser.add_argument("-i", "--index-url", dest="index")
    parser.add_argument("--extra-index-url", dest="extra_index")
    parser.add_argument("--trusted-host", dest="trusted_host")
    args, remainder = parser.parse_known_args(line.split())
    index = args.index
    extra_index = args.extra_index
    trusted_host = args.trusted_host
    if (
        strict
        and sum(bool(arg) for arg in (index, extra_index, trusted_host, remainder)) > 1
    ):
        raise ValueError("Index arguments must be on their own lines.")
    return index, extra_index, trusted_host, remainder


import numpy as np

list01 = [1,2,3,4,5]
list02 = [0,2,4,8,16]

cv01 = np.std(list01)/np.mean(list01)
cv02 = np.std(list02)/np.mean(list02)

print('list01의 변동계수 : ', "%.3f" %cv01)
print('list02의 변동계수 : ', "%.3f" %cv02)