import csv
import json
import logging
import pickle
from datetime import date

import pymysql
from flask import Flask, request, jsonify, \
    send_from_directory
from flask_cors import CORS
from pymysql import cursors

logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.DEBUG,
    datefmt='%Y-%m-%d %H:%M:%S',
    filename='myapp.log',
    filemode='w')

app = Flask(__name__)
CORS(app)

def load_from_file(filename):
    with open(filename, 'rb') as f:
        url_list_divided = pickle.load(f)
    return url_list_divided

def load_from_json_file(filename):
    with open(filename, 'r') as f:
        url_list_json = json.load(f)
    return url_list_json

# these 2 objects are image-caption data to be annotated, saved by pickle.dump
# Format:
# [
#   [(caption_1, url_1, source_1), (caption_2, url_2, source_2), ...] # annotator 1
#   [(caption_1, url_1, source_1), (caption_2, url_2, source_2), ...] # annotator 2
#   ...
# ]
#{'id':[(caption, url, source),(caption, url, source), ...]}
url_list = load_from_file('url_list.pkl')
test_url_list = load_from_file('url_list_divided.pkl')

@app.route('/', methods=('GET', 'POST',))
def hello_world():
    return 'Hello World!'

@app.route('/login', methods=['POST', 'OPTIONS'])
def login():
    id_annotator = request.args.get('id_annotator')
    passwd_annotator = request.args.get('passwd_annotator')
    req_json = request.get_json()
    app.logger.info(req_json)
    if req_json:
        id_annotator = req_json['id_annotator']
        passwd_annotator = req_json['passwd_annotator']
    app.logger.info('{} {} is trying to log in'.format(id_annotator, passwd_annotator))

    if id_annotator and passwd_annotator:

        db = pymysql.connect('localhost', 'merterm', '1234567890', 'google_annotation')

        cursor = db.cursor(cursors.DictCursor)
        sql = "SELECT * FROM `annotator` WHERE id_annotator='" + id_annotator + "'"
        # sql = "SELECT `id_annotator`, `passwd_annotator` FROM `annotator` WHERE id_annotator='" + id_annotator + "'"
        app.logger.debug('Database query: %s', sql)
        cursor.execute(sql)
        data = cursor.fetchone()
        app.logger.debug('Database query result: {}'.format(data))
        db.close()

        # logged in
        if data and data['passwd_annotator'] == passwd_annotator:
            return jsonify({'code': 200, 'msg': 'logged in', 'token': id_annotator})

    return jsonify({'code': 400, 'msg': 'error'})

@app.route('/index', methods=['POST', 'OPTIONS'])
def index():
    token = request.headers.get('token')
    if not token:
        app.logger.debug('{} is trying to get batches.'.format(token))
        return jsonify({'code': 400, 'msg': 'error'})
    app.logger.debug('{} is trying to get batches.'.format(token))
    batches = []

    batches = []
    if token.isdigit():
        id_annotator = int(token)
        batches = url_list[id_annotator - 1]
    elif token == 'test':
        batches = test_url_list[0]
    else:
        return jsonify({'code': 400, 'msg': 'id error'})

    ret = list(range(1, len(batches) + 1))
    return jsonify({'code': 200, 'id_batches': ret})

@app.route('/getone', methods=['POST', 'OPTIONS'])
def get_one():
    token = request.headers.get('token')
    id_batch = request.headers.get('id_batch')
    id_image = request.headers.get('id_image')
    if not token or id_batch is None or id_image is None:
        app.logger.debug('{} {} {} is trying to get one.'.format(token, id_image, id_batch))
        app.logger.debug(request.headers)
        return jsonify({'code': 400, 'msg': 'error'})
    id_batch = int(id_batch) - 1
    id_image = int(id_image) - 1
    app.logger.debug('{} is trying to get image {} in batch {}.'.format(token, id_image, id_batch))
    batches = []

    batches = []
    if token.isdigit():
        id_annotator = int(token)
        batches = url_list[id_annotator - 1]
    elif token == 'test':
        batches = test_url_list[0]
    else:
        return jsonify({'code': 400, 'msg': 'id error'})

    if id_batch >= len(batches) or id_batch < 0:
        return jsonify({'code': 400, 'msg': 'bad id_batch'})
    if id_image >= len(batches[id_batch]) or id_image < 0:
        return jsonify({'code': 400, 'msg': 'bad id_image'})
    app.logger.debug('size sanity check: {} {} {}'.format(id_image, id_batch, len(batches[id_batch])))
    ret = batches[id_batch][id_image]
    app.logger.debug('returning {}'.format(ret))
    source = 'test' if token == 'test' else ret[2]
    return jsonify({'code': 200, 'caption': ret[0], 'url': ret[1], 'source': source})

@app.route('/export', methods=['POST', 'OPTIONS'])
def export():
    token = request.headers.get('token')
    if not token or token != 'admin':
        app.logger.info('{} is trying to export.'.format(token))
        app.logger.debug(request.headers)
        return jsonify({'code': 400, 'msg': 'error'})

    db = pymysql.connect('localhost', 'merterm', '1234567890', 'google_annotation')

    cursor = db.cursor()
    sql = "SELECT * FROM `annotation`"
    app.logger.debug('Database query: %s', sql)
    cursor.execute(sql)
    data = cursor.fetchall()
    # app.logger.debug('Database query result: {}'.format(data))

    date_today = date.today().strftime('%m%d')

    with open('output_{}.tsv'.format(date_today), 'w') as fp:
        writer = csv.writer(fp, delimiter='\t', lineterminator='\n')
        col_names = [col[0] for col in cursor.description]
        writer.writerow(col_names)
        writer.writerows(data)
    db.close()

    return jsonify({'code': 200, 'msg': 'success'})

@app.route('/download')
def download():
    token = request.headers.get('token')
    app.logger.info('{} is trying to download.'.format(token))
    if not token or token != 'admin':
        app.logger.debug(request.headers)
        return jsonify({'code': 400, 'msg': 'error'})
    date_today = date.today().strftime('%m%d')

    return send_from_directory('.', 'output_{}.tsv'.format(date_today), as_attachment=True)

@app.route('/rmdb')
def rmdb():
    token = request.headers.get('token')
    app.logger.info('{} is trying to download.'.format(token))
    if not token or token != 'admin':
        app.logger.debug(request.headers)
        return jsonify({'code': 400, 'msg': 'error'})

    db = pymysql.connect('localhost', 'merterm', '1234567890', 'google_annotation')

    cursor = db.cursor()
    sql = "delete FROM `annotation`"
    app.logger.debug('Database deletion: %s', sql)
    cursor.execute(sql)
    data = cursor.fetchall()
    app.logger.debug('Database deletion result: {}'.format(data))
    db.commit()
    db.close()
    return jsonify({'code': 200, 'msg': 'error'})

@app.route('/annotate', methods=['POST', 'OPTIONS'])
def annotate():
    app.logger.debug(request.headers)
    token = request.headers.get('token')
    id_batch = request.headers.get('id_batch')
    id_image = request.headers.get('id_image')
    url = request.headers.get('url')
    caption = request.headers.get('caption')
    jsdata = request.get_json()
    if not token or id_batch is None or id_image is None or not url or not caption or not jsdata:
        app.logger.debug('{} {} {} {} {} is trying to annotate.'.format(token, id_image, id_batch, url, caption))
        app.logger.debug(jsdata)
        return jsonify({'code': 400, 'msg': 'error'})
    app.logger.info('{} {} {} {} {} is trying to annotate.'.format(token, id_image, id_batch, url, caption))
    app.logger.debug(jsdata)
    id_batch = int(id_batch) - 1
    id_image = int(id_image) - 1

    batches = []
    if token.isdigit():
        id_annotator = int(token)
        batches = url_list[id_annotator - 1]
    elif token == 'test':
        batches = test_url_list[0]
    else:
        return jsonify({'code': 400, 'msg': 'id error'})

    if id_batch >= len(batches) or id_batch < 0:
        return jsonify({'code': 400, 'msg': 'bad id_batch'})
    if id_image >= len(batches[id_batch]) or id_image < 0:
        return jsonify({'code': 400, 'msg': 'bad id_image'})

    db = pymysql.connect('localhost', 'merterm', '1234567890', 'google_annotation')

    cursor = db.cursor(cursors.DictCursor)
    caption = caption.replace("'", "''")
    url = url.replace("'", "''")

    other = jsdata['other']
    other = other.replace("'", "''")
    other = other.replace("\r", "|")
    other = other.replace("\n", "|")

    values = "NULL, \'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\'".format(
        token, caption,
        url,
        jsdata['cb0'],
        jsdata['cb1'],
        jsdata['cb2'],
        jsdata['cb3'],
        jsdata['cb4'],
        jsdata['cb5'],
        jsdata['cb6'],
        other,
        jsdata['cbWhen'],
        jsdata['cbHow'],
        jsdata['cbWhere'],
        jsdata['Identification'],
        jsdata['source'],
        jsdata['cbBrokenImg'],
        jsdata['cbMetaGood'],
        jsdata['cbMetaBad'],
        jsdata['cbVisible1'],
        jsdata['cbVisible2'],
        jsdata['cbVisible3'],
        jsdata['cbVisible4'],
        jsdata['cbVisible5'],
        jsdata['cbSubjectiveGood'],
        jsdata['cbSubjectiveBad'],
        jsdata['cbStory1'],
        jsdata['cbStory2'],
        jsdata['cbStory3'],
        jsdata['cbStory4'],
        jsdata['cbStory5'],
    )
    sql = "INSERT INTO annotation () VALUES ({})".format(values)
    app.logger.debug('Database insertion: %s', sql)
    cursor.execute(sql)
    db.commit()
    db.close()

    id_image += 1
    if id_image >= len(batches[id_batch]):
        return jsonify({'code': 200, 'id_image': -1})
    else:
        return jsonify({'code': 200, 'id_image': id_image + 1})

@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

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


# 가장 먼 노드
# 11 points

import collections
def solution(n, edge):
    dic = collections.defaultdict(list)
    for s, e in edge:
        dic[s - 1].append(e - 1)
        dic[e - 1].append(s - 1)

    been = [False for i in range(n)]
    q = [0]
    cnt = 0
    while len(q) > 0:
        newq = set()
        for node in q:
            been[node] = True
            for nxt in dic[node]:
                if not been[nxt]:
                    newq.add(nxt)
        q = [node for node in list(newq) if not been[node]]
        if len(q) == 0:
            break
        cnt = len(q)
    return cnt


"""
"""
from collections import defaultdict

import torch
from torch.utils.data import DataLoader
from torch.utils.data.sampler import RandomSampler

from ac.util import array_like_stack

def mt_collate_fn(batch_list):
    """ Collate function for a multi-task dataset.

    Assumes all inputs are the same size.

    Args:
        batch_list (list) list of sequences
    """
    all_inputs = []
    all_targets = defaultdict(list)
    all_info = []

    for inputs, targets, info in batch_list:
        all_inputs.append(inputs)
        all_info.append(info)
        for task, target in targets.items():
            if len(target.shape) < 1:
                target = target.unsqueeze(dim=0)
            all_targets[task].append(target)

    # stack targets and inputs
    all_targets = {task: array_like_stack(targets)
                   for task, targets in all_targets.items()}
    all_inputs = array_like_stack(all_inputs)
    return all_inputs, all_targets, all_info

class MTDataLoader(DataLoader):
    def __init__(self,
                 dataset,
                 batch_size=1,
                 shuffle=False,
                 num_workers=6,
                 sampler=None,
                 num_samples=1000,
                 replacement=False,
                 weight_task=None,
                 class_probs=None,
                 pin_memory=False):

        if sampler == 'RandomSampler':
            sampler = RandomSampler(data_source=dataset, num_samples=num_samples,
                                    replacement=True)
            self.num_samples = int(round(num_samples / batch_size))
        else:
            self.num_samples = int(round(len(dataset) / batch_size))

        super().__init__(dataset=dataset, batch_size=batch_size, shuffle=shuffle,
                         num_workers=num_workers, sampler=sampler, pin_memory=pin_memory,
                         collate_fn=mt_collate_fn)

    def __len__(self):
        return self.num_samples


# Girilen yazı palindorm ise EVET, değilse HAYIR yazan programı yazınız.
#yazıdaki boşluklar hesaba katılmayacak.
#palindrom : soldan sağa ve sağdan sola okunduğunda aynı olan yazıdır.

s=input()
t=""
for i in range(len(s)):
    if s[i] !=" ":
        t+=s[i]

kontrol=True

for i in range(len(t)//2):
    if t[i].lower() != t[len(t)-1-i].lower():
        kontrol=False
        break
if kontrol:
    print("EVET")
else:
    print("HAYIR")

basic projects 5 (karakter dizileri-strings/palindrom_yazi.py


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

from flask import Flask
import os
import logg
import pandas as pd
import numpy as np
from pipeline import Model_Pipeline,CleaningTextData,FillingNaN,TfIdf
from sklearn.ensemble import GradientBoostingRegressor
import nltk
import ssl
import datetime

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context
nltk.download('stopwords')
nltk.download('wordnet')
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from flask import request, jsonify

log = None
app = Flask(__name__)

data=""
prediction = None
gbr_result = None

@app.route('/')
def hello_world():
	return str(data)

@app.route('/api/v1/resources/conv', methods=['GET'])
def api_filter():
    query_parameters = request.args

    id = query_parameters.get('id')
    campaign_id = query_parameters.get('campaign_id')
    country_code = query_parameters.get('country_code')
    date = query_parameters.get('date')
    original_spend = query_parameters.get('original_spend')
    impression = query_parameters.get('impression')
    reach = query_parameters.get('reach')
    click = query_parameters.get('click')
    conversion_values_usd = query_parameters.get('conversion_values_usd')
    project_id = query_parameters.get('project_id')
    fb_id = query_parameters.get('fb_id')
    campaign_name = query_parameters.get('campaign_name')
    start_time = query_parameters.get('start_time')
    currency_code = query_parameters.get('currency_code')

    d = {
        'id':id,
        'campaign_id':campaign_id,
        'country_code':country_code,
        'date':date,
        'original_spend':float(original_spend),
        'impression':impression,
        'reach':reach,
        'click':click,
        'conversion_values_usd':float(conversion_values_usd),
        'project_id':project_id,
        'fb_id':fb_id,
        'campaign_name':campaign_name,
        'start_time':start_time,
        'currency_code':currency_code,
    }

    print(d)

    if not (id or campaign_id or country_code or date or original_spend or impression or reach or click or project_id or fb_id):
        return page_not_found(404)

    df = pd.DataFrame(d, index=[0])

    #df = pd.read_csv("try_to_test.csv")
    df = df.set_index('id')

    print(df)

    submition_res = func(df)

    return jsonify(submition_res.to_json(orient="records"))

@app.errorhandler(404)
def page_not_found(e):
    return "
404

The resource could not be found.
", 404

def func(X_test):

    y_test = X_test['conversion_values_usd']

    del X_test['conversion_values_usd']

    data = pipeline.pipelineData(X_test)

    print("sdfknksdnfklsldnfnklsdnf")

    print(type(data))

    data['conversion_values_usd'] = y_test.values

    print("sdfknksdnfsdfklaslflnksalfdkklsldnfnklsdnf")
    data = pd.DataFrame(data)

    print(data)

    print(type(data))

    del data["start_time"]
    del data["currency_code"]
    del data["country_code"]

    data["date"] = data["date"].apply(lambda x: int(x.strftime('%w')))

    data = data.astype('float')

    prediction = gbr_result.predict(data)

    submition_res = pd.DataFrame({'id': list(X_test.index), 'conversion_predict': prediction})
    print(submition_res)

    return submition_res

if __name__ == "__main__":

    log_directory = 'log'
    if not os.path.exists(log_directory):
        os.makedirs(log_directory)

    pipeline = Model_Pipeline("dft_idf_final.joblib")
    gbr_result = Model_Pipeline("XGBRegressor.joblib")

    #log = logg.setup_logging('Server')
    #log = logg.get_log("Web-server")

    app.run(debug=False,host='0.0.0.0')


import urllib.request
from bs4 import BeautifulSoup
import ssl
import json

# Ignore SSL cerificate errors(for HTTPS sites)
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter -')
# for HTTPS
html = urllib.request.urlopen(url, context=ctx).read()
# html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')

for ingredients in soup:
    print(ingredients)

output = []

# Retrieve all of the anchor tags, tag is an object
tags = soup('a')
for tag in tags:
    dictionary = {}
    link = tag.get('href', None)
    name = tag.text.strip()
    dictionary[name] = link
    output.append(dictionary)

serialized_json = json.dumps(output)
f = open('grind75-links.json', 'x')
f.write(serialized_json)
f.close()


class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        s_len = len(s)
        p_len = len(p)
        if s_len < p_len:
            return []

        p_count = Counter(p)
        s_count = Counter()
        result = []

        for i in range(s_len):
            s_count[s[i]]+=1
            if i>=p_len:
                if s_count[s[i-p_len]]==1:
                    del s_count[s[i-p_len]]
                else:
                    s_count[s[i-p_len]]-=1
            if s_count==p_count:
                result.append(i-p_len+1)
        return result


# explanations for member functions are provided in requirements.py
# each file that uses a Zip Tree should import it from this file.

from typing import TypeVar
import random

KeyType = TypeVar('KeyType')
ValType = TypeVar('ValType')

class Node:
    def __init__(self, key: KeyType, val: ValType, rank: int):
        self.key = key
        self.val = val
        self.rank = rank
        self.left = None
        self.right = None

class ZipTree:
    def __init__(self):
        self.root = None
        self.size = 0

    @staticmethod
    def get_random_rank() -> int:
        rk = 0
        while True:
            if random.randint(0, 1) == 0:
                return rk
            else:
                rk += 1

    def unzip(self, newNode: Node, top: Node):
        def unzip_lookup(k: int, node: Node):
            if not node:
                return (None, None)
            if node.key < k:
                (P, Q) = unzip_lookup(k, node.right)
                node.right = P
                return (node, Q)
            else:
                (P, Q) = unzip_lookup(k, node.left)
                node.left = Q
                return (P, node)

        return unzip_lookup(newNode.key, top)

    def insert(self, key: KeyType, val: ValType, rank: int = -1):
        if rank == -1:
            rank = self.get_random_rank()
        self.size += 1
        newNode = Node(key, val, rank)
        if not self.root:
            self.root = newNode
            return
        parent = None
        ptr = self.root
        while ptr and ptr.rank > newNode.rank:
            parent = ptr
            if newNode.key < ptr.key:
                ptr = ptr.left
            else:
                ptr = ptr.right
        while ptr and (ptr.rank == newNode.rank) and (ptr.key < newNode.key):
            parent = ptr
            ptr = ptr.right
        (P, Q) = self.unzip(newNode, ptr)
        newNode.left = P
        newNode.right = Q
        if not parent:
            self.root = newNode
        else:
            if newNode.key < parent.key:
                parent.left = newNode
            else:
                parent.right = newNode

    def zip(self, node: Node):
        def zipup(P: Node, Q: Node):
            if not P:
                return Q
            if not Q:
                return P
            if Q.rank > P.rank:
                Q.left = zipup(P, Q.left)
                return Q
            else:
                P.right = zipup(P.right, Q)
                return P

        return zipup(node.left, node.right)

    def remove(self, key: KeyType):
        self.size -= 1
        ptr = self.root
        parent = None
        direction = None
        while ptr.key != key:
            if ptr.key < key:
                parent = ptr
                ptr = ptr.right
                direction = "right"
            else:
                parent = ptr
                ptr = ptr.left
                direction = "left"

        n = self.zip(ptr)
        if not parent:
            self.root = n
        else:
            if direction == "left":
                parent.left = n
            else:
                parent.right = n

    def find(self, key: KeyType) -> ValType:
        ptr = self.root
        while ptr:
            if key == ptr.key:
                return ptr.val
            elif key < ptr.key:
                ptr = ptr.left
            else:
                ptr = ptr.right
        return None

    def get_size(self) -> int:
        return self.size

    def get_height_of_node(self, n: Node) -> int:
        if not n:
            return -1
        hl = self.get_height_of_node(n.left)
        hr = self.get_height_of_node(n.right)
        return 1 + max(hl, hr)

    def get_height(self) -> int:
        return self.get_height_of_node(self.root)

    def get_depth(self, key: KeyType):
        d = 0
        ptr = self.root
        while ptr:
            if key == ptr.key:
                return d
            else:
                d += 1
                if key < ptr.key:
                    ptr = ptr.left
                else:
                    ptr = ptr.right

# feel free to define new classes/methods in addition to the above
# fill in the definitions of each required member function (above),
# and any additional member functions you define


from edge_type import EdgeType

# Network structure

# Network sizes for edge types
NETWORK_SIZES = {
	# How many computers there are inside of a local wired network
	EdgeType.LOCAL_WIRED: 10,

	# How many computers there are inside of a local wireless network
	EdgeType.LOCAL_WIRELESS: 15,

	EdgeType.USB_SHARED: {
		# How many different networks a single USB drive should connect to
		'NUMBER_OF_NETWORKS': 3,

		# How many nodes in each network a single USB drive should connect to
		'NODES_IN_NETWORK': 4,

		# How many disconnected computers a single USB drive should connect to
		'NUMBER_OF_DISCONNECTED_COMPUTERS': 1
	}
}

# Total number of local wired networks
NUMBER_OF_LOCAL_WIRED_NETWORKS = 3000

# Total number of local wireless networks
NUMBER_OF_LOCAL_WIRELESS_NETWORKS = 5000

# Total number of USB sharing networks
NUMBER_OF_USB_SHARING_NETWORKS = 400

# Total number of PLCs
NUMBER_OF_PLC_NODES = 10000

# Transmission probabilities

# USB edge type

# The probability, for each wave, that an infected computer will infect its neighbor via USB
USB_TRANSMISSION_PROBABILITY = 0.01

# The probability, for each wave, that an infected computer will infect its neighbor via LNK vulnerability
LNK_TRANSMISSION_PROBABILITY = 0.1

# The probability, for each wave, that an infected computer will infect its neighbor via autorun vulnerability
AUTORUN_TRANSMISSION_PROBABILITY = 0.1

# Wired local network edge type

# The probability, for each wave, that an infected computer will infect its neighbor via print spooler vulnerability
PRINT_SPOOLER_TRANSMISSION_PROBABILITY = 0.1

# The probability, for each wave, that an infected computer will infect its neighbor via WinCC
WINCC_TRANSMISSION_PROBABILITY = 0.1

# The probability, for each wave, that an infected computer will infect its neighbor via SMB
SMB_TRANSMISSION_PROBABILITY = 0.1

# Wired and wireless local network edge type

# The probability, for each wave, that an infected computer will infect its neighbor via a network share
NETWORK_SHARES_TRANSMISSION_PROBABILITY = 0.1

# The probability, for each wave, that a given computer will get infected from a windows auto update
WINDOWS_AUTO_UPDATE_TRANSMISSION_PROBABILITY = 0.1

# Limits

# The number of milliseconds a wave is
WAVE_DURATION = 86400000

# The number of milliseconds until stuxnet self destructs
INFECTION_DURATION = 94608000000

# The number of computers a USB can infect before it self destructs
INFECTION_LIMIT = 3

# Number of initial USB nodes infected. Should be less than the number of USB sharing networks
NUMBER_OF_INITIAL_USB_NODES_INFECTED = 10

# Should draw the graph at the end
SHOULD_DRAW_GRAPH = False


import json
from urllib.parse import urlparse

LINKS_KEY = "links"
SCHEME_DELIMITER = "//"

ERROR_LINKS_LIST_OR_STR = "Links must be list or string"
ERROR_LINK_STR = "Link must be string"
ERROR_NO_DATA = "No data"
ERROR_BAD_DATA_FORMAT = "Not json data format"
ERROR_NO_KEY = f"'{LINKS_KEY}' key not found"
ERROR_BAD_RANGE_DATA = "range_data must be list"

class RedisLinksConnector:
    def __init__(self, client, name, id_name):
        self.client = client
        self.name = name
        self.id_name = id_name

    def add(self, links, timestamp):
        id = self.client.incr(self.id_name)

        pipe = self.client.pipeline(True)
        pipe.zadd(self.name, {id: timestamp})
        for link in links:
            pipe.rpush(id, link)
        pipe.execute()

    def get_by_range(self, min, max):
        ids = self.client.zrangebyscore(self.name, min, max)
        res = []
        for id in ids:
            links = self.client.lrange(id, 0, -1)
            res.extend([link.decode() for link in links])
        return res

class Links:
    def __init__(self, links):
        if not isinstance(links, (list, str)):
            raise TypeError(ERROR_LINKS_LIST_OR_STR)

        if isinstance(links, str):
            links = [links]

        if not all([isinstance(link, str) for link in links]):
            raise TypeError(ERROR_LINK_STR)

        self.links = links

    @staticmethod
    def get_domain(url):
        if SCHEME_DELIMITER not in url:
            url = SCHEME_DELIMITER + url
        parse = urlparse(url)
        return parse.netloc

    @classmethod
    def from_json(cls, json):
        if not json:
            raise ValueError(ERROR_NO_DATA)
        if not isinstance(json, dict):
            raise TypeError(ERROR_BAD_DATA_FORMAT)
        if LINKS_KEY not in json:
            raise KeyError(ERROR_NO_KEY)

        links = json[LINKS_KEY]
        return Links(links)

    def get_domains(self):
        res = []

        for link in self.links:
            res.append(self.get_domain(link))

        return list(set(res))


from collections import defaultdict, Counter

def read_input(file_path: str) -> list[tuple[list[str], list[str]]]:
    patterns_displayed_pairs = []
    with open(file_path, 'r') as fp:
        for line in fp.readlines():
            patterns, displayed = line.split('|')
            patterns = patterns.strip().split()
            displayed = displayed.strip().split()
            patterns_displayed_pairs.append((patterns, displayed))
    return patterns_displayed_pairs

def invert_dict(d: dict) -> dict:
    invert_dict = defaultdict(set)
    for k, v in d.items():
        invert_dict[v].add(k)
    return invert_dict

def solve_display(
        patterns: list[str], freq_to_segments: dict[int, set[str]], neighbors_to_segments: dict[int, set[str]]
) -> dict[str, str]:
    bad_segment_to_freq = Counter(list(''.join(patterns)))
    freq_to_bad_segments = invert_dict(bad_segment_to_freq)

    bad_segment_to_segment = {}
    # non ambiguous segments
    for freq, segments in freq_to_segments.items():
        if len(segments) == 1:
            segment = next(iter(segments))
            bad_segment = freq_to_bad_segments[freq].pop()
            bad_segment_to_segment[bad_segment] = segment
            del freq_to_bad_segments[freq]

    # ambiguous segments
    bad_segment_to_neighbors = defaultdict(int)
    for pattern in patterns:
        for segment in pattern:
            bad_segment_to_neighbors[segment] += len(pattern) - 1

    segments_used = set(bad_segment_to_segment.values())
    for bad_segments in freq_to_bad_segments.values():
        for bad_segment in bad_segments:
            bad_segment_neighbors = bad_segment_to_neighbors[bad_segment]
            candidates = neighbors_to_segments[bad_segment_neighbors]
            segment = next(iter(candidates - segments_used), None)
            bad_segment_to_segment[bad_segment] = segment
            segments_used.add(segment)

    return bad_segment_to_segment

def transform_segments(displayed_num: str, bad_segment_to_segment: dict[str, str]) -> str:
    trasnformed = []
    for bad_segment in displayed_num:
        trasnformed.append(bad_segment_to_segment[bad_segment])
    return ''.join(sorted(trasnformed))

def calc_number(
        displayed_nums: list[str], bad_segment_to_segment: dict[str, str], segment_to_num: dict[str, int]
) -> int:
    number = 0
    for displayed_num in displayed_nums:
        displayed_num = transform_segments(displayed_num, bad_segment_to_segment)
        displayed_num = segment_to_num[displayed_num]
        number = (number * 10) + displayed_num
    return number

def solve_displays(
        patterns_displayed_pairs: list[tuple[list[str], list[str]]],
        segment_to_num: dict[str, int],
        freq_to_segments: dict[int, set[str]],
        neighbors_to_segments: dict[int, set[str]]
) -> list[int]:
    numbers = []
    for patterns, displayed_nums in patterns_displayed_pairs:
        bad_segment_to_segment = solve_display(patterns, freq_to_segments, neighbors_to_segments)
        number = calc_number(displayed_nums, bad_segment_to_segment, segment_to_num)
        numbers.append(number)
    return numbers

if __name__ == '__main__':

    patterns_displayed_pairs = read_input('input.txt')

    num_to_segments = {
        0: 'abcefg',
        1: 'cf',
        2: 'acdeg',
        3: 'acdfg',
        4: 'bcdf',
        5: 'abdfg',
        6: 'abdefg',
        7: 'acf',
        8: 'abcdefg',
        9: 'abcdfg'
    }

    segment_to_freq = defaultdict(int)
    segment_to_neighbors = defaultdict(int)
    for segments in num_to_segments.values():
        for segment in segments:
            segment_to_freq[segment] += 1
            segment_to_neighbors[segment] += len(segments) - 1
    freq_to_segments = invert_dict(segment_to_freq)
    neighbors_to_segments = invert_dict(segment_to_neighbors)
    segment_to_num = {segments: num for num, segments in num_to_segments.items()}

    numbers = solve_displays(patterns_displayed_pairs, segment_to_num, freq_to_segments, neighbors_to_segments)
    print(sum(numbers))


import os
import time
import argparse

import torch
import numpy as np
from PIL import Image
from torch.autograd import Variable
from torchvision import transforms

from nets import basic, depth_predciton, basic_NL, DGNLNet
from config import test_raincityscapes_path
from misc import check_mkdir
from skimage.metrics import mean_squared_error
from skimage.metrics import peak_signal_noise_ratio
from skimage.metrics import structural_similarity

from dataset3 import ImageFolder, make_dataset
from skimage.measure import label, regionprops
from jittor_code.utils import reverse_mapping, visulize_mapping, edge_align, get_boundary_point
from hungarian_matching import caculate_tp_fp_fn

os.environ['CUDA_VISIBLE_DEVICES'] = '0'

torch.manual_seed(2019)
torch.cuda.set_device(0)

ckpt_path = './ckpt'
args = {
    'snapshot': '40000',
    'depth_snapshot': ''
}

transform = transforms.Compose([
    transforms.Resize([272,480]),
    transforms.ToTensor() ])

to_pil = transforms.ToPILImage()

def predict(exp_name, root_input, threshold):
    net = DGNLNet().cuda()

    if len(args['snapshot']) > 0:
        print('load snapshot \'%s\' for testing' % args['snapshot'])
        net.load_state_dict(torch.load(os.path.join(ckpt_path, exp_name, args['snapshot'] + '.pth'),
                                       map_location=lambda storage, loc: storage.cuda(0)))

    net.eval()
    avg_time = 0

    save_path = os.path.join(ckpt_path, exp_name, '(%s) prediction_%s_%s' % (exp_name, root_input.split("/")[-1], args['snapshot']))
    check_mkdir(save_path)

    with torch.no_grad():
        img_list = [img_name for img_name in os.listdir(root_input)]

        for idx, img_name in enumerate(img_list):
            img = Image.open(os.path.join(root_input, img_name)).convert('RGB')
            w, h = img.size
            img_var = Variable(transform(img).unsqueeze(0)).cuda()

            start_time = time.time()

            res, key_points = net(img_var)

            torch.cuda.synchronize()

            avg_time = avg_time + time.time() - start_time
            print('predicting: %d / %d, avg_time: %.5f' % (idx + 1, len(img_list), avg_time/(idx+1)))
            result = transforms.Resize((h, w))(to_pil(res.data.squeeze(0).cpu()))
            result.save(os.path.join(save_path, img_name))

            ################### DHT ##########################
            key_points = torch.sigmoid(key_points)
            binary_kmap = key_points.squeeze().cpu().numpy() > threshold
            kmap_label = label(binary_kmap, connectivity=1)
            props = regionprops(kmap_label)
            plist = []
            for prop in props:
                plist.append(prop.centroid)

            size = (272, 480)
            b_points = reverse_mapping(plist, numAngle=100, numRho=100, size=(272, 480))
            scale_w = size[1] / 480
            scale_h = size[0] / 272
            for i in range(len(b_points)):
                y1 = int(np.round(b_points[i][0] * scale_h))
                x1 = int(np.round(b_points[i][1] * scale_w))
                y2 = int(np.round(b_points[i][2] * scale_h))
                x2 = int(np.round(b_points[i][3] * scale_w))
                if x1 == x2:
                    angle = -np.pi / 2
                else:
                    angle = np.arctan((y1-y2) / (x1-x2))
                (x1, y1), (x2, y2) = get_boundary_point(y1, x1, angle, size[0], size[1])
                b_points[i] = (y1, x1, y2, x2)

            vis = visulize_mapping(b_points, size[::-1], result)
            vis.save(os.path.join(save_path, img_name).replace(".png", "_dht.png"))

def evaluate(exp_name, root_input, threshold):
    net = DGNLNet().cuda()

    if len(args['snapshot']) > 0:
        print('load snapshot \'%s\' for testing' % args['snapshot'])
        net.load_state_dict(torch.load(os.path.join(ckpt_path, exp_name, args['snapshot'] + '.pth'),
                                       map_location=lambda storage, loc: storage.cuda(0)))

    net.eval()
    avg_time = 0

    with torch.no_grad():

        img_list = make_dataset(root_input, is_train=False)
        MSE, PSNR, SSIM = 0, 0, 0
        total_tp = np.zeros(99)
        total_fp = np.zeros(99)
        total_fn = np.zeros(99)

        for idx, path in enumerate(img_list):
            save_path = os.path.join(ckpt_path, exp_name, '(%s) prediction_%s' % (exp_name, args['snapshot']))
            check_mkdir(save_path)

            img_path, gt_path, data_path = path
            data = np.load(data_path, allow_pickle=True).item()
            gt_coords = data["coords"]
            img = Image.open(img_path).convert('RGB')
            w, h = img.size
            img_var = Variable(transform(img).unsqueeze(0)).cuda()

            start_time = time.time()

            res, key_points = net(img_var)

            torch.cuda.synchronize()

            avg_time = avg_time + time.time() - start_time
            print('predicting: %d / %d, avg_time: %.5f' % (idx + 1, len(img_list), avg_time/(idx+1)))

            ##################### Dehaze ########################
            result = transforms.Resize((h, w))(to_pil(res.data.squeeze(0).cpu()))
            result.save(os.path.join(save_path, img_path.split("/")[-1]))

            gt = Image.open(gt_path).convert('RGB')
            result1 = np.array(result)
            gt = np.array(gt)
#            print(result.shape, gt.shape)
            MSE += mean_squared_error(gt, result1)
            PSNR += peak_signal_noise_ratio(gt, result1)
            SSIM += structural_similarity(gt, result1, multichannel=True)

            ################### DHT ##########################
            key_points = torch.sigmoid(key_points)
            binary_kmap = key_points.squeeze().cpu().numpy() > threshold
            kmap_label = label(binary_kmap, connectivity=1)
            props = regionprops(kmap_label)
            plist = []
            for prop in props:
                plist.append(prop.centroid)
            size = (272, 480)
            b_points = reverse_mapping(plist, numAngle=100, numRho=100, size=(272, 480))

            for i in range(1, 100):
                tp, fp, fn = caculate_tp_fp_fn(b_points, gt_coords, thresh=i*0.01)
                total_tp[i-1] += tp
                total_fp[i-1] += fp
                total_fn[i-1] += fn

            scale_w = size[1] / 480
            scale_h = size[0] / 272
            for i in range(len(b_points)):
                y1 = int(np.round(b_points[i][0] * scale_h))
                x1 = int(np.round(b_points[i][1] * scale_w))
                y2 = int(np.round(b_points[i][2] * scale_h))
                x2 = int(np.round(b_points[i][3] * scale_w))
                if x1 == x2:
                    angle = -np.pi / 2
                else:
                    angle = np.arctan((y1-y2) / (x1-x2))
                (x1, y1), (x2, y2) = get_boundary_point(y1, x1, angle, size[0], size[1])
                b_points[i] = (y1, x1, y2, x2)
            vis = visulize_mapping(b_points, size[::-1], result)
            vis.save(os.path.join(save_path, img_path.split("/")[-1].replace(".png", "_dht.png")))

        total_recall = total_tp / (total_tp + total_fn + 1e-8)
        total_precision = total_tp / (total_tp + total_fp + 1e-8)
        f = 2 * total_recall * total_precision / (total_recall + total_precision + 1e-8)

        print('%s_%s:' % (exp_name, args['snapshot']))
        print("MSE: " + str(MSE / len(img_list)))
        print("PSNR: " + str(PSNR / len(img_list)))
        print("SSIM: " + str(SSIM / len(img_list)))
        print('total_precison: ' + str(total_precision.mean()))
        print('total_recall" '+ str(total_recall.mean()))
        print('f-measure@0.95: ' + str(f[95 - 1]))

        f = open("result.txt", "a")
        f.write('%s_%s:\n' % (exp_name, args['snapshot']))
        f.write("MSE: " + str(MSE / len(img_list)) + "\n")
        f.write("PSNR: " + str(PSNR / len(img_list)) + "\n")
        f.write("SSIM: " + str(SSIM / len(img_list)) + "\n")
        f.write("total_precison: " + str(total_precision.mean()) + "\n")
        f.write("total_recall: "+ str(total_recall.mean()) + "\n")
        f.write("f-measure@0.95: " + str(f[95 - 1]) + "\n")

        f.close()

def parse_opt():
    parser = argparse.ArgumentParser()
    parser.add_argument('--exp_name', type=str, default='DGNLNet', help='model name')
    parser.add_argument('--root_input', type=str, default='dataset/sewer', help='input dir')
    parser.add_argument('--val', action='store_true', help='if val')
    parser.add_argument('--threshold', type=float, default=0.01, help='for dht')
    opt = parser.parse_args()
    return opt

if __name__ == '__main__':
    opt = parse_opt()
    print(opt.val, opt.exp_name)
    if opt.val:
        evaluate(opt.exp_name, opt.root_input, opt.threshold)
    else:
        predict(opt.exp_name, opt.root_input, opt.threshold)


"""
Data-Store Models
and a couple things to basically automatically create an API from a Model
"""
from google.appengine.ext import ndb
import datetime
import json
import logging

def university_key(name):
	return ndb.Key("University", name)

def course_id(dept, number):
	return dept+str(number)

def course_key(key_id):
	return ndb.Key("Course", key_id)

def can_cache_courses_key():
	"""Only one key for list of courses"""
	return ndb.Key("CanCache", 1)

class CanCache(ndb.Model):
	""" Super brilliant Idea: Lots of things will change very infrequently, so store the date it was last updated.
	If it wasn't updated, then list is cached client side.
	The benefit of this is in drastically reduces Data-Store Reads
	Reduce DB Reads => Save Money
	"""
	updated_at = ndb.DateTimeProperty(auto_now=True)

class University(ndb.Model):
	"""Model for College/Universities"""
	full_name = ndb.StringProperty(required=True)
	abbrev = ndb.StringProperty(required=True)
	city = ndb.StringProperty()
	state = ndb.StringProperty()

	courses = ndb.KeyProperty(repeated=True)

	# Date-Time Properties
	created_at = ndb.DateTimeProperty(auto_now_add=True)
	updated_at = ndb.DateTimeProperty(auto_now=True)

class Course(ndb.Model):
	"""Model for Courses"""
	department = ndb.StringProperty()
	number = ndb.IntegerProperty()
	name = ndb.StringProperty(required=True)

	ratings = ndb.KeyProperty(repeated=True)

	# List of emails so that user can only rate once
	raters = ndb.StringProperty(repeated=True)

	# Date-Time Properties
	created_at = ndb.DateTimeProperty(auto_now_add=True)
	updated_at = ndb.DateTimeProperty(auto_now=True)

class Rating(ndb.Model):
	"""Model for Ratings"""
	easiness = ndb.IntegerProperty(required=True)
	recommend = ndb.IntegerProperty(required=True)
	interesting = ndb.IntegerProperty(required=True)

	grade = ndb.IntegerProperty()

	professor = ndb.StringProperty()
	comment = ndb.StringProperty()
	book = ndb.StringProperty();

	user_email = ndb.StringProperty()

	# list of user's emails => safe hacking/trouble
	likes = ndb.StringProperty(repeated=True)
	dislikes = ndb.StringProperty(repeated=True)

	# Date-Time Properties
	created_at = ndb.DateTimeProperty(auto_now_add=True)
	updated_at = ndb.DateTimeProperty(auto_now=True)

def encode_to_dict(obj):
	"""Encode a data-store model to a dictionary"""
	result = {}

	for attr in dir(obj):
		if not attr.startswith("_") and not callable(getattr(obj,attr)):
			value = getattr(obj, attr)
			if isinstance(value, datetime.datetime):
				value = encode_date_time(value)
			elif isinstance(value, ndb.key.Key):
				value = dict(kind=value.kind(), id=value.id())
			result[attr] = value

	return result

def encode_date_time(dt_obj):
	result = {}

	# get attributes, but only the int ones
	for attr in dir(dt_obj):
		if not attr.startswith("_") and not callable(getattr(dt_obj, attr)):
			value = getattr(dt_obj, attr)
			if isinstance(value, int):
				result[attr] = value

	return result

def prepare_body(obj, key_method):
	"""Takes a decoded JSON object and prepares it for the data-store"""
	for key in obj:
		val = obj[key]
		if isinstance(val, dict):
			if val.get('kind'): # is a key
				val = key_method(kind=val['kind'], ID=val['id'], body=None)
			elif val.get('year'): # is a date-time
				val = datetime.datetime(**val)
	return obj

def API_GET(model_type, key_method, request, kind):
	"""One annoyance: for get: use key=id"""
	result_list = []

	if len(request.params) == 0: # no params, so return all stored objects -> "list mode"
		qry = model_type.query()
		for model in qry.iter():
				result_list.append(encode_to_dict(model))

	else:

		for param in request.params:
			if param == 'key':
				key = key_method(KIND=kind, ID=request.get("key"), BODY=None)
				result_list.append(encode_to_dict(key.get()))
			else:
				qry = model_type.query(getattr(model_type, param) == request.get(param))
				for model in qry.iter():
					result_list.append(encode_to_dict(model))

	#remove duplicates
	unique = []
	seen_id = {}
	for result in result_list:
		ID = result["key"]["id"]
		if not seen_id.get(ID):
			unique.append(result)
			seen_id[ID] = True

	return unique

def API_POST(model_type, key_method, request, kind):
	"""Return Success, Data
	Data is either an error message or the created key"""
	body = json.loads(request.body)

	#key = key_method(kind=kind, body=body, ID=None)

	#if key.get():
	#	return False, "Key already exists"
		# make new object in datastore
	body = prepare_body(obj=body, key_method=key_method)
	model = model_type(**body)

		#model.key = key
	model.put()

	return True, "key"

def API_PUT(model_type, key_method, request, kind):
	"""One pitfall: Whatever attribute defines the unique key CAN be changed by this method;
	these methods I'm creating put the responsibilty on the front end to ensure that
	bad things do not happen
	Return Success, MSg"""

	body = json.loads(request.body)

	if not body.get('key'):
		return False, "Required Arg Key not found"

	key = key_method(kind=body['key']['kind'], ID=body['key']['id'], body=None)

	model = key.get()

	if not model:
		return False, "Object Not Found in DB"
	else:
		del body['key']

		body = prepare_body(obj=body, key_method=key_method)

		for attr in body:
			setattr(model, attr, body[attr])

		model.put()

		return True, "Success"

def API_DELETE(model_type, key_method, request, kind):
	"Takes a 'key' in the query params"
	if request.get('key'):
		ID = request.get('key')

		key = key_method(kind=kind, ID=ID, body=None)

		key.delete()

		return True, "Successfully Deleted"
	else:
		return False, "Object not found"

"""For Now I'm not using Body"""
def Key_Method(kind, ID, body):
	if isinstance(ID, str):
		ID = int(str)
	if kind == 'Task':
		return ndb.Key('Task', ID)
	elif kind == 'Task_Entry':
		return ndb.Key('Task_Entry', ID)


import urllib.request
import urllib.parse
import http.cookiejar
import ssl
import re
#
# def hand(url,page):
#     url = url1 + str(page) + '.html'
#     headers={}
#     request = urllib.request.Request(url=url, headers=headers)
#     return  request

def get_text(a_herf):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'
    }
    request=urllib.request.Request(url=a_herf,headers=headers)
    #发送请求，获得内容
    response=urllib.request.urlopen(request).read().decode()
    pattern=re.compile(r'
(.*?)
',re.S)
    it=pattern.findall(response)
    #写一个正则将所有的图片去掉
    text=it[0]
    pat=re.compile(r'')
    text=pat.sub('',text)
   # exit()
    return text

def parse_content(content):
    pattern=re.compile(r'
(.*?)
',re.S)#转义一下.为\.
    #返回的格式是一个列表，包含多个元组，元祖的第一个元素正则表达式中第一项对应正则表达式中的第一个括号
    it=pattern.findall(content)
    #print(it)
    #遍历列表
    for href_title in it:
        #获取内容的链接
        a_herf='http://www.yikexun.cn'+href_title[0]
        title=href_title[1]
        print(a_herf)
        #向href发送请求，获取内容
        text=get_text(a_herf)
        #写入到文件里
        string='
%s
%s'%(title,text)
        with open ('lizhi.html','a',encoding='utf8') as fp: #爬每一页的时候，将内容追加到文件中#如果不设置encoding就是gdk
            fp.write(string)

ssl._create_default_https_context = ssl._create_unverified_context

headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'
    }
start_page=int(input('请输入起始页码'))
end_page=int(input('请输入结束页码'))
url1='http://www.yikexun.cn/jingdiangaoxiaoyulu/list_9_'
for page in range(start_page,end_page+1):
    url=url1+str(page)+'.html'
    #print(url)
    request=urllib.request.Request(url=url,headers=headers)
    content=urllib.request.urlopen(request).read().decode()
    #print(content)
    #hand(url,page)
    #解析内容
    parse_content(content)


import mysql.connector
from mysql.connector import errorcode
from database import config, DB_NAME, TABLES

def get_connection():
	cnx = mysql.connector.connect(**config)
	cursor = cnx.cursor()
	cursor.execute("USE {}".format(DB_NAME))

	result = {
		'connection' : cnx,
		'cursor' : cursor
	}
	return (result)

def	execute_sql(sql, data={}, return_id=False):
	conn = get_connection()
	cnx = conn['connection']
	cursor = conn['cursor']
	cursor.execute(sql, data)
	cnx.commit()
	last_id = cursor.lastrowid
	cursor.close()
	cnx.close()
	if (return_id):
		return (last_id)
	else:
		return (0)

def drop_table(table):
	sql = "DROP TABLE " + table
	execute_sql(sql)

#drop_table('users')
#drop_table('hashes')
#drop_table('tags')
#drop_table('tag_map')
#drop_table('messages')
#drop_table('views')


#!/usr/bin/python
# -*- coding: utf-8 -*-
""" handler for an openssl ca """
from __future__ import print_function
import os
import json
import base64
import uuid
import re
from OpenSSL import crypto
# pylint: disable=E0401
from acme.helper import load_config, build_pem_file, uts_now, uts_to_date_utc, b64_url_recode, cert_serial_get, convert_string_to_byte, convert_byte_to_string, csr_cn_get, csr_san_get

class CAhandler(object):
    """ CA  handler """

    def __init__(self, debug=None, logger=None):
        self.debug = debug
        self.logger = logger
        self.issuer_dict = {
            'issuing_ca_key' : None,
            'issuing_ca_cert' : None,
            'issuing_ca_crl'  : None,
        }
        self.ca_cert_chain_list = []
        self.cert_validity_days = 365
        self.openssl_conf = None
        self.cert_save_path = None
        self.save_cert_as_hex = False
        self.whitelist = []
        self.blacklist = []

    def __enter__(self):
        """ Makes ACMEHandler a Context Manager """
        if not self.issuer_dict['issuing_ca_key']:
            self._config_load()
        return self

    def __exit__(self, *args):
        """ cose the connection at the end of the context """

    def _ca_load(self):
        """ load ca key and cert """
        self.logger.debug('CAhandler._ca_load()')
        ca_key = None
        ca_cert = None
        # open key and cert
        if 'issuing_ca_key' in self.issuer_dict:
            if os.path.exists(self.issuer_dict['issuing_ca_key']):
                if 'passphrase' in self.issuer_dict:
                    with open(self.issuer_dict['issuing_ca_key'], 'r') as fso:
                        ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, fso.read(), convert_string_to_byte(self.issuer_dict['passphrase']))
                else:
                    with open(self.issuer_dict['issuing_ca_key'], 'r') as fso:
                        ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, fso.read())
        if 'issuing_ca_cert' in self.issuer_dict:
            if os.path.exists(self.issuer_dict['issuing_ca_cert']):
                with open(self.issuer_dict['issuing_ca_cert'], 'r') as fso:
                    ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, fso.read())
        self.logger.debug('CAhandler._ca_load() ended')
        return(ca_key, ca_cert)

    def _certificate_chain_verify(self, cert, ca_cert):
        """ verify certificate chain """
        self.logger.debug('CAhandler._certificate_chain_verify()')

        error = None
        pem_file = build_pem_file(self.logger, None, b64_url_recode(self.logger, cert), True)

        try:
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, pem_file)
        except BaseException as err_:
            cert = None
            error = err_

        if not error:
            #Create a certificate store and add ca cert(s)
            try:
                store = crypto.X509Store()
                store.add_cert(ca_cert)
            except BaseException:
                error = 'issuing certificate could not be added to trust-store'

            if not error:
                # add ca chain to truststore
                for cert_name in self.ca_cert_chain_list:
                    try:
                        with open(cert_name, 'r') as fso:
                            cain_cert = crypto.load_certificate(crypto.FILETYPE_PEM, fso.read())
                        store.add_cert(cain_cert)
                    except BaseException:
                        error = 'certificate {0} could not be added to trust store'.format(cert_name)

            if not error:
                # Create a certificate context using the store and the downloaded certificate
                store_ctx = crypto.X509StoreContext(store, cert)
                # Verify the certificate, returns None if it can validate the certificate
                try:
                    # pylint: disable=E1111
                    result = store_ctx.verify_certificate()
                except BaseException as err_:
                    result = str(err_)
            else:
                result = error
        else:
            result = 'certificate could not get parsed'

        self.logger.debug('CAhandler._certificate_chain_verify() ended with {0}'.format(result))
        return result

    def _certificate_extensions_add(self, cert_extension_dic, cert, ca_cert):
        """ verify certificate chain """
        self.logger.debug('CAhandler._certificate_extensions_add()')

        _tmp_list = []
        # add extensins from config file
        for extension in cert_extension_dic:
            self.logger.debug('adding extension: {0}: {1}: {2}'.format(extension, cert_extension_dic[extension]['critical'], cert_extension_dic[extension]['value']))
            if extension == 'subjectKeyIdentifier':
                self.logger.info('_certificate_extensions_add(): subjectKeyIdentifier')
                _tmp_list.append(crypto.X509Extension(convert_string_to_byte(extension), critical=cert_extension_dic[extension]['critical'], value=convert_string_to_byte(cert_extension_dic[extension]['value']), subject=cert))
            elif 'subject' in cert_extension_dic[extension]:
                self.logger.info('_certificate_extensions_add(): subject')
                _tmp_list.append(crypto.X509Extension(convert_string_to_byte(extension), critical=cert_extension_dic[extension]['critical'], value=convert_string_to_byte(cert_extension_dic[extension]['value']), subject=cert))
            elif 'issuer' in cert_extension_dic[extension]:
                self.logger.info('_certificate_extensions_add(): issuer')
                _tmp_list.append(crypto.X509Extension(convert_string_to_byte(extension), critical=cert_extension_dic[extension]['critical'], value=convert_string_to_byte(cert_extension_dic[extension]['value']), issuer=ca_cert))
            else:
                _tmp_list.append(crypto.X509Extension(type_name=convert_string_to_byte(extension), critical=cert_extension_dic[extension]['critical'], value=convert_string_to_byte(cert_extension_dic[extension]['value'])))

        self.logger.debug('CAhandler._certificate_extensions_add() ended')
        return _tmp_list

    def _certificate_extensions_load(self):
        """ verify certificate chain """
        self.logger.debug('CAhandler._certificate_extensions_load()')

        file_dic = dict(load_config(self.logger, None, self.openssl_conf))

        cert_extention_dic = {}
        if 'extensions' in file_dic:
            for extension in file_dic['extensions']:

                cert_extention_dic[extension] = {}
                parameters = file_dic['extensions'][extension].split(',')

                # set crititcal task if applicable
                if parameters[0] == 'critical':
                    cert_extention_dic[extension]['critical'] = bool(parameters.pop(0))
                else:
                    cert_extention_dic[extension]['critical'] = False

                # remove leading blank from first element
                parameters[0] = parameters[0].lstrip()

                # check if we have an issuer option (if so remove it and mark it as to be set)
                if 'issuer:' in parameters[-1]:
                    cert_extention_dic[extension]['issuer'] = bool(parameters.pop(-1))

                # check if we have an issuer option (if so remove it and mark it as to be set)
                if 'subject:' in parameters[-1]:
                    cert_extention_dic[extension]['subject'] = bool(parameters.pop(-1))

                # combine the remaining items and put them in as values
                cert_extention_dic[extension]['value'] = ','.join(parameters)

        self.logger.debug('CAhandler._certificate_extensions_load() ended')
        return cert_extention_dic

    def _certificate_store(self, cert):
        """ store certificate on disk """
        self.logger.debug('CAhandler._certificate_store()')
        serial = cert.get_serial_number()
        # save cert if needed
        if self.cert_save_path and self.cert_save_path is not None:
            # create cert-store dir if not existing
            if not os.path.isdir(self.cert_save_path):
                self.logger.debug('create certsavedir {0}'.format(self.cert_save_path))
                os.mkdir(self.cert_save_path)

            # determine filename
            if self.save_cert_as_hex:
                self.logger.info('convert serial to hex: {0}: {1}'.format(serial, '{:X}'.format(serial)))
                cert_file = '{:X}'.format(serial)
            else:
                cert_file = str(serial)
            with open('{0}/{1}.pem'.format(self.cert_save_path, cert_file), 'wb') as fso:
                fso.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
        else:
            self.logger.error('CAhandler._certificate_store() handler configuration incomplete: cert_save_path is missing')

        self.logger.debug('CAhandler._certificate_store() ended')

    def _config_check(self):
        """ check config for consitency """
        self.logger.debug('CAhandler._config_check()')
        error = None
        if 'issuing_ca_key' in self.issuer_dict and self.issuer_dict['issuing_ca_key']:
            if not os.path.exists(self.issuer_dict['issuing_ca_key']):
                error = 'issuing_ca_key {0} does not exist'.format(self.issuer_dict['issuing_ca_key'])
        else:
            error = 'issuing_ca_key not specfied in config_file'

        if not error:
            if 'issuing_ca_cert' in self.issuer_dict and self.issuer_dict['issuing_ca_cert']:
                if not os.path.exists(self.issuer_dict['issuing_ca_cert']):
                    error = 'issuing_ca_cert {0} does not exist'.format(self.issuer_dict['issuing_ca_cert'])
            else:
                error = 'issuing_ca_cert must be specified in config file'

        if not error:
            if 'issuing_ca_crl' in self.issuer_dict and self.issuer_dict['issuing_ca_crl']:
                if not os.path.exists(self.issuer_dict['issuing_ca_crl']):
                    error = 'issuing_ca_crl {0} does not exist'.format(self.issuer_dict['issuing_ca_crl'])
            else:
                error = 'issuing_ca_crl must be specified in config file'

        if not error:
            if self.cert_save_path:
                if not os.path.exists(self.cert_save_path):
                    error = 'cert_save_path {0} does not exist'.format(self.cert_save_path)
            else:
                error = 'cert_save_path must be specified in config file'

        if not error:
            if self.openssl_conf:
                if not os.path.exists(self.openssl_conf):
                    error = 'openssl_conf {0} does not exist'.format(self.openssl_conf)

        if not error and not self.ca_cert_chain_list:
            error = 'ca_cert_chain_list must be specified in config file'

        if error:
            self.logger.error('CAhandler config error: {0}'.format(error))

        self.logger.debug('CAhandler._config_check() ended'.format())
        return error

    def _config_load(self):
        """" load config from file """
        self.logger.debug('CAhandler._config_load()')
        config_dic = load_config(self.logger, 'CAhandler')

        if 'issuing_ca_key' in config_dic['CAhandler']:
            self.issuer_dict['issuing_ca_key'] = config_dic['CAhandler']['issuing_ca_key']
        if 'issuing_ca_cert' in config_dic['CAhandler']:
            self.issuer_dict['issuing_ca_cert'] = config_dic['CAhandler']['issuing_ca_cert']
        if 'issuing_ca_key_passphrase_variable' in config_dic['CAhandler']:
            try:
                self.issuer_dict['passphrase'] = os.environ[config_dic['CAhandler']['issuing_ca_key_passphrase_variable']]
            except BaseException as err:
                self.logger.error('CAhandler._config_load() could not load issuing_ca_key_passphrase_variable:{0}'.format(err))
        if 'issuing_ca_key_passphrase' in config_dic['CAhandler']:
            if 'passphrase' in self.issuer_dict and self.issuer_dict['passphrase']:
                self.logger.info('CAhandler._config_load() overwrite issuing_ca_key_passphrase_variable')
            self.issuer_dict['passphrase'] = config_dic['CAhandler']['issuing_ca_key_passphrase']
        if 'ca_cert_chain_list' in config_dic['CAhandler']:
            self.ca_cert_chain_list = json.loads(config_dic['CAhandler']['ca_cert_chain_list'])
        if 'cert_validity_days' in config_dic['CAhandler']:
            self.cert_validity_days = int(config_dic['CAhandler']['cert_validity_days'])
        if 'cert_save_path' in config_dic['CAhandler']:
            self.cert_save_path = config_dic['CAhandler']['cert_save_path']
        if 'issuing_ca_crl' in config_dic['CAhandler']:
            self.issuer_dict['issuing_ca_crl'] = config_dic['CAhandler']['issuing_ca_crl']
        # convert passphrase
        if 'passphrase' in self.issuer_dict:
            self.issuer_dict['passphrase'] = self.issuer_dict['passphrase'].encode('ascii')
        if 'openssl_conf' in config_dic['CAhandler']:
            self.openssl_conf = config_dic['CAhandler']['openssl_conf']
        if 'whitelist' in config_dic['CAhandler']:
            self.whitelist = json.loads(config_dic['CAhandler']['whitelist'])
        if 'blacklist' in config_dic['CAhandler']:
            self.blacklist = json.loads(config_dic['CAhandler']['blacklist'])
        self.save_cert_as_hex = config_dic.getboolean('CAhandler', 'save_cert_as_hex', fallback=False)
        self.logger.debug('CAhandler._config_load() ended')

    def _crl_check(self, crl, serial):
        """ check if CRL already contains serial """
        self.logger.debug('CAhandler._crl_check()')
        sn_match = False

        # convert to lower case
        if isinstance(serial, str):
            serial = serial.lower()

        serial = convert_string_to_byte(serial)
        if crl and serial:
            crl_list = crl.get_revoked()
            if crl_list:
                for rev in crl_list:
                    if serial == rev.get_serial().lower():
                        sn_match = True
                        break
        self.logger.debug('CAhandler._crl_check() with:{0}'.format(sn_match))
        return sn_match

    def _csr_check(self, csr):
        """ check CSR against definied whitelists """
        self.logger.debug('CAhandler._csr_check()')

        if self.whitelist or self.blacklist:
            result = False
            # get sans and build a list
            _san_list = csr_san_get(self.logger, csr)

            san_list = []
            check_list = []

            for san in _san_list:
                try:
                    # SAN list must be modified/filtered)
                    (_san_type, san_value) = san.lower().split(':')
                    san_list.append(san_value)
                except BaseException:
                    # force check to fail as something went wrong during parsing
                    check_list.append(False)
                    self.logger.debug('san_list parsing failed at entry: {0}'.format(san))

            # get common name and atttach it to san_list
            cn_ = csr_cn_get(self.logger, csr)
            if cn_:
                cn_ = cn_.lower()
                if cn_ not in san_list:
                    # append cn to san_list
                    self.logger.debug('append cn to san_list')
                    san_list.append(cn_)

            # go over the san list and check each entry
            for san in san_list:
                check_list.append(self._string_wlbl_check(san, self.whitelist, self.blacklist))

            if check_list:
                # cover a cornercase with empty checklist (no san, no cn)
                if False in check_list:
                    result = False
                else:
                    result = True

        else:
            result = True

        self.logger.debug('CAhandler._csr_check() ended with: {0}'.format(result))
        return result

    def _list_check(self, entry, list_, toggle=False):
        """ check string against list """
        self.logger.debug('CAhandler._list_check({0}:{1})'.format(entry, toggle))
        self.logger.debug('check against list: {0}'.format(list_))

        # default setting
        check_result = False

        if entry:
            if list_:
                for regex in list_:
                    regex_compiled = re.compile(regex)
                    if bool(regex_compiled.search(entry)):
                        # parameter is in set flag accordingly and stop loop
                        check_result = True
            else:
                # empty list, flip parameter to make the check successful
                check_result = True

        if toggle:
            # toggle result if this is a blacklist
            check_result = not check_result

        self.logger.debug('CAhandler._list_check() ended with: {0}'.format(check_result))
        return check_result

    def _pemcertchain_generate(self, ee_cert, issuer_cert):
        """ build pem chain """
        self.logger.debug('CAhandler._pemcertchain_generate()')

        if issuer_cert:
            pem_chain = '{0}{1}'.format(ee_cert, issuer_cert)
        else:
            pem_chain = ee_cert
        for cert in self.ca_cert_chain_list:
            if os.path.exists(cert):
                with open(cert, 'r') as fso:
                    cert_pem = fso.read()
                pem_chain = '{0}{1}'.format(pem_chain, cert_pem)

        self.logger.debug('CAhandler._pemcertchain_generate() ended')
        return pem_chain

    def _string_wlbl_check(self, entry, white_list, black_list):
        """ check single against whitelist and blacklist """
        self.logger.debug('CAhandler._string_wlbl_check({0})'.format(entry))

        # default setting
        chk_result = False

        # check if entry is in white_list
        wl_check = self._list_check(entry, white_list)
        if wl_check:
            self.logger.debug('{0} in white_list'.format(entry))
            if black_list:
                # we need to check blacklist if there is a blacklist and wl check passed
                if self._list_check(entry, black_list):
                    self.logger.debug('{0} in black_list'.format(entry))
                else:
                    self.logger.debug('{0} not in black_list'.format(entry))
                    chk_result = True
            else:
                chk_result = wl_check
        else:
            self.logger.debug('{0} not in white_list'.format(entry))

        self.logger.debug('CAhandler._string_wlbl_check({0}) ended with: {1}'.format(entry, chk_result))
        return chk_result

    def enroll(self, csr):
        """ enroll certificate """
        self.logger.debug('CAhandler.enroll()')

        cert_bundle = None
        cert_raw = None

        error = self._config_check()

        if not error:
            try:
                # check CN and SAN against black/whitlist
                result = self._csr_check(csr)

                if result:
                    # prepare the CSR
                    csr = build_pem_file(self.logger, None, b64_url_recode(self.logger, csr), None, True)

                    # load ca cert and key
                    (ca_key, ca_cert) = self._ca_load()

                    # load certificate_profile (if applicable)
                    if self.openssl_conf:
                        cert_extension_dic = self._certificate_extensions_load()
                    else:
                        cert_extension_dic = []

                    # creating a rest form CSR
                    req = crypto.load_certificate_request(crypto.FILETYPE_PEM, csr)
                    # sign csr
                    cert = crypto.X509()
                    cert.gmtime_adj_notBefore(0)
                    cert.gmtime_adj_notAfter(self.cert_validity_days * 86400)
                    cert.set_issuer(ca_cert.get_subject())
                    cert.set_subject(req.get_subject())
                    cert.set_pubkey(req.get_pubkey())
                    cert.set_serial_number(uuid.uuid4().int)
                    cert.set_version(2)
                    cert.add_extensions(req.get_extensions())

                    default_extension_list = [
                        crypto.X509Extension(convert_string_to_byte('subjectKeyIdentifier'), False, convert_string_to_byte('hash'), subject=cert),
                        crypto.X509Extension(convert_string_to_byte('authorityKeyIdentifier'), False, convert_string_to_byte('keyid:always'), issuer=ca_cert),
                        crypto.X509Extension(convert_string_to_byte('basicConstraints'), True, convert_string_to_byte('CA:FALSE')),
                        crypto.X509Extension(convert_string_to_byte('extendedKeyUsage'), False, convert_string_to_byte('clientAuth,serverAuth')),
                    ]

                    if cert_extension_dic:
                        try:
                            cert.add_extensions(self._certificate_extensions_add(cert_extension_dic, cert, ca_cert))
                        except BaseException as err_:
                            self.logger.error('CAhandler.enroll() error while loading extensions form file. Use default set.\nerror: {0}'.format(err_))
                            cert.add_extensions(default_extension_list)
                    else:
                        # add keyUsage if it does not exist in CSR
                        ku_is_in = False
                        for ext in req.get_extensions():
                            if convert_byte_to_string(ext.get_short_name()) == 'keyUsage':
                                ku_is_in = True
                        if not ku_is_in:
                            default_extension_list.append(crypto.X509Extension(convert_string_to_byte('keyUsage'), True, convert_string_to_byte('digitalSignature,keyEncipherment')))

                        # add default extensions
                        cert.add_extensions(default_extension_list)

                    cert.sign(ca_key, 'sha256')

                    # store certifiate
                    self._certificate_store(cert)
                    # create bundle and raw cert
                    cert_bundle = self._pemcertchain_generate(convert_byte_to_string(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)), open(self.issuer_dict['issuing_ca_cert']).read())
                    cert_raw = convert_byte_to_string(base64.b64encode(crypto.dump_certificate(crypto.FILETYPE_ASN1, cert)))
                else:
                    error = 'urn:ietf:params:acme:badCSR'

            except BaseException as err:
                self.logger.error('CAhandler.enroll() error: {0}'.format(err))
                error = 'Unknown exception'

        self.logger.debug('CAhandler.enroll() ended')
        return(error, cert_bundle, cert_raw, None)

    def poll(self, _cert_name, poll_identifier, _csr):
        """ poll status of pending CSR and download certificates """
        self.logger.debug('CAhandler.poll()')

        error = 'Method not implemented.'
        cert_bundle = None
        cert_raw = None
        rejected = False

        self.logger.debug('CAhandler.poll() ended')
        return(error, cert_bundle, cert_raw, poll_identifier, rejected)

    def revoke(self, cert, rev_reason='unspecified', rev_date=None):
        """ revoke certificate """
        self.logger.debug('CAhandler.revoke({0}: {1})'.format(rev_reason, rev_date))
        code = None
        message = None
        detail = None

        # overwrite revocation date - we ignore what has been submitted
        rev_date = uts_to_date_utc(uts_now(), '%y%m%d%H%M%SZ')

        if 'issuing_ca_crl' in self.issuer_dict and self.issuer_dict['issuing_ca_crl']:
            # load ca cert and key
            (ca_key, ca_cert) = self._ca_load()
            # turn of chain_check due to issues in pyopenssl (check is not working if key-usage is set)
            # result = self._certificate_chain_verify(cert, ca_cert)
            result = None
            # proceed if the cert and ca-cert belong together
            # if not result:
            serial = cert_serial_get(self.logger, cert)
            # serial = serial.replace('0x', '')
            if ca_key and ca_cert and serial:
                serial = hex(serial).replace('0x', '')
                if os.path.exists(self.issuer_dict['issuing_ca_crl']):
                    # existing CRL
                    with open(self.issuer_dict['issuing_ca_crl'], 'r') as fso:
                        crl = crypto.load_crl(crypto.FILETYPE_PEM, fso.read())
                    # check CRL already contains serial
                    sn_match = self._crl_check(crl, serial)
                else:
                    # new CRL
                    crl = crypto.CRL()
                    sn_match = None

                # this is the revocation operation
                if not sn_match:
                    revoked = crypto.Revoked()
                    revoked.set_reason(convert_string_to_byte(rev_reason))
                    revoked.set_serial(convert_string_to_byte(serial))
                    revoked.set_rev_date(convert_string_to_byte(rev_date))
                    crl.add_revoked(revoked)
                    # save CRL
                    crl_text = crl.export(ca_cert, ca_key, crypto.FILETYPE_PEM, 7, convert_string_to_byte('sha256'))
                    with open(self.issuer_dict['issuing_ca_crl'], 'wb') as fso:
                        fso.write(crl_text)
                    code = 200
                else:
                    code = 400
                    message = 'urn:ietf:params:acme:error:alreadyRevoked'
                    detail = 'Certificate has already been revoked'
            else:
                code = 400
                message = 'urn:ietf:params:acme:error:serverInternal'
                detail = 'configuration error'
            #else:
            #    code = 400
            #    message = 'urn:ietf:params:acme:error:serverInternal'
            #    detail = result
        else:
            code = 400
            message = 'urn:ietf:params:acme:error:serverInternal'
            detail = 'Unsupported operation'

        self.logger.debug('CAhandler.revoke() ended')
        return(code, message, detail)

    def trigger(self, _payload):
        """ process trigger message and return certificate """
        self.logger.debug('CAhandler.trigger()')

        error = 'Method not implemented.'
        cert_bundle = None
        cert_raw = None

        self.logger.debug('CAhandler.trigger() ended with error: {0}'.format(error))
        return (error, cert_bundle, cert_raw)


import datetime
from django.shortcuts import render, redirect
from .models import Request, Review
from .forms import AddRequest, AddUserForm
from django.contrib.auth.decorators import permission_required
from .forms import RegistrForm
from django.contrib.auth.decorators import login_required

# Create your views here.
def home(request):
    return render(request, 'home.html')

def add_request(request):

    if request.method == 'POST':

        form = AddRequest(request.POST, request.FILES)

        if form.is_valid():
            new_request = Request()
            new_request.date = datetime.datetime.now()
            new_request.name = form.cleaned_data['name']
            new_request.surname = form.cleaned_data['surname']
            new_request.email = form.cleaned_data['email']
            new_request.company = form.cleaned_data['company']
            new_request.message = form.cleaned_data['message']
            new_request.save()
            return redirect('message_success')

    elif request.method == "GET":
        form = AddRequest()

    return render(request, 'add_request.html', {'form': form})

def message(request):
    success = Request.objects.last
    viewed_message = request.session.get("viewed_message",[])
    return render(request, 'message_success.html', {'message':success})

@permission_required('cargo.add_review')
def add_review(request):

    if request.method == 'POST':
        new_form = AddUserForm(request.POST, request.FILES)
        if new_form.is_valid():
            review = new_form.save(commit=False)
            review.date = datetime.datetime.now()
            review.save()
            new_form.save_m2m()

            return redirect('reviews')

    elif request.method == "GET":
        new_form = AddUserForm()

    return render(request, 'add_review.html', {'new_form': new_form})

def reviews(request):
    all_reviews = Review.objects.all().order_by('-date')
    viewed_reviews = request.session.get("viewed_reviews", [])
    return render(request, 'reviews.html', {'all_reviews':  all_reviews, 'viewed_reviews': viewed_reviews})

def review(request, id):
    try:
        review = Review.objects.get(id=id)
        viewed_reviews = request.session.get("viewed_reviews", [])
        if id not in viewed_reviews:
            viewed_reviews.append(id)
        request.session['viewed_reviews'] = viewed_reviews
    except:
        review = ""
    return render(request, 'review.html', {'review': review})

# def message2(request):
#     success = Review.objects.all
#     viewed_message = request.session.get("message2",[])
#     return render(request, 'message.html', {'message': success })

def regist(request):
    # Массив для передачи данных шаблонны
    data = {}
    # Проверка что есть запрос POST
    if request.method == 'POST':
        # Создаём форму
        form = RegistrForm(request.POST)
        # Валидация данных из формы
        if form.is_valid():
            # Сохраняем пользователя
            form.save()

            # Передача формы к рендару
            data['form'] = form
            # Передача надписи, если прошло всё успешно
            data['res'] = "Всё прошло успешно"
            # Рендаринг страницы
            return render(request, 'registration/register_done.html', data)
    else: # Иначе
        # Создаём форму
        form = RegistrForm()
        # Передаём форму для рендеринга
        data['form'] = form
        # Рендаринг страницы
    return render(request, 'registration/register.html', data)

# def reviews(request):
#     all_reviews = Review.objects.all()
#     viewed_reviews = request.session.get("viewed_reviews", [])
#     return render(request, 'reviews.html', {' reviews':  all_reviews})
#
#                   # , 'viewed_reviews': viewed_reviews})
#
# def review(request, id):
#     try:
#         review = Review.objects.get(id=id)
#         viewed_reviews = request.session.get("viewed_reviews", [])
#         if id not in viewed_reviews:
#             viewed_reviews.append(id)
#         request.session['viewed_reviews'] = viewed_reviews
#     except:
#         review = ""
#     return render(request, 'review.html', {'review': review})


from unittest import TestCase, main
from student.project.student import Student

class TestStudent(TestCase):
    NAME = "Username"

    def setUp(self) -> None:
        self.student = Student(self.NAME)

# Test Init Method
    def test__student_init_without_courses__should_create_obj_without_courses(self):
        self.assertEqual(self.NAME, self.student.name)
        self.assertEqual({}, self.student.courses)

    def test__student_init_wit_courses__should_create_obj_with_courses(self):
        course_name = "Python OOP"
        courses = {course_name: ['note1', 'note2']}

        student = Student(self.NAME, courses)

        self.assertEqual(self.NAME, self.student.name)
        self.assertEqual(courses, student.courses)

# Test Enroll Method
    def test__student_enroll__when_course_is_already_enrolled__should_update_course_notes(self):
        course_name = "Python"
        courses = {course_name: ['note1', 'note2']}

        student = Student(self.NAME, courses)

        result = student.enroll(course_name, ['note3', 'note4'])

        self.assertEqual("Course already added. Notes have been updated.", result)
        self.assertEqual(['note1', 'note2', 'note3', 'note4'], student.courses[course_name])

    def test__student_enroll__without_course_notes__should_update_course_notes(self):
        course_name = "Python"
        course_notes = ['note1', 'note2']

        result = self.student.enroll(course_name, course_notes)

        self.assertEqual("Course and course notes have been added.", result)
        self.assertTrue(course_name in self.student.courses)
        self.assertEqual(course_notes, self.student.courses[course_name])

    def test__student_enroll__without_course_notes_Y__should_update_course_notes(self):
        course_name = "Python"
        course_notes = ['note1', 'note2']

        result = self.student.enroll(course_name, course_notes, "Y")

        self.assertEqual("Course and course notes have been added.", result)
        self.assertTrue(course_name in self.student.courses)
        self.assertEqual(course_notes, self.student.courses[course_name])

    def test__student_enroll__without_course_notes_when_invalid_add_course__should_add_course(self):
        course_name = "Python"
        course_notes = ['note1', 'note2']

        result = self.student.enroll(course_name, course_notes, "N")

        self.assertEqual("Course has been added.", result)
        self.assertTrue(course_name in self.student.courses)
        self.assertEqual([], self.student.courses[course_name])

# Test Add Notes Method
    def test__add_notes_with_not_existing_course__should_raise_error(self):
        with self.assertRaises(Exception) as error:
            self.student.add_notes("Python", "Note3")
        self.assertEqual("Cannot add notes. Course not found.", str(error.exception))

    def test__add_notes_with_existing_course__should_append_notes(self):
        course_name = "Python"
        courses = {course_name: ['note1', 'note2']}
        student = Student(self.NAME, courses)

        result = student.add_notes(course_name, 'note3')

        self.assertEqual("Notes have been updated", result)
        self.assertEqual(['note1', 'note2', 'note3'], student.courses[course_name])

    def test__leave_course_that_not_exist__should_rise_exception(self):
        self.student.enroll("Python", [])

        with self.assertRaises(Exception) as error:
            self.student.leave_course("Python OOP")
        self.assertEqual("Cannot remove course. Course not found.", str(error.exception))

    def test__leave_course_that_exist__should_remove_course(self):
        course_name = "Python"
        student = Student(self.NAME, {course_name: []})

        result = student.leave_course(course_name)
        self.assertEqual("Course has been removed", result)
        self.assertTrue(course_name not in student.courses)

if __name__ == '__main__':
    main()

Python Programming OOP/Ex_10_Testing/Exercise Resources/student/tests/test_student.py


# File: basic_pyre.py
#
# This file contains the basic regex tests run on the
# python translated regex expressions.
#

from org.transcrypt.stubs.browser import __pragma__
import re
from basictests import *

def run (test):
    """ basic tests of the re engine. The point is to
    exercise most of the methods to make sure they behave as
    expected. These tests are expected to provide exhaustive
    coverage of the regex engine.
    """
    checkFlagsExist(test)

    escapeTests(test)
    checkMatchProperties(test)
    checkRegexProperties(test)

    checkIgnoreCase(test)

    checkSearchWithGroups(test)
    checkMatchOps(test)
    checkMatchWithGroups(test)
    # checkMatchWithNamedGroups(test)           # !!! @JdeH temporarily disabled this
    checkFullMatchOps(test)
    checkFindAllOps(test)
    checkSplitOps(test)
    checkSubOps(test)
    checkSyntaxErrors(test)
    checkConditionalGroups(test)
    checkCommentGroup(test)
    checkWithFlags(test)

    checkFindIter(test)


from django.urls import path

from rooms.views.view_v1_amenity import AmenitiesListAPI, RoomAmenitiesAPI
from rooms.views.view_v1_room import (
    RoomCreateAPI,
    RoomCreatePhotosAPI,
    RoomDeleteAPI,
    RoomDetailAPI,
    RoomsListAPI,
    RoomUpdateAPI,
)

urlpatterns = [
    path("v1/list", RoomsListAPI.as_view()),
    path("v1/create", RoomCreateAPI.as_view()),
    path("v1/detail/<int:room_id>", RoomDetailAPI.as_view()),
    path("v1/update/<int:room_id>", RoomUpdateAPI.as_view()),
    path("v1/delete/<int:room_id>", RoomDeleteAPI.as_view()),
    path("v1/<int:room_id>/amenities", RoomAmenitiesAPI.as_view()),
    path("v1/<int:room_id>/photos", RoomCreatePhotosAPI.as_view()),
    path("v1/amenities/list", AmenitiesListAPI.as_view()),
]


from pandac.PandaModules import *
loadPrcFile('config/Config.prc')

from direct.showbase.ShowBase import ShowBase
import Globals
import ToontownLoader
from dna.DNAStorage import DNAStorage

class Window(ShowBase):

    def __init__(self):
        ShowBase.__init__(self)

        cbm = CullBinManager.getGlobalPtr()
        cbm.addBin('ground', CullBinManager.BTUnsorted, 18)
        cbm.addBin('shadow', CullBinManager.BTBackToFront, 19)
        cbm.addBin('gui-popup', CullBinManager.BTFixed, 60)

        camera.setPosHpr(0, 0, 0, 0, 0, 0)
        self.camLens.setMinFov(Globals.DefaultCameraFov / (4. / 3.))
        self.camLens.setNearFar(Globals.DefaultCameraNear, Globals.DefaultCameraFar)
        self.cam2d.node().setCameraMask(BitMask32.bit(1))

        # Keep VFS here to use files
        self.vfs = VirtualFileSystem.getGlobalPtr()
        for mount in Globals.mounts:
            self.vfs.mount("multifiles/" + mount, "/", 0)

        oldLoader = self.loader
        self.loader = ToontownLoader.ToontownLoader(self)
        __builtins__.loader = self.loader
        oldLoader.destroy()

        self.loadDnaStore()

        from hood.places.ToontownCentral import TTC
        self.ttc = TTC(None)
        self.ttc.load()
        self.ttc.startSky()

    def loadDnaStore(self):
        if not hasattr(self, 'dnaStore'):
            self.dnaStore = DNAStorage()

            self.loader.loadDNA('phase_4/dna/storage.xml').store(self.dnaStore)

            '''self.dnaStore.storeFont(Globals.getInterfaceFont(), 'humanist')
            self.dnaStore.storeFont(Globals.getSignFont(), 'mickey')
            self.dnaStore.storeFont(ToontownGlobals.getSuitFont(), 'suit')'''

            self.loader.loadDNA('phase_3.5/dna/storage_interior.xml').store(self.dnaStore)

    def setCurrentZone(self, zone):
        self.currentZone = zone

    def setLastPlayground(self, zone):
        self.lastPlayground = zone

T = Window()
T.run()


#!/usr/bin/python
#https://practice.geeksforgeeks.org/problems/common-subsequence/0

def sol(a, b):
    """
    Follows the standard DP approach of finding common subsequence.
    The common length can be >=1 so if we find a common character in both
    the strings, it does the job
    """
    m = len(a)
    n = len(b)
    dp = [[0 for _ in range(n+1)] for _ in range(m+1)]

    for i in range(1, m+1):
        for j in range(1, n+1):
            if a[i-1] == b[j-1]:
                dp[i][j] = 1 + dp[i-1][j-1]
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])
            if dp[i][j] >= 1:
                return 1
    return 0


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

from django.shortcuts import render
import datetime

# Create your views here.

def greetings_info(request):

    date = datetime.datetime.now()
    hours = datetime.datetime.now().strftime('%H')

    msg = 'Hello Guest very Good '

    if hours < 12 :
        msg = msg + " MORNING"

    elif hours < 16:
        msg = msg + " AFTERNOON"

    elif hours < 21:
        msg = msg + " EVENING"

    else:
        msg = msg+ " NIGHT"

    return render(request, 'displayapp/result.html', {'msg':msg,'date':date})


T = int(input())
for test_case in range(1, T + 1):
    N, M = map(int, input().split())
    flag = [list(input()) for _ in range(N)]
    ans = N * M     # 최대 N * M번 바꿔야 하므로 최솟값인 ans를 N * M으로 설정
    w_cnt = 0

    # 반복문으로 모든 경우의 수를 계산해서 최솟값을 찾는다.
    for w in range(N - 2):  # 흰색 먼저
        for i in range(M):
            if flag[w][i] != 'W':
                w_cnt += 1

        b_cnt = 0
        for b in range(w + 1, N - 1):   # 파란색
            for j in range(M):
                if flag[b][j] != 'B':
                    b_cnt += 1

            r_cnt = 0
            for r in range(b + 1, N):   # 빨간색
                for k in range(M):
                    if flag[r][k] != 'R':
                        r_cnt += 1

            cnt = w_cnt + b_cnt + r_cnt
            if ans > cnt:
                ans = cnt

    print(f'#{test_case} {ans}')


from typing import List

import os
import pathlib
import sys

import subprocess
import h5py
from machinable import Component
from neuroh5.io import read_population_names

def h5_copy_dataset(f_src, f_dst, dset_path):
    print(f"Copying {dset_path} from {f_src} to {f_dst} ...")
    target_path = str(pathlib.Path(dset_path).parent)
    f_src.copy(f_src[dset_path], f_dst[target_path])

class PrepareData(Component):
    def output_filepath(self, path: str = "cells") -> str:
        return self.local_directory(f"{path}.h5")

    def on_compute_predicate(self):
        def generate_uid(use):
            if getattr(use, "refreshed_at", None) is not None:
                return f"{use.uuid}-{use.refreshed_at}"
            return use.uuid

        return {
            "uses": sorted(
                map(
                    generate_uid,
                    self.uses,
                )
            )
        }

    def __call__(self):
        self.network = None
        self.spike_trains = None
        self.synapses = {}
        self.distance_connections = {}
        self.synapse_forest = {}
        for dependency in self.uses:
            if (
                dependency.module
                == "miv_simulator.interface.network_architecture"
            ):
                self.network = dependency
            elif (
                dependency.module
                == "miv_simulator.interface.legacy.derive_spike_trains"
            ):
                self.spike_trains = dependency
            elif dependency.module == "miv_simulator.interface.connections":
                populations = read_population_names(
                    dependency.config.forest_filepath
                )
                for p in populations:
                    if p in self.distance_connections:
                        # check for duplicates
                        raise ValueError(
                            f"Redundant distance connection specification for population {p}"
                            f"Found duplicate in {dependency.config.forest_filepath}, while already "
                            f"defined in {self.distance_connections[p].config.forest_filepath}"
                        )
                    self.distance_connections[p] = dependency
            elif dependency.module == "miv_simulator.interface.synapse_forest":
                if dependency.config.population in self.synapse_forest:
                    # check for duplicates
                    raise ValueError(
                        f"Redundant distance connection specification for population {dependency.config.population}"
                        f"Found duplicate in {dependency}, while already "
                        f"defined in {self.synapse_forest[dependency.config.population]}"
                    )
                self.synapse_forest[dependency.config.population] = dependency
            elif dependency.module == "miv_simulator.interface.synapses":
                if dependency.config.population in self.synapses:
                    # check for duplicates
                    raise ValueError(
                        f"Redundant specification for population {dependency.config.population}"
                        f"Found duplicate in {dependency}, while already "
                        f"defined in {self.synapses[dependency.config.population]}"
                    )
                self.synapses[dependency.config.population] = dependency

        print(f"Consolidating generated data files into unified H5")

        MiV_populations = ["PYR", "OLM", "PVBC", "STIM"]
        MiV_IN_populations = ["OLM", "PVBC"]
        MiV_EXT_populations = ["STIM"]

        print("Import H5Types")
        with h5py.File(self.output_filepath("cells"), "w") as f:
            input_file = h5py.File(self.network.config.filepath, "r")
            h5_copy_dataset(input_file, f, "/H5Types")
            input_file.close()

        print("Import coordinate entries")
        with h5py.File(self.output_filepath("cells"), "a") as f_dst:
            grp = f_dst.create_group("Populations")

            for p in MiV_populations:
                grp.create_group(p)

            for p in MiV_populations:
                coords_dset_path = f"/Populations/{p}/Generated Coordinates"
                coords_output_path = f"/Populations/{p}/Coordinates"
                distances_dset_path = f"/Populations/{p}/Arc Distances"
                with h5py.File(self.network.config.filepath, "r") as f_src:
                    h5_copy_dataset(f_src, f_dst, coords_dset_path)
                    h5_copy_dataset(f_src, f_dst, distances_dset_path)

        print("Create forest entries and synapse attributes")

        def _run(commands):
            cmd = " ".join(commands)
            print(cmd)
            subprocess.check_output(commands)

        for p in MiV_populations:
            if p not in ["OLM", "PVBC", "PYR"]:
                continue
            forest_file = self.synapse_forest[p].output_filepath
            synapses_file = self.synapses[p].output_filepath
            forest_syns_file = self.synapse_forest[p].output_filepath
            forest_dset_path = f"/Populations/{p}/Trees"
            forest_syns_dset_path = f"/Populations/{p}/Synapse Attributes"

            cmd = [
                "h5copy",
                "-p",
                "-s",
                forest_dset_path,
                "-d",
                forest_dset_path,
                "-i",
                forest_file,
                "-o",
                self.output_filepath(),
            ]
            _run(cmd)

            cmd = [
                "h5copy",
                "-p",
                "-s",
                forest_syns_dset_path,
                "-d",
                forest_syns_dset_path,
                "-i",
                synapses_file,
                "-o",
                self.output_filepath(),
            ]
            _run(cmd)

        print("Create vector stimulus entries")
        vecstim_file_dict = {"A Diag": self.spike_trains.output_filepath}

        vecstim_dict = {
            f"Input Spikes {stim_id}": stim_file
            for stim_id, stim_file in vecstim_file_dict.items()
        }
        for vecstim_ns, vecstim_file in vecstim_dict.items():
            for p in MiV_EXT_populations:
                vecstim_dset_path = f"/Populations/{p}/{vecstim_ns}"
                cmd = [
                    "h5copy",
                    "-p",
                    "-s",
                    vecstim_dset_path,
                    "-d",
                    vecstim_dset_path,
                    "-i",
                    vecstim_file,
                    "-o",
                    self.output_filepath(),
                ]
                _run(cmd)

        print("Copy coordinates for STIM cells")
        cmd = [
            "h5copy",
            "-p",
            "-s",
            "/Populations/STIM/Generated Coordinates",
            "-d",
            "/Populations/STIM/Coordinates",
            "-i",
            self.output_filepath(),
            "-o",
            self.output_filepath(),
        ]
        _run(cmd)

        with h5py.File(self.output_filepath("connections"), "w") as f:
            input_file = h5py.File(self.network.config.filepath, "r")
            h5_copy_dataset(input_file, f, "/H5Types")
            input_file.close()

        print("Create connectivity entries")
        for p, e in self.distance_connections.items():
            connectivity_file = e.output_filepath
            print(connectivity_file)
            projection_dset_path = f"/Projections/{p}"
            cmd = [
                "h5copy",
                "-p",
                "-s",
                projection_dset_path,
                "-d",
                projection_dset_path,
                "-i",
                connectivity_file,
                "-o",
                self.output_filepath("connections"),
            ]
            _run(cmd)