from collections import namedtuple
import config.training
import tensorflow as tf

Trainer = namedtuple("Trainer", [
    "d_train_op",
    "g_train_op",
    "d_loss",
    "g_loss",
    "accuracy",
])

def losses(real_logits, fake_logits):
    with tf.name_scope("d_loss"):
        with tf.name_scope("d_real_loss"):
            d_real_loss = tf.nn.sigmoid_cross_entropy_with_logits(
                labels = (
                    (1 - config.training.LABEL_SMOOTHING)
                    * tf.ones_like(real_logits)
                ),
                logits = real_logits
            )
        with tf.name_scope("d_fake_loss"):
            d_fake_loss = tf.nn.sigmoid_cross_entropy_with_logits(
                labels = tf.zeros_like(fake_logits),
                logits = fake_logits
            )
        d_loss = tf.reduce_mean(
            tf.concat(
                [d_real_loss, d_fake_loss],
                axis = 0
            )
        )

    with tf.name_scope("g_loss"):
        g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
            labels = tf.ones_like(fake_logits),
            logits = fake_logits
        ))

    return d_loss, g_loss

def accuracy(real_logits, fake_logits):
    with tf.name_scope("accuracy"):
        accuracy = tf.reduce_mean(tf.concat([
            tf.cast(tf.equal(
                tf.round(tf.sigmoid(real_logits)),
                tf.ones_like(real_logits)), tf.float32
            ),
            tf.cast(tf.equal(
                tf.round(tf.sigmoid(fake_logits)),
                tf.zeros_like(fake_logits)), tf.float32
            )
        ], axis = 0))

    return accuracy

def build(real_logits, fake_logits):
    d_loss, g_loss = losses(
        real_logits = real_logits,
        fake_logits = fake_logits
    )

    discriminator_vars = tf.get_collection(
        tf.GraphKeys.TRAINABLE_VARIABLES,
        scope = "discriminator"
    )
    generator_vars = tf.get_collection(
        tf.GraphKeys.TRAINABLE_VARIABLES,
        scope = "generator"
    )

    optimizer = tf.train.AdamOptimizer(
        learning_rate = config.training.LEARNING_RATE,
        beta1 = config.training.BETA1
    )

    update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
    with tf.control_dependencies(update_ops):
        d_train_op = optimizer.minimize(
            d_loss,
            var_list = discriminator_vars
        )

    with tf.control_dependencies(update_ops):
        g_train_op = optimizer.minimize(
            g_loss,
            var_list = generator_vars
        )

    return Trainer(
        d_train_op = d_train_op,
        g_train_op = g_train_op,
        d_loss = d_loss,
        g_loss = g_loss,
        accuracy = accuracy(
            real_logits = real_logits,
            fake_logits = fake_logits,
        ),
    )


"""empty message

Revision ID: 8dc6b7729d49
Revises: fde7518177ce
Create Date: 2019-02-16 23:06:18.550438

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '8dc6b7729d49'
down_revision = 'fde7518177ce'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('atributos',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('usuarios',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('login', sa.String(length=100), nullable=False),
    sa.Column('senha', sa.String(length=100), nullable=False),
    sa.Column('atributos_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['atributos_id'], ['atributos.id'], ondelete='CASCADE'),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('login')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('usuarios')
    op.drop_table('atributos')
    # ### end Alembic commands ###


#https://programmers.co.kr/learn/courses/30/lessons/62048

def solution(w,h):

    num = 0
    if w == 1 or h == 1:
        answer = 0
    elif w == h:
        answer = w*h-w
    else:
        for i in range(1, w):
            h_len = h*i/w
            num += int(h_len)
        answer = num*2

    return answer


# simulation for Problem 6
import random
from math import sqrt

N = 100000
total_counter = 0
reach_3_0_times = 0
for i in range(N):
    x = 0
    y = 0
    counter = 0
    while True:
        if abs(y) >= 2 or x <= -2:
            total_counter += counter
            if x == -2 and y == 0:
                reach_3_0_times += 1
            break
        a = random.randint(0, 3)
        if a == 0:
            x += 1
        elif a == 1:
            y += 1
        elif a == 2:
            x -= 1
        else:
            y -= 1
        counter += 1
print('expectation of E[T]')
print('empirical value', total_counter / N)
print('theoretical value', -8+(8+5*sqrt(2))*sqrt(7-4*sqrt(2))+(5*sqrt(2)-8)*sqrt(7+4*sqrt(2)))

print('first hit (-2, 0)')
print('empirical value', reach_3_0_times / N)
print('theoretical value', 8-((2*sqrt(2)-1)*sqrt(7-4*sqrt(2)) + (2*sqrt(2)+1)*sqrt(7+4*sqrt(2)))/2)


import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms import Resize
import random
import matplotlib.pyplot as plt
import gc
gc.collect(2)
import numpy as np
import buteo as beo
import os

def patience_calculator(epoch, t_0, t_m, max_patience=50):
    """ Calculate the patience for the scheduler. """
    if epoch <= t_0:
        return t_0

    p = [t_0 * t_m ** i for i in range(100) if t_0 * t_m ** i <= epoch][-1]
    if p > max_patience:
        return max_patience

    return p

class TiledMSE(nn.Module):
    """
    Calculates the MSE at full image level and at the pixel level and weights the two.
    result = (sum_mse * (1 - bias)) + (mse * bias)
    """

    def __init__(self, bias=0.2):
        super(TiledMSE, self).__init__()
        self.bias = bias

    def forward(self, y_pred, y_true):
        y_pred_sum = torch.sum(y_pred, dim=(1, 2, 3)) / (y_pred.shape[1] * y_pred.shape[2] * y_pred.shape[3])
        y_true_sum = torch.sum(y_true, dim=(1, 2, 3)) / (y_true.shape[1] * y_true.shape[2] * y_true.shape[3])

        sum_mse = ((y_pred_sum - y_true_sum) ** 2).mean()
        mse = ((y_pred - y_true) ** 2).mean()

        weighted = (sum_mse * (1 - self.bias)) + (mse * self.bias)

        return weighted

def render_s2_as_rgb(arr, channel_first=False):
    # If there are nodata values, lets cast them to zero.
    if np.ma.isMaskedArray(arr):
        arr = np.ma.getdata(arr.filled(0))

    if channel_first:
        arr = beo.channel_first_to_last(arr)
    # Select only Blue, green, and red. Then invert the order to have R-G-B
    rgb_slice = arr[:, :, 0:3][:, :, ::-1]

    # Clip the data to the quantiles, so the RGB render is not stretched to outliers,
    # Which produces dark images.
    rgb_slice = np.clip(
        rgb_slice,
        np.quantile(rgb_slice, 0.02),
        np.quantile(rgb_slice, 0.98),
    )

    # The current slice is uint16, but we want an uint8 RGB render.
    # We normalise the layer by dividing with the maximum value in the image.
    # Then we multiply it by 255 (the max of uint8) to be in the normal RGB range.
    rgb_slice = (rgb_slice / rgb_slice.max()) * 255.0

    # We then round to the nearest integer and cast it to uint8.
    rgb_slice = np.rint(rgb_slice).astype(np.uint8)

    return rgb_slice

def visualise(x, y, y_pred=None, images=5, channel_first=False, vmin=0, vmax=1, save_path=None):
    rows = images
    if y_pred is None:
        columns = 2
    else:
        columns = 3
    i = 0
    fig = plt.figure(figsize=(10 * columns, 10 * rows))

    for idx in range(0, images):
        arr = x[idx]
        rgb_image = render_s2_as_rgb(arr, channel_first)

        i = i + 1
        fig.add_subplot(rows, columns, i)
        plt.imshow(rgb_image)
        plt.axis('on')
        plt.grid()

        i = i + 1
        fig.add_subplot(rows, columns, i)
        plt.imshow(y[idx], vmin=vmin, vmax=vmax, cmap='magma')
        plt.axis('on')
        plt.grid()

        if y_pred is not None:
            i = i + 1
            fig.add_subplot(rows, columns, i)
            plt.imshow(y_pred[idx], vmin=vmin, vmax=vmax, cmap='magma')
            plt.axis('on')
            plt.grid()

    fig.tight_layout()

    del x
    del y
    del y_pred

    if save_path is not None:
        plt.savefig(save_path)
    plt.close()


# CSV with default delimeter (,)

import csv
# opening a csv file with read mode
with open ("Python/CSV Reader Function/CSV/csv-without-spaces.csv", 'r') as f:
    reader = csv.reader(f)

    # print each line row by row
    for row in reader:
        print(row)

f.close()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import requests
from bs4 import BeautifulSoup

link = '''https://api-zero.livere.com/v1/comments/list?callback=jQuery112409167777692145258_1515115423265&limit=10&repSeq=
3871836&requestPath=%2Fv1%2Fcomments%2Flist&consumerSeq=1020&livereSeq=28583&smartloginSeq=5154&_=1515115423267'''
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    'Host': 'api-zero.livere.com'
}
response = requests.get(link, headers = headers)

json_data = json.loads(response.text)
comment_list = json_data['data']['comments']
for each_comment in comment_list:
    message = comment_list[each_comment]['content']
    print(message)


#!/usr/bin/env python3

import argparse
import torch

def main(args):
    ckpt = torch.load(args.checkpoint)
    ns = ckpt["args"]

    for line in ns.__dict__.items():
        print(line)

def parse_args():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--checkpoint", type=str, required=True)

    return parser.parse_args()

if __name__ == "__main__":
    main(parse_args())


import ReferenceDictionary as dd
from colored_box_image import create_colored_box_image as cbox
from range_charts import t_chart
from save_plot import insert_plot as IP

def conditional(df, dfdict):
    output = open("problem_output.txt","w")

    for test , pval in dfdict.items():
        #get name and unit of the test seperately
        usename = test.replace(" [mg/dL]", "").replace(" [nmol/L]", "").replace(" [-/-]", "")
        if "[mg/dL]" in test:
            unit =  "[mg/dL]"
        elif "[nmol/L]" in test:
            unit = "[nmol/L]"
        else:
            unit = None

        #check the test's existence
        try:
            attribute = getattr(dd.TESTS(),usename)
        except:
            output.write(f"{test} is not in tests dictionary.\n")
        else:
            try:
                    attribute["Optimal"]
            except:
                try:
                    attribute["OptimalnCD"] #Do these exist?
                    attribute["OptimalCD"]
                except:
                    print("Problem")
                    pass
                else: # more than two reference values
                    while True:
                        past = input("History of any Cardiovascular Events? y/n ")
                        if past == "n":
                            optval = float(attribute["OptimalnCD"][2:].strip())
                            riskval = float(attribute["Risk"][2:].strip())
                            constant = 2 * (abs(optval - riskval)) / 3

                            fig = t_chart(df[test], optval, riskval, attribute["OptimalnCD"] ,attribute["Risk"], constant)
                            plot_file = f'{usename}.png'
                            IP(plot_file, fig)

                            cbox(usename, df[test], "noref", unit)
                            break
                        elif past == "y":
                            optval = float(attribute["OptimalCD"][2:].strip())
                            riskval = float(attribute["Risk"][2:].strip())
                            constant = 2 * (abs(optval - riskval)) / 3

                            fig = t_chart(df[test], optval, riskval, attribute["OptimalCD"] ,attribute["Risk"], constant)
                            plot_file = f'{usename}.png'
                            IP(plot_file, fig)

                            cbox(usename, df[test], "noref", unit)
                            break
                        else:
                            print("Wrong input.")
            else:
                if attribute["Optimal"] is None and attribute["Risk"] is None: #check for no reference
                    cbox(usename, pval, "noref", unit)
                elif attribute["Optimal"][2:].strip() == attribute["Risk"][2:].strip(): #check for one reference value
                    condition = f"{pval} {attribute}"
                    if pval == attribute["Optimal"][2:].strip():
                        cbox(usename, pval, "not boolean", unit)
                    elif eval(f"{pval} {attribute['Optimal']}"): # pval > or < Optimal w
                        cbox(usename, pval, False, unit)
                    else:
                        cbox(usename, pval, True, unit)

                else: #two reference value
                    optval = float(attribute["Optimal"][2:].strip())
                    riskval = float(attribute["Risk"][2:].strip())
                    constant = 2 * (abs(optval - riskval)) / 3

                    fig = t_chart(df[test], optval, riskval, attribute["Optimal"] ,attribute["Risk"], constant) # or "Optimal" , "Risk" as line names
                    plot_file = f'{usename}.png'
                    IP(plot_file, fig)

                    cbox(usename, df[test], "noref", unit)
    output.close()

def calculated_LFLC(df):
    db = dd.TESTS.LFLC
    cLFLC = round(df["LDFC [mg/dL]"]/df["LDCH [mg/dL]"],2)

    optval = float(db["Optimal"][2:].strip())
    riskval = float(db["Risk"][2:].strip())
    constant = 2 * (abs(optval - riskval)) / 3

    fig = t_chart(cLFLC, optval, riskval, db["Optimal"] ,db["Risk"], constant)
    plot_file = 'LFLC.png'
    IP(plot_file, fig)

    cbox(plot_file.replace(".png",""), cLFLC, "noref")

def calculated_HFHC(df):
    db = dd.TESTS.HFHC
    cHFHC = round(df["HDFC [mg/dL]"]/df["HDCH [mg/dL]"],2)

    if eval(f"{cHFHC} {db['Optimal']}"):
        cbox("HFHC", cHFHC, False)
    else:
        cbox("HFHC", cHFHC, True)


# Given a column title as appear in an Excel sheet, return its corresponding column number.

# For example:

#     A -> 1
#     B -> 2
#     C -> 3
#     ...
#     Z -> 26
#     AA -> 27
#     AB -> 28
#     ...

# Example 1:

# Input: "A"
# Output: 1

# Example 2:

# Input: "AB"
# Output: 28

# Example 3:

# Input: "ZY"
# Output: 701

# Constraints:

#     1 <= s.length <= 7
#     s consists only of uppercase English letters.
#     s is between "A" and "FXSHRXW".

class Solution:
    def titleToNumber(self, s: str) -> int:
        count = 0
        # print(int('A'))
        for i in range(len(s)):
            count += (ord(s[i]) - 64) * (26 ** (len(s) - i - 1))
        return count


rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

import random

print("Wellcome to Rock, Paper, Scissors game!\n")

print("Here are some rules: \nRock wins against scissors;\nPaper wins against rock; \nScissors wins against paper\n")

player = int(input("Let's start the game! Type 0 for Rock, 1 for Paper or 2 for Scissors!\n"))

if player == 0:
  print(f"Your Choice: {rock}")
elif player == 1:
  print(f"Your Choice: {paper} ")
elif player == 2:
  print(f"Your Choice: {scissors} ")
else:
  print("You should type 0, 1 or 2. Try again!\n")
  exit(0)

computer = random.randint(0, 2)

if computer == 0:
  print(f"Computer  Choice: {rock}")
elif computer == 1:
  print(f"Computer  Choice: {paper} ")
elif computer == 2:
  print(f"Computer  Choice: {scissors} ")

if  computer == player:
  print("Draw!")
elif (player == 0 and computer == 1) or (player == 1 and computer == 2) or (player == 2 and computer == 0):
  print("You lost! :(")
else:
  print("You are the winner! :)")


import re
import sqlite3
import pandas as pd
from datetime import datetime
import quickstart
# from __future__ import print_function
import datetime
from datetime import datetime
from dateutil.relativedelta import relativedelta, MO, SU
import os.path
import pprint
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import quickstart

FP308_id = 'mu04c7ugregh71cdbp6jij6522j4paev@import.calendar.google.com'
MS307_id = 'ggr7r4l0c2aog6t6lfbmotp6b9vg6gi9@import.calendar.google.com'
NL461_id = 'jorp1cu13a8a9p3s40qimcl61ijfh2tp@import.calendar.google.com'
HS407_id = 'mkclgiicomv8fg042k3262osmtevi4qk@import.calendar.google.com'
today = datetime.today()
start = today - relativedelta(weekday=MO(-1))
end = today - relativedelta(weekday=SU(1))
end_date = end.isoformat('T') + "Z"
start_date = start.isoformat('T') + "Z"

cal_data = quickstart.Quickstart.main()
calendar_ids = []
personal_cal_ids = []
cal_summary = []

# Get all Airbnb calendar id's
def get_cal_ids():

    for calendar_list_entry in cal_data[0]:
        cals = calendar_list_entry['id']
        if "import.calendar" in cals:
            print('SUMMARY----->:', calendar_list_entry['summaryOverride'], 'BNB_CALS:', cals)
            calendar_ids.append(cals)
        elif 'group.calendar' in cals:
            print('SUMMARY----->:', calendar_list_entry['summary'], 'PER_CALS:', cals)
            cal_summary.append(calendar_list_entry['summary'])
            personal_cal_ids.append(cals)
    return calendar_ids, personal_cal_ids

get_cal_ids()

# Get data for each event
def get_eventData():
    service = cal_data[1]
    data_lst = []
    cal_id = calendar_ids
    while True:

        for cal_ids in cal_id:
            events_result = service.events().list(calendarId=cal_ids, timeMin=start_date, timeMax=end_date, singleEvents=True, orderBy='startTime').execute()

            events = events_result.get('items', [])
            for event in events:
                data = cal_ids, event['iCalUID'], event['end'].get('dateTime', event['end'].get('date')), event['start'].get('dateTime', event['start'].get('date'))
                data_lst.append(data)
        return data_lst

# pprint.pprint(get_eventData())

def import_data(summary, start, end, iCalUID):
    _resource = {
                'summary': summary,
                    'start': {
                        'date': start
                    },
                    'end': {
                        'date': end
                    },
                    'iCalUID': iCalUID
                }
    return _resource

    # Imports private copy of event
def import_event():
    event_values = get_eventData()

    for vals in event_values:
        if vals[0] == calendar_ids[0]:
            FP308_resource = import_data(cal_summary[1], vals[3], vals[2], vals[1])
            # imported_event = service.events().import_(calendarId=personal_cal_ids[1], body=FP308_resource).execute()
            print('FP308:', personal_cal_ids[1])
            print(FP308_resource)
        elif vals[0] == calendar_ids[1]:
            MS307_resource = import_data(cal_summary[0], vals[3], vals[2], vals[1])
            # imported_event = service.events().import_(calendarId=personal_cal_ids[0], body=MS307_resource).execute()
            print('MS308:', personal_cal_ids[0])
            print(MS307_resource)
        elif vals[0] == calendar_ids[2]:
            NL461_resource = import_data(cal_summary[3], vals[3], vals[2], vals[1])
            # imported_event = service.events().import_(calendarId=personal_cal_ids[3], body=NL461_resource).execute()
            print('NL461:', personal_cal_ids[3])
            print(NL461_resource)
        elif vals[0] == calendar_ids[3]:
            HS407_resource = import_data(cal_summary[2], vals[3], vals[2], vals[1])
            # imported_event = service.events().import_(calendarId=personal_cal_ids[2], body=HS407_resource).execute()
            print('HS407:', personal_cal_ids[2])
            print(HS407_resource)
        else:
            'No data!'

pprint.pprint(import_event())
print('---------------------------------------------------------')

def calculate_total(cleaning_list):
    apt_lst = re.findall(r'\w+', cleaning_list)

    total_cost = 0
    for apt in apt_lst:
        if 'FP308' in apt:
            total_cost += 60
        elif 'NL461' in apt:
            total_cost += 50
        elif 'MS307' in apt:
            total_cost += 45
        elif 'HS407' in apt:
            total_cost += 45
        else:
            total_cost += 0
    return 'Total: ' + str(total_cost)

cleaning_lst = '''
    8/23: MS307 FP308 HS407
    8/24: NL461 FP308
    8/25: HS407
    8/26: MS307 HS407
    8/27: MS307 NL461
    8/28: FP308
    8/29: FP308 MS307 HS407
'''

# print(cleaning_lst + '\n Total: ' + calculate_total(cleaning_lst))

# def get_query_results():
#     conn = sqlite3.connect('/Users/tracygoss/Library/Messages/chat.db')
#     cur1 = conn.cursor()
#     cur1.execute('''SELECT datetime(m.date / 1000000000 + strftime ("%s", "2001-01-01"), "unixepoch", "localtime") AS message_date,
#                  text
#              FROM chat c
#                 JOIN chat_message_join cmj ON c."ROWID" = cmj.chat_id
#                 JOIN message m ON cmj.message_id = m."ROWID"
#              WHERE c.chat_identifier = "+12064290405" and m.is_sent = 1
#              ORDER BY m.date DESC
#              LIMIT 10; ''')

#     results = ''
#     for message_data in cur1.fetchall():
#         print(message_data)
#         results += str(message_data)
#     return results

# text_messages = get_query_results()

# print(text_messages + '\n' + calculate_total(text_messages))


from trac.db import Table, Column, Index

__all__ = ['version', 'schema']

name = 'remote_ticket'
version = 3

schema  = [
    Table('remote_ticket_links',
          key=('source_name', 'source', 'type',
               'destination_name', 'destination'))[
        Column('source_name'),
        Column('source', type='int'),
        Column('type'),
        Column('destination_name'),
        Column('destination', type='int'),
        ],
    Table('remote_tickets', key=('remote_name', 'id'))[
        Column('remote_name'),
        Column('id', type='int'),
        Column('cachetime', type='int64'),
        Column('time', type='int64'),
        Column('changetime', type='int64'),
        Column('component'),
        Column('severity'),
        Column('priority'),
        Column('owner'),
        Column('reporter'),
        Column('cc'),
        Column('version'),
        Column('milestone'),
        Column('status'),
        Column('resolution'),
        Column('summary'),
        Column('description'),
        Column('keywords'),
        Index(['cachetime']),
        Index(['status']),
        ],
    ]


''' Intcode Computer impolementation.
From: https://github.com/m-berk/AdventOfCode2019/blob/master/Day9.2.py '''

class intCodeComputer:
    def __init__(self, programCode, id=0, relBase=0, indx=0, emptySpace=10000, inptArr=[], verbose=False):
        self.relativeBase = 0
        self.memory = []
        self.memory = programCode.copy()
        for i in range(emptySpace):
            self.memory.append(0)
        self.index = indx
        self.inputArray = inptArr.copy()
        self.outputArray = []
        self.id = id
        self.finished = False
        self.verbose = verbose

    def setSingleMemoryAddress(self, pos, val):
        self.memory[pos] = val

    def compute(self):  # computes until there's an input requiered

        while (not self.finished):

            # formatting OPCODE

            TempLen = len(str(self.memory[self.index]))
            StringToAdd = ""
            for i in range(5 - TempLen):
                StringToAdd += "0"
            self.memory[self.index] = StringToAdd + str(self.memory[self.index])
            # print(self.memory[self.index])

            # reading parameters according to the given parameter modes ----------------------
            parameters = []
            parameterMode = str(self.memory[self.index][:3])
            # print(self.memory[self.index], parameterMode)
            # print(parameterMode)
            OpCode = str(self.memory[self.index])[-2:]
            self.memory[self.index] = int(self.memory[self.index])
            if (parameterMode[2] == "0"):
                parameters.append(int(self.memory[self.index + 1]))
            elif (parameterMode[2] == "1"):
                parameters.append(self.index + 1)
            else:  # paramMode 2
                parameters.append(int(self.memory[self.index + 1]) + self.relativeBase)

            if (parameterMode[1] == "0"):
                parameters.append(int(self.memory[self.index + 2]))
            elif (parameterMode[1] == "1"):
                parameters.append(self.index + 2)
            else:  # paramMode 2
                parameters.append(self.memory[self.index + 2] + self.relativeBase)

            if (parameterMode[0] == "0"):
                parameters.append(int(self.memory[self.index + 3]))
            elif (parameterMode[0] == "1"):
                parameters.append(self.index + 3)
            else:  # paramMode 2
                parameters.append(int(self.memory[self.index + 3]) + self.relativeBase)

            if (OpCode == "01"):
                self.memory[parameters[2]] = int(self.memory[parameters[0]]) + int(self.memory[parameters[1]])
                self.index += 4
            elif (OpCode == "02"):
                self.memory[parameters[2]] = int(self.memory[parameters[0]]) * int(self.memory[parameters[1]])
                self.index += 4
            elif (OpCode == "03"):
                if (len(self.inputArray) != 0):
                    self.memory[parameters[0]] = self.inputArray[0]
                    self.index += 2
                    self.inputArray.pop(0)
                else:
                    if self.verbose: print("waiting input")
                    break
            elif (OpCode == "04"):
                # print("output from int comp "+str(self.id)+ "  :" +str(self.memory[parameters[0]]))
                self.outputArray.append(self.memory[parameters[0]])
                self.index += 2
            elif (OpCode == "05"):
                if (self.memory[parameters[0]] != 0):
                    self.index = int(self.memory[parameters[1]])
                else:
                    self.index += 3
            elif (OpCode == "06"):
                if (self.memory[parameters[0]] == 0):
                    self.index = int(self.memory[parameters[1]])
                else:
                    self.index += 3
            elif (OpCode == "07"):
                if (int(self.memory[parameters[0]]) < int(self.memory[parameters[1]])):
                    self.memory[parameters[2]] = 1
                else:
                    self.memory[parameters[2]] = 0
                self.index += 4
            elif (OpCode == "08"):
                if (self.memory[parameters[0]] == self.memory[parameters[1]]):
                    self.memory[parameters[2]] = 1
                else:
                    self.memory[parameters[2]] = 0
                self.index += 4
            elif (OpCode == "09"):
                self.relativeBase += self.memory[parameters[0]]
                self.index += 2
            elif (OpCode == "99"):
                if self.verbose: print(str(self.id) + ". computer has finished")
                self.finished = True
                break

    def addInput(self, input):
        self.inputArray.append(input)

    def printOutputs(self):
        print(self.outputArray)

    def getOutput(self):
        return self.outputArray

    def flushOutputs(self):
        self.outputArray.clear()

    def outputASCII(self):
        ascii_out = self.outputArray
        line = ''.join( [chr(a) for a in ascii_out] )
        print(line)

    def interactiveRun(self):
        while not self.finished:
            self.compute()
            self.outputASCII()
            input_command = input()
            self.inputArray = [ord(a) for a in input_command+'\n']

        print()
        print('PROGRAM FINISHED')


"""create table comment

Revision ID: 9336eef458e7
Revises: 9d8c8c38a1d0
Create Date: 2022-03-30 21:37:02.080429

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID

# revision identifiers, used by Alembic.
revision = "9336eef458e7"
down_revision = "d66baafab5ec"
branch_labels = None
depends_on = None

def upgrade():
    NOW = sa.text("NOW()")

    op.create_table(
        "comment",
        sa.Column("id", sa.Integer, autoincrement=True, primary_key=True),
        sa.Column("uid", UUID, server_default=sa.func.uuid_generate_v4()),
        sa.Column("created_at", sa.DateTime, nullable=False, server_default=NOW),
        sa.Column(
            "updated_at", sa.DateTime, nullable=False, server_default=NOW, onupdate=NOW
        ),
        sa.Column("body", sa.TEXT),
        sa.Column(
            "author_id", sa.Integer, sa.ForeignKey("user.id", ondelete="CASCADE")
        ),
        sa.Column(
            "track_id", sa.Integer, sa.ForeignKey("track.id", ondelete="CASCADE")
        ),
    )

def downgrade():
    op.drop_table("comment")


import matplotlib.pyplot as plt
import numpy as np
import json
import os
import argparse
from typing import List
from ast import For
from datetime import datetime,timedelta
from pkgutil import extend_path
from matplotlib.transforms import Bbox
from matplotlib.cbook import get_sample_data
from matplotlib._png import read_png
from mpl_toolkits import mplot3d
from helper import Helper
from timing import Timing
from model.ApproachBody import ApproachBody
from model.BuyExplorationData import BuyExplorationData
from model.Cargo import Cargo
from model.CodexEntry import CodexEntry
from model.Commander import Commander
from model.DiscoveryScan import DiscoveryScan
from model.Docked import Docked
from model.DockingCancelled import DockingCancelled
from model.DockingDenied import DockingDenied
from model.DockingGranted import DockingGranted
from model.DockingRequested import DockingRequested
from model.DockingTimeout import DockingTimeout
from model.Fileheader import Fileheader
from model.FSDJump import FSDJump
from model.FSDJumpConflicts import FSDJumpConflicts
from model.FSDJumpConflictsFaction import FSDJumpConflictsFaction
from model.FSDJumpFactions import FSDJumpFactions
from model.FSDJumpSystemFaction import FSDJumpSystemFaction
from model.FSDTarget import FSDTarget
from model.FSSAllBodiesFound import FSSAllBodiesFound
from model.FSSDiscoveryScan import FSSDiscoveryScan
from model.FSSSignalDiscovered import FSSSignalDiscovered
from model.LeaveBody import LeaveBody
from model.Liftoff import Liftoff
from model.LoadGame import LoadGame
from model.Loadout import Loadout
from model.Location import Location
from model.MaterialCollected import MaterialCollected
from model.MaterialDiscarded import MaterialDiscarded
from model.MaterialDiscovered import MaterialDiscovered
from model.Materials import Materials
from model.Missions import Missions
from model.MultiSellExplorationData import MultiSellExplorationData
from model.NavBeaconScan import NavBeaconScan
from model.NavRoute import NavRoute
from model.NewCommander import NewCommander
from model.Passengers import Passengers
from model.Powerplay import Powerplay
from model.Progress import Progress
from model.Rank import Rank
from model.Reputation import Reputation
from model.SAAScanComplete import SAAScanComplete
from model.SAASignalsFound import SAASignalsFound
from model.Scan import Scan
from model.SellExplorationData import SellExplorationData
from model.StartJump import StartJump
from model.Statistics import Statistics
from model.SupercruiseEntry import SupercruiseEntry
from model.SupercruiseExit import SupercruiseExit
from model.Synthesis import Synthesis
from model.Touchdown import Touchdown
from model.Undocked import Undocked
from model.Music import Music

class ED:
    def __init__(self):
        '''
        Constructor
        '''

        with open("config.json", "r") as config_file:
            config = json.load(config_file)
        self.journals_path = config.get("journals_path")
        self.green_system_materials = {
            "basic": [
                "carbon",
                "vanadium",
                "germanium",
            ],
            "standard": [
                "carbon",
                "vanadium",
                "germanium",
                "cadmium",
                "niobium",
            ],
            "premium": [
                "carbon",
                "germanium",
                "niobium",
                "arsenic",
                "yttrium",
                "polonium",
            ]
        }

        self.timing = Timing()

    def parseArgs(self):
        '''
        Parse command line arguments
        '''

        # Initiate the parser
        parser = argparse.ArgumentParser()

        # Add possible arguments
        parser.add_argument("--all-events", help="Handle all journal event types", action="store_true")
        parser.add_argument("--all-journals", help="Parse all journal files", action="store_true")
        parser.add_argument("--events", help="Journal event types, separated by comma (,)")
        parser.add_argument("--journal-from", help="Journal timestamp from")
        parser.add_argument("--journal-to", help="Journal timestamp to. If ommited, assume current datetime")
        parser.add_argument("--save-events-to-csv", help="Save events to CSV", action="store_true")
        parser.add_argument("--save-events-to-json", help="Save events to JSON", action="store_true")
        parser.add_argument("--save-system-coordinates-to-csv", help="Save system coordinates to CSV", action="store_true")
        parser.add_argument("--scan-type", help="For event type 'Scan' - Scan type can be Basic, Detailed, NavBeacon, NavBeaconDetail, AutoScan")
        parser.add_argument("--materials", help="For event type 'Scan' - Materials, separated by comma (,)")
        parser.add_argument("--landable", help="For event type 'Scan' - If the body is landable or not", action="store_true")
        parser.add_argument("--was-mapped", help="For event type 'Scan' - If the body was mapped", action="store_true")
        parser.add_argument("--was-discovered", help="For event type 'Scan' - If the body was discovered", action="store_true")
        parser.add_argument("--green-systems", help="For event type 'Scan' - Filter 'green' systems (systems where you can find materials for FSD injections)", action="store_true")
        parser.add_argument("--total-earnings", help="For event types 'SellExplorationData', 'MultiSellExplorationData' - Get total earnings", action="store_true")

        # Read arguments from the command line
        self.args = parser.parse_args()

        if (self.args.all_events):
            self.args.events = []
        else:
            if (self.args.events):
                self.args.events = [event.strip() for event in self.args.events.split(",")]
            else:
                raise Exception("Provide at least one journal event type by using the '--events' option or use '--all-events' option")

        if (not self.args.all_journals):
            if (self.args.journal_from):
                self.args.journal_from = datetime.strptime(self.args.journal_from, "%Y-%m-%d")
            else:
                raise Exception("Provide a 'from' timestamp to start filtering for journals using the '--journal-from' option  (format: YYYY-mm-dd)")

            if (self.args.journal_to):
                self.args.journal_to = datetime.strptime(self.args.journal_to, "%Y-%m-%d")

        return self.args

    def createObjectByEvent(self, line):
        e = line.get("event")
        switch = {
            "ApproachBody": ApproachBody,
            "BuyExplorationData": BuyExplorationData,
            "Cargo": Cargo,
            "CodexEntry": CodexEntry,
            "Commander": Commander,
            "DiscoveryScan": DiscoveryScan,
            "Docked": Docked,
            "DockingCancelled": DockingCancelled,
            "DockingDenied": DockingDenied,
            "DockingGranted": DockingGranted,
            "DockingRequested": DockingRequested,
            "DockingTimeout": DockingTimeout,
            "Fileheader": Fileheader,
            "FSDJump": FSDJump,
            "FSDJumpConflicts": FSDJumpConflicts,
            "FSDJumpConflictsFaction": FSDJumpConflictsFaction,
            "FSDJumpFactions": FSDJumpFactions,
            "FSDJumpSystemFaction": FSDJumpSystemFaction,
            "FSDTarget": FSDTarget,
            "FSSAllBodiesFound": FSSAllBodiesFound,
            "FSSDiscoveryScan": FSSDiscoveryScan,
            "FSSSignalDiscovered": FSSSignalDiscovered,
            "LeaveBody": LeaveBody,
            "Liftoff": Liftoff,
            "LoadGame": LoadGame,
            "Loadout": Loadout,
            "Location": Location,
            "MaterialCollected": MaterialCollected,
            "MaterialDiscarded": MaterialDiscarded,
            "MaterialDiscovered": MaterialDiscovered,
            "Materials": Materials,
            "Missions": Missions,
            "MultiSellExplorationData": MultiSellExplorationData,
            "NavBeaconScan": NavBeaconScan,
            "NavRoute": NavRoute,
            "NewCommander": NewCommander,
            "Passengers": Passengers,
            "Powerplay": Powerplay,
            "Progress": Progress,
            "Rank": Rank,
            "Reputation": Reputation,
            "SAAScanComplete": SAAScanComplete,
            "SAASignalsFound": SAASignalsFound,
            "Scan": Scan,
            "SellExplorationData": SellExplorationData,
            "StartJump": StartJump,
            "Statistics": Statistics,
            "SupercruiseEntry": SupercruiseEntry,
            "SupercruiseExit": SupercruiseExit,
            "Synthesis": Synthesis,
            "Touchdown": Touchdown,
            "Undocked": Undocked,
            "Music": Music
        }
        classname = switch.get(e, None)
        if (classname != None):
            method = getattr(classname, 'fromDict')
            val = method(line)
            return val
        return None

    def parseJournalsData(self):
        # TODO: Probably merge all the function in order to avoid repetitive loops
        self.timing.startTimingExecution()
        journal_file_names = self.filerJournalsByTimestamp()
        journals_data_lines = self.loadJournalLines(journal_file_names)
        self.journals = self.parseJournalLines(journals_data_lines)
        self.timing.stopTimingExecution("Parse journals")

    def filerJournalsByTimestamp(self):
        files = os.listdir(self.journals_path)
        journal_file_names = []
        for file in files:
            parts = file.split(".")
            if (parts[0] == "Journal"):
                journal_date = datetime.strptime(parts[1][0:6], "%y%m%d")
                if (
                    self.args.all_journals or
                    (self.args.journal_to is None and journal_date >= self.args.journal_from) or
                    (journal_date >= self.args.journal_from and self.args.journal_to >= journal_date)
                ):
                    journal_file_names.append(file)
        return journal_file_names

    def loadJournalLines(self, journal_file_names):
        journals_data_lines = []
        for filename in journal_file_names:
            with open("{}\\{}".format(self.journals_path, filename), "r", encoding="utf8") as json_file:
                lines = json_file.readlines()
                for l in lines:
                    line = json.loads(l)
                    if (not self.args.events or (line.get("event") in self.args.events)):
                        journals_data_lines.append(line)
        if (self.args.save_events_to_csv):
            self.saveEventsAsCSV(journals_data_lines)
        if (self.args.save_events_to_json):
            self.saveEventsAsJSON(journals_data_lines)
        return journals_data_lines

    def parseJournalLines(self, journals_data_lines):
        journals = []
        for line in journals_data_lines:
            obj = self.createObjectByEvent(line)
            if (obj is not None):
                journals.append(obj)
        return journals

    #region Custom methods

    def loadGreenSystems(self):
        # TODO: Create generic object in order to hold system data and details from other events
        data = []
        self.timing.startTimingExecution()
        for line in self.journals:
            if (isinstance(line, FSDJump)):
                planets = []
                has_basic_materials = False
                has_standard_materials = False
                has_premium_materials = False
                is_green_system = False
                # TODO: 30ms at each loop
                scan_data = [l for l in self.journals if isinstance(l, Scan) and l.system_address == line.system_address]
                for planet in scan_data:
                    b = []
                    s = []
                    p = []
                    if (planet.landable and len(planet.materials) > 0):
                        b = [m.name for m in planet.materials if m.name in self.green_system_materials["basic"]]
                        s = [m.name for m in planet.materials if m.name in self.green_system_materials["standard"]]
                        p = [m.name for m in planet.materials if m.name in self.green_system_materials["premium"]]
                    if not has_basic_materials:
                        has_basic_materials = True if b else False
                    if not has_standard_materials:
                        has_standard_materials = True if s else False
                    if not has_premium_materials:
                        has_premium_materials = True if p else False
                    is_green_system = has_basic_materials and has_standard_materials and has_premium_materials
                    p = {
                        "system_address": planet.system_address,
                        "body_name": planet.body_name,
                        "surface_gravity": planet.surface_gravity,
                        "has_basic_materials": has_basic_materials,
                        "has_standard_materials": has_standard_materials,
                        "has_premium_materials": has_premium_materials,
                        "materials": {
                            "basic": b,
                            "standard": s,
                            "premium": p
                        }
                    }
                    planets.append(p)
                data.append({
                    "system": {
                        "name": line.star_system,
                        "address": line.system_address,
                        "star_pos": line.star_pos,
                        "is_green_system": is_green_system,
                        "planets": planets
                    }
                })
        self.timing.stopTimingExecution("Green systems")
        return {
            "type": "green_systems",
            "data": data
        }

    def loadSystemCoordinates(self):
        data = []
        for line in self.journals:
            if (isinstance(line, FSDJump)):
                if (len(line.star_pos) > 0):
                    data.append({
                        "timestamp": line.timestamp,
                        "star_system": line.star_system,
                        "jump_dist": line.jump_dist,
                        "X": line.star_pos[0],
                        "Y": line.star_pos[1],
                        "Z": line.star_pos[2]
                    })
        if (self.args.save_system_coordinates_to_csv):
            self.saveSystemCoordinatesAsCSV(data)
        return {
            "type": "coordinates",
            "data": data
        }

    def getTotalEarnings(self):
        total_earnings = 0
        for line in self.journals:
            if (isinstance(line, SellExplorationData) or isinstance(line, MultiSellExplorationData)):
                total_earnings += line.total_earnings
        print("Total earnings: {0:,} CR".format(total_earnings))
        return {
            "type": "total_earnings",
            "data": total_earnings
        }

    def saveSystemCoordinatesAsCSV(self, data):
        print("Save system coordinates as CSV...")
        Helper.saveAsCSV(data, ["timestamp", "star_system", "jump_dist", "X", "Y", "Z"], "coordinates.csv", ";")

    def saveEventsAsJSON(self, data):
        print("Save events as JSON...")
        Helper.saveAsJSON(data)

    def saveEventsAsCSV(self, data):
        d = []
        for line in data:
            d.append({
                "timestamp": line["timestamp"],
                "event": line["event"],
                "data": line
            })
        print("Save events as CSV...")
        Helper.saveAsCSV(d, ["timestamp", "event", "data"], "events.csv", "##")

    #endregion

class EDStats:
    filter_types: List[str]

    def __init__(self) -> None:
        self.filter_types = [
            "coordinates",
            "green_systems",
            "total_earnings"
        ]

    # TODO: initData can contain anything not just coordinates.
    # Probably pass event type as well
    def initData(self, data):
        if (data["type"] in self.filter_types):
            if (data["type"] == "coordinates"):
                self.x = [d["X"] for d in data["data"]]
                self.y = [d["Y"] for d in data["data"]]
                self.z = [d["Z"] for d in data["data"]]
            elif (data["type"] == "green_systems"):
                self.x = [m["system"]["star_pos"][0] for m in data["data"] if m["system"]["is_green_system"]]
                self.y = [m["system"]["star_pos"][1] for m in data["data"] if m["system"]["is_green_system"]]
                self.z = [m["system"]["star_pos"][2] for m in data["data"] if m["system"]["is_green_system"]]

    def initialize2DPlot(self):
        self.im = plt.imread("milky_way_ed_9000px.jpg")
        self.fig, self.ax = plt.subplots(figsize=(20, 20))
        self.fig.tight_layout()
        self.ax.imshow(self.im, extent=[-45000, 45000, -20000, 70000])

    def initialize3DPlot(self):
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111, projection='3d')
        # self.fig, self.ax = plt.subplots(subplot_kw=dict(projection="3d"))
        self.fig.tight_layout()
        self.ax.axes.set_xlim3d(left=-45000, right=45000)
        self.ax.axes.set_ylim3d(bottom=-20000, top=70000)
        self.ax.axes.set_zlim3d(bottom=-25000, top=25000)
        # self.ax.set(xlabel="X axis", ylabel="Y axis", title="test plot")

    def plot2DData(self):
        self.ax.plot(self.x, self.z)

    def scatter2DData(self):
        self.ax.scatter(self.x, self.z)

    def plot3DData(self):
        # inverted Y <-> Z axes
        self.ax.plot3D(self.x, self.z, self.y)

    def scatter3DData(self):
        self.im = plt.imread("milky_way_ed_9000px.jpg")
        # inverted Y <-> Z axes
        self.ax.scatter3D(self.x, self.z, self.y)

    def savePlotToFile(self):
        # self.fig.savefig("plot_{}.png".format(datetime.now().replace(microsecond=0).strftime("%Y-%m-%d_%H-%M-%S")), bbox_inches="tight")
        self.fig.savefig("plot.png", bbox_inches="tight")

    def showPlot(self):
        plt.show()

if __name__ == "__main__":
    # journal_date_from = datetime(2021, 1, 29)
    # journal_date_to = datetime(2023, 6, 1)

    ed = ED()
    ed.timing.startTimingExecution()
    ed.parseArgs()
    ed.parseJournalsData()
    data = ed.loadSystemCoordinates()
    ed.timing.stopTimingExecution("Main")
    # ed.getTotalEarnings()
    # stats = EDStats()
    # stats.initData(data)
    # stats.initialize2DPlot()
    # stats.scatter2DData()
    # stats.initialize3DPlot()
    # stats.scatter3DData()
    # stats.savePlotToFile()
    # stats.showPlot()


import bidict
import discord

from discord.ext import commands
from time import time

def dms_only():
    def predicate(ctx: commands.Context):
        return isinstance(ctx.channel, discord.DMChannel)
    return commands.check(predicate)

def is_ticket_open(ctx: commands.Context, ticket_channels):
    return ctx.channel in ticket_channels or ctx.channel in ticket_channels.inverse

class Ticket(commands.Cog):

    def __init__(self, bot):
        self.ticket_channels: bidict.BidictBase[discord.abc.Messageable, discord.abc.Messageable] = bidict.bidict()
        self.bot = bot

    # def log_channel(self, channel: discord.TextChannel):
    #     pass

    @commands.Cog.listener('on_message')
    async def on_message(self, message: discord.Message):
        if message.author.bot:
            return
        if message.channel in self.ticket_channels:

            try:
                await self.ticket_channels[message.channel].send(content=message.content)
                if message.attachments:
                    await self.ticket_channels[message.channel].send('\n'.join([a.url for a in message.attachments]))
            except Exception as e:
                await message.channel.send("Could not send message, reason: {}".format(e))

        elif message.channel in self.ticket_channels.inverse:
            try:
                await self.ticket_channels.inverse[message.channel].send(content=message.author.mention + ': ' + message.content)
                if message.attachments:
                    await self.ticket_channels.inverse[message.channel].send('\n'.join([a.url for a in message.attachments]))
            except Exception as e:
                await message.channel.send("Could not send message, reason: {}".format(e))

    @commands.command('ticket.open')
    async def ticket_open(self, ctx, *args):

        if not isinstance(ctx.channel, discord.DMChannel):
            await ctx.author.send("For your privacy the command you just typed is for my DMs only")
            await ctx.message.delete()
            return

        if ctx.channel in self.ticket_channels:
            await ctx.send("You have already opened a ticket, please close it using `!ticket.close` to open a new one")
            return

        name = ' '.join(args)
        guilds = ctx.author.mutual_guilds
        guild = discord.utils.find(lambda g: g.name.lower() == name.lower(), guilds)
        if guild is None:
            await ctx.send("I Don't know that guild")
            return

        ticket_role_ids = self.bot.get_data(guild.id, 'ticket_roles_ids', [])

        if not any(map(lambda r: r.id in ticket_role_ids, guild.get_member(ctx.author.id).roles)):
            await ctx.author.send("you do not have permissions to open a ticket in this guild")
            return

        category: discord.CategoryChannel = discord.utils.get(guild.categories, id=self.bot.get_data(guild.id, 'ticket_category', 0))
        if not category:
            await ctx.author.send('This guild has not set up the ticket system yet')
            return
        ticket_channel = await category.create_text_channel('ticket-{}'.format(time()))
        self.ticket_channels[ctx.channel] = ticket_channel
        await ctx.send("The ticket is now open, talk to me and I'll pass it on")

    @commands.command('ticket.close')
    async def ticket_close(self, ctx):
        if not is_ticket_open(ctx, self.ticket_channels):
            await ctx.send("there is no open ticket linked to this channel")
            return

        if isinstance(ctx.channel, discord.DMChannel):
            if ctx.channel in self.ticket_channels.keys():
                guild_channel = self.ticket_channels[ctx.channel]
                # self.log_channel(guild_channel)
                self.ticket_channels.pop(ctx.channel)
                await ctx.channel.send("Ticket closed, I will no longer pass your messages to the server")
                # await guild_channel.delete()
        else:
            if ctx.channel not in self.ticket_channels.inverse:
                return
            # self.log_channel(ctx.channel)
            dm_channel = self.ticket_channels.inverse.pop(ctx.channel)
            await dm_channel.send("Ticket closed, I will no longer pass your messages to the server")
            # await ctx.channel.delete()

    @commands.command('ticket.exclude')
    async def ticket_exclude(self, ctx, members: commands.Greedy[discord.Member]):
        if not is_ticket_open(ctx, self.ticket_channels):
            await ctx.send("there is no open ticket linked to this channel")
            return

        if isinstance(ctx.channel, discord.DMChannel):
            ticket_channel = self.ticket_channels[ctx.channel]
        else:
            ticket_channel = ctx.channel

        if isinstance(ticket_channel, discord.TextChannel):
            exclude_permission = discord.PermissionOverwrite(view_channel=False)
            for member in members:
                await ticket_channel.set_permissions(member, overwrite=exclude_permission)

    @commands.command('ticket.include')
    async def ticket_include(self, ctx, members: commands.Greedy[discord.Member]):
        if not is_ticket_open(ctx, self.ticket_channels):
            await ctx.send("there is no open ticket linked to this channel")
            return

        if isinstance(ctx.channel, discord.DMChannel):
            ticket_channel = self.ticket_channels[ctx.channel]
        else:
            ticket_channel = ctx.channel

        if isinstance(ticket_channel, discord.TextChannel):
            include_permission = discord.PermissionOverwrite(view_channel=True)
            for member in members:
                await ticket_channel.set_permissions(member, overwrite=include_permission)

    @commands.command('ticket.view')
    async def ticket_view(self, ctx):
        if not is_ticket_open(ctx, self.ticket_channels):
            await ctx.send("there is no open ticket linked to this channel")
            return

        if isinstance(ctx.channel, discord.DMChannel):
            ticket_channel = self.ticket_channels[ctx.channel]
        else:
            ticket_channel = ctx.channel
        embed = discord.Embed(title=ticket_channel.name)
        embed.add_field(name='Permitted Users', value='\n'.join([m.mention for m in ticket_channel.members]))
        await ctx.send(embed=embed)

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


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

import argparse
import os

USAGE = r"""
             %prog -e CTGCAG -o out_file \

             provide a Restriction endonuclease with cut site
             example 1: C:\Users\user\Desktop>C:\Users\user\AppData\Local\Programs\Python\Python35\python.exe 1.py -e TTCGA^A -o rest.txt \
                 TTCOT \
             example 2: C:\Users\user\Desktop>C:\Users\user\AppData\Local\Programs\Python\Python35\python.exe 1.py -o rest.txt \
                 CTGCAG \
                 CTGCA^G
          """

parser = argparse.ArgumentParser(description = USAGE)

# parser.add_argument('-e', "--restriction", action = "store", type= str, default = "CTGCA^G", help = "the restriction enzyme you choose")
parser.add_argument('-e', "--restriction", action = "store", type= str, dest = "RE", default = "CTGCA^G", help = "the restriction enzyme you choose")
parser.add_argument('-o', "--output", action = "store", type = argparse.FileType("w"))

args = parser.parse_args()

os.chdir("C:\\Users\\user\\Downloads\\")

def read_fasta(fp):
    name, seq = (None, [])
    for line in fp:
        line = line.rstrip()
        if line.startswith(">"):
            if name:
                yield (name, ''.join(seq))
            name, seq = (line, [])
        else:
            seq.append(line)
    if name:
        yield (name, ''.join(seq))

cut_site = args.RE.find("^")
enz_seq =args.RE.replace("^","")
print (enz_seq)

with open("test_restriction.fa") as f_handle:
    for contig_n, seq in read_fasta(f_handle):
        #print (args.restriction)
        print (args.RE)
        #args.output.write (seq+"##\n")
        enz_locus = -1
        while True:
            # find enzyme sequence location from the start
            enz_locus = seq.find(enz_seq, enz_locus + 1)
            # break if not found
            if enz_locus == -1:
                break
            args.output.write("{0}\n".format(enz_locus + cut_site))

args.output.close()

os.chdir("C:\\Users\\user\\Desktop\\")

def get_lines(file_obj):
    items = [""]*2
    #items = ("", "")
    for number, line in enumerate(file_obj):
        slot=number % 2
        items[slot] = line.rstrip()
        if number >=1:
            yield (items)

bed_file = open(args.output.name + ".bed", 'w')
#with open("rest.txt", 'r') as fobj:
with open(args.output.name, 'r') as fobj:
    for loci in get_lines(fobj):
        #print (loci)
        #length = abs(int(loci[0]) - int(loci[1]))
        if int(loci[0]) > int(loci[1]):

            length = int(loci[0]) - int(loci[1])
            bed_file.write("{0}\t{1}\t{2}\t{3}\n".format("test_contig", loci[1], loci[0], length))
        else:
            length = int(loci[1]) - int(loci[0])
            bed_file.write("{0}\t{1}\t{2}\t{3}\n".format("test_contig", loci[0], loci[1], length))

bed_file.close()


#!/usr/env/python

"""
Base Event Publisher and Subscriber

Implements the Event, Publisher and Subscriber classes, that provides a pub-
sub interface for broadcasting Events from Publishers (Subject) to Subscribers
(Observers). The Publisher is an Observer as well that enables rebroadcasting
of Events.

Classes:
- Event
- Subscriber
- Publisher
"""

from collections import abc
from dataclasses import dataclass
from enum import IntEnum
from typing import Callable, Generic, TypeVar, Union

from rx import Observer
from rx.subjects import Subject

T = TypeVar('T')

@dataclass
class Event(Generic[T]): # pylint: disable=E1136
  """
  Data class for an event. Each event has a specified event type,
  and the object associated with the event as context.

  Generics:
    T:  Contextual object associated with each Event.

  Attributes:
    kind:     The type of event.
    context:  The object associated with this event.
  """
  kind: IntEnum
  context: T

  def setparams(self, **kwargs):
    """
    Assigns the given keyword arguments as attributes to this Event.

    Args:
      kwargs:
        The arguments to set as attributes.
    """
    for k, v in kwargs.items():
      setattr(self, k, v)

class Subscriber(Observer, Generic[T]): # pylint: disable=E1136
  """
  Implements the wrapper for an Observer.

  Each Event is paired with an IntEnum event type (or kind), and invokes
  specific event handler methods for each Event type.

  Generics:
    T:  Contextual object associated with each Event.

  Extends:
    Observer

  Attributes:
    events:
      The registered Event types (kind).
      If None, no register Event types.
    eventmapper:
      A lambda method that maps each Event to a
      method name for a specific event handler.
    strict:
      Boolean flag whether or not to raise an exception
      when Event handler not found.
      - True:  Raise exception when handler not found.
      - False: Otherwise. Default.
  """
  events:       Union[IntEnum, None]
  eventmapper:  Callable[[Event[T]], str]
  strict:       bool

  def __init__(self, events: Union[IntEnum, None] = None):
    """
    Initialize this Subscriber with the given Event types.

    Args:
      events:
        The registered Event types (kind).
        If None, no register Event types.
    """
    def eventmapper(event: Event[T]) -> str:
      assert isinstance(event, Event)
      assert isinstance(event.kind, IntEnum)

      return f'on_{event.kind.name}'.lower()

    self.events = events
    self.eventmapper = eventmapper
    self.strict = False

  ### Methods: Event Handlers

  def on_next(self, event: Event[T]):
    """
    The Event handler when an Event occurs.

    Args:
      event:
        The next Event to occur.

    Raises:
      AttributeError:
        Event handler not found.
    """
    handle = self.eventmapper(event)
    if hasattr(self, handle):
      #print(f'{type(self).__name__}.{handle}')
      getattr(self, handle)(event)
    elif self.strict:
      raise AttributeError(handle)

  def on_completed(self):
    """
    The Event handler when no more Events.
    Subscription completed.
    """
    pass # Do nothing

  def on_error(self, exception: Exception):
    """
    The Event handler when an error occurs.

    Args:
      exception:
        The error that occurred.
    """
    pass # Do nothing

class Publisher(Subscriber[T], abc.Container):
  """
  Implements the wrapper for an Observer and a Subject.

  Broadcasts the Events to the subscribed Observers on the Subject.
  Each Event is paired with an IntEnum event type (or kind), and invokes
  specific event handler methods for each Event type.

  Generics:
    T:  Contextual object associated with each Event.

  Extends:
    Subscriber[T]
    abc.Container

  Attributes:
    subject:
      The Subject for Observers to subscribe to.
    presubj:
      The Subject for Observers to subscribe to, whose
      on_next are always called before, self.on_next
      and the subjects' on_next.
  """
  subject: Subject
  presubj: Subject

  def __init__(self, events: Union[IntEnum, None] = None):
    """
    Initialize this Publisher with the given Event types.

    Args:
      events:
        The registered Event types (kind).
        If None, no register Event types.
    """
    Subscriber.__init__(self, events)

    self.presubj = Subject()
    self.subject = Subject()

  ### Methods: Queries

  def __contains__(self, observer: Observer) -> bool:
    """
    Determine whether or not the given is already subscribed
    to this Publisher.

    Args:
      observer:
        The Observer to test whether or not
        already subscribed to this Publisher.

    Returns:
      True:   If already subscribed.
      False:  Otherwise.
    """
    return observer in self.subject.observers or \
           observer in self.presubj.observers

  ### Methods: Subscribe

  def subscribe(self, observer: Observer, before: bool = False):
    """
    Subscribes the given Observer to the subject of
    this Publisher when an Event occurs.

    Args:
      observer:
        The Observer to subscribe to.
      before:
        Boolean flag for whether or not to receive Event
        before self.on_next or after self.on_next.
        True, for before; False, otherwise.
    """
    assert observer not in self

    subject = self.presubj if before else self.subject
    subject.subscribe(observer)

  ### Methods: Broadcast

  def broadcast(self, event: Event, **kwargs):
    """
    Broadcast the given event to subscribed Observers.

    Args:
      event:
        The Event to be broadcasted.
      kwargs:
        The parameters to be added or modified
        within the given Event.
    """
    if hasattr(event, 'source') and event.source is self:
      return

    event.setparams(source=self, **kwargs)
    self.subject.on_next(event)

  ### Methods: Event Handlers

  def on_next(self, event: Event[T]):
    """
    The Event handler when an Event occurs.
    Broadcast next Event.

    Overrides:
      Subscriber.on_next

    Args:
      event:
        The next Event to occur.
    """
    if hasattr(event, 'source') and event.source is self:
      return

    self.presubj.on_next(event)

    try:
      if self.events:
        Subscriber.on_next(self, event)
    finally:
      self.broadcast(event)

  def on_completed(self):
    """
    The Event handler when no more Events. Subscription completed.
    Broadcast completion Event.

    Overrides:
      Subscriber.on_completed
    """
    self.presubj.on_completed()
    self.subject.on_completed()

  def on_error(self, exception: Exception):
    """
    The Event handler when an error occurs.
    Broadcast error Event.

    Overrides:
      Subscriber.on_error

    Args:
      exception:
        The error that occurred.
    """
    self.presubj.on_error(exception)
    self.subject.on_error(exception)


import models
from proto import Handler

class CommentHandler(Handler):
    # This is an AJAX handler. Do not navigate here

    def get(self, post_id):
        '''Retrieves comments for post. Sends them to user in JSON
        '''
        post = models.Post.get_by_id(int(post_id))
        if post:
            comments = post.comments
            obj = {'success': True}
            if comments and self.user:
                obj['result'] = self.render_str('comment.html',
                                                comments=comments,
                                                user=self.user)
            elif comments:
                obj['result'] = self.render_str('comment.html',
                                                comments=comments)
        else:
            obj = {'success': False}
        self.json(obj)

    def post(self, post_id):
        '''Takes a new comment as input. If user is logged in comment is
        added to db, rendered using jinja, and returned to the user in JSON.
        If error, success: False and an error message is sent to user in JSON.
        '''

        comment = self.request.get('comment')
        post = models.Post.get_by_id(int(post_id))

        @self.logged_in
        def post_comment(post, comment):
            if not self.valid_post:
                return
            elif not comment:
                obj = {
                       'success': False,
                       "message": 'You have to type a comment'
                }
            else:
                comment = models.Comment(user=self.user, comment=comment,
                                         post=post)
                comment.put()
                obj = {
                        'success': True,
                        'result': self.render_str('newcommentresponse.html',
                                                  comment=comment,
                                                  user=self.user)
                }
                self.json(obj)

        post_comment(post, comment)


import pytest
import random
import string

from name import Name

@pytest.fixture
def name():
    return get_name()

def get_name():
    length = random.randint(1, 12)
    first = "".join(
        random.choices(
            string.ascii_uppercase + string.ascii_lowercase, k=length
        )
    )
    last = "".join(
        random.choices(string.ascii_uppercase + string.digits, k=length)
    )
    return Name(parts=[first, last], sort_order=(0, 1))

@pytest.fixture
def name_factory():
    class NameFactory(object):
        def get(self):
            name_factory = get_name()
            return name_factory

    return NameFactory()

def test_name_equals(name_factory) -> None:
    ret = 0
    # using loop on the small chace that the random names are the same
    for i in range(1, 10):
        name1 = name_factory.get()
        name2 = name_factory.get()
        if name1 != name2:
            ret += 1
    assert ret >= 5

def test_name_sort() -> None:
    name1 = Name(["Bob", "T", "Smith"])
    name2 = Name(["Zee", "Atlantic"], (1, 0))
    name3 = Name(["Zee", "Atlantic"], (0, 1))
    name4 = Name(["Zee", "Atlantic"])
    assert name1 > name2 and str(name1) < str(name2)
    assert name1 < name3
    assert name1 < name4

def test_name_repr() -> None:
    name = Name(["Niomi", "Turle"])
    name2 = eval(repr(name))
    print(name2)


import cv2
import time
from time import sleep
from djitellopy import tello
import KeyboardControl as kc

kc.init()
drone = tello.Tello()
drone.connect()
print(drone.get_battery())
drone.streamon()
x, y, z, r = 0, 0, 0, 0
global img

def getKeyboardInput():
    lr, fb, ud, yv = 0, 0, 0, 0
    speed = 45
    u = False
    global x, y, z, r

    if kc.getKey("LEFT"):
        lr = -speed
        x -= speed
    elif kc.getKey("RIGHT"):
        lr = speed
        x += speed
    if kc.getKey("UP"):
        # forward
        fb = speed
        y += speed
    elif kc.getKey("DOWN"):
        # backward
        fb = -speed
        y -= speed

    if kc.getKey("w"):
        ud = speed
        z += speed
    elif kc.getKey("s"):
        ud = -speed
        z -= speed

    if kc.getKey("a"):
        yv = speed
        r += speed
    elif kc.getKey("d"):
        yv = -speed
        r -= speed

    if kc.getKey("q"):   drone.land()
    if kc.getKey("e"):   drone.takeoff(); z += 80
    if kc.getKey("u"):
        drone.move_left(60)
        sleep(0.5)
        drone.move_forward(60)
        sleep(0.5)
        # sleep(10)

    if kc.getKey("z"):
        cv2.imwrite(f'Resources/Images/{time.time()}.jpg', img)
        sleep(0.3)

    sleep(0.25)
    return [lr, fb, ud, yv]

while True:
    vals = getKeyboardInput()
    drone.send_rc_control(vals[0], vals[1], vals[2], vals[3])
    img = drone.get_frame_read().frame
    print("Current height is: " + str(drone.get_height()))
    img = cv2.resize(img, (712, 712))
    print("Current distance difference is: " + "x :" + str(x) + "y :" + str(y) + "z :" + str(z))
    cv2.imshow("Image", img)
    cv2.waitKey(1)


# -*- coding: UTF-8 -*-
"""PyRamen Homework Starter."""

# @TODO: Import libraries
import csv
from pathlib import Path

menuFile = Path('.\Resources/menu_data.csv')
salesFile = Path('.\Resources/sales_data.csv')

# @TODO: Initialize list objects to hold our menu and sales data
menu = []
sales = []

# @TODO: Read in the menu data into the menu list

with open (menuFile , 'r') as menuData:
    csvRead = csv.reader(menuData, delimiter = ',')
    # skip header record
    next(menuData)
    for  menuRow in menuData:
        menuRowStripped=menuRow.rstrip()
        each=[]
        each=menuRowStripped.split(',')
        menu.append(each)

# @TODO: Read in the sales data into the sales list

with open (salesFile , 'r') as salesData:
    csvRead = csv.reader(salesData, delimiter = ',')
    # skip header record
    next(salesData)
    for  salesRow in salesData:
        salesRowStripped=salesRow.rstrip()
        each=[]
        each=salesRowStripped.split(',')
        sales.append(each)

# @TODO: Initialize dict object to hold our key-value pairs of items and metrics
report = {}

# Initialize a row counter variable
row_count = 0

# @TODO: Loop over every row in the sales list object
for each_sale in sales:
    menu_item=each_sale[-1]
    quantity=each_sale[-2]
    if menu_item not in report:
        report={ menu_item:{"01-count":0,"02-revenue":0,"03-cogs":0,"04-profit":0} }
    else:
        #print (f"{menu_item} already exist in report!")
        pass

print (report)

    # Line_Item_ID,Date,Credit_Card_Number,Quantity,Menu_Item
    # @TODO: Initialize sales data variables

    # @TODO:
    # If the item value not in the report, add it as a new entry with initialized metrics
    # Naming convention allows the keys to be ordered in logical fashion, count, revenue, cost, profit

    # @TODO: For every row in our sales data, loop over the menu records to determine a match

        # Item,Category,Description,Price,Cost
        # @TODO: Initialize menu data variables

        # @TODO: Calculate profit of each item in the menu data

        # @TODO: If the item value in our sales data is equal to the any of the items in the menu, then begin tracking metrics for that item

            # @TODO: Print out matching menu data

            # @TODO: Cumulatively add up the metrics for each item key

        # @TODO: Else, the sales item does not equal any fo the item in the menu data, therefore no match

    # @TODO: Increment the row counter by 1

# @TODO: Print total number of records in sales data

# @TODO: Write out report to a text file (won't appear on the command line output)


import unittest
from ultra.scenarios.common.social_vehicle_definitions import *

class SocialVehiclesTest(unittest.TestCase):
    def test_get_social_vehicles(self):
        all_types = ["default", "aggressive", "cautious", "blocker"]
        for behavior in all_types:
            vehicle = get_social_vehicle_behavior(behavior)
            self.assertTrue(vehicle is not None)
        vehicle = get_social_vehicle_behavior("Unknown")
        self.assertTrue(vehicle is None)

    def test_get_all_behaviors(self):
        all_types = ["default", "aggressive", "cautious", "blocker"]
        vehicles = get_all_behaviors()
        self.assertTrue(sorted(vehicles) == sorted(all_types))

    def test_get_social_vehicle_color(self):
        vehicles = [
            "default-2244061760535854552",
            "aggressive-224406176053585455",
            "cautious-224406176053585455",
            "blocker-224406176053585455",
            "stopwatcher_aggressive--2078631594661947501",
        ]
        for vid in vehicles:
            behavior_id = vid.split("-")[0]
            b_id, color = get_social_vehicle_color(vid)
            self.assertTrue(b_id == behavior_id)

        unknown_type = "dummy-None"
        b_id, color = get_social_vehicle_color(unknown_type)
        self.assertTrue(b_id, f" Unknown ***** {unknown_type} *******")


import torch
import torch.nn as nn
import torch.nn.functional as func
from torch.autograd import Function
import time
import pdb
import subprocess
import numpy as np
from configure import Config

config = Config()

class NCutsLoss(nn.Module):
    def __init__(self):
        super(NCutsLoss,self).__init__()
        self.gpu_list = []
        '''
        for i in range(torch.cuda.device_count()):
            self.gpu_list.append(torch.cuda.device(i))
# the ratio of the free space among all gpus
        self.gpu_room_list = []
        self.gpu_room_update()
        '''
    def gpu_room_update(self):
        self.gpu_room_list = []
        free_memory = get_gpu_memory_map()
        total_free = 0
        count_ratio = 0.0
        for _, value in free_memory.items():
            total_free+=value
        for dev in self.gpu_list:
            ratio = float(free_memory[dev])/total_free
            self.gpu_room_list.append(ratio)
            count_ratio += ratio
        if (count_ratio - 1 < 0):
            self.gpu_room_list[-1]+=1.0-count_ratio

    def forward(self, seg, weight):
#too many values to unpack
        K = torch.tensor(seg.size()[1])
        Kconst = K.float().cuda(seg.device)
        #pdb.set_trace()
        cropped_seg = torch.zeros(seg.size()[0],seg.size()[1],seg.size()[2],seg.size()[3],(config.radius-1)*2+1,(config.radius-1)*2+1).cuda(seg.device)
        padding_size = (config.radius-1,config.radius-1,config.radius-1,config.radius-1)
        padded_seg = torch.nn.functional.pad(seg,padding_size)
        for m in torch.arange((config.radius-1)*2+1,dtype=torch.long):
            for n in torch.arange((config.radius-1)*2+1,dtype=torch.long):
                cropped_seg[:,:,:,:,m,n].copy_(padded_seg[:,:,m:m+seg.size()[2],n:n+seg.size()[3]])
        multi1 = cropped_seg.mul(weight)
        multi2 = multi1.view(multi1.shape[0],multi1.shape[1],multi1.shape[2],multi1.shape[3],-1).sum(-1).mul(seg)
        multi3 = weight.view(weight.shape[0],weight.shape[1],weight.shape[2],weight.shape[3],-1).sum(-1).mul(seg)
        assocA = multi2.view(multi2.shape[0],multi2.shape[1],-1).sum(-1)
        assocV = multi3.view(multi3.shape[0],multi3.shape[1],-1).sum(-1)
        assoc = assocA.div(assocV).sum(-1)
        return Kconst - assoc
        '''
        for idx in torch.arange(N,dtype=torch.long):
            print("loss: "+str(idx))

            xi = x[idx,:,:,:].transpose(0,2).transpose(0,1)
            plain_x = xi.reshape(-1,3)
            self.gpu_room_update()
            capacity = 0
            chunks = []
            for ratio in self.gpu_room_list[:-1]:
                chunks.append(ratio*plain_x.size()[0])
                capacity += ratio*plain_x.size()[0]
            chunks.append(plain_x.size()[0]-capacity)
            gpu_num = len(self.gpu_list)
            xj = list(torch.cuda.comm.scatter(plain_x,self.gpu_list,chunks))
            xi = list(torch.cuda.comm.broadcast(xi,self.gpu_list))
            #print(torch.__version__)
            segj = list(torch.cuda.comm.scatter(seg.reshape(-1)[idx,:,:,:],self.gpu_list,chunks))
            segi = list(torch.cuda.comm.broadcast(seg[idx,:,:,:],self.gpu_list))
            for k in torch.arange(K,dtype=torch.long):
                for i in range(gpu_num):

                        #dist1 = (x[i,j]-x).norm(p=2,dim=2).pow(2).mul(seg[k])
                        #print(str(x[i,j].size())+"\t"+str(x.size())+"\t"+str(dist1.size())+"\t"+str(seg[k].size()))

                    dist1 = xi.add_(-1,xi[i,j]).norm(p=2,dim=2).pow_(2).mul_(segi[k]).sum().mul_(segi[k,i,j])
                assocA[i,j] = dist1
                assocV = torch.zeros(X,Y).cuda()

                for i in torch.arange(X,dtype=torch.long):
                    for j in torch.arange(Y,dtype=torch.long):
                        temp = (xi[i,j]-xi).norm(p=2,dim=2).pow(2)
                        assocV[i,j] = torch.mul(segi[k,i,j],temp.sum()).cuda()
                Nassoc[k] = assocA.sum().div(assocV.sum()).cuda()
            print(Kconst)
            print(Nassoc)
            loss += Kconst - Nassoc.sum()
        return loss
        '''

    def crop_seg(self,seg):
        cropped_seg = torch.zeros(seg.size()[0],seg.size()[1],seg.size()[2],seg.size()[3],(config.radius-1)*2+1,(config.radius-1)*2+1)
        padding_size = (config.radius,config.radius,config.radius,config.radius)
        padded_seg = torch.nn.functional.pad(seg,padding_size)
        for m in torch.arange((config.radius-1)*2+1,dtype=torch.long):
            for n in torch.arange((config.radius-1)*2+1,dtype=torch.long):
                cropped_seg[:,:,:,:,m,n].copy_(padded_seg[:,:,m:m+seg.size()[2],n:n+seg.size()[3]])
        return cropped_seg

def get_gpu_memory_map():
    """Get the current gpu usage.

    Returns
    -------
    usage: dict
        Keys are device ids as integers.
        Values are memory free as integers in MB.
    """
    result = subprocess.check_output(
        [
            'nvidia-smi', '--query-gpu=memory.free',
            '--format=csv,nounits,noheader'
        ], encoding='utf-8')
    # Convert lines into a dictionary
    gpu_memory = [int(x) for x in result.strip().split('\n')]
    gpu_memory_map = dict(zip(range(len(gpu_memory)), gpu_memory))
    return gpu_memory_map


# SPDX-License-Identifier: Apache-2.0
from torch.optim import lr_scheduler
from warmup_scheduler import GradualWarmupScheduler

class StepLRScheduler:
    def __init__(
        self,
        optim,
        base_lr,
        step_size,
        gamma,
        warmup_steps=0,
        steps_per_epoch=None,
        **kargs
    ):
        super(StepLRScheduler, self).__init__()
        if steps_per_epoch and steps_per_epoch > 0:
            step_size = step_size * steps_per_epoch
            warmup_steps = warmup_steps * steps_per_epoch
        self.optim = optim
        self.base_lr = base_lr
        self.step_size = step_size
        self.gamma = gamma
        self.scheduler = lr_scheduler.StepLR(optim, step_size=step_size, gamma=gamma)
        if warmup_steps > 0:
            self.scheduler = GradualWarmupScheduler(
                optim, 1.0, warmup_steps, self.scheduler
            )
            self.optim.step()

    def step(self):
        self.scheduler.step()

    def get_last_lr(self):
        return self.optim.param_groups[0]["lr"]

class CosineAnnealingLRScheduler:
    def __init__(
        self,
        optim,
        base_lr,
        steps_per_epoch,
        total_epochs,
        warmup_steps=0,
        **kargs
    ):
        super(CosineAnnealingLRScheduler, self).__init__()
        if steps_per_epoch and steps_per_epoch > 0:
            warmup_steps = warmup_steps * steps_per_epoch
        self.optim = optim
        self.base_lr = base_lr
        t_max = total_epochs * steps_per_epoch
        self.scheduler = lr_scheduler.CosineAnnealingLR(optim, T_max=t_max)
        if warmup_steps > 0:
            self.scheduler = GradualWarmupScheduler(
                optim, 1.0, warmup_steps, self.scheduler
            )
            self.optim.step()

    def step(self):
        self.scheduler.step()

    def get_last_lr(self):
        return self.optim.param_groups[0]["lr"]


# capture.py

# Script used to capture image and save it in img folder which is then used to train the model

import time

import cv2
import numpy as np

from utilityfunctions import utils
from utilityfunctions import imgproc as imp

def saveImage(image, gesture):

    # Define image path and filename
    folder = utils.imgPathsRaw[gesture]
    name = utils.gestureTxt[gesture] + '-' + time.strftime('%Y%m%d-%H%M%S')
    extension = '.png'

    print("Saving " + name + extension + " - Accept ([y]/n)?")

    # Write gesture name to image and show for a few seconds
    imgTxt = image.copy()
    font = cv2.FONT_HERSHEY_COMPLEX
    cv2.putText(imgTxt, utils.gestureTxt[gesture], (10,25), font, 1, (0, 0, 255))
    cv2.imshow('Camera', imgTxt)
    key = cv2.waitKey(2000)
    if key not in [110, 120]:
        # Key is not x or n. Save image
        cv2.imwrite(folder + name + extension, image)
        print("Saved ({}x{})".format(image.shape[1], image.shape[0]))
    else:
        print("Save cancelled")

try:
    # Create camera object with pre-defined settings
    cameraobject = utils.cameraSetup()

    # Initialize variable to stop while loop execution
    stop = False

    # Initialize opencv GUI window (resizeable)
    cv2.namedWindow('Camera', cv2.WINDOW_AUTOSIZE)

    # Print instructions
    print("\nImage capture mode")
    print("Press the following keys to capture:")
    print("Rock gesture: r")
    print("Paper gesture: p")
    print("Scisors gesture: s or c")
    print("Press ESC or q to quit capture mode\n")

    # Main loop
    while not stop:
        # Capture image from camera
        image = cameraobject.getOpenCVImage()

        # Crop image
        image = imp.crop(image)

        # Add framerate to copy of image
        rotatedImage = imp.fastRotate(image)
        txtPos = (5, rotatedImage.shape[0] - 10)
        cameraobject.addFrameRateText(rotatedImage, txtPos, bgr=(0,0,255))

        # Display image
        cv2.imshow('Camera', rotatedImage)

        # Wait for key press
        key = cv2.waitKey(1)
        if key in [27, 113]:
            # Escape or "Q" key pressed; Stop.
            stop = True
        else:
            gesture = None
            if key == 114:
                # "R" key pressed (Rock)
                gesture = utils.ROCK
            elif key == 112:
                # "P" key pressed (Paper)
                gesture = utils.PAPER
            elif key in [115, 99]:
                # "S" or "C" key pressed (Scisors)
                gesture = utils.SCISSORS
            if gesture is not None:
                saveImage(image, gesture)

finally:
    cv2.destroyAllWindows()
    cameraobject.close()


#!/usr/bin/env python
import re
import argparse
import gzip

def get_args():
    parser = argparse.ArgumentParser(description="This program will take two paired-end fastq files and will keep only unique reads based on the UMI")
    parser.add_argument("-r1", "--fastqr1", help="Input the filename for Read 1 (fastq)", type=str, required=True)
    parser.add_argument("-r2", "--fastqr2", help="Input the filename for Read 2 (fastq)", type=str, required=True)
    parser.add_argument("-or1", "--outputr1", help="Input the output filename for Read 1 (fastq)", type=str, required=True)
    parser.add_argument("-or2", "--outputr2", help="Input the output filename for Read 2 (fastq)", type=str, required=True)
    return parser.parse_args()

args = get_args()
fast = args.fastqr1
fast2 = args.fastqr2
out_r1_file = args.outputr1
out_r2_file = args.outputr2

#Variables
existing_umi=set()
existing_probes={}

#Functions
def read_file(f:str) -> list:
    '''This function will take in a fastq file and return a list containing the data of a record'''
    head = f.readline().strip()
    seq = f.readline().strip()
    sep = f.readline().strip()
    qsc = f.readline().strip()
    if head == "":
        return 0
    return [head,seq,sep,qsc]

#Opening files
f_or1 = open(out_r1_file, "w")
f_or2 = open(out_r2_file, "w")
report = "umi_report.txt"
probes_set = set()

with open("probes.csv","r") as fp:
    for line in fp:
        probe = line.strip()
        probes_set.add(probe)

#Actual Code
n=0
with gzip.open(fast,"rt") as fhr1, gzip.open(fast2,"rt") as fhr2:
    while True:
        R1=read_file(fhr1)
        R2=read_file(fhr2)
        #If the read 1 encounters an empty line it will stop reading and break the loop
        if R1 == 0:
            break
        n+=1
        #Changing variable name to make it easier to follow
        head_r1,seq_r1,sep,qsc_r1 = R1
        head_r2,seq_r2,sep,qsc_r2 = R2
        #Obtain global UMI
        umi = head_r1.split(":")[7].split()[0]
        if umi not in existing_umi:
            existing_umi.add(umi)
            f_or1.write("\n".join(R1)+"\n")
            f_or2.write("\n".join(R2)+"\n")
            for thing in probes_set:
                if thing in seq_r1:
                    existing_probes[thing] = 1

with open(report,"w") as fr:
    fr.write("Stats from Getting Unique reads\n\n")
    fr.write("The Ammount of reads is: " + str(n) + "\n\n")
    for key in existing_probes:
        fr.write(str(key) + "\t" + str(existing_probes[key]) + "\t" + str(round(existing_probes[key]/n * 100, 2)) + "%\n")
    fr.write("The Ammount unique reads is: " + str(len(existing_umi)) + "\n\n")

f_or1.close()
f_or2.close()


from typing import List
from dataclasses import dataclass

from app.database.db import Database
from app.database.db_operations import DatabaseOperations

@dataclass
class InvoiceDatabaseOperations(DatabaseOperations):
    def __init__(self) -> None:
        self.queries_data = self.get_queries_data()

    def get_details_of_paid_orders_without_invoice(self) -> List:
        SQL_query: str = self.queries_data["get_details_of_paid_orders_without_invoice"]
        with Database(function_name="Get details of paid orders without invoice") as database:
            database.cursor.execute(SQL_query)
            database_result: List = database.cursor.fetchall()

        orders_list = []
        for database_order_data in database_result:
            order_details = []
            order_details.append(database_order_data)
            orders_list.append(order_details)
        return orders_list

    def get_customer_details(self, customer_id: int):
        SQL_query: str = self.queries_data["get_customer_details"].replace("{customer_id}", str(customer_id))
        with Database(function_name="Get customer details") as database:
            database.cursor.execute(SQL_query)
            result: List = database.cursor.fetchall()[0]
        return result

    def get_items_details(self, order_id: int):
        SQL_query: str = self.queries_data["get_items_details"].replace("{order_id}", str(order_id))
        with Database(function_name="Get items details") as database:
            database.cursor.execute(SQL_query)
            result: List = database.cursor.fetchall()
        return result

    def add_invoice_id(self, order_id: int, invoice_id: int):
        SQL_query: str = self.queries_data["add_invoice_id"].replace("{order_id}", str(order_id))
        SQL_query = SQL_query.replace("{invoice_id}", str(invoice_id))
        with Database(function_name="Add invoice ID") as database:
            database.cursor.execute(SQL_query)
            database.commit()