import torch

from torch.nn import BCELoss
from vegans.utils import WassersteinLoss
from vegans.utils.networks import Generator, Adversary, Encoder
from vegans.models.unconditional.AbstractGenerativeModel import AbstractGenerativeModel

class AbstractGANGAE(AbstractGenerativeModel):
    """ Abstract class for GAN with structure of one generator, one discriminator / critic and
    one encoder. Examples are the `LRGAN`, `VAEGAN` and `BicycleGAN`.

    Parameters
    ----------
    generator: nn.Module
        Generator architecture. Produces output in the real space.
    adversary: nn.Module
        Adversary architecture. Produces predictions for real and fake samples to differentiate them.
    encoder : nn.Module
        Encoder architecture. Produces predictions in the latent space.
    x_dim : list, tuple
        Number of the output dimensions of the generator and input dimension of the discriminator / critic.
        In the case of images this will be [nr_channels, nr_height_pixels, nr_width_pixels].
    z_dim : int, list, tuple
        Number of the latent dimensions for the generator input. Might have dimensions of an image.
    optim : dict or torch.optim
        Optimizer used for each network. Could be either an optimizer from torch.optim or a dictionary with network
        name keys and torch.optim as value, i.e. {"Generator": torch.optim.Adam}.
    optim_kwargs : dict
        Optimizer keyword arguments used for each network. Must be a dictionary with network
        name keys and dictionary with keyword arguments as value, i.e. {"Generator": {"lr": 0.0001}}.
    feature_layer : torch.nn.*
        Output layer used to compute the feature loss. Should be from either the discriminator or critic.
        If `feature_layer` is not None, the original generator loss is replaced by a feature loss, introduced
        [here](https://arxiv.org/abs/1606.03498v1).
    fixed_noise_size : int
        Number of images shown when logging. The fixed noise is used to produce the images in the folder/images
        subdirectory, the tensorboard images tab and the samples in get_training_results().
    lambda_grad: float
        Weight for the reconstruction loss of the gradients. Pushes the norm of the gradients to 1.
    device : string
        Device used while training the model. Either "cpu" or "cuda".
    ngpu : int
        Number of gpus used during training if device == "cuda".
    folder : string
        Creates a folder in the current working directory with this name. All relevant files like summary, images, models and
        tensorboard output are written there. Existing folders are never overwritten or deleted. If a folder with the same name
        already exists a time stamp is appended to make it unique.
    """

    #########################################################################
    # Actions before training
    #########################################################################
    def __init__(
            self,
            generator,
            adversary,
            encoder,
            x_dim,
            z_dim,
            optim=None,
            optim_kwargs=None,
            adv_type="Discriminator",
            feature_layer=None,
            fixed_noise_size=32,
            device=None,
            folder=None,
            ngpu=0,
            secure=True,
            _called_from_conditional=False):

        self.adv_type = adv_type
        self.generator = Generator(generator, input_size=z_dim, device=device, ngpu=ngpu, secure=secure)
        self.adversary = Adversary(adversary, input_size=x_dim, adv_type=adv_type, device=device, ngpu=ngpu, secure=secure)
        self.encoder = Encoder(encoder, input_size=x_dim, device=device, ngpu=ngpu, secure=secure)
        self.neural_nets = {
            "Generator": self.generator, "Adversary": self.adversary, "Encoder": self.encoder
        }

        super().__init__(
            x_dim=x_dim, z_dim=z_dim, optim=optim, optim_kwargs=optim_kwargs, feature_layer=feature_layer,
            fixed_noise_size=fixed_noise_size, device=device, ngpu=ngpu, folder=folder, secure=secure
        )
        self.hyperparameters["adv_type"] = adv_type
        if not _called_from_conditional and self.secure:
            assert self.generator.output_size == self.x_dim, (
                "Generator output shape must be equal to x_dim. {} vs. {}.".format(self.generator.output_size, self.x_dim)
            )

    def _define_loss(self):
        if self.adv_type == "Discriminator":
            loss_functions = {"Generator": BCELoss(), "Adversary": BCELoss()}
        elif self.adv_type == "Critic":
            loss_functions = {"Generator": WassersteinLoss(), "Adversary": WassersteinLoss()}
        else:
            raise NotImplementedError("'adv_type' must be one of Discriminator or Critic.")
        return loss_functions

    #########################################################################
    # Actions during training
    #########################################################################
    def calculate_losses(self, X_batch, Z_batch, who=None):
        """ Calculates the losses for GANs using a 1v1 architecture.

        This method is called within the `AbstractGenerativeModel` main `fit()` loop.

        Parameters
        ----------
        X_batch : torch.Tensor
            Current x batch.
        Z_batch : torch.Tensor
            Current z batch.
        who : None, optional
            Name of the network that should be trained.
        """
        if who == "Generator":
            losses = self._calculate_generator_loss(X_batch=X_batch, Z_batch=Z_batch)
        elif who == "Adversary":
            losses = self._calculate_adversary_loss(X_batch=X_batch, Z_batch=Z_batch)
        elif who == "Encoder":
            losses = self._calculate_encoder_loss(X_batch=X_batch, Z_batch=Z_batch)
        else:
            losses = self._calculate_generator_loss(X_batch=X_batch, Z_batch=Z_batch)
            losses.update(self._calculate_adversary_loss(X_batch=X_batch, Z_batch=Z_batch))
            losses.update(self._calculate_encoder_loss(X_batch=X_batch, Z_batch=Z_batch))
        return losses

    def _step(self, who=None):
        if who is not None:
            self.optimizers[who].step()
            if who == "Adversary":
                if self.adv_type == "Critic":
                    for p in self.adversary.parameters():
                        p.data.clamp_(-0.01, 0.01)
        else:
            [optimizer.step() for _, optimizer in self.optimizers.items()]

    #########################################################################
    # Utility functions
    #########################################################################
    def encode(self, x):
        return self.encoder(x)


from flask import Blueprint

from app import models
from app.utils import send_result

api = Blueprint('categories', __name__)

# categories = [
#     {'id': 1, 'name': "birthday cake",
#      'subcategory':
#          [
#              {
#                  "sub_id": 1,
#                  "sub_name": "chiffon cake"
#              },
#              {
#                  "sub_id": 2,
#                  "sub_name": "pound cake"
#              },
#              {
#                  "sub_id": 3,
#                  "sub_name": "fruit cake"
#              }
#          ]
#      }
# ]

@api.route('', methods=['GET'])
def get_all():
    t = [x.json() for x in models.Category.query.all()]
    for i in t:
        i["subcategory"] = [x.json() for x in models.Subcategory.get_by_id_category(i['id'])]
    return send_result(t)


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

class BossproPipeline(object):
    f1,f2 = None,None
    def open_spider(self,spider):
        self.f1 = open('a.txt','w',encoding='utf-8')
        self.f2 = open('b.txt', 'w', encoding='utf-8')
    def process_item(self, item, spider):

        #item在同一时刻只可以接收到某一个指定item对象
        if item.__class__.__name__ == 'FirstItem':
            job_title = item['job_title']
            self.f1.write(job_title+'\n')
        else:
            job_desc = item['job_desc']
            self.f2.write(job_desc)
        return item


import torch
import torch.nn as nn

from typing import Optional

from .attention_block import CrossAttentionBlock

class PerceiverDecoder(nn.Module):

    def __init__(
        self,
        latent_dim: int,
        q_dim: int,
        heads: int = 4,
        qk_out_dim: Optional[int] = None,
        v_out_dim: Optional[int] = None,
        projection_dim: Optional[int] = None,
        cross_attn_widening_factor: int = 1,
        dropout: float = 0.0
        ):

        super().__init__()
        self.cross_attn = CrossAttentionBlock(
            q_dim=q_dim,
            kv_dim=latent_dim,
            qk_out_dim=qk_out_dim,
            v_out_dim=v_out_dim,
            heads=heads,
            widening_factor=cross_attn_widening_factor,
            dropout=dropout
        )

        if projection_dim is not None:
            self.projection = nn.Linear(q_dim, projection_dim)
        else:
            self.projection = nn.Identity()

    def forward(self, x_q: torch.Tensor, latents: torch.Tensor, query_mask: Optional[torch.Tensor] = None):

        output = self.cross_attn(
            x_q=x_q,
            x_kv=latents,
            attention_mask=query_mask
        )

        return self.projection(output)


from flask import Flask, request, render_template, jsonify
from flask_restful import Api, Resource, reqparse, abort
from flask_sqlalchemy import SQLAlchemy
import sys

app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)

class UserModel(db.Model):
    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(30), nullable=False)

    def __repr__(self):
        return f"User(username = {username})"

class RoomModel(db.Model):
    room_id = db.Column(db.Integer, primary_key=True)
    roomname = db.Column(db.String(30), nullable=False)

    def __repr__(self):
        return f"Room(roomname = {roomname})"

db.drop_all()
db.create_all()

roomMessages = []
listOfMessages = []
listOfUsers = []
messages = []

listRoom = []
listRoomUser = []
listRoomOwner = []
nestedListuser = []
loggedin = ''
currentRoom = ''

class UserMessage:
    def __init__(self, user_id, message):
        self.user_id = user_id
        self.message = message

    def __repr__(self):
        return f"Message(message = {message})"

    def __str__(self):
        return f"Message(message = {message})"

@app.route("/", methods=['GET', 'POST'])
def index():
    return render_template('login.html', uservalues=UserModel.query.all())

@app.route("/goback", methods=['GET', 'POST'])
def goBack():
    global nestedListuser
    global loggedin
    return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, loggedin=loggedin, listRoomUser=listRoomUser)

@app.route("/api/users", methods=['GET', 'POST'])
def adduser():
    if request.method == 'POST':
        name=request.form['username']
        user_id=UserModel(username=name)
        user = UserModel(user_id=user_id.user_id, username=name)
        db.session.add(user)
        db.session.commit()
        listOfUsers.append(user.user_id)
        return render_template('login.html', uservalues=UserModel.query.all())
    else: return render_template('login.html', uservalues=UserModel.query.all())

@app.route("/api/users/<string:name>", methods=['GET', 'POST'])
def addclientuser(name):
    global loggedin
    user_id=UserModel(username=name)
    user = UserModel(user_id=user_id.user_id, username=name)
    db.session.add(user)
    db.session.commit()
    loggedin = user.user_id
    listOfUsers.append(user.user_id)
    return str(loggedin)

@app.route("/api/userlogin/<int:user_id>")
def login(user_id):
    global loggedin
    loggedin = user_id
    return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), loggedin=loggedin, listRoomUser=listRoomUser)

@app.route("/api/user/<int:user_id>")
def deleteuser(user_id):
    try:
        user = UserModel.query.filter_by(user_id=user_id).delete()
        db.session.commit()
        listOfUsers.remove(user.user_id)
        return render_template('login.html', uservalues=UserModel.query.all())
    except: abort(404, message="User ID is not valid")

@app.route("/api/rooms", methods=['GET', 'POST'])
def addroom():
    global listRoom
    global listRoomUser
    global listRoomOwner
    global nestedListuser
    global loggedin
    if request.method == 'POST':
        name=request.form['roomname']
        room_id=RoomModel(roomname=name)
        room = RoomModel(room_id=room_id.room_id, roomname=name)
        db.session.add(room)
        db.session.commit()
        listRoom.append(room.room_id)
        listRoomUser.append([])
        roomMessages.append([])
        return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, loggedin=loggedin, listRoomUser=listRoomUser)
    else: return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, loggedin=loggedin, listRoomUser=listRoomUser)

@app.route("/api/rooms/<string:name>", methods=['GET', 'POST'])
def addclientroom(name):
    global listRoom
    global listRoomUser
    room_id=RoomModel(roomname=name)
    room = RoomModel(room_id=room_id.room_id, roomname=name)
    db.session.add(room)
    db.session.commit()
    listRoom.append(room.room_id)
    listRoomUser.append([])
    roomMessages.append([])
    return str(room.room_id)

@app.route("/api/room/<int:room_id>", methods=['GET'])
def getroom(room_id):
    currentRoom = room_id
    return render_template('room.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, messages=listOfMessages, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages, listRoomUser=listRoomUser)

@app.route("/api/room/<int:room_id>/messages", methods=['GET'])
def onlygetmessage(room_id):
    global nestedListuser
    global loggedin
    global listOfMessages
    a = listRoom.index(room_id)
    listOfMessages = roomMessages[a]
    return render_template('chatroom.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)

@app.route("/api/room/<int:room_id>/<int:user_id>/messages", methods=['GET', 'POST'])
def message(room_id, user_id):
    global nestedListuser
    global loggedin
    global listOfMessages
    if user_id in listOfUsers:
        try:
            if request.method == 'POST':
                inMessage=request.form['message']
                m = UserMessage(user_id, inMessage)
                a = listRoom.index(room_id)
                listOfMessages = roomMessages[a]
                listOfMessages.append(m)
                return render_template('chatroom.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)
            return render_template('chatroom.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)
        except:
            return render_template('room.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)
    else: abort(404, message="User id does not exist")

@app.route("/api/room/<string:message>/<int:room_id>/<int:user_id>/messages", methods=['GET', 'POST'])
def messageclient(message, room_id, user_id):
    global nestedListuser
    global listOfMessages
    try:
        m = UserMessage(user_id, message)
        a = listRoom.index(room_id)
        listOfMessages = roomMessages[a]
        listOfMessages.append(m)
        return render_template('room.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)
    except:
        return render_template('room.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)

@app.route("/api/room/<int:room_id>/users", methods=['GET', 'POST'])
def roomusers(room_id):
    global listRoomUser
    global listRoom
    global loggedin
    global nestedListuser
    global currentRoom
    try:
        currentRoom = room_id
        a = listRoom.index(room_id)
        nestedListuser = listRoomUser[a]
        nestedListuser.append(loggedin)
        return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, messages=listOfMessages, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages, listRoomUser=listRoomUser)
    except:
        return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, messages=listOfMessages, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages, listRoomUser=listRoomUser)

@app.route("/api/room/<int:room_id>/<int:user_id>/fetch", methods=['GET', 'POST'])
def fetchMessages(room_id, user_id):
    m = UserMessage(user_id, message)
    a = listRoom.index(room_id)
    listOfMessages = roomMessages[a]
    messagesarray = []
    for mes in listOfMessages:
        messagesarray.append(mes.message)
    return jsonify(messagesarray)

@app.route("/api/room/fetch", methods=['GET'])
def fetchAllMessages():
    allMessages = []
    nestedMessages = []
    for i in listRoom:
        allMessages.append([])

    for mes in roomMessages:
        for j in mes:
            allMessages[roomMessages.index(mes)].append(j.message)
    return jsonify(allMessages)

@app.route("/api/room/fetchRoom_idList", methods=['GET'])
def fetchlistOfRoom_id():
    return jsonify(listRoom)

@app.route("/api/room/fetchRoomUsers", methods=['GET'])
def fetchRoomUsers():
    return jsonify(listRoomUser)

if __name__ == "__main__":
    app.run(debug=True)


import numpy as np
import matplotlib.pyplot as plt
import os.path
import csv
import numpy as np
import argparse
from Bio import SeqIO
import RNA
import matplotlib.pyplot as plt
import numpy as np

class DNA(object):
    """
    The DNA class represents a DNA sequence in a biological context.

    Class Attributes:
    dna_alphabet : set
        The nucleotides that can be found in a DNA sequence (Adenine, Guanine, Cytosine, Thymine, and N for unknown).

    Instance Attributes:
    sequence : str
        A string representing the DNA sequence. All characters are automatically converted to upper-case.

    Methods:
    __len__:
        Returns the length of the DNA sequence.
    __getitem__:
        Allows indexing into the DNA sequence.
    __hash__:
        Returns a hash value of the DNA sequence.
    __repr__:
        Returns a string representation of the DNA sequence.
    __eq__:
        Determines if two DNA objects have the same DNA sequence.

    Note: The DNA sequence should only contain characters that are in the dna_alphabet.
    No checks for invalid characters are performed.
    """

    dna_alphabet = set("AGCTN")

    def __init__(self, sequence):
        self.sequence = sequence.upper()

    def __len__(self):
        return len(self.sequence)

    def __getitem__(self, key):
        return self.sequence[key]

    def __hash__(self):
        return hash(self.sequence)

    def __repr__(self):
        return self.sequence

    def __eq__(self, other):
        return self.sequence == other.sequence

class SingleAlignment(object):
    """
    The SingleAlignment class represents a single alignment of a small RNA (sRNA) sequence against a reference sequence.

    Each instance of the class reflects an exact match and carries a list of floating-point counts representing the number of sRNAs
    from each input read file that align at this location.

    Attributes:
    srna : DNA
        The DNA object representing the sRNA read.
    position : int
        The position in the reference sequence where the sRNA read aligns.
    strand : str
        The DNA strand ('+' or '-') where the sRNA read aligns.
    times_aligned : int
        The total number of positions the sRNA read can align to across all reference sequences.
    indv_alignments : list of float
        A numpy array of floating-point counts representing sRNA count for each individual sample.  Float as may be reads per million reads

    Methods:
    srna_len():
        Returns the length of the sRNA read.
    standard_error():
        Calculates the standard error of the individual alignment counts.
    mean_alignments():
        Calculates the mean of the individual alignment counts
    __str__():
        Returns a string representation of the SingleAlignment object, suitable for output.
    __repr__():
        Returns the same as __str__(), a string representation of the object.
    __eq__():
        Determines if two SingleAlignment objects are identical, including their individual alignments.
    """

    def __init__(self, srna, position, strand, times_aligned, indv_alignments):
        self.srna = srna
        self.position = position
        self.strand = strand
        self.times_aligned = times_aligned
        self.indv_alignments = indv_alignments

    def srna_len(self):
        return len(self.srna)

    def standard_error(self):  # TODO: check - likely don't neeed here
        return np.std(self.indv_alignments, ddof=1) / np.sqrt(
            np.size(self.indv_alignments)
        )

    def mean_alignments(self):
        return np.mean(self.indv_alignments)

    def __str__(self):
        return "{0}\t{1}\t{2}\t{3}\t{4}".format(
            self.srna,
            self.position,
            self.strand,
            self.times_aligned,
            self.indv_alignments,
        )

    def __repr__(self):
        return self.__str__()

    def __eq__(self, other):
        return (
            self.srna == other.srna
            and self.position == other.position
            and self.strand == other.strand
            and self.times_aligned == other.times_aligned
            and np.array_equal(self.indv_alignments, other.indv_alignments)
        )

class SingleRefProfile(object):
    """
    The SingleRefProfile class encapsulates the alignment profile of a single reference sequence.

    This class stores the length of the reference sequence, the number of replicates, the length of sRNA, and a list of all sRNA alignments against this reference.

    Attributes:
    ref_len : int
        The length of the reference sequence.
    replicates : int
        The number of replicates.
    srna_len : int
        The length of sRNA.
    all_alignments : list of SingleAlignment objects
        A list of SingleAlignment objects representing all sRNA alignments against the reference sequence.

    Methods:
    __str__():
        Returns a string representation of the SingleRefProfile object, suitable for output.
    __repr__():
        Returns the same as __str__(), a string representation of the object.
    __eq__(other: SingleRefProfile) -> bool:
        Determines if two SingleRefProfile objects are identical, including their list of alignments.
        `other` is the other SingleRefProfile object to compare with.
    """

    def __init__(self):
        self.ref_len = 0
        self.replicates = 0
        self.srna_len = 0
        self.all_alignments = []

    def __str__(self):
        return "{0}\t{1}".format(self.ref_len, self.all_alignments)

    def __repr__(self):
        return self.__str__()

    def __eq__(self, other):
        return (
            self.ref_len == other.ref_len
            and self.all_alignments == other.all_alignments
            and self.replicates == other.replicates
            and self.snra_len == other.srna_len
        )

class RefProfiles(object):
    """
    The RefProfiles class represents the alignment profiles for all reference sequences in an alignment file of a set read or sRNA length.

    This class stores the length of the small RNA read (sRNA), the number of replicates, and a dictionary containing SingleRefProfile
    objects for each reference sequence.

    Attributes:
    srna_len : int
        The length of the sRNA.
    replicates : int
        The number of replicate samples.
    single_ref_profiles : dict
        A dictionary where keys are reference sequence headers and values are SingleRefProfile objects representing the alignment profile for each reference sequence.

    Methods:
    __str__():
        Returns a string representation of the RefProfiles object, suitable for output.
    __eq__():
        Determines if two RefProfiles objects are identical.
    load_single_ref_profiles(in_file):
        Loads alignment profiles from a given scram2 profile file. Each line of the file represents a SingleAlignment of a sRNA read.
    """

    def __init__(self):
        self.srna_len = 0
        self.replicates = 0
        self.single_ref_profiles = {}

    def __str__(self):
        return "{0}\t{1}\t{2}".format(
            self.srna_len, self.replicates, self.single_ref_profiles
        )

    def __eq__(self, other):
        return (
            self.replicates == other.replicates
            and self.single_ref_profiles == other.single_ref_profiles
            and self.srna_len == other.srna_len
        )

    def load_single_ref_profiles(
        self, in_file, header=None, start=None, end=None, padding=0
    ):
        """Loads a scram2 profile file for a single sRNA length

        Args:
            in_file (string): scram2 profile file path
            header (string): specific header to be parsed
            start (int): start position of the range
            end (int): end position of the range
            padding (int): number of base pairs to include on either end of the range
        """
        try:
            with open(in_file, "r") as in_handle:
                reader = csv.reader(in_handle, delimiter=",")
                for row in reader:
                    if row[0] == "Header":
                        continue
                    (
                        row_header,
                        ref_len,
                        srna,
                        position,
                        strand,
                        times_aligned,
                        *indv_alignments,
                    ) = row
                    row_header = row_header.split()[0]
                    # Skip alignments that do not match the input header or are outside the input positions
                    if header is not None and row_header != header:
                        continue
                    if (
                        start is not None
                        and end is not None
                        and (
                            int(position) < start - padding
                            or int(position) > end + padding
                        )
                    ):
                        continue

                    # Construct a SingleAlignment object

                    srna = DNA(srna)
                    times_aligned = int(times_aligned)
                    ref_len = int(ref_len)
                    position = int(position)
                    if start is not None:
                        position = (
                            position - start + padding
                        )  # New position relative to the start of the subset
                        ref_len = end - start + 2 * padding  # New reference length
                    indv_alignments = np.array([float(x) for x in indv_alignments])
                    sa = SingleAlignment(
                        srna, position, strand, times_aligned, indv_alignments
                    )

                    # Add the SingleAlignment to the corresponding SingleRefProfile
                    if row_header not in self.single_ref_profiles:
                        self.single_ref_profiles[row_header] = SingleRefProfile()
                        self.single_ref_profiles[row_header].ref_len = ref_len
                        self.single_ref_profiles[row_header].replicates = len(
                            indv_alignments
                        )
                        self.single_ref_profiles[row_header].srna_len = len(srna)
                        self.srna_len = len(srna)
                    self.single_ref_profiles[row_header].all_alignments.append(sa)

                # Set the number of replicates based on the last read alignment
                if "sa" in locals():
                    self.replicates = len(sa.indv_alignments)
                else:
                    raise ValueError("The input file does not contain any alignments")
        except FileNotFoundError:
            print(f"The input file {in_file} does not exist. Skipping.")
        except Exception as e:
            print(f"An error occurred while processing the input file {in_file}: {e}")

class SectStruct(object):
    """
    Seconday structure data
    """

    def __init__(self, ref_file, header, start=None, end=None):
        self.ref_file = ref_file
        self.header = header
        self.start = start
        self.end = end
        self.sequence = None
        self.structure = None
        self.pairs = []
        self._get_sequence()
        self.length = len(self.sequence)
        self._get_structure()
        self._get_pairs()

    def _get_sequence(self):
        for seq_record in SeqIO.parse(self.ref_file, "fasta"):
            if seq_record.id == self.header:
                if self.start is None or self.end is None:
                    self.sequence = str(seq_record.seq)
                else:
                    self.sequence = str(seq_record.seq[self.start : self.end])

    def _get_structure(self):
        self.structure, _ = RNA.fold(self.sequence)

    def _get_pairs(self):
        stack = []
        for i, char in enumerate(self.structure):
            if char == "(":
                stack.append(i + 1)  # index starts from 1
            elif char == ")":
                start = stack.pop()
                end = i + 1  # index starts from 1
                self.pairs.append((start, end))

class DataForPlot(object):
    """
    Data for plotting class
    """

    def __init__(self, ref_profiles, header):
        self.ref_profiles = ref_profiles
        self.header = header
        self.ref_len = ref_profiles.single_ref_profiles[header].ref_len
        self.srna_len = ref_profiles.srna_len
        self.replicates = ref_profiles.replicates
        self.fwd = np.zeros((self.ref_len + 1, self.replicates), dtype=float)
        self.rvs = np.zeros((self.ref_len + 1, self.replicates), dtype=float)
        self.x_axis = list(range(len(self.fwd)))
        self.y_flat = []
        self._extract_from_ref_profiles()

    def _extract_from_ref_profiles(self):
        """Extracts data from a ref profiles object

        Args:
            ref_profiles (RefProfiles): ref profiles object
            header (string): header of the reference sequence
        """
        for sa in self.ref_profiles.single_ref_profiles[self.header].all_alignments:
            if sa.strand == "+":
                self.fwd[sa.position] = sa.indv_alignments
            else:
                self.rvs[sa.position] = sa.indv_alignments

    def convert_to_coverage(self, abund=True):
        """
        TODO: Fix
        """
        self.fwd = self._coverage_per_strand(self.fwd, abund)
        self.rvs = self._coverage_per_strand(self.rvs, abund)

    def _coverage_per_strand(
        self, old_array, abund
    ):  # TODO: Fix for better use of numpy
        """

        Args:
            old_array (_type_): _description_
        """
        new_arr = np.zeros((old_array.shape), dtype=float)
        for i in range(len(new_arr) - self.srna_len + 1):
            for j in range(len(new_arr[i])):
                if not abund:
                    new_arr[i : i + self.srna_len, j] += old_array[i, j]
                else:
                    for k in range(self.srna_len):
                        if old_array[i, j] > new_arr[i + k, j]:
                            new_arr[i + k, j] = old_array[i, j]
        return new_arr

    def convert_to_error_bounds(self):  # TODO: document and test
        """_summary_"""
        self.fwd = self._error_bounds(self.fwd)
        self.rvs = self._error_bounds(self.rvs)

    def _error_bounds(self, old_array):  # TODO: document and test
        """_summary_"""
        new_arr = np.zeros((self.ref_len + 1, 2), dtype=float)
        for i in range(len(new_arr)):
            new_arr[i, 0] = np.mean(old_array[i, :]) - (
                np.std(old_array[i, :]) / np.sqrt(self.replicates)
            )
            new_arr[i, 1] = np.mean(old_array[i, :]) + (
                np.std(old_array[i, :]) / np.sqrt(self.replicates)
            )
        return new_arr

    def flatten(self, d=1):
        if d == 1:
            for i in range(self.fwd.shape[1]):
                self.y_flat.append(self.fwd[:, [i]].flatten())
                self.y_flat.append(-self.rvs[:, [i]].flatten())
        else:
            for i in range(self.fwd.shape[1]):
                self.y_flat.append(self._smoothTriangle(self.fwd[:, [i]].flatten(), d))
                self.y_flat.append(self._smoothTriangle(-self.rvs[:, [i]].flatten(), d))

    @staticmethod
    def _smoothTriangle(data, degree):
        triangle = np.concatenate(
            (np.arange(degree + 1), np.arange(degree)[::-1])
        )  # up then down
        smoothed = []

        for i in range(degree, len(data) - degree * 2):
            point = data[i : i + len(triangle)] * triangle
            smoothed.append(np.sum(point) / np.sum(triangle))
        # Handle boundaries
        smoothed = [smoothed[0]] * int(
            degree + degree / 2
        ) + smoothed  # TODO: this can be better
        while len(smoothed) < len(data):
            smoothed.append(smoothed[-1])
        return smoothed

    def __str__(self):  # TODO: update
        return "{0}\t{1}\t{2}\t{3}\t{4}".format(
            self.header,
            self.ref_len,
            self.srna_len,
            self.fwd,
            self.rvs,
        )

    def __repr__(self):
        return self.__str__()

    def __eq__(self, other):  # TODO: update
        return (
            self.header == other.header
            and self.ref_len == other.ref_len
            and self.srna_len == other.srna_len
            and np.array_equal(self.fwd, other.fwd)
            and np.array_equal(self.rvs, other.rvs)
        )

def align_plot(
    align_prefix,
    align_lens,
    header,
    start=None,
    end=None,
    smoothing_window=1,
    cov=True,
    abund=True,
    se=True,
    save=True,
    ylim_set=(0, 0),
    sec_structure=False,
    ref_file=None,
    show_seq=False,
):
    ss = None
    if sec_structure:
        ss = SectStruct(ref_file, header, start, end)
        if show_seq:
            print("Selected sequence:")
            print(ss.sequence)
    set_up_plot(ss)

    all_handles = []
    all_labels = []

    for len in align_lens:
        file_path = "{0}_{1}.csv".format(align_prefix, len)
        if os.path.isfile(file_path):
            rp = RefProfiles()
            rp.load_single_ref_profiles(file_path, header=header, start=start, end=end)
            if isinstance(header, list):
                for h in header:
                    ret = single_plot(
                        rp, h, start, end, smoothing_window, cov, abund, se, ylim_set
                    )
                    if ret is not None:  # Checking if a valid return is obtained
                        handles, labels = ret
                        all_handles.extend(handles)
                        all_labels.extend(labels)
            else:
                ret = single_plot(
                    rp, header, start, end, smoothing_window, cov, abund, se, ylim_set
                )
                if ret is not None:  # Checking if a valid return is obtained
                    handles, labels = ret
                    all_handles.extend(handles)
                    all_labels.extend(labels)
        else:
            print(f"File {file_path} not found. Skipping.")

    if se:
        # Create a legend with the combined handles and labels
        plt.legend(all_handles, all_labels, loc="upper right")

    if save:
        if isinstance(header, list):
            save_file = align_prefix + "_" + "_".join(header) + ".png"
        else:
            save_file = align_prefix + "_" + header + ".png"

        # Include start and end positions in the filename if provided
        if start is not None and end is not None:
            save_file = save_file.replace(".png", f"_{start}_{end}.png")

        plt.savefig(save_file)
    plt.show()

def set_up_plot(ss=None):
    """ """
    plt.figure(figsize=(12, 12), dpi=600)
    plt.xlabel("Position")
    plt.ylabel("Abundance")
    plt.axis("equal")  # TODO: check if needed
    if ss is not None:
        sec_struct_setup(ss)
    plt.gca().set_yticks([])

def sec_struct_setup(ss):
    max_y = 0  # Variable to store maximum y value
    for x1, x2 in ss.pairs:
        # The two points
        p1 = np.array([x1, 0])
        p2 = np.array([x2, 0])

        # The center of the circle
        c = (p1 + p2) / 2

        # The radius of the circle
        r = np.linalg.norm(p1 - p2) / 2
        # Updating max_y if current r is greater
        max_y = max(max_y, r)

        # The angles for the arc
        t = np.linspace(0, np.pi, 100)

        # Parametric equations for the circle
        x = c[0] + r * np.cos(t)
        y = c[1] + r * np.sin(t)

        plt.plot(x, y, c="blue", linewidth=0.1, alpha=0.8)
    plt.axis("equal")  # ensure the circle isn't distorted
    plt.xlim(0, ss.length + 1)  # set x-axis limits based on sequence length

    # Set symmetrical y-limits around 0
    plt.ylim(-max_y, max_y)  # Hide y-axis ticks for the main y-axis

def single_plot(
    ref_profiles,
    header,
    start=None,
    end=None,
    smoothing_window=1,
    cov=True,
    abund=True,
    se=True,
    ylim_set=0,
    padding=0,
):
    """Your single_plot function..."""

    # Create the second axis
    ax2 = plt.gca().twinx()
    ax2.set_ylim(-ylim_set, ylim_set)
    cols = {
        18: "#f781bf",
        19: "#a65628",
        20: "#984ea3",
        21: "red",
        22: "blue",
        23: "#999999",
        24: "darkgreen",
        25: "brown",
        26: "#dede00",
        27: "orange",
        28: "yellow",
    }

    try:
        spd = DataForPlot(ref_profiles, header)

        ax2.plot(spd.x_axis, [0] * len(spd.x_axis), color="grey", linewidth=0.5)
        header = header.split()[0]
        title = f"Profile for {header}"
        if start is not None and end is not None:
            title += f" from position {start} to {end}"
        ax2.set_title(title)

        if cov:
            if abund:
                spd.convert_to_coverage(abund=True)
            else:
                spd.convert_to_coverage(abund=False)
        if se:
            spd.convert_to_error_bounds()
            spd.flatten(smoothing_window)
            ax2.fill_between(
                spd.x_axis,
                spd.y_flat[0],
                spd.y_flat[2],
                color=cols[spd.srna_len],
                alpha=0.4,
                label=str(spd.srna_len) + " nt",
            )
            ax2.fill_between(
                spd.x_axis,
                spd.y_flat[1],
                spd.y_flat[3],
                color=cols[spd.srna_len],
                alpha=0.4,
            )
        else:
            spd.flatten(smoothing_window)
            first = True
            for i in range(spd.replicates):
                if first:
                    ax2.plot(
                        spd.x_axis,
                        spd.y_flat[i],
                        spd.y_flat[i + spd.replicates],
                        color=cols[spd.srna_len],
                        alpha=0.8,
                        label=str(spd.srna_len) + " nt",
                    )
                    first = False
                else:
                    ax2.plot(
                        spd.x_axis,
                        spd.y_flat[i],
                        spd.y_flat[i + spd.replicates],
                        color=cols[spd.srna_len],
                        alpha=0.8,
                    )
                ax2.fill_between(
                    spd.x_axis,
                    spd.y_flat[i],
                    spd.y_flat[i + spd.replicates],
                    color=cols[spd.srna_len],
                    alpha=0.05,
                )
        if start is not None:
            x_ticks = ax2.get_xticks()
            ax2.set_xticks(
                x_ticks, [int(x + start - padding) for x in x_ticks]
            )  # Adjusting for 30 bp padding
        ax2.yaxis.tick_right()
        handles, labels = ax2.get_legend_handles_labels()
        return handles, labels
    except:
        pass

def comma_separated_ints(value):
    try:
        return [int(v) for v in value.split(",")]
    except ValueError:
        raise argparse.ArgumentTypeError(
            "Invalid comma-separated integers: '{}'".format(value)
        )

def comma_separated_strings(value):
    return value.split(",")

# command line interface for profile_plot
# TODO: check start and stop positions are valid
def main():
    parser = argparse.ArgumentParser(description="Plot abundance profiles")
    parser.add_argument("align_prefix", help="Prefix of alignment files")
    parser.add_argument(
        "align_lens",
        help="Comma-separated list of siRNA lengths to plot",
        type=comma_separated_ints,
    )
    parser.add_argument("header", help="Header of plot", type=comma_separated_strings)
    parser.add_argument(
        "-s", "--smoothing_window", help="Smoothing window", type=int, default=1
    )
    parser.add_argument("-c", "--coverage", help="Plot coverage", action="store_true")
    parser.add_argument("-a", "--abundance", help="Plot abundance", action="store_true")
    parser.add_argument("-e", "--error", help="Plot error", action="store_true")
    parser.add_argument(
        "-y", "--ylim", help="Set y-axis limit", type=int, nargs=2, default=0
    )
    parser.add_argument("-n", "--no_save", help="Do not save plot", action="store_true")
    parser.add_argument(
        "-start", "--start", help="Start position for the subset", type=int
    )
    parser.add_argument("-end", "--end", help="End position for the subset", type=int)
    parser.add_argument(
        "--sec_structure",
        help="Plot secondary structure of reference sequence",
        action="store_true",
    )
    parser.add_argument(
        "--ref_file",
        help="Alignment reference file (FASTA) for use in generating secondary structure",
        type=str,
        default=None,
    )

    args = parser.parse_args()

    # Error-checking condition
    if args.sec_structure and args.ref_file is None:
        parser.error("--ref_file is required when --sec_structure is set")

    if args.abundance:
        args.coverage = True

    align_plot(
        args.align_prefix,
        args.align_lens,
        args.header,
        args.start,
        args.end,
        args.smoothing_window,
        args.coverage,
        args.abundance,
        args.error,
        not args.no_save,
        args.ylim,
        args.sec_structure,
        args.ref_file,
    )

if __name__ == "__main__":
    main()


def find(index):
    if index == 1:
        return "4"
    elif index == 2:
        return "7"
    else:
        count = get_count(index)
        x = 2 ** count - 2
        if index - x <= 2**(count-1):
            return "4"+find(index - 2**(count-1))
        else:
            return "7"+find(index - 2*2**(count-1))

def get_count(target):
    result = 1
    while 2**(result+1) - 2 < target:
        result += 1
    return result

t = int(input())
for ind in range(t):
    n = int(input())
    print(find(n))


import ssl

from puppy.simple.http import SafeHTTP
from puppy.socket.server import SocketServer, SocketWorker

class HTTPWorker(SocketWorker):

    interface = None

    def initialize(self):
        # Create the HTTP interface
        self.interface = SafeHTTP()

    def handle(self):
        try:
            # Read request from client
            request = self.interface.receive_request(self.socket)

            # Handle client request
            response = self.parent.handler(request)

            # Transmit response to client
            self.interface.transmit_response(self.socket, response)
        except IOError:
            # Stop the worker
            raise KeyboardInterrupt()

class HTTPSWorker(HTTPWorker):

    def initialize(self):
        # Initialize the handler
        super(HTTPSWorker, self).initialize()

        try:
            # Wrap socket with SSL using parent's context
            self.socket = self.parent.context.wrap_socket(self.socket, server_side=True)
        except (ssl.SSLError, OSError):
            # Raise exception to stop the handler
            raise KeyboardInterrupt()

class HTTPServer(SocketServer):

    def __init__(self, handler, http=80, https=443):
        # Initialize looper
        super(HTTPServer, self).__init__({("0.0.0.0", http): HTTPWorker, ("0.0.0.0", https): HTTPSWorker})

        # Set the handler
        self.handler = handler

        # Initialize SSL context
        self.context = ssl.create_default_context()
        self.context.check_hostname = False
        self.context.verify_mode = ssl.CERT_NONE


import random
print("Lets play a game of rock paper scissors")
print("Lets play a game of rock paper scissors")
print("Lets play a game of rock paper scissors")
print("Rock,\n" "Paper, \n" "Scissors")

player1 = input("P1, Please put your character here:").lower()
#print("****NO CHEATING! \n\n" * 25)
player2 = input("P2, Please put your character here:").lower()
computer3 = random.randint(0, 2)
if computer3 == 0:
	computer = "rock"
elif computer3 == 1:
	computer = "paper"
else:
	computer = "scissors"
print(computer)
if player1 == player2:
	print("Its a tie!")
elif player1 == "rock":
	if player2 == "scissors":
		print("player1 wins")
	elif player2 == "paper":
		print("player2 wins")
elif player1 == "paper":
	if player2 == "scissors":
		print("player2 wins")
	elif player2 == "rock":
		print("player1 wins")
elif player1 == "scissors":
	if player2 == "rock":
		print("player2 wins")
	elif player2 == "paper":
		print("player1 wins")
else:
	print("Something went wrong")

Python/Rock Paper Scissors Game (ON HOLD).py


import pandas as pd

bond = pd.read_csv('Datasets\jamesbond.csv', index_col='Film')
bond.sort_index(inplace=True)

bond.nsmallest(n=3, columns='Box Office')

bond.nlargest(n=3, columns='Box Office')

print(bond['Box Office'].nlargest(10))


class Solution():
    class Node:
        def __init__(self, val=0, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right

    # root
    def __init__(self):
         self.root1 = None
         self.root2 = None

    # add root
    def add_root1(self, val):
        node = self.Node(val)
        self.root1 = node

    def add_root2(self, val):
        node = self.Node(val)
        self.root2 = node

     # add left node
    def add_left1(self, val):
         current = self.root1
         self.add_leftt1(current, val)

    def add_leftt1(self, node, val):
        if node.left == None:
            new_node = self.Node(val)
            node.left = new_node
            return
        self.add_leftt1(node.left, val)

    def add_left2(self, val):
         current = self.root2
         self.add_leftt2(current, val)

    def add_leftt2(self, node, val):
        if node.left == None:
            new_node = self.Node(val)
            node.left = new_node
            return
        self.add_leftt2(node.left, val)

    # add right node
    def add_right1(self, val):
        current = self.root1
        self.add_rightt1(current, val)

    def add_rightt1(self, node, val):
        if node.right == None:
             new_node = self.Node(val)
             node.right = new_node
             return
        self.add_rightt1(node.right, val)

    def add_right2(self, val):
        current = self.root2
        self.add_rightt2(current, val)

    def add_rightt2(self, node, val):
        if node.right == None:
             new_node = self.Node(val)
             node.right = new_node
             return
        self.add_rightt2(node.right, val)

    # displaying the value
    def display(self, node):
        current = node
        detail = "Root Node: "
        self.display_temp(current, detail)

    def display_temp(self, node, detail):
         if node == None:
             return
         print(f"{detail}: {node.val}")
         self.display_temp(node.left, f"Left child of {node.val}: ")
         self.display_temp(node.right, f"Right child of {node.val}: ")

    def isSameTree(self, p, q):
        #check if we reach the end
        if p is None and q is None:
            return True
        #check if one is reach the end
        if p is None or q is None:
            return False
        # if not equal
        if p.val != q.val:
            return False
        # recursive call
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

    # adding value
    def main(self):
        # add value in first node
        self.add_root1(1)
        self.add_left1(2)
        self.add_right1(3)
        self.display(self.root1)
        print()
        # add value in second node
        self.add_root2(1)
        self.add_left2(2)
        self.add_right2(3)
        self.display(self.root2)
        print()
        # class out solution in main
        ans = self.isSameTree(self.root1, self.root2)
        print("Is Same Tree")
        print(ans)

solution = Solution()
solution.main()


import codecs
import datetime
import glob
import os
import shutil

#
#   This script is intended to help spooling from TSV files in a local folder
#   to the various AWS environments for NDLA.
#
#   EXPECTED INPUT: A folder where the TSV files to import are saved as "1.tsv", "2.tsv" etc.
#   according to the following list
#   OUTPUT: Shell scripts for spooling to each AWS environment, and copies of the input files ready to email
#   in the export folder.

#   SET THESE VALUES before running - must point to existing folders
#   filesystem root (needed because Ubuntu on Windows...)
fs_root = "/c/"

#   folder where TSV input files are stored
input_folder = "ndla-spoling/"

#   folder where TSV files are copied to and renamed with pretty names for sending out mail
export_folder = "ndla-export/"

#   TSV files are downloaded from these URLs:

#    1  https://docs.google.com/spreadsheets/d/1q-A35Q_PZ6xsFx0EkeLHlDTuEQi2evNNB-pGfThiSPo/  medieuttrykk
#    2  https://docs.google.com/spreadsheets/d/16SW5rFxpOXBW7tJV-OuhpRBto1vcqZDQ6MMQSYWNvUI/  kinesisk
#    3  https://docs.google.com/spreadsheets/d/1srIDLu9B7pM4Yjvsu-7S2LBZBWK665rD1Qph5IevCPU/  samfunnsfag
#    4  https://docs.google.com/spreadsheets/d/16ZomBB7X56q2dhqxYurBB7ysU-a7Xja94K775i-pYzs/  helsearbeiderfag-vg2
#    5  https://docs.google.com/spreadsheets/d/1abr7bK8nbbiDai364QKx8-BYN5xgZC9yt0Vf-ElUQ8Y/  test

#    6  https://docs.google.com/spreadsheets/d/1XAwgVE4mTg-kGuB0jbEg05iJuHLBapPgZhd0pzrbjqc/  brønnteknikk
#    7  https://docs.google.com/spreadsheets/d/1LMIR3tVwR41ppkEjG-cVjf-yzelIOJtED_kaypvhblw/  markedsføring-og-ledelse
#    8  https://docs.google.com/spreadsheets/d/1D4YngL5Jb5so3Jdm4RrIRy43CVccRsu-NUw1FwH4jyY/  tysk
#    9  https://docs.google.com/spreadsheets/d/1YOxZ78mBBxZAl1I834oHhj1kqbF5n2OekDZDJT-HtQU/  historie
#   10  https://docs.google.com/spreadsheets/d/1KZFqT4KlFbDPVge0evUP5pR754tTpTE7lfRJpQNzDvw/  matematikk-fellesfag

#   11  https://docs.google.com/spreadsheets/d/1310W8EjeegGxKWuuF00lz44_XsTJNLTYxQzKJWyV_74/  bygg-og-anleggsteknikk
#   12  https://docs.google.com/spreadsheets/d/1_Gha5AVP5wUAfhF9BeQIWVyPElAsIReOYmVfZhedcyo/  service-og-samferdsel
#   13  https://docs.google.com/spreadsheets/d/1g_dV6vesx61XOQGBPL0xW4lDGmFxGWJD2ZsrDy0nP-8/  naturbruk
#   14  https://docs.google.com/spreadsheets/d/1I7r0SRG0NXr2ML6wYffEr-bkoURj-ERdA88h1Vu9oq0/  medie-og-informasjonskunnskap
#   15  https://docs.google.com/spreadsheets/d/19IClAPKQloxKn-iTs1Bnnaden34-lNgoVEAmVtKxMh0/  sørsamisk

#   16  https://docs.google.com/spreadsheets/d/1CX6oEo8YPCY3j_Dv8spnxs4NsI59LFfwfDF6enAcMac/  elektrofag
#   17  https://docs.google.com/spreadsheets/d/1JR4zsKyh7LC-vMG-EC-X_ovpg14IbUH3Qa3Z-flF5m0/  engelskspråklig-litteratur-og-kultur
#   18  https://docs.google.com/spreadsheets/d/1FnptdafPRBH5cqzjAf_JOZD2zz25W8kUMFIpUJ1v910/  kommunikasjon-og-kultur
#   19  https://docs.google.com/spreadsheets/d/1V8PNUocFJ09s63uWjL88UACFcIYh0xWlyhInlp9cG_Q/  norsk
#   20  https://docs.google.com/spreadsheets/d/121vfBZR9RvwFfYD8rqZfQEMSxGSvKj1zstNa2Jiu3ZI/  NDLA film
#
#   21  https://docs.google.com/spreadsheets/d/1SXV7O7xwKbyi7tUc86mYwYk3c9gLnSUVwOYNH8quBEw/  naturfag
#   22  https://docs.google.com/spreadsheets/d/1cU1B8QbFAl3d-9uD2E2kK4HZoKWxpCxgkkiQJSgnKQ4/  salg-service-sikkerhet
#   23  https://docs.google.com/spreadsheets/d/1pJH4KE1FA1W9nnQ0vkgIpZGCrksg0aEjtrNUGHCxtTg/  samfunnsfaglig-engelsk
#   24  https://docs.google.com/spreadsheets/d/1TldbFJRmIIcVCBFUO5F1Ae8NJHyrUy0pN6n-D8wZr50/  helse-og-oppvekst
#   25  https://docs.google.com/spreadsheets/d/1dHnhasaBYDoF9768FLlHajt0hnp0KoEpxrCrYiNzZ1A/  ikt-servicefag
#
#   26  https://docs.google.com/spreadsheets/d/1XGiUf6GdYbIgOPYZ4iLDyIttOPKD43BPKpy526ELq8A/  kroppsøving
#   27  https://docs.google.com/spreadsheets/d/17YfYge4G8KFXeLDC0BJCfdjBlWeYDYIlIsSM1GlxYDY/  internasjonal engelsk
#   28  https://docs.google.com/spreadsheets/d/1F5jj5287R57Z-709bfFYBKykr5W-JYoO3fxMctlvoGs/  teknikk og industriell produksjon
#   29  https://docs.google.com/spreadsheets/d/1imO2qaSVbQLpq24cnt8rzlZSMr7tigdDOHr--AMyt_Q/  praktisk matematikk
#   30  https://docs.google.com/spreadsheets/d/1EhmDHgeaS76dvSeFCV2dVLbMpps3FLN1gwaMsRMmtn0/  Matematikk for yrkesfaglige programmer
#   31  https://docs.google.com/spreadsheets/d/1p5LtP-nSpp4L81nRL6uThDOPftb41h9rUdVt5rb8VJ8/  Matematikk for samfunnsfag
#   32  https://docs.google.com/spreadsheets/d/1fs8zarUb28VnzRsdarO6D0u45eRaI-LAn82ez18ng1o/  Matematikk for realfag
#   33  https://docs.google.com/spreadsheets/d/1dtLKlULCspVKxXod3TEzjiJRtNPBFvPWAG2qq1HxKEw/  1T - Matematikk fellesfag
#   34  https://docs.google.com/spreadsheets/d/1t49dUUQFnrAKnmq8xftIzHkMbY08fQ9i7b-1lhi6CVc/  1P - Matematikk fellesfag
#   35  https://docs.google.com/spreadsheets/d/1UtiPGBPS-h3VUdUejPRJjk0Mi1yad4SOHXjwUYxC024/  Reiseliv
#   36  https://docs.google.com/spreadsheets/d/1ny0gSl57scuev-MCs7kXBmdKj-eEJqqYP4NuP0CI7LA/  Transport og logistikk
#   37  https://docs.google.com/spreadsheets/d/1H4EBhvVpaK9tnHdagm7X54YR_orYgg2A4Ij70SvSiF8/  Restaurant- og matfag Vg1
#   38  https://docs.google.com/spreadsheets/d/1BfP-RZ3NfhWjO87nFe6JqcdfBG2wK6zvbCTt_5MExu0/  Design og håndverk Vg1
#   39  https://docs.google.com/spreadsheets/d/1vk9-mASASr-UpPKy-N_08EcDRd1EpD1_2nVaq-fe_bM/  Engelsk Vg1
#   40  https://docs.google.com/spreadsheets/d/15oLpaisgmSKHjjK_6wKHuccVRMHpPGf_MwlykTeWjZE/  BUA-faget
#   41  https://docs.google.com/spreadsheets/d/17QSXFo0qguVNkykZRP5QsdStdWl2oY2TLlGLES9DPvk/  Kokk- og servitørfaget VG2
#   42  https://docs.google.com/spreadsheets/d/1pcWpSDSARt9M64Fo35S7uLm1cc2oabwWshi1miS3xBA/  Biologi
#   43  https://docs.google.com/spreadsheets/d/1gYPHFkA0Ji4qYhbW41hUTlOcvOatFcoYDJKXr3C7Kng/  Sosiologi og sosialantropologi
#   44  https://docs.google.com/spreadsheets/d/1iO2wjB_AeFep0lmhSfWrEK3rGWRGqP_D46COV06o9ek/  Religion og etikk

jar_location = "target/taxonomy-import.jar"

now = datetime.date.today()
year = str(now.year)
month = str(now.month).zfill(2)
day = str(now.day).zfill(2)
date = year + month + day

servers = [
    ("test", "http://ndla-taxonomy-test.uarauzeick.eu-central-1.elasticbeanstalk.com/"),
    ("brukertest", "http://ndla-taxonomy-brukertest.uarauzeick.eu-central-1.elasticbeanstalk.com/"),
    ("spoletest", "http://ndla-taxonomy-spoletest.eu-central-1.elasticbeanstalk.com/"),
    ("staging", "http://ndla-taxonomy-staging.uarauzeick.eu-central-1.elasticbeanstalk.com/"),
    ("prod", "http://ndla-taxonomy-prod.uarauzeick.eu-central-1.elasticbeanstalk.com/"),
    ("dev", "http://ndla-taxonomy-dev.eu-central-1.elasticbeanstalk.com/"),
    ("localhost", "http://localhost:5000/")
]

# Maps short names to "pretty names" for subjects, ordered by ID

subjects = [
    ("medieuttrykk", "Medieuttrykk og mediesamfunnet"),
    ("kinesisk", "Kinesisk"),
    ("samfunnsfag", "Samfunnsfag"),
    ("helsearbeiderfag-vg2", "Helsearbeiderfag Vg2"),
    ("test", "Testfag"),
    ("brønnteknikk", "Brønnteknikk"),
    ("markedsføring-og-ledelse", "Markedsføring og ledelse 1"),
    ("tysk", "Tysk"),
    ("historie", "Historie Vg2 og Vg3"),
    ("matematikk-fellesfag", "Matematikk fellesfag"),
    ("bygg-og-anleggsteknikk", "Bygg- og anleggsteknikk"),
    ("service-og-samferdsel", "Service og samferdsel Vg1"),
    ("naturbruk", "Naturbruk Vg1"),
    ("medie-og-informasjonskunnskap", "Medie- og informasjonskunnskap"),
    ("sørsamisk", "Sørsamisk"),
    ("elektrofag", "Elektrofag"),
    ("engelskspråklig-litteratur-og-kultur", "Engelskspråklig litteratur og kultur"),
    ("kommunikasjon-og-kultur", "Kommunikasjon og kultur"),
    ("norsk", "Norsk"),
    ("ndla-film", "NDLA film"),
    ("naturfag", "Naturfag"),
    ("salg-service-sikkerhet", "Salg, service og sikkerhet Vg2"),
    ("samfunnsfaglig-engelsk", "Samfunnsfaglig engelsk"),
    ("helse-og-oppvekst", "Helse- og oppvekstfag Vg1"),
    ("ikt-servicefag", "IKT-servicefag Vg2"),
    ("kroppsøving", "Kroppsøving"),
    ("internasjonal-engelsk", "Internasjonal engelsk"),
    ("teknikk-og-industriell-produksjon", "Teknikk og industriell produksjon"),
    ("praktisk-matematikk", "Praktisk matematikk"),
    ("matematikk-for-yrkesfag", "Matematikk for yrkesfaglige programmer"),
    ("matematikk-for-samfunnsfag", "Matematikk for samfunnsfag"),
    ("matematikk-for-realfag", "Matematikk for realfag"),
    ("matematikk-1T-fellesfag", "1T - Matematikk fellesfag"),
    ("matematikk-1P-fellesfag", "1P - Matematikk fellesfag"),
    ("reiseliv", "Reiseliv"),
    ("transport-og-logistikk", "Transport og logistikk"),
    ("restaurant-og-matfag", "Restaurant- og matfag Vg1"),
    ("design-og-håndverk", "Design og håndverk Vg1"),
    ("engelsk", "Engelsk Vg1"),
    ("bua-faget","BUA-faget"),
    ("kokk-og-servitør-faget", "Kokk- og servitørfag Vg2"),
    ("biologi", "Biologi"),
    ("sosiologi-og-sosialantropologi", "Sosiologi og sosialantropologi"),
    ("religion-og-etikk", "Religion og etikk")
]

def make_filename(id):
    subject_short_name = subjects[id][0]
    return "ndla-" + str(id + 1).zfill(2) + "-" + subject_short_name + "-" + date + ".tsv"

def copy_renamed_input_files():
    current_dir = os.getcwd()
    os.chdir(fs_root+input_folder)
    for file in glob.glob("*.tsv"):
        end_index = file.find(".tsv")
        name = file[:end_index]
        index_from_name = int(name) - 1
        new_name = make_filename(index_from_name)
        if not os.path.exists("../" + export_folder):
            os.mkdir("../" + export_folder)
        shutil.copy2(file, "../" + export_folder + "/" + new_name)
    os.chdir(current_dir)

def create_shell_scripts():
    for server in servers:
        with codecs.open(server[0] + ".sh", "w", "utf-8-sig") as script:
            script.write("#!/bin/sh\n\n")
            for idx, subject in enumerate(subjects):
                id = str(idx + 1)
                path = fs_root + input_folder
                input_file = path + id + ".tsv"
                subject_id = 'urn:subject:' + id
                subject_name = "\"" + subject[1] + "\""
                logfile = '{}{}-{}-{}-{}.log'.format(path, id, subject[0], date, server[0])
                environment = server[1]
                script.write(
                    "cat {} | {} -i {} -ci CLIENT_ID -cs CLIENT_SECRET -ts TOKEN_SERVER -n {} -e {} &> {}\n".format(input_file, jar_location, subject_id, subject_name,
                                                                  environment, logfile))
            script.close()

copy_renamed_input_files()
create_shell_scripts()


"""Metaclass for parametrizing a class by its __init__ parameters.

Caleb Levy, 2015.
"""

from inspect import getargspec
from operator import attrgetter

from funcstructs.compat import with_metaclass

def hascustominit(cls):
    """Return true if cls does not call default initializer."""
    # In pypy2, the following:

    # >>>> class A(object): pass
    # >>>> A.__init__ is object.__init__

    # returns False. Hence the need to traverse class dicts in mro
    for c in type.mro(cls):
        if '__init__' in c.__dict__:
            return c is not object

def base_slots(cls):
    """Return all member descriptors in C and its bases."""
    slots = set()
    for c in type.mro(cls):
        slots.update(getattr(c, '__slots__', ()))
    return slots

class ParamMeta(type):
    """A parametrized type.

    Parametrized classes represent objects whose behavior is determined by a
    fixed set of independent variables. They are automatically assigned
    __slots__ and accessors for the parameters of their __init__ methods.

    Parametrized types enforce the following contract:
    --------------------------------------------------
    1) All of their bases define __slots__.
    2) Their unparametrized bases do not override the default __init__.
    3) The __slots__ of their unparametrized bases are empty.
    4) They cannot be multiply inherited from.
    5) Their __init__ methods cannot take variable arguments.

    Additionally, the '__parameters__' and '__slots__' attributes of
    parametrized classes are reserved for internal use.
    """

    def __new__(mcls, name, bases, dct):
        slotted = ['__dict__' not in base.__dict__ for base in bases]
        parametrized = [isinstance(base, ParamMeta) for base in bases]
        initialized = [hascustominit(base) for base in bases]

        # Extract __init__ parameters
        def default_init(self): pass
        if any(parametrized):
            param_base = bases[parametrized.index(True)]
            if hascustominit(param_base):
                default_init = param_base.__init__
        init_args = getargspec(dct.get('__init__', default_init))

        # Enforce the Contract
        # --------------------
        # RULE 0) No Reserved Names.
        for attr in ['__slots__', '__parameters__']:
            if attr in dct:
                raise TypeError("cannot set reserved attribute %r" % attr)
        # RULE 1) All Bases Have Slots. This requirement guarantees
        # access to __dict__ is prevented for objects of the resulting
        # type. See "notes on using slots" in the documentation of
        # Python's data model.
        for base, has_slots in zip(bases, slotted):
            if not has_slots:
                raise TypeError("base %s does not have __slots__" % base)
        # RULE 2) No Unparametrized __init__. Mixin classes can define
        # behavior, but not the fundamental variables.
        for has_init, is_parametrized in zip(initialized, parametrized):
            if has_init and not is_parametrized:
                raise TypeError("unparametrized base %s with __init__" % base)
        # RULE 3) Unparametrized Bases Have Slots. This is a natural
        # consequence of maintaining consistency between the __slots__
        # and parameters of the type's bases, along with imposing rules
        # one and two.
        for base, is_parametrized in zip(bases, parametrized):
            if not is_parametrized and base_slots(base):
                raise TypeError("unparametrized base with nonempty slots")
        # RULE 4) Max of One Parametrized Base. Instance layout conflicts
        # prevent mixing of types with different parameters, and the meaning
        # of inheriting from different bases with the same parameters is
        # unclear, leaving little reason to allow it.
        if parametrized.count(True) > 1:
            raise TypeError("multiple parametrized bases")
        # RULE 5) Fixed Parameter Count.
        if init_args.varargs is not None or init_args.keywords is not None:
            raise TypeError("variable arguments in %s.__init__" % name)

        # Add __slots__ to new type. This must be done before class creation,
        # which is why we need a metaclass. Take care not to duplicate names of
        # existing member descriptors, which could lead to undefined behavior,
        # as per the python docs.
        current_params = tuple(init_args.args[1:])
        old_params = set()
        for base in bases:
            old_params.update(base_slots(base))
        new_params = ()
        for param in current_params:
            if param not in old_params:
                new_params += param,
        dct['__slots__'] = new_params

        # For docs and convenience
        dct['__parameters__'] = current_params
        # Make sure _param_values always returns a tuple
        if not current_params:
            def _param_values(self): return ()
        else:
            pg = attrgetter(*current_params)
            if len(current_params) == 1:
                def _param_values(self): return pg(self),
            else:
                def _param_values(self): return pg(self)
        dct.setdefault('_param_values', _param_values)
        return super(ParamMeta, mcls).__new__(mcls, name, bases, dct)

class Parametrized(with_metaclass(ParamMeta, object)):
    """Helper class that provides a standard way to create Parametrized
    classes using inheritance.
    """
    pass


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 19:46:34 2020

@author: Lenovo
"""

def getResult(c):
    s=bin(c)[2:]
    res=''
    while len(s)<8:
        s='0'+s
    for i in range(int(len(s)/2)):
        res=res+s[2*i+1]+s[2*i]
    return int(res, 2)

if __name__ == '__main__':
    n=int(input())
    for i in range(n):
        c=int(input())
        v=getResult(c)
        print(v)


# -*- coding: utf-8 -*-
"""
Part I Autumn Term
Lecture 2: Frequency domain analysis

Fast Fourier Transform - complex conjugate.

Last modified on Thu Sep 15 02:11:19 2022
@author: Dr Frederic Cegla, Amanda Lee
"""

###############################################################
# Import required functions, modules, packages, and libraries #
###############################################################
# Functions
from numpy import pi as pi                     # Import NumPy constants and mathematical functions
from numpy.fft import fft as fft, ifft as ifft # Import NumPy discrete Fourier transform functions

# Modules, packages, and libraries
import soundfile as sf                         # Import audio library
import numpy as np                             # Import the fundamental package for scientific computing with Python
import matplotlib.pyplot as plt                # Import the state-based interface for interactive plots and simple cases of programmatic plot generation

######################################
# Step 1: Display time domain signal #
######################################
(data, Fs) = sf.read("Chimes.wav") # Read data and extract sampling frequency from sound file
FNy = Fs/2 # Define Nyquist frequency
T = (len(data)-1)/Fs # Define time period
t = np.linspace(0, T, len(data)) # Create time vector
y = data[:, 0] # Extract data from channel 1 only (note that the loaded wave file is stereo)

plt.figure("Figure 1: Time domain signal") # Create a new figure
plt.title("Time domain signal") # Set a title for the axes
plt.plot(t, y) # Plot y vs t
plt.xlim(t[0], t[-1]) # Set the x limits of the current axes
plt.xlabel("Time / s") # Set the label for the x-axis
plt.ylabel("Amplitude / arb. unit") # Set the label for the y-axis

###########################################
# Step 2: Display frequency domain signal #
###########################################
F = np.linspace(0, Fs, len(t)) # Create frequency vector
Fy = fft(y) # Take FFT of signal y

fig = plt.figure("Figure 2: Frequency domain signal") # Create a new figure
fig.suptitle("Frequency domain signal") # Add a centered suptitle to the figure

plt.subplot(2, 1, 1) # Add an axes to the current figure (top plot)
plt.plot(F, np.abs(Fy)) # Plot Fy vs F (magnitude)
plt.xlim(0, FNy) # Display up to Nyquist frequency
plt.ylim(bottom=0) # Set the y limits of the current axes
plt.xlabel("Frequency / Hz") # Set the label for the x-axis
plt.ylabel("Amplitude / arb. unit") # Set the label for the y-axis

plt.subplot(2, 1, 2) # Add an axes to the current figure (bottom plot)
plt.plot(F, np.angle(Fy)) # Plot Fy vs F (phase)
plt.xlim(0, FNy) # Display up to Nyquist frequency
plt.ylim(-pi, pi) # Set the y limits of the current axes
plt.xlabel("Frequency / Hz") # Set the label for the x-axis
plt.ylabel("Phase / rad") # Set the label for the y-axis

plt.tight_layout()

##################################################
# Step 3: Recreate upper half frequency spectrum #
##################################################
Fy_new = np.zeros(np.size(Fy), dtype="complex_") # Initialise an array to store new spectrum
FNy_idx = int( len(F)/2 ) - 1 # Find the Nyquist frequency array index
Fy_new[1 : FNy_idx+1] = Fy[1 : FNy_idx+1] # Copy spectrum up to Nyquist frequency
Fy_new[FNy_idx+1 :] = np.conj( Fy[FNy_idx+1 : 0 : -1] ) # Recreate spectrum above Nyquist frequency

plt.figure("Figure 3: Frequency domain signal (reconstructed)") # Create a new figure
plt.title("Frequency domain signal (reconstructed)") # Set a title for the axes
plt.plot(F, np.abs(Fy_new), label="Reconstructed signal") # Plot reconstructed signal (Fy_new vs F; magnitude)
plt.plot(F, np.abs(Fy), ":", label="Original signal") # Plot original signal (Fy vs F; magnitude)
plt.axvline(x=FNy, color="k", linestyle="--") # Display axis of symmetry at Nyquist frequency
plt.xlim(F[0], F[-1]) # Set the x limits of the current axes
plt.ylim(bottom=0) # Set the y limits of the current axes
plt.xlabel("Frequency / Hz") # Set the label for the x-axis
plt.ylabel("Amplitude / arb. unit") # Set the label for the y-axis
plt.legend() # Place a legend on the axes

###############################################
# Step 4: Recover original time domain signal #
###############################################
y_new = np.real( ifft(Fy_new) ) # Take IFFT of signal Fy_new

plt.figure("Figure 4: Time domain signal (reconstructed)") # Create a new figure
plt.title("Time domain signal (reconstructed)") # Set a title for the axes
plt.plot(t, y_new, label="Reconstructed signal") # Plot reconstructed signal (y_new vs t)
plt.plot(t, y, ":", label="Original signal") # Plot original signal (y vs t)
plt.xlim(t[0], t[-1]) # Set the x limits of the current axes
plt.xlabel("Time / s") # Set the label for the x-axis
plt.ylabel("Amplitude / arb. unit") # Set the label for the y-axis
plt.legend() # Place a legend on the axes
plt.show() # Display all open figures


import numpy as np
import joblib
import os
from ctrls.controller import Controller

class EpsilonController(Controller):
    """ A controller that modifies the probability "epsilon" of taking a random action periodically.

    Parameters
    ----------
    initial_e : float
        Start epsilon
    e_decays : int
        How many updates are necessary for epsilon to reach eMin
    e_min : float
        End epsilon
    evaluate_on : str
        After what type of event epsilon shoud be updated periodically. Possible values: 'action', 'episode', 'epoch'.
    periodicity : int
        How many [evaluateOn] are necessary before an update of epsilon occurs
    reset_every : str
        After what type of event epsilon should be reset to its initial value. Possible values:
        'none', 'episode', 'epoch'.
    """

    def __init__(self, initial_e=1., e_decays=10000, e_min=0.1, evaluate_on='action', periodicity=1, reset_every='none'):
        """Initializer.
        """

        super(self.__class__, self).__init__()
        periodicity = int(periodicity)
        initial_e = float(initial_e)
        e_decays = int(e_decays)
        e_min = float(e_min)
        self._count = 0
        self._init_e = initial_e
        self._e = initial_e
        self._e_min = e_min
        self._e_decay = (initial_e - e_min) / e_decays
        self._periodicity = periodicity

        self._on_action = 'action' == evaluate_on
        self._on_episode = 'episode' == evaluate_on
        self._on_epoch = 'epoch' == evaluate_on
        if not self._on_action and not self._on_episode and not self._on_epoch:
            self._on_action = True

        self._reset_on_episode = 'episode' == reset_every
        self._reset_on_epoch = 'epoch' == reset_every

    def onStart(self, agent):
        if (self._active == False):
            return

        self._reset(agent)

    def onEpisodeEnd(self, agent, terminal_reached, reward):
        if (self._active == False):
            return

        if self._reset_on_episode:
           self. _reset(agent)
        elif self._on_episode:
            self._update(agent)

    def onEpochEnd(self, agent):
        if (self._active == False):
            return

        if self._reset_on_epoch:
            self._reset(agent)
        elif self._on_epoch:
            self._update(agent)

    def onActionChosen(self, agent, action):
        if (self._active == False):
            return

        if self._on_action:
            self._update(agent)

    def _reset(self, agent):
        self._count = 0
        agent._train_policy.setAttribute("epsilon", self._init_e)
        self._e = self._init_e

    def _update(self, agent):
        self._count += 1
        if self._periodicity <= 1 or self._count % self._periodicity == 0:
            agent._train_policy.setAttribute("epsilon",self._e)
            self._e = max(self._e - self._e_decay, self._e_min)


import hmac
import os

from typing import Union

from bip32 import BIP32
from bip_utils import Bech32Encoder, Bech32Decoder
from hashlib import blake2b, pbkdf2_hmac, sha512

from nacl import bindings
from nacl.signing import SigningKey, VerifyKey

from mimblewimble.crypto.bulletproof import EBulletproofType

from mimblewimble.crypto.commitment import Commitment
from mimblewimble.crypto.secret_key import SecretKey
from mimblewimble.crypto.public_keys import PublicKeys
from mimblewimble.crypto.rangeproof import RangeProof
from mimblewimble.crypto.pedersen import Pedersen

from mimblewimble.crypto.bulletproof import EBulletproofType
from mimblewimble.crypto.bulletproof import ProofMessage
from mimblewimble.crypto.bulletproof import RewoundProof
from mimblewimble.crypto.bulletproof import Bulletproof

class KeyChain:
    def __init__(self, master_key: bytes, bulletproof_nonce: SecretKey):
        self.master_key = master_key
        self.bulletproof_nonce = bulletproof_nonce

    def derivePrivateKey(self, path: str):
        # derive the seed at the path
        master_key = self.master_key.getBytes()
        bip32 = BIP32(
            chaincode=master_key[32:], privkey=master_key[:32])
        sk = bip32.get_privkey_from_path(path)
        return SecretKey(sk)

    def derivePrivateKeyAmount(self, path: str, amount: int):
        p = Pedersen()
        sk = self.derivePrivateKey(path)
        ska = p.blindSwitch(sk, amount)
        return ska

    def deriveED25519Seed(self, path: str):
        sk_der = self.derivePrivateKey(path)

        # compute the blake2 hash of that key and that is ed25519 seed
        seed_blake = blake2b(sk_der.getBytes(), digest_size=32).digest()
        return seed_blake

    def deriveED25519SecretKey(self, path: str):
        # get the seed
        seed_blake = self.deriveED25519Seed(path)

        # get the ed25519 secret key and public key from it
        pk, sk = bindings.crypto_sign_seed_keypair(seed_blake)
        return sk

    def deriveED25519PublicKey(self, path: str):
        # get the seed
        seed_blake = self.deriveED25519Seed(path)

        # get the ed25519 public key and public key from it
        pk, sk = bindings.crypto_sign_seed_keypair(seed_blake)
        return pk

    def signED25519(self, message: bytes, path: str) -> bytes:
        sk = self.deriveED25519SecretKey(path)
        signature = bindings.crypto_sign(message, sk)
        del sk
        return signature

    @classmethod
    def verifyED25519(
            self,
            public_key: Union[bytes, str],
            signature: bytes,
            message: bytes) -> bool:
        public_key_bytes = public_key
        if isinstance(public_key, str):
            public_key_bytes = KeyChain.slatepackAddressToED25519PublicKey(public_key)
        recovered = bindings.crypto_sign_open(signature, public_key_bytes)
        return recovered == message

    def deriveSlatepackAddress(self, path: str, testnet=False):
        pk = self.deriveED25519PublicKey(path)

        # compute the slatepack address
        network = 'grin'
        if testnet:
            network = 'tgrin'
        slatepack_address = Bech32Encoder.Encode(network, pk)

        return slatepack_address

    @classmethod
    def slatepackAddressToED25519PublicKey(
            self, address: str, testnet=False) -> bytes:
        # compute the slatepack address
        network = 'grin'
        if testnet:
            network = 'tgrin'

        public_key = Bech32Decoder.Decode(network, address)
        return public_key

    def rewindRangeProof(
            self,
            commitment: Commitment,
            rangeproof: RangeProof,
            bulletproof_type: EBulletproofType):
        b = Bulletproof()
        if bulletproof_type == EBulletproofType.ORIGINAL:
            nonce = KeyChain.createNonce(
                commitment, self.bulletproof_nonce)
            return b.rewindProof(
                commitment, rangeproof, nonce)
        elif bulletproof_type == EBulletproofType.ENHANCED:
            pks = PublicKeys()
            master_public_key = pks.calculatePublicKey(self.master_key)

            rewind_nonce_hash = SecretKey(blake2b(
                master_public_key.getBytes(),
                digest_size=32).digest())

            return b.rewindProof(
                commitment,
                rangeproof,
                KeyChain.createNonce(commitment, rewind_nonce_hash))
        raise ValueError('Unimplemented bulletproof type')

    def generateRangeProof(
            self,
            path: str,
            amount: int,
            commitment: Commitment,
            blinding_factor: SecretKey,
            bulletproof_type: EBulletproofType):

        key_indices = KeyChain.getKeyIndices(path)
        proof_message = ProofMessage.fromKeyIndices(
            key_indices, bulletproof_type)

        b = Bulletproof()
        if bulletproof_type == EBulletproofType.ORIGINAL:
            nonce = KeyChain.createNonce(
                commitment, self.bulletproof_nonce)
            return b.generateRangeProof(
                amount, blinding_factor, nonce, nonce, proof_message)
        elif bulletproof_type == EBulletproofType.ENHANCED:
            private_nonce_hash = SecretKey(blake2b(
                self.master_key.getBytes(),
                digest_size=32).digest())

            pks = PublicKeys()
            master_public_key = pks.calculatePublicKey(self.master_key)

            rewind_nonce_hash = SecretKey(blake2b(
                master_public_key.getBytes(),
                digest_size=32).digest())

            return b.generateRangeProof(
                amount,
                blinding_factor,
                KeyChain.createNonce(commitment, private_nonce_hash),
                KeyChain.createNonce(commitment, rewind_nonce_hash),
                proof_message)
        raise ValueError('Unimplemented bulletproof type')

    @classmethod
    def getKeyIndices(self, path: str):
        key_indices = []
        for v in path.split('/'):
            try:
                i = int(v)
            except:
                continue
            key_indices.append(i)
        return key_indices

    @classmethod
    def createNonce(self, commitment: Commitment, nonce_hash: SecretKey):
        nonce = blake2b(
            commitment.getBytes() + nonce_hash.getBytes(),
            digest_size=32).digest()
        return SecretKey(nonce)

    @classmethod
    def fromSeed(self, master_seed):
        # I AM VOLDEMORT
        m = hmac.new('IamVoldemort'.encode('utf8'), digestmod=sha512)
        m.update(master_seed)
        master_key = SecretKey(m.digest())
        p = Pedersen()
        bulletproof_nonce = p.blindSwitch(master_key, 0)
        return KeyChain(master_key, bulletproof_nonce)

    @classmethod
    def fromRandom(self):
        master_seed = os.urandom(32)
        return KeyChain.fromSeed(master_seed)


import sys
import heapq
input = sys.stdin.readline

N = int(input())

max_heap = []

for n in range(N):
    tmp = int(input())

    if tmp == 0:
        if len(max_heap):
            print(-1 * heapq.heappop(max_heap))
        else:
            print(0)
    else:
        heapq.heappush(max_heap, -tmp)


import numpy as np
import scipy.io.wavfile as wav
import scipy.signal as signal
import matplotlib.pyplot as plt

# Load audio file
rate, audio = wav.read("speech.wav")

# Normalize audio data
audio = audio / np.max(np.abs(audio))

# Apply pre-emphasis filter
pre_emphasis = 0.97
emphasized_audio = np.append(audio[0], audio[1:] - pre_emphasis * audio[:-1])

# Define frame length and overlap
frame_length = int(0.025 * rate)
frame_overlap = int(0.01 * rate)

# Generate frames of audio data
frames = []
for i in range(0, len(emphasized_audio) - frame_length, frame_overlap):
    frame = emphasized_audio[i:i + frame_length]
    frames.append(frame)

# Apply Hamming window to frames
windowed_frames = np.array(frames) * signal.hamming(frame_length)

# Compute power spectrum of frames using Fourier Transform
power_spectrum = np.abs(np.fft.rfft(windowed_frames, n=512))**2

# Compute Mel filterbank energies
num_filters = 26
low_freq_mel = 0
high_freq_mel = (2595 * np.log10(1 + (rate / 2) / 700))  # Convert Hz to Mel
mel_points = np.linspace(low_freq_mel, high_freq_mel, num_filters + 2)
hz_points = 700 * (10**(mel_points / 2595) - 1)  # Convert Mel to Hz
bin = np.floor((frame_length + 1) * hz_points / rate)

filterbank = np.zeros((num_filters, int(np.floor(frame_length / 2 + 1))))
for m in range(1, num_filters + 1):
    f_m_minus = int(bin[m - 1])
    f_m = int(bin[m])
    f_m_plus = int(bin[m + 1])

    for k in range(f_m_minus, f_m):
        filterbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])
    for k in range(f_m, f_m_plus):
        filterbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])

filterbank_energies = np.dot(power_spectrum, filterbank.T)
filterbank_energies = np.where(filterbank_energies == 0, np.finfo(float).eps, filterbank_energies)  # Numerical Stability

# Compute logarithmic Mel spectrum
log_filterbank_energies = 20 * np.log10(filterbank_energies)

# Apply discrete cosine transform (DCT) to decorrelate the filterbank energies
num_ceps = 12
mfcc = np.zeros((len(log_filterbank_energies), num_ceps))
for i in range(num_ceps):
    norm = np.sqrt(2.0 / frame_length)
    if i == 0:
        norm = np.sqrt(1.0 / frame_length)
    for j in range(len(log_filterbank_energies)):
        mfcc[j, i] = norm * np.sum(log_filterbank_energies[j] * np.cos(np.pi * i / num_filters * (np.arange(num_filters) + 0.5)))

# Use the first 12 MFCC coefficients as features for speech recognition
features = mfcc[:, 0:12]

# Train a


print('''
            10.11 – Número favorito: Escreva um programa que pergunte qual é o número
            favorito de um usuário. Use json.dump() para armazenar esse número em um
            arquivo. Escreva um programa separado que leia esse valor e apresente a
            mensagem “Eu sei qual é o seu número favorito! É _____.”.
''')

import json

def get_numero_favorito():

    filename = 'numero_favorito.json'
    try:
        with open(filename) as f_obj:
            number = json.load(f_obj)
    except FileNotFoundError:
        username = input("Qual é o seu número favorito? ")
        with open(filename, 'w') as f_obj:
            json.dump(username, f_obj)
            print(f"O seu número favorito é {username}.")
    else:
        print(f"Eu sei qual é o seu número favorito! É {number}.")

get_numero_favorito()


import json
from models import User, session
from wallet import WalletApi

client = WalletApi()

def get_orders(id):
    "Returns all orders attached to a specifici user"
    pass

def get_products1():
    "Pulls down al the store products"
    file = open('./products.json')
    data = json.load(file)
    return data['First Listing']

def get_products2():
    "product types & prices"
    file = open('./products.json')
    data = json.load(file)
    return data['Second Listing']

def get_user(msg):
    "Returns or creates a new user"
    id = msg.from_user.id

    user = session.query(User).filter_by(id=id).first()
    if user:
        return user
    else:
        mnemonic, address = client.create_wallet()
        user = User(id=id, balance="0", orders=0, address=address, mnemonic=mnemonic)
        session.add(user)
        session.commit()
        return user

def update_balance(msg):
    "Updates User Balance"
    user = get_user(msg)

    balance = client.get_balance(address = user.address)
    user.balance = str(balance)
    session.add(user)
    session.commit()
    return str(balance)

def get_received_msg(msg):
    "Delete This Message"

    message_id = msg.message_id
    chat = msg.chat
    return chat, message_id

def send_out_payment(user, amount, wallet):
    status = client.send_money(user, amount, wallet)
    return status


import shutil

from kivy import utils
from kivy.clock import Clock
from kivy.core.text import LabelBase
from kivy.graphics.texture import Texture
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.image import Image
from kivy.uix.screenmanager import Screen, ScreenManager
from kivymd.app import MDApp
import cv2
import os
from kivymd.font_definitions import theme_font_styles
from kivymd.uix.button import MDIconButton, MDFloatingActionButtonSpeedDial
from kivymd.uix.label import MDLabel
from datetime import datetime

import measureDimension
import objectDetection
import textRecognition
import warpPerspective

pathImage = "images/1.jpg"
imgChosen = False
img = cv2.imread(pathImage)

class MainScreen(Screen):
    pass

class MainScreenManager(ScreenManager):
    screen_stack = []
    header_text = StringProperty()
    recognized_text = StringProperty()
    image_path = StringProperty()

    options = {
        'Warp Perspective': 'perspective-less',
        'Object Detection': 'cube-scan',
        'Recognize Text': 'text-recognition',
        'Measure': 'tape-measure',
    }

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def push(self, screen_name):
        if screen_name not in self.screen_stack:
            self.screen_stack.append(self.current)
            self.transition.direction = "up"
            self.current = screen_name

    def pop(self):
        if len(self.screen_stack) > 0:
            screen_name = self.screen_stack[-1]
            del self.screen_stack[-1]
            self.transition.direction = "down"
            self.current = screen_name

    def start_button_clicked(self):
        self.image_per_frame = Image(allow_stretch=True)
        self.header_text = 'Measure'
    #Object Detection
        self.tinyNetwork = objectDetection.initializeNetwork()
        self.network = objectDetection.initializeNetwork(tiny=False)
    #adding screen
        screen_layout = MainScreen(name='main_screen')
        self.add_widget(screen_layout)
    #displaying cam feed
        screen_layout.add_widget(self.image_per_frame)
    #capture button
        capture_button = MDIconButton(icon="camera-iris",
                                      pos_hint={"center_x": .5, "center_y": .1},
                                      user_font_size="45sp",
                                      theme_text_color="Custom",
                                      text_color= utils.get_color_from_hex('CEDFF0'))
        screen_layout.add_widget(capture_button)
        capture_button.bind(on_press=self.take_picture)

    #select from gallery button
        gallery_button = MDIconButton(icon='camera-burst',
                                      pos_hint={"center_x": .15, "center_y": .1},
                                      user_font_size="30sp",
                                      theme_text_color="Custom",
                                      text_color=utils.get_color_from_hex('CEDFF0')
                                      )
        screen_layout.add_widget(gallery_button)
        gallery_button.bind(on_press=self.open_gallery)
    #Floating Speed dial button
        speed_dial = MDFloatingActionButtonSpeedDial(callback= self.callback)
        speed_dial.data = self.options
        speed_dial.root_button_anim = True
        screen_layout.add_widget(speed_dial)
        self.ids['my_speed_dial'] = speed_dial
    #video capture
        self.capture = cv2.VideoCapture(0)
        Clock.schedule_interval(self.update, 1 / 60)
    #Adding Border
        screen_layout.add_widget(Image(source='ui/Border.png',
                                       allow_stretch=True,
                                       keep_ratio=False))
    #Flash Light Button
        flash_button = MDIconButton(icon='flash-off',
                                    pos_hint={"center_x": .1, "center_y": .95},
                                    user_font_size="20sp",
                                    theme_text_color="Custom",
                                    text_color=utils.get_color_from_hex('CEDFF0')
                                    )
        screen_layout.add_widget(flash_button)
        self.ids['my_flash_button'] = flash_button
        flash_button.bind(on_press= self.flash_button_pressed)
    #Close Button
        close_button = MDIconButton(icon='close',
                                    pos_hint={"center_x": .9, "center_y": .95},
                                    user_font_size="20sp",
                                    theme_text_color="Custom",
                                    text_color=utils.get_color_from_hex('CEDFF0'))
        screen_layout.add_widget(close_button)
        close_button.bind(on_press= self.close_button_clicked)
    #Header
        header_label = MDLabel(text=self.header_text,
                               halign="center",
                               font_style='Quicksand',
                               pos_hint={"center_y": .90})
        screen_layout.add_widget(header_label)
        self.ids['my_header_label'] = header_label

    def flash_button_pressed(self, value):
        if self.ids.my_flash_button.icon == 'flash-off':
            self.ids.my_flash_button.icon = 'flash'
        else:
            self.ids.my_flash_button.icon = 'flash-off'

    def close_button_clicked(self, value):
        MDApp.get_running_app().stop()

    def callback(self, instance):
        if instance.icon == 'tape-measure':
            self.header_text = 'Measure'
        elif instance.icon == 'text-recognition':
            self.header_text = 'Recognize Text'
        elif instance.icon == 'perspective-less':
            self.header_text = 'Warp Perspective'
        elif instance.icon == 'cube-scan':
            self.header_text = 'Object Detection'

        self.ids.my_header_label.text = self.header_text

    def update(self, *args):
        self.load_video()

    def createTexture(self, frame):
        buffer = cv2.flip(frame, 0).tobytes()
        texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
        texture.blit_buffer(buffer, colorfmt='bgr', bufferfmt='ubyte')
        return texture

    def load_video(self, *args):
        ret, frame = self.capture.read()
        if not ret or imgChosen:
            frame = img
        self.image_per_frame_cv = frame
        if self.header_text == 'Warp Perspective' and self.header_text == 'Measure':
            texture = self.load_video_for_warpPerspective(frame)
            self.image_per_frame.texture = texture
        elif self.header_text == 'Object Detection':
            texture = self.load_video_for_object_detection(frame)
            self.image_per_frame.texture = texture
        else:
            texture = self.createTexture(frame)
            self.image_per_frame.texture = texture

    def load_video_for_warpPerspective(self, image_per_frame_cv):
        imgBigContour, warpedImg = warpPerspective.warpPers(image_per_frame_cv)
        texture = self.createTexture(imgBigContour)
        return texture

    def load_video_for_object_detection(self, image_per_frame_cv):
        #objectDetectedImg = objectDetection.detectObject(self.tinyNetwork, image_per_frame_cv)
        objectDetectedImg = image_per_frame_cv
        texture = self.createTexture(objectDetectedImg)
        return texture

    def take_picture(self, *args):
        now = datetime.now()
        image_name = 'Image'+now.strftime("_%Y_%m_%d_%H_%M_%S.png")
        imgCaptured = self.image_per_frame_cv
    #Recognize Text
        if self.header_text == 'Recognize Text':
            self.recognized_text = textRecognition.getText(self.image_per_frame_cv)
            imgCaptured = textRecognition.boundingBoxes(imgCaptured)
    #Object Detection
        elif self.header_text == 'Object Detection':
            imgCaptured = objectDetection.detectObject(self.network, imgCaptured)
    #Measure
        elif self.header_text == 'Measure':
            imgCaptured = measureDimension.measureDim(self.image_per_frame_cv)
    #WarpPerspective
        elif self.header_text == 'Warp Perspective':
            imgBigContour, warpedImg = warpPerspective.warpPers(self.image_per_frame_cv)
            imgCaptured = warpedImg

        cv2.imwrite(image_name, imgCaptured)
        self.image_path = image_name

        if self.header_text == 'Recognize Text':
            self.push('bottom_sheet_tr')
        else:
            self.push('bottom_sheet_all')

    def saveImage(self, imgPath):
        path = 'images'
        shutil.move(imgPath, path)

    def deleteCapturedImage(self, imgPath):
        if os.path.exists(imgPath):
            os.remove(imgPath)

    def open_gallery(self, *args):
        self.push('bottom_sheet_screen')

    def chooseImage(self, imgPath):
        global img
        img = cv2.imread(imgPath)
        global imgChosen
        imgChosen = True
        self.pop()

class OTDRSystem(MDApp):
    manager = ObjectProperty(None)
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Blue"
        self.theme_cls.primary_hue = "50"
        # Adding Custom Font
        LabelBase.register(name='Quicksand',
                           fn_regular='fonts/Quicksand-Regular.ttf')
        theme_font_styles.append('Quicksand')
        self.theme_cls.font_styles['Quicksand'] = ['Quicksand',
                                                   16,
                                                   False,
                                                   0.15, ]
        self.manager = MainScreenManager()

        return  self.manager

OTDRSystem().run()