import scipy.stats as sts
import argparse
import pandas as pd
import glob

def ParseArguments():
    parser = argparse.ArgumentParser(description="Kolmogorov–Smirnov test")
    parser.add_argument('--input-file', default="generated_numbers.pkl", required=False, help='input file (default: %(default)s)')
    parser.add_argument('--input-dir', default="pickles_dir", required=False, help='input directory with .pkl files (default: %(default)s)')
    parser.add_argument('--pval-file', default="p-values.csv", required=False, help='output file with p-values (default: %(default)s)')
    args = parser.parse_args()

    return args.input_file, args.input_dir, args.pval_file

input_file, input_dir, pval_file = ParseArguments()

if input_dir=="":
    numbers_info = pd.read_pickle(input_file)
    M = int(numbers_info['Modulus'])
    numbers = numbers_info['numbers'] #liczby (pseudolosowe)
    numbers = list(map(lambda x: x/M, numbers)) #zamiana na liczby z przedziału (0 , 1)
    test = sts.kstest(numbers, cdf = 'uniform')

    print("Kolmogorov–Smirnov test results:")
    print("p-value: "+str(test[1]))
    print("Statistic: "+str(test[0]))
    print("PARAMETERS:")
    print("M: "+str(numbers_info['Modulus']))
    print("n: "+str(numbers_info['n']))
    print("Numbers have beed generated with: "+str(numbers_info['PRNG']))
    pvals = []
    pvals.append(test[1])
    print("Saving p-value to ",pval_file)
    df=pd.DataFrame(pvals,columns=["p-value"])
    df.to_csv(pval_file, index = False)
else:
    print("input_dir = ", input_dir)
    pvals = []
    file_list = list((glob.glob(input_dir + "/**.pkl")))
    file_list.sort()
    for file_name in file_list:
        print("Processing file ", file_name, " ...")
        numbers_info = pd.read_pickle(file_name)
        M=numbers_info['Modulus']
        numbers = numbers_info['numbers']
        numbers = list(map(lambda x: x/M, numbers)) #zamiana na liczby z przedziału (0 , 1)
        test = sts.kstest(numbers, cdf = 'uniform')
        pvals.append(test[1])

    print("Saving p-values to ",pval_file)
    df=pd.DataFrame(pvals,columns=["p-value"])
    df.to_csv(pval_file, index = False)


from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from ..models import Posts
from django.db.models import Q, Count

def index(request, category=None):
    page = request.GET.get('page', '1') # 페이지를 읽어온다. 없을경우 1을 뱉는다 ?page =
    kw = request.GET.get('kw', '') # 검색어

    if category == 'freeboard':
        posts_list = Posts.objects.filter(category_id=1).order_by('-create_date')
    elif category == 'diary':
        posts_list = Posts.objects.filter(category_id=2).order_by('-create_date')
    elif category == 'QnA':
        posts_list = Posts.objects.filter(category_id=3).order_by('-create_date')
    else:
        posts_list = Posts.objects.order_by('-create_date')

    if kw:
        posts_list = posts_list.filter( # icontains 대소문자 구분없음, 있음은 contains
            Q(subject__icontains=kw) | # 제목 검색
            Q(content__icontains=kw) | # 내용 검색
            Q(reply__content__icontains=kw) | # 댓글 내용
            Q(reply__author__username__icontains=kw) | # 댓글 작성자
            Q(author__username__icontains=kw) # 일기 작성자
        ).distinct() # 중복제거
    paginator = Paginator(posts_list, 10) # 한페이지에 보여줄 페이지 갯수 10
    page_obj = paginator.get_page(page) # 페이지 오브젝트에 담아서 보여줌
    context = {'category': category, 'posts_list': page_obj, 'page': page, 'kw': kw}

    return render(request, 'main/posts_list.html', context)

def detail(request, posts_id):
    posts = get_object_or_404(Posts, pk=posts_id)

    page = request.GET.get('page', '1')
    kw = request.GET.get('kw', 'first') # 정렬방법

    if kw == 'voter': # 추천순
        paginator = Paginator(posts.reply_set.all().annotate(num_votes=Count('voter')).order_by('-num_votes'), 10)
    elif kw == 'latest': # 최신순
        paginator = Paginator(posts.reply_set.all().order_by('-id'), 10)
    else: # 등록순
        paginator = Paginator(posts.reply_set.all(), 10)

    page_obj = paginator.get_page(page)

    context = {'posts': posts, 'reply_list': page_obj, 'page': page, 'kw': kw}
    return render(request, 'main/posts_detail.html', context)


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

import numpy as np
import pandas as pd
import random

# min-max 归一化
def normalization(data):
    _range = np.max(data) - np.min(data)
    return (data - np.min(data)) / _range

# 加载数据
def load_data(file_name):
    df = pd.read_csv(file_name)
    print('read csv data shape: ', df.shape)
    # features
    features = df.iloc[:, :-1].to_numpy()
    features = normalization(features)
    ones = np.ones(shape=features.shape[0])
    # np.c_按行链接矩阵
    features = np.c_[features, ones]
    print('features shape: ', features.shape)
    # labels
    labels = np.squeeze(df.iloc[:, -1:].to_numpy().reshape(1, -1))
    labels = normalization(labels)
    print('labels shape: ', labels.shape)
    return features, labels

# 批量读取数据
def data_iter(batch_size, X, y):
    num_examples = len(X)
    indices = list(range(num_examples))
    random.shuffle(indices)
    for i in range(0, num_examples, batch_size):
        batch_indices = indices[i:max(i+batch_size, num_examples)]
        yield X[batch_indices], y[batch_indices]

# sigmoid
def sigmoid(x):
    return 1.0 / (1.0 + np.exp(-x))

# 计算损失
def compute_loss(X, y, w):
    y_hat = sigmoid(np.dot(X, w))
    loss = -np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))
    loss /= len(X)
    return loss

# 计算梯度
def compute_gradient(X, y, w):
    grad = np.dot(X.T, sigmoid(np.dot(X, w)) - y)
    grad /= len(X)
    return grad

# 训练
def fit(X, y):
    print('fit start')
    # 初始化模型参数
    np.random.seed(1)
    w = np.random.rand(X.shape[1])
    print('init w: ', w)

    # 开始训练
    batch_size = 10
    learning_rate = 0.1
    iter_max = 10000
    for n_iter in range(1, iter_max+1):
        # compute loss
        loss = compute_loss(X, y, w)
        print(f'current loss: {loss}')
        if abs(loss) <= 1e-4:
            print(f'loss <= 1e-4, fit finish')
            break
        for (batch_X, batch_y) in data_iter(batch_size, X, y):
            grad = compute_gradient(batch_X, batch_y, w)
            w -= learning_rate * grad
    return w

# 预测
def predict(X, y, w):
    count = 0
    for index, x in enumerate(X):
        pred = sigmoid(np.dot(x, w))
        if y[index] == 1 and pred > 0.5:
            count += 1
        if y[index] == 0 and pred < 0.5:
            count += 1
    return 100 * count / len(X)

if __name__ == '__main__':
    X, y = load_data('data.csv')
    w = fit(X, y)
    print('w', w)
    X_test, y_test = load_data('test_data.csv')
    predict_result = predict(X_test, y_test, w)
    print(f'predict_result: {predict_result}%')


# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from oslo_utils import timeutils

from senlin.common import exception
from senlin.common import utils as common_utils
from senlin.engine import cluster_policy as cpm
from senlin.objects import cluster_policy as cpo
from senlin.tests.unit.common import base
from senlin.tests.unit.common import utils

CLUSTER_ID = '8d674833-6c0c-4e1c-928b-4bb3a4ebd4ae'
POLICY_ID = 'fa573870-fe44-42aa-84a9-08462f0e6999'
PROFILE_ID = '12abef70-ab31-484a-92aa-02388f0e6ccc'

class TestClusterPolicy(base.SenlinTestCase):

    def setUp(self):
        super(TestClusterPolicy, self).setUp()
        self.context = utils.dummy_context()

    def test_cluster_policy_init(self):
        values = {
            'priority': 12,
            'enabled': True,
        }
        cp = cpm.ClusterPolicy(CLUSTER_ID, POLICY_ID, **values)

        self.assertIsNone(cp.id)
        self.assertEqual(CLUSTER_ID, cp.cluster_id)
        self.assertEqual(POLICY_ID, cp.policy_id)
        self.assertEqual(12, cp.priority)
        self.assertTrue(cp.enabled)
        self.assertEqual({}, cp.data)
        self.assertIsNone(cp.last_op)
        self.assertEqual('', cp.cluster_name)
        self.assertEqual('', cp.policy_type)
        self.assertEqual('', cp.policy_name)

    def test_cluster_policy_store(self):
        utils.create_profile(self.context, PROFILE_ID)
        cluster = utils.create_cluster(self.context, CLUSTER_ID, PROFILE_ID)
        policy = utils.create_policy(self.context, POLICY_ID)
        values = {
            'priority': 12,
            'enabled': True,
        }
        cp = cpm.ClusterPolicy(cluster.id, policy.id, **values)
        self.assertIsNone(cp.id)
        cp_id = cp.store(self.context)
        self.assertIsNotNone(cp_id)

        result = cpo.ClusterPolicy.get(self.context, CLUSTER_ID, POLICY_ID)

        self.assertIsNotNone(result)
        self.assertEqual(12, result.priority)
        self.assertTrue(result.enabled)
        self.assertEqual({}, result.data)
        self.assertIsNone(result.last_op)

        # do an update
        cp.enabled = False
        cp.priority = 60
        cp.data = {'foo': 'bar'}
        timestamp = timeutils.utcnow(True)
        cp.last_op = timestamp

        new_id = cp.store(self.context)
        self.assertEqual(cp_id, new_id)

        result = cpo.ClusterPolicy.get(self.context, CLUSTER_ID, POLICY_ID)

        self.assertIsNotNone(result)
        self.assertFalse(result.enabled)
        self.assertEqual(60, result.priority)
        self.assertEqual({'foo': 'bar'}, result.data)
        self.assertEqual(common_utils.isotime(timestamp),
                         common_utils.isotime(result.last_op))

    def test_cluster_policy_load(self):
        ex = self.assertRaises(exception.PolicyNotAttached,
                               cpm.ClusterPolicy.load,
                               self.context, 'some-cluster', 'any-policy')
        self.assertEqual("The policy 'any-policy' is not attached to the "
                         "specified cluster 'some-cluster'.",
                         str(ex))

        utils.create_profile(self.context, PROFILE_ID)
        cluster = utils.create_cluster(self.context, CLUSTER_ID, PROFILE_ID)
        policy = utils.create_policy(self.context, POLICY_ID)

        values = {
            'priority': 12,
            'enabled': True,
        }
        cp = cpm.ClusterPolicy(cluster.id, policy.id, **values)
        cp_id = cp.store(self.context)

        result = cpm.ClusterPolicy.load(self.context, CLUSTER_ID, POLICY_ID)

        self.assertEqual(cp_id, result.id)
        self.assertEqual(cluster.id, result.cluster_id)
        self.assertEqual(policy.id, result.policy_id)
        self.assertTrue(result.enabled)
        self.assertEqual(12, result.priority)
        self.assertEqual({}, result.data)
        self.assertIsNone(result.last_op)
        self.assertEqual('test-cluster', result.cluster_name)
        self.assertEqual('senlin.policy.dummy-1.0', result.policy_type)
        self.assertEqual('test_policy', result.policy_name)

    def test_cluster_policy_to_dict(self):
        values = {
            'priority': 12,
            'enabled': True,
        }
        cp = cpm.ClusterPolicy(CLUSTER_ID, POLICY_ID, **values)
        self.assertIsNone(cp.id)
        expected = {
            'id': None,
            'cluster_id': CLUSTER_ID,
            'policy_id': POLICY_ID,
            'enabled': True,
            'data': {},
            'last_op': None,
            'cluster_name': '',
            'policy_type': '',
            'policy_name': '',
        }

        self.assertEqual(expected, cp.to_dict())


from typing import Text
import requests
import json
import pprint as pp
from datetime import datetime
import re

def get_suggestions(search_string: str):
    base_url = 'https://utility.arcgis.com/usrsvcs/servers/b89ba3a68c664268b9bdea76948b4f11/rest/services/World/GeocodeServer/suggest'
    query_data = {
        'f': 'json',
        'text': search_string,
        'maxSuggestions': 60,
        'countryCode': 'BRA'
    }
    req = requests.get(base_url, params=query_data)
    res = json.loads(req.content)

    valid_suggestions = list(filter(lambda x: 'Curitiba' in x['text'], res['suggestions']))

    return valid_suggestions

def find_adress_candidates(single_line: str):
    base_url = 'https://utility.arcgis.com/usrsvcs/servers/b89ba3a68c664268b9bdea76948b4f11/rest/services/World/GeocodeServer/findAddressCandidates'
    query_data = {
        'f': 'json',
        'outSR': json.dumps({
            'wkid': 102100
        }),
        'outFields': '*',
        'countryCode': 'BRA',
        'maxLocations': 6,
        'SingleLine': single_line
    }

    req = requests.get(base_url, params=query_data)
    res = json.loads(req.content)

    return res

def get_codope(geometry):
    base_url = 'https://services1.arcgis.com/46Oage49MS2a3O6A/arcgis/rest/services/Mapa_Rodizio_Abastecimento_RMC_View/FeatureServer/1/query'
    query_data = {
        'f': 'json',
        'returnGeometry': False,
        'geometryType': 'esriGeometryPoint',
        'outFields': '*',
        'geometry': json.dumps(geometry)
    }

    req = requests.get(base_url, params=query_data)
    res = json.loads(req.content)

    codope = res['features'][0]['attributes']['codope']

    return codope

def get_by_codope(codope: str):
    base_url = 'https://services1.arcgis.com/46Oage49MS2a3O6A/arcgis/rest/services/Mapa_Rodizio_Abastecimento_RMC_View/FeatureServer/2/query'
    query_data = {
        'f': 'json',
        'returnGeometry': False,
        'outFields': '*',
        'where': "(CODOPE = '{}')".format(codope)
    }

    req = requests.get(base_url, params=query_data)
    res = json.loads(req.content)

    return res

def print_time_stamps(query_data):
    data = query_data['features']
    for entry in data:
        entry = entry['attributes']
        ts_retomada = datetime.fromtimestamp(entry['RETOMADA'] / 1000)
        ts_norm = datetime.fromtimestamp(entry['NORMALIZACAO'] / 1000)
        ts_init = datetime.fromtimestamp(entry['INICIO'] / 1000)

        print('INICIO: {} / NORMALIZACAO: {} / RETOMADA: {}'.format(ts_init, ts_norm, ts_retomada))

if __name__ == '__main__':
    suggestions = get_suggestions(search_string='Jose Clementino Bettega')
    # pp.pprint(suggestions)

    single_line = suggestions[0]['text']
    res = find_adress_candidates(single_line=single_line)

    geometry = res['candidates'][0]['location']
    geometry['spatialReference'] = {
        'wkid': 102100
    }

    codope = get_codope(geometry)
    res = get_by_codope(codope)

    print('Results query by codope')
    pp.pprint(res)

    # print_time_stamps(res)
    print('CODOPE: {}'.format(codope))

    # pp.pprint(res)


class Solution(object):
    def getMinimumDifference(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        arr = []
        def helper(root):
            if not root:
                return
            arr.append(root.val)
            helper(root.left)
            helper(root.right)

        helper(root)
        arr.sort()
        minDiff = (arr[-1]-arr[0])
        for i in range(1, len(arr)):
            if arr[i] - arr[i-1] < minDiff:
                minDiff = arr[i] - arr[i-1]

        return minDiff

Python/Tree/Minimum Absolute Difference in BST.py


import torch
import torch.nn as nn
import torch.nn.functional as F
import logging
import collections
from util import compute_aggreeings, AverageMeter, get_mask, mask_tokens

def eval(model, val_loader, a2v, args, test=False):
    model.eval()
    count = 0
    metrics, counts = collections.defaultdict(int), collections.defaultdict(int)

    with torch.no_grad():
        if not args.mc:
            model.module._compute_answer_embedding(a2v)
        for i, batch in enumerate(val_loader):
            answer_id, answer, video, question = (
                batch["answer_id"],
                batch["answer"],
                batch["video"].cuda(),
                batch["question"].cuda(),
            )
            video_len = batch["video_len"]
            question_mask = (question > 0).float()
            video_mask = get_mask(video_len, video.size(1)).cuda()
            count += answer_id.size(0)

            if not args.mc:
                predicts = model(
                    video,
                    question,
                    text_mask=question_mask,
                    video_mask=video_mask,
                )
                topk = torch.topk(predicts, dim=1, k=10).indices.cpu()
                if args.dataset != "ivqa":
                    answer_id_expanded = answer_id.view(-1, 1).expand_as(topk)
                else:
                    answer_id = (answer_id / 2).clamp(max=1)
                    answer_id_expanded = answer_id
                metrics = compute_aggreeings(
                    topk,
                    answer_id_expanded,
                    [1, 10],
                    ["acc", "acc10"],
                    metrics,
                    ivqa=(args.dataset == "ivqa"),
                )
            else:
                fusion_proj, answer_proj = model(
                    video,
                    question,
                    text_mask=question_mask,
                    video_mask=video_mask,
                    answer=answer.cuda(),
                )
                fusion_proj = fusion_proj.unsqueeze(2)
                predicts = torch.bmm(answer_proj, fusion_proj).squeeze()
                predicted = torch.max(predicts, dim=1).indices.cpu()
                metrics["acc"] += (predicted == answer_id).sum().item()

    step = "val" if not test else "test"
    for k in metrics:
        v = metrics[k] / count
        logging.info(f"{step} {k}: {v:.2%}")

    return metrics["acc"] / count

def train(model, train_loader, a2v, optimizer, criterion, scheduler, epoch, args):
    model.train()
    running_vqa_loss, running_acc, running_mlm_loss = (
        AverageMeter(),
        AverageMeter(),
        AverageMeter(),
    )
    for i, batch in enumerate(train_loader):
        answer_id, answer, video, question = (
            batch["answer_id"],
            batch["answer"],
            batch["video"].cuda(),
            batch["question"].cuda(),
        )
        video_len = batch["video_len"]
        question_mask = (question > 0).float()
        video_mask = (
            get_mask(video_len, video.size(1)).cuda() if args.max_feats > 0 else None
        )
        N = answer_id.size(0)
        if not args.mc:
            model.module._compute_answer_embedding(a2v)
            predicts = model(
                video,
                question,
                text_mask=question_mask,
                video_mask=video_mask,
            )
        else:
            fusion_proj, answer_proj = model(
                video,
                question,
                text_mask=question_mask,
                video_mask=video_mask,
                answer=answer.cuda(),
            )
            fusion_proj = fusion_proj.unsqueeze(2)
            predicts = torch.bmm(answer_proj, fusion_proj).squeeze()

        if args.dataset == "ivqa":
            a = (answer_id / 2).clamp(max=1).cuda()
            vqa_loss = criterion(predicts, a)
            predicted = torch.max(predicts, dim=1).indices.cpu()
            predicted = F.one_hot(predicted, num_classes=len(a2v))
            running_acc.update((predicted * a.cpu()).sum().item() / N, N)
        else:
            vqa_loss = criterion(predicts, answer_id.cuda())
            predicted = torch.max(predicts, dim=1).indices.cpu()
            running_acc.update((predicted == answer_id).sum().item() / N, N)

        if args.mlm_prob:
            inputs = batch["question"]
            inputs, labels = mask_tokens(
                inputs, model.module.bert.bert_tokenizer, mlm_probability=0.15
            )
            mlm_loss = model(
                video,
                question=inputs.cuda(),
                labels=labels.cuda(),
                text_mask=question_mask,
                video_mask=video_mask,
                mode="mlm",
            )
            mlm_loss = mlm_loss.mean()
            loss = mlm_loss + vqa_loss
        else:
            loss = vqa_loss

        optimizer.zero_grad()
        loss.backward()
        if args.clip:
            nn.utils.clip_grad_norm_(model.parameters(), max_norm=args.clip)
        optimizer.step()
        scheduler.step()

        running_vqa_loss.update(vqa_loss.detach().cpu().item(), N)
        if args.mlm_prob:
            running_mlm_loss.update(mlm_loss.detach().cpu().item(), N)
        if (i + 1) % (len(train_loader) // args.freq_display) == 0:
            if args.mlm_prob:
                logging.info(
                    f"Epoch {epoch + 1}, Epoch status: {float(i + 1) / len(train_loader):.4f}, Training VideoQA loss: "
                    f"{running_vqa_loss.avg:.4f}, Training acc: {running_acc.avg:.2%}, Training MLM loss: {running_mlm_loss.avg:.4f}"
                )
            else:
                logging.info(
                    f"Epoch {epoch + 1}, Epoch status: {float(i + 1) / len(train_loader):.4f}, Training VideoQA loss: "
                    f"{running_vqa_loss.avg:.4f}, Training acc: {running_acc.avg:.2%}"
                )
            running_acc.reset()
            running_vqa_loss.reset()
            running_mlm_loss.reset()


import json

class Kasir:
    stokBarang = {}

    barangPembeli = {}

    def __init__(self):
        pass

    def simpanBeliJson(self):
        with open("beli.json", "w") as beliFileJson:
            json.dump(Kasir.barangPembeli, beliFileJson)

    def isiStok(self):
        with open("stok.json", "r") as stokReadJson:
            stokDict = json.load(stokReadJson)
            for key, value in stokDict.items():
                print("Barang :", key, "Harga:", value)

    def isiKranjang(self):
        print("Isi Belanjaan Anda: ")
        for key, value in Kasir.barangPembeli.items():
            print("BARANG \t:", key)
            for key2 in value:
                print(key2.upper(), "\t:", value[key2])

    def tambahStok(self):
        stokTrue = input("Apa Anda Belum Punya Database Stock?(y/t) ")
        keyStok = input("Masukkan Barang: ")
        valueStok = int(input("Masukkan Harga: "))
        if stokTrue.lower() == "y":
            Kasir.stokBarang.update({keyStok: valueStok})
            with open("stok.json", "w") as stokFileJson:
                json.dump(Kasir.stokBarang, stokFileJson)
                print("=== Database Stock Sudah diBuat!!!===")
        else:
            with open("stok.json", "r") as stokReadJson:
                stokDict = json.load(stokReadJson)
                if keyStok.lower() in stokDict.keys():
                    print("Barang Sudah Ada!!! \nTambahkan Barang Lain!!!")
                    Kasir.tambahStok(self)
                else:
                    stokDict.update({keyStok: valueStok})
                    with open("stok.json", "w") as stokFileJson:
                        json.dump(stokDict, stokFileJson)
                    print("=== Stock Berhasil Ditambahkan :) ===")

    def editStok(self):
        keyStokEdit = input("Masukkan Barang yang Dirubah: ")
        valueStokEdit = int(input("Masukkan Harga: "))
        with open("stok.json", "r") as stokReadJson:
            stokDict = json.load(stokReadJson)
            if keyStokEdit.lower() in stokDict.keys():
                stokDict.update({keyStokEdit: valueStokEdit})
                with open("stok.json", "w") as stokFileJson:
                    json.dump(stokDict, stokFileJson)
                print("=== Stock Berhasil DiRubah :) ===")
            else:
                print("===Stock Barang Tidak Ditemukan!!!===")
                print("===Edit Barang Yang Ada===!!!")
                Kasir.editStok(self)

    def hapusStok(self):
        keyStockHapus = input("Masukkan Nama Barang yang Dihapus: ")
        with open("stok.json", "r") as stokReadJson:
            stokDict = json.load(stokReadJson)
            if keyStockHapus.lower() in stokDict.keys():
                del stokDict[keyStockHapus]
                with open("stok.json", "w") as stokFileJson:
                    json.dump(stokDict, stokFileJson)
                print("=== Stock Berhasil Dihapus :) ===")
            else:
                print("===Stock Barang Tidak Ditemukan!!!===")
                print("===Hapus Barang Yang Ada===!!!")
                Kasir.hapusStok(self)

    def beliStock(self, keyStokBeli, jmlhStokBeli):
        with open("stok.json", "r") as stokReadJson:
            stokDict = json.load(stokReadJson)
            Kasir.barangPembeli.update(
                {keyStokBeli: {"jumlah": jmlhStokBeli, "harga": stokDict[keyStokBeli]}})
            print("===Belanja Ditambahkan Kekranjang===")
            Kasir.simpanBeliJson(self)

    def totalIsiKranjang(self):
        totalHarga = 0
        hargaKali = 0
        with open("beli.json", "r") as beliJson:
            stokDict = json.load(beliJson)
            for key, value in stokDict.items():
                harga = float(value["harga"])
                jumlah = int(value["jumlah"])
                hargaKali = harga * jumlah
                print(f"{key} \t: {harga} * {jumlah} = {hargaKali}")
                totalHarga += hargaKali
            print("Harga Total Barang: ", totalHarga)

    # testing fungstion

    def testTotalIsiKranjang(self):
        totalHarga = 0
        hargaKali = 0
        with open("beli.json", "r") as beliJson:
            stokDict = json.load(beliJson)
            for key, value in stokDict.items():
                harga = float(value["harga"])
                jumlah = int(value["jumlah"])
                hargaKali = harga * jumlah
                print(f"{key} \t: {harga} * {jumlah} = {hargaKali}")
                totalHarga += hargaKali
            return totalHarga

    def testIsiKranjang(self, cariVaribel):
        with open("beli.json", "r") as beliJson:
            stokDict = json.load(beliJson)
            if cariVaribel.lower() in stokDict.keys():
                return True
            else:
                return False

    def testIsiStok(self, cariVaribel):
        with open("stok.json", "r") as stokReadJson:
            stokDict = json.load(stokReadJson)
            if cariVaribel.lower() in stokDict.keys():
                return True
            else:
                return False


import glob
import argparse
import re
import os.path
import shutil
import sys
import tempfile
import itertools
import json

VALID_PROTOCOLS = ['git', 'ssh', 'http', 'https', 'ssh-colon', 'file', 'relative']
VERSION = '0.2.0'

parser = argparse.ArgumentParser(
        description = 'Recursively search directory for .git/config files and update all remote URIs',
        formatter_class = argparse.RawDescriptionHelpFormatter,
        epilog = '''
%(prog)s expects a JSON file containing search paramaters and a substitution
dictionary. A simple example:

{
  "search": {
     "hostname": "oldgit|oldgit.example.org",
     "path": "/+(?:var|srv)/+git"
   },
  "replace": {
    "hostname": "newgit.example.com",
    "username": "git",
    "protocol": "ssh-colon",
    "substitutions": {
      "oldproject1": "new/path/project1",
      "oldproject2": "oldproject2"
    }
  }
}

With this file search for .git/config files recursively and replace all
occurrences matching the provided search rules and replace the URLs.
.gitmodules can also be modified.

(Note that search.hostname and search.path are regular expressions, which have
to be escaped to be valid JSON. These expressions are part of a bigger
expression and must not contain anchors like '^' and '$'.)

%(prog)s provides several ways to test your rules before changing your files.
In all cases %(prog)s expects a JSON file as the first argument and one or
several files or directories. The files are expected to be .git/config files
(and/or .gitmodules files if --modules is given) and/or directories that will
be searched recursively for mentioned files.

%(prog)s --list-configs
  Simply list all the .git/config files found (with matching URIs inside)

%(prog)s --list-projects
  List all the project names matching the search criteria. If the project does
  not have a substitution rule, a warning will be issued.

%(prog)s --list-projects --list-categorised --show-new-path
  List all found projects, indented by config file name, along with the new
  name it will be substituted with (not the full URI, but the new path).

%(prog)s --dry-run
  Print the contents of all the files that would have been modified.

The resulting URI must be specified with hostname, username and protocol. All
of these can be overridden by the command line. When using the protocol
'relative' the hostname may be of the form '../..' and username is ignored.

TIP: Before changing .gitmodules files, it might be a good idea to run %(prog)s
--list-config --modules-only to get a list of the modified projects. This can
be handy for an automated script running 'git commit' of the changes later:
    %(prog)s --list-config config.json --modules-only my_path

This is done by the helper script 'list_affected_gitmodules.sh'. Another
script, commit_gitmodules_changes.sh, will add and commit all affected
.gitmodules files and push them to the remote 'origin'. The complete list of
actions for renaming all URIs in local .git/configs as well as updating all
submodules and committing and pushing the changes are as follows:
    # Do a dry run first:
    %(prog)s --modules --dry-run config.json my_paths
    # Store a list of the projects that will be changed and needs to be commited:
    /usr/share/doc/%(prog)s/scripts/list_affected_gitmodules.sh config.json my_paths > modified_projects
    # Replace URIs:
    %(prog)s --modules config.json my_paths
    # Add, commit and push changes to submodule URIs:
    /usr/share/doc/%(prog)s/scripts/commit_gitmodules_changes.sh modified_projects
        '''
        )
parser.add_argument('--list-configs', action = 'store_true', help = 'List all matching .git/config files and do nothing else')
parser.add_argument('--list-projects', action = 'store_true', help = 'List all projects found in all found .git/config files and do nothing else')
parser.add_argument('--show-new-path', const = ' → ', default = None, nargs = '?', help = 'When listing projects, also show their new paths, separated by a delimiter (default " → ")')
parser.add_argument('--list-categorised', action = 'store_true', help = 'When listing projects, print them indented under the config file they are found in')
parser.add_argument('--dry-run', '-d', action = 'store_true', help = 'Instead of substituting paths just print what would have been done (same as --list-projects --show-new-path --list-categorised')
parser.add_argument('--protocol', '-p', choices = VALID_PROTOCOLS, help = 'Protocol to use in the new URI, default ssh (overrides config)')
parser.add_argument('--username', '-u', help = 'Username to use in the new URI (overrides config)')
parser.add_argument('--modules', '-m', action = 'store_true', help = 'Replace/inspect URIs in .gitmodules files as well')
parser.add_argument('--modules-only', action = 'store_true', help = 'Replace/inspect URIs in .gitmodules files only')
parser.add_argument('--hostname', help = 'Hostname in the new URI (overrides config)')
parser.add_argument('--version', action='version', version='%(prog)s ' + VERSION)
parser.add_argument('config', help = 'JSON configuration file')
parser.add_argument('targets', nargs = '+', metavar = 'file|directory', help = 'One or several directories containing git projects, or one or several git project files, to be updated')

def printIfMatching(gitConfigFile):
    with open(gitConfigFile, 'r') as config:
        if regex.search(config.read()):
            print(gitConfigFile)

def listProjects(gitConfigFile, subst, categorise = False, showNew = None):
    if categorise:
        print(gitConfigFile, ':', sep='')

    with open(gitConfigFile, 'r') as config:
        for match in regex.finditer(config.read()):
            project = match.group('project')
            try:
                newName = subst[project]
            except KeyError :
                print('WARNING: The project "{0}" does not have a defined new path'.format(project), file = sys.stderr)
                continue

            if categorise:
                print('\t', end='')
            if showNew is not None:
                print('{0}{1}{2}'.format(project, showNew, newName))
            else:
                print(match.group('project'))

def replace(gitConfigFile, subst, host, proto, username = None, dryRun = False):
    if dryRun:
        print('In {0} the following would be the new contents:'.format(gitConfigFile))

    (_, tempFile) = tempfile.mkstemp()
    try:
        with open(gitConfigFile, 'r') as configOrig, open(tempFile, 'w') as temp:
            def replace(match):
                project = match.group('project')
                try:
                    newName = subst[project]
                except KeyError :
                    print('WARNING: The project "{0}" does not have a defined new path and will not be replaced'.format(project), file = sys.stderr)
                    if not dryRun:
                        temp.write(match.string)

                    return match.string

                user = username + '@' if username is not None else ''
                if proto == 'ssh-colon':
                    uri = '{user}{host}:{path}'.format(
                        user = user,
                        host = host,
                        path = newName
                        )
                elif proto == 'relative':
                    uri = '{host}/{path}'.format(
                            host = host,
                            path = newName
                            )
                else:
                    uri = '{proto}://{user}{host}/{path}'.format(
                        proto = proto,
                        user = user,
                        host = host,
                        path = newName
                        )

                return match.group('key') + uri

            result = regex.sub(lambda match: replace(match), configOrig.read())
            if dryRun:
                print(result)
            else:
                temp.write(result)

    except IOError as e:
        print('Failed to replace config / creating temporary file {}: {}'.format(e.filename, e.strerror), file = sys.stderr)
        try:
            os.remove(tempFile)
        except IOError:
            pass
    else:
        if not dryRun:
            shutil.move(tempFile, gitConfigFile)

def confFiles(path, includeGitModules = False, gitModulesOnly = False):
    if gitModulesOnly:
        return glob.iglob(target + '/**/.gitmodules', recursive = True)
    elif includeGitModules:
        return itertools.chain(
                glob.iglob(target + '/**/.git/config', recursive = True),
                glob.iglob(target + '/**/.git/modules/**/config', recursive = True),
                glob.iglob(target + '/**/.gitmodules', recursive = True)
                )
    else:
        return itertools.chain(
                glob.iglob(target + '/**/.git/config', recursive = True),
                glob.iglob(target + '/**/.git/modules/**/config', recursive = True)
                )

def validateJSONConfig(json):
    if 'protocol' in json['replace'] and json['replace']['protocol'] not in VALID_PROTOCOLS:
        raise ValueError('replace/protocol "{}" is invalid (valid protocols: {})'
                .format(json['replace']['protocol'], ', '.join(VALID_PROTOCOLS)))

    try:
        re.compile(json['search']['hostname'])
        if 'path' in json['search']:
            re.compile(json['search']['path'])
    except re.error as e:
        print('Config contains invalid regex "{}": {}'.format(e.pattern, e.msg), file = sys.stderr)

if __name__ == '__main__':
    args = parser.parse_args()

    with open(args.config) as confFile:
        json = json.load(confFile)

    validateJSONConfig(json)

    if 'path' in json['search']:
        # TODO: relative path is way to simplified:
        regex = re.compile("""
        ^(?P<key>\s*url\s*=\s*)
        (?:
        # Either an URI:
          (?:(file|ssh|git|http|https)://)?         # protocol, optional
          (?:[a-z_][a-z0-9_-]*[$]?@)??              # Linux username, followed by '@', optional
          (?:{hosts})                               # Accepted hostnames
          :?(?:{paths})                             # Common paths
        | # or a relative path
          \.\.)
        /+(?P<project>[^\.\n]+)                     # project name
        (?:\.git)??                                 # optionally followed by ".git"
        \s*$""".format(
            hosts = json['search']['hostname'],
            paths = json['search']['path']), re.MULTILINE | re.VERBOSE)
    else:
        regex = re.compile("""
        ^(?P<key>\s*url\s*=\s*)
        (?:(file|ssh|git|http|https)://)?           # protocol, optional
        (?:[a-z_][a-z0-9_-]*[$]?@)??                # Linux username, followed by '@', optional
        (?:{hosts})                                 # Accepted hostnames
        :?
        (?P<project>[^\.\n]+)                       # project path/name
        (?:\.git)??                                 # optionally followed by ".git"
        \s*$""".format(hosts = json['search']['hostname']), re.MULTILINE | re.VERBOSE)

    for target in args.targets:
        if os.path.isdir(target):
            for config in confFiles(target, args.modules, args.modules_only):
                if args.list_configs:
                    printIfMatching(config)
                elif args.list_projects:
                    listProjects(
                            config,
                            subst = json['replace']['substitutions'],
                            categorise = args.list_categorised,
                            showNew = args.show_new_path
                            )
                else:
                    replace(
                            config,
                            subst = json['replace']['substitutions'],
                            host = args.hostname if args.hostname else json['replace']['hostname'],
                            proto = args.protocol if args.protocol else json['replace']['protocol'],
                            username = args.username if args.username else json['replace'].get('username'),
                            dryRun = args.dry_run
                            )
        else:
            if args.list_configs:
                printIfMatching(target)
            elif args.list_projects:
                listProjects(
                        target,
                        subst = json['replace']['substitutions'],
                        categorise = args.list_categorised,
                        showNew = args.show_new_path
                        )
            else:
                    replace(
                            target,
                            subst = json['replace']['substitutions'],
                            host = args.hostname if args.hostname else json['replace']['hostname'],
                            proto = args.protocol if args.protocol else json['replace']['protocol'],
                            username = args.username if args.username else json['replace'].get('username'),
                            dryRun = args.dry_run
                            )


from datetime import datetime

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.core.serializers import serialize
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView, DeleteView, DetailView, ListView, UpdateView
from .models import MatsterApplication
from .forms import MasterForm
from Appartament.models import Appartament
from House.models import House
from User.models import User
# Create your views here.

class MasterList(ListView):
    model = MatsterApplication
    template_name = 'Master_application/master_list.html'
    queryset = MatsterApplication.objects.all()

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(MasterList, self).get_context_data(**kwargs)
        context['owners'] = User.objects.all()
        context['masters'] = User.objects.filter(role__user__isnull=False).distinct()
        return context

class MasterCreate(CreateView):
    form_class = MasterForm
    template_name = 'Master_application/master_create.html'
    success_url = reverse_lazy('master_list')

    def get_context_data(self, **kwargs):
        context = super(MasterCreate, self).get_context_data(**kwargs)
        return context

class MasterUpdate(UpdateView):
    form_class = MasterForm
    model = MatsterApplication
    template_name = 'Master_application/master_update.html'
    success_url = reverse_lazy('master_list')

    def get_context_data(self, **kwargs):
        context = super(MasterUpdate, self).get_context_data(**kwargs)
        return context

    def form_valid(self, form):
        return super().form_valid(form=form)

class MasterDetail(DetailView):
    model = MatsterApplication
    template_name = 'Master_application/master_detail.html'

class MasterDelete(DeleteView):
    model = MatsterApplication
    success_url = reverse_lazy('master_list')

    def get(self, request, *args, **kwags):
        return self.delete(self, request, *args, *kwags)

def filter_master_appartament(request):
    print(request.GET.get('owner_id'))
    if request.GET.get('owner_id') != '' or request.GET.get('owner_id') is not None:
        appartaments = serialize('json', Appartament.objects.filter(owner_id=request.GET.get('owner_id')))
        houses = serialize('json', House.objects.all())
        return JsonResponse({'appartaments': appartaments, 'houses': houses}, status=200)

def master_appartament_list(request):
    masters = MatsterApplication.objects.all()

    #Search
    search_master_num = request.GET.get('master_num')
    search_master_time = request.GET.get('master_time')
    search_master_type = request.GET.get('master_type')
    search_master_description = request.GET.get('master_description')
    search_master_flat = request.GET.get('master_flat')
    search_master_owner = request.GET.get('master_owner')
    search_master_phone = request.GET.get('master_phone')
    search_master_name = request.GET.get('master_name')
    search_master_status = request.GET.get('master_status')

    query = Q()

    if search_master_num:
        query &= Q(id__icontains=search_master_num)

    if search_master_time:
        start = datetime.strptime(search_master_time[0:10], '%d.%m.%Y').date()
        end = datetime.strptime(search_master_time[13:23], '%d.%m.%Y').date()
        print()
        print('date:', start, '+', end)
        print()
        query &= Q(date_master__gte=start.strftime('%Y-%m-%d'), date_master__lte=end.strftime('%Y-%m-%d'))

    if search_master_type:
        query &= Q(typeMaster__name=search_master_type)

    if search_master_description:
        query &= Q(description_problem__icontains=search_master_description)

    if search_master_flat:
        query &= Q(appartament__number_appartament__icontains=search_master_flat)

    if search_master_owner:
        query &= Q(ownerAppartament=search_master_owner)

    if search_master_phone:
        query &= Q(name_master__phone_number__icontains=search_master_phone)

    if search_master_name:
        query &= Q(name_master_id=search_master_name)

    if search_master_status:
        query &= Q(status=search_master_status)

    masters = masters.filter(query)

    start = int(request.GET.get('start', 0))
    length = int(request.GET.get('length', 10))

    paginator = Paginator(masters, length)
    masters = paginator.get_page(start // length + 1)

    data = []

    for master in masters:
        data.append({
            'id': master.id,
            'time': f'{master.date_master.strftime("%d.%m.%Y")}-{master.time_master.strftime("%H:%M")}',
            'type': master.typeMaster.name,
            'description': master.description_problem,
            'flat': master.appartament.number_appartament,
            'owner': master.ownerAppartament.get_full_name(),
            'phone': master.name_master.phone_number,
            'master': master.name_master.get_full_name(),
            'status': master.status
        })

    response = {
        'draw': request.GET.get('draw'),
        'recordsTotal': MatsterApplication.objects.all().count(),
        'recordsFiltered': masters.paginator.count,
        'data': data
    }

    return JsonResponse(response)


import sys
import os

#Caesar class:
#   variables: charToInt and intToChar
#   functions: getCharListFromFile(), writeToFile(), getIntListFromCharList(), getCharListFromIntList(), getWordListFromCharList(), encrypt(), decrypt(), bruteforce()
#   description: The Caesar class can encrypt and decrypt text from a file using a shift cipher. It also has multiple helper functions for the conversion of elements within a list.

class Caesar:
    def __init__(self):
        #Dictionary is used by getIntListFromCharList()
        #Note: notice that the uppercase and lowercase keys of the same letter pair to the same value; this is to allow either as usable input
        self.charToInt = {
            "a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7, "i": 8, "j": 9, "k": 10, "l": 11, "m": 12, "n": 13, "o": 14, "p": 15, "q": 16, "r": 17, "s": 18, "t": 19, "u": 20, "v": 21, "w": 22, "x": 23, "y": 24, "z": 25,
            "A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": 10, "L": 11, "M": 12, "N": 13, "O": 14, "P": 15, "Q": 16, "R": 17, "S": 18, "T": 19, "U": 20, "V": 21, "W": 22, "X": 23, "Y": 24, "Z": 25
        }

        #Dictionary is used by getCharListFromIntList()
        self.intToChar = {
            0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h", 8: "i", 9: "j", 10: "k", 11: "l", 12: "m", 13: "n", 14: "o", 15: "p", 16: "q", 17: "r", 18: "s", 19: "t", 20: "u", 21: "v", 22: "w", 23: "x", 24: "y", 25: "z"
        }

    #getCharListFromFile()
    #   parameters: filename
    #   returns: charList
    #   description: Function takes the name of a file as a string, reads from the file, and returns a list containing each char* sequentially read from the file
    #   * note: the "chars" are actually single character strings, here and anywhere else "char" is used in the naming of items in this code; ex: "s"
    def getCharListFromFile(self, filename):
        with open(filename, 'r') as f:
            temp = f.read()
        charList = list(temp)
        return charList

    #writeToFile()
    #   parameters: filename, charList
    #   returns: nothing
    #   description: Function takes the name to be used for writing a file and a list of chars, and sequentially writes all the chars from the list to a textfile.
    def writeToFile(self, filename, charList):
        with open(filename, 'w') as f:
            for x in charList:
                f.write(x)

    #getIntListFromCharList()
    #   parameters: charList
    #   returns: intList
    #   description: Function takes a list of chars, converts each char to a corresponding int value, and returns a list of the int values.
    #   note: Function ignores " ", "\n", and "\t" and appends them to the list of ints as they are.
    def getIntListFromCharList(self, charList):
        intList = []
        for x in charList:
            if x not in self.charToInt:
                intList.append(x)
            else:
                intList.append(self.charToInt[x])
        return intList

    #getCharListFromIntList()
    #   parameters: intList
    #   returns: charList
    #   description: Function takes a list of ints, converts each int to a corresponding char value, and returns a list of the char values.
    #   note: Function ignores " ", "\n", and "\t" and appends them to the list of ints as they are.
    def getCharListFromIntList(self, intList):
        charList = []
        for x in intList:
            if x not in self.intToChar:
                charList.append(x)
            else:
                charList.append(self.intToChar[x])
        return charList

    #encrypt()
    #   parameters: key, intList
    #   returns: encryptedList
    #   description: Function takes an int as a key value and a list of ints, shifts the values of the ints determined by the key value in the positive direction,
    #   and returns a list of the shifted ints.
    #   note: The mathematical function used for the shifting is "(x + key) % 26", where x is an int value inside intList
    def encrypt(self, key, intList):
        key = int(key)
        encryptedList = []
        for x in intList:
            if x not in self.intToChar:
                encryptedList.append(x)
            else:
                shifted_int = (x + key) % 26
                encryptedList.append(shifted_int)
        return encryptedList

    #decrypt()
    #   parameters: key, intList
    #   returns: decryptedList
    #   description: Function takes an int as a key value and a list of ints, shifts the values of the ints determined by the key value in the negative direction,
    #   and returns a list of the shifted ints.
    #   note: The mathematical function used for the shifting is "(x - key) % 26", where x is an int value inside intList
    def decrypt(self, key, intList):
        key = int(key)
        decryptedList = []
        for x in intList:
            if x not in self.intToChar:
                decryptedList.append(x)
            else:
                decrypted_int = (x - key) % 26
                decryptedList.append(decrypted_int)
        return decryptedList

    #getWordListFromCharList()
    #   parameters: charList
    #   returns: wordList
    #   description: Function take a list of chars, concatenates a string from the chars of the list, splits the string into strings that are whole words,
    #   and returns a list of those words.
    def getWordListFromCharList(self, charList):
        temp = ""
        for x in charList:
            temp += x
        wordList = temp.split()
        return wordList

    #bruteforce()
    #   parameters: intList, dictionaryList, threshold
    #   returns: possibleKeys
    #   description: Function takes a list of ints, a list of words from a dictionary file, and a float as a threshold value.
    #   It then calls decrypt() on the int list for each possible key value. Each result is then checked against a list of dictionary words.
    #   A counter is used to keep track of matches. A percentage of matches is calculated and if it is greater than or equal to the threshold value,
    #   its corresponding key is added to a list of possible keys. This list of possible keys is then returned.
    #   note: Function actually returns a list of tuples. Each tuple contains a possible key value and a list of words that are possibly decrypted.
    def bruteforce(self, intList, dictionaryList, threshold):
        decryptedList = []
        possibleKeys = []
        percent_found = 0.0

        for x in range(26):
            decryptedList = self.decrypt(x, intList)
            charList = self.getCharListFromIntList(decryptedList)
            wordList = self.getWordListFromCharList(charList)
            counter = 0
            for y in wordList:
                for z in dictionaryList:
                    if y == z:
                        counter += 1
            percent_found = float(counter) / float(len(wordList))
            if percent_found >= threshold:
                possibleKeyTuple = (x, percent_found, wordList)
                possibleKeys.append(possibleKeyTuple)
        return possibleKeys

#Argument_Handler class:
#   functions: doesFileExist(), isArgTextfile(), isArgInt(), isArgFlag()
#   description: Argument_Handler class is used for validation of command line arguments.

class Argument_Handler:
    #doesFileExist()
    #   parameters: argIndex
    #   returns: True or False
    #   description: Function takes an int that is the index of a command line argument passed during program execution.
    #   It then looks at the referenced argument to see if it is a file in the current directory and returns True or False accordingly.
    def doesFileExist(self, argIndex):
        if os.path.isfile(sys.argv[argIndex]) == False:
            print(sys.argv[argIndex] + " does not exist in the current directory.")
            return False
        else:
            return True

    #isArgTextfile()
    #   parameters: argIndex
    #   returns: True or False
    #   description: Function takes an int that is the index of a command line argument passed during program execution.
    #   It then looks at the referenced argument to see if it is a textfile with the .txt extension and returns True or False accordingly.
    def isArgTextfile(self, argIndex):
        filename_split = sys.argv[argIndex].split(".")
        try:
            if filename_split[1] != "txt":
                print("Both the input file and the output file for encrypting and decrypting must be text files and use the .txt extension.\n\tExample: secret_message.txt")
                return False
            else:
                return True
        except:
            print("Both the input file and the output file for encrypting and decrypting must be text files and use the .txt extension.\n\tExample: secret_message.txt")
            return False

    #isArgInt()
    #   parameters: argIndex
    #   returns: True or False
    #   description: Function takes an int that is the index of a command line argument passed during program execution.
    #   It then looks at the referenced argument to see if it is an int and returns True of False accordingly.
    def isArgInt(self, argIndex):
        try:
            key = int(sys.argv[argIndex])
            if type(key) is int:
                return True
            else:
                print("The key must be an integer.")
                return False
        except:
            print("The key must be an integer.")
            return False

    #isArgFlag()
    #   parameters: argIndex
    #   returns: True or False
    #   description: Function takes an int that is the index of a command line argument passed during program execution.
    #   It then looks at the referenced argument to see whether it is a special flag that designates whether the program should encrypt, decrypt, or bruteforce.
    #   The function returns True of False accordingly.
    #   The special flags are "-e", "-d", and "-c"
    def isArgFlag(self, argIndex):
        if (sys.argv[argIndex] == "-e") or (sys.argv[argIndex] == "-d") or (sys.argv[argIndex] == "-c"):
            return True
        else:
            print("The proper syntax is as follows:\n'python caesar.py -e input.txt key output.txt' to encrypt\n'python caesar.py -d input.txt key output.txt' to decrypt\n'python caesar.py -c input.txt' to bruteforce")
            return False

    #isArgsLengthValid()
    #   parameters: No Parameters
    #   returns: True or False
    #   description: Function checks the length of sys.argv. If the length is 3 or 5, it returns True.
    def isArgsLengthValid(self):
        if (len(sys.argv) == 3) or (len(sys.argv) == 5):
            return True
        else:
            print("The proper syntax is as follows:\n'python caesar.py -e input.txt key output.txt' to encrypt\n'python caesar.py -d input.txt key output.txt' to decrypt\n'python caesar.py -c input.txt' to bruteforce")
            return False

def main():
    caesar = Caesar()
    arg_handler = Argument_Handler()

    if arg_handler.isArgsLengthValid():
        if arg_handler.isArgFlag(1):
            if (sys.argv[1] == "-e") or (sys.argv[1] == "-d"):
                if (arg_handler.doesFileExist(2)) and (arg_handler.isArgTextfile(2)):
                    if arg_handler.isArgInt(3):
                        if arg_handler.isArgTextfile(4):
                            charList = caesar.getCharListFromFile(sys.argv[2])
                            intList = caesar.getIntListFromCharList(charList)
                            if sys.argv[1] == "-e":
                                encryptedList = caesar.encrypt(sys.argv[3], intList)
                                e_charList = caesar.getCharListFromIntList(encryptedList)
                                caesar.writeToFile(sys.argv[4], e_charList)
                            if sys.argv[1] == "-d":
                                decryptedList = caesar.decrypt(sys.argv[3], intList)
                                d_charList = caesar.getCharListFromIntList(decryptedList)
                                caesar.writeToFile(sys.argv[4], d_charList)
            if sys.argv[1] == "-c":
                if (arg_handler.doesFileExist(2)) and (arg_handler.isArgTextfile(2)):
                    charList = caesar.getCharListFromFile(sys.argv[2])
                    intList = caesar.getIntListFromCharList(charList)
                    charDictList = caesar.getCharListFromFile("dictionary")
                    dictionaryList = caesar.getWordListFromCharList(charDictList)
                    possibleKeys = caesar.bruteforce(intList, dictionaryList, 0.8) #Threshold value is set to 80%
                    print("########## Possible Keys ##########\n")
                    print("### Output Format: ('Key', 'Percent of Words Found in Dictionary', [Words Shifted Using Key]) ###\n")
                    for x in possibleKeys:
                        print(x)
                        print("\n")

main()


''' Task 3
Написати функцiю season, яка приймає один аргумент — номер мiсяця (вiд 1 до 12), яка буде
повертати пору року, якiй цей мiсяць належить (зима, весна, лiто або осiнь)'''

def season(num_month):
    dict_season = {(1,2,12):'Winter', (3,4,5):'Spring', (6,7,8):'Summer', (9,10,11):'Autumn'}
    for key in dict_season:
        for i in key:
            if i == num_month:
                print(dict_season.get(key))

season(11)


# -*- coding: utf-8 -*-
__doc__ == """
Simple view that exposes a REST API over HTTP
to retrieve the least of last read books from
a bookshelf.

To run it:

.. code-block:: python

   $ python last_read.py --topic mytopic --broker <BROKER_ADDR>:9092 --port 8080 --name lastread --id lastread1 --tags book last

This will listen for HTTP request on `127.0.0.1:8080`
and will return a JSON encoded list of book
documents.

The service will be automatically registered to the local consul
agent (assuming running localhost:8500) using the
name, id and tags provided

When the process is terminated, the service is deregistered
automatically.
"""
import asyncio
import json
import signal

from aiohttp import web

from discolib import register_service, deregister_service
from eventlib import consume_events, stop_consuming_events
from restlib import webserver, route_to_resource
from utils import get_cli_parser

# internal state
bookshelf = []
loop = asyncio.get_event_loop()

async def bookshelf_view(request):
    """
    View to see the current list of books
    in your bookshelf.
    """
    return web.Response(body=json.dumps(bookshelf).encode('utf-8'),
                        headers={"content-type": "application/json"})

async def event_handler(message):
    """
    Called whenever a new event was received from
    the event store.

    Simply store the event in a local state arena.
    """
    bookshelf.append(message.value.decode('utf-8'))

def run():
    """
    Entry point to this microservice.
    """
    args = get_cli_parser().parse_args()

    # schedule the internal event consumer
    # that will run until we terminate this service
    asyncio.ensure_future(consume_events(topic=args.topic.encode('utf-8'),
                                         group=args.group,
                                         addr=args.broker,
                                         callback=event_handler))

    # let's start the REST server that will
    # serve the view's resource
    srv = loop.run_until_complete(webserver(args.addr, args.port))
    loop.run_until_complete(route_to_resource(bookshelf_view))

    # finally, let's advertize this service
    # to the rest of the world
    svc = loop.run_until_complete(register_service(
            id=args.id,
            name=args.name,
            port=args.port,
            address=args.addr,
            tags=args.tags
        )
    )

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        loop.run_until_complete(deregister_service(svc))
        loop.run_until_complete(stop_consuming_events())

        srv.close()
        loop.run_until_complete(srv.wait_closed())
        # give the time for remaining requests to complete
        loop.run_until_complete(asyncio.sleep(2))

    loop.close()

if __name__ == '__main__':  # pragma: no cover
    run()


import math
import random
import pygame
import sys
from pygame.locals import *
from copy import deepcopy

pygame.init()
pygame.mixer.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
player1keys = [False, False, False, False]
player2keys = [False, False, False, False]
player1pos = [0] #Min: 0 Max: 2130
player2pos = [[615, 150, 3]]
ballpos = [300, 300]
ballvel = [-1, 1]
for num in range(0, 6):
    player1pos.append(player1pos[num] + 17)
    player2pos.append([player2pos[num][0], player2pos[num][1] - 17, 3])
UP, LEFT, DOWN, RIGHT = 0, 1, 2, 3
xMAX, yMAX, xMIN, yMIN = 614, 451, 0, 0
posMIN, posMAX = 0, 2130
hasBounced = False

player1 = pygame.image.load("sprites/player1.png")
player2 = pygame.image.load("sprites/player2.png")
ball = pygame.image.load("sprites/ball.png")

running = 1
exitcode = 0
while running:
    screen.fill(0)

    for box in player1pos:
        if(box <= xMAX):
            screen.blit(player1, [box + 1, yMIN + 1])
        elif(box <= xMAX + yMAX):
            screen.blit(player1, [xMAX + 1, box - xMAX + 1])
        elif(box <= xMAX*2 + yMAX):
            screen.blit(player1, [xMAX*2 + yMAX - box + 1, yMAX + 1])
        else:
            screen.blit(player1, [xMIN + 1, xMAX*2 + yMAX*2 - box + 1])
    for box in player2pos:
        if(box[2] == UP):
            if(box[0] > xMAX):
                box[2] = RIGHT
                box[0] = xMAX
            elif(box[0] < xMIN):
                box[2] = LEFT
                box[0] = xMIN
        if(box[2] == LEFT):
            if(box[1] > yMAX):
                box[2] = DOWN
                box[1] = yMAX
            elif(box[1] < yMIN):
                box[2] = UP
                box[1] = yMIN
        if(box[2] == DOWN):
            if(box[0] > xMAX):
                box[2] = RIGHT
                box[0] = xMAX
            elif(box[0] < xMIN):
                box[2] = LEFT
                box[0] = xMIN
        if(box[2] == RIGHT):
            if(box[1] > yMAX):
                box[2] = DOWN
                box[1] = yMAX
            elif(box[1] < yMIN):
                box[2] = UP
                box[1] = yMIN
        screen.blit(player2, [box[0], box[1]])
    screen.blit(ball, ballpos)
    ballpos[0] += ballvel[0]
    ballpos[1] += ballvel[1]
    #if(player1pos[0][2] == 1 and ballpos[0] <= player1pos[0][0] and ballpos[1] <= player1pos[5][1] and ballpos[1] >= player1pos[0][1]):
    #    ballvel[0] *= -1
    #if(player1pos[0][2] == 3 and ballpos[0] >= player1pos[0][0] - 17 and ballpos[1] >= player1pos[5][1] and ballpos[1] <= player1pos[0][1]):
    #    ballvel[0] *= -1
    if(ballpos[0] > xMAX - 8 or ballpos[0] < xMIN - 10):
        if not hasBounced:
            ballvel[0] *= -1
            hasBounced = True
        else:
            hasBounced = False
    if(ballpos[1] > yMAX - 5 or ballpos[1] < yMIN - 10):
        if not hasBounced:
            ballvel[1] *= -1
            hasBounced = True
        else:
            hasBounced = False
    pygame.display.flip()

    for ev in pygame.event.get():
        if ev.type == KEYDOWN:
            if ev.key == K_w:
                player1keys[0] = True
            elif ev.key == K_a:
                player1keys[1] = True
            elif ev.key == K_s:
                player1keys[2] = True
            elif ev.key == K_d:
                player1keys[3] = True
            if ev.key == K_UP:
                player2keys[0] = True
            elif ev.key == K_LEFT:
                player2keys[1] = True
            elif ev.key == K_DOWN:
                player2keys[2] = True
            elif ev.key == K_RIGHT:
                player2keys[3] = True
        if ev.type == KEYUP:
            if ev.key == K_w:
                player1keys[0] = False
            elif ev.key == K_a:
                player1keys[1] = False
            elif ev.key == K_s:
                player1keys[2] = False
            elif ev.key == K_d:
                player1keys[3] = False
            elif ev.key == K_UP:
                player2keys[0] = False
            elif ev.key == K_LEFT:
                player2keys[1] = False
            elif ev.key == K_DOWN:
                player2keys[2] = False
            elif ev.key == K_RIGHT:
                player2keys[3] = False
        if ev.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)

    #Checks Player #1's Key inputs
    if player1keys[0]:
        if player1pos[6] > xMAX and player1pos[0] <= xMAX + yMAX:
            for num in range(0,7):
                player1pos[num] -= 2
        if player1pos[6] > xMAX*2 + yMAX:
            for num in range(0,7):
                player1pos[num] += 2
                if player1pos[num] > 2130:
                    player1pos[num] -= 2130
    elif player1keys[2]:
        if player1pos[6] > xMAX and player1pos[0] <= xMAX + yMAX:
            for num in range(0,7):
                player1pos[num] += 2
        if player1pos[6] > xMAX*2 + yMAX:
            for num in range(0,7):
                player1pos[num] -= 2
    elif player1keys[1]:
        if player1pos[6] > xMAX + yMAX and player1pos[0] <= xMAX*2 + yMAX:
            for num in range(0,7):
                player1pos[num] += 2
        if player1pos[0] < xMAX or player1pos[0] > 2015:
            for num in range(0,7):
                player1pos[num] -= 2
                if player1pos[num] < 0:
                    player1pos[num] += 2130
    elif player1keys[3]:
        if player1pos[6] > xMAX + yMAX and player1pos[0] <= xMAX*2 + yMAX:
            for num in range(0,7):
                player1pos[num] -= 2
        if player1pos[0] < xMAX or player1pos[0] > 2010:
            for num in range(0,7):
                player1pos[num] += 2

    #Checks Player #2's key inputs
    if player2keys[0]:
        if player2pos[6][2] == LEFT:
            for box in player2pos:
                if(box[2] == LEFT):
                    box[1] -= 2
                elif(box[2] == UP):
                    box[0] += 2
        elif player2pos[0][2] == RIGHT:
            for box in player2pos:
                if(box[2] == RIGHT):
                    box[1] -= 2
                elif(box[2] == UP):
                    box[0] -= 2
    elif player2keys[2]:
        if player2pos[0][2] == LEFT:
            for box in player2pos:
                if(box[2] == LEFT):
                    box[1] += 2
                elif(box[2] == DOWN):
                    box[0] += 2
        elif player2pos[6][2] == RIGHT:
            for box in player2pos:
                if(box[2] == RIGHT):
                    box[1] += 2
                elif(box[2] == DOWN):
                    box[0] -= 2
    elif player2keys[1]:
        if player2pos[0][2] == UP:
            for box in player2pos:
                if(box[2] == UP):
                    box[0] -= 2
                elif(box[2] == LEFT):
                    box[1] += 2
        elif player2pos[6][2] == DOWN:
            for box in player2pos:
                if(box[2] == DOWN):
                    box[0] -= 2
                elif(box[2] == LEFT):
                    box[1] -= 2
    elif player2keys[3]:
        if player2pos[6][2] == UP:
            for box in player2pos:
                if(box[2] == UP):
                    box[0] += 2
                elif(box[2] == RIGHT):
                    box[1] += 2
        elif player2pos[0][2] == DOWN:
            for box in player2pos:
                if(box[2] == DOWN):
                    box[0] += 2
                elif(box[2] == RIGHT):
                    box[1] -= 2
    pygame.time.delay(6)


from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.dashboard, name='dashboard'),
    url(r'^add_mentor$', views.add_mentor, name='add_mentor'),
    url(r'^add_investor$', views.add_investor, name='add_investor'),

    url(r'^show_startups$', views.show_startups, name='show_startups'),
    url(r'^show_investors$', views.show_investors, name='show_investors'),
    url(r'^show_mentors$', views.show_mentors, name='show_mentors'),
    #url(r'^test$', views.test),
    url(r'^upload_documents$', views.upload_documents, name='upload_documents'),
    url(r'^update_info$', views.update_info, name='update_info'),
    url(r'^show_tickets$', views.show_tickets, name='show_tickets'),
    url(r'^show_incubation$', views.show_incubation, name='show_incunbation'),
    url(r'^accept_fund/(?P<pk>[0-9]+)$',views.accept_fund,name='accept_fund'),
    url(r'^reject_fund/(?P<pk>[0-9]+)$',views.reject_fund,name='reject_fund'),
    url(r'^accept_incubation/(?P<pk>[0-9]+)$',views.accept_incubation,name='accept_incubation'),
    url(r'^reject_incubation/(?P<pk>[0-9]+)$',views.reject_incubation,name='reject_incubation'),
    url(r'^show_ticket/(?P<pk>[0-9]+)$',views.show_ticket,name='show_ticket'),
    url(r'^solve_ticket/(?P<pk>[0-9]+)$',views.solve_ticket,name='solve_ticket'),
    url(r'^assign_mentor$', views.assign_mentor, name='assign_mentor'),
    url(r'^reviews$', views.reviews, name='reviews'),
    url(r'^set_milestone/(?P<pk>[0-9]+)$',views.set_milestone,name='set_milestone'),
    url(r'^show_milestone/(?P<pk>[0-9]+)$',views.show_milestone,name='show_milestone'),
    url(r'^show_funded_startups$', views.show_funded_startups, name='show_funded_startups'),
    url(r'^complete_milestone/(?P<pk>[0-9]+)$',views.complete_milestone,name='complete_milestone'),

]


# In class naming convension we use camel casing in which first word of the name
# is capital
# Class is blueprint of object. just like an architecture which first draws the blueprint
# of any construction. He can use that same blueprint for another constructions also. like that
# we define class as blueprint of object which we use to create new objects by same class.

# Here we defining a class
class Point:
    def move(self):
        print("Move")

    def draw(self):
        print("draw")

# after that we are creating object below.
point1 = Point() #object created using class name with () parenthesis.
# now below we accessing properties of class using '.' operator.
point1.draw() # calling draw method of class point using . operator.
point1.move() # there are some inbuilt methods also present there.

point1.x = 10 # we can also give and access new properties to object
point1.y = 20 # like this x and y co-ordinates.
print(point1.x)
print(point1.y)

point2 = Point()
print(point2.x) # this will give an attribute error because
# we have given x and y attributes to only point1 object so we cant access
# it by using point2.


#coding=utf-8
import sys
import pygame
from Bullet import Bullet
from Alien import Alien
from time import sleep

def check_keydown_events(event,ai_settings,screen,ship,bullets,stats,play_Button,aliens,sb):
    """按键响应"""
     #按下的是方向键右
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
     #按下的是方向键左
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    #按下的是空格
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings,screen,ship,bullets)
     #按下q
    elif event.key == pygame.K_q:
        sys.exit()#退出游戏
        #按下p
    elif event.key == pygame.K_p:
        start_game(ai_settings,screen,stats,play_Button,ship,aliens,bullets,sb)

def check_play_button(ai_settings,screen,stats,play_Button,ship,aliens,bullets,sb,mouse_x,mouse_y):
    """鼠标点击play按钮时的相应"""
    if play_Button.rect.collidepoint(mouse_x,mouse_y) and not stats.game_action:
       start_game(ai_settings,screen,stats,play_Button,ship,aliens,bullets,sb)

def start_game(ai_settings,screen,stats,play_Button,ship,aliens,bullets,sb):
    """开始游戏"""
     #改变游戏是否开开始的标识为true
    stats.game_action = True
    #重置游戏
    stats.reset_stats()
    #清空外星人和子弹
    aliens.empty()
    bullets.empty()
    #创建一组外星人
    create_fleet(ai_settings,screen,ship,aliens)
    #创建飞船
    ship.center_ship()
    #隐藏光标
    pygame.mouse.set_visible(False)
    #重置速度
    ai_settings.initialize_dynamic_settings()
    #重新设置计分
    sb.prep_level()
    sb.prep_score()
    sb.prep_high_score()
    sb.prep_ship()#显示剩余飞机数量

def fire_bullet(ai_settings,screen,ship,bullets):
    """发射子弹"""
    if len(bullets) < ai_settings.bullet_allowed:#如果子弹数量没有超过限制
        new_bullet = Bullet(ai_settings,screen,ship)#创建一个新子弹
        bullets.add(new_bullet)#添加到
def check_keyup_events(event,ship):
    """按键松开"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False

def check_events(ai_settings,aliens,screen,ship,bullets,stats,play_Button,sb):
    """按键响应事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:#点击窗口关闭按钮
            sys.exit()#退出游戏
             #检测键盘有按键按下
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event,ai_settings,screen,ship,bullets,stats,play_Button,aliens,sb)
            #检测键盘是否有按键松开
        elif event.type == pygame.KEYUP:
            check_keyup_events(event,ship)
            #检测是否有鼠标按下
        elif event.type == pygame.MOUSEBUTTONDOWN:
            #获取鼠标点击的位置
            mouse_x,mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings,screen,stats,play_Button,ship,aliens,bullets,sb,mouse_x,mouse_y)

def update_screen(ai_settings,screen,ship,stats,aliens,bullets,play_Button,sb):
    """更新动画"""

    screen.fill(ai_settings.screen_color)#为屏幕填充颜色,RGB

    #根据子弹的大小位置等信息绘制子弹
    for bullet in bullets:
        bullet.draw_bullet()
    #绘制飞船
    ship.blitem()
    #自动根据编组内每个成员的rect绘制
    aliens.draw(screen)
    if not stats.game_action:
        play_Button.draw_button()
        #刷新分数
    sb.show_score()
    #让最近绘制的屏幕可见
    pygame.display.flip()#不断擦去旧屏幕，显示新屏幕，不断刷新，形成动画
def update_bullet(ai_settings,screen,ship,stats,aliens,bullets,sb):
    """刷新子弹"""
     #自动对编组中的每一个成员执行update
    bullets.update()

    #对消失的子弹进行删除
    for bullet in bullets:
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)

    check_bullet_alien_collisions(ai_settings,screen,ship,stats,aliens,bullets,sb)

def check_bullet_alien_collisions(ai_settings,screen,ship,stats,aliens,bullets,sb):
    """外星人与子弹发生碰撞"""
     #检查外星人与子弹是否产生碰撞
    collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)#后面两个布尔值的意思是若发生碰撞则两个元素都删除，
    #若改为false，true则发生碰撞时子弹不消失，外星人消失
    if collisions:
        for aliens in collisions.values():
            stats.score+=ai_settings.alien_points * len(aliens)
            sb.prep_score()
            check_high_score(stats,sb)

    if len(aliens) == 0:#如果外星人全部消失则重新创建一组外星人
        bullets.empty()#清除子弹
        ai_settings.increase_speed()
        create_fleet(ai_settings,screen,ship,aliens)
        stats.level+=1#消灭一组外星人 等级加一
        sb.prep_level()#刷新等级
        ai_settings.bullet_with+=0.5
def update_aliens(ai_settings,stats,screen,ship,aliens,bullets,sb):
    """更新外星人"""
    check_fleet_edges(ai_settings,aliens)
    aliens.update()

    #如果外星人与飞船相撞
    if pygame.sprite.spritecollideany(ship,aliens):
        ship_hit(ai_settings,stats,screen,ship,aliens,bullets,sb)
    #到屏幕底端
    check_aliens_bottom(ai_settings,stats,screen,ship,aliens,bullets,sb)

def ship_hit(ai_settings,stats,screen,ship,aliens,bullets,sb):
    """外星人与飞船相撞"""

    if stats.ships_left > 1:
        stats.ships_left-=1#飞船数减一
        aliens.empty()#外星人重置
        bullets.empty()#子弹重置
        create_fleet(ai_settings,screen,ship,aliens)#创建新的外星人
        ship.center_ship()#重置飞船位置
        stats.game_action = True
        sleep(0.1)#暂停0.1s
        sb.prep_ship()#更新当前飞机图标
    else :
        stats.game_action = False
        pygame.mouse.set_visible(True)

def get_number_aliens_x(ai_settings,alien_width):
    """计算每行外星人数"""
    available_space_x = ai_settings.screen_width - (3 * alien_width)#减去一个外星人的位置
    number_aliens_x = int(available_space_x / (2 * alien_width))#能放多少个外星人
    return number_aliens_x

def create_alien(ai_settings,screen,aliens,alien_number,number_row):
    """创建一个外星人，并将它放到分组里"""
    alien = Alien(ai_settings,screen)#创建一个外星人
    alien_width = alien.rect.width
    alien.x = alien_width + 2 * alien_width * alien_number#位置，每个外星人之间间隔一个外星人的距离
    alien.rect.x = alien.x#设置位置，外星人的位置由rect中的值决定
    alien.rect.y =3* alien.rect.height + 2 * alien.rect.height * number_row
    aliens.add(alien)#添加到编组中
def get_number_rows(ai_settings,ship_height,alien_height):
    """计算可容纳多少行外星人"""
    available_space_y = ai_settings.screen_height - 4* alien_height - ship_height
    #窗口高度减去外星人与最上面边距之间的距离，外星人与飞船之间的距离（外星人高度的三倍），飞船的高度
    number_rows = available_space_y / (2 * alien_height)#减后的距离除以外星人所占的高度（每行外星人之间有一行外星人高度的距离）
    return number_rows

def create_fleet(ai_settings,screen,ship,aliens):
    """创建一组外星人"""
    alien = Alien(ai_settings,screen)#生成外星人单个实例
    alien_width = alien.rect.width#外星人宽
    number_aliens_x = get_number_aliens_x(ai_settings,alien_width)#一行创建多少个外星人
    number_rows = int(get_number_rows(ai_settings,ship.rect.height,alien.rect.height))#创建多少行外星人

    for number_row in range(number_rows):
        for alien_number in range(number_aliens_x):#从0开始计数
            create_alien(ai_settings,screen,aliens,alien_number,number_row)#创建外星人
def check_fleet_edges(ai_settings,aliens):
    """外星人到达屏幕边缘做出的反应"""
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_settings,aliens)
            break

def change_fleet_direction(ai_settings,aliens):
    """外星人向下移动，并改变移动方向"""
    for alien in aliens.sprites():
        alien.rect.y+=ai_settings.fleet_drop_speed#向下移动
    ai_settings.fleet_direction *= -1#改变方向
def check_aliens_bottom(ai_settings,stats,screen,ship,aliens,bullets,sb):
    """检查是否有外星人到达屏幕底端"""
    screen_rect = screen.get_rect()#获取屏幕rect对象
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:#当外星人的底部大于或等于窗口的底部时，说明外星人撞到屏幕底部
            ship_hit(ai_settings,stats,screen,ship,aliens,bullets,sb)
            break

def check_high_score(stats,sb):
    """检查分数，获取最高分"""
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        sb.prep_high_score()


import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import pickle
from joblib import dump, load
from sklearn import ensemble
from sklearn import metrics
import numpy as np

def main():
  GrBosstClass = load_GRB()
  Bagging = load_Bagging()
  data = loadSet()
  defaulData = loadDefaultSet()
  currentModelSelected = 0
  vl15H = 0
  speedWind = 0
  cloydy3H = 0
  vl9H = 0
  rainToday = 1
  sun = 0
  tempAir15H = 0
  dav15H = 0
  minTemp = 0
  maxTemp = 0

  st.title("Модуль С")
  st.markdown("", unsafe_allow_html=True)
  st.sidebar.markdown('
 Модели
', unsafe_allow_html=True)
  modelSelect = st.sidebar.radio("Выберите модель машинного обучения", ["Градиентный бустинг", "Бэггиннг"])

  st.sidebar.markdown('
 Дата сеты
', unsafe_allow_html=True)
  dataSetSelect = st.sidebar.radio("Выберите дата сет", ["Исходный", "После препроцесса"])

  if dataSetSelect == "После препроцесса":
    '''В датасете после препроцесса остались только самые важные десять полей. Также перекодированы столбцы: локация, направление ветра и был ли сегодня дождь.'''
    st.write(data.head(10))

  if dataSetSelect == "Исходный":
    ''' Исходный датасет имеет полный список полей. Также в нём не заполнены пустые значения и ни один признак не перекодирован.'''
    st.write(defaulData.head(10))

  if modelSelect == "Градиентный бустинг":
    currentModelSelected = GrBosstClass
    "Предсказание градиентного бустинга"
    "Градиентный бустинг предсказывает с точностью в 85%"

  if modelSelect == "Бэггиннг":
    currentModelSelected = Bagging
    "Предсказание бэггиннга"
    "Бэггинг предсказывает с точностью в 84%"
  "Для предсказания дождя на завтрашний день исопльзуются основные 10 параметров."
  ""
  inpType = st.radio("Как будете вводить данные?", ['Строкой', "Буду заполнять каждое поле отдельно!"])
  if inpType == "Буду заполнять каждое поле отдельно!":
    vl15H = st.number_input("Влажность воздуха в 15:00")
    speedWind = st.number_input("Скорость порыва ветра")
    cloydy3H = st.number_input("Облачность в 15:00 (от 0 до 9)")
    vl9H = st.number_input("Влажность в 9 утра")
    rainTodayStr = st.radio("Был ли сегодня дождь?", ["Да" , "Нет"])
    rainToday = 1
    if rainTodayStr =="Да":
      rainToday = 1
    else:
      rainToday = 0
    sun = st.number_input("Солнечный свет (от 0 до 13,9)")
    tempAir15H = st.number_input("Температура воздуха в 15:00")
    dav15H = st.number_input("Давление в 15:00")
    minTemp = st.number_input("Минимальная температура воздуха")
    maxTemp = st.number_input("Максимальная температура воздуха")
  if inpType == "Строкой":
    a = st.text_input('Ввести данные строкой:', help= "Ввдетие числа через запятую. Без точек и запятых в конце строки!")
    if a:
      a = a.split(',')
      a = [float(i) for i in a]
      polya = a
  else:
    polya = int(currentModelSelected.predict([[vl15H,speedWind,cloydy3H,vl9H,rainToday,sun,tempAir15H,dav15H,minTemp,maxTemp]]))
  "Введенные данные: " + str(vl15H) + ", " + str(speedWind) + ", " + str(cloydy3H) + ", " + str(vl9H) + ", " +str(rainToday) + ", " + str(sun) + ", " + str(tempAir15H) + ", " + str(dav15H) + ", " + str(minTemp) + ", " + str(maxTemp) + "."
  if st.button("Рассчитать прогноз", key=None, help="Предсказать будет ли дождь завтра при помощи метода " + modelSelect):
    res = polya
    if res == 0:
      st.markdown("
Скорее всего завтра не будет дождя 😄
", unsafe_allow_html=True)
    else:
      st.markdown("
Скорее всего завтра будет дождь... 😔
", unsafe_allow_html=True)

@st.cache
def loadSet():
  df = pd.read_csv("data/watherPreProcces.csv")
  return df

### models

@st.cache
def load_GRB():
  with open('models/GrBosstClass.pkl', 'rb') as pkl_file:
    grb = pickle.load(pkl_file)
  return grb

@st.cache(allow_output_mutation=True)
def load_Bagging():
  with open('models/Bagging.pkl', 'rb') as pkl_file:
    Bagging = pickle.load(pkl_file)
  return Bagging

@st.cache
def loadDefaultSet():
  df = pd.read_csv("data/weather.csv")
  return df

if __name__ == "__main__":
  main()


from users.models import MossaicUser

from risk_models.models import *
from projects.models import *
from communities.models import *

from django import forms
from django.forms.models import *
from django.forms import ModelForm, Textarea
from django.forms.widgets import HiddenInput
from django.forms.models import inlineformset_factory
from django.forms.models import modelformset_factory
from django.forms.models import BaseInlineFormSet
from django.forms import ModelForm, Textarea
from django.forms.widgets import HiddenInput

# this code is terrible....  will fix someday

class SurveyItem(ModelForm):
	class Meta:
		model = Observation
		widgets = {
			'community': HiddenInput,
			'user': HiddenInput,
			'timestamp': HiddenInput,
			'metric': HiddenInput
		}

	def __init__(self, *args, **kwargs):
		self.request = kwargs.pop('request', None)
		return super(SurveyItem, self).__init__(*args, **kwargs)

	def is_filled(self):
		cleaned_data = self.cleaned_data
		metric = cleaned_data.get("metric")

		if metric.metricType == 'M':
			mcValue = cleaned_data.get("mcValue")
			if mcValue == None:
				return False
			return True

		if metric.metricType == 'D':
			value = cleaned_data.get("value")
			if value == None:
				return False
			return True

		return False

	def clean(self):
		cleaned_data = self.cleaned_data
		metric = cleaned_data.get("metric")

		if metric.metricType == 'M':
			mcValue = cleaned_data.get("mcValue")
			if mcValue == None:
				raise forms.ValidationError('No choice made')
			return cleaned_data

		if metric.metricType == 'D':
			value = cleaned_data.get("value")
			if value == None:
				raise forms.ValidationError('No choice made')
			return cleaned_data

	def save(self, *args, **kwargs):
		kwargs['commit'] = False

		obs = super(SurveyItem, self).save(*args, **kwargs)
		if self.request:
			obs.user = MossaicUser.objects.get(pk=self.request.user.id)  #there must be a better way...

		obs.save()


import wx
from wx.lib.agw import customtreectrl
from wx.lib.agw.aui import GetManager

from ..controller.project import Project
from ..pluginapi import Plugin
from ..pluginapi.plugin import ActionInfo

class FileExplorerPlugin(Plugin):
    """Provides a tree view for Files and Folders. Opens selected item with mouse right-click."""
    datafile = property(lambda self: self.get_selected_datafile())
    defaults = {"opened": True,
                "docked": True,
                "own colors": False
                }

    def __init__(self, application, controller=None):
        Plugin.__init__(self, application, default_settings=self.defaults)
        self._app = application
        self.settings = self._app.settings.config_obj['Plugins']['File Explorer']
        self._parent = wx.App.Get().GetTopWindow()
        self._filemgr = self.filemgr
        self._filemgr.SetThemeEnabled(True)
        self._mgr = GetManager(self._filemgr)
        self._controller = controller
        self._pane = None
        self._filetreectrl = None
        self.font = self._filemgr.GetFont()

    def register_frame(self, parent=None):
        if parent:
            self._parent = parent

            if self._mgr.GetPane("file_manager") in self._mgr._panes:
                register = self._mgr.InsertPane
            else:
                register = self._mgr.AddPane

            register(self._filemgr, wx.lib.agw.aui.AuiPaneInfo().Name("file_manager").
                     Caption("Files").LeftDockable(True).CloseButton(True))

            self._mgr.Update()

    def enable(self):
        self.register_action(ActionInfo('View', 'View File Explorer', self.on_show_file_explorer,
                                        shortcut='F11',
                                        doc='Show File Explorer panel',
                                        position=1))
        # self.save_setting('opened', True)
        if self.opened:
            self.on_show_file_explorer(None)

    def close_tree(self):
        self._mgr.DetachPane(self._filemgr)
        self._filemgr.Hide()
        self._mgr.Update()
        self.save_setting('opened', False)

    def disable(self):
        self.close_tree()
        # self.save_setting('opened', False)
        self.unsubscribe_all()
        self.unregister_actions()

    def is_focused(self):
        return self._filemgr.HasFocus()

    def on_show_file_explorer(self, event):
        _ = event
        if not self._parent:
            self._parent = wx.App.Get().GetWindow()  # self.frame
        if not self._filemgr:  # This is not needed because file explorer is always created
            self._filemgr = FileExplorer(self._parent, self._controller)

        self._pane = self._mgr.GetPane(self._filemgr)
        global_settings = self._app.settings.config_obj['General']
        apply_global = global_settings['apply to panels']
        use_own = self.settings['own colors']
        if apply_global or not use_own:
            html_background = self.settings.get('background help', (240, 242, 80))
            html_foreground = self.settings.get('foreground text', (7, 0, 70))
        else:
            html_background = self.settings.get('background', (240, 242, 80))
            html_foreground = self.settings.get('foreground', (7, 0, 70))
        html_font_face = self.settings.get('font face', '')
        html_font_size = self.settings.get('font size', 11)
        self._filetreectrl = self._filemgr.GetTreeCtrl()
        self._filemgr.Show(True)
        self._filemgr.SetMinSize(wx.Size(200, 225))
        self._mgr.DetachPane(self._filemgr)
        self._mgr.AddPane(self.filemgr,
                          wx.lib.agw.aui.AuiPaneInfo().Name("file_manager").
                          Caption("Files").LeftDockable(True).
                          CloseButton(True))
        self._filemgr.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)
        self._filemgr.SetBackgroundColour(html_background)
        self._filemgr.SetForegroundColour(html_foreground)
        self.font = self._filemgr.GetFont()
        self.font.SetFaceName(html_font_face)
        self.font.SetPointSize(html_font_size)
        self._filemgr.SetFont(self.font)
        self._filemgr.Refresh()
        self._filetreectrl.SetBackgroundColour(html_background)
        self._filetreectrl.SetForegroundColour(html_foreground)
        self._filetreectrl.SetFont(self.font)
        self._filetreectrl.Refresh()
        self._filemgr.Raise()
        self._mgr.Update()
        self.save_setting('opened', True)
        self.update_tree()

    def update_tree(self):
        if not self._filemgr:
            return
        self._filemgr.update_tree()

class FileExplorer(wx.GenericDirCtrl):

    def __init__(self, parent, controller=None):
        wx.GenericDirCtrl.__init__(self, parent, id=-1, size=(200, 225), style=wx.DIRCTRL_3D_INTERNAL)
        self._controller = controller
        self.SetThemeEnabled(True)
        self.Refresh()

    def update_tree(self):
        if isinstance(self._controller, Project):
            if self._controller.data and len(self._controller.data.directory) > 1:
                self.SelectPath(self._controller.data.source)
                try:
                    self.ExpandPath(self._controller.data.source)
                except Exception:
                    pass
                self.Refresh()
                self.Update()


from pyramid.httpexceptions import HTTPError
from pyramid.httpexceptions import HTTPNotFound
from oekocms.views import error_view
from oekocms.views import exception_decorator
from fanstatic import Library
from fanstatic import Resource
import kotti.static as ks

lib_oekocms = Library('oekocms', 'static')
view_css =  Resource(lib_oekocms, "layout.css", depends=[ks.view_css])
edit_css =  Resource(lib_oekocms, "edit.css", depends=[ks.edit_css])
nav_css =  Resource(lib_oekocms, "primary-navigation.css")

def add_fanstatic_resources(config):
    ks.view_needed.add(view_css)
    ks.view_needed.add(nav_css)
    ks.edit_needed.add(edit_css)

def includeme(config):
    config.include('pyramid_zcml')
    config.load_zcml('configure.zcml')
    config.add_view(
        error_view,
        context=HTTPNotFound,
        renderer='oekocms:templates/view/error-404.pt',
    )
    config.add_view(
        error_view,
        context=HTTPError,
        renderer='oekocms:templates/view/error.pt',
    )
    config.add_view(
        error_view,
        decorator=exception_decorator,
        context=Exception,
        renderer='oekocms:templates/view/error.pt',
    )
    config.add_static_view('static-oekocms', 'oekocms:static')
    config.override_asset('kotti', 'oekocms:kotti-overrides/')
    add_fanstatic_resources(config)