from __future__ import division
from __future__ import print_function

import sys
from os import path
from argparse import ArgumentParser
import numpy as np
import json
import time
import logging

sys.path.append(path.dirname(path.dirname(path.dirname(path.dirname(path.abspath(__file__))))) + '/utils/')
sys.path.append(path.dirname(path.dirname(path.dirname(path.dirname(path.abspath(__file__))))) + '/CART/')

from algorithm_utils import StateData,set_algorithms_output_data,init_logger
from cart_lib import Node

def main(args):
    sys.argv =args
    init_logger()
    # Parse arguments
    parser = ArgumentParser()
    parser.add_argument('-cur_state_pkl', required=True,
                        help='Path to the pickle file holding the current state.')
    parser.add_argument('-prev_state_pkl', required=True,
                        help='Path to the pickle file holding the previous state.')
    parser.add_argument('-local_step_dbs', required=True,
                        help='Path to db holding local step results.')
    args, unknown = parser.parse_known_args()
    fname_cur_state = path.abspath(args.cur_state_pkl)
    fname_prev_state = path.abspath(args.prev_state_pkl)
    local_dbs = path.abspath(args.local_step_dbs)

    # Load global state
    global_state = StateData.load(fname_prev_state).data
    globalTreeJ = global_state['globalTree'].tree_to_json()

    myresult =  {"result": [{"type": "application/json", "data": globalTreeJ}]}
    t1 = global_state['t1']
    t2 = time.localtime(time.time())
    t0 = [ 'yy','mm','dd','hh','min','sec','wday','yday','isdst']
    logging.info(" Time: ")
    for i in range(len(t1)):
        logging.info([t0[i], t2[i], t1[i], t2[i]- t1[i]])
    set_algorithms_output_data(myresult)

if __name__ == '__main__':   main()


#receiver-udp

import socket
import sys

# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port

TCP_IP = '127.0.0.1'
TCP_PORT = 10000
BUFFER_SIZE = 20  # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

stdata = []

conn, addr = s.accept()
print('Connection address:', addr)
while True:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    temp = data.decode("utf-8").split(";")
    print("received data:", data)
    if len(stdata) > 0:
        if temp[0] < stdata[len(stdata)-1]:
            print('fel ordning motaget:{} senast motagen:{}'.format(temp[0], stdata[len(stdata) - 1]))
        elif int(temp[0]) != int(stdata[len(stdata) - 1]) + 1:
            print('fel paket saknas eller kommit i fel ordning motaget:{} senast motagen:{}'.format(temp[0], stdata[len(stdata)-1]))
    stdata.append(temp[0])
    stdata.sort()
conn.close()


#!/usr/bin/env python3
"""Select a set of marker genes from the aligned genes."""

import argparse
import logging
import os
import gzip
import pandas as pd

def select_markers(
    alignments,
    min_coverage=50.,
    max_n=10
):

    # Calculate the coverage
    alignments = alignments.assign(
        coverage = 100 * alignments.length / alignments.slen
    )

    # Filter by coverage
    alignments = alignments.query(
        f"coverage >= {min_coverage}"
    )

    # Summarize each gene
    gene_df = alignments.groupby("sseqid").apply(summarize_gene)

    # Calculate the score for each gene
    gene_df = gene_df.assign(
        score = \
            gene_df.avg_iden * \
            (gene_df.n_genomes / gene_df.n_genomes.max()) * \
            (gene_df.gene_len / gene_df.gene_len.median()).clip(upper=1)
    ).sort_values(
        by=["score", "gene_len"],
        ascending=False
    )

    # Select the top N genes which are found in at least 3 genomes
    marker_genes = gene_df.query(
        "n_genomes >= 3"
    ).head(
        max_n
    ).index.values

    return marker_genes

def summarize_gene(df):

    # Get the number of genomes
    n_genomes = df.genome.unique().shape[0]

    # Get the average amino acid identity
    avg_iden = df.pident.mean() / 100.

    # Get the gene length
    gene_len = df.slen.values[0]

    return pd.Series(
        dict(
            n_genomes=n_genomes,
            avg_iden=avg_iden,
            gene_len=gene_len
        )
    )

def subset_fasta(gene_list, fasta_in, fasta_out):
    """Filter a FASTA file to just those sequences in the provided list"""

    gene_set = set(gene_list)

    # Open the input and output file handles
    with gzip.open(fasta_out, "wt") as handle_o, gzip.open(fasta_in, "rt") as handle_i:

        for header, seq in fasta_parser(handle_i):

            if header in gene_set:

                handle_o.write(f">{header}\n{seq}\n")

def fasta_parser(handle):
    """Parse a file handle in FASTA format."""

    header = None
    seq = []

    for line in handle:
        if line[0] == ">":
            if header is not None and len(seq) > 0:
                yield header, "".join(seq)
            header = line[1:].split(" ")[0].rstrip("\n")
            seq = []
        else:
            if len(line) > 1:
                seq.append(line.rstrip("\n"))

    if header is not None and len(seq) > 0:
        yield header, "".join(seq)

if __name__ == "__main__":
    ##################
    # SET UP LOGGING #
    ##################

    # Set the level of the logger to INFO
    logFormatter = logging.Formatter(
        '%(asctime)s %(levelname)-8s [select_markers.py] %(message)s'
    )
    logger = logging.getLogger('gig-map')
    logger.setLevel(logging.INFO)

    # Write to STDOUT
    consoleHandler = logging.StreamHandler()
    consoleHandler.setFormatter(logFormatter)
    logger.addHandler(consoleHandler)

    ###################
    # PARSE ARGUMENTS #
    ###################

    # Create the parser
    parser = argparse.ArgumentParser(
        description="Select a set of marker genes from the aligned genes"
    )

    # Add the arguments
    parser.add_argument(
        '--input',
        type=str,
        required=True,
        help='Alignments of genes across genomes in CSV format'
    )
    parser.add_argument(
        '--all-genes',
        type=str,
        required=True,
        help='File containing all gene sequences in FASTA format (gzip-compressed)'
    )
    parser.add_argument(
        '--output',
        type=str,
        required=True,
        help='Subset of alignments to just those selected marker genes'
    )
    parser.add_argument(
        '--max-n',
        type=int,
        required=True,
        help='Maximum number of marker genes to select'
    )
    parser.add_argument(
        '--min-coverage',
        type=float,
        default=50.,
        help='Minimum alignment coverage threshold for selecting marker genes'
    )
    parser.add_argument(
        '--aln-fmt',
        type=str,
        default="qseqid sseqid pident length qstart qend qlen sstart send slen",
        help='Headers for the columns in the inputs, space delimited'
    )

    # Parse the arguments
    args = parser.parse_args()

    # Do not overwrite the output
    msg = f"Output already exists, stopping ({args.output}"
    assert os.path.exists(args.output) is False, msg

    # Read in the alignments
    assert os.path.exists(args.input)
    logger.info(f"Reading from {args.input}")
    alignments = pd.read_csv(args.input)

    # Filter down to the selected markers
    marker_genes = select_markers(
        alignments,
        min_coverage=args.min_coverage,
        max_n=args.max_n
    )

    # Write out the sequences of the selected markers
    subset_fasta(
        marker_genes,
        args.all_genes,
        args.output
    )


import requests
from bs4 import BeautifulSoup
import json

def get_citations_needed_count(url):
    """
    Retrieves a Wikipedia page and counts the number of citations needed.

    Args:
        url (str): The URL of the Wikipedia page.

    Returns:
        int: The number of citations needed.

    """
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    citation_needed_tags = soup.find_all('sup' , class_='noprint Inline-Template Template-Fact')
    return len(citation_needed_tags)

def get_citations_needed_report(url):
    """
    Retrieves a Wikipedia page and generates a report of passages that need citations.

    Args:
        url (str): The URL of the Wikipedia page.

    Returns:
        list: A list of text statements for each citation.

    """
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    citation_needed_tags = soup.find_all('sup' , class_='noprint Inline-Template Template-Fact')
    statements = " "

    for citation in citation_needed_tags:
        statement = citation .find_previous('p')
        # statements.append(statement.text)
        statements += statement.text

    return statements

url = 'https://en.wikipedia.org/wiki/History_of_Mexico'
count = get_citations_needed_count(url)
statements = get_citations_needed_report(url)

print(f"Number of citations needed: {count}")
print("Citations needed report:")
print(statements)

# report = {
#     "number_of_citations_needed": count,
#     "citations": statements
# }

# with open('report.json', 'w') as file:
#     json.dump(report, file)

# print(json.dumps(report, indent=4))


import xml.etree.ElementTree as ET
myTree = ET.parse('movies.xml')
myroot = myTree.getroot()

#print(myroot[3][1].attrib)
#for x in myroot[0]:
#   print(x.tag,x.attrib,x.text)

for x in myroot.findall('movie'):
    item = x.find('type').text
    print(item)

for x in myroot.iter('description'):
    a=str(x.text)+" Description has been added"
    x.text=str(a)
    x.set('updated','yes')
myTree.write('new.xml')

ET.SubElement(myroot[0],'bollywood')
for x in myroot.iter('bollywood'):
    b='comedy'
    x.text=str(b)
myTree.write('new2.xml')


import object_detection
import os
import tensorflow as tf
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
from object_detection.builders import model_builder
from object_detection.utils import config_util

#infos sur le modèle qu'on va utiliser
CUSTOM_MODEL_NAME = 'my_ssd_mobnet'
PRETRAINED_MODEL_NAME = 'ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8'
PRETRAINED_MODEL_URL = 'http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz'
TF_RECORD_SCRIPT_NAME = 'generate_tfrecord.py'
LABEL_MAP_NAME = 'label_map.pbtxt'
#chemins:
paths = {
    'WORKSPACE_PATH': os.path.join('Tensorflow', 'workspace'),
    'SCRIPTS_PATH': os.path.join('Tensorflow','scripts'),
    'APIMODEL_PATH': os.path.join('Tensorflow','models'),
    'ANNOTATION_PATH': os.path.join('Tensorflow', 'workspace','annotations'),
    'IMAGE_PATH': os.path.join('Tensorflow', 'workspace','images'),
    'MODEL_PATH': os.path.join('Tensorflow', 'workspace','models'),
    'PRETRAINED_MODEL_PATH': os.path.join('Tensorflow', 'workspace','pre-trained-models'),
    'CHECKPOINT_PATH': os.path.join('Tensorflow', 'workspace','models',CUSTOM_MODEL_NAME),
    'OUTPUT_PATH': os.path.join('Tensorflow', 'workspace','models',CUSTOM_MODEL_NAME, 'export'),
    'PROTOC_PATH':os.path.join('Tensorflow','protoc')
 }
files = {
    'PIPELINE_CONFIG':os.path.join('Tensorflow', 'workspace','models', CUSTOM_MODEL_NAME, 'pipeline.config'),
    'TF_RECORD_SCRIPT': os.path.join(paths['SCRIPTS_PATH'], TF_RECORD_SCRIPT_NAME),
    'LABELMAP': os.path.join(paths['ANNOTATION_PATH'], LABEL_MAP_NAME)
}

# Construire un modele depuis les donnees du pipeline
configs = config_util.get_configs_from_pipeline_file(files['PIPELINE_CONFIG'])
detection_model = model_builder.build(model_config=configs['model'], is_training=False)

# Restaurer le dernier checkpoint
ckpt = tf.compat.v2.train.Checkpoint(model=detection_model)
ckpt.restore(os.path.join(paths['CHECKPOINT_PATH'], 'ckpt-7')).expect_partial()

@tf.function
def detect_fn(image):#fonction recevant une image sous forme de tenseurs et execute la detection dans cette image
    image, shapes = detection_model.preprocess(image)
    prediction_dict = detection_model.predict(image, shapes)
    detections = detection_model.postprocess(prediction_dict, shapes)
    return detections

import cv2
import numpy as np
import pygame
from matplotlib import pyplot as plt

#%matplotlib inline

#creer un category index depuis la labelmap
category_index = label_map_util.create_category_index_from_labelmap(files['LABELMAP'])

def trainedmodel(IMAGE_P):#fonction pour detection d'images
    img = cv2.imread(IMAGE_P)
    image_np = np.array(img)#convertir la video image par image en tableau numpy
    #convertir l'image en tenseurs compatible avec tensorflow
    input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
    detections = detect_fn(input_tensor)#appel de la fonction de detection sur l'image convertie

    num_detections = int(detections.pop('num_detections'))
    detections = {key: value[0, :num_detections].numpy()
                  for key, value in detections.items()}
    detections['num_detections'] = num_detections

    # detection_classes should be ints.
    detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

    label_id_offset = 1
    image_np_with_detections = image_np.copy()#resultat est l'image en format numpy avec les detections effectuees
        #tracer la boite englobante
    viz_utils.visualize_boxes_and_labels_on_image_array(
                image_np_with_detections,
                detections['detection_boxes'],
                detections['detection_classes']+label_id_offset,
                detections['detection_scores'],
                category_index,
                use_normalized_coordinates=True,
                max_boxes_to_draw=5,
                min_score_thresh=.8,
                agnostic_mode=False)

    plt.imshow(cv2.cvtColor(image_np_with_detections, cv2.COLOR_BGR2RGB))
    plt.savefig("static/mygraph.png")#sauvegarder l'image resultat dans static/mygraph.png

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route('/upload', methods=['POST'])
def upload_image():
    #recuperer image uploade et la mettre dans static/image.png
    image = request.files['photo']
    image.save('static/image.png')#recuperer image uploade et la mettre dans static/image.png
    return redirect(url_for('show_image'))

@app.route("/step2")
def show_image():#afficher l'image resultat
    image_pat = 'static/image.png'
    trainedmodel(image_pat)#appel de la fonction de detection d'images
    return render_template("show_image.html", image_path='mygraph.png')

@app.route("/camera")
def camera():#fonction pour detection en temps reel
    cap = cv2.VideoCapture(0)#ouvrir camera et recuperer ses donnees
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    pygame.mixer.init()
    detection_sound = pygame.mixer.Sound('alarm.wav')

    while cap.isOpened():
        ret, frame = cap.read()
        image_np = np.array(frame)#convertir la video image par image en tableau numpy

        #convertir l'image en tenseurs compatible avec tensorflow
        input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
        detections = detect_fn(input_tensor)#appel de la fonction de detection sur l'image convertie

        num_detections = int(detections.pop('num_detections'))
        detections = {key: value[0, :num_detections].numpy()
                    for key, value in detections.items()}
        detections['num_detections'] = num_detections

        # detection_classes should be ints.
        detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

        label_id_offset = 1
        image_np_with_detections = image_np.copy() #resultat est l'image en format numpy avec les detections effectuees
        #tracer la boite englobante
        viz_utils.visualize_boxes_and_labels_on_image_array(
                    image_np_with_detections,
                    detections['detection_boxes'],
                    detections['detection_classes']+label_id_offset,
                    detections['detection_scores'],
                    category_index,
                    use_normalized_coordinates=True,
                    max_boxes_to_draw=5,
                    min_score_thresh=.75,
                    agnostic_mode=False)

        cv2.imshow('object detection',  cv2.resize(image_np_with_detections, (800, 600)))
        if detections['detection_scores'][0] >= 0.75: # Si il y a detection, emmetre le son d'alarme
            detection_sound.play()

        if cv2.waitKey(10) & 0xFF == ord('q'):
            cap.release()
            cv2.destroyAllWindows()
            break

    return render_template("index.html")
@app.route("/video", methods=['POST'])
def video():#fonction pour detection dans une video
    video = request.files['video']
    video.save('static/video.mp4')#uploader la video dans le chemin static/video.mp4
    cap = cv2.VideoCapture('static/video.mp4')#recuperer la video avec opencv
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    pygame.mixer.init()
    detection_sound = pygame.mixer.Sound('alarm.wav')

    while cap.isOpened():
        ret, frame = cap.read()
        image_np = np.array(frame)#convertir l'image en tableau numpy
        #convertir l'image en tenseurs compatible avec tensorflow
        input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
        detections = detect_fn(input_tensor)#appel de la fonction de detection sur l'image convertie

        num_detections = int(detections.pop('num_detections'))
        detections = {key: value[0, :num_detections].numpy()
                    for key, value in detections.items()}
        detections['num_detections'] = num_detections

        # detection_classes should be ints.
        detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

        label_id_offset = 1
        image_np_with_detections = image_np.copy() #resultat est l'image en format numpy avec les detections effectuees
        #tracer la boite englobante
        viz_utils.visualize_boxes_and_labels_on_image_array(
                    image_np_with_detections,
                    detections['detection_boxes'],
                    detections['detection_classes']+label_id_offset,
                    detections['detection_scores'],
                    category_index,
                    use_normalized_coordinates=True,
                    max_boxes_to_draw=5,
                    min_score_thresh=.75,
                    agnostic_mode=False)

        cv2.imshow('object detection',  cv2.resize(image_np_with_detections, (800, 600)))

        if detections['detection_scores'][0] >= 0.75:  # Si il y a detection, emmetre le son d'alarme
            detection_sound.play()

        if cv2.waitKey(10) & 0xFF == ord('q'):
            cap.release()
            cv2.destroyAllWindows()
            break

    return render_template("index.html")

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


n= int(input())
for _ in range(n):
  ck= 1
  x= list(map(int,input()))[::-1]
  for i in range(len(x)):
    if i == ck:
      num= x[i]*2

      if num > 9:
        while num > 9:
          res= 0
          for k in list(map(int,str(num))):
              res+= int(k)
          num = res
        x[i]= num

      x[i]= num
      ck+=2
  if sum(x)%10==0:
    print("PASS")
  else:
    print("FAIL")


from flask import Flask, request, Response, render_template
import os
import socket
import threading
import webbrowser
import subprocess
import requests
import json
import time

import conf
import util

app = Flask(__name__)

port = None
browser_process = None

@app.route('/keycloak.json')
def controller_keycloak_conf():
    return render_template("keycloak.json", idp_url=conf.IDP_URL, client_name=conf.IDP_CLIENT_NAME)

@app.route('/login')
def controller_login():
    return render_template("login.html", idp_url=conf.IDP_URL, port=port)

@app.route('/deliver-tokens', methods=['POST'])
def controller_deliver_tokens():
    if request.is_json:
        body = request.get_json()
        _write_tokens(body['access_token'], int(body['access_token_valid_sec']), body['refresh_token'])

        #if browser_process is not None:
        #    print("Terminating")
        #    browser_process.terminate()
        #else:
        #    print("Browser process is None ???")

        _shutdown_server()

        return Response(status=200)

    else:
        return Response(status=400)

def _write_tokens(access_token, valid_sec, refresh_token):
    access_token_file = json.dumps({
        'access_token': access_token,
        'expires_at': round(time.time()) + valid_sec
    })

    util.write_restricted_file('access_token', access_token_file)
    util.write_restricted_file('refresh_token', refresh_token)

def _shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

def _get_free_port():
    for p in range(conf.AUTH_PORT_RANGE_FIRST, conf.AUTH_PORT_RANGE_LAST + 1):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind(('127.0.0.1', p))
            sock.close()
            return p
        except OSError:
            # Port already in use?
            pass

    raise OSError("Unable to bind to ports {} - {}".format(conf.AUTH_PORT_RANGE_FIRST, conf.AUTH_PORT_RANGE_LAST))

def _open_browser(url):
    global browser_process
    webbrowser.open(url)
    #browser_name = webbrowser.get().name
    #browser_process = subprocess.Popen([browser_name, url],
    #                                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

def _refresh_using_refresh_token() -> bool:
    if not os.path.isfile('refresh_token'):
        util.debug("No refresh token found")
        return False

    with open('refresh_token') as f:
        refresh_token = f.read()

    token_req_body = {
        'grant_type': 'refresh_token',
        'refresh_token': refresh_token,
        'client_id': conf.IDP_CLIENT_NAME
    }

    r = requests.post(conf.IDP_URL + "/auth/realms/master/protocol/openid-connect/token", data=token_req_body)

    if r.status_code == 200:
        resp_body = r.json()
        _write_tokens(resp_body['access_token'], resp_body['expires_in'], resp_body['refresh_token'])
        util.debug("Refreshed tokens using refresh token")
        return True
    else:
        util.warn("Refreshing tokens failed with status {}".format(r.status_code))
        return False

def auth():
    global port

    if _refresh_using_refresh_token():
        return

    port = _get_free_port()
    url = 'http://127.0.0.1:{}/login'.format(port)

    # Assume the server starts in 1 second
    threading.Timer(1, lambda: _open_browser(url)).start()

    app.run(host='127.0.0.1', port=port)

if __name__ == '__main__':
    auth()


import turtle
kép = turtle.Screen()
Sanyi = turtle.Turtle()
kép.bgcolor("lightgreen")
Sanyi.color("blue")
Sanyi.pensize(3)
Sanyi.speed(0.01)
for x in range(0, 5):
    Sanyi.forward(200)
    Sanyi.right(144)
kép.mainloop()


import os
import sys
import hashlib
import subprocess
import csv
import json
import argparse
import pandas as pd
from datetime import datetime

class ReproductionOracle:

    def __init__(self):
        self.bug_id = ''
        self.program = ''
        self.bug_type = ''
        self.crash_path = ''
        self.crash_input_file = ''
        self.output_csv_file = ''
        self.binary_file = ''
        self.flags = ''
        self.prog_output = ''
        self.oracle_config = ''
        self.bt_full = ''
        self.bt_func = ''
        self.crash_inst = ''
        self.tmp_crash_details = ''
        self.signature_hash = ''
        self.my_sig = ''
        self.oracle = ''
        self.signal = False
        self.file_exist = False
        #self.writer = None
        self.crash_dict = dict()
        self.hash_set = set([])
        #self.csv_rows = []
        self.whitelist = ['libdislocator', '__GI_', '__assert_fail', 'libc_','__stack_','libc.so',
        'libasan.so','libc_start_main','_start']
        self.curr_dir = os.path.dirname(os.path.realpath(__file__))

    def check_white_list(self,line):
        for item in self.whitelist:
            if item in line:
                return True
        return False

    def get_path_to_line(self,directory, line):
        if "/" in line:
            line = os.path.basename(line)

        for path, subdirs, files in os.walk(directory):
            for file_name in files:
                file_to_assess = os.path.join(path, file_name)
                #print(file_name)
                if os.path.isfile(file_to_assess):
                    if file_name.strip() == line.strip().split(":")[0]:
                        print(os.path.join(path, line))
                        return os.path.join(path, line)
        return None

    def get_line(self,file_name):
        # tmp
        if "./" in file_name:
            file_name = file_name.replace("./","/")
        tmp_line = ''
        num = 0
        if ":" not in file_name: return
        with open(file_name.split(":")[0].strip()) as fp:
            if ".c"in file_name:
                num = int(file_name.split(".c:")[1].strip())
            else:
                num = int(file_name.split(".h:")[1].strip())
            count=1
            for line in fp:
                if count == num:
                    #return line
                    if ";" in line:
                        if ";" in tmp_line:
                            return tmp_line+line
                        else:
                            return tmp_line+line
                    else:
                        tmp_line+=line
                        num = count+1
                        #print(num)
                count+=1

    def read_job_file(self,filename):
        with open(filename,'r') as json_file:
            cve_json_data = json.load(json_file)
            # Bug id can be autogenerated aswell
        self.bug_id = cve_json_data['bug_id'].strip()
        self.program = cve_json_data['program'].strip()
        self.bug_type = cve_json_data['bug_type'].strip()
        self.crash_path = cve_json_data['crash_path'].strip()
        self.crash_input_file = cve_json_data['crash_input_file'].strip()
        self.output_csv_file = cve_json_data['output_csv_file'].strip()
        self.binary_file = cve_json_data['binary_file'].strip()
        self.flags = cve_json_data['flags'].strip()
        if self.flags.lower() == 'n/a': self.flags = ''
        self.prog_output = cve_json_data['prog_output'].strip()
        if self.prog_output.lower() == 'n/a': self.prog_output = ''
        self.oracle_config = cve_json_data['oracle_config'].strip()
        if self.oracle_config.lower() == 'n/a': self.oracle_config = ''

    """
    save features/symptoms to a CSV file
    """
    def commit_to_csv(self,csv_rows):
        self.file_exist = False
        if os.path.exists(self.output_csv_file):
            self.file_exist = True
            print("[*] {0} File Exists ".format(self.output_csv_file))
        with open(self.output_csv_file, "a") as out_file:
            writer = csv.writer(out_file)
            if not self.file_exist:
                writer_fields = ['id', 'bug_id', 'program', 'signal',
                'bug_type' ,'crash_func_full','crash_func',
                'back_trace_full','back_trace_func','crash_line']
                writer.writerow(writer_fields)
            writer.writerows(csv_rows)

    def exec_commands(self, oracle='gdb'):
        self.crash_dict = dict()
        self.hash_set = set([])
        self.signal = False
        csv_rows = []
        cmd = ''
        cmd_output = None
        stdout = None
        stderr = None
        cras_lst = []
        if self.oracle_config == 'no_preload':
            gdb_script = './gdb_bt_script_no_preload.gdb'
        else:
            gdb_script = './gdb_bt_script.gdb'
        self.oracle = oracle
        print("=====================================")
        print("[*]Processing Bug: [{0}]".format(self.bug_id))
        if oracle == 'gdb':
            print("[*]Oracle is: [GDB Debugger]")
        elif oracle == 'asan':
            print("[*]Oracle is: [Address Sanitizer]")

        with open(self.crash_input_file) as crash_file:
            for filename in crash_file:
                filename = os.path.join(self.curr_dir,filename)
                filename = filename.strip()
                if oracle == 'gdb':
                    if self.flags and self.prog_output:
                        cmd = 'gdb --batch --command='+gdb_script+' --args '+self.binary_file+' '+self.flags+' '+filename+' '+self.prog_output
                    elif self.flags:
                        cmd = 'gdb --batch --command='+gdb_script+' --args '+self.binary_file+' '+self.flags+' '+filename
                    elif self.prog_output:
                        cmd = 'gdb --batch --command='+gdb_script+' --args '+self.binary_file+' '+filename+' '+self.prog_output
                        #print("[*]Command: {0}".format(cmd))
                        #print(cmd)
                    else:
                        #print("Yeah")
                        cmd = 'gdb --batch --command='+gdb_script+' --args '+self.binary_file+' '+filename
                    #print("[*]Command: {0}".format(cmd))
                    #print("Command:[{0}]".format(cmd))
                    tmp_out = subprocess.Popen("rm *.tif ", shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    cmd_output = subprocess.Popen("timeout 2 "+cmd, shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    stdout,stderr = cmd_output.communicate()
                    stdout = stdout.splitlines()
                    self.parse_gdb_crash(stdout,stderr,filename)
                elif oracle == 'asan':
                    if self.flags and self.prog_output:
                        cmd = self.binary_file+' '+self.flags+' '+filename+' '+self.prog_output
                    elif self.flags:
                        cmd = self.binary_file+' '+self.flags+' '+filename
                    elif self.prog_output:
                        cmd = self.binary_file+' '+filename+' '+self.prog_output
                        #print(cmd)
                    else:
                        cmd = self.binary_file+' '+filename#+' ou.tif'
                    tmp_out = subprocess.Popen("rm *.tif", shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    cmd_output = subprocess.Popen("timeout 1 "+cmd, shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    stdout,stderr = cmd_output.communicate()
                    stdout = stdout.splitlines()

                    #print("[*]Command: {0}".format(cmd))
                    if len(stdout) <10:
                        print("[*] {0} didnt crash".format(filename))
                        continue
                    else:
                        #print("[*]Command: {0}".format(stdout))
                        self.parse_asan_crash(stdout,stderr,filename)
                else:
                    print("[*] Invalid reproduction oracle {0}".format(self.oracle))
                    exit(1)
                if self.signature_hash not in self.hash_set and self.signal:
                    try:
                        print("=====================================")
                        print("           Summary")
                        print("=====================================")
                        print("[*]BT Full: {0}".format(self.bt_full))
                        print("[*]BT Func: {0}".format(self.bt_func))
                        crash_func_full = self.bt_full.split("<-")[1].strip()
                        print("[*]Crash Func Full: {0}".format(crash_func_full))
                        crash_func = self.bt_func.split("<-")[1].strip()
                        print("[*]Crash Funct: {0}".format(crash_func))
                        print("[*]Signal: {0}".format(self.my_sig))
                        print("[*]Crash Instruction: {0}".format(self.crash_inst))
                        cr_line = self.tmp_crash_details.split("<-")[1].strip()
                        print("[*]Crash Line 1: {0}".format(cr_line))
                        cr_line = cr_line.split("@")[1].strip()
                        print("[*]Crash Line 2: {0}".format(cr_line))

                        if oracle == 'gdb':
                            print("[*]Line Searched: {0}".format(os.path.join(self.crash_path,cr_line)))
                            path_to_file = self.get_path_to_line(self.crash_path, cr_line)
                            cr_line = self.get_line(path_to_file).strip()
                        elif oracle == 'asan':
                            print("[*]Line Searched: {0}".format(os.path.join(self.crash_path,cr_line)))
                            path_to_file = self.get_path_to_line(self.crash_path, cr_line)
                            cr_line = self.get_line(path_to_file).strip()
                        print("[*]Crash Line 3: {0}".format(cr_line))
                        print("------------------------------------")

                    except Exception as e:
                        print("Error: {0}".format(e))
                        continue
                    row = [self.signature_hash, self.bug_id, self.program, self.my_sig, self.bug_type,
                           crash_func_full, crash_func, self.bt_full, self.bt_func, cr_line]
                    self.hash_set.add(self.signature_hash)
                    csv_rows.append(row)
                if self.signature_hash in self.crash_dict and self.signal:
                    self.crash_dict[self.signature_hash].append(filename)
                elif self.signature_hash not in self.crash_dict and self.signal:
                    self.crash_dict[self.signature_hash] = [filename]
        self.commit_to_csv(csv_rows)

    def parse_gdb_crash(self,stdout,stderr,filename):
        self.crash_inst = ''
        self.bt_full = ''
        self.bt_func = ''
        self.tmp_crash_details = ''
        self.my_sig = ''
        self.signal = False
        my_ins = []
        crash_in_lib = True

        for line in stdout:
            line = line.decode("utf-8",errors='ignore')
            if not line: continue
            if "received signal" in line:
                self.signal = True
                self.my_sig =  line.split("signal",1)[1]
                self.my_sig =  self.my_sig.split(",",1)[0].strip()
                fl = self.crash_input_file.split("/")
                fl = fl[-1]
                self.bug_type = "unknown"
            if self.signal:
                if "__GI_" in line or "__assert_fail" in line or "libc_" in line or "__stack_" in line \
                or "libdislocator" in line or "_IO_new_file" in line or "malloc.c" in line \
                or "_IO_new_fclose" in line:
                    continue
                if "#" in line and "in" in line and "at" in line and ".c:"in line:
                    crash_in_lib = False
                    my_ins = line.split()
                    if "#" in str(my_ins[0]) and "0x" in str(my_ins[1]):
                        self.bt_full+= "<-"+str(my_ins[3].strip())+"@"+os.path.basename(my_ins[-1])
                        self.bt_func+= "<-"+str(my_ins[3].strip())
                        self.tmp_crash_details+= "<-"+str(my_ins[3].strip())+"@"+my_ins[-1].strip()
                    elif "#" in str(my_ins[0]) and "0x" not in str(my_ins[1]):
                        self.bt_full+= "<-"+str(my_ins[1].strip()+"@"+os.path.basename(my_ins[-1]))
                        self.bt_func+= "<-"+str(my_ins[1].strip())
                        self.tmp_crash_details+= "<-"+str(my_ins[1].strip()+"@"+my_ins[-1].strip())
                if "=>" in line:
                    self.crash_inst =  line.split(":")[1].strip()
        with open(filename, 'rb') as poc:
            buf = poc.read()
            self.signature_hash = hashlib.sha256(buf).hexdigest()
        #self.signature_hash = hashlib.sha256(self.bt_full.encode()).hexdigest()
        #print(self.signature_hash)

    def parse_asan_crash(self,stdout,stderr,filename):
        self.crash_inst = ''
        self.bt_full = ''
        self.bt_func = ''
        self.tmp_crash_details = ''
        self.my_sig = ''
        self.signal = False
        my_ins = []
        crash_in_lib = True

        for line in stdout:
            line = line.decode("utf-8",errors='ignore')
            if not line: continue
            if "ERROR: AddressSanitizer:" in line:
                if "AddressSanitizer failed to allocate" in line:
                    self.bug_type = line.split("AddressSanitizer")[1].split("0x")[0].strip()
                elif "on address" in line and "AddressSanitizer" in line:
                    self.bug_type = line.split("AddressSanitizer:")[1].split("on")[0].strip()
                elif "detected" in line and "LeakSanitizer" in line and "on" in line:
                    self.bug_type = line.split("detected")[1].split("on")[0].strip()
                elif "detected" in line and "LeakSanitizer" in line:
                    self.bug_type = line.split("detected")[1].strip()
                else:
                    self.bug_type = 'unknown'
                sig_type = line.split("AddressSanitizer:")[1]
                sig_type = sig_type.split("on")[0].strip()
                if "buffer" in sig_type or "SEGV" in sig_type or "use-after" in sig_type:
                    self.my_sig = 'SIGSEGV'
                elif "FPE" in sig_type:
                    self.my_sig = 'SIGFPE'
                else:
                    self.my_sig = 'Unknown'
                self.signal = True
                fl = self.crash_input_file.split("/")
                fl = fl[-1]
            if self.signal:
                if "#" in line and "0x" in line and ("libc.so" not in line.strip().lower()
                and "libasan.so" not in line.strip().lower() and "libc_start_main" \
                not in line.strip().lower() and "_start" not in line):
                    crash_in_lib = False
                    my_ins = line.split()
                    if "#" in str(my_ins[0]) and "0x" in str(my_ins[1]):
                        if "_start" in my_ins[3].strip() or "__libc_start_main" in my_ins[3].strip(): continue
                        self.bt_full+= "<-"+str(my_ins[3].strip())+"@"+os.path.basename(my_ins[-1])
                        self.bt_func+= "<-"+str(my_ins[3].strip())
                        self.tmp_crash_details+= "<-"+str(my_ins[3].strip())+"@"+my_ins[-1].strip()
                    elif "#" in str(my_ins[0]) and "0x" not in str(my_ins[1]):
                        self.bt_full+= "<-"+str(my_ins[1].strip()+"@"+os.path.basename(my_ins[-1]))
                        self.bt_func+= "<-"+str(my_ins[1].strip())
                        self.tmp_crash_details+= "<-"+str(my_ins[1].strip()+"@"+my_ins[-1].strip())
                if "=>" in line:
                    self.crash_inst =  line.split(":")[1].strip()
                else:
                    self.crash_inst = "N/A"
            if "can not provide additional" in line: break
            if "allocated by thread" in line: break
        with open(filename, 'rb') as poc:
            buf = poc.read()
            self.signature_hash = hashlib.sha256(buf).hexdigest()
        #self.signature_hash = hashlib.sha256(self.bt_full.encode()).hexdigest()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description= "Crash Reproduction Oracle for Extracting Symptoms")
    parser.add_argument("-g","--gdb",dest="gdb",default=None, help="Reproduce crash using GDB Debugger")
    parser.add_argument("-a","--asan",dest="asan",default=None,help="Reproduce crash using Address Sanitizer")
    args = parser.parse_args()
    rep_oracle = ReproductionOracle()

    if len(sys.argv) == 1:
        parser.print_help()
    if args.gdb:
        rep_oracle.read_job_file(args.gdb)
        rep_oracle.exec_commands()
    elif args.asan:
        rep_oracle.read_job_file(args.asan)
        rep_oracle.exec_commands(oracle='asan')


import json
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from urllib import response

import boto3

today = datetime.now(timezone.utc)
INACTIVITY_DAYS = 90

def check_date(date_to_check, days_to_expire=90):
    expired_date = today - timedelta(days_to_expire)

    if isinstance(date_to_check, str):
        snapshot_date_obj = datetime.fromisoformat(date_to_check)
    else:
        snapshot_date_obj = date_to_check

    try:
        results = snapshot_date_obj - expired_date
        if results.days <= 0:
            return True
        else:
            return False
    except Exception as err:
        print(err)

def datetime_converter(json_dict):
    """convert datetime in json dict to string."""
    if isinstance(json_dict, datetime):
        return json_dict.__str__()

client = boto3.client("iam")

response = client.get_paginator("list_roles").paginate().build_full_result()
all_role_names = [role["RoleName"] for role in response["Roles"]]

# print(json.dumps(response, default=datetime_converter, indent=4))

for role_name in all_role_names:
    response = client.get_role(RoleName=role_name)
    if "RoleLastUsed" in response["Role"]:
        if "LastUsedDate" in response["Role"]["RoleLastUsed"]:
            lastUsedDate = response["Role"]["RoleLastUsed"]["LastUsedDate"]
            if check_date(date_to_check=lastUsedDate, days_to_expire=INACTIVITY_DAYS):
                print(
                    f"The role {role_name}, with lastUsedDate {lastUsedDate} has expired.",
                )
            # else:
            #     print(f"The role {role_name}, with lastUsedDate {lastUsedDate} has not expired.")


# -*- coding: utf-8 -*-
"""
Created on Thu Sep  9 20:59:46 2021

@author: ivand

@Dado un string (definido por ti), escribe un programa que genere un diccionario
 en donde la llave es la posición de cada caracter del string y el valor el
 propio caracter.
"""

x = 'mineria de datos'
y = list(x)
z = {k:v for k, v in enumerate(y)}
print(z)


def dense_to_sparse(tensor):
    r"""Converts a dense adjacency matrix to a sparse adjacency matrix defined
    by edge indices and edge attributes.

    Args:
        tensor (Tensor): The dense adjacency matrix.
     :rtype: (:class:`LongTensor`, :class:`Tensor`)
    """
    assert tensor.dim() == 2
    index = tensor.nonzero().t().contiguous()
    value = tensor[index[0], index[1]]
    return index, value


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

"""solution uses a one dimensional data structure.
   we keep track of horizontal and vertical layout
   by storing the necessary positions to check.
"""
indexes = [
    [0, 1, 2, 3, 4],
    [5, 6, 7, 8, 9],
    [10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19],
    [20, 21, 22, 23, 24],
    [0, 5, 10, 15, 20],
    [1, 6, 11, 16, 21],
    [2, 7, 12, 17, 22],
    [3, 8, 13, 18, 23],
    [4, 9, 14, 19, 24]
]

class Board:
    def __init__(self, numbers):
        """one dimensional array of tuples (number, is_striked_out)"""
        self.items = [ (n, False) for n in numbers]
        self.has_won = False

    def _eval_winning_condition(self) -> None:
        for i in indexes:
            if (all(self.items[x][1] == True for x in i)):
                self.has_won = True
                return

    def calc_score(self, winner) -> int:
        return winner * sum([x[0] if x[1] == False else 0 for x in self.items])

    def strikeout(self, number) -> None:
        """"marks given number and evaluates winning condition"""
        for idx, x in enumerate(self.items):
            if x[0] == number:
                self.items[idx] = (number, True)

        self._eval_winning_condition()

    def wins(self) -> bool:
        return self.has_won

    @staticmethod
    def open_boards(boards) -> int:
        """"""
        return sum([0 if b.wins() else 1 for b in boards])

    def __str__(self) -> str:
        return " ".join(f"({i[0]}/{i[1]})" for i in self.items)

def init_board_from_input(lines):
    return [int(x) for x in " ".join(lines).split() if x.isdigit()]

def read_input(filename: str):
    with open(filename, "r") as f:
        numbers = [int(x) for x in f.readline().rstrip().split(",")]

        # split and filter empty lines
        lines = list(filter(None, f.read().splitlines()))

    boards = [ Board(init_board_from_input(lines[i:i+5]) ) for i in range(0, len(lines), 5)  ]

    return numbers, boards

def part_1(filename: str) -> None:
    numbers, boards = read_input(filename)

    for number in numbers:
        for idx, board in enumerate(boards):

            board.strikeout(number)

            if board.wins():
                score = board.calc_score(number)
                print(f"{idx+1} wins with {score} points")
                return

def part_2(filename: str) -> None:
    numbers, boards = read_input(filename)

    for number in numbers:
        for idx, board in enumerate(boards):
            if board.wins():
                continue

            board.strikeout(number)

            if board.wins() and Board.open_boards(boards) == 0:
                score = board.calc_score(number)
                print(f"{idx+1} wins with {score} points")
                return

if __name__ == "__main__":
    filename = sys.argv[1]

    part_1(filename)
    part_2(filename)


'''Operates on output of read_data.py.
Stacks numpy arrays from folders, and store result from each
folder as a numpy array (with the same name + .npy).
Also strips out corrupted npys (WHY do they get corrupted?)'''
from pathlib import Path
import numpy as np

folders = Path('./processed_data').glob('*/')
folders = ['processed_data']
for folder in folders:
    fns = (x for x in Path(str(folder)).glob('*/') if x.is_dir())
    for fn in fns:
        files = Path(str(fn)).glob('*.npy')
        name = str(fn)
        arrays = []
        for afile in files:
            anarray = np.load(str(afile))
            arrays.append(np.squeeze(anarray))
        print(fn)
        print(np.array(arrays).shape)
        np.save(str(fn), np.array(arrays))


from django.conf.urls import url, include
from management import views
from rest_framework.routers import DefaultRouter

# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'restaurants', views.RestaurantViewSet)
router.register(r'dishes', views.DishViewSet)
router.register(r'images', views.ImageResourceViewSet)
router.register(r'videos', views.VideoResourceViewSet)

urlpatterns = [
    url(r'^', include(router.urls))
]


import sqlite3

class BotDB:
    def __init__(self, db_file: str):
        self.conn = sqlite3.connect(db_file)
        self.cursor = self.conn.cursor()

        self.cursor.execute('''CREATE TABLE IF NOT EXISTS "categories" (
	"id"	INTEGER NOT NULL UNIQUE,
	"name"	TEXT NOT NULL,
	PRIMARY KEY("id" AUTOINCREMENT)
);''')
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS "products" (
	"id"	INTEGER NOT NULL UNIQUE,
	"name"	TEXT NOT NULL,
	"category_id"	TEXT NOT NULL,
	"description"	TEXT,
	"price"	REAL NOT NULL,
	"image_path"	TEXT,
	PRIMARY KEY("id" AUTOINCREMENT),
	FOREIGN KEY("category_id") REFERENCES "categories"("id")
);''')
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS "orders" (
	"id"	INTEGER NOT NULL UNIQUE,
	"user_id"	INTEGER NOT NULL,
	"product_id"	INTEGER NOT NULL,
	"order_date"	TEXT NOT NULL,
	"delivery_date"	TEXT NOT NULL,
	PRIMARY KEY("id" AUTOINCREMENT),
	FOREIGN KEY("user_id") REFERENCES "users"("id"),
	FOREIGN KEY("product_id") REFERENCES "products"("id")
);''')
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS "users" (
	"id"	INTEGER NOT NULL UNIQUE,
	"user_telegram_id"	INTEGER NOT NULL,
	"nickname"	TEXT NOT NULL,
	"phone_number"	INTEGER NOT NULL,
	PRIMARY KEY("id" AUTOINCREMENT)
);''')

    def user_exists(self, user_id: int):
        result = self.cursor.execute("SELECT id FROM users WHERE user_telegram_id = ?", (user_id,))
        return bool(len(result.fetchall()))

    def add_user(self, user_id: int, nickname: str, phone_number: int):
        self.cursor.execute("INSERT INTO users (user_telegram_id, nickname, phone_number) VALUES(?, ?, ?)", (user_id, nickname, phone_number))
        return self.conn.commit()

    def get_categories(self):
        result = self.cursor.execute("SELECT name FROM categories").fetchall()
        lst = []
        for i in result:
            lst.append(i[0])
        return lst

    def get_category_id(self, category: str):
        result = self.cursor.execute("SELECT id FROM categories WHERE name = ?", (category,)).fetchall()
        return result[0]

    def get_products_in_category(self, category_id: int):
        result = self.cursor.execute("SELECT name FROM products WHERE category_id = ?", (category_id)).fetchall()
        lst = []
        for i in result:
            lst.append(i[0])
        return lst

    def get_product_id(self, product_name: str):
        return self.cursor.execute("SELECT id FROM products WHERE name = ?", (product_name,)).fetchall()[0]

    def get_product(self, product_id: int):
        return {
            'id': product_id[0],
            'name': self.cursor.execute("SELECT name FROM products WHERE id = ?", (product_id)).fetchall()[0][0],
            'category_id': self.cursor.execute("SELECT category_id FROM products WHERE id = ?", (product_id)).fetchall()[0][0],
            'description': self.cursor.execute("SELECT description FROM products WHERE id = ?", (product_id)).fetchall()[0][0],
            'price': self.cursor.execute("SELECT price FROM products WHERE id = ?", (product_id)).fetchall()[0][0],
            'image_path': self.cursor.execute("SELECT image_path FROM products WHERE id = ?", (product_id)).fetchall()[0][0]
        }

    def add_order(self, user_id: int, product_id: int, order_date: str, delivery_date: str):
        self.cursor.execute("INSERT INTO orders (user_id, product_id, order_date, delivery_date) VALUES(?, ?, ?, ?)", (user_id, product_id, order_date, delivery_date))
        return self.conn.commit()

    def close(self):
        self.conn.close()


import uuid
from ..admin import Get
from dao import ApiKeyDAO
from utils.check_active import CheckActive

class Create:
    """Class for creating an API key."""

    def __init__(self, admin_id: int = None, api_key: str = None) -> None:
        """
        Initialize a Create instance.

        Args:
            admin_id (int, optional): The ID of the admin account. Defaults to None.
            api_key (str, optional): The API key for authentication. Defaults to None.
        """
        self.admin_id = admin_id
        self.api_key = api_key
        self.response = self.__create()

    def __create(self) -> dict:
        """
        Create an API key.

        Returns:
            dict: A dictionary containing the response of the operation.
                If successful, the dictionary will have a "success" key with a message,
                the generated API key, the API key owner's ID, and the active status.
                If unsuccessful, the dictionary will have an "error" key with a message.
        """
        if __name__ != "__main__":
            if not CheckActive(self.api_key).get_response():
                return {"error": "Invalid API Key"}
            admin_account = Get(self.admin_id).get_response()
            if not admin_account:
                return {"error": "Admin account does not exist"}
            elif admin_account["role"] != "superadmin":
                return {"error": "You do not have permission to generate API keys"}

        try:
            random_api_key_gen: str = uuid.uuid4().hex
            with ApiKeyDAO() as api_key_dao:
                api_key_dao.create(self.admin_id, random_api_key_gen)
            return {
                "success": "API key generated",
                "api_key": random_api_key_gen,
                "api_key_owner_id": self.admin_id,
                "active": True
            }
        except Exception as e:
            print(e)
            return {"error": "Failed to generate API key"}

    def get_response(self) -> dict:
        """
        Get the response of the API key creation.

        Returns:
            dict: A dictionary containing the response of the API key creation.
        """
        return self.response


import numpy as np
import pandas as pd

names = ['Bob', 'Jessica', 'Mary', 'John', 'Mel']
births = [968, 155, 77, 578, 973]

BabyDataSet = list(zip(names, births))
print(BabyDataSet)

df = pd.DataFrame(data=BabyDataSet, columns=['Names', 'Births'])
print(df)

# df.to_csv('births1880.csv', index=False, header=True)
#
# df = pd.read_csv('births1880.csv')
# print(df)
#
# df = pd.read_csv('births1880.csv', names=['Names', 'Births'])
# print(df)

#To find the most popular name or the baby name with the higest birth rate, we can do one of the following
# Method 1:
Sorted = df.sort_values(['Births'], ascending=False)
print(Sorted.head(1))

# Method 2:
print(df['Births'].max())

df['Births'].plot()


import re

def replace(text: str, replacement: str = 'QUOTE') -> str:
    """Replaces direct quotes in text with a placeholder token.

    Args:
        text: String. A contiguous sequence of text from which you want to
            extract direct quotes.
        replacement: String. The placeholder to put in place of direct quotes.

    Returns:
        String: original text with direct quotes replaced by `replacement`.

    Example:
        extract('They said, "This is my quote."', 'QUOTE') -> 'They said QUOTE.'
    """
    regex = r"\B[‘\'\"](.*?)[’\'\"\"]+(?=$|\s)\B|\B[’\'\"](.*[^\'\s])+(?=$|\s)"
    result = re.sub(regex, replacement, text, 0, re.MULTILINE)

    return result


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: skip-file

import json

import reflex as rx

from app.views.utils.view_interface import ViewInterface

class FooterView(ViewInterface):
    """Builds the app navbar"""

    def build(self):
        """Inheritdoc"""

        file = open("version.json", encoding="utf-8")

        v_file = json.load(file)

        home_link = rx.text(
            "Version: " + v_file["version"],
            font_size="10px",
            as_="b",
            padding_right="30px",
            padding_bottom="10px",
        )

        return rx.hstack(
            rx.spacer(),
            home_link,
            position="fixed",
            width="100%",
            bottom="0px",
            z_index="999",
        )


import gzip
import os
import random
import tempfile
import uuid
from io import BytesIO
from unittest import TestCase

import corehq.blobs.util as mod
from corehq.blobs.exceptions import GzipStreamError

class TestRandomUrlId(TestCase):

    sample_size = 100

    def setUp(self):
        self.ids = [mod.random_url_id(8) for x in range(self.sample_size)]

    def test_random_id_length(self):
        self.assertGreater(min(len(id) for id in self.ids), 0, self.ids)
        self.assertEqual(max(len(id) for id in self.ids), 11, self.ids)

    def test_random_id_randomness(self):
        self.assertEqual(len(set(self.ids)), self.sample_size, self.ids)

class TestGzipStream(TestCase):

    def test_compression(self):
        desired_size = mod.GzipStream.CHUNK_SIZE * 4
        content = uuid.uuid4().bytes * 4
        while len(content) < desired_size:
            content += uuid.uuid4().bytes * 4

        compress_stream = mod.GzipStream(BytesIO(content))
        with tempfile.NamedTemporaryFile() as compressed_f:
            compressed_f.write(compress_stream.read())
            compressed_f.flush()
            with gzip.open(compressed_f.name, 'r') as reader:
                actual = reader.read()
            file_size = os.stat(compressed_f.name).st_size
            self.assertGreater(len(content), file_size)
        self.assertEqual(content, actual)
        self.assertEqual(len(content), compress_stream.content_length)

    def test_content_length_access(self):
        with tempfile.NamedTemporaryFile() as f:
            f.write(b"x" * 11)
            f.seek(0)
            compress_stream = mod.GzipStream(f)

            # Try to read content_length without reading the stream
            with self.assertRaises(GzipStreamError):
                compress_stream.content_length  # noqa

            # Try to read content_length after partially reading the stream
            content_length = len(compress_stream.read(5))
            with self.assertRaises(GzipStreamError):
                compress_stream.content_length  # noqa

            # Read content_length after completely reading the stream and check
            # that it's correct
            content_length += len(compress_stream.read())
            self.assertNotEqual(compress_stream.content_length, content_length)
            self.assertEqual(compress_stream.content_length, 11)

    def test_content_length_0(self):
        # NOTE invariant based on GzipFile implementation
        zipper = mod.GzipStream(BytesIO(b""))
        zipper.read(10)
        assert zipper._buf.size == 0, f"invariant failed ({zipper._buf.size})"
        with self.assertRaises(GzipStreamError):
            zipper.content_length
        zipper.read()
        self.assertEqual(zipper.content_length, 0)

    def test_content_length_1(self):
        # NOTE invariant based on GzipFile implementation
        zipper = mod.GzipStream(BytesIO(b"x"))
        zipper.read(10)
        assert zipper._buf.size == 0, f"invariant failed ({zipper._buf.size})"
        with self.assertRaises(GzipStreamError):
            zipper.content_length
        zipper.read()
        self.assertEqual(zipper.content_length, 1)

    def test_content_length_10x_chunk(self):
        # NOTE invariant based on GzipFile implementation
        self.addCleanup(random.seed)
        random.seed(42)
        size = mod.GzipStream.CHUNK_SIZE * 10
        data = bytes(random.getrandbits(8) for _ in range(size))
        zipper = mod.GzipStream(BytesIO(data))
        zipper.read(16405)
        assert zipper._buf.size == 0, f"invariant failed ({zipper._buf.size})"
        with self.assertRaises(GzipStreamError):
            zipper.content_length
        zipper.read()
        self.assertEqual(zipper.content_length, size, "bad content length")

    def test_content_length_after_partial_read_and_close(self):
        # NOTE invariant based on GzipFile implementation
        zipper = mod.GzipStream(BytesIO(b""))
        zipper.read(1)
        assert zipper._buf.size, f"invariant failed ({zipper._buf.size})"
        zipper.close()
        with self.assertRaises(GzipStreamError):
            zipper.content_length

    def test_content_length_after_full_read_and_close(self):
        zipper = mod.GzipStream(BytesIO(b"x"))
        zipper.read()
        zipper.close()
        self.assertEqual(zipper.content_length, 1)


import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dropout, Flatten, Dense
from keras import applications
from keras.utils.np_utils import to_categorical

import models_configuration as mc
import tensorflow as tf
import math
import os
import cv2
# dimensions of our images.
img_width, img_height = 64, 64

# weights_path = 'models/vgg16_weights.h5'
top_model_weights_path = 'shoe_model_shape_vgg16_3.h5'
train_data_dir = 'shoe-dataset-shape/train/'
validation_data_dir = 'shoe-dataset-shape/validation'
train_feature = 'shoe_features_shape_train.npy'
validation_feature = 'shoe_features_shape_validation.npy'
epochs = 50
batch_size = 30
classes = 9

nb_train_samples = 32365
nb_validation_samples = 7926

tf.device('/device:GPU:0')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

from keras import backend as K
K.set_image_dim_ordering('th')

def save_bottlebeck_features():
    datagen = ImageDataGenerator(rescale=1. / 255)

    # build the VGG16 network
    model = applications.VGG16(include_top=False, weights='imagenet')

    train_generator = datagen.flow_from_directory(train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical', shuffle=False)
    predict_size_train = int(math.ceil(train_generator.samples / batch_size))
    # predict_size_train = train_generator.samples // batch_size
    bottleneck_features_train = model.predict_generator(train_generator, predict_size_train, verbose = 1)
    # np.save(open(train_feature, 'wb'), bottleneck_features_train)
    np.save(train_feature, bottleneck_features_train)

    val_generator = datagen.flow_from_directory(validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size,class_mode='categorical', shuffle=False)
    predict_size_validation = int(math.ceil(val_generator.samples / batch_size))
    # predict_size_validation = val_generator.samples // batch_size
    bottleneck_features_validation = model.predict_generator(val_generator, predict_size_validation, verbose = 1)
    np.save(validation_feature, bottleneck_features_validation)
    # np.save(open(validation_feature, 'wb'), bottleneck_features_validation)

def train_top_model():
    train_data = np.load(train_feature)
    # train_data = np.load(open(train_feature,'rb'))
    train_labels = np.array([0] * 4684 + [1] * 2022 + [2] * 3775 + [3] * 4544 + [4] * 3195 + [5] * 4562 + [6] * 2300 + [7] * 2002 + [8] * 5281)

    validation_data = np.load(validation_feature)
    # validation_data = np.load(open(validation_feature,'rb'))
    validation_labels = np.array([0] * 1171 + [1] * 441 + [2] * 949 + [3] * 1121 + [4] * 799 + [5] * 1141 + [6] * 575 + [7] * 409 + [8] * 1320)

    model = Sequential()
    model.add(Flatten(input_shape=train_data.shape[1:]))
    # model.add(Flatten())
    model.add(Dense(256, activation='relu', name = 'fc1'))
    model.add(Dropout(0.5))
    model.add(Dense(classes, activation='softmax', name = 'prediction'))

    model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

    train_labels = to_categorical(train_labels, classes)
    validation_labels = to_categorical(validation_labels, classes)

    model.fit(train_data, train_labels,
              epochs=epochs,
              batch_size=batch_size,
              validation_data=(validation_data, validation_labels),
              verbose = 1)
    model.save(top_model_weights_path)

save_bottlebeck_features()
train_top_model()


from django.shortcuts import get_object_or_404, render
from django.contrib.auth.decorators import login_required

from admission.models import Admission
from admission.forms import AdmissionForm
from campus.models import Campus, Category
from taggit.models import Tag

def index(request, tag_slug=None):
    campus_lists = Campus.published.all()
    categories = Category.objects.all()
    tag = None

    if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        campus_lists = campus_lists.filter(tag__in=[tag])

    return render(request, 'home/index.html', {
        'tag': tag,
        'campus_lists': campus_lists,
        'categories': categories
    })

@login_required
def campus_detail(request, year, month, day, slug):
    campus = get_object_or_404(Campus, slug=slug, publish__month=month,
                               publish__year=year, publish__day=day, status='published')
    if request.method == "POST":
        print("POSTED")
        admission_form = AdmissionForm(request.POST)
        student = request.user
        # request.user.info_personnel
        # print(request.user.adresse)
        Admission.objects.create(user=student, campus=campus, student_infos=student.info_personnel,
                                 student_adresse=student.adresse, student_bac=student.baccalaureat, student_file=student.student_file)
    else:
        admission_form = AdmissionForm()
    return render(request, 'home/campus_detail.html', {
        'campus': campus,
        'admission_form': admission_form
    })

def campus_per_pays(request, slug, id):
    pays_campus = Campus.published.filter(pays_id=id)
    categories = Category.objects.all()

    return render(request, 'home/index.html', {
        'campus_lists': pays_campus,
        'categories': categories
    })


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

from django.db import migrations, models
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('nutep', '0004_auto_20170403_1559'),
    ]

    operations = [
        migrations.CreateModel(
            name='Team',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=150, verbose_name=b'\xd0\x9d\xd0\xb0\xd0\xb8\xd0\xbc\xd0\xb5\xd0\xbd\xd0\xbe\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xb8\xd0\xb5', db_index=True)),
                ('users', models.ManyToManyField(related_name='teams', to=settings.AUTH_USER_MODEL, blank=True)),
            ],
        ),
        migrations.AddField(
            model_name='contract',
            name='owner',
            field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AddField(
            model_name='line',
            name='owner',
            field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AddField(
            model_name='uploadedtemplate',
            name='owner',
            field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AddField(
            model_name='contract',
            name='teams',
            field=models.ManyToManyField(to='nutep.Team', blank=True),
        ),
        migrations.AddField(
            model_name='line',
            name='teams',
            field=models.ManyToManyField(to='nutep.Team', blank=True),
        ),
        migrations.AddField(
            model_name='uploadedtemplate',
            name='teams',
            field=models.ManyToManyField(to='nutep.Team', blank=True),
        ),
    ]


# -*- coding:utf-8 -*-
# Time : 2019/08/11 上午 11:57
# Author : 御承扬
# e-mail:2923616405@qq.com
# project:  PyQt5
# File : qt13_textEdit.py
# @software: PyCharm

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout, QPushButton
import sys

class TextEditDemo(QWidget):
    def __init__(self, parent=None):
        super(TextEditDemo, self).__init__(parent)
        self.setWindowTitle("QTextEdit 例子")
        self.setWindowIcon(QIcon("./images/Python2.ico"))
        self.resize(300, 270)
        self.textEdit = QTextEdit()
        self.btnPress1 = QPushButton("显示文本")
        self.btnPress2 = QPushButton("显示 HTML")
        layout = QVBoxLayout()
        layout.addWidget(self.textEdit)
        layout.addWidget(self.btnPress1)
        layout.addWidget(self.btnPress2)
        self.setLayout(layout)
        self.btnPress1.clicked.connect(self.btnPress1_Clicked)
        self.btnPress2.clicked.connect(self.btnPress2_Clicked)

    def btnPress1_Clicked(self):
        self.textEdit.setPlainText("Hello PyQt5!\n单击按钮")

    def btnPress2_Clicked(self):
        self.textEdit.setHtml("<red>Hello PyQt5!\n单击按钮。")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = TextEditDemo()
    win.show()
    sys.exit(app.exec_())


import streamlit as st
import cv2
import speech_recognition as sr
import threading
import face_recognition
import pyaudio
import time

# Create a button to stop the webcam
stop_button = st.sidebar.button("Stop Webcam")

# Création d'un contrôle de valeur dans la barre latérale
temps = st.sidebar.slider("Sélectionnez un temps d'enregistrement en secondes", 0, 60, 5)

def detect_face(img):
    # Convertir l'image en RGB
    rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # Détecter les visages dans l'image
    faces = face_recognition.face_locations(rgb, model='hog')

    # Pour chaque visage détecté, détecter l'âge, le genre et les émotions
    for (top, right, bottom, left) in faces:
        # Dessiner un rectangle autour du visage détecté
        cv2.rectangle(img, (left, top), (right, bottom), (255, 0, 0), 2)

    return img

def main():
    st.title("Contrôle de la caméra par commande vocale")

    # Initialiser l'enregistreur vocal
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 44100
    RECORD_SECONDS = 30
    p = pyaudio.PyAudio()

    while True:
        r = sr.Recognizer()
        with sr.Microphone() as source:
            st.write("Dites 'Démarrer' pour démarrer la caméra.")
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source)
            try:
                text = r.recognize_google(audio, language='fr-FR')
                st.write("Vous avez dit : " + text)
                cap = cv2.VideoCapture(0) # 0 pour la webcam intégrée, 1 pour une webcam externe
                stframe = st.empty() # Créer un espace vide pour afficher l'image

                if "démarrer" in text.lower():
                    #st.write("Démarrage de la caméra...")
                    #cap = cv2.VideoCapture(0) # 0 pour la webcam intégrée, 1 pour une webcam externe
                    stframe = st.empty() # Créer un espace vide pour afficher l'image

                    cap.set(cv2.CAP_PROP_FPS, 60)
                    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
                    cap.set(cv2.CAP_PROP_FOURCC, fourcc)
                    out = cv2.VideoWriter('record.avi',fourcc, 20.0, (640,480))

                    count = 0
                    while True:
                        count += 1
                        ret, frame = cap.read()
                        if ret:
                            frame = cv2.flip(frame, 1)

                            # Appeler la fonction de détection de visage dans un thread séparé seulement une image sur deux pour accélérer le traitement
                            #if count % 2 == 0:
                            thread = threading.Thread(target=detect_face, args=(frame))
                            thread.start() # Lancer le thread
                            thread.join() # Attendre la fin du thread pour continuer

                            # Afficher l'image dans Streamlit
                            stframe.image(frame, channels="BGR")
                            out.write(frame)

                        if cap.get(cv2.CAP_PROP_POS_MSEC) >= temps*1000:
                            st.write("Fin de l'enregistrement")
                            break
                        cap.release()
                        cv2.destroyAllWindows()
                else:
                    st.write("Commande non reconnue.")
                    break
            except sr.UnknownValueError:
                st.write("répète on comprend pas")

        if stop_button:
        # Stop the webcam video stream
            cap.release()

if __name__ == "__main__":
    main()


# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import copy
from collections import OrderedDict
import numpy as np
from astropy.table import Table
from astropy.io import fits
import astropy.units as u
from ..utils.nddata import NDDataArray, BinnedDataAxis
from ..utils.scripts import make_path
from ..utils.fits import energy_axis_to_ebounds, ebounds_to_energy_axis
from ..data import EventList

__all__ = ["CountsSpectrum", "PHACountsSpectrum", "PHACountsSpectrumList"]

log = logging.getLogger("__name__")

class CountsSpectrum(object):
    """Generic counts spectrum.

    Parameters
    ----------
    energy_lo : `~astropy.units.Quantity`
        Lower bin edges of energy axis
    energy_hi : `~astropy.units.Quantity`
        Upper bin edges of energy axis
    data : `~astropy.units.Quantity`, array-like
        Counts

    Examples
    --------
    .. plot::
        :include-source:

        from gammapy.spectrum import CountsSpectrum
        import numpy as np
        import astropy.units as u

        ebounds = np.logspace(0,1,11) * u.TeV
        data = np.arange(10)
        spec = CountsSpectrum(
            energy_lo=ebounds[:-1],
            energy_hi=ebounds[1:],
            data=data,
        )
        spec.plot(show_poisson_errors=True)
    """

    default_interp_kwargs = dict(bounds_error=False, method="nearest")
    """Default interpolation kwargs"""

    def __init__(self, energy_lo, energy_hi, data=None, interp_kwargs=None):
        axes = [
            BinnedDataAxis(
                energy_lo, energy_hi, interpolation_mode="log", name="energy"
            )
        ]

        if interp_kwargs is None:
            interp_kwargs = self.default_interp_kwargs
        self.data = NDDataArray(axes=axes, data=data, interp_kwargs=interp_kwargs)

    @property
    def energy(self):
        return self.data.axis("energy")

    @classmethod
    def from_hdulist(cls, hdulist, hdu1="COUNTS", hdu2="EBOUNDS"):
        """Read OGIP format hdulist"""
        counts_table = Table.read(hdulist[hdu1])
        counts = counts_table["COUNTS"].data
        ebounds = ebounds_to_energy_axis(hdulist[hdu2])
        return cls(
            data=counts, energy_lo=ebounds.lower_bounds, energy_hi=ebounds.upper_bounds
        )

    @classmethod
    def read(cls, filename, hdu1="COUNTS", hdu2="EBOUNDS"):
        """Read from file."""
        filename = make_path(filename)
        with fits.open(str(filename), memmap=False) as hdulist:
            return cls.from_hdulist(hdulist, hdu1=hdu1, hdu2=hdu2)

    def to_table(self):
        """Convert to `~astropy.table.Table`.

        Data format specification: :ref:`gadf:ogip-pha`
        """
        channel = np.arange(self.energy.nbins, dtype=np.int16)
        counts = np.array(self.data.data.value, dtype=np.int32)

        names = ["CHANNEL", "COUNTS"]
        meta = {"name": "COUNTS"}
        return Table([channel, counts], names=names, meta=meta)

    def to_hdulist(self):
        """Convert to `~astropy.io.fits.HDUList`.

        This adds an ``EBOUNDS`` extension to the ``BinTableHDU`` produced by
        ``to_table``, in order to store the energy axis
        """
        table = self.to_table()
        name = table.meta["name"]
        hdu = fits.BinTableHDU(table, name=name)
        ebounds = energy_axis_to_ebounds(self.energy.bins)
        return fits.HDUList([fits.PrimaryHDU(), hdu, ebounds])

    def write(self, filename, **kwargs):
        """Write to file."""
        filename = make_path(filename)
        self.to_hdulist().writeto(str(filename), **kwargs)

    def fill(self, events):
        """Fill with list of events.

        TODO: Move to `~gammapy.utils.nddata.NDDataArray`

        Parameters
        ----------
        events : `~astropy.units.Quantity`, `gammapy.data.EventList`,
            List of event energies
        """
        if isinstance(events, EventList):
            events = events.energy

        energy = events.to(self.energy.unit)
        binned_val = np.histogram(energy.value, self.energy.bins)[0]
        self.data.data = binned_val

    @property
    def total_counts(self):
        """Total number of counts
        """
        return self.data.data.sum()

    def plot(
        self,
        ax=None,
        energy_unit="TeV",
        show_poisson_errors=False,
        show_energy=None,
        **kwargs
    ):
        """Plot as data points.

        kwargs are forwarded to `~matplotlib.pyplot.errorbar`

        Parameters
        ----------
        ax : `~matplotlib.axis` (optional)
            Axis instance to be used for the plot
        energy_unit : str, `~astropy.units.Unit`, optional
            Unit of the energy axis
        show_poisson_errors : bool, optional
            Show poisson errors on the plot
        show_energy : `~astropy.units.Quantity`, optional
            Show energy, e.g. threshold, as vertical line

        Returns
        -------
        ax: `~matplotlib.axis`
            Axis instance used for the plot
        """
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax
        counts = self.data.data.value
        x = self.energy.nodes.to_value(energy_unit)
        bounds = self.energy.bins.to_value(energy_unit)
        xerr = [x - bounds[:-1], bounds[1:] - x]
        yerr = np.sqrt(counts) if show_poisson_errors else 0
        kwargs.setdefault("fmt", "")
        ax.errorbar(x, counts, xerr=xerr, yerr=yerr, **kwargs)
        if show_energy is not None:
            ener_val = u.Quantity(show_energy).to_value(energy_unit)
            ax.vlines(ener_val, 0, 1.1 * max(self.data.data.value), linestyles="dashed")
        ax.set_xlabel("Energy [{}]".format(energy_unit))
        ax.set_ylabel("Counts")
        ax.set_xscale("log")
        ax.set_ylim(0, 1.2 * max(self.data.data.value))
        return ax

    def plot_hist(self, ax=None, energy_unit="TeV", show_energy=None, **kwargs):
        """Plot as histogram.

        kwargs are forwarded to `~matplotlib.pyplot.hist`

        Parameters
        ----------
        ax : `~matplotlib.axis` (optional)
            Axis instance to be used for the plot
        energy_unit : str, `~astropy.units.Unit`, optional
            Unit of the energy axis
        show_energy : `~astropy.units.Quantity`, optional
            Show energy, e.g. threshold, as vertical line
        """
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax
        kwargs.setdefault("lw", 2)
        kwargs.setdefault("histtype", "step")
        weights = self.data.data.value
        bins = self.energy.bins.to_value(energy_unit)
        x = self.energy.nodes.to_value(energy_unit)
        ax.hist(x, bins=bins, weights=weights, **kwargs)
        if show_energy is not None:
            ener_val = u.Quantity(show_energy).to_value(energy_unit)
            ax.vlines(ener_val, 0, 1.1 * max(self.data.data.value), linestyles="dashed")
        ax.set_xlabel("Energy [{}]".format(energy_unit))
        ax.set_ylabel("Counts")
        ax.set_xscale("log")
        return ax

    def peek(self, figsize=(5, 10)):
        """Quick-look summary plots."""
        import matplotlib.pyplot as plt

        fig, ax = plt.subplots(1, 1, figsize=figsize)
        self.plot_hist(ax=ax)
        return ax

    def copy(self):
        """A deep copy of self."""
        return copy.deepcopy(self)

    def rebin(self, parameter):
        """Rebin.

        Parameters
        ----------
        parameter : int
            Number of bins to merge

        Returns
        -------
        rebinned_spectrum : `~gammapy.spectrum.CountsSpectrum`
            Rebinned spectrum
        """
        if len(self.data.data) % parameter != 0:
            raise ValueError(
                "Invalid rebin parameter: {}, nbins: {}".format(
                    parameter, len(self.data.data)
                )
            )

        # Copy to keep attributes
        retval = self.copy()
        energy = retval.energy
        energy.lo = energy.lo[0::parameter]
        energy.hi = energy.hi[parameter - 1 :: parameter]
        split_indices = np.arange(parameter, len(retval.data.data), parameter)
        counts_grp = np.split(retval.data.data, split_indices)
        counts_rebinned = np.sum(counts_grp, axis=1)
        retval.data.data = counts_rebinned

        return retval

class PHACountsSpectrum(CountsSpectrum):
    """Counts spectrum corresponding to OGIP PHA format.

    The ``bkg`` flag controls whether the PHA counts spectrum represents a
    background estimate or not (this slightly affects the FITS header
    information when writing to disk).

    Parameters
    ----------
    energy_lo : `~astropy.units.Quantity`
        Lower bin edges of energy axis
    energy_hi : `~astropy.units.Quantity`
        Upper bin edges of energy axis
    data : array-like, optional
        Counts
    quality : int, array-like, optional
        Mask bins in safe energy range (1 = bad, 0 = good)
    backscal : float, array-like, optional
        Background scaling factor
    areascal : float, array-like, optional
        Area scaling factor
    is_bkg : bool, optional
        Background or soure spectrum, default: False
    obs_id : int
        Observation identifier, optional
    livetime : `~astropy.units.Quantity`, optional
        Observation livetime
    offset : `~astropy.units.Quantity`, optional
        Field of view offset
    meta : dict, optional
        Meta information
    """

    def __init__(
        self,
        energy_lo,
        energy_hi,
        data=None,
        quality=None,
        backscal=None,
        areascal=None,
        is_bkg=False,
        obs_id=None,
        livetime=None,
        offset=None,
        meta=None,
    ):
        super(PHACountsSpectrum, self).__init__(energy_lo, energy_hi, data)
        if quality is None:
            quality = np.zeros(self.energy.nbins, dtype="i2")
        self._quality = quality
        if backscal is None:
            backscal = np.ones(self.energy.nbins)
        self.backscal = backscal
        if areascal is None:
            areascal = np.ones(self.energy.nbins)
        self.areascal = areascal
        self.is_bkg = is_bkg
        self.obs_id = obs_id
        self.livetime = livetime
        self.offset = offset
        self.meta = meta or OrderedDict()

    @property
    def quality(self):
        """Bins in safe energy range (1 = bad, 0 = good)"""
        return self._quality

    @quality.setter
    def quality(self, quality):
        self._quality = quality

    @property
    def phafile(self):
        """PHA file associated with the observation"""
        if isinstance(self.obs_id, list):
            filename = "pha_stacked.fits"
        else:
            filename = "pha_obs{}.fits".format(self.obs_id)
        return filename

    @property
    def arffile(self):
        """ARF associated with the observation"""
        return self.phafile.replace("pha", "arf")

    @property
    def rmffile(self):
        """RMF associated with the observation"""
        return self.phafile.replace("pha", "rmf")

    @property
    def bkgfile(self):
        """Background PHA files associated with the observation"""
        return self.phafile.replace("pha", "bkg")

    @property
    def bins_in_safe_range(self):
        """Indices of bins within the energy thresholds"""
        idx = np.where(np.array(self.quality) == 0)[0]
        return idx

    @property
    def counts_in_safe_range(self):
        """Counts with bins outside safe range set to 0"""
        data = self.data.data.copy()
        data[np.nonzero(self.quality)] = 0
        return data

    @property
    def lo_threshold(self):
        """Low energy threshold of the observation (lower bin edge)"""
        idx = self.bins_in_safe_range[0]
        return self.energy.lo[idx]

    @lo_threshold.setter
    def lo_threshold(self, thres):
        idx = np.where(self.energy.lo < thres)[0]
        self.quality[idx] = 1

    @property
    def hi_threshold(self):
        """High energy threshold of the observation (upper bin edge)"""
        idx = self.bins_in_safe_range[-1]
        return self.energy.hi[idx]

    @hi_threshold.setter
    def hi_threshold(self, thres):
        idx = np.where(self.energy.lo > thres)[0]
        if len(idx) != 0:
            idx = np.insert(idx, 0, idx[0] - 1)
        self.quality[idx] = 1

    def reset_thresholds(self):
        """Reset energy thresholds (i.e. declare all energy bins valid)"""
        self.quality = np.zeros_like(self.quality)

    def rebin(self, parameter):
        """Rebin.

        See `~gammapy.spectrum.CountsSpectrum`.
        This function treats the quality vector correctly
        """
        retval = super(PHACountsSpectrum, self).rebin(parameter)
        split_indices = np.arange(parameter, len(self.data.data), parameter)
        quality_grp = np.split(retval.quality, split_indices)
        quality_summed = np.sum(quality_grp, axis=1)
        # Exclude groups where not all bins are within the safe threshold
        condition = quality_summed == parameter
        quality_rebinned = np.where(
            condition, np.ones(len(retval.data.data)), np.zeros(len(retval.data.data))
        )
        retval.quality = np.array(quality_rebinned, dtype=int)

        # if backscal is not the same in all channels cannot merge
        if not np.isscalar(retval.backscal):
            if not np.isclose(np.diff(retval.backscal), 0).all():
                raise ValueError("Cannot merge energy dependent backscal")
            else:
                retval.meta.backscal = retval.backscal[0] * np.ones(retval.energy.nbins)

        # average areascal
        areascal_grp = np.split(retval.areascal, split_indices)
        retval.areascal = np.mean(areascal_grp, axis=1)

        return retval

    @property
    def _backscal_array(self):
        """Helper function to always return backscal as an array"""
        if np.isscalar(self.backscal):
            return np.ones(self.energy.nbins) * self.backscal
        else:
            return self.backscal

    def to_table(self):
        """Convert to `~astropy.table.Table`."""
        table = super(PHACountsSpectrum, self).to_table()

        table["QUALITY"] = self.quality
        table["BACKSCAL"] = self._backscal_array
        table["AREASCAL"] = self.areascal

        meta = OrderedDict()
        meta["name"] = "SPECTRUM"
        meta["hduclass"] = "OGIP"
        meta["hduclas1"] = "SPECTRUM"
        meta["corrscal"] = ""
        meta["chantype"] = "PHA"
        meta["detchans"] = self.energy.nbins
        meta["filter"] = "None"
        meta["corrfile"] = ""
        meta["poisserr"] = True
        meta["hduclas3"] = "COUNT"
        meta["hduclas4"] = "TYPE:1"
        meta["lo_thres"] = self.lo_threshold.to_value("TeV")
        meta["hi_thres"] = self.hi_threshold.to_value("TeV")
        meta["exposure"] = self.livetime.to_value("s")
        meta["obs_id"] = self.obs_id

        if not self.is_bkg:
            if self.rmffile is not None:
                meta["respfile"] = self.rmffile

            meta["backfile"] = self.bkgfile
            meta["ancrfile"] = self.arffile
            meta["hduclas2"] = "TOTAL"
        else:
            meta["hduclas2"] = "BKG"

        meta.update(self.meta)

        table.meta = meta
        return table

    @classmethod
    def from_hdulist(cls, hdulist, hdu1="SPECTRUM", hdu2="EBOUNDS"):
        """Create from `~astropy.io.fits.HDUList`."""
        counts_table = Table.read(hdulist[hdu1])
        ebounds = Table.read(hdulist[2])
        emin = ebounds["E_MIN"].quantity
        emax = ebounds["E_MAX"].quantity

        # Check if column are present in the header
        quality = None
        areascal = None
        backscal = None
        if "QUALITY" in counts_table.colnames:
            quality = counts_table["QUALITY"].data
        if "AREASCAL" in counts_table.colnames:
            areascal = counts_table["AREASCAL"].data
        if "BACKSCAL" in counts_table.colnames:
            backscal = counts_table["BACKSCAL"].data

        kwargs = dict(
            data=counts_table["COUNTS"],
            backscal=backscal,
            energy_lo=emin,
            energy_hi=emax,
            quality=quality,
            areascal=areascal,
            livetime=counts_table.meta["EXPOSURE"] * u.s,
            obs_id=counts_table.meta["OBS_ID"],
        )
        if hdulist[1].header["HDUCLAS2"] == "BKG":
            kwargs["is_bkg"] = True
        return cls(**kwargs)

    @classmethod
    def read(cls, filename, hdu1="SPECTRUM", hdu2="EBOUNDS"):
        """Read from file."""
        filename = make_path(filename)
        with fits.open(str(filename), memmap=False) as hdulist:
            return cls.from_hdulist(hdulist, hdu1=hdu1, hdu2=hdu2)

    def to_sherpa(self, name):
        """Convert to `sherpa.astro.data.DataPHA`.

        Parameters
        ----------
        name : str
            Instance name
        """
        from sherpa.utils import SherpaFloat
        from sherpa.astro.data import DataPHA

        table = self.to_table()

        # Workaround to avoid https://github.com/sherpa/sherpa/issues/248
        if np.isscalar(self.backscal):
            backscal = self.backscal
        else:
            backscal = self.backscal.copy()
            if np.allclose(backscal.mean(), backscal):
                backscal = backscal[0]

        return DataPHA(
            name=name,
            channel=(table["CHANNEL"].data + 1).astype(SherpaFloat),
            counts=table["COUNTS"].data.astype(SherpaFloat),
            quality=table["QUALITY"].data,
            exposure=self.livetime.to_value("s"),
            backscal=backscal,
            areascal=self.areascal,
            syserror=None,
            staterror=None,
            grouping=None,
        )

class PHACountsSpectrumList(list):
    """List of `~gammapy.spectrum.PHACountsSpectrum` objects.

    All spectra must have the same energy binning.
    This represent the PHA type II data format.
    See https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/spectra/ogip_92_007/node8.html
    """

    def write(self, outdir, **kwargs):
        """Write to file"""
        outdir = make_path(outdir)
        self.to_hdulist().writeto(str(outdir), **kwargs)

    def to_hdulist(self):
        """Convert to `~astropy.io.fits.HDUList`"""
        hdu = fits.BinTableHDU(self.to_table())
        ebounds = energy_axis_to_ebounds(self[0].energy.bins)
        return fits.HDUList([fits.PrimaryHDU(), hdu, ebounds])

    def to_table(self):
        """Convert to `~astropy.table.Table`."""
        is_bkg = self[0].is_bkg
        nbins = self[0].energy.nbins
        spec_num = np.empty([len(self), 1], dtype=np.int16)
        channel = np.empty([len(self), nbins], dtype=np.int16)
        counts = np.empty([len(self), nbins], dtype=np.int32)
        quality = np.empty([len(self), nbins], dtype=np.int32)
        backscal = np.empty([len(self), nbins], dtype=np.int32)
        backfile = list()
        for idx, pha in enumerate(self):
            t = pha.to_table()
            spec_num[idx] = pha.obs_id
            channel[idx] = t["CHANNEL"].data
            counts[idx] = t["COUNTS"].data
            quality[idx] = t["QUALITY"].data
            backscal[idx] = t["BACKSCAL"].data
            backfile.append("bkg.fits[{}]".format(idx))

        meta = self[0].to_table().meta
        meta["hduclas4"] = "TYPE:II"
        meta["ancrfile"] = "arf.fits"
        meta["respfile"] = "rmf.fits"

        data = [spec_num, channel, counts, quality, backscal]
        names = ["SPEC_NUM", "CHANNEL", "COUNTS", "QUALITY", "BACKSCAL"]
        table = Table(data, names=names, meta=meta)

        if not is_bkg:
            table.meta.pop("backfile")
            table["BACKFILE"] = backfile

        return table

    @classmethod
    def read(cls, filename):
        """Read from file."""
        filename = make_path(filename)
        with fits.open(str(filename), memmap=False) as hdulist:
            return cls.from_hdulist(hdulist)

    @classmethod
    def from_hdulist(cls, hdulist):
        """Create from `~astropy.io.fits.HDUList`."""
        energy = ebounds_to_energy_axis(hdulist[2])
        kwargs = dict(energy_lo=energy[:-1], energy_hi=energy[1:])
        if hdulist[1].header["HDUCLAS2"] == "BKG":
            kwargs["is_bkg"] = True

        counts_table = Table.read(hdulist[1])
        speclist = cls()
        for row in counts_table:
            kwargs["data"] = row["COUNTS"]
            kwargs["backscal"] = row["BACKSCAL"]
            kwargs["quality"] = row["QUALITY"]
            kwargs["livetime"] = hdulist[1].header["EXPOSURE"] * u.s
            kwargs["obs_id"] = row["SPEC_NUM"]
            spec = PHACountsSpectrum(**kwargs)
            speclist.append(spec)

        return speclist


# Reverse Linked List
# 반복 구조로 구현(1) , 72ms
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def reverseList(self, head: ListNode):
        node, prev = head, None

        while node:
            next, node.next = node.next, prev
            prev, node = node, next

        return prev

# 반복 구조로 구현(2) - 가장 나한테 이해가 잘되는 방법, 43ms
class Solution:
    def reverseList(self, head: ListNode):
        prev = None

        # head를 한 칸씩 움직이면서 이전 노드들까지의 역순 연결리스트 만들기
        while head:
            temp = head
            head = head.next
            temp.next = prev
            prev = temp

        return prev

# 재귀 구조로 구현, 59ms
class Solution:
    def reverseList(self, head: ListNode):
        def reverse(node: ListNode, prev: ListNode = None):
            if not node:
                return prev
            next, node.next = node.next, prev
            return reverse(next, node)

        return reverse(head)


N, K = [int(x) for x in input("").split()]
S1 = input("")
S2 = 'x'*len(S1)

#print(S1)
#print(S2)

limit = 0
for c in range(len(S1)):
    if S1[c] == 'o':
        S2 = S2[0:c] + 'o' + S2[c+1:]
        limit += 1
    if limit == K:
        break

print(S2)


from PySide6.QtWidgets import QWidget, QVBoxLayout

from package.chart_widget import ChartWidget
from package.data_store import DataStore
from package.projection_widget import ProjectionWidget

class ProjectionTab(QWidget):

    def __init__(self, data: DataStore) -> None:
        super(ProjectionTab, self).__init__()
        self._data = data
        self._projections = DataStore()
        self._projector = ProjectionWidget(self._data, self._projections)
        self._chart = ChartWidget(self._data, self._projections)
        self._window_layout = QVBoxLayout()
        self._init_ui()

    def _init_ui(self) -> None:
        self._window_layout.addWidget(self._projector)
        self._window_layout.addWidget(self._chart)
        self.setLayout(self._window_layout)


import os
import tarfile
from binascii import crc32
from os.path import getmtime, getsize, isdir, isfile, join

from twisted.python import constants  # pylint: disable=import-error

from platformio.compat import hashlib_encode_data

class PROJECT_SYNC_STAGE(constants.Flags):
    INIT = constants.FlagConstant()
    DBINDEX = constants.FlagConstant()
    DELETE = constants.FlagConstant()
    UPLOAD = constants.FlagConstant()
    EXTRACTED = constants.FlagConstant()
    COMPLETED = constants.FlagConstant()

class ProjectSync:
    def __init__(self, path):
        self.path = path
        if not isdir(self.path):
            os.makedirs(self.path)
        self.items = []
        self._db = {}

    def add_item(self, path, relpath, cb_filter=None):
        self.items.append((path, relpath, cb_filter))

    def get_items(self):
        return self.items

    def rebuild_dbindex(self):
        self._db = {}
        for path, relpath, cb_filter in self.items:
            if cb_filter and not cb_filter(path):
                continue
            self._insert_to_db(path, relpath)
            if not isdir(path):
                continue
            for root, _, files in os.walk(path, followlinks=True):
                for name in files:
                    self._insert_to_db(
                        join(root, name), join(relpath, root[len(path) + 1 :], name)
                    )

    def _insert_to_db(self, path, relpath):
        if not isfile(path):
            return
        index_hash = "%s-%s-%s" % (relpath, getmtime(path), getsize(path))
        index = crc32(hashlib_encode_data(index_hash))
        self._db[index] = (path, relpath)

    def get_dbindex(self):
        return list(self._db.keys())

    def delete_dbindex(self, dbindex):
        for index in dbindex:
            if index not in self._db:
                continue
            path = self._db[index][0]
            if isfile(path):
                os.remove(path)
            del self._db[index]
        self.delete_empty_folders()
        return True

    def delete_empty_folders(self):
        deleted = False
        for item in self.items:
            if not isdir(item[0]):
                continue
            for root, dirs, files in os.walk(item[0]):
                if not dirs and not files and root != item[0]:
                    deleted = True
                    os.rmdir(root)
        if deleted:
            return self.delete_empty_folders()

        return True

    def compress_items(self, fileobj, dbindex, max_size):
        compressed = []
        total_size = 0
        tar_opts = dict(fileobj=fileobj, mode="w:gz", bufsize=0, dereference=True)
        with tarfile.open(**tar_opts) as tgz:
            for index in dbindex:
                compressed.append(index)
                if index not in self._db:
                    continue
                path, relpath = self._db[index]
                tgz.add(path, relpath)
                total_size += getsize(path)
                if total_size > max_size:
                    break
        return compressed

    def decompress_items(self, fileobj):
        fileobj.seek(0)
        with tarfile.open(fileobj=fileobj, mode="r:gz") as tgz:
            tgz.extractall(self.path)
        return True