"""
Route generator.
"""
import openmdao.api as om
import numpy as np
from fastuav.utils.constants import *
from fastuav.models.performance.mission.phase_builder import PhaseBuilder

class RouteBuilder(om.Group):
    """
    This class builds a route from a provided definition.
    If the mission is not a sizing one, then the takeoff weight is recalculated from the route payload.
    Else, the takeoff weight is taken as the maximum takeoff weight.
    """

    def initialize(self):
        self.options.declare("mission_name", default=None, types=str)
        self.options.declare("is_sizing", default=False, types=bool)
        self.options.declare("route_name", default=None, types=str)
        self.options.declare("route_definition", default=None, types=dict)

    def setup(self):
        mission_name = self.options["mission_name"]
        is_sizing = self.options["is_sizing"]
        route_name = self.options["route_name"]
        route_definition = self.options["route_definition"]
        phases_dict = {}

        if not is_sizing:
            self.add_subsystem("compute_tow",
                               ComputeTOW(mission_name=mission_name,
                                          route_name=route_name),
                               promotes=["*"])

        for phase_definition in route_definition.values():
            phase_id = phase_definition[PHASE_ID_TAG]
            phase_name, propulsion_id = self.get_part_attributes(phase_id)
            if phase_name is not None:
                phases_dict[phase_name] = propulsion_id
                self.add_subsystem(phase_id,
                                   PhaseBuilder(mission_name=mission_name,
                                                is_sizing=is_sizing,
                                                route_name=route_name,
                                                phase_name=phase_name,
                                                propulsion_id=propulsion_id),
                                   promotes=["*"])
        self.add_subsystem("route",
                           RouteComponent(mission_name=mission_name,
                                          route_name=route_name,
                                          phases_dict=phases_dict,
                                          propulsion_id_list=RouteBuilder.get_propulsion_id_list(route_definition)),
                           promotes=["*"])

    @staticmethod
    def get_part_attributes(part_id):
        """
        Gets the phase name (e.g. "climb") corresponding the to phase identifier (e.g. "vertical_climb"),
        and also returns the propulsion identifier (e.g. "multirotor" or "fixedwing") used to complete this phase.
        Note that take-off is not taken into account when building the mission profile, as its duration is neglected.
        """
        if part_id == VERTICAL_CLIMB_TAG:
            part_name = CLIMB_TAG
            propulsion_id = MR_PROPULSION
        elif part_id == FW_CLIMB_TAG:
            part_name = CLIMB_TAG
            propulsion_id = FW_PROPULSION
        elif part_id == MR_CRUISE_TAG:
            part_name = CRUISE_TAG
            propulsion_id = MR_PROPULSION
        elif part_id == FW_CRUISE_TAG:
            part_name = CRUISE_TAG
            propulsion_id = FW_PROPULSION
        elif part_id == HOVER_TAG:
            part_name = HOVER_TAG
            propulsion_id = MR_PROPULSION
        else:
            part_name = None
            propulsion_id = None
        return part_name, propulsion_id

    @staticmethod
    def get_propulsion_id_list(route_definition):
        """
        Gets the list of propulsion identifiers (e.g. "multirotor", "fixedwing") used to complete the route.
        """
        propulsion_id_list = []
        for phase_definition in route_definition.values():
            phase_id = phase_definition[PHASE_ID_TAG]
            _, propulsion_id = RouteBuilder.get_part_attributes(phase_id)
            if propulsion_id is not None:
                propulsion_id_list.append(propulsion_id)
        return set(propulsion_id_list)

class ComputeTOW(om.ExplicitComponent):
    """
    Computes Take Off Weight (TOW) from Maximum Take Off Weight (MTOW), design paylaod and route payload
    """

    def initialize(self):
        self.options.declare("mission_name", default=None, types=str)
        self.options.declare("route_name", default=None, types=str)

    def setup(self):
        mission_name = self.options["mission_name"]
        route_name = self.options["route_name"]
        self.add_input("data:weight:mtow", val=np.nan, units="kg")
        self.add_input("mission:sizing:payload:mass", val=np.nan, units="kg")
        self.add_input("mission:%s:%s:payload:mass" % (mission_name, route_name), val=np.nan, units="kg")
        self.add_output("mission:%s:%s:tow" % (mission_name, route_name), units="kg")

    def setup_partials(self):
        # Finite difference all partials.
        self.declare_partials("*", "*", method="fd")

    def compute(self, inputs, outputs):
        mission_name = self.options["mission_name"]
        route_name = self.options["route_name"]
        mtow = inputs["data:weight:mtow"]
        m_pay_design = inputs["mission:sizing:payload:mass"]
        m_pay_mission = inputs["mission:%s:%s:payload:mass" % (mission_name, route_name)]

        tow = mtow - m_pay_design + m_pay_mission

        outputs["mission:%s:%s:tow" % (mission_name, route_name)] = tow

class RouteComponent(om.ExplicitComponent):
    """
    This component computes the route parameters (energy and duration) from the phases its made of.
    """

    def initialize(self):
        self.options.declare("mission_name", default=None, types=str)
        self.options.declare("route_name", default=None, types=str)
        self.options.declare("phases_dict", default={}, types=dict)
        self.options.declare("propulsion_id_list", default=None, types=set)

    def setup(self):
        mission_name = self.options["mission_name"]
        route_name = self.options["route_name"]
        phases_dict = self.options["phases_dict"]
        propulsion_id_list = self.options["propulsion_id_list"]

        for phase_name in phases_dict.keys():
            self.add_input("mission:%s:%s:%s:energy" % (mission_name, route_name, phase_name),
                           val=np.nan,
                           units="kJ")
            self.add_input("mission:%s:%s:%s:duration" % (mission_name, route_name, phase_name),
                           val=np.nan,
                           units="min")

        for propulsion_id in propulsion_id_list:
            self.add_output("mission:%s:%s:energy:%s" % (mission_name, route_name, propulsion_id), units="kJ")
            self.add_output("mission:%s:%s:duration:%s" % (mission_name, route_name, propulsion_id), units="min")

        self.add_output("mission:%s:%s:energy" % (mission_name, route_name), units="kJ")
        self.add_output("mission:%s:%s:duration" % (mission_name, route_name), units="min")

    def setup_partials(self):
        self.declare_partials("*", "*", method="fd")

    def compute(self, inputs, outputs):
        mission_name = self.options["mission_name"]
        route_name = self.options["route_name"]
        phases_dict = self.options["phases_dict"]
        propulsion_id_list = self.options["propulsion_id_list"]

        # Initialize route parameters
        E_route = .0  # [kJ] energy consumption on whole route
        t_route = .0  # [min] duration of whole route

        # Loop through propulsion systems to associate energy consumption to corresponding battery
        for propulsion_id in propulsion_id_list:
            E_route_prop_id = sum(
                inputs["mission:%s:%s:%s:energy" % (mission_name, route_name, phase_name)] for phase_name in phases_dict
                if phases_dict[phase_name] == propulsion_id)
            t_route_prop_id = sum(
                inputs["mission:%s:%s:%s:duration" % (mission_name, route_name, phase_name)] for phase_name in phases_dict
                if phases_dict[phase_name] == propulsion_id)
            outputs["mission:%s:%s:energy:%s" % (mission_name, route_name, propulsion_id)] = E_route_prop_id
            outputs["mission:%s:%s:duration:%s" % (mission_name, route_name, propulsion_id)] = t_route_prop_id

            # Add to route
            E_route += E_route_prop_id
            t_route += t_route_prop_id

        outputs["mission:%s:%s:energy" % (mission_name, route_name)] = E_route
        outputs["mission:%s:%s:duration" % (mission_name, route_name)] = t_route


#!/usr/bin/python
#
# The script converts ovs ufid to tc cookie.
#
# ./convert-ovs-ufid-to-tc-cookie.py [ufid]
#

from __future__ import print_function
import sys
import os

if len(sys.argv) < 2:
    print("Usage: %s [ufid]" % os.path.basename(sys.argv[0]))
    sys.exit(1)

ufid = sys.argv[1]

try:
    sp = ufid.split('-')
    w3 = sp[4][:4]
    w4 = sp[3]
    w5 = sp[4][-8:]
    sp[3] = w3
    sp[4] = w4
    sp.append(w5)
except IndexError:
    print("ERROR: Invalid ufid ?")
    sys.exit(1)

# Replace w1 and w2
tmp = sp[1]
sp[1] = sp[2]
sp[2] = tmp

cookie = []
for i in sp:
    tmp = ""
    for j in range(int(len(i) / 2)):
        pos = j*2
        m = i[pos:pos+2]
        tmp = m + tmp
    cookie.append(tmp)

print(''.join(cookie))


numeros = ('Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze', 'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove', 'Vinte')
ink = int(input('Digite um número entre 1 e 20: '))
if ink in range(1, 21) and ink <= 20:
    print(f'{numeros[ink-1]}')
if int not in range(1, 21):
    while True:
        ink = int(input('Número inválido, tente novamente. Digite um número entre 1 e 20:'))
        if ink in range(1, 21) and ink <= 20:
            print(f'{numeros[ink-1]}')
            break


import datetime
import io
import pathlib
import pickle
import re
import uuid

# import gym
import numpy as np
import tensorflow as tf
import tensorflow.compat.v1 as tf1
import tensorflow_probability as tfp
from tensorflow.keras.mixed_precision import experimental as prec
from tensorflow_probability import distributions as tfd

def count_episodes(directory):
    filenames = directory.glob("*.npz")
    lengths = [int(n.stem.rsplit("-", 1)[-1]) - 1 for n in filenames]
    episodes, steps = len(lengths), sum(lengths)
    return episodes, steps

def graph_summary(writer, fn, *args):
    step = tf.summary.experimental.get_step()

    def inner(*args):
        tf.summary.experimental.set_step(step)
        with writer.as_default():
            fn(*args)

    return tf.numpy_function(inner, args, [])

# def video_summary(name, video, step=None, fps=20):
#     #   name = name if isinstance(name, str) else name.decode('utf-8')
#     name = str(name)

#     if np.issubdtype(video.dtype, np.floating):
#         video = np.clip(255 * video, 0, 255).astype(np.uint8)
#     print("video.shape:", video.shape)
#     B, T, H, W, C = video.shape
#     try:
#         # frames = video.transpose((1, 2, 0, 3, 4)).reshape((T, H, B * W, C))
#         frames = video
#         summary = tf1.Summary()
#         image = tf1.Summary.Image(height=H, width=W, colorspace=C)
#         image.encoded_image_string = encode_gif(frames, fps)
#         summary.value.add(tag=name + "/gif", image=image)
#         tf.summary.experimental.write_raw_pb(summary.SerializeToString(), step)
#     except (IOError, OSError) as e:
#         print("GIF summaries require ffmpeg in $PATH.", e)
#         frames = video.transpose((0, 2, 1, 3, 4)).reshape((1, B * H, T * W, C))
#         tf.summary.image(name + "/grid", frames, step)

def video_summary(name, video, step=None, fps=20):
    # print("name:", name)
    # name = name if isinstance(name, str) else name.decode("utf-8")
    name = str(name)
    if np.issubdtype(video.dtype, np.floating):
        video = np.clip(255 * video, 0, 255).astype(np.uint8)
    B, T, H, W, C = video.shape
    try:
        frames = video.transpose((1, 2, 0, 3, 4)).reshape((T, H, B * W, C))
        summary = tf1.Summary()
        image = tf1.Summary.Image(height=B * H, width=T * W, colorspace=C)
        image.encoded_image_string = encode_gif(frames, fps)
        summary.value.add(tag=name + "/gif", image=image)
        tf.summary.experimental.write_raw_pb(summary.SerializeToString(), step)
    except (IOError, OSError) as e:
        print("GIF summaries require ffmpeg in $PATH.", e)
        frames = video.transpose((0, 2, 1, 3, 4)).reshape((1, B * H, T * W, C))
        tf.summary.image(name + "/grid", frames, step)

def encode_gif(frames, fps):
    from subprocess import Popen, PIPE

    h, w, c = frames[0].shape
    pxfmt = {1: "gray", 3: "rgb24"}[c]
    cmd = " ".join(
        [
            f"ffmpeg -y -f rawvideo -vcodec rawvideo",
            f"-r {fps:.02f} -s {w}x{h} -pix_fmt {pxfmt} -i - -filter_complex",
            f"[0:v]split[x][z];[z]palettegen[y];[x]fifo[x];[x][y]paletteuse",
            f"-r {fps:.02f} -f gif -",
        ]
    )
    proc = Popen(cmd.split(" "), stdin=PIPE, stdout=PIPE, stderr=PIPE)
    for image in frames:
        proc.stdin.write(image.tostring())
    out, err = proc.communicate()
    if proc.returncode:
        raise IOError("\n".join([" ".join(cmd), err.decode("utf8")]))
    del proc
    return out

class TanhBijector(tfp.bijectors.Bijector):
    def __init__(self, validate_args=False, name="tanh"):
        super().__init__(
            forward_min_event_ndims=0, validate_args=validate_args, name=name
        )

    def _forward(self, x):
        return tf.nn.tanh(x)

    def _inverse(self, y):
        dtype = y.dtype
        y = tf.cast(y, tf.float32)
        y = tf.where(
            tf.less_equal(tf.abs(y), 1.0),
            tf.clip_by_value(y, -0.99999997, 0.99999997),
            y,
        )
        y = tf.atanh(y)
        y = tf.cast(y, dtype)
        return y

    def _forward_log_det_jacobian(self, x):
        log2 = tf.math.log(tf.constant(2.0, dtype=x.dtype))
        return 2.0 * (log2 - x - tf.nn.softplus(-2.0 * x))

class SampleDist:
    def __init__(self, dist, samples=100):
        self._dist = dist
        self._samples = samples

    @property
    def name(self):
        return "SampleDist"

    def __getattr__(self, name):
        return getattr(self._dist, name)

    def mean(self):
        samples = self._dist.sample(self._samples)
        return tf.reduce_mean(samples, 0)

    def mode(self):
        sample = self._dist.sample(self._samples)
        logprob = self._dist.log_prob(sample)
        return tf.gather(sample, tf.argmax(logprob))[0]

    def entropy(self):
        sample = self._dist.sample(self._samples)
        logprob = self.log_prob(sample)
        return -tf.reduce_mean(logprob, 0)

class OneHotDist:
    def __init__(self, logits=None, probs=None):
        self._dist = tfd.Categorical(logits=logits, probs=probs)
        self._num_classes = self.mean().shape[-1]
        self._dtype = prec.global_policy().compute_dtype

    @property
    def name(self):
        return "OneHotDist"

    def __getattr__(self, name):
        return getattr(self._dist, name)

    def prob(self, events):
        indices = tf.argmax(events, axis=-1)
        return self._dist.prob(indices)

    def log_prob(self, events):
        indices = tf.argmax(events, axis=-1)
        return self._dist.log_prob(indices)

    def mean(self):
        return self._dist.probs_parameter()

    def mode(self):
        return self._one_hot(self._dist.mode())

    def sample(self, amount=None):
        amount = [amount] if amount else []
        indices = self._dist.sample(*amount)
        sample = self._one_hot(indices)
        probs = self._dist.probs_parameter()
        sample += tf.cast(probs - tf.stop_gradient(probs), self._dtype)
        return sample

    def _one_hot(self, indices):
        return tf.one_hot(indices, self._num_classes, dtype=self._dtype)


import pandas as pd
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import scale

letters = pd.read_csv('G:/Software/Machine learning/1/18. Support Vector Machine (SVM)/SVM/letter-recognition.csv')

letters.columns = ['letter', 'xbox', 'ybox', 'width', 'height', 'onpix', 'xbar',
       'ybar', 'x2bar', 'y2bar', 'xybar', 'x2ybar', 'xy2bar', 'xedge',
       'xedgey', 'yedge', 'yedgex']

order = list(np.sort(letters['letter'].unique()))
print(order)

letter_means = letters.groupby('letter').mean()
letter_means.head()

sns.countplot(x = 'letter' , data = letters)

round(letters.drop('letter', axis=1).mean(), 2)

plt.figure(figsize=(16, 8))
sns.barplot(x='letter', y='xbox',  data=letters, order=order)

plt.figure(figsize=(18, 10))
sns.heatmap(letter_means)

round(letters.drop('letter', axis=1).mean(), 2)

X = letters.drop("letter", axis = 1)
y = letters['letter']

X_scaled = scale(X)

X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size = 0.3, random_state = 101)

model_linear = SVC(kernel='linear')
model_linear.fit(X_train, y_train)
y_pred = model_linear.predict(X_test)

print("accuracy:", metrics.accuracy_score(y_true = y_test, y_pred = y_pred), "\n")

mat = metrics.confusion_matrix(y_true = y_test, y_pred = y_pred)
print(mat)

non_linear_model = SVC(kernel='rbf')
non_linear_model.fit(X_train, y_train)
y_pred = non_linear_model.predict(X_test)
print("accuracy:", metrics.accuracy_score(y_true=y_test, y_pred=y_pred), "\n")

print(metrics.confusion_matrix(y_true=y_test, y_pred=y_pred))

non_linear_model = SVC(kernel='poly')
non_linear_model.fit(X_train, y_train)
y_pred = non_linear_model.predict(X_test)
print("accuracy:", metrics.accuracy_score(y_true=y_test, y_pred=y_pred), "\n")

print(metrics.confusion_matrix(y_true=y_test, y_pred=y_pred))

folds = KFold(n_splits = 5, shuffle = True, random_state = 101)

hyper_params = [ {'gamma': [1e-2, 1e-3, 1e-4],'C': [1, 10, 100, 1000]}]

model = SVC(kernel="rbf")

model_cv = GridSearchCV(estimator = model, param_grid = hyper_params, scoring= 'accuracy', cv = folds,  verbose = 1,return_train_score=True)

model_cv.fit(X_train, y_train)

cv_results = pd.DataFrame(model_cv.cv_results_)
cv_results

cv_results['param_C'] = cv_results['param_C'].astype('int')

# # plotting
plt.figure(figsize=(16,6))

# subplot 1/3
plt.subplot(131)
gamma_01 = cv_results[cv_results['param_gamma']==0.01]

plt.plot(gamma_01["param_C"], gamma_01["mean_test_score"])
plt.plot(gamma_01["param_C"], gamma_01["mean_train_score"])
plt.xlabel('C')
plt.ylabel('Accuracy')
plt.title("Gamma=0.01")
plt.ylim([0.60, 1])
plt.legend(['test accuracy', 'train accuracy'], loc='upper left')
plt.xscale('log')

# subplot 2/3
plt.subplot(132)
gamma_001 = cv_results[cv_results['param_gamma']==0.001]

plt.plot(gamma_001["param_C"], gamma_001["mean_test_score"])
plt.plot(gamma_001["param_C"], gamma_001["mean_train_score"])
plt.xlabel('C')
plt.ylabel('Accuracy')
plt.title("Gamma=0.001")
plt.ylim([0.60, 1])
plt.legend(['test accuracy', 'train accuracy'], loc='upper left')
plt.xscale('log')

# subplot 3/3
plt.subplot(133)
gamma_0001 = cv_results[cv_results['param_gamma']==0.0001]

plt.plot(gamma_0001["param_C"], gamma_0001["mean_test_score"])
plt.plot(gamma_0001["param_C"], gamma_0001["mean_train_score"])
plt.xlabel('C')
plt.ylabel('Accuracy')
plt.title("Gamma=0.0001")
plt.ylim([0.60, 1])
plt.legend(['test accuracy', 'train accuracy'], loc='upper left')
plt.xscale('log')


import os, sys
import pygame as pg
from random import choice, randrange

class Symbol:
    def __init__(self, x, y, speed):
        self.x, self.y = x, y
        self.speed = speed
        self.value = choice(green_katakana)
        self.interval = randrange(5, 30)

    def draw(self, color):
        # randomize the sybol
        frames = pg.time.get_ticks()
        if not frames % self.interval:
            self.value = choice(green_katakana if color == 'green' else lightgreen_katakana)

        # fall effect of the symbol
        self.y = self.y + self.speed if self.y < HEIGHT else -FONT_SIZE
        surface.blit(self.value, (self.x, self.y))

class SymbolColumn:
    def __init__(self, x, y):
        self.column_height = randrange(8, 24)
        self.speed = randrange(2, 5)
        # colum of symbol
        self.symbols = [Symbol(x, i, self.speed) for i in range(y, y - FONT_SIZE * self.column_height, - FONT_SIZE)]

    def draw(self):
        # different colors
        [symbol.draw('green') if i else symbol.draw('lightgreen') for i, symbol in enumerate(self.symbols)]

# old method for center screen
os.environ['SDL_VIDEO_CENTERED'] = '1'
RES = WIDTH, HEIGHT = 1280, 720
FONT_SIZE = 40
alpha_value = 0

# pygame setup ======================================
pg.init()
screen = pg.display.set_mode(RES)
clock = pg.time.Clock()
# blur effect
surface = pg.Surface(RES)
surface.set_alpha(alpha_value)

# katakana from hexadecimal values
katakana = [chr(int('0x30a0', 16) + i) for i in range(96)]
# load font
font = pg.font.Font('font/MS Mincho.ttf', FONT_SIZE, bold= True)
green_katakana = [font.render(char, True, (40, randrange(160, 256), 40)) for char in katakana]
# font color
lightgreen_katakana = [font.render(char, True, pg.Color('lightgreen')) for char in katakana]

# Instance of class
symbol_columns = [SymbolColumn(x, randrange(-HEIGHT, 0)) for x in range(0, WIDTH, FONT_SIZE)]

while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()

    # Draw ------------------------
    screen.blit(surface, (0, 0))
    surface.fill(pg.Color('black'))

    # many colums
    [symbol_column.draw() for symbol_column in symbol_columns]

    if not pg.time.get_ticks() % 20 and alpha_value < 170:
        alpha_value += 6
        surface.set_alpha(alpha_value)

    # pygame setup ------------------------
    pg.display.flip()
    clock.tick(60)
    pg.display.set_caption(f'FPS: {clock.get_fps() :.0f}')


import tkinter as tk
from tkinter import *
import threading
import numpy as np

arr = [[-1,-3, -4, 0],[3, 7, -8, 3], [1, -6, 2, 5],[-8, -4, -1, -1]]
d = [-3, 30, -90, 12]

def funcLU(a):
    U = [[0 for i in range(len(a))] for i in range(len(a))]
    for i in range(len(a)):
        for j in range(len(a)):
            U[i][j] = a[i][j]
    L = [[0 for i in range(len(a))] for i in range(len(a))]

    for i in range(len(a)):
        for k in range(i+1,len(a)):
            L[k][i] = U[k][i]/U[i][i]
            for j in range(i,len(a)):
                U[k][j] = U[k][j] - L[k][i] * U[i][j]
        L[i][i] = 1

    return L, U

def solve(L, U, d):
    x, y = [0 for i in range(len(L))], [0 for i in range(len(U))]

    y[0] = d[0]
    for i in range(1, len(L)):
        y[i] = d[i]
        for j in range(i):
            y[i]-=L[i][j]*y[j]

    x[len(U)-1] = (y[len(U)-1]/U[len(U)-1][len(U)-1])
    for i in range(len(U)-2, -1, -1):
        x[i] = y[i]
        for j in range(len(L)-1, i, -1):
            x[i]-=U[i][j]*x[j]
        x[i] = (x[i]/U[i][i])
    return x

def det(a):
    L, U = funcLU(a)
    d = 1
    for i in range(len(U)):
        d*=U[i][i]
    return d

def obr(a):
    b = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]

    for k in range(len(a)):
        if abs(a[k][k]):
            for i in range(k+1, len(a)):
                if abs(a[i][k]) > abs(a[k][k]):
                    for j in range(k, len(a)):
                        a[k][j], a[i][j] = a[i][j], a[k][j]
                        b[k][j], b[i][j] = b[i][j], b[k][j]
                    b[k], b[i] = b[i], b[k]
                    break
        p = a[k][k]
        for j in range(k, len(a)):
            a[k][j] /= p
            b[k][j] /= p
        for i in range(len(a)):
            if i == k or a[i][k] == 0: continue
            f = a[i][k]
            for j in range(k, len(a)):
                a[i][j] -= f * a[k][j]
                b[i][j] -= f * b[k][j]

    return b

def make_window():
    window = tk.Tk()
    window.title("Окно управления")
    window.geometry('320x320')
    text_var = []
    entries = []

    def ButtonCall1():
        detr = det(arr)
        print("Определитель:", detr)
        L, U = funcLU(arr)
        L1 = np.array(L)
        print("L-матрица")
        print(L1)
        U1 = np.array(U)
        print("U-матрица")
        print(U1)
        x = solve(L, U, d)
        a = [[0 for i in range(len(arr))] for i in range(len(arr))]
        for i in range(len(arr)):
            for j in range(len(arr)):
                a[i][j] = arr[i][j]
        A_1 = np.array(obr(a))
        print("Обратная-матрица:")
        print(A_1)
        print("Ответ: x =", x)

    button = tk.Button(window, text="14 Вариант", command=ButtonCall1)
    button.place(x=130, y=200)

    def get_mat():
        own_arr = []
        own_d = []
        for i in range(len(arr)):
            own_arr.append([])
            for j in range(len(arr)):
                own_arr[i].append(int(text_var[i][j].get()))
        for i in range(len(arr)):
            own_d.append(int(d_var[i].get()))
        print(own_arr)
        print(d)
        detr = det(own_arr)
        print("Определитель:", detr)
        L, U = funcLU(own_arr)
        L1 = np.array(L)
        print("L-матрица")
        print(L1)
        U1 = np.array(U)
        print("U-матрица")
        print(U1)
        x = solve(L, U, own_d)
        a = [[0 for i in range(len(own_arr))] for i in range(len(own_arr))]
        for i in range(len(own_arr)):
            for j in range(len(own_arr)):
                a[i][j] = own_arr[i][j]
        A_1 = np.array(obr(a))
        print("Обратная-матрица:")
        print(A_1)
        print("Ответ: x =", x)
        own_arr = []
        own_d = []
        print(x)

    x2, y2 = 0, 0
    for i in range(len(arr)):
        text_var.append([])
        entries.append([])
        for j in range(len(arr)):
            text_var[i].append(StringVar())
            entries[i].append(Entry(window, textvariable=text_var[i][j],width=3))
            entries[i][j].place(x=60 + x2, y=50 + y2)
            x2 += 30

        y2 += 30
        x2 = 0

    y2 = 0
    d_var = []
    d_var1 = []
    for i in range(len(arr)):
        d_var.append(StringVar())
        d_var1.append(Entry(window, textvariable=d_var[i],width=3))
        d_var1[i].place(x = 240, y=50 + y2)
        y2 += 30

    button = tk.Button(window, text="Собственные условия", command=get_mat)
    button.place(x=100, y=240)

    tk.mainloop()

def main():
    t1 = threading.Thread(target=make_window)
    t1.start()

main()


import time
import requests
import schedule
api_key = 'API_KEY'

def job():
    msg = 'Go workout!'
    requests.post('https://api.mynotifier.app', {
        "apiKey": api_key,  # This is your own private key
        "message": msg,  # Could be anything
        "description": "You need to work!",  # Optional
        "body": "",  # Optional
        "type": "info",  # info, error, warning or success
        "project": ""  # Optional. Project ids can be found in project tab <-
    })
    print("Send message")

schedule.every().day.at("7:30").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)


#!/usr/bin/env python3
"""
Consuming API SpaceX
"""

import requests

if __name__ == '__main__':
    url = 'https://api.spacexdata.com/v4'
    data = requests.get(url + '/launches/upcoming').json()

    date_launch = [elem['date_unix'] for elem in data]

    index = date_launch.index(min(date_launch))

    launch = data[index]

    id_launch = launch['id']
    id_rocket = launch['rocket']
    id_launch_pad = launch['launchpad']

    launch_name = requests.get(url + '/launches/{}'.format(id_launch))
    launch_name = launch_name.json()['name']
    date_local = launch['date_local']
    rocket_name = requests.get(url + '/rockets/{}'.format(id_rocket))
    rocket_name = rocket_name.json()['name']
    launchpad = requests.get(url + '/launchpads/{}'.format(id_launch_pad))
    launchpad = launchpad.json()['name']
    launchpad_loc = requests.get(url + '/launchpads/{}'.format(id_launch_pad))
    launchpad_loc = launchpad_loc.json()['locality']

    result = ''
    result += '{}'.format(launch_name)
    result += ' ({})'.format(date_local)
    result += ' {}'.format(rocket_name)
    result += ' - {}'.format(launchpad)
    result += ' ({})'.format(launchpad_loc)

    print(result)


import tensorflow as tf
from tensorflow import keras

from components.layers import Dense2d
from components.layers import Sampling
from components.layers import StackNTimes

class SparseLinear(keras.layers.Layer):
    def __init__(self, output_dim, min_log_var=-14):
        super(SparseLinear, self).__init__()
        self.output_dim = output_dim
        self.min_log_var = min_log_var

        self.stack_inputs = StackNTimes(axis=1)

        self.mean = Dense2d(1)

        self.log_var = Dense2d(1, activation='elu')

        self.sample_normal = Sampling(dist='normal')

    def call(self, inputs, training):

        y_p = inputs[0]
        samples = inputs[1]

        h_y_p = self.stack_inputs(y_p, samples)

        mean = self.mean(h_y_p)
        mean = tf.squeeze(mean, axis=-1)

        log_var = (-self.min_log_var)*self.log_var(h_y_p/(-self.min_log_var))
        log_var = tf.squeeze(log_var, axis=-1)
        std = tf.exp(log_var/2)

        eps = self.sample_normal(params=[tf.constant(0, dtype=tf.float32),
                                         tf.constant(1, dtype=tf.float32)],
                                 shape=tf.shape(mean))

        y_params = tf.stack([mean, log_var], axis=-1)

        y = mean + std*eps

        return [y_params, y]


import random

class Carta():
    def __init__(self, numero, pal):
        assert (
                    0 <= numero), "Error: Valor del numero de la carta es incorrecte"
        assert (
                    numero <= 11), "Error: Valor del numero de la carta es incorrecte"
        assert (0 <= pal), "Error: Valor del pal de la carta es incorrecte"
        assert (pal <= 3), "Error: Valor del pal de la carta es incorrecte"
        self.numero = numero
        self.pal = pal

    def get_numero(self):
        return self.numero

    def get_pal(self):
        return self.pal

    def set_numero(self, numero):
        assert (
                    0 <= numero), "Error: Valor del numero de la carta es incorrecte"
        assert (
                    numero <= 11), "Error: Valor del numero de la carta es incorrecte"
        self.numero = numero

    def set_pal(self, pal):
        assert (pal <= 3), "Error: Valor del pal de la carta es incorrecte"
        assert (0 <= pal), "Error: Valor del pal de la carta es incorrecte"
        self.pal = pal

    def __str__(self):
        Llnomspal = ["Bastos", "Copes", "Espases", "Oros"]
        LLnumero = ["As", "2", "3", "4", "5", "6", "7", "8", "9", "Sota",
                    "Cavall", "Rei"]
        return (LLnumero[self.numero] + " de " + Llnomspal[self.pal])

    def __gt__(self, altre):
        if (self.numero > altre.numero):
            return True
        elif (self.numero == altre.numero):
            if (self.pal < altre.pal):
                return True
            else:
                return False
        else:
            return False

class Baralla():
    def __init__(self):
        self.pila = []
        for i in range(0, 4):
            for e in range(0, 12):
                carta = Carta(e, i)
                self.pila.append(carta)

    def get_pila(self):
        return self.pila

    def set_pila(self, pila):
        self.pila = pila

    def __str__(self):
        out = ""
        for c in self.pila:
            out = out + str(c) + "\n"
        return out

    def barrejar(self):
        random.shuffle(self.pila)

    def pop_carta(self):
        if (len(self.pila) == 0):
            return None
        else:
            carta = self.pila.pop()
            return carta

    def quantitat_cartes(self):
        return (len(self.pila))

class Jugador():
    def __init__(self, nom):
        self.nom = str(nom)
        self.ma = []
        self.rondes = []

    def get_nom(self):
        return self.nom

    def get_ma(self):
        return self.ma

    def get_rondes(self):
        return self.rondes

    def set_nom(self, nom):
        self.nom = str(nom)

    def set_ma(self, ma):
        self.ma = ma

    def set_rondes(self, rondes):
        self.rondes = rondes

    def str_cartes_ma(self):
        cartesma = ""
        a = 1
        for i in self.ma:
            cartesma += (str(a) + " -> " + str(i) + "\n")
            a += 1
        return cartesma

    def afegir_carta_ma(self, carta):
        if (carta != None):
            self.ma.append(carta)

    def afegir_carta_rondes(self, carta1, carta2):
        if (carta1 != None and carta2 != None):
            self.rondes.append(carta1)
            self.rondes.append(carta2)

    def seleccionar_carta_ma(self, index):
        assert (index >= 0 and index < len(
            self.ma)), "Error: Selecció carta incorrecte"
        return self.ma[index]

    def eliminar_carta_ma(self, carta):
        if carta in self.ma:
            self.ma.remove(carta)

    def quantitat_cartes_ma(self):
        return len(self.ma)

    def punts_cartes_rondes(self):
        valor = 0
        for i in self.rondes:
            valor += i.numero + 1
        return valor

class JugadorMaquina(Jugador):
    def _init_(self, nom):
        Jugador.__init__(self, nom)

    def seleccionar_carta_ma(self):
        if len(self.ma) > 1:
            carta_Alta = max(self.ma)
        elif len(self.ma) == 1:
            carta_Alta = self.ma[0]
        else:
            carta_Alta = None
        return carta_Alta

def Joc(nom1, nom2):
    random.seed(nom1 + nom2)
    jugador = Jugador(nom1)
    maquina = JugadorMaquina(nom2)
    baralla = Baralla()
    baralla.barrejar()

    for i in range(3):
        carta1 = baralla.pop_carta()
        jugador.afegir_carta_ma(carta1)
        carta2 = baralla.pop_carta()
        maquina.afegir_carta_ma(carta2)
    while (jugador.quantitat_cartes_ma() > 0) and (
            maquina.quantitat_cartes_ma() > 0):
        print(jugador.str_cartes_ma())
        err = True
        while err == True:
            try:
                tria = int(input(nom1 + " quina carta tires?"))
                se1 = jugador.seleccionar_carta_ma(tria - 1)
                err = False
            except ValueError:
                print("Error : el valor ha de ser un sencer")
            except AssertionError as error:
                print(error)
        se2 = maquina.seleccionar_carta_ma()
        print(nom1, "ha tirat", se1)
        print(nom2, "ha tirat", se2)
        if se1 > se2:
            jugador.afegir_carta_rondes(se1, se2)
        else:
            maquina.afegir_carta_rondes(se1, se2)

        jugador.eliminar_carta_ma(se1)
        maquina.eliminar_carta_ma(se2)

        if (baralla.quantitat_cartes() > 0):
            jugador.afegir_carta_ma(baralla.pop_carta())
            maquina.afegir_carta_ma(baralla.pop_carta())
    return (jugador, maquina)

if __name__ == "__main__":
    nom1 = input()
    nom2 = input()
    jug1, jug2 = Joc(nom1, nom2)
    valor1 = jug1.punts_cartes_rondes()
    print(nom1, "te", valor1)
    valor2 = jug2.punts_cartes_rondes()
    print(nom2, "te", valor2)
    if (valor1 > valor2):
        print("El guanyador és:", nom1)
    elif (valor2 > valor1):
        print("El guanyador és:", nom2)
    else:
        print("Empat!")


from ...abs.client_abc import ClientABC

from ...utils.adapters import append_client_to_name
from ...utils.adapters import save_to_file

import uuid

from PIL import Image

from google.cloud import vision
from google.cloud.vision import types
from google.api_core.exceptions import PermissionDenied

from pprint import pprint as p

import io
import os

__all__ = ["GoogleVisionClient"]

def object_localization(objects):

    data = []
    for object_ in objects:
        obj_data = {
            object_.name : {'confidence' : object_.score}
        }
        for vertex in object_.bounding_poly.normalized_vertices:
            obj_data[object_.name].setdefault('vertices', []).append([vertex.x, vertex.y])
        data.append(obj_data)

    return data

parsers = {
    'object_localization' : object_localization
}

class GoogleVisionClient(ClientABC):

    def __init__(self,service_account):
        self.client = vision.ImageAnnotatorClient()\
                    .from_service_account_json(service_account)

    REPORTS = {'object_localization' : lambda client, image: client.object_localization(
        image=image).localized_object_annotations
        }

    def get_response(self, file_path, report_type):

        try:
            with io.open(file_path, 'rb') as image_file:
                content = image_file.read()
            image = vision.types.Image(content=content)
        except:
            try:
                image = vision.types.Image()
                image.source.image_uri = self.file_path
            except PermissionDenied:
                raise PermissionDenied("Ensure Vision API is enabled")

        objects = self.REPORTS[report_type](self.client,image)

        return parsers[report_type](objects)

    def read(self, shuttle, report_type, gcs_file_path=None):

        shuttle.client = self

        shuttle.name = append_client_to_name(shuttle=shuttle)

        if gcs_file_path: #in the cloud
            shuttle.data = self.get_response(file_path=gcs_file_path, report_type=report_type)
        else: #using image obj
            tmp_file = '{}/{}.jpg'.format(shuttle.staging_path, uuid.uuid4().hex)
            save_to_file(data=shuttle.data,file_path=tmp_file)
            shuttle.data = self.get_response(file_path=tmp_file, report_type=report_type)
            os.remove(tmp_file)

        return shuttle

    def write(self,shuttle):
        raise NotImplementedError('Cannot write to the Google VisionAPI')

    def delete(self,shuttle):
        raise NotImplementedError('Cannot delete on the Google VisionAPI')

    def edit(self,shuttle):
        raise NotImplementedError('Cannot edit the Google VisionAPI')

    def merge(self,shuttle):
        raise NotImplementedError('Cannot merge on the Google VisionAPI')


#Author Name: Bijan Amirzadehasl
#Date: 11/1/2021
#Program Name: Amirzadehasl_Player.py
#Purpose: Create a player class. Create and store three player objects. Display the attributes of the three players

#player class
class Player:
    def __init__(self, name, team, position, age, gp, mpg):
        self.name = name
        self.team = team
        self.position = position
        self.age = age
        self.gp = gp
        self.mpg = mpg

def main():
    #three player objects
    p1 = Player('Jaylen Adams', 'Mil', 'G', 24.86, 7, 2.6)
    p2 = Player('Steven Adams', 'Nor', 'C', 27.65, 36, 27.4)
    p3 = Player('Bam Adebayo', 'Mia', 'C-F', 23.66, 33, 33.9)

#formatted output displaying player's attributes
    print("{:<15} {:<12} {:<12} {:<12} {:<12} {:<12}".format('Name', 'Team', 'Position', 'Age', 'GP', 'MPG'))
    print("{:<15} {:<12} {:<12} {:<12} {:<12} {:<12}".format(p1.name, p1.team, p1.position, p1.age, p1.gp, p1.mpg))
    print("{:<15} {:<12} {:<12} {:<12} {:<12} {:<12}".format(p2.name, p2.team, p2.position, p2.age, p2.gp, p2.mpg))
    print("{:<15} {:<12} {:<12} {:<12} {:<12} {:<12}".format(p3.name, p3.team, p3.position, p3.age, p3.gp, p3.mpg))

main()


from django.http import JsonResponse

class GenericJsonResponse(JsonResponse):
    def __init__(self, code=0, message='成功', data=None):
        final_data = {
            'code': code,
            'message': message
        }
        if data is not None:
            final_data['data'] = data
        super(GenericJsonResponse, self).__init__(data=final_data)


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

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('training', '0019_auto_20150813_1040'),
    ]

    operations = [
        migrations.AlterField(
            model_name='assessment',
            name='deadline',
            field=models.DateTimeField(default=datetime.datetime(2015, 8, 18, 20, 10, 14, 688356)),
        ),
        migrations.AlterField(
            model_name='feedback',
            name='score',
            field=models.DecimalField(null=True, max_digits=4, decimal_places=1, blank=True),
        ),
    ]


#!/usr/bin/python3

from assets.headers import enumeration_header
from assets.shortcuts import Exit
from assets.prefixes import eagleshell_prefix, invalid_input_prefix
from assets.colors import *

class Enumeration:
    def __init__(self):
        try:
            enumeration_header()
            print('Scripts:')
            print('\n\t1): BR4NCH - Linux PE Enumeration Script')
            print('\n\tZ): Back')
            print('\tX): Exit\n')
            while True:
                enumeration_select = input(eagleshell_prefix).lower()
                if enumeration_select == '1':
                    print(YELLOW + '\n\tYou can download our PE Enum Script on our Github Page:' + RESET + BLUE + '\n\thttps://github.com/TRSTN4/BR4NCH\n' + RESET)
                elif enumeration_select == 'z':
                    from ..scripts import Scripts
                    Scripts()
                elif enumeration_select == 'x':
                    Exit()
                else:
                    print(invalid_input_prefix)
                    continue
        except KeyboardInterrupt:
            Exit()


import sys
from common import *

if __name__ == "__main__":
    expected_arg_count = 3
    if len(sys.argv) != expected_arg_count:
        print('incorrect argument count')
        sys.exit()
    input = numpy.genfromtxt(sys.argv[1], delimiter=';', dtype='<U25')
    output = to_determined_machine(input)
    numpy.savetxt(sys.argv[2], output, delimiter=';', fmt='%s')


# Esse algoritmo é baseado no LSD de strings do livro Algorithms
# Inclusive seria possível deixa-lo mais genérico para que também
# ordenasse strings do mesmo tamanho
# Usa o key index counting (o for d in range(0,ndigits) ) para ordenar

def radix_sort (aList,r):

    if len(aList) <= 0:
        return

    ndigits = 0
    bigger = max (aList)
    # baseado no maior numero, descobre a qtde de casas decimais
    while bigger > 0:
        ndigits += 1
        bigger //= r

    n = len(aList)

    # para cada casa decimal (ndigits !? abaixo)
    for d in range(0,ndigits):

        count = [0] * (r + 1)

        # aqui calculo o bucket baseado no digito atual
        # e onde ele se encaixa exatamente. Lembrando que para
        # a primeira entrada, sempre fazemos +1 para que depois
        # na parte de posicionamento, a conta fique facil
        # ex.: ((8 // (10 ** 0)) % r) = 8  # testando o primeiro digito (unidades)
        # ex.: ((28 // (10 ** 1)) % r) = 2 # testando o segundo digito (dezenas)

        for i in range(0,n):
            bucket = ((aList[i] // (10 ** d)) % r)
            count [(bucket) + 1] += 1
        #print (count)

        # define os indices iniciais de cada bucket
        for c in range(0,r):
            count [c + 1] += count[c]
        #print (count)

        # copia os dados ordenados para a aux
        aux = [0] * n
        for i in range (0,n):
            bucket = ((aList[i] // (10 ** d)) % r)
            aux[ count [ (bucket)  ]   ] = aList[i]
            count [ (bucket)  ] += 1

        for i in range(0,n):
            aList[i] = aux[i]

if __name__ == "__main__":

    aList = [8,20,35,12,11,7,66,44,30,18,71]
    print (aList)

    radix_sort(aList,10)

    print (aList)


#! /usr/bin/python3

import numpy as np

#This file contains the implemetation of the PAMR algorithm

fee = 0.0025#(so 0.25%)

def compute_portfolio(prev_b,x):
    eps = 1
    m = len(prev_b)
    moneys = list(prev_b)
    x_L = [x[name] for name in moneys]
    prev_b_L = [prev_b[name] for name in moneys]
    x_b = np.dot(x_L,[1/m]*m)
    diff = [xi - x_b for xi in x_L]
    norm = np.dot(diff,diff)
    to = 0
    if norm != 0:
        to = max(0,(np.dot(prev_b_L,x_L) - eps)/np.dot(diff,diff))
    b = {name : prev_b_L[j] - to*diff[j] for j,name in enumerate(moneys)}
    return b

def compute_amounts(prev_b,b,holdings,price):
    amounts = {name : holdings[name]*price[name] for name in holdings}
    total_btc = sum(list(amounts.values()))
    total_move = sum([abs(prev_b[name] - b[name]) for name in b])
    total_btc_after = total_btc - total_btc*total_move*fee
    amounts_after = {name : total_btc_after*b[name] for name in b}
    amounts_diff = {name :amounts_after[name] - amounts[name] for name in b}
    return amounts_diff,total_btc

def sell_moneys(amounts,bids,holdings):
    #amounts are in coins
    btc = 0
    #ask > bid so ask = sell price, bid = buy price
    for name in amounts:
        if amounts[name] < 0:
            x = min(holdings[name],abs(amounts[name]))
            #sell
            btc += x*bids[name]*(1-fee)
            holdings[name] -= x
    return btc

def buy_moneys(amounts,asks,btc,holdings):
    #amounts are in btc
    total_buy = sum([0 if amounts[name] < 0 else amounts[name] for name in amounts])
    for name in amounts:
        if amounts[name] > 0:
            holdings[name] += (((amounts[name]/total_buy)*btc) / asks[name])*(1-fee)

def manage_portfolio_past(moneys,period):
    n = len(moneys[list(moneys)[0]]['close'])
    m = len(moneys)
    holdings = {}
    btc_equ_L = []
    average_gains = []
    b = {}
    last_i = 0
    for i in range(0,n,period):
        last_i = i
        #balance portfolio
        total_btc = 1
        gain = 1
        price = {name : moneys[name]['close'][i] for name in moneys}
        if i > 0:
            gain = sum([moneys[name]['close'][i]/moneys[name]['close'][0] for name in moneys])/m
            asks = {}
            bids = {}
            for name in moneys:
                asks[name] = price[name]
                bids[name] = price[name]
            x = {name : price[name]/moneys[name]['close'][i-period] for name in moneys}
            prev_b = b
            b = compute_portfolio(b,x)
            amounts,total_btc = compute_amounts(prev_b,b,holdings,price)
            btc = sell_moneys({name:amounts[name]/price[name] for name in amounts},bids,holdings)
            buy_moneys(amounts,asks,btc,holdings)
        else:
            b = {name : 1/m for name in moneys}
            holdings = {name : (total_btc/m)/price[name] for name in moneys}
        #print("bitcoin : ",total_btc)
        for j in range(i,min(i+period,n)):
            btc_equ_L.append(total_btc)
            average_gains.append(gain)
    for name in moneys:
        moneys[name]['btc_equ'] = btc_equ_L
        moneys[name]['average_gains'] = average_gains
    x_tot = [moneys[name]['close'][last_i]/moneys[name]['close'][0] for name in moneys]
    print("end btc : ",btc_equ_L[-1])
    print("var = ",sum(x_tot)/m)
    return {name : moneys[name]['close'][last_i] for name in list(moneys)},b,moneys[list(moneys)[0]]['date'][last_i]


import unittest

from gbakeboy import Memory
from gbakeboy import hex2int as h2i
from gbakeboy import MAX_MEMORY_BYTES

mem_start = h2i('0000')

class test_memory(unittest.TestCase):

    def setUp(self):
        self.mem = Memory()

    def load_data(self, mem):
        # Load some test data into memory
        data = bytes([0x13, 0x01, 0x00, 0x01, 0x08, 0x09])
        self.mem.load(data, mem_start)

    def test_init(self):
        self.assertEqual(len(self.mem.memory), MAX_MEMORY_BYTES)
        self.assertEqual(sum(self.mem.memory), 0)

    def test_load(self):
        # Load some data
        data = bytes([0x13, 0x01, 0x00, 0x00, 0x08, 0x09])
        self.mem.load(data, mem_start)

        read_data = self.mem.read_byte(mem_start)
        self.assertEqual(read_data, 0x13)
        read_data = self.mem.read_byte(mem_start + 1)
        self.assertEqual(read_data, 0x01)
        read_data = self.mem.read_byte(mem_start + 4)
        self.assertEqual(read_data, 0x08)

        # Test we can overwrite data
        data = bytes([0x14, 0x02, 0x01, 0x08, 0xA8, 0x09])
        self.mem.load(data, mem_start)

        read_data = self.mem.read_byte(mem_start + 1)
        self.assertEqual(read_data, 0x02)
        read_data = self.mem.read_byte(mem_start + 4)
        self.assertEqual(read_data, 0xA8)

    def test_read_byte(self):
        self.load_data(self.mem)

        read_data = self.mem.read_byte(mem_start)
        self.assertEqual(read_data, 0x13)

        read_data = self.mem.read_byte(mem_start + 2)
        self.assertEqual(read_data, 0x00)

    def test_read_byte_outside_mem_range(self):
        self.load_data(self.mem)
        read_data = self.mem.read_byte(MAX_MEMORY_BYTES - 1)
        self.assertEqual(read_data, 0x00)

        with self.assertRaises(MemoryError):
            self.mem.read_byte(MAX_MEMORY_BYTES)

        with self.assertRaises(MemoryError):
            self.mem.read_byte(0x00 - 2)

    def test_read_word(self):
        self.load_data(self.mem)

        read_data = self.mem.read_word(mem_start)
        self.assertEqual(read_data, 0x0113)

        read_data = self.mem.read_word(mem_start + 4)
        self.assertEqual(read_data, 0x0908)

    def test_read_word_outside_mem_range(self):
        self.load_data(self.mem)

        with self.assertRaises(MemoryError):
            self.mem.read_word(MAX_MEMORY_BYTES)

        with self.assertRaises(MemoryError):
            self.mem.read_word(0x00 - 2)


from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import TemplateView
from django.contrib.auth.models import User
import urllib
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.context_processors import csrf

# Create your views here.

def get_authorization_url(request):

        # URL to where we will redirect to
        redirect_url = urllib.quote_plus(settings.SITE_URL + reverse('register_google'))

        # create a unique state value for CSRF validation
        request.session['google_state'] = unicode(csrf(request)['csrf_token'])

        scope = urllib.quote_plus('https://www.googleapis.com/auth/userinfo.email') + '+' + \
                urllib.quote_plus('https://www.googleapis.com/auth/userinfo.profile')

        # redirect to google for approval
        url = 'https://accounts.google.com/o/oauth2/auth?' \
              + 'scope=' + scope \
              + '&state=' + request.session['google_state'] \
              + '&redirect_uri=' + redirect_url \
              + '&response_type=code' \
              + '&client_id=' + settings.GOOGLE_OAUTH2_CLIENT_ID \
              + '&access_type=offline' \
              + '&approval_prompt=auto'

        return url
def verify(request):
        # Google will direct with state and code in the URL
        # ?state=zNHRjuYO...&code=4/zK5F93g2we...

        # ensure we have a session state and the state value is the same as what google returned
        if 'google_state' not in request.session \
           or 'state' not in request.GET \
           or 'code' not in request.GET \
           or request.session['google_state'] != request.GET['state']:
            return False
        else:
            return True

def get_user_profile(request, userid):
    user = User.objects.get(id=userid)
    return render(request, 'ProfileView/profile.html', {"user":user})

def select_profile(request):
	get_authorization_url(request)
	HttpResponseRedirect(url)


# Importing Modules

from time import sleep

# Welcome

print("Hello User!")
sleep (.2)
user_name = input("Please enter your name: ")
sleep (.2)
print("Your name is: ", user_name)
sleep (.2)

# Main Code

print("Please select from one of the following operations: ")
sleep (.2)
print("1 = Addition")
sleep (.2)
print("2 = Subtraction")
sleep (.2)
print("3 = Multiplication")
sleep (.2)
print("4 = Division")
sleep (.2)

# Getting user's input
user_input_1 = int(input("Enter number 1/2/3/4: "))
sleep (.2)

# If user selected Addition
if user_input_1 == 1:
    print("You have selected Addition")
    sleep (.2)
    print("Now you have to enter any two number which you have to Add")
    sleep (.2)
    add1 = int(input("> "))
    print("You entered: ", add1)
    sleep (.2)
    add2 = int(input("> "))
    print("You entered: ", add2)

    sum = add1 + add2
    sleep (.2)
    print(add1, "+", add2, "=", sum)
    sleep (.2)

    # Bye
    print("Thanks for using this Calculator programme!")
    sleep (.2)
    print("Hope you have a nice day!")
    sleep (.5)
    exit() # Exiting Programme

# If selected Subtraction
elif user_input_1 == 2:
    print("You have selected Subtraction")
    sleep (.2)
    print("Now you have to enter any two number which you have to Subtract")
    sleep (.2)

    sub1 = int(input("> "))
    print("You entered: ", sub1)
    sleep (.2)
    sub2 = int(input("> "))
    print("You entered: ", sub2)

    sub_ans = sub1 - sub2
    sleep (.2)
    print(sub1, "-", sub2, "=", sub_ans)
    sleep (.2)

    # Bye
    print("Thanks for using this Calculator programme!")
    sleep (.2)
    print("Hope you have a nice day!")
    sleep (.5)
    exit() # Exiting Programme

# If selected Multiplication
elif user_input_1 == 3:
    print("You have selected Multiplication")
    sleep (.2)
    print("Now you have to enter any two number which you have to Multiply")
    sleep (.2)

    mul1 = int(input("> "))
    print("You entered: ", mul1)
    sleep (.2)
    mul2 = int(input("> "))
    print("You entered: ", mul2)

    mul_ans = mul1 * mul2
    sleep (.2)
    print(mul1, "*", mul2, "=", mul_ans)
    sleep (.2)

    # Bye
    print("Thanks for using this Calculator programme!")
    sleep (.2)
    print("Hope you have a nice day!")
    sleep (.5)
    exit() # Exiting Programme

# If selected Division
elif user_input_1 == 4:
    print("You have selected Division")
    sleep (.2)
    print("Now you have to enter any two number which you have to Divide")
    sleep (.2)

    div1 = int(input("> "))
    print("You entered: ", div1)
    sleep (.2)
    div2 = int(input("> "))
    print("You entered: ", div2)

    div_ans = div1 / div2
    sleep (.2)
    print(div1, "/", div2, "=", div_ans)
    sleep (.2)

    # Bye
    print("Thanks for using this Calculator programme!")
    sleep (.2)
    print("Hope you have a nice day!")
    sleep (.5)
    exit() # Exiting Programme

else:
    print("Wrong Input!")
    sleep (.2)
    print("Exiting!")
    sleep (.2)
    sleep (.2)
    sleep (.2)
    exit()


import socket
from cryptography.fernet import Fernet

user   = "Alice"
server = "Bob"
key_TGS = b"BgIFUaxnefMzR1FI_Sv-meLxCV4e5RI6zp-5Y_RlR6s="

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
port = 22222
server_socket.bind(("127.0.0.1", port))
server_socket.listen(5)

while True:
    # Step 5
    c, addr = server_socket.accept()
    (enc_1, enc_2) = c.recv(1024).decode().split()
    print(f"Connection request received from Client: {user}, Address: {addr}")
    # Step 6
    fernet_1 = Fernet(key_TGS)
    (user_tmp, key_session) = fernet_1.decrypt(enc_2.encode()).split()
    fernet_2 = Fernet(key_session)
    nonce = fernet_2.decrypt(enc_1.encode()).decode()
    nonce_new = str(int(nonce) - 1)
    enc = fernet_2.encrypt(nonce_new.encode())
    c.send(enc)
    print(f"Nonce: {nonce} received from Client: {user_tmp}")
    print(f"Session Key: {key_session} received from Client: {user_tmp}")
    print(f"Sending new Nonce: {nonce_new} to Client: {user_tmp}...")
    c.close()
    break


"""
The corresponding TorchPlus layers to PyTorch's `torch.nn`.

They look identical but perform various magic behind the scenes to enable "+"
sequences, layers without parentheses, etc.
"""

from inspect import isclass
import sys
import torch
from torch.nn.modules import Module

from . import extra
from .internal import Keyword

def wrap_layer_classes(from_module, to_module):
    """
    Create a corresponding wrapper in to_module for each from_module nn.Module.
    """
    for class_name in dir(from_module):
        if class_name == 'Module':
            continue
        klass = getattr(from_module, class_name)
        if not isclass(klass):
            continue
        if not issubclass(klass, Module):
            continue
        assert not hasattr(to_module, class_name)
        wrapped = Keyword(klass)
        setattr(to_module, class_name, wrapped)

this_module = sys.modules[__name__]
wrap_layer_classes(torch.nn.modules, this_module)
wrap_layer_classes(extra, this_module)


array=list(map(int,input().split()))
max_num=array[0]
max=0
for i in range(1,len(array)):
    if array[i]>max_num:
        max_num=array[i]
        max=i
print(max+1,end=" ")
for j in range(max+1,len(array)):
   if array[max]==array[j]:
        print(j+1,end=" ")


player_to_words= { }
player_to_points={}
#functions
  #add word that a player got
def play_word(player,word):
    if player in player_to_words:
      player_to_words[player].append(word)
      update_point()
    else:
       w=[word]
       player_to_words.update({player:(w)})
       update_point()

  #score word
def score_word(word):
    point_total = 0
    for letter in word:
      point_total += letter_to_points.get(letter, 0)
    return point_total
  #update score
def update_point():
    for player, words in player_to_words.items():
      player_point=0
      for word in words:
        player_point+=score_word(word)
        player_to_points[player]=player_point

letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10, 0]
player=" "

letter_to_points={
    key: value
    for key, value
    in zip(letters, points)
    }

while (player!= "exit"):

  player=input('Please input the player name that got the word or type exit to see the score: ').title()

  if player=="Exit":
    winner_name= max(player_to_points, key=player_to_points.get)
    winner_pt= max(player_to_points.values())
    print(winner_name)
    print(winner_pt)

    print(player_to_points)

    print(player_to_words)

    print ("Winner is "+ winner_name + " with "+ str(winner_pt)+ " points! ")

    break
  else:
    word=input('Please enter the word that the player got: ').upper()

    play_word(player,word)
    print(player_to_points)
    print(player_to_words)


import datetime
import math

def prodList(myList) :
    result = 1
    for x in myList:
         result = result * x
    return result

getal = 1
a = 1
max = 100000
t = datetime.datetime.now()
result = []
E = []
rad = []

for getal in range (1, max+1):
	a = getal
	b = 2
	while a%2==0:
	  a = a/2
	  rad.append(2)
	for b in range(3, int(math.sqrt(getal))+1,2):
	  while a%b == 0:
	  	a = a/b
	  	rad.append(b)
	if a > 2:
		rad.append(int(a))
	#print (set(rad))
	E.append([getal, prodList(rad), prodList(set(rad))])
	rad = []
#E.sort(key=lambda x: x[0])
E.sort(key=lambda x: x[2])

#print (E)
print (E[10000-1])
runtime  = datetime.datetime.now() - t
print (runtime)


import sys
import os
import requests
import aiohttp
import aiofiles
import asyncio
import time

if len(sys.argv[1:])!=1:
    print("Usage: python3 web_sync.py <file_name>")
    sys.exit(1)

async def get_file_content(file_path):
    f = await aiofiles.open(file_path, "r", encoding="utf-8")
    return await f.read()

async def get_content(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def write_content(content,file):
    if os.name == "posix":
        tmp_dir = f"/tmp/web_{file}"
    else:
        tmp_dir = f"./Tp6/tmp/web_{file}"

    if not os.path.exists(tmp_dir.split('/')[0]):
        os.makedirs(tmp_dir)
    elif not os.path.exists('/'.join(tmp_dir.split('/')[1:])):
        os.makedirs('/'.join(tmp_dir.split('/')[1:]))
    elif not os.path.exists(tmp_dir):
        os.makedirs(tmp_dir)

    os.chdir(tmp_dir)

    f= await aiofiles.open(file+".html","w", encoding="utf-8")
    await f.write(content)
    await f.close()

    os.chdir("../../..")

if __name__ == "__main__":
    startTime= time.time()
    file_path = sys.argv[1]
    sites= asyncio.run(get_file_content(file_path))
    for site in sites.split("\n"):
        file_name = site.split(".")[1]
        print(file_name)
        asyncio.run(write_content(asyncio.run(get_content(site)),file_name))
    print(f"Done! In {time.time()-startTime} seconds")


# --------------------------------------
# CSCI 127, Lab 3
# February 1, 2018
# Your Name
# --------------------------------------

def count_built_in(sentence):
    return sentence.count("z")

def count_iterative(sentence):
    count = 0
    for letter in sentence:
        if letter == "z":
            count += 1
    return count

def count_recursive(sentence):
    s = len(sentence)
    if s == 0:
        return 0
    elif sentence[0] == "z":
        return 1 + count_recursive(sentence[1:])
    else:
        return remove_recursive(sentence[1:])

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

def main():
    answer = "yes"
    while (answer == "yes") or (answer == "y"):
        sentence = input("Please enter a sentence: ")
        sentence = sentence.lower()
        print()
        print("Calculating the number of z's using ...")
        print("---------------------------------------")
        print("Built-in function =", count_built_in(sentence))
        print("Iteration =", count_iterative(sentence))
        print("Recursion =", count_recursive(sentence))
        print()
        answer = input("Would you like to continue: ").lower()
        print()

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

main()


"""
file_management
Contains the main functionality for managing the files
Most functions have complete functionality and don't
return any value, printing the process output
Authors:
    Ana Calzada
    Martin Sanchez
"""

import re
import os
import sys
import requests
import encryption
from Cryptodome.PublicKey import RSA

token = 'IMPORT TOKEN HERE'

def upload(file, dest_id):
    """ Upload a file.
    Given the file (path) and the id of the destinatary, it
    encrypts and signs the file and then uploads it.
    """
    # Get file and private key
    data, filename = read_from_file(file)
    if data is None:
        return

    key_pr = encryption.get_key()
    if key_pr is None:
        print('\nError: No private key found, create an id first with --create_id', file=sys.stderr)
        return

    # Sign file
    print('Solicitando envío de fichero a SecureBox')
    print('-> Firmando fichero...', end='', flush=True)
    try:
        signature, data = encryption.sign_data(data, key_pr)
    except:
        print('\nError: Could not sign file, error with private key', file=sys.stderr)
        return
    print('OK', flush=True)

    # Retrieve public key from dest
    print('-> Recuperando clave pública de ID {0}...'.format(dest_id), end='', flush=True)
    r = encryption.request_public_key(dest_id)
    if r.status_code != 200:
        print_error_server(r)
        return
    key_pu = RSA.import_key(r.json()['publicKey'])
    print('OK', flush=True)

    # Encrypt with public key
    print('-> Cifrando fichero...', end='', flush=True)
    try:
        iv, enc_session_key, enc_data = encryption.encrypt_data(signature+data, key_pu)
    except:
        print('\nError: Could not encrypt file, error with public key', file=sys.stderr)
        return
    to_send = iv + enc_session_key + enc_data
    print('OK', flush=True)

    # Upload
    print('-> Subiendo fichero al servidor...', end='', flush=True)
    url = 'https://vega.ii.uam.es:8080/api/files/upload'
    file = {'ufile': (filename, to_send)}
    headers = {'Authorization': 'Bearer '+token}
    r = requests.post(url, files=file, headers=headers)

    if r.status_code != 200:
        print_error_server(r)
        return
    print('OK', flush=True)
    print('Subida realizada correctamente, ID del fichero: {0}'.format(r.json()['file_id']))
    return

def download_file(file_id, src_id):
    """ Downloads a file.
    Given a file id (created on upload), it fetches it from
    the server and then tries to decrypt it.
    """
    # Get private key to decrypt
    key_pr = encryption.get_key()
    if key_pr is None:
        print('\nError: No private key found, create an id first with --create_id', file=sys.stderr)
        return

    # Fetch file
    print('Descargando fichero de SecureBox...', end='',flush=True)
    url = 'https://vega.ii.uam.es:8080/api/files/download'
    args = {'file_id': file_id}
    headers = {'Authorization': 'Bearer '+token}
    r = requests.post(url, json=args, headers=headers)

    if r.status_code != 200:
        print_error_server(r)
        return
    content = r.content

    # Retrieve original filename with regex
    try:
        regex = r"(?<=filename=\")(?:[^\"\\]|\\.)*(?=\")"
        matches = re.findall(regex, r.headers['Content-Disposition'])
        if len(matches) > 0:
            filename = matches[0]
        else:
            filename = 'download'
    except:
        filename = 'download'

    print('OK',flush=True)
    print('-> {0} bytes descargados correctamente'.format(len(content)),flush=True)

    # Decrypt content and verify
    print('-> Descifrando fichero...',end='',flush=True)
    try:
        iv, enc_session_key, enc_data = encryption.get_encrypted_components(content)
        data = encryption.decrypt_data(iv, enc_session_key, enc_data, key_pr)
    except:
        print('\nError: Could not decrypt file, invalid private key', file=sys.stderr)
        return
    print('OK', flush=True)

    # Get public key to verify
    print('-> Recuperando clave pública de ID {0}...',end='',flush=True)
    r = encryption.request_public_key(src_id)
    if r.status_code != 200:
        print_error_server(r)
        return
    key_pu = RSA.import_key(r.json()['publicKey'])
    print('OK',flush=True)

    print('-> Verificando firma...',end='',flush=True)
    signature, data = encryption.get_signed_components(data)
    if encryption.verify_data(signature, data, key_pu):
        print('OK',flush=True)
    else:
        print('\nError: Sign verification failed', file=sys.stderr)

    if write_in_file(filename, data):
        print('Fichero \'{0}\' descargado y verificado correctamente'.format(filename))
    return

def list_files():
    """ Prints a list of files.
    Accesses the server to retrieve the list of files under the
    current user.
    """
    # Make request
    url = 'https://vega.ii.uam.es:8080/api/files/list'
    headers = {'Authorization': 'Bearer '+token}

    print('Recuperando lista de ficheros subidos al servidor...',end='',flush=True)
    r = requests.post(url, headers=headers)

    if r.status_code != 200:
        print_error_server(r)
        return
    print('OK',flush=True)

    # Print results
    json = r.json()
    num = json['num_files']
    files = json['files_list']
    print('Se han encontrado {0} ficheros:'.format(num))
    for i in range(num):
        print('[{index}] {name}, ID: {id}'.format(index=i, name=files[i]['fileName'], id=files[i]['fileID']))

    return

def delete_file(id):
    """ Deletes a files.
    Given a valid file id (of a file owned by the user), it
    tries to delete it from the server.
    """
    url = 'https://vega.ii.uam.es:8080/api/files/delete'
    args = {'file_id': id}
    headers = {'Authorization': 'Bearer '+token}

    print('Solicitando borrado del fichero #{0}...'.format(id),end='',flush=True)
    r = requests.post(url, json=args, headers=headers)

    if r.status_code != 200:
        print_error_server(r)
        return
    print('OK',flush=True)
    print('Fichero con fileID#{0} borrado correctamente'.format(id))

    return

def get_abs_path(rel_path):
    script_dir  = os.path.dirname(__file__)
    abs_path    = os.path.join(script_dir, rel_path)
    return abs_path

def write_in_file(file, data):
    """ Write data in file and print in case of error.
    Returns True if success,
            False if error
    """
    # Save file
    try:
        f = open(file, 'wb')
        f.write(data)
        f.close()
    except:
        print('\nError: Could not save output in {0}'.format(file), file=sys.stderr)
        return False
    return True

def read_from_file(file):
    """ Read data and name from file and print in case of error.
    Returns data and filename if success,
            None if error
    """
    try:
        f = open(file, 'rb')
        data = f.read()
        name = os.path.basename(file)
        f.close()
    except:
        print('\nError: Could not find file {0}'.format(file), file=sys.stderr)
        return None
    return data, name

def print_error_server(response):
    """ Print error message from server response
    """

    if response.status_code > 499:
        print('\nError: Server fault responded with code {0}'.format(response.status_code), file=sys.stderr)
        return

    if response.status_code == 401 or response.status_code == 403:
        print('\nError: Server responded with code {0}'.format(response.status_code), end='', file=sys.stderr)
        try:
            print(': {0}'.format(response.json()['description']),file=sys.stderr)
        except:
            print(': No description',file=sys.stderr)
        return

    print('\nError: Causa desconocida', file=sys.stderr)
    return


import pip

def install(package):
    pip.main(['install', package])

# Example
if __name__ == '__main__':
    install('pyttk')
    install('python-tk')
    install('google-api-python-client')
    install('python-dateutil')
    install('pillow')
    install('matplotlib')
    install('numpy')
    install('pyinstaller')


import sys, os, time, math
from fastapi import FastAPI
import torch
import time
from typing import Optional
from fastapi.middleware.cors import CORSMiddleware
import torch
from diffusers import StableDiffusionPipeline
from PIL import Image
import base64

#pipe = StableDiffusionPipeline.from_single_file("/run/media/privateserver/NECTAC1TBSSD/a1111/stable-diffusion-webui/models/Stable-diffusion/sd15.safetensors", torch_dtype=torch.float16).to("cuda")

def stable_diffusion(prompt):
    # Generate an image using a prompt
    pipe.safety_checker = None
    pipe.requires_safety_checker = False
    image = pipe(prompt=prompt, num_inference_steps=30).images[0]

    # Save the image directly as PNG
    image.save("generated_image.png")

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

app = FastAPI()

origins = [
    "http://localhost:3000",  # React app address
    "http://127.0.0.1:3000"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

from exllamav2 import(
    ExLlamaV2,
    ExLlamaV2Config,
    ExLlamaV2Cache,
    ExLlamaV2Cache_8bit,
    ExLlamaV2Tokenizer,
    model_init,
)

import argparse
import torch

from exllamav2.generator import (
    ExLlamaV2StreamingGenerator,
    ExLlamaV2Sampler
)

from examples.chat_formatting import CodeBlockFormatter
from examples.chat_prompts import prompt_formats
prompt_formats_list = list(prompt_formats.keys())

# Options

parser = argparse.ArgumentParser(description = "Simple Llama2 chat example for ExLlamaV2")
parser.add_argument("-dm", "--draft_model_dir", type = str, default = None, help = "Path to draft model directory")
parser.add_argument("-nds", "--no_draft_scale", action = "store_true", help = "If draft model has smaller context size than model, don't apply alpha (NTK) scaling to extend it")

parser.add_argument("-modes", "--modes", action = "store_true", help = "List available modes and exit.")
parser.add_argument("-mode", "--mode", choices = prompt_formats_list, help = "Chat mode. Use llama for Llama 1/2 chat finetunes.")
parser.add_argument("-un", "--username", type = str, default = "User", help = "Username when using raw chat mode")
parser.add_argument("-bn", "--botname", type = str, default = "Chatbot", help = "Bot name when using raw chat mode")
parser.add_argument("-sp", "--system_prompt", type = str, help = "Use custom system prompt")

parser.add_argument("-temp", "--temperature", type = float, default = 0.70, help = "Sampler temperature, default = 0.95 (1 to disable)")
parser.add_argument("-topk", "--top_k", type = int, default = 20, help = "Sampler top-K, default = 20 (0 to disable)")
parser.add_argument("-topp", "--top_p", type = float, default = 0.9, help = "Sampler top-P, default = 0.9 (0 to disable)")
parser.add_argument("-typical", "--typical", type = float, default = 1.0, help = "Sampler typical threshold, default = 1.0 (0 to disable)")
parser.add_argument("-repp", "--repetition_penalty", type = float, default = 1.15, help = "Sampler repetition penalty, default = 1.15 (1 to disable)")
parser.add_argument("-maxr", "--max_response_tokens", type = int, default = 4096, help = "Max tokens per response, default = 1000")
parser.add_argument("-resc", "--response_chunk", type = int, default = 250, help = "Space to reserve in context for reply, default = 250")
parser.add_argument("-ncf", "--no_code_formatting", action = "store_true", help = "Disable code formatting/syntax highlighting")

parser.add_argument("-c8", "--cache_8bit", action = "store_true", default = True, help = "Use 8-bit cache")

parser.add_argument("-pt", "--print_timings", action = "store_true", help = "Output timings after each prompt")

# Arrrgs

model_init.add_args(parser)
args = parser.parse_args()

# Prompt templates/modes

if args.modes:
    print(" -- Available formats:")
    for k, v in prompt_formats.items():
        print(f" --   {k:12} : {v().description}")
    sys.exit()

username = args.username
botname = args.botname
system_prompt = args.system_prompt

mode = 'chatml'

prompt_format = prompt_formats[mode]()
prompt_format.botname = botname
prompt_format.username = username
if system_prompt is None: system_prompt = prompt_format.default_system_prompt()

# Initialize model and tokenizer

args.model_dir = "modeldir"

model_init.check_args(args)
model_init.print_options(args)
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
print(args)
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
model, tokenizer = model_init.init(args, allow_auto_split = True)

# Initialize draft model if provided, assume it always fits on first device

draft_model = None
draft_cache = None

if args.draft_model_dir:

    print(f" -- Draft model: {args.draft_model_dir}")

    draft_config = ExLlamaV2Config()
    draft_config.model_dir = args.draft_model_dir
    draft_config.prepare()

    if draft_config.max_seq_len < model.config.max_seq_len:

        if args.no_draft_scale:
            print(f" !! Warning: Draft model native max sequence length is less than sequence length for model. Speed may decrease after {draft_config.max_seq_len} tokens.")
        else:
            ratio = model.config.max_seq_len / draft_config.max_seq_len
            alpha = -0.13436 + 0.80541 * ratio + 0.28833 * ratio ** 2
            draft_config.scale_alpha_value = alpha
            print(f" -- Applying draft model RoPE alpha = {alpha:.4f}")

    draft_config.max_seq_len = model.config.max_seq_len
    draft_config.no_flash_attn = args.no_flash_attn

    print(" -- Loading draft model...")

    draft_model = ExLlamaV2(draft_config)
    draft_model.load()

    #if args.cache_8bit:
    draft_cache = ExLlamaV2Cache_8bit(draft_model)
    #else:
    #draft_cache = ExLlamaV2Cache(draft_model)

# Create cache

#if args.cache_8bit:
cache = ExLlamaV2Cache_8bit(model, lazy = not model.loaded)
#else:
    #cache = ExLlamaV2Cache(model, lazy = not model.loaded)

# Load model now if auto split enabled

if not model.loaded:

    print(" -- Loading model...")
    model.load_autosplit(cache)

# Chat context

def format_prompt(user_prompt, first):
    global system_prompt, prompt_format

    if first:
        return prompt_format.first_prompt() \
            .replace("<|system_prompt|>", system_prompt) \
            .replace("<|user_prompt|>", user_prompt)
    else:
        return prompt_format.subs_prompt() \
            .replace("<|user_prompt|>", user_prompt)

def encode_prompt(text):
    global tokenizer, prompt_format

    add_bos, add_eos, encode_special_tokens = prompt_format.encoding_options()
    return tokenizer.encode(text, add_bos = add_bos, add_eos = add_eos, encode_special_tokens = encode_special_tokens)

user_prompts = []
responses_ids = []

def get_tokenized_context(max_len):
    global user_prompts, responses_ids

    while True:

        context = torch.empty((1, 0), dtype=torch.long)

        for turn in range(len(user_prompts)):

            up_text = format_prompt(user_prompts[turn], context.shape[-1] == 0)
            up_ids = encode_prompt(up_text)
            context = torch.cat([context, up_ids], dim=-1)

            if turn < len(responses_ids):
                context = torch.cat([context, responses_ids[turn]], dim=-1)

        if context.shape[-1] < max_len: return context

        # If the context is too long, remove the first Q/A pair and try again. The system prompt will be moved to
        # the first entry in the truncated context

        user_prompts = user_prompts[1:]
        responses_ids = responses_ids[1:]

# Generator

generator = ExLlamaV2StreamingGenerator(model, cache, tokenizer, draft_model, draft_cache)

settings = ExLlamaV2Sampler.Settings()
settings.temperature = args.temperature
settings.top_k = args.top_k
settings.top_p = args.top_p
settings.typical = args.typical
settings.token_repetition_penalty = args.repetition_penalty

max_response_tokens = args.max_response_tokens
min_space_in_context = args.response_chunk

# Stop conditions

generator.set_stop_conditions(prompt_format.stop_conditions(tokenizer))

# ANSI color codes

col_default = "\u001b[0m"
col_user = "\u001b[33;1m"  # Yellow
col_bot = "\u001b[34;1m"  # Blue
col_error = "\u001b[31;1m"  # Magenta
col_sysprompt = "\u001b[37;1m"  # Grey

# Code block formatting

codeblock_formatter = None if args.no_code_formatting else CodeBlockFormatter()
in_code_block = False

delim_overflow = ""

# Other options

print_timings = args.print_timings

# Main loop

print(f" -- Prompt format: {args.mode}")
print(f" -- System prompt:")
print()
print(col_sysprompt + system_prompt.strip() + col_default)

from pydantic import BaseModel

class GenerateResponseModel(BaseModel):
    user_message: str
    username: str
    botname: str
    print_timings: Optional[bool] = False
    in_code_block: Optional[bool] = False

from fastapi.responses import StreamingResponse
from typing import Generator
import re

def get_first_prompt(text):
    match = re.search(r'\[image\](.*?)\[/image\]', text)
    return match.group(1) if match else None

def generate_prompt_response(user_message,username,botname,print_timings,in_code_block):
    col_default = "\u001b[0m"
    global responses_ids
    global user_prompts
    up = user_message
    response_output = ""
    responses_ids2 = responses_ids
    user_prompts2 = user_prompts
    user_prompts = []
    responses_ids = []
    user_prompts.append(up)
    # Send tokenized context to generator
    active_context = get_tokenized_context(model.config.max_seq_len - min_space_in_context)
    generator.begin_stream(active_context, settings)

    if prompt_format.print_bot_name():
        response_output += col_bot + botname + ": " + col_default

    if print_timings:
        time_begin_stream = time.time()
        if draft_model is not None:
            generator.reset_sd_stats()

    while True:
        chunk, eos, tokens = generator.stream()
        if eos:
            responses_ids = responses_ids2
            user_prompts = user_prompts2
            return response_output
        if len(response_output) == 0:
            chunk = chunk.lstrip()
        response_output += chunk
        continue

import re
@app.post("/generate_response/")
async def generate_response(data: GenerateResponseModel) -> StreamingResponse:
    def stream_output():
        global user_prompts
        global responses_ids
        user_message = data.user_message
        username = data.username
        botname = data.botname
        print_timings = data.print_timings
        in_code_block = data.in_code_block
        col_default = "\u001b[0m"

        if (user_message == "clear"):
            user_prompts = []
            responses_ids = []
            return
        pattern = r"inject_response=Q:(.*?)A:(.*)"
        match = re.match(pattern, user_message)

        if (user_message == "history"):
            ite = 0
            for response_tokens in responses_ids:
                response_text = tokenizer.decode(response_tokens[0])
                yield "USER: " + user_prompts[ite]
                yield "\n"
                yield "------------------"
                yield "\n"
                yield response_text
                yield "\n"
                ite = ite + 1
            return
        if match:
            question, response = match.groups()
            user_prompts = [question]
            response = tokenizer.encode(response)
            response_tokens = torch.tensor(response)
            responses_ids = [response_tokens]
            return

        phrases = ["generate an image", "create an image", "make an image", "want an image", "give me an image", "provide an image", "show me an image","generate me an image","generate a photo","create a photo","make a photo","generate a photo"]
        if any(phrase in user_message.lower() for phrase in phrases):
            final_message = '''
            I want you to parse an user message and put [image][/image] tags around image requests.

            Example input:
            "generate the image of a bear, my son wants to see it!"
            Output:
            [image]a bear[/image]
            Example input:
            "generate an image about oppeheimer, and write a 1000 word essay about him"
            Output:
            [image]oppeheimer[image]
            Example input:
            "I want an image of a beautiful woman in a red dress!"
            Output:
            [image]a beautiful woman in a red dress[/image]
            Example input:
            "Generate a photo of Obama."
            Output:
            [image]photography of Barack Obama[/image]

            Always using [image][/image] tags surrounding the parsed request!

            I need you to identify which image the user asked, and put [image][/image] prompts around it.
            Only provide a reply with the tags. Do not output anything else.

            The user asked this, identify the image and surround it with tags: '''"\""+user_message+"\""'''

            '''
            prompt = generate_prompt_response(final_message,username,botname,print_timings,in_code_block)
            prompt = get_first_prompt(prompt)
            try:
                stable_diffusion("best quality, 8k uhd,"+prompt)
            except:
                yield '''Sorry, there was a problem when I was trying to generate the image.'''
            # Read the 'generated_image.png' file that your code produced
            with open("generated_image.png", "rb") as image_file:
                # Convert the image to Base64
                encoded_string = base64.b64encode(image_file.read()).decode('utf-8')

            # Embed the Base64 string into the <img> tag
            if prompt:
                img_tag = f'''Generated an image with the prompt "{prompt}" : \n <img src="data:image/png;base64,{encoded_string}" alt="Embedded Image" />'''+"\n"
                yield img_tag
        up = user_message

        user_prompts.append(up)

        active_context = get_tokenized_context(model.config.max_seq_len - min_space_in_context)
        generator.begin_stream(active_context, settings)

        if prompt_format.print_bot_name():
            yield col_bot + botname + ": " + col_default

        response_tokens = 0
        response_text = ""
        responses_ids.append(torch.empty((1, 0), dtype = torch.long))

        if print_timings:
            time_begin_stream = time.time()
            if draft_model is not None:
                generator.reset_sd_stats()

        while True:
            chunk, eos, tokens = generator.stream()
            yield chunk
            if len(response_text) == 0: chunk = chunk.lstrip()
            response_text += chunk
            responses_ids[-1] = torch.cat([responses_ids[-1], tokens], dim=-1)

            chunk, codeblock_delimiter = (chunk, False) if codeblock_formatter is None else codeblock_formatter.process_delimiter(chunk)

            '''if not in_code_block and codeblock_delimiter:
                codeblock_formatter.begin()
                yield "\n"
                in_code_block = True
                codeblock_delimiter = False

            if in_code_block:
                yield codeblock_formatter.get_code_block(chunk)
            else:
                yield chunk

            if in_code_block and codeblock_delimiter:
                if eos: yield codeblock_formatter.get_code_block("\n")
                yield "\033[0m"
                in_code_block = False
                codeblock_delimiter = False
                '''

            if generator.full():
                active_context = get_tokenized_context(model.config.max_seq_len - min_space_in_context)
                generator.begin_stream(active_context, settings)

            response_tokens += 1
            if response_tokens == max_response_tokens:
                if tokenizer.eos_token_id in generator.stop_tokens:
                    responses_ids[-1] = torch.cat([responses_ids[-1], tokenizer.single_token(tokenizer.eos_token_id)], dim=-1)
                yield "\n"
                yield col_error + f" !! Response exceeded {max_response_tokens} tokens and was cut short." + col_default
                break

            if eos:
                if prompt_format.print_extra_newline():
                    yield "\n"
                break

        if print_timings:
            time_end_stream = time.time()
            speed = response_tokens / (time_end_stream - time_begin_stream)
            if draft_model is not None:
                eff, acc, _, _, _ = generator.get_sd_stats()
                sd_stats = f", SD eff. {eff*100:.2f}%, SD acc. {acc*100:.2f}%"
            else:
                sd_stats = ""
            yield "\n"
            yield col_sysprompt + f"(Response: {response_tokens} tokens, {speed:.2f} tokens/second{sd_stats})" + col_default

    return StreamingResponse(stream_output())

# If running the app directly
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)


#!/usr/bin/python3
#Poshmark Packing Slip Generator
#uses Poshmark order notification email as input
#Requires Python 3.7 and FPDF library

import argparse
import email
import quopri
import urllib.request

from html.parser import HTMLParser
from fpdf import FPDF

class Order():

  section = -1
  sections = []
  contents = []
  images = []

  def __init__(self, shipfrom, seller):
    self.add_section("Shipping From")
    for line in shipfrom:
      self.add_content(line)
    self.add_section("Seller")
    self.add_content(seller)
    self.add_section("header")

  def add_section(self, section):
    self.section += 1
    self.sections.append(section)
    self.contents.append([])
    self.images.append("")

  def add_content(self, content):
    if self.section > -1:
      self.contents[self.section].append(content)

  def add_image(self, url):
    if self.section > -1:
      self.images[self.section] = url

  def get_content(self, section, multiple=False):
    if multiple:
      result = []
      for index in range(0,len(self.sections)):
        if self.sections[index] == section:
          tuple = self.contents[index], self.images[index]
          result.append(tuple)
    elif section in self.sections:
      index = self.sections.index(section)
      result = self.contents[index]
    else:
      result = None
    return result

class PackSlip():

  def __init__(self, order):
    self.order = order

  def generate(self, pdf_name):
    self.left_margin = .75
    self.top_margin = 1
    self.pdf = FPDF("P", "in", "Letter")
    self.pdf.set_margins(self.left_margin, self.top_margin, self.left_margin)
    self.pdf.add_page()
    self.header()
    self.y = 3
    self.items()
    self.pdf.output(pdf_name)

  def header(self):
    self.pdf.set_font("Arial", "B", 24)
    self.pdf.cell(7, .5, "Packing Slip", 0, 1, 'C')
    self.heading("Shipping From", 0, .75, 3.5, 12)
    self.heading("Shipping To", 3.5, .75, 3.5, 12)
    self.heading("Seller", 0, 2, 1.5)
    self.heading("Buyer", 1.5, 2, 1.5)
    self.heading("Order Date", 3, 2, 1.5)
    self.heading("Order ID", 4.5, 2, 2.5)

  def heading(self, section, x=0, y=0, w=7, p=11):
    if y: self.pdf.set_y(y + self.top_margin)
    if x: self.pdf.set_x(x + self.left_margin)
    self.pdf.set_font("Arial", "B", p)
    self.pdf.cell(w, .25, section, 0, 2, 'L')
    contents = self.order.get_content(section)
    self.block(contents, w, .2, p)

  def block(self, lines, w=7, h=.2, p=11):
    self.pdf.set_font("Arial", "", p)
    for line in lines:
      self.pdf.cell(w, h, line, 0, 2, 'L')

  def items(self):
    items = self.order.get_content("Item", True)
    for item in items:
      self.item(item)
      self.y = self.y + 1

  def item(self, item):
    content, image = item
    x = self.left_margin
    y = self.y + self.top_margin
    self.pdf.image(image, x, y, .75, .75)
    self.pdf.set_xy(x+1, y)
    self.block(content[1:4], 6, .25)

  def print_items(self):
    items = self.order.get_content("Item", True)
    for item in items:
      self.print_item(item)

  def print_item(self, item):
    content, image = item
    print("Item")
    print(" ", image)
    for index in range(1,4):
      print(" ", content[index])

class Tag():

  name = ""
  attrs = {}
  sections = ["Shipping To", "Order Date", "Order ID", "Buyer", "Item"]

  def __init__(self, order):
    self.order = order

  def attr(self, name):
    for (key, value) in self.attrs:
      if key == name: return value
    return None

  def start(self):
    if self.name == "img":
      #if self.attr("alt") == "Poshmark":
      #  print("Logo URL:", self.attr("src"))
      if self.attr("width") == "75":
        self.order.add_image(self.attr("src"))
        #print("Item URL:", self.attr("src"))

  def data(self, data):
    if self.name == "td":
      section = data.strip()
      if section in self.sections:
        self.order.add_section(section)
        #print("Section: ", data)
      else:
        if data.strip() != "":
          self.order.add_content(data)
          #print("   Data: ", data)

class Parser(HTMLParser):
  def __init__(self, order):
    self.order = order
    self.tag = None
    self.tags = []
    super().__init__()

  def handle_starttag(self, tag, attrs):
    self.tags.append(self.tag)
    self.tag = Tag(self.order)
    self.tag.name = tag
    self.tag.attrs = attrs
    self.tag.start()

  def handle_endtag(self, tag):
    if self.tag != None:
      self.tag = self.tags.pop()

  def handle_data(self, data):
    if self.tag != None:
      self.tag.data(data);

def email_html(file):
  infile = open(file, "rb")
  message = email.message_from_binary_file(infile)
  if message.is_multipart():
    for part in message.get_payload():
      body = part.get_payload()
      break
  else:
    body = message.get_payload(decode=True)
  return quopri.decodestring(body).decode()

def packslip_from_email(email, pdf):
  shipfrom = ["Curtis F Kaylor", "159 Hunter Ave", "Munroe Falls OH 44262"]
  seller = "@revcurtisp"
  order = Order(shipfrom, seller)
  parser = Parser(order)
  html = email_html(email)
  parser.feed(html)
  packslip = PackSlip(order)
  packslip.generate(pdf)

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument("emlfile", help="Input File Name (with .eml extension)")
  parser.add_argument("pdffile", help="Output File Name (with .pdf extension)")
  args = parser.parse_args()

  packslip_from_email(args.emlfile, args.pdffile)

if __name__ == "__main__":
    main()


from discriminator import *
from utils import *
from data import *
from checkers import *
from logger import *

# суть эксперимента: для выбранных вручную разынх точек напечатать
# значения их дискриминантной силы при заданном радусе/сайде
def make_experiment(X, Y, parent_x, parent_y,  side, radius):
    #pics = get_diverse_set_of_numbers(104)[0:100]
    pics = get_numbers_of_type(3)[0:10]
    #pics = etalons_of3()
    pic = etalons_of3()[0]
    nbins = 10

    descriptor = get_descriptor(pic, x=parent_x, y=parent_y, side=1)
    hypotheses_list = init_hypos_const_side(pic, X,Y, side, radius, parent_x, parent_y)
    evaluations = eval_many_hypos_for_descriptor(pics, hypotheses_list, descriptor, nbins)
    return evaluations

def get_descriptor(pic, x, y, side):
    pics_for_stat = get_diverse_set_of_numbers(20)
    checker = check_mean
    A = init_descriptor(pic, x, y, side, checker, pics_for_stat)
    return A

def init_hypos_const_side(pic, X,Y, side, radius,parent_x, parent_y):
    checker = check_mean
    pics_for_stat = get_diverse_set_of_numbers(20)
    hypotheses_list = []
    for i in range(0, len(X)):
        hypo = init_hypo(side, checker, pics_for_stat, pic, X[i], Y[i], parent_x, parent_y, radius)
        hypotheses_list.append(hypo)
    return hypotheses_list

def visualise_evals_at_fig(X,Y,list_of_evals, pic_shape):
    num_pics = len(list_of_evals)
    cm = plt.cm.get_cmap('RdYlBu')
    max, min = np.array(list_of_evals).max(),np.array(list_of_evals).min()

    fig, ax = plt.subplots(num_pics)
    for i in range(num_pics):
        res = np.zeros(pic_shape)
        evals = list_of_evals[i]
        ax[i].imshow(res, cmap='gray_r')
        sc = ax[i].scatter(X, Y, s=100, c=evals, marker='o', vmax=max, vmin=min, alpha=0.4, cmap=cm)
    plt.colorbar(sc)
    return fig

if __name__ == "__main__":
    logger = HtmlLogger("mean2")
    pic = etalons_of3()[0]
    X,Y = select_coord_on_pic(pic)
    fig = visualise_points_on_fig(pic, X, Y)
    logger.add_fig(fig)
    list_of_evals=[]
    parentX = X[0]
    parentY = Y[0]
    X=X[1:]
    Y=Y[1:]

    radius = 0
    logger.add_text("radius = "+ str(radius))
    evals1 = make_experiment(X,Y, parent_x=parentX, parent_y=parentY, side=2, radius=radius)
    logger.add_text(str(X) + ", Y=" + str(Y) )
    logger.add_text("evals: " + str(evals1))
    list_of_evals.append(evals1)

    radius = 1
    logger.add_text("radius = " + str(radius))
    evals2 = make_experiment(X,Y, parent_x=parentX, parent_y=parentY, side=2, radius=radius)
    logger.add_text(str(X) + ", Y=" + str(Y))
    logger.add_text("evals: " + str(evals2))
    list_of_evals.append(evals2)

    fig = visualise_evals_at_fig(X, Y, list_of_evals, pic.shape)
    logger.add_fig(fig)

    logger.close()


# !/usr/bin/Python

# website: http://pythonprogramminglanguage.com/socket-server-network

'''
A server can be created using sockets.
Sockets work on the application layer,
it does not specify any protocol and on this level
you’d define an application protocol yourself.
'''

import socket
import sys

'''
The steps:
1. bind socket to port
2. start listening
3. wait for client
4. receive data
'''

HOST = ''
PORT = 8000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("# Socket created")

# Create sockt on port
try:
    s.bind((HOST, PORT))
except s.error as msg:
    print("# Bind Failed")
    sys.exit()

print("# Socket bind complete")

# Start listening on socket
s.listen(10)
print("# Socket now listening")

# Wait for client
conn, addr = s.accept()
print("# Connected to " + addr[0] + ":" + str(addr[1]))

# Receive data from client
while True:
    data = conn.recv(1024)
    line = data.decode("utf-8") # convert to string (Python 3 only)
    line = line.replace("\n", "") # remove newline character
    print(line)

s.close()


import os
# A lista
lista = []
#Funções:
def adicionar(lista):
    while True:
        nova_add = input('Adicione os novos objetos: ')
        if nova_add == '':
            print('Sua lista não pode estar vazia!')
            continue
        if nova_add == 'sair':
            break
        else:
            os.system('cls')
            lista.append(nova_add)
            print('Sua lista:')
            listar(lista)
def remover(lista):
    os.system('cls')
    listar(lista)
    remover = input(f'Selecione uma das opções acima para remover: ')
    indice = int(remover)
    del lista[indice]
    listar(lista)
def listar(lista):
    for i, valor in enumerate(lista):
        print(i, valor)
#O loop
while True:
    os.system('cls')
    if lista == []:
        print('Sua lista está vazia!')
    else:
        print('Sua lista:')
    listar(lista)
    print('Escolha uma das opções abaixo!')
    op =  input('(A)dicionar (R)emover ').capitalize()
    if op == 'A' or 'R':
        ...
    else:
        print('Selecione uma das opções válidas!')
    if op == 'A':
        os.system('cls')
        adicionar(lista)
    elif op == 'R':
        remover(lista)
    else:
        print('Selecione uma das opções válidas!')
#Fim do loop


import sys
import collections

def bfs():

    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    queue.append((0, 0, 0))
    is_visited[0][0][0] = 1

    while len(queue) != 0:

        cur = queue.popleft()
        (is_broken, i, j) = cur

        if (i, j) == (n - 1, m - 1):
            return is_visited[is_broken][i][j]

        for (next_i, next_j) in [(i + _dir[0], j + _dir[1]) for _dir in directions]:

            if next_i < 0 or next_i > (n - 1) or next_j < 0 or next_j > (m - 1) :

                continue

            if is_visited[is_broken][next_i][next_j] != 0:

                continue

            if maze[next_i][next_j] == 0 and is_visited[is_broken][next_i][next_j] == 0:

                is_visited[is_broken][next_i][next_j] = is_visited[is_broken][i][j] + 1
                queue.append((is_broken, next_i, next_j))
                continue

            if maze[next_i][next_j] == 1 and  is_broken == 0:

                is_visited[1][next_i][next_j] = is_visited[is_broken][i][j] + 1
                queue.append((1, next_i, next_j))
                continue

    return -1

n, m = map(int, input().split())
maze = [(list(map(int, list(input())))) for _ in range(n)]
is_visited = [[[0] * m for __ in range(n)] for _ in range(2)]
queue = collections.deque()
print(bfs())

백준/Gold/2206.벽 부수고 이동하기/벽 부수고 이동하기.py

벽 부수고 이동하기.py