import unittest

import torch

from models.matcher import HungarianMatcher
from models.position_encoding import PositionEmbeddingSine, PositionEmbeddingLearned
from models.backbone import Backbone, Joiner, BackboneBase
from util import box_ops
from util.misc import nested_tensor_from_tensor_list
from hubconf import detr_resnet50, detr_resnet50_panoptic

class Tester(unittest.TestCase):

    def test_box_cxcywh_to_xyxy(self):
        t = torch.rand(10, 4)
        r = box_ops.box_xyxy_to_cxcywh(box_ops.box_cxcywh_to_xyxy(t))
        self.assertLess((t - r).abs().max(), 1e-5)

    @staticmethod
    def indices_torch2python(indices):
        return [(i.tolist(), j.tolist()) for i, j in indices]

    def test_hungarian(self):
        n_queries, n_targets, n_classes = 100, 15, 91
        logits = torch.rand(1, n_queries, n_classes + 1)
        boxes = torch.rand(1, n_queries, 4)
        tgt_labels = torch.randint(high=n_classes, size=(n_targets,))
        tgt_boxes = torch.rand(n_targets, 4)
        matcher = HungarianMatcher()
        targets = [{'labels': tgt_labels, 'boxes': tgt_boxes}]
        indices_single = matcher({'pred_logits': logits, 'pred_boxes': boxes}, targets)
        indices_batched = matcher({'pred_logits': logits.repeat(2, 1, 1),
                                   'pred_boxes': boxes.repeat(2, 1, 1)}, targets * 2)
        self.assertEqual(len(indices_single[0][0]), n_targets)
        self.assertEqual(len(indices_single[0][1]), n_targets)
        self.assertEqual(self.indices_torch2python(indices_single),
                         self.indices_torch2python([indices_batched[0]]))
        self.assertEqual(self.indices_torch2python(indices_single),
                         self.indices_torch2python([indices_batched[1]]))

        # test with empty targets
        tgt_labels_empty = torch.randint(high=n_classes, size=(0,))
        tgt_boxes_empty = torch.rand(0, 4)
        targets_empty = [{'labels': tgt_labels_empty, 'boxes': tgt_boxes_empty}]
        indices = matcher({'pred_logits': logits.repeat(2, 1, 1),
                           'pred_boxes': boxes.repeat(2, 1, 1)}, targets + targets_empty)
        self.assertEqual(len(indices[1][0]), 0)
        indices = matcher({'pred_logits': logits.repeat(2, 1, 1),
                           'pred_boxes': boxes.repeat(2, 1, 1)}, targets_empty * 2)
        self.assertEqual(len(indices[0][0]), 0)

    def test_position_encoding_script(self):
        m1, m2 = PositionEmbeddingSine(), PositionEmbeddingLearned()
        mm1, mm2 = torch.jit.script(m1), torch.jit.script(m2)  # noqa

    def test_backbone_script(self):
        backbone = Backbone('resnet50', True, False, False)
        torch.jit.script(backbone)  # noqa

    def test_model_script_detection(self):
        model = detr_resnet50(pretrained=False).eval()
        scripted_model = torch.jit.script(model)
        x = nested_tensor_from_tensor_list([torch.rand(3, 200, 200), torch.rand(3, 200, 250)])
        out = model(x)
        out_script = scripted_model(x)
        self.assertTrue(out["pred_logits"].equal(out_script["pred_logits"]))
        self.assertTrue(out["pred_boxes"].equal(out_script["pred_boxes"]))

    def test_model_script_panoptic(self):
        model = detr_resnet50_panoptic(pretrained=False).eval()
        scripted_model = torch.jit.script(model)
        x = nested_tensor_from_tensor_list([torch.rand(3, 200, 200), torch.rand(3, 200, 250)])
        out = model(x)
        out_script = scripted_model(x)
        self.assertTrue(out["pred_logits"].equal(out_script["pred_logits"]))
        self.assertTrue(out["pred_boxes"].equal(out_script["pred_boxes"]))
        self.assertTrue(out["pred_masks"].equal(out_script["pred_masks"]))

if __name__ == '__main__':
    unittest.main()


import time
import sys

def main(SoveWithLookup) :

    WIN         = 6
    DRAW        = 3
    LOSE        = 0

    ROCK        = 1
    PAPER       = 2
    SCISSORS    = 3

    if False == SoveWithLookup :

        # Translations
        ELF_MOVE_TRANSLATIONS    = {"A" : ROCK, "B" : PAPER, "C" : SCISSORS}
        PLAYER_MOVE_TRANSLATIONS = {"X" : ROCK, "Y" : PAPER, "Z" : SCISSORS}
        SCORE_TRANSLATIONS       = {"X" : LOSE, "Y" : DRAW,  "Z" : WIN}

        # Translated Results
        WINNING_MOVES = {ROCK       : PAPER,
                        PAPER      : SCISSORS,
                        SCISSORS   : ROCK}
        LOSING_MOVES  = {ROCK       : SCISSORS,
                        PAPER      : ROCK,
                        SCISSORS   : PAPER}

        # Read the Move List into an array of Move/Response
        with open("../input.txt", "r") as inputFile:

            # First Extract the Elves
            moves = [line.split() for line in inputFile.readlines()]

            # Score
            part1Score = 0
            part2Score = 0

            for move in moves :

                # Translate the Current Game State
                elfMove       = ELF_MOVE_TRANSLATIONS[move[0]]
                p1PlayerMove  = PLAYER_MOVE_TRANSLATIONS[move[1]]  # Part 1 Assumes Column B is a Move
                p2PlayerScore = SCORE_TRANSLATIONS[move[1]]        # Part 2 Assumes Column B is the intended Game State

                # Extract the Score from the Part 1 Move Criteria
                if WINNING_MOVES[elfMove] == p1PlayerMove :
                    part1Score += WIN
                elif elfMove == p1PlayerMove :
                    part1Score += DRAW
                else :
                    part1Score += LOSE
                #end

                part1Score += p1PlayerMove

                # Extract the Move from the Part 2 Score Criteria
                if LOSE == p2PlayerScore :
                    part2Score += LOSING_MOVES[elfMove]
                elif DRAW == p2PlayerScore :
                    part2Score += elfMove
                else :
                    part2Score += WINNING_MOVES[elfMove]
                #end

                part2Score += p2PlayerScore

            #end

            print(f"Part 1: {part1Score}")
            print(f"Part 2: {part2Score}")

        #end

    else :

        with open("../input.txt", "r") as inputFile:

            PART1 = {
                "A X" : DRAW + ROCK,
                "A Y" : WIN  + PAPER,
                "A Z" : LOSE + SCISSORS,
                "B X" : LOSE + ROCK,
                "B Y" : DRAW + PAPER,
                "B Z" : WIN  + SCISSORS,
                "C X" : WIN  + ROCK,
                "C Y" : LOSE + PAPER,
                "C Z" : DRAW + SCISSORS
            }

            PART2 = {
                "A X" : SCISSORS + LOSE,
                "A Y" : ROCK     + DRAW,
                "A Z" : PAPER    + WIN,
                "B X" : ROCK     + LOSE,
                "B Y" : PAPER    + DRAW,
                "B Z" : SCISSORS + WIN,
                "C X" : PAPER    + LOSE,
                "C Y" : SCISSORS + DRAW,
                "C Z" : ROCK     + WIN
            }

            # First Extract the Moves
            moves = [line.strip() for line in inputFile.readlines()]

            # Score
            print(f"Part 1: {sum([PART1[move] for move in moves])}")
            print(f"Part 2: {sum([PART2[move] for move in moves])}")

        #end

    #end

#end

if __name__ == "__main__" :
    startTime      = time.perf_counter()
    main(True)
    print(f"{(time.perf_counter() - startTime)}s", file=sys.stderr)
#end


import socket
import hashlib
import hmac
import json
import logging
from threading import Thread
import threading
import time
from typing import Any

import BRACHA.utils as utils

from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305

RCV_BUFFER_SIZE = 8192
KEY_SIZE = 32
KEY_EXCHANGE = 0  # 1

class AuthenticatedLink:
    def __init__(self, self_id, self_ip, idn, ip, proc):
        self.proc = proc
        self.self_id = self_id  # id of sending process
        self.id = idn  # id of receiving process
        self.self_ip = self_ip
        self.ip = ip
        self.key = {}
        self.sending_port = (
            int("50" + str(self.self_id) + str(self.id))
            if self.self_id < 10 and self.id < 10
            else int("5" + str(self.self_id) + str(self.id))
        )
        self.receiving_port = (
            int("50" + str(self.id) + str(self.self_id))
            if self.self_id < 10 and self.id < 10
            else int("5" + str(self.id) + str(self.self_id))
        )
        self.written = False
        self.bytes_sent = 0

    def key_exchange(self):
        if KEY_EXCHANGE == 1:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as self.sock:
                self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                while True:
                    # Try Except used to repeat the connection until the other socket is opened again
                    try:
                        self.sock.connect((self.ip, self.sending_port))

                        self.__check(self.id, self.sock)

                        break
                    except ConnectionRefusedError:
                        continue
        else:
            self.key[self.id] = utils.get_key(self.self_id, self.id)

    def receiver(self):
        logging.info("AUTH:Start thread to receive messages...")
        t = Thread(target=self.__receive)
        t.start()

    # This handles the message receive
    # Now the listening port is the concatenation 50/5 - 'receiving process' - 'sending process'
    def __receive(self):
        host = ""  # Symbolic name meaning all available interfaces

        logging.info("AUTH:Port used for receiving: %d", self.receiving_port)

        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as self.s:
            self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.s.bind((host, self.receiving_port))
            self.s.listen(1000)

            while True:
                conn, addr = self.s.accept()

                with conn:
                    received_data = b""
                    while True:
                        try:
                            data = conn.recv(RCV_BUFFER_SIZE)

                            if not data:
                                break
                            received_data += data
                        except ConnectionResetError:
                            print("Connection reset by peer")
                            pass

                    if len(received_data) != 0:
                        parsed_data = {}
                        try:
                            parsed_data = json.loads(received_data.decode())
                        except json.JSONDecodeError:
                            print("Decode Error: data too long")

                        if not self.written:
                            start_time = time.time() * 1000

                            logging.info(
                                "----- EVALUATION CHECKPOINT: message receiving, time: %s -----",
                                start_time,
                            )

                            self.written = True

                        logging.info(
                            "AUTH: <%s, %d> -- sent this data %s",
                            self.ip,
                            self.id,
                            parsed_data,
                        )

                        # Useful for performance evaluation, upon the arrival of the first
                        # message it starts timer to monitor execution time

                        if "MSG" not in parsed_data.keys():
                            self.__add_key(parsed_data)
                            conn.sendall(b"synACK")

                        else:
                            t = Thread(
                                target=self.__deliver,
                                args=(parsed_data, threading.currentThread()),
                            )
                            t.start()

                        logging.info("AUTH:Received DATA: %s", data)

    def __add_key(self, key_dict):
        # self.key[self.id] = utils.get_key(self.self_id, self.id)
        self.key[self.id] = key_dict["KEY"].encode("latin1")

        logging.info(
            "AUTH: <%s, %d> is the one with this key: %s", self.ip, self.id, self.key
        )

    def __check(self, sock, idn):
        if idn not in self.key and self.self_id <= idn:
            self.key[idn] = ChaCha20Poly1305.generate_key()

            key_to_send = {"KEY": self.key[idn].decode("latin1")}
            logging.info("AUTH: Key generated")
            logging.info("AUTH: This is what I am sending: %s", key_to_send)

            data = json.dumps(key_to_send)
            sock.sendall(data.encode())
            temp = sock.recv(RCV_BUFFER_SIZE, 0).decode()

            if temp != "synACK":  # Ack used for synchronization with other process
                return 1

    # Compute the hmac of the message with a key associated to the process with self.id
    # The message is returned as a dictionary: {"MSG": message,"HMAC": hmac, "FLAG": flag}
    # The hmac is computed starting from the concatenation of flag and message
    # Example: flag = "SEND" , message = "Hello" ----> HMAC("SENDHello")
    def __auth(self, sock, message):
        self.__check(sock, self.id)
        mess = {
            "MSG": message["MSG"],
            "HMAC": hmac.new(
                self.key.get(self.id, "Key not found"),
                (message["FLAG"] + message["MSG"]).encode("utf-8"),
                hashlib.sha256,
            ).hexdigest(),
            "FLAG": message["FLAG"],
        }

        return mess

    # The send open a new socket, the port is the concatenation of 50/5- id of sending process - id of receiving process
    # Example: sending_id = 1, receiving_id = 2 ---> port = 5012
    def send(self, message):
        # It uses ternary operator

        logging.info(
            "AUTH: Port used to connect: %d to <%s,%d>",
            self.sending_port,
            self.ip,
            self.id,
        )

        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            while True:
                try:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                    sock.connect((self.ip, self.sending_port))

                    # Mess is a dictionary
                    mess = self.__auth(sock, message)
                    parsed_data = json.dumps(mess)

                    # split big message into small chunks
                    chunks = [
                        parsed_data[i : i + RCV_BUFFER_SIZE]
                        for i in range(0, len(parsed_data), RCV_BUFFER_SIZE)
                    ]

                    # Send each chunk sequentially
                    for chunk in chunks:
                        data = bytes(chunk, encoding="utf-8")
                        sock.sendall(data)

                        # takes into account byte sent
                        self.bytes_sent += len(data)

                    logging.info("AUTH: %s sent to <%s, %d>", mess, self.ip, self.id)
                    break
                except:
                    continue

    # It checks message authenticity comparing the hmac
    def __check_auth(self, message):
        try:
            temp_hash = hmac.new(
                self.key.get(self.id, "Key not found"),
                (message["FLAG"] + message["MSG"]).encode("utf-8"),
                hashlib.sha256,
            ).hexdigest()
            return temp_hash == message["HMAC"]
        except TypeError as e:
            print("TypeError:", e.args)

    def __deliver(self, message, t):
        flag = message["FLAG"]

        if not self.__check_auth(message):
            logging.info("--- Authenticity check failed for %s", message)
            print("Authenticity check failed")
            return

        message.pop("HMAC", None)

        if flag == "SEND":
            self.proc.deliver_send(message, self.id)
        elif flag == "ECHO":
            self.proc.deliver_echo(message, self.id)
        elif flag == "READY":
            self.proc.deliver_ready(message, self.id)


def soma_recursiva(seq):
    # Caso base: se a sequência estiver vazia, a soma é 0
    if not seq:
        return 0
    else:
        # A soma é o primeiro elemento da sequência mais a soma dos restantes
        return seq[0] + soma_recursiva(seq[1:])

# Exemplo de uso
minha_sequencia = [1, 2, 3, 4, 5]
resultado = soma_recursiva(minha_sequencia)
print(f"A soma da sequência {minha_sequencia} é {resultado}")
# A soma é o primeiro elemento da sequência mais a soma dos restantes


# calEval.py
# Author Phyo Htut

class Operator:

  def __init__(self, c, p):
    self.cmd = c
    self.prior = p

def exe(cmd, o1, o2):
  if cmd == '+':
    return o1 + o2
  elif cmd == '-':
    return o1 - o2
  elif cmd == '*':
    return o1 * o2
  elif cmd == '/':
    return o1 / o2
  elif cmd == '^':
    return o1 ** o2

delim = '+-=*/^()'

prio = {'+' : 1, '-' : 1, '*' : 2, '/' : 2, '^' : 3}

def eva(exp):
  opn = []
  opr = []

  token = ''
  pBump = 0

  for c in exp:

    if c not in delim:
      token += c
    else:
      if c == '(':
        pBump += 3
      elif c == ')':
        pBump -= 3
      else:
        opn.append(int(token.strip()))
        token = ''

        if len(opr) == 0:
          opr.append(Operator(c, prio.get(c) + pBump))
        else:

          while len(opn) >= 2 and ( opr[len(opr) - 1].prior >= prio.get(c) + pBump):
            op2 = opn.pop()
            op1 = opn.pop()
            cd = opr.pop().cmd

            opn.append(exe(cd, op1, op2))
          opr.append(Operator(c, prio.get(c) + pBump))

  opn.append(int(token.strip()))

  while len(opn) >= 2:
    op2 = opn.pop()
    op1 = opn.pop()
    cd = opr.pop().cmd

    opn.append(exe(cd, op1, op2))

  return opn[0]


from __future__ import print_function
import os
import json
import _pickle as cPickle
import numpy as np
import util.utils as utils
import warnings
with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=FutureWarning)
import h5py
from xml.etree.ElementTree import parse
import torch
from torch.utils.data import Dataset
import tools.compute_softscore
import itertools
import re

COUNTING_ONLY = False

def is_howmany(q, a, label2ans):
    if 'how many' in q.lower() or \
       ('number of' in q.lower() and 'number of the' not in q.lower()) or \
       'amount of' in q.lower() or \
       'count of' in q.lower():
        if a is None or answer_filter(a, label2ans):
            return True
        else:
            return False
    else:
        return False

def answer_filter(answers, label2ans, max_num=10):
    for ans in answers['labels']:
        if label2ans[ans].isdigit() and max_num >= int(label2ans[ans]):
            return True
    return False

def _create_entry(img, question, answer):
    if None!=answer:
        answer.pop('image_id')
        answer.pop('question_id')
    entry = {
        'question_id' : question['question_id'],
        'image_id'    : question['image_id'],
        'image'       : img,
        'question'    : question['question'],
        'answer'      : answer}
    return entry

def _load_dataset(dataroot, name, img_id2val, label2ans):
    """Load entries

    img_id2val: dict {img_id -> val} val can be used to retrieve image or features
    dataroot: root path of dataset
    name: 'train', 'val', 'test-dev2015', test2015'
    """
    question_path = os.path.join(
        dataroot, 'v2_OpenEnded_mscoco_%s_questions.json' % \
        (name + '2014' if 'test'!=name[:4] else name))
    questions = sorted(json.load(open(question_path))['questions'],
                       key=lambda x: x['question_id'])
    if 'test'!=name[:4]: # train, val
        answer_path = os.path.join(dataroot, 'cache', '%s_target.pkl' % name)
        answers = cPickle.load(open(answer_path, 'rb'))
        answers = sorted(answers, key=lambda x: x['question_id'])

        utils.assert_eq(len(questions), len(answers))
        entries = []
        for question, answer in zip(questions, answers):
            utils.assert_eq(question['question_id'], answer['question_id'])
            utils.assert_eq(question['image_id'], answer['image_id'])
            img_id = question['image_id']
            if not COUNTING_ONLY or is_howmany(question['question'], answer, label2ans):
                entries.append(_create_entry(img_id2val[img_id], question, answer))
    else: # test2015
        entries = []
        for question in questions:
            img_id = question['image_id']
            if not COUNTING_ONLY or is_howmany(question['question'], None, None):
                entries.append(_create_entry(img_id2val[img_id], question, None))

    return entries

class VQAFeatureDataset(Dataset):
    def __init__(self, name, dictionary, dataroot='data', adaptive=False):
        super(VQAFeatureDataset, self).__init__()
        assert name in ['train', 'val', 'test-dev2015', 'test2015']

        ans2label_path = os.path.join(dataroot, 'cache', 'trainval_ans2label.pkl')
        label2ans_path = os.path.join(dataroot, 'cache', 'trainval_label2ans.pkl')
        self.ans2label = cPickle.load(open(ans2label_path, 'rb'))
        self.label2ans = cPickle.load(open(label2ans_path, 'rb'))
        self.num_ans_candidates = len(self.ans2label)

        self.dictionary = dictionary
        self.adaptive = adaptive

        self.img_id2idx = cPickle.load(
            open(os.path.join(dataroot, '%s%s_imgid2idx.pkl' % (name, '' if self.adaptive else '36')), 'rb'))

        h5_path = os.path.join(dataroot, '%s%s.hdf5' % (name, '' if self.adaptive else '36'))

        print('loading features from h5 file')
        # with h5py.File(h5_path, 'r') as hf:
        #     self.features = np.array(hf.get('image_features'))
        #     self.spatials = np.array(hf.get('spatial_features'))
        #     if self.adaptive:
        #         self.pos_boxes = np.array(hf.get('pos_boxes'))
        hf = h5py.File(h5_path, 'r')
        self.features = hf.get('image_features')
        self.spatials = hf.get('spatial_features')
        if self.adaptive:
            self.pos_boxes = hf.get('pos_boxes')

        self.entries = _load_dataset(dataroot, name, self.img_id2idx, self.label2ans)
        self.tokenize()
        self.tensorize()
        # self.v_dim = self.features.size(1 if self.adaptive else 2)
        # self.s_dim = self.spatials.size(1 if self.adaptive else 2)
        self.v_dim = self.features.shape[1 if self.adaptive else 2]
        self.s_dim = self.spatials.shape[1 if self.adaptive else 2]

    def tokenize(self, max_length=14):
        """Tokenizes the questions.

        This will add q_token in each entry of the dataset.
        -1 represent nil, and should be treated as padding_idx in embedding
        """
        for entry in self.entries:
            tokens = self.dictionary.tokenize(entry['question'], False)
            tokens = tokens[:max_length]
            if len(tokens) < max_length:
                # Note here we pad in front of the sentence
                padding = [self.dictionary.padding_idx] * (max_length - len(tokens))
                tokens = tokens + padding
            utils.assert_eq(len(tokens), max_length)
            entry['q_token'] = tokens

    def tensorize(self):
        # self.features = torch.from_numpy(self.features)
        # self.spatials = torch.from_numpy(self.spatials)

        for entry in self.entries:
            question = torch.from_numpy(np.array(entry['q_token']))
            entry['q_token'] = question

            answer = entry['answer']
            if None != answer:
                labels = np.array(answer['labels'])
                scores = np.array(answer['scores'], dtype=np.float32)
                if len(labels):
                    labels = torch.from_numpy(labels)
                    scores = torch.from_numpy(scores)
                    entry['answer']['labels'] = labels
                    entry['answer']['scores'] = scores
                else:
                    entry['answer']['labels'] = None
                    entry['answer']['scores'] = None

    def __getitem__(self, index):
        entry = self.entries[index]
        if not self.adaptive:
            # features = self.features[entry['image']]
            # spatials = self.spatials[entry['image']]
            features = torch.from_numpy(self.features[entry['image']])
            spatials = torch.from_numpy(self.spatials[entry['image']])
        else:
            # features = self.features[self.pos_boxes[entry['image']][0]:self.pos_boxes[entry['image']][1],:]
            # spatials = self.spatials[self.pos_boxes[entry['image']][0]:self.pos_boxes[entry['image']][1],:]
            features = torch.from_numpy(
                self.features[self.pos_boxes[entry['image']][0]:self.pos_boxes[entry['image']][1], :])
            spatials = torch.from_numpy(
                self.spatials[self.pos_boxes[entry['image']][0]:self.pos_boxes[entry['image']][1], :])

        question = entry['q_token']
        question_id = entry['question_id']
        answer = entry['answer']
        if None != answer:
            labels = answer['labels']
            scores = answer['scores']
            target = torch.zeros(self.num_ans_candidates)
            if labels is not None:
                target.scatter_(0, labels, scores)
            return features, spatials, question, target
        else:
            return features, spatials, question, question_id

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


#!/usr/bin/env python3

"""
Module that performs extraction. For usage, refer to documentation for the class
'Extractor'. This module can also be executed directly,
e.g. 'extractor.py <input> <output>'.
"""

import argparse
import hashlib
import multiprocessing
import os
import shutil
import tempfile
import traceback

import magic
import binwalk

class Extractor(object):
    """
    Class that extracts kernels and filesystems from firmware images, given an input file or directory and output directory.
    """

    # Directories that define the root of a UNIX filesystem, and the appropriate threshold condition
    UNIX_DIRS = ["bin", "etc", "dev", "home", "lib", "mnt", "opt", "root", "run", "sbin", "tmp", "usr", "var"]
    UNIX_THRESHOLD = 4

    # Lock to prevent concurrent access to visited set. Unfortunately, must be static because it cannot be pickled or passed as instance attribute.
    visited_lock = multiprocessing.Lock()

    def __init__(self, indir, outdir=None, rootfs=True, kernel=True):
        # Input firmware update file or directory
        self._input = os.path.abspath(indir)
        # Output firmware directory
        self.output_dir = os.path.abspath(outdir) if outdir else None

        # Whether to attempt to extract kernel
        self.do_kernel = kernel

        # Whether to attempt to extract root filesystem
        self.do_rootfs = rootfs

        # Set containing MD5 checksums of visited items
        self.visited = set()

        # List containing tagged items to extract as 2-tuple: (tag [e.g. MD5], path)
        self._list = list()

    def __getstate__(self):
        """
        Eliminate attributes that should not be pickled.
        """
        self_dict = self.__dict__.copy()
        del self_dict["_list"]
        return self_dict

    @staticmethod
    def io_dd(indir, offset, size, outdir):
        """
        Given a path to a target file, extract size bytes from specified offset to given output file.
        """
        if not size:
            return

        with open(indir, "rb") as ifp:
            with open(outdir, "wb") as ofp:
                ifp.seek(offset, 0)
                ofp.write(ifp.read(size))

    @staticmethod
    def magic(indata, mime=False):
        """
        Performs file magic while maintaining compatibility with different libraries.
        """

        try:
            if mime:
                mymagic = magic.open(magic.MAGIC_MIME_TYPE)
            else:
                mymagic = magic.open(magic.MAGIC_NONE)
            mymagic.load()
        except AttributeError:
            mymagic = magic.Magic(mime)
            mymagic.file = mymagic.from_file
        return mymagic.file(indata)

    @staticmethod
    def io_md5(target):
        """
        Performs MD5 with a block size of 64kb.
        """
        blocksize = 65536
        hasher = hashlib.md5()

        with open(target, 'rb') as ifp:
            buf = ifp.read(blocksize)
            while buf:
                hasher.update(buf)
                buf = ifp.read(blocksize)
            return hasher.hexdigest()

    @staticmethod
    def io_rm(target):
        """
        Attempts to recursively delete a directory.
        """
        shutil.rmtree(target, ignore_errors=False, onerror=Extractor._io_err)

    @staticmethod
    def _io_err(function, path, excinfo):
        """
        Internal function used by '_rm' to print out errors.
        """
        print(("!! %s: Cannot delete %s!\n%s" % (function, path, excinfo)))

    @staticmethod
    def io_find_rootfs(start, recurse=True):
        """
        Attempts to find a Linux root directory.
        """

        # Recurse into single directory chains, e.g. jffs2-root/fs_1/.../
        path = start
        while (len(os.listdir(path)) == 1 and
               os.path.isdir(os.path.join(path, os.listdir(path)[0]))):
            path = os.path.join(path, os.listdir(path)[0])

        # count number of unix-like directories
        count = 0
        for subdir in os.listdir(path):
            if subdir in Extractor.UNIX_DIRS and \
                os.path.isdir(os.path.join(path, subdir)):
                count += 1

        # check for extracted filesystem, otherwise update queue
        if count >= Extractor.UNIX_THRESHOLD:
            return (True, path)

        # in some cases, multiple filesystems may be extracted, so recurse to find best one
        if recurse:
            for subdir in os.listdir(path):
                if os.path.isdir(os.path.join(path, subdir)):
                    res = Extractor.io_find_rootfs(os.path.join(path, subdir), False)
                    if res[0]:
                        return res

        return (False, start)

    def extract(self):
        """
        Perform extraction of firmware updates from input to tarballs in output directory.
        """
        if os.path.isdir(self._input):
            for path, _, files in os.walk(self._input):
                for item in files:
                    self._list.append(os.path.join(path, item))
        elif os.path.isfile(self._input):
            self._list.append(self._input)
        else:
            print("!! Cannot read file: %s" % (self._input,))

        if self.output_dir and not os.path.isdir(self.output_dir):
            os.makedirs(self.output_dir)

        for item in self._list:
            self._extract_item(item)

    def _extract_item(self, path):
        """
        Wrapper function that creates an ExtractionItem and calls the extract() method.
        """

        ExtractionItem(self, path, 0).extract()

class ExtractionItem(object):
    """
    Class that encapsulates the state of a single item that is being extracted.
    """

    # Maximum recursion breadth and depth
    RECURSION_BREADTH = 5
    RECURSION_DEPTH = 3

    def __init__(self, extractor, path, depth):
        # Temporary directory
        self.temp = None

        # Recursion depth counter
        self.depth = depth

        # Reference to parent extractor object
        self.extractor = extractor

        # File path
        self.item = path

        # Checksum
        self.checksum = Extractor.io_md5(path)

        # Tag
        self.tag = "1"

        # Output file path and filename prefix
        self.output = os.path.join(self.extractor.output_dir, self.tag) if \
                                   self.extractor.output_dir else None

        # Status, with terminate indicating early termination for this item
        self.terminate = False
        self.status = None
        self.update_status()

    def __del__(self):
        if self.temp:
            self.printf(">> Cleaning up %s..." % self.temp)
            Extractor.io_rm(self.temp)

    def printf(self, fmt):
        """
        Prints output string with appropriate depth indentation.
        """
        print(("\t" * self.depth + fmt))

    def get_kernel_status(self):
        """
        Get the flag corresponding to the kernel status.
        """
        return self.status[0]

    def get_rootfs_status(self):
        """
        Get the flag corresponding to the root filesystem status.
        """
        return self.status[1]

    def update_status(self):
        """
        Updates the status flags using the tag to determine completion status.
        """
        kernel_done = os.path.isfile(self.get_kernel_path()) if \
            self.extractor.do_kernel and self.output else \
            not self.extractor.do_kernel

        rootfs_done = os.path.isfile(self.get_rootfs_path()) if \
            self.extractor.do_rootfs and self.output else \
            not self.extractor.do_rootfs

        self.status = (kernel_done, rootfs_done)

        return self.get_status()

    def get_status(self):
        """
        Returns True if early terminate signaled, extraction is complete, otherwise False.
        """
        return True if self.terminate or all(i for i in self.status) else False

    def get_kernel_path(self):
        """
        Return the full path (including filename) to the output kernel file.
        """
        return self.output + ".kernel" if self.output else None

    def get_rootfs_path(self):
        """
        Return the full path (including filename) to the output root filesystem file.
        """
        return self.output + ".tar.gz" if self.output else None

    def extract(self):
        """
        Perform the actual extraction of firmware updates, recursively. Returns
        True if extraction complete, otherwise False.
        """
        self.printf("\n" + self.item.encode("utf-8", "replace").decode("utf-8"))

        # check if item is complete
        if self.get_status():
            self.printf(">> Skipping: completed!")
            return True

        # check if exceeding recursion depth
        if self.depth > ExtractionItem.RECURSION_DEPTH:
            self.printf(">> Skipping: recursion depth %d" % self.depth)
            return self.get_status()

        # check if checksum is in visited set
        self.printf(">> MD5: %s" % self.checksum)
        with Extractor.visited_lock:
            if self.checksum in self.extractor.visited:
                self.printf(">> Skipping: %s..." % self.checksum)
                return self.get_status()
            else:
                self.extractor.visited.add(self.checksum)

        # check if filetype is blacklisted
        if self._check_blacklist():
            return self.get_status()

        # create working directory
        self.temp = tempfile.mkdtemp()

        try:
            self.printf(">> Tag: %s" % self.tag)
            self.printf(">> Temp: %s" % self.temp)
            self.printf(">> Status: Kernel: %s, Rootfs: %s, Do_Kernel: %s, Do_Rootfs: %s" % (
                            self.get_kernel_status(), self.get_rootfs_status(),
                            self.extractor.do_kernel, self.extractor.do_rootfs))

            for analysis in [self._check_archive, self._check_encryption, self._check_firmware,
                             self._check_kernel, self._check_rootfs, self._check_compressed]:
                # Move to temporary directory so binwalk does not write to input
                os.chdir(self.temp)

                # Update status only if analysis changed state
                if analysis():
                    if self.update_status():
                        self.printf(">> Skipping: completed!")
                        return True
        except Exception:
            traceback.print_exc()

        return False

    def _check_blacklist(self):
        """
        Check if this file is blacklisted for analysis based on file type.
        """
        # First, use MIME-type to exclude large categories of files
        filetype = Extractor.magic(self.item.encode("utf-8", "surrogateescape"), mime=True)
        if any(s in filetype for s in ["application/x-executable",
                                       "application/x-dosexec",
                                       "application/x-object",
                                       "application/pdf",
                                       "application/msword",
                                       "image/", "text/", "video/"]):
            self.printf(">> Skipping: %s..." % filetype)
            return True

        # Next, check for specific file types that have MIME-type 'application/octet-stream'
        filetype = Extractor.magic(self.item.encode("utf-8", "surrogateescape"))
        if any(s in filetype for s in ["executable", "universal binary", "relocatable", "bytecode", "applet"]):
            self.printf(">> Skipping: %s..." % filetype)
            return True

        # Finally, check for specific file extensions that would be incorrectly identified
        if self.item.endswith(".dmg"):
            self.printf(">> Skipping: %s..." % (self.item))
            return True

        return False

    def _check_archive(self):
        """
        If this file is an archive, recurse over its contents, unless it matches an extracted root filesystem.
        """
        return self._check_recursive("archive")

    def _check_encryption(self):
        header = b""
        with open(self.item, "rb") as f:
            header = f.read(4)

        if header == b"SHRS":
            print(">>>> Found D-Link encrypted firmware in %s!" % (self.item))

            # Source: https://github.com/0xricksanchez/dlink-decrypt
            command = 'dd if=%s skip=1756 iflag=skip_bytes status=none | openssl aes-128-cbc -d -nopad -nosalt -K "c05fbf1936c99429ce2a0781f08d6ad8" -iv "67c6697351ff4aec29cdbaabf2fbe346" --nosalt -in /dev/stdin -out %s > /dev/null 2>&1' % (self.item, os.path.join(self.temp, "dlink_decrypt"))
            os.system(command)
            return True
        return False

    def _check_firmware(self):
        """
        If this file is of a known firmware type, directly attempt to extract the kernel and root filesystem.
        """
        for module in binwalk.scan(self.item, "-y", "header", "--run-as=root", "--preserve-symlinks", signature=True, quiet=True):
            for entry in module.results:
                # uImage
                if "uImage header" in entry.description:
                    if not self.get_kernel_status() and "OS Kernel Image" in entry.description:
                        kernel_offset = entry.offset + 64
                        kernel_size = 0

                        for stmt in entry.description.split(','):
                            if "image size:" in stmt:
                                kernel_size = int(''.join(i for i in stmt if i.isdigit()), 10)

                        if kernel_size != 0 and kernel_offset + kernel_size <= os.path.getsize(self.item):
                            self.printf(">>>> %s" % entry.description)

                            tmp_fd, tmp_path = tempfile.mkstemp(dir=self.temp)
                            os.close(tmp_fd)
                            Extractor.io_dd(self.item, kernel_offset, kernel_size, tmp_path)
                            kernel = ExtractionItem(self.extractor, tmp_path, self.depth)

                            return kernel.extract()

                # TP-Link or TRX
                elif not self.get_kernel_status() and not self.get_rootfs_status() and \
                            "rootfs offset: " in entry.description and "kernel offset: " in entry.description:
                    kernel_offset = 0
                    kernel_size = 0
                    rootfs_offset = 0
                    rootfs_size = 0

                    for stmt in entry.description.split(','):
                        if "kernel offset:" in stmt:
                            kernel_offset = int(stmt.split(':')[1], 16)
                        elif "kernel length:" in stmt:
                            kernel_size = int(stmt.split(':')[1], 16)
                        elif "rootfs offset:" in stmt:
                            rootfs_offset = int(stmt.split(':')[1], 16)
                        elif "rootfs length:" in stmt:
                            rootfs_size = int(stmt.split(':')[1], 16)

                    # compute sizes if only offsets provided
                    if kernel_offset != rootfs_size and kernel_size == 0 and rootfs_size == 0:
                        kernel_size = rootfs_offset - kernel_offset
                        rootfs_size = os.path.getsize(self.item) - rootfs_offset

                    # ensure that computed values are sensible
                    if (kernel_size > 0 and kernel_offset + kernel_size <= os.path.getsize(self.item)) and \
                                (rootfs_size != 0 and rootfs_offset + rootfs_size <= os.path.getsize(self.item)):
                        self.printf(">>>> %s" % entry.description)

                        tmp_fd, tmp_path = tempfile.mkstemp(dir=self.temp)
                        os.close(tmp_fd)
                        Extractor.io_dd(self.item, kernel_offset, kernel_size, tmp_path)
                        kernel = ExtractionItem(self.extractor, tmp_path, self.depth)
                        kernel.extract()

                        tmp_fd, tmp_path = tempfile.mkstemp(dir=self.temp)
                        os.close(tmp_fd)
                        Extractor.io_dd(self.item, rootfs_offset, rootfs_size, tmp_path)
                        rootfs = ExtractionItem(self.extractor, tmp_path, self.depth)
                        rootfs.extract()

                        return self.update_status()
        return False

    def _check_kernel(self):
        """
        If this file contains a kernel version string, assume it is a kernel.
        """
        if not self.get_kernel_status():
            for module in binwalk.scan(self.item, "-y", "kernel", "--run-as=root", "--preserve-symlinks", signature=True, quiet=True):
                for entry in module.results:
                    if "kernel version" in entry.description:
                        if "Linux" in entry.description:
                            if self.get_kernel_path():
                                shutil.copy(self.item, self.get_kernel_path())
                            else:
                                self.extractor.do_kernel = False
                            self.printf(">>>> %s" % entry.description)
                            return True
                        # VxWorks, etc
                        else:
                            self.printf(">>>> Ignoring: %s" % entry.description)
                            return False
                return False
        return False

    def _check_rootfs(self):
        """
        If this file contains a known filesystem type, extract it.
        """

        if not self.get_rootfs_status():
            # work-around issue with binwalk signature definitions for ubi
            for module in binwalk.scan(self.item, "-e", "-r", "-y", "filesystem", "-y", "ubi", "--run-as=root", "--preserve-symlinks", signature=True, quiet=True):
                for entry in module.results:
                    self.printf(">>>> %s" % entry.description)
                    break

                if module.extractor.directory:
                    unix = Extractor.io_find_rootfs(module.extractor.directory)

                    if not unix[0]:
                        return False

                    self.printf(">>>> Found Linux filesystem in %s!" % unix[1])
                    if self.output:
                        shutil.make_archive(self.output, "gztar", root_dir=unix[1])
                    else:
                        self.extractor.do_rootfs = False
                    return True
        return False

    def _check_compressed(self):
        """
        If this file appears to be compressed, decompress it and recurse over its contents.
        """
        return self._check_recursive("compressed")

    def _check_recursive(self, fmt):
        """
        Unified implementation for checking both "archive" and "compressed" items.
        """
        desc = None
        # perform extraction
        for module in binwalk.scan(self.item, "-e", "-r", "-y", fmt, "--run-as=root", "--preserve-symlinks", signature=True, quiet=True):
            for entry in module.results:
                # skip cpio/initrd files since they should be included with kernel
                # if "cpio archive" in entry.description:
                #     self.printf(">> Skipping: cpio: %s" % entry.description)
                #     self.terminate = True
                #     return True
                desc = entry.description
                self.printf(">>>> %s" % entry.description)
                break

            if module.extractor.directory:
                unix = Extractor.io_find_rootfs(module.extractor.directory)

                # check for extracted filesystem, otherwise update queue
                if unix[0]:
                    self.printf(">>>> Found Linux filesystem in %s!" % unix[1])
                    if self.output:
                        shutil.make_archive(self.output, "gztar", root_dir=unix[1])
                    else:
                        self.extractor.do_rootfs = False
                    return True
                else:
                    count = 0
                    self.printf(">> Recursing into %s ..." % fmt)
                    for root, _, files in os.walk(module.extractor.directory):
                        # sort both descending alphabetical and increasing length
                        files.sort()
                        files.sort(key=len)

                        # handle case where original file name is restored; put it to front of queue
                        if desc and "original file name:" in desc:
                            orig = None
                            for stmt in desc.split(","):
                                if "original file name:" in stmt:
                                    orig = stmt.split("\"")[1]
                            if orig and orig in files:
                                files.remove(orig)
                                files.insert(0, orig)

                        for filename in files:
                            if count > ExtractionItem.RECURSION_BREADTH:
                                self.printf(">> Skipping: recursion breadth %d" % ExtractionItem.RECURSION_BREADTH)
                                self.terminate = True
                                return True
                            else:
                                new_item = ExtractionItem(self.extractor, os.path.join(root, filename), self.depth+1)
                                if new_item.extract():
                                    if self.update_status():
                                        return True
                            count += 1
        return False

def main():
    parser = argparse.ArgumentParser(description="Extracts filesystem and kernel from Linux-based firmware images")
    parser.add_argument("input", action="store", help="Input file or directory")
    parser.add_argument("output", action="store", nargs="?", default="images", help="Output directory for extracted firmware")
    parser.add_argument("-nf", dest="rootfs", action="store_false", default=True, help="Disable extraction of root filesystem")
    parser.add_argument("-nk", dest="kernel", action="store_false", default=True, help="Disable extraction of kernel")
    result = parser.parse_args()

    extract = Extractor(result.input, result.output, result.rootfs, result.kernel)
    extract.extract()

if __name__ == "__main__":
    main()


import django_filters
from django_filters import FilterSet, DateTimeFilter
from django.forms import DateTimeInput
from .models import Post

class PostFilter(FilterSet):
    title = django_filters.CharFilter(
        field_name='title',
        lookup_expr='icontains',
        label='Заголовок',
    )

    type = django_filters.ChoiceFilter(
        field_name='category_type',
        label='Тип',
        empty_label='Выбрать',
        choices=Post.CATEGORY_CHOICES,
    )

    added_after = DateTimeFilter(
        field_name='date_create',
        lookup_expr='gt',
        label='Дата публикации с:',
        widget=DateTimeInput(
            format='%Y-%m-%dT%H:%M',
            attrs={'type': 'datetime-local'},
        )
    )


# 6.10

# isPrime 함수를 정의하고 매개변수로 number를 받는다.
def isPrime(number) :

    # 결과 출력 시 줄바꿈을 위한 카운트
    lineChange = 0

    # 만약 매개변수가 2이면
    if number == 2 :

        # 2는 소수이므로 2를 출력하고
        print("2")

        # 함수를 끝낸다.
        return

    # 1부터 number-1까지 반복한다.
    for x in range(1, number) :

        # 약수의 개수를 0으로 초기화한다.
        count = 0

        # 1부터 x까지 반복한다.
        for y in range(1, x) :

            # 딱 나누어 떨어지면 약수이므로
            if x % y == 0 :

                # 약수의 개수를 증가시킨다.
                count = count + 1

        # 만약 약수의 개수가 1개이면
        if count == 1 :

            # 소수이므로 결과를 출력한다.
            print(format(x, "5.0f"), end = '  ')

            # 줄바꿈 카운트를 증가시킨다.
            lineChange = lineChange + 1

            # 줄바꿈 카운트가 10이면
            if lineChange == 10 :

                # 줄바꿈 카운트를 초기화시키고
                lineChange = 0

                # 줄을 바꾼다.
                print()

# 숫자를 입력받는다.
num = eval(input("숫자를 입력하세요 : "))

print(num, "이하의 숫자 중에서 소수를 찾습니다.")

# 소수를 찾는다.
isPrime(num)


#-----<Step1: Intstall Required Packages>---------
import streamlit as st
import pickle
import numpy as np
from sklearn import metrics
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier as knn
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
import pickle
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import precision_score,recall_score,f1_score

# Title and Subheader
from PIL import Image
image = Image.open('fitbod_logo2.jpg')
st.image(image, width=1,caption=None,
    use_column_width=True)
st.title("Fitbod Helper: Predict Churn User")
st.header("Step0: Understand Dataset")

image = Image.open('new_churn.jpg')
st.image(image, width=1,caption='New User VS. Churn User',
    use_column_width=True)

# Load the pipeline and data
X_test = pickle.load(open('X_test.sav', 'rb'))
y_test = pickle.load(open('y_test.sav', 'rb'))
workoutData = pickle.load(open('workoutData.sav', 'rb'))
replace_cols=['churn_user']
for i in replace_cols :
    y_test[i]  = y_test[i].replace({1.0 : 1, 0.0:0})

pipe1 = pickle.load(open('pipe_KNN.sav', 'rb'))
knn_pre_class = pipe1.predict(X_test)
knn_pre_prob = pipe1.predict_proba(X_test)
#score1 = pipe1.score(X_test, y_test)
score1 = 0.688
#auc1 = cross_val_score(pipe1, X_test, y_test, scoring='roc_auc', cv=10)
# precision_KNN= precision_score(y_true=y_test, y_pred=knn_pre_class)
precision_KNN = 0.500
# recall_KNN=recall_score(y_true=y_test, y_pred=knn_pre_class)
recall_KNN = 0.200
#f1_KNN=f1_score(y_true=y_test, y_pred=knn_pre_class)
f1_KNN = 0.286

pipe2 = pickle.load(open('pipe_RF.sav', 'rb'))
rf_pre_class = pipe2.predict(X_test)
rf_pre_prob = pipe2.predict_proba(X_test)
#score2 = pipe2.score(X_test, y_test)
score2=0.938
#auc1 = cross_val_score(pipe1, X_test, y_test, scoring='roc_auc', cv=10)
#precision_RF= precision_score(y_true=y_test, y_pred=rf_pre_class)
precision_RF=0.500
#recall_RF=recall_score(y_true=y_test, y_pred=rf_pre_class)
recall_RF= 0.400
#f1_RF=f1_score(y_true=y_test, y_pred=rf_pre_class)
f1_RF=0.444

pipe3 = pickle.load(open('pipe_LR.sav', 'rb'))
lr_pre_class = pipe3.predict(X_test)
lr_pre_prob = pipe3.predict_proba(X_test)
#score3 = pipe3.score(X_test, y_test)
score3=0.625
#auc1 = cross_val_score(pipe1, X_test, y_test, scoring='roc_auc', cv=10)
#precision_LR= precision_score(y_true=y_test, y_pred=lr_pre_class)
precision_LR=0.400
#recall_LR=recall_score(y_true=y_test, y_pred=lr_pre_class)
recall_LR = 0.400
#f1_LR=f1_score(y_true=y_test, y_pred=lr_pre_class)
f1_LR = 0.400

clf_compare ={'Accuracy':[score1,score2,score3],
                     'precision':[precision_KNN,precision_RF,precision_LR],
                     'recall':[recall_KNN,recall_RF,recall_LR],
                     'F1 Score':[f1_KNN,f1_RF,f1_LR]}
clf_compare = pd.DataFrame(clf_compare)
clf_compare.index=['KNN','Random Forest','Logistic Regression']

if st.checkbox('Show User Workout History Data (original)--->>>'):
    st.write(workoutData.head())
uploaded_file = st.file_uploader("Choose a CSV file in the Workout History Format", type="csv")
st.set_option('deprecation.showfileUploaderEncoding', False)

if uploaded_file is not None:
    data = pd.read_csv(uploaded_file)
    st.write(data)

if st.checkbox('Show Processed Data (Model Inputs)--->>>'):
    st.write(X_test.head())

def test_demo(index):
    values = X_test.iloc[index]
    image = Image.open('user3.png')
    st.sidebar.image(image, width=1,caption='User Workout History Portrait',
    use_column_width=True)
    # Create User Input Data in the sidebar/text
    active_days = st.sidebar.slider("How Many Days User Has Workouted with Fitbod?")
    workout_times = st.sidebar.slider("What's the Total Workout Times?")
    workout_per_day = st.sidebar.slider("What's the Workout Times per Day?")
    volume_total = st.sidebar.text_input("What's the Total Exercise Volume on Fitbod?")
    volume_per_day = st.sidebar.slider("Volume(Reps) per Day?")
    intensity_total = st.sidebar.text_input("Total Intensity(Weight)?")
    intensity_per_day = st.sidebar.slider("Intensity(Weight) per Day?")
    favorite_exercise_0 = st.sidebar.selectbox("User's Most Frequently Chosen Exercise?", workoutData.exerciseName.unique().tolist(),key='2')
    dic = {'Barbell Bench Press':0.22, 'Dumbbell Bench Press':0.33, 'Dumbbell Bench Press':0.307, 'Close-Grip Bench Press':0.57,
    'Deadlift':0.3077, 'Dumbbell Lunge':0.4286, 'Dumbbell Shoulder Press':0.50, 'Dumbbell Row':0.6, 'Dumbbell Bent Over Row':0.4
    }
    favorite_exercise= dic[favorite_exercise_0]
    most_recent_exercise_0 = st.sidebar.selectbox("User's Latest Chosen Exercise?",workoutData.exerciseName.unique().tolist(),key='2')
    most_recent_exercise=dic[most_recent_exercise_0]

    stay_days = st.sidebar.slider("Total Days User Has Registered on Fitbod?")
    active_extent= st.sidebar.slider("User's Active Extent?",min_value=0.00, max_value=1.00, step=0.01)
    last_to_now= st.sidebar.slider("How Many Days Went since User's Latest Workout?")
    high_volume_user = st.sidebar.slider("Whether User is High Volume?")
    high_intensity_user = st.sidebar.slider("Whether User is High Intensity User?")
    high_active_user = st.sidebar.slider("Whether User is Highly Active?")

    #Print the prediction result
    st.balloons()
    st.header("Step1: Choose Model")
    if st.checkbox('See the model performance comparison before choosing your favorite one :)'):
        st.write(clf_compare)
        st.write('               🎉 Random Forest Wins the Best AUC Score！！    ')
        image = Image.open('model_AUC.jpg')
        st.image(image, width=1,caption='AUC comparison of 3 Trained Models (Examples)',
    use_column_width=True)
    alg = ['KNN', 'Random Forest', 'Logistic Regression']
    classifier = st.selectbox('Which model do you want to choose for prediction?', alg)
    st.header("Step2: See Machine Learning prediction for this user!")
    dic2={1:'Attention! This is potential churn user!',0:'Congras! This user will stay in Fitbod in the prediction period!'}

    if classifier == 'KNN':
        #pip1 = pickle.load(open('pipe_KNN.sav', 'rb'))
        user_prediction_data = np.array([active_days,
       workout_times, workout_per_day, volume_total, volume_per_day,
       intensity_total, intensity_per_day, favorite_exercise,
       most_recent_exercise, stay_days, active_extent, last_to_now,
       high_volume_user, high_intensity_user, high_active_user]).reshape(1,15)

        res = pipe1.predict_proba(user_prediction_data)
        churn = pipe1.predict(user_prediction_data)
        st.write('According to your input, the churn rate is predicted to be', res[:,1])
        if churn ==0:
            st.write('🎉Congras! Our model suggests that this user will stay in Fitbod for the prediction period!')
        elif churn==1:
            st.write('😢Attention! This is a potential churn user!')
        st.text('Notice: the recall of this model means',)
        image = Image.open('knn_recall.jpg')
        st.image(image, width=1,
    use_column_width=True)
        #st.write('Recall: ', recall_KNN)

        #st.write('Confusion Matrix: ', cm)

    elif classifier == 'Random Forest':
        #pip2 = pickle.load(open('pipe_RF.sav', 'rb'))
        user_prediction_data = np.array([active_days,
       workout_times, workout_per_day, volume_total, volume_per_day,
       intensity_total, intensity_per_day, favorite_exercise,
       most_recent_exercise, stay_days, active_extent, last_to_now,
       high_volume_user, high_intensity_user, high_active_user]).reshape(1,15)

        res = pipe2.predict_proba(user_prediction_data)
        churn = pipe2.predict(user_prediction_data)
        st.write('According to your input, the churn rate is predicted to be', res[:,1])
        if churn ==0:
            st.write('🎉Congras! Our model suggests that this user will stay in Fitbod for the prediction period!')
        elif churn==1:
            st.write('😢Attention! This is a potential churn user!')
        st.text('Notice: the recall of this model means',)
        image = Image.open('rf_lr_recall.jpg')
        st.image(image, width=1,
    use_column_width=True)

        image = Image.open('rf_feature.jpg')
        st.image(image, width=1,caption='Feature Importance for Random Forest',
    use_column_width=True)

        #st.write('Confusion Matrix: ', cm)

    elif classifier == 'Logistic Regression':
        #if st.checkbox('See the interpretation of model--->>>'):
            #image = Image.open('LR_feature_importance.jpg')
            #st.image(image, width=1,caption=None, use_column_width=True)
        user_prediction_data = np.array([active_days,
       workout_times, workout_per_day, volume_total, volume_per_day,
       intensity_total, intensity_per_day, favorite_exercise,
       most_recent_exercise, stay_days, active_extent, last_to_now,
       high_volume_user, high_intensity_user, high_active_user]).reshape(1,15)

        res = pipe3.predict_proba(user_prediction_data)
        churn = pipe3.predict(user_prediction_data)
        st.write('According to your input, the churn rate is predicted to be', res[:,1])
        if churn ==0:
            st.write('🎉Congras! Our model suggests that this user will stay in Fitbod for the prediction period!')
        elif churn==1:
            st.write('😢Attention! This is a potential churn user!')
        st.text('Notice: the recall of this model means',)
        image = Image.open('rf_lr_recall.jpg')
        st.image(image, width=1,
    use_column_width=True)

        image = Image.open('LR_feature.png')
        st.image(image, width=1,caption='Feature Importance for Logistic Regression',
    use_column_width=True)
        #st.write('Confusion Matrix: ', cm)
number = st.text_input('Choose sample from dataset (0 - 200):', 0)  # Input the index number
test_demo(int(number))  # Run the test function


# importing the libraries required

from collections import Counter
from nltk.corpus.reader import sentiwordnet
import requests
import bs4
import string
import re
from nltk.tokenize import word_tokenize,sent_tokenize
from nltk.corpus import stopwords
from collections import Counter
from nltk.sentiment.vader import SentimentIntensityAnalyzer

# creating a method to parse and extract data from the url provided;
# Data cleaning, tokenization and emotion checking is added too.

def extract(url):

    # url = str(input("Please enter the url from where you want to extract the Information:\n"))

    headers = {
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0',
    }

    r= requests.get(url, headers=headers)
    htmlcontent  = r.content

    # Parsing the html content using Beautiful Soup

    soup = bs4.BeautifulSoup(htmlcontent,"html.parser")

    article_title = soup.find("span",class_ = "td-bred-no-url-last").text
    article_body = soup.find("div", class_ = "td-post-content",).text

    directory = (r"")

    # get fileName from user
    filepath = directory + input("Enter filename: ")

    # Creates a new file
    with open(filepath, 'w', errors = "ignore") as f:
        f.write(article_title)
        f.write(article_body)

    with open(filepath,"r") as f:
        text = f.read()

    lower_case = text.lower()

    cleaned_text = lower_case.translate(str.maketrans("","",string.punctuation))

    tokenized_text = word_tokenize(cleaned_text,"english")

    final_text_list = []

    for word in tokenized_text:
        if word not in stopwords.words("english"):
            final_text_list.append(word)

    # print(final_text_list)

    emotion_list = []
    with open("emotions.txt","r") as f:
        for line in f:
            cleaned_emotions = line.replace("\n", "").replace("'","").replace(",","").strip()
            word,emotion = cleaned_emotions.split(":")

            if word in final_text_list:
                emotion_list.append(emotion)

    # print(emotion_list)

    # method to get the values for sensitive analysis. Using nested methods to get results

    # def sentiment_analysis(text):
    score = SentimentIntensityAnalyzer().polarity_scores(text)
    pos = score["pos"]
    print(f"Positive Score {pos}")
    neg = score["neg"]
    print(f"Negetive Score {neg}")
    if pos>neg:
        print("Positive Sentiment is observed")
    elif neg>pos:
        print("Negetive Sentiment is observed")
    else:
        print("Neutral Sentiment is observed")

    #Polarity Score

    pol = ((pos-neg)/(pos+neg)+ 0.000001)
    print(f"The Polarity score is {pol}")

    # ubjective Score

    subj = ((pos+neg)/(len(text))+ 0.000001)
    print(f"The Subjectivity score is {subj}")

    # Word count on the clean text(removed punctuations and stopwords)

    # def word_count(text):
    # from nltk.tokenize import word_tokenize

    no_of_words = len(word_tokenize(cleaned_text))
    print(f"The Word Count : {no_of_words}")

    # Avg Word length = total no of characters / total no of words

    # def avg_word_len(text):
    # from nltk.tokenize import word_tokenize

    no_of_chars = 0
    for word in word_tokenize(cleaned_text):
        no_of_chars  = no_of_chars+ len(word)

    avg_word_len = no_of_chars / no_of_words
    print(f"Avg_word_length : {avg_word_len}")

    # avg no of words per sentence = no_of_words / no_of_sentences

    # def avg_no_of_words_per_sent(text):
    # from nltk.tokenize import word_tokenize,sent_tokenize

    no_of_sents = len(sent_tokenize(cleaned_text))
    avg_no_of_words_per_sent = (no_of_words / no_of_sents)
    print(f"The Avg no of words per Sentence : {avg_no_of_words_per_sent}")

    # Method to print syllables

    # def syllable_count(word):
    # word = word.lower()

    words=word_tokenize(cleaned_text)
    vowels = "a","e","i","o","u","y"
    no_of_syllables = 0
    for word in words:
        if word[0] in vowels:
            no_of_syllables = no_of_syllables+1

    for index in range (1,len(word)):
        if word[index] in vowels and word[index-1] not in vowels:
            no_of_syllables = no_of_syllables+1

    if word.endswith("e"):
        no_of_syllables = no_of_syllables - 1

    if no_of_syllables == 0:
        no_of_syllables = no_of_syllables+1

    print(f"The No of syllables present:{no_of_syllables}")

    # Method to count the complex numbers

    # def complex_word_count(text):
    # from nltk.tokenize import word_tokenize
    words=word_tokenize(cleaned_text)
    complex_word = 0
    for word in words:
        if (no_of_syllables>2):
            complex_word = complex_word+1

    print(f"The complex word count : {complex_word}")

    # Method for the percentage of complex numbers

    # def percent_complex(text):
    # from nltk.tokenize import word_tokenize

    complex_percent = (complex_word/ no_of_words)*100
    print(f"The Percentage of complex words : {complex_percent}")

    # Fog Index

    # def fog_index(text):
    # avg_sent_length = avg_no_of_words_per_sent()

    fog_read = 0.4*(avg_no_of_words_per_sent/ complex_percent)
    print(f"The Fog Index : {fog_read}")

    # Method to find personal Pronoun Count
    # def personal_pronoun(text):

    count = 0
    if "I" in text:
        pronoun = re.split("I", text)
        count = count+1
        if "us" in text:
            pronoun = re.split("us", text)
            count = count+1
            if "we" in text:
                pronoun = re.split("we", text)
                count = count+1
                if "my" in text:
                    pronoun = re.split("my", text)
                    count = count+1
                    if "ours" in text:
                        pronoun = re.split("ours", text)
                        count = count+1

    print(f"Number of pronouns present: {count}")

with open("abc.txt","r") as f:
        for line in f:
            e = extract(line)
            print(e)


from pathlib import Path
import sys
from threading import *
from time import *
from record import *

# Explicit imports to satisfy Flake8
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage, Label
import tkinter as tk
import tkinter.filedialog # Keep this

# Multithreading context switching every 1.0 seconds
sys.setswitchinterval(1.0)

OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path(r"assets/frame0")
print(ASSETS_PATH)

def relative_to_assets(path: str) -> Path:
    return ASSETS_PATH/Path(path)

# Function to record the baseline
def recBaselineFunc():
    addr = entry_1.get("1.0",'end-1c')
    if not addr:
        tk.messagebox.showerror(
            title="Empty Fields!", message="Please enter IP Address.")
        return

    global ip_addr
    ip_addr = "ws://" + addr

    print("Recording Baseline")
    updateConsole("Basline Recorded")
    record_baseline(ip_addr)

# Starts the main program
def startFunc():
    addr = entry_1.get("1.0",'end-1c')
    if not addr:
        tk.messagebox.showerror(
            title="Empty Fields!", message="Please enter IP Address.")
        return

    global ip_addr
    ip_addr = "ws://" + addr

    print("Starting program")
    updateConsole("Starting program")
    global record_app
    global stream_data_app
    record_app.start()
    stream_data_app.start()

# Exit the program
def exitFunc():
    print("Exiting")
    sys.exit()

#########################################################################
# Returns a score based on the acceleration
def score_acc(data):
    baseline_acc_fn = 'baseline_data/baseline_acc.csv'

    x, y, z = [], [], []
    with open(baseline_acc_fn,'r') as csvfile:
        lines = csv.reader(csvfile, delimiter=',')
        for row in lines:
            x.append(float(row[0]))
            y.append(float(row[1]))
            z.append(float(row[2]))

    const = 0.0
    px = (abs(max(x)-min(x)) * const)
    py = (abs(max(y)-min(y)) * const)
    pz = (abs(max(z)-min(z)) * const)

    xmax, xmin = max(x)+px, min(x)-px
    ymax, ymin = max(y)+py, min(y)-py
    zmax, zmin = max(z)+pz, min(z)-pz

    # Score:
    score = 0
    for tx,ty,tz in data:
        ref = 3
        if (tx>xmax or tx<xmin):
            ref -= 1
        if (ty>ymax or ty<ymin):
            ref -= 1
        if (tz>zmax or tz<zmin):
            ref -= 1

        if (ref < 2): # ABNORMAL
            pass
        else: # NORMAL
            score += 1
            pass

    score = (score/len(data)) * 100
    updateScore(score)
    print(score)

# Returns a score based on gyroscope data
# FIXME - not in use
def score_gyr(data):
    baseline_gyr_fn = 'baseline_data/baseline_gyr.csv'

    x, y, z = [], [], []
    with open(baseline_gyr_fn,'r') as csvfile:
        lines = csv.reader(csvfile, delimiter=',')
        for row in lines:
            x.append(float(row[0]))
            y.append(float(row[1]))
            z.append(float(row[2]))

    const = 0.0
    px = (abs(max(x)-min(x)) * const)
    py = (abs(max(y)-min(y)) * const)
    pz = (abs(max(z)-min(z)) * const)

    xmax, xmin = max(x)+px, min(x)-px
    ymax, ymin = max(y)+py, min(y)-py
    zmax, zmin = max(z)+pz, min(z)-pz

    # Score:
    score = 0
    for tx,ty,tz in data:
        ref = 3
        if (tx>xmax or tx<xmin):
            ref -= 1
        if (ty>ymax or ty<ymin):
            ref -= 1
        if (tz>zmax or tz<zmin):
            ref -= 1

        if (ref < 2): # ABNORMAL
            pass
        else: # NORMAL
            score += 1
            pass

    score = (score/len(data)) * 100

# Function to update the score on the ui
def updateScore(chng):
    label_1.config(text = chng)

# Function to update the console
def updateConsole(chng):
    label_2.config(text = chng)
#########################################################################

# Main code for the ui
def ui():
    window = Tk()
    window.geometry("400x550")
    window.configure(bg = "#FFFFFF")

    canvas = Canvas(
        window,
        bg = "#FFFFFF",
        height = 550,
        width = 400,
        bd = 0,
        highlightthickness = 0,
        relief = "ridge"
    )

    canvas.place(x = 0, y = 0)
    canvas.create_rectangle(
        34.0,
        114.0,
        355.0,
        349.0,
        fill="#D9D9D9",
        outline="")

    image_image_1 = PhotoImage(
        file=relative_to_assets("image_1.png"))
    image_1 = canvas.create_image(
        206.0,
        55.0,
        image=image_image_1
    )

    canvas.create_text(
        96.0,
        139.0,
        anchor="nw",
        text="IP Address:",
        fill="#000000",
        font=("Inter Bold", 15 * -1)
    )

    entry_image_1 = PhotoImage(
        file=relative_to_assets("entry_1.png"))
    entry_bg_1 = canvas.create_image(
        242.5,
        149.0,
        image=entry_image_1
    )

    global entry_1
    entry_1 = Text(
        bd=0,
        bg="#F1F1F1",
        fg="#000716",
        highlightthickness=0,
        font=("Helvetica", 7)
    )
    entry_1.place(
        x=191.0,
        y=142.0,
        width=103.0,
        height=12.0
    )

    # Walking Score rectangle
    canvas.create_rectangle(
        95.0,
        402.0,
        306.0,
        525.0,
        fill="#D9D9D9",
        outline="")

    global label_1
    label_1 = Label(
        bd=0,
        bg="#F1F1F1",
        fg="#000716",
        highlightthickness=0,
        text="100"
    )
    label_1.place(
        x=175.0,
        y=450.0,
        width=50.0,
        height=50.0
    )

    global label_2
    label_2 = Label(
        bd=0,
        bg="#F1F1F1",
        fg="#000716",
        highlightthickness=0,
        text=">> Welcome!"
    )
    label_2.place(
        x=100.0,
        y=347.0,
        width=200.0,
        height=30.0
    )

    button_image_1 = PhotoImage(
        file=relative_to_assets("button_1.png"))
    button_1 = Button(
        image=button_image_1,
        borderwidth=0,
        highlightthickness=0,
        command=startFunc,
        relief="flat"
    )
    button_1.place(
        x=126.0,
        y=230.0,
        width=136.35812377929688,
        height=40.0
    )

    button_image_2 = PhotoImage(
        file=relative_to_assets("button_2.png"))
    button_2 = Button(
        image=button_image_2,
        borderwidth=0,
        highlightthickness=0,
        command=recBaselineFunc,
        relief="flat"
    )
    button_2.place(
        x=95.0,
        y=172.0,
        width=199.0,
        height=40.0
    )

    button_image_3 = PhotoImage(
        file=relative_to_assets("button_3.png"))
    button_3 = Button(
        image=button_image_3,
        borderwidth=0,
        highlightthickness=0,
        command=exitFunc,
        relief="flat"
    )
    button_3.place(
        x=152.0,
        y=290.0,
        width=85.0,
        height=34.46666717529297
    )

    canvas.create_text(
        133.0,
        412.0,
        anchor="nw",
        text="Walking Score",
        fill="#000000",
        font=("Inter Bold", 20 * -1)
    )
    window.resizable(False, False)

    window.mainloop()

# Class to start new thread for recording real-time data
class record_APP(Thread):
    def run(self):
        global ip_addr
        record(ip_addr)

# Class to start thread to capture the real-time data
class stream_data_APP(Thread):
    def run(self):
        while True:
            # print(list(LIVE_DATA.queue))
            live_data = list(LIVE_DATA.queue)
            if len(live_data) == REALTIME_SAMPLES:
                score_acc(list(LIVE_DATA.queue))
                # score_gyr(list(LIVE_DATA.queue))
            sleep(0.1)

def main():
    global record_app
    global stream_data_app
    record_app = record_APP(daemon=True)
    stream_data_app = stream_data_APP(daemon=True)

    global ip_addr

    ui()

if __name__ == "__main__":
    main()


# TO USE - WORK PERFECTLY!
#  sudo pip3 install gatt
#  sudo apt-get install python3-dbus
#
# https://github.com/getsenic/gatt-python

# all AT commands for Bluetooth 4.0:
# http://fab.cba.mit.edu/classes/863.15/doc/tutorials/programming/bluetooth/bluetooth40_en.pdf
# try: AT+PIO....    no \n at the end! The + sign is part of the command
import gatt

manager = gatt.DeviceManager(adapter_name='hci0')

class AnyDevice(gatt.Device):
    def connect_succeeded(self):
        super().connect_succeeded()
        print("[%s] Connected" % (self.mac_address))

    def connect_failed(self, error):
        super().connect_failed(error)
        print("[%s] Connection failed: %s" % (self.mac_address, str(error)))

    def disconnect_succeeded(self):
        super().disconnect_succeeded()
        print("[%s] Disconnected" % (self.mac_address))

    def services_resolved(self):
        super().services_resolved()
        print("[%s] Resolved services" % (self.mac_address))
        for service in self.services:
            print("[%s]  Service [%s]" % (self.mac_address, service.uuid))
            for characteristic in service.characteristics:
                print("[%s]    Characteristic [%s]" % (self.mac_address, characteristic.uuid))

    def write_characteristic(self, uuid, value):
        for service in self.services:
            for characteristic in service.characteristics:
                if characteristic.uuid==uuid:
                    characteristic.write_value(value.encode("utf-8"))
                    return
        print("Unknow characteristic {}. Try services_resolved".format(uuid))

    def characteristic_write_value_succeeded(self, characteristic):
        print("Door is open!")
        self.manager.stop()

    def characteristic_write_value_failed(self, characteristic, error):
        print("Failed to open the door:", error)
        self.manager.stop()

device = AnyDevice(mac_address='50:8C:B1:69:A2:F1', manager=manager)
device.connect()
device.services_resolved()
door_characteristic="0000ffe1-0000-1000-8000-00805f9b34fb"
device.write_characteristic(door_characteristic, "ONCE")
try:
    manager.run()
finally:
    device.disconnect()


import os
from tensorflow import keras
import tensorflow as tf
from sarp.utils import (
    load_expert_data_hospital,
    separate_train_test,
    curriculum_training,
)

if __name__ == "__main__":
    batch_size = 32
    num_epochs = 100
    num_hidden = 256
    learning_rate = 0.001

    # load the expert data
    data_dir = os.path.dirname(os.path.realpath(__file__)) + f"/data/expert_data"
    num_samples = len(os.listdir(data_dir))

    state, action, _, _ = load_expert_data_hospital(data_dir, num_samples)
    train_data, test_data = separate_train_test([state, action], test_ratio=0.2)

    state_train, action_train = train_data
    state_test, action_test = test_data

    # build model
    model = keras.Sequential(
        [
            keras.layers.Dense(num_hidden, activation="relu"),
            keras.layers.Dense(num_hidden, activation="relu"),
            keras.layers.Dense(action_train[0].shape[-1], activation="linear"),
        ]
    )
    model.compile(
        optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
        loss="mse",
        metrics=["mse"],
    )

    # train model
    tf_callback = [
        keras.callbacks.ReduceLROnPlateau(
            monitor="val_loss",
            factor=0.1,
            patience=5,
            min_lr=0.00001,
            verbose=1,
        ),
        keras.callbacks.EarlyStopping(
            monitor="val_loss", patience=10, restore_best_weights=True
        ),
    ]
    # model.fit(
    #     tf.concat(state_train, 0),
    #     tf.concat(action_train, 0),
    #     batch_size=batch_size,
    #     epochs=num_epochs,
    #     validation_data=(tf.concat(state_test, 0), tf.concat(action_test, 0)),
    #     callbacks=tf_callback,
    # )
    curriculum_training(
        model,
        state_train,
        action_train,
        state_test,
        action_test,
        epochs=num_epochs,
        batch_size=batch_size,
        learning_rate=learning_rate,
    )
    # save model
    current_dir = os.path.dirname(os.path.realpath(__file__))
    if not os.path.exists(current_dir + f"/trained_models/policy"):
        os.makedirs(current_dir + f"/trained_models/policy")
    keras.models.save_model(
        model,
        f"{current_dir}/trained_models/policy/model",
        overwrite=True,
        include_optimizer=False,
        save_format=None,
        signatures=None,
        options=None,
        save_traces=True,
    )


"""
Problem: Array Replace
Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem.

Example

For inputArray = [1, 2, 1], elemToReplace = 1, and substitutionElem = 3, the output should be
arrayReplace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3].

Input/Output

[execution time limit] 4 seconds (py3)

[input] array.integer inputArray

Guaranteed constraints:
0 ≤ inputArray.length ≤ 104,
0 ≤ inputArray[i] ≤ 109.

[input] integer elemToReplace

Guaranteed constraints:
0 ≤ elemToReplace ≤ 109.

[input] integer substitutionElem

Guaranteed constraints:
0 ≤ substitutionElem ≤ 109.

[output] array.integer
"""
def arrayReplace(inputArray, elemToReplace, substitutionElem):
    for i in range(len(inputArray)):
        if elemToReplace == inputArray[i]:
            inputArray[i] = substitutionElem
    return inputArray
"""
Problem: Even Digits only
Check if all digits of the given integer are even.

Example

For n = 248622, the output should be
evenDigitsOnly(n) = true;
For n = 642386, the output should be
evenDigitsOnly(n) = false.
Input/Output

[execution time limit] 4 seconds (py3)

[input] integer n

Guaranteed constraints:
1 ≤ n ≤ 109.

[output] boolean

true if all digits of n are even, false otherwise.
"""
def evenDigitsOnly(n):
    num = str(n)
    for i in range(len(num)):
        if int(num[i]) % 2 != 0:
            return False
    return True

"""
Problem: variable name
Correct variable names consist only of English letters, digits and underscores and they can't start with a digit.

Check if the given string is a correct variable name.

Example

For name = "var_1__Int", the output should be
variableName(name) = true;
For name = "qq-q", the output should be
variableName(name) = false;
For name = "2w2", the output should be
variableName(name) = false.
Input/Output

[execution time limit] 4 seconds (py3)

[input] string name

Guaranteed constraints:
1 ≤ name.length ≤ 10.

[output] boolean

true if name is a correct variable name, false otherwise.
"""
def variableName(name):
    for i in name:
        if i.isalnum() or i == "_":
            if name[0].isnumeric():
                return False
            continue
        else:
            return False
    return True
"""
Problem: Alphabetic Shift
Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a).

Example

For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz".

Input/Output

[execution time limit] 4 seconds (py3)

[input] string inputString

A non-empty string consisting of lowercase English characters.

Guaranteed constraints:
1 ≤ inputString.length ≤ 1000.

[output] string

The resulting string after replacing each of its characters.
"""
def alphabeticShift(inputString):
    check = set()
    arr = list(inputString)
    for i in range(len(arr)):
        if i in check:
            continue
        for j in range(i, len(arr)):
            if arr[i] == arr[j]:
                r = chr(ord(arr[i]) + 1)
                if r == "{":
                    r = "a"
                arr[j] = r
                check.add(j)

    inputString = ""
    for i in arr:
        inputString += i
    return inputString
"""
Problem: Chess Border Cell Color
Given two cells on the standard chess board, determine whether they have the same color or not.

Example

For cell1 = "A1" and cell2 = "C3", the output should be
chessBoardCellColor(cell1, cell2) = true.

For cell1 = "A1" and cell2 = "H3", the output should be
chessBoardCellColor(cell1, cell2) = false.

Input/Output

[execution time limit] 4 seconds (py3)

[input] string cell1

Guaranteed constraints:
cell1.length = 2,
'A' ≤ cell1[0] ≤ 'H',
1 ≤ cell1[1] ≤ 8.

[input] string cell2

Guaranteed constraints:
cell2.length = 2,
'A' ≤ cell2[0] ≤ 'H',
1 ≤ cell2[1] ≤ 8.

[output] boolean

true if both cells have the same color, false otherwise.
"""
def chessBoardCellColor(cell1, cell2):
    if cell1 == cell2:
        return True

    x1,y1=cell1[0],cell1[1]
    x2,y2=cell2[0],cell2[1]

    x1,x2 = ord(x1),ord(x2)
    y1,y2 = int(y1),int(y2)

    if abs(y2-y1) % 2 ==0:
        if abs(x2-x1)%2==0:
            return True
    else:
        if not abs(x2-x1)%2==0:
            return True

    return False

Arcade/Intro/06. Rain of Reason/Problem 25 - 29.py


#program 3 of DAY 6

import random

length = int(input('enter the size of random number list    :   '))

lst = []
for i in range(length):
    ran = random.randint(-10,10)
    lst.append(ran)
print('the random number list is :  \n\n{}'.format(lst))

lst2 = []

for i in lst:
    if i >= 0:
        lst2.append(i)

if 0 not in lst2:
    lst2.append(0)
lst2.sort()

small = min(lst2)
for i in lst2:
    if ((small + 1) not in lst2):
        print('\nthe smallest positive number is  :  {}'.format(small+1))
        break
    else:
        small = small + 1


import csv
from datetime import date, timedelta
from .ApiSheetClient import ApiSheetClient

class HelabaReader:

    def __init__(self):

        # Mapping can not be done as product type is not included in export-file

        self.client = ApiSheetClient("Issuance Data Collection", "Helaba")

        finaldict = {}
        finaldict["date"] = date.today().strftime('%Y-%m-%d')

        resultdict = self.compare()
        finaldict["Zertifikate"] = resultdict

        self.client.updateFile(finaldict)

    '''
    def updateFile(entry):

        fname = "/Users/janickspirig/Desktop/Stats/DZBankStat/results.txt"

        with open(fname, 'a+') as outfile:
            outfile.seek(0, 2)  # end of file
            size = outfile.tell()  # the size...
            outfile.truncate(size - 1)
            outfile.write(',')
            json.dump(entry, outfile)
            outfile.write(']')
            outfile.close()
    '''

    def readData(self, area, date):
        products = []

        if area == "Zeichnungen":
            sub_fname = "Laufende"
        else:
            sub_fname = "Gesamtuebersicht"

        with open("/Users/janickspirig/PycharmProjects/IsuanceDataService/sp-handler/data/Helaba/{} {} {}.csv".format(sub_fname, area, date), "r",
                  encoding='ISO-8859-1') as f:

            reader = csv.reader(f, delimiter=";")
            next(reader)
            for i, line in enumerate(reader):
                if len(line) > 0:
                    product_id = line[1]
                    try:
                        product_type = line[0]
                    except IndexError:
                        product_type = "NotAllocated"
                    products.append([product_id, product_type])
        return products

    def compare(self):
        yesterday = (date.today() - timedelta(days=1)).strftime('%d-%m-%Y')
        today = date.today().strftime('%d-%m-%Y')

        oldProducts = self.readData("Neuemissionen", yesterday)
        newProducts = self.readData("Neuemissionen", today)

        count_dict = {}
        for x in newProducts:
            if not any(x[0] in sl for sl in oldProducts):
                if not x[1] in count_dict.keys():
                    count_dict[x[1]] = {}
                    count_dict[x[1]]['amount'] = 1
                    count_dict[x[1]]['ISINs'] = [x[0]]
                    # product type and then we have the number, so lets do product type as key and then another nested dict with number and examples --> and here at examples we put in some random IDs
                else:
                    count_dict[x[1]]['amount'] = count_dict[x[1]]['amount'] + 1
                    count_dict[x[1]]['ISINs'].append(x[0])
        return count_dict


import os
import setuptools

with open("/home/runner/termux-1/keepitrunning/README.md", "r") as fh:
    long_description = fh.read()

with open('/home/runner/termux-1/keepitrunning/requirements.txt') as f:
    required = f.read().splitlines()

setuptools.setup(
    name="keepitrunning",
    version="1.0.0",
    author="jiroawesome",
    description="A simple python library that makes your python website 24/7.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/jiroawesome/keepitrunning",
    project_urls={
        "Bug Tracker": "https://github.com/jiroawesome/keepitrunning/issues",
    },
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    package_dir={"": "src"},
    package_data={'': ['**/*']},
    packages=setuptools.find_packages(where="src"),
    python_requires=">=3.6",
    install_requires=required
)


from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django import forms
from django.conf.urls import url
from django.http import Http404
from django.http import HttpResponseRedirect
from django.shortcuts import render

from mvs.models import Aanmelding, Vrijwilliger

class AutocompleteOffMixin:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for field_name in self.fields:
            self.fields[field_name].widget.attrs["autocomplete"] = "off"

class VrijwilligerVraagForm(AutocompleteOffMixin, forms.Form):
    url = "vrijwilliger"
    title = "Vrijwilligers"
    description = "Zoals elk jaar zijn we weer op zoek naar vrijwilligers om ons te helpen tijdens de dagen. We kunnen helaas niet zonder. Hebt u tijd om te helpen? Ook als u maar een dag of een dagdeel kunt, bent u van harte welkom."

    aanmelden = forms.ChoiceField(
        label="Kunt u komen helpen?",
        choices=[
            ("ja", "Ja"),
            ("nee", "Nee"),
            ("nee", "Ik heb me al aangemeld"),
        ],
        widget=forms.RadioSelect,
    )

class VrijwilligerForm(AutocompleteOffMixin, forms.ModelForm):
    title = "Vrijwilligers"

    class Meta:
        model = Vrijwilliger
        exclude = []

        labels = {
            "tel": "Telefoonnummer 1",
            "tel2": "Telefoonnummer 2",
            "ehbo": "Heeft u een EHBO diploma?",
            "stage": "Bent u vrijwilliger voor een maatschappelijke stage?",
            "dagen": "Op welke dagen zou u (eventueel) kunnen komen helpen?",
            "taken": "Hebt u een voorkeur voor een bepaalde taak?",
            "eigen_kind": "Indien u een groep wilt begeleiden, wilt u uw eigen kind in de groep? (Geef de naam van de kinderen die u in de groep wil:)",
            "opmerkingen": "Hebt u nog andere opmerkingen?",
        }

        widgets = {
            "dagen": forms.CheckboxSelectMultiple,
            "taken": forms.CheckboxSelectMultiple,
            "geboortedatum": forms.DateInput(attrs={"type": "date"}),
        }

class VrijwilligerInschrijvenForm(VrijwilligerForm):
    url = "vrijwilliger/aanmelden"

    nog_een = forms.BooleanField(
        label="Wilt u nog een vrijwilliger opgeven?", required=False
    )

class AanmeldingBasisForm(AutocompleteOffMixin, forms.ModelForm):
    url = ""
    title = "Mezzeveulespeule Inschrijfformulier"
    heeft_allergien = forms.BooleanField(
        label="Heeft uw kind allergieën of zijn er bijzonderheden?", required=False
    )

    description = "Zijn jullie met meerdere kinderen thuis en willen jullie allemaal meedoen? Dat kan! Vul voor elk kind een apart formulier in. "

    class Meta:
        model = Aanmelding
        fields = [
            "voornaam",
            "achternaam",
            "geslacht",
            "klas",
            "adres",
            "email",
            "tel1",
            "tel2",
            "school",
        ]

        labels = {
            "voornaam": "Wat is zijn/haar voornaam?",
            "achternaam": "Wat is zijn/haar achternaam?",
            "geslacht": "Een jongen of meisje?",
            "klas": "In welke klas zit uw kind?",
            "adres": "Wat is zijn of haar adres?",
            "email": "Wat is uw e-mailadres?",
            "tel1": "Op welk telefoonnummer kunnen we u bereiken voor en tijdens de dagen?",
            "tel2": "Op welk tweede telefoonnummer kunnen we u in noodgevallen ook bellen?",
            "school": "Op welke school zit uw kind?",
        }
        widgets = {"geslacht": forms.RadioSelect}

class AllergienForm(AutocompleteOffMixin, forms.ModelForm):
    url = "allergien"
    title = "Allergieën en bijzonderheden"

    class Meta:
        model = Aanmelding
        fields = ["allergien"]
        labels = {
            "allergien": "Welke allergie heeft uw kind? Of waar moeten we rekening mee houden?"
        }

class GroepsmaatjeForm(AutocompleteOffMixin, forms.ModelForm):
    url = "groepsmaatje"
    title = "Groepsmaatje"
    description = ""

    class Meta:
        model = Aanmelding
        fields = ["groepsmaatje", "groepsmaatje_school"]

        labels = {
            "groepsmaatje": "Bij wie wil uw kind graag in de groep?",
            "groepsmaatje_school": "Op welke school zit dit groepsmaatje?",
        }

class OvernachtingForm(AutocompleteOffMixin, forms.ModelForm):
    url = "overnachting"
    title = "Overnachting voor groep 8"
    description = "Zit uw kind is groep 8? Dan mag hij voor 3,50 euro extra ook blijven overnachten. "

    class Meta:
        model = Aanmelding
        fields = ["overnachting"]
        labels = {"overnachting": "Wil uw kind ook blijven overnachten?"}

class OpmerkingenForm(AutocompleteOffMixin, forms.ModelForm):
    url = "opmerkingen"
    title = "Opmerkingen of vragen?"

    class Meta:
        model = Aanmelding
        fields = ["opmerkingen"]

        labels = {"opmerkingen": "Hebt u nog opmerkingen of vragen?"}

def get_form(url, post=None, initial=None):
    """
    Bepaal correcte formulier
    """
    forms = [
        VrijwilligerInschrijvenForm,
        VrijwilligerVraagForm,
        AanmeldingBasisForm,
        AllergienForm,
        GroepsmaatjeForm,
        OvernachtingForm,
        OpmerkingenForm,
    ]

    for form in forms:
        if form.url == url:
            if hasattr(form, "Meta") and form.Meta.model == Aanmelding:
                return form(post, initial=initial)
            else:
                return form(post)
    raise Http404

def redirect_to(form):
    return HttpResponseRedirect("/inschrijven/{0}".format(form.url))

def signedup_view(request):
    aangemeld_naam = request.session["aangemeld_naam"]
    if request.method == "POST":
        if "nog_een_kind" in request.POST:
            request.session["aanmelding"] = request.session["zelfde_kind"]

        request.session["zelfde_kind"] = {}
        request.session["aangemeld_naam"] = ""
        return redirect_to(AanmeldingBasisForm)

    return render(request, "signedup.html", {"aangemeld_naam": aangemeld_naam})

def signup_view(request, url):

    # Make sure aanmelding exists
    if "aanmelding" not in request.session:
        request.session["aanmelding"] = {}

    # Maak sessie leeg, handige link
    if url == "leeg":
        request.session["aanmelding"] = {}
        return redirect_to(AanmeldingBasisForm)

    # Handle einde

    if request.method == "POST":
        form = get_form(url, post=request.POST)

        if form.is_valid():
            # Copy all values into session
            if hasattr(form, "Meta") and form.Meta.model == Aanmelding:
                for key in form.Meta.fields:
                    request.session["aanmelding"][key] = form.cleaned_data[key]

            request.session.modified = True

            # Redirect to the next page
            if isinstance(form, AanmeldingBasisForm):
                if form.cleaned_data["heeft_allergien"]:
                    return redirect_to(AllergienForm)
                else:
                    return redirect_to(GroepsmaatjeForm)

            elif isinstance(form, AllergienForm):
                return redirect_to(GroepsmaatjeForm)

            elif isinstance(form, GroepsmaatjeForm):
                # Maybe go to Groep 8 page
                if request.session["aanmelding"]["klas"] == "8":
                    return redirect_to(OvernachtingForm)
                else:
                    return redirect_to(VrijwilligerVraagForm)

            elif isinstance(form, OvernachtingForm):
                return redirect_to(VrijwilligerVraagForm)

            elif isinstance(form, VrijwilligerVraagForm):
                if form.cleaned_data["aanmelden"] == "ja":
                    return redirect_to(VrijwilligerInschrijvenForm)
                else:
                    return redirect_to(OpmerkingenForm)
            elif isinstance(form, VrijwilligerInschrijvenForm):

                # Save form
                form.save()
                if form.cleaned_data["nog_een"]:
                    # TODO: Iets laten weten?
                    return redirect_to(VrijwilligerInschrijvenForm)
                else:
                    return redirect_to(OpmerkingenForm)

            elif isinstance(form, OpmerkingenForm):
                print(dict(request.session))

                aanmelding = Aanmelding(**request.session["aanmelding"])
                aanmelding.save()

                # Reset inschrijving
                zelfde_kind = {}
                for key in ["achternaam", "adres", "email", "tel1", "tel2", "school"]:
                    zelfde_kind[key] = request.session["aanmelding"][key]

                request.session["aangemeld_naam"] = (
                    aanmelding.voornaam + " " + aanmelding.achternaam
                )
                request.session["aanmelding"] = {}
                request.session["zelfde_kind"] = zelfde_kind

                # Sla formulier definitief op
                return HttpResponseRedirect("/inschrijven/aangemeld")

        # Not valid POST? Just show errors
    else:
        if url == VrijwilligerInschrijvenForm.url:
            aanmelding = request.session["aanmelding"]
            form = VrijwilligerInschrijvenForm(
                initial={
                    "achternaam": aanmelding["achternaam"],
                    "adres": aanmelding["adres"],
                    "tel": aanmelding["tel1"],
                    "email": aanmelding["email"],
                }
            )
        else:
            form = get_form(url, initial=request.session["aanmelding"])

    # Laat het formulier zien
    return render(request, "signup.html", {"form": form})

@apphook_pool.register
class SignUpHook(CMSApp):
    name = "Aanmeldingsformulier"

    def get_urls(self, page=None, language=None, **kwargs):

        # replace this with the path to your application's URLs module
        return [
            url(r"^aangemeld", signedup_view),
            url(r"^(.*)", signup_view),
        ]