import numpy
from matplotlib import pyplot
from utils import timeit

@timeit
def get_data():
    data = []
    with open('input.txt') as input_file:
        for line in input_file:
            points = tuple((int(x), int(y)) for x, y in (point.split(',') for point in line.strip().split(' -> ')))
            data.append(points)
    return data

def build_grid(paths, infinite_floor=False):
    paths.append(((500, 0),))
    min_x = min(point[0] for path in paths for point in path)
    min_y = min(point[1] for path in paths for point in path)
    max_x = max(point[0] for path in paths for point in path)
    max_y = max(point[1] for path in paths for point in path)

    if infinite_floor:
        max_y += 2
        min_x = min(min_x, 500 - (max_y - min_y) - 2)
        max_x = max(max_x, 500 + (max_y - min_y) + 2)
        paths = [((min_x, max_y), (max_x, max_y))] + paths

    paths = tuple(tuple((x - min_x, max_y - y) for x, y in path) for path in paths)
    start_point = paths[-1][0]

    grid = numpy.full((max_x - min_x + 1, max_y - min_y + 1), '.')
    for path in paths:
        for (a_x, a_y), (b_x, b_y) in zip(path, path[1:]):
            a_x, b_x = min(a_x, b_x), max(a_x, b_x)
            a_y, b_y = min(a_y, b_y), max(a_y, b_y)

            grid[a_x:b_x + 1, a_y:b_y + 1] = '#'

    return grid, start_point

def get_resting_place(path, grid):
    x, y = path[-1]
    while True:
        if not 0 <= x < grid.shape[0] or not 0 <= y < grid.shape[1]:
            return None
        y -= 1
        if grid[x][y] == '.':
            pass
        elif grid[x - 1][y] == '.':
            x -= 1
        elif grid[x + 1][y] == '.':
            x += 1
        else:
            return path
        path.append((x, y))

@timeit
def part_1(paths, infinite_floor=False):
    grid, start_point = build_grid(paths, infinite_floor)

    path = [start_point]
    count = 0

    while path:
        path = get_resting_place(path, grid)
        if not path:
            break
        x, y = path.pop()
        grid[x][y] = 'o'
        count += 1

    pyplot.imshow(numpy.rot90(grid.view(numpy.uint32)))
    pyplot.show()
    return count

@timeit
def part_2(paths):
    return part_1.func(paths, infinite_floor=True)

def main():
    data = get_data()
    part_1(data)
    part_2(data)

if __name__ == "__main__":
    main()


import json

from tags.tests.base_test import TagsBaseTestCase

class TagNamespaceTestCase(TagsBaseTestCase):
    fixtures = ["test_authentication.yaml", "test_marketplace.yaml"]

    def test_create_scoped_namespace(self):
        ##############################
        # Creation of global namespace

        self.login("17admin")
        res = self.post(
            "/tags/namespaces/", {"scoped_to_model": "global", "name": "users"}
        )
        self.assertStatusCode(res, 201)

        # Check cannot create two global namespaces with the same name
        res = self.post(
            "/tags/namespaces/", {"scoped_to_model": "global", "name": "users"}
        )

        self.assertStatusCode(res, 400)

        ############################################
        # Creation of a namespace for an association

        self.login("17admin_pdm")
        res = self.post(
            "/tags/namespaces/",
            {"scoped_to_model": "association", "scoped_to_pk": "pdm", "name": "farine"},
        )
        self.assertStatusCode(res, 201)

        # Try to get all namespaces
        res = self.get("/tags/namespaces/")
        self.assertStatusCode(res, 200)
        self.assertEqual(len(res.data["results"]), 2)
        self.assertSetEqual(
            {n["name"] for n in res.data["results"]}, {"users", "farine"}
        )

        # Try to get only the namespaces for the association + globals
        res = self.get("/tags/namespaces/association/pdm/")
        self.assertStatusCode(res, 200)
        self.assertEqual(len(res.data["namespaces"]), 2)
        self.assertSetEqual(
            {n["name"] for n in res.data["namespaces"]}, {"farine", "users"}
        )

        # Try to get namespace forgetting the scope
        res = self.post(
            "/tags/namespaces/", {"scoped_to_model": "association", "name": "test_v"}
        )
        self.assertStatusCode(res, 400)

        res = self.post("/tags/namespaces/", {"scoped_to_pk": "pdm", "name": "test_w"})
        self.assertStatusCode(res, 400)

        # Try to get global namespace
        res = self.get("/tags/namespaces/?scoped_to_model=global")
        self.assertStatusCode(res, 200)
        self.assertEqual(len(res.data["results"]), 1)
        self.assertSetEqual({n["name"] for n in res.data["results"]}, {"users"})

        #######################################
        # Creation without proper authorization
        self.login("17admin_biero")
        res = self.post(
            "/tags/namespaces/",
            {"scoped_to_model": "association", "scoped_to_pk": "pdm", "name": "test_x"},
        )
        self.assertStatusCode(res, 403)

        self.login("17admin_biero")
        res = self.post(
            "/tags/namespaces/", {"scoped_to_model": "global", "name": "test_y"}
        )
        self.assertStatusCode(res, 403)

    def test_edit_namespace(self):
        ###########################
        # Create needed namespaces
        self.login("17admin")
        res = self.post(
            "/tags/namespaces/", {"scoped_to_model": "global", "name": "users"}
        )
        self.assertStatusCode(res, 201, user_msg=res.data)
        namespace_user = json.loads(res.content)

        self.login("17admin_pdm")
        res = self.post(
            "/tags/namespaces/",
            {"scoped_to_model": "association", "scoped_to_pk": "pdm", "name": "farine"},
        )
        self.assertStatusCode(res, 201)
        namespace_farine = json.loads(res.content)

        ###########################
        # Basic namespace edition

        self.login("17admin_biero")
        # Global namespace
        res = self.patch(
            "/tags/namespaces/{}/".format(namespace_user["id"]), {"name": "coucou"}
        )
        self.assertStatusCode(res, 403)

        res = self.delete("/tags/namespaces/{}/".format(namespace_user["id"]))
        self.assertStatusCode(res, 403)

        # Specific namespace that doesn't belong to us
        res = self.patch(
            "/tags/namespaces/{}/".format(namespace_farine["id"]), {"name": "coucou"}
        )
        self.assertStatusCode(res, 403)

        res = self.delete("/tags/namespaces/{}/".format(namespace_farine["id"]))
        self.assertStatusCode(res, 403)

        self.login("17admin")
        res = self.patch(
            "/tags/namespaces/{}/".format(namespace_user["id"]), {"name": "coucou"}
        )
        self.assertStatusCode(res, 200)

        self.login("17admin_pdm")
        res = self.patch(
            "/tags/namespaces/{}/".format(namespace_farine["id"]), {"name": "coucou"}
        )
        self.assertStatusCode(res, 200)

        ############################
        # Try to move the namespace
        self.login("17admin_pdm")
        res = self.patch(
            "/tags/namespaces/{}/".format(namespace_user["id"]),
            {"scoped_to_model": "global"},
        )
        self.assertStatusCode(res, 400)

        res = self.patch(
            "/tags/namespaces/{}/".format(namespace_user["id"]),
            {"scoped_to_model": "association", "scoped_to_pk": "biero"},
        )
        self.assertStatusCode(res, 400)

    def test_get_namespace_for_object(self):
        self.login("17admin_pdm")
        res = self.post(
            "/tags/namespaces/",
            {"scoped_to_model": "association", "scoped_to_pk": "pdm", "name": "farine"},
        )
        self.assertStatusCode(res, 201)

        namespace_id = res.data["id"]

        results = self.get("/tags/namespaces/?product=4").data[
            "results"
        ]  # get namespaces for a pdm product
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0]["id"], namespace_id)

        results = self.get("/tags/namespaces/?product=3").data[
            "results"
        ]  # get namespaces for a biero product
        self.assertEqual(len(results), 0)


import re
import keyword
import os
from collections import Counter

def add_keywords(python_kw, cpp_kw, java_kw):
    # keyword.kwlist is a list with python language keywords
    python_kw.extend(keyword.kwlist)
    # list of cpp keywords: http://www.cplusplus.com/doc/oldtutorial/variables/
    cpp_kw.extend(['asm', 'auto', 'bool', 'break', 'case', 'catch', 'char', 'class', 'const', 'const_cast', 'continue',
                   'default', 'delete', 'do', 'double', 'dynamic_cast', 'else', 'enum', 'explicit', 'export', 'extern',
                   'false', 'float', 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable', 'namespace',
                   'new', 'operator', 'private', 'protected', 'public', 'register', 'reinterpret_cast', 'return',
                   'short', 'signed', 'sizeof', 'static', 'static_cast', 'struct', 'switch', 'template', 'this',
                   'throw', 'true', 'try', 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual',
                   'void', 'volatile', 'wchar_t', 'while'])
    # list of java keywords: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
    java_kw.extend(['abstract', 'continue', 'for', 'new', 'switch', 'assert', 'default',  'goto', 'package',
                    'synchronized', 'boolean', 'do', 'if', 'private', 'this', 'break', 'double', 'implements',
                    'protected', 'throw', 'byte', 'else', 'import', 'public', 'throws', 'case', 'enum', 'instanceof',
                    'return', 'transient', 'catch', 'extends', 'int', 'short', 'try', 'char', 'final', 'interface',
                    'static', 'void', 'class', 'finally', 'long', 'strictfp', 'volatile', 'const', 'float', 'native',
                    'super', 'while'])

def word_frequency(file):
    # separate words in the given file
    words = re.findall(r'\w+', open(file).read().lower())
    # returns a counter with the number of appearances of each word in the file
    word_counter = Counter(words)
    return word_counter

def guess_language(file):
    python_kw = []
    cpp_kw = []
    java_kw = []
    # fill the lists with each language keywords
    add_keywords(python_kw, cpp_kw, java_kw)
    # get words frequency
    word_counter = word_frequency(file)
    # count appearances of each language keywords in the given file
    kw_counter = {'python': 0, 'cpp': 0, 'java': 0}
    for kw in python_kw:
        kw_counter['python'] += word_counter[kw]
    for kw in cpp_kw:
        kw_counter['cpp'] += word_counter[kw]
    for kw in java_kw:
        kw_counter['java'] += word_counter[kw]
    # guess language depending on the number of each language keywords encountered
    language = max(kw_counter, key=kw_counter.get)
    return language

def main():
    # Put the files to test in directories called 'cpp', 'java' and 'python'. The output will show a summary of the
    # given files, the prediction success percentage and the files in which it failed.
    cpp_files = os.listdir('cpp/')
    java_files = os.listdir('java/')
    python_files = os.listdir('python/')
    total_files = cpp_files.__len__() + java_files.__len__() + python_files.__len__()
    total_hits = 0

    # Iterate over all the files
    for file in cpp_files:
        if guess_language('cpp/' + file) == 'cpp':
            total_hits = total_hits + 1
        else:
            print('Missed prediction: ', file, '\tLanguage: cpp\tPredicted: ', guess_language('cpp/' + file))
    for file in java_files:
        if guess_language('java/' + file) == 'java':
            total_hits = total_hits + 1
        else:
            print('Missed prediction: ', file, '\tLanguage: java\tPredicted: ', guess_language('java/' + file))
    for file in python_files:
        if guess_language('python/' + file) == 'python':
            total_hits = total_hits + 1
        else:
            print('Missed prediction: ', file, '\tLanguage: python\tPredicted: ', guess_language('python/' + file))

    # print summary
    print('\nTotal files: ', total_files)
    print('Files correctly classified: ', total_hits)
    print('Hit percentage: ', round(total_hits / total_files * 100, 2), '%')

if __name__ == "__main__":
    main()


class Solution:
    def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
        # 空矩阵，退出
        if not grid or not grid[0]:
            return 0
        rows, columns = len(grid), len(grid[0])
        # 维度小于3， 退出
        if rows < 3 or columns < 3:
            return 0
        count = 0
        # 以左上点出发，全局搜索[0, rows - 3], [0, columns - 3]
        for i in range(rows - 2):
            for j in range(columns - 2):
                # 判断是否为幻方
                if self.__validMagicSquare(grid, i, j):
                    count += 1
        return count

    def __validMagicSquare(self, grid, row, column):
        # 第一部分：3维幻方，中间必=5
        if grid[row + 1][column + 1] != 5:
            return False
        # 第二部分： 判断是否属于[0, 9]，且不重复
        s = set()
        for i in range(3):
            for j in range(3):
                t = grid[row + i][column + j]
                # t在[0, 9]之间，且不重复
                if t in s or t < 1 or t > 9:
                    return False
                else:
                    s.add(grid[row + i][column + j])
        # 第三部分：判断所有的行列的和是否相等，无需判断对角线足以
        for i in range(3):
            sumRow, sumCol = 0, 0
            for j in range(3):
                sumRow += grid[row + i][column + j]
                sumCol += grid[row + j][column + i]
            #  3维幻方的行列和=15
            if sumRow != 15 or sumCol != 15:
                return False
        return True


# 1 - Напишите программу, которая принимает на вход вещественное число и показывает сумму его цифр. Учтите, что числа могут быть отрицательными

# Пример:

# 67.82 -> 23
# (-0.56) -> 11

num = input('Введите вещественное число: ')

num = num.replace('-', '')

x = num.split(".")
int_num = int(x[0])
fract_num = int(x[1])

result = 0

while (int_num != 0):
    result = result + (int_num % 10)
    int_num = int_num // 10

while (fract_num != 0):
    result = result + (fract_num % 10)
    fract_num = fract_num // 10

print(result)


# -*- coding: utf-8 -*-

import abc
import importlib

from django.core.exceptions import ImproperlyConfigured
from django.conf import settings

class BaseEventsPushBackend(object, metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def emit_event(self, message:str, *, routing_key:str, channel:str="events"):
        pass

def load_class(path):
    """
    Load class from path.
    """

    mod_name, klass_name = path.rsplit('.', 1)

    try:
        mod = importlib.import_module(mod_name)
    except AttributeError as e:
        raise ImproperlyConfigured('Error importing {0}: "{1}"'.format(mod_name, e))

    try:
        klass = getattr(mod, klass_name)
    except AttributeError:
        raise ImproperlyConfigured('Module "{0}" does not define a "{1}" class'.format(mod_name, klass_name))

    return klass

def get_events_backend(path:str=None, options:dict=None):
    if path is None:
        path = getattr(settings, "EVENTS_PUSH_BACKEND", None)

        if path is None:
            raise ImproperlyConfigured("Events push system not configured")

    if options is None:
        options = getattr(settings, "EVENTS_PUSH_BACKEND_OPTIONS", {})

    cls = load_class(path)
    return cls(**options)


from flask import Flask
from flask import render_template, url_for, jsonify, request
from game import Game

app = Flask(__name__)

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

game=0
@app.route('/init', methods=['POST'])
def init():
    global game
    game = Game()
    game.start()

    # I have no idea why this is necessary but without the list comprehension it
    # breaks.
    data = [int(x) for x in game.grid.flatten()]
    response = jsonify({'board': data})
    return response

directions = { 'U': (1,-1), 'D': (1, 1), 'L': (0,-1), 'R': (0, 1) }

@app.route('/move', methods=['POST'])
def move():
    d = request.args['direction']
    game.move(*directions[d.upper()])

    response = jsonify({ 'board': [int(x) for x in game.grid.flatten()] })
    return response


import json

filename = r'/home/xxm/下载/qlora/data/estate_qa.json'
with open(filename, 'r', encoding='utf-8') as f:
    lines = f.readlines()
    for line in lines:
        line = line.strip()
        example = json.loads(line)
        content = example['output']
        if content == '':
            print(example)


import os
import json

def get_ground_truth(filename):
    #0022000159342.jpg
    #0022000159342_1.jpg
    if filename.find("_")!=-1:
        return filename[0:filename.find("_")]
    else:
        return filename[0:filename.find(".")]

f = open("single_test.txt","r")
for line in f.readlines():
    data = line.strip().split(" ")
    filename = data[0]
    left = data[1]
    top = data[2]
    right = data[3]
    bottom = data[4]
    bbox = {}
    bbox["left"] = left
    bbox["top"] = top
    bbox["right"] = right
    bbox["bottom"] = bottom
    attrib = {}
    attrib["Type"] = "EAN13"
    result = {}
    result["attrib"] = attrib
    result["bbox"] = bbox
    result["text"] = get_ground_truth(filename)
    results = []
    results.append(result)
    fw = open(filename+".txt","w")
    fw.write(json.dumps(results))
    fw.close()
f.close()


import streamlit as st
import pandas as pd
import pickle
from random import randint

books = pd.read_csv('df_2.csv')
df_1 = pickle.load(open('df_1.pkl', 'rb'))

def recommendation(title):
    recommendations = pd.DataFrame(df_1.nlargest(11, title)['title'])
    recommendations = recommendations[recommendations['title'] != title]
    list_name = recommendations['title'].values.tolist()

    add_img = []
    for name in list_name:
        add_img.append(books[books['title'] == name]['image_url'].iloc[0])

    return list_name, add_img

st.title('Content Based Book Recommendation System ')

with st.container():
    select = st.selectbox(
        'Which book would you like to choose?',
        books['title'].values)

    st.write('You selected:', select)

    if st.button('Recommend'):
        col = ["a", "b", "c", "d", "e"]

        list_books, list_imgs = recommendation(select)

        col = st.columns(5)
        with st.container():
            for i in range(5):
                c = col[i]
                with c:
                    st.text(list_books[i])
                    st.image(list_imgs[i])

        with st.container():
            col = st.columns(5)
            for i in range(5):
                c = col[i]
                with c:
                    st.text(list_books[i+5])
                    st.image(list_imgs[i+5])

with st.container():
    st.header('Books')

    colb = ['a', 'b', 'c', 'd', 'e']
    for i in range(10):
        with st.container():
            colb = st.columns(5)
            for c in colb:
                index = randint(0, len(books))
                book = books.iloc[index]
                with c:
                    st.text(book.title)
                    st.image(book.image_url)


"""
Python module to parse FastQC output data.
"""

from __future__ import print_function

class Fadapa(object):
    """
    Returns a parsed data object for given fastqc data file
    """

    def __init__(self, file_name, **kwargs):
        """
        :arg file_name: Name of fastqc_data text file.
        :type file_name: str.
        """
        self.file_name = file_name
        self._content = open(file_name, **kwargs).read().splitlines()
        self._m_mark = '>>'
        self._m_end = '>>END_MODULE'

    def summary(self):
        """
        Returns a list of all modules present in the content.
        Module begins  with  _m_mark ends with _m_end.

        :return: List of modules and their status.

        Sample module:

        >>Basic Statistics	pass
        #Measure	Value
        Filename	sample1.fastq
        >>END_MODULE

        """
        modules = [line.split('\t') for line in self._content
                   if self._m_mark in line and self._m_end not in line]
        data = [[i[2:], j] for i, j in modules]
        data.insert(0, ['Module Name', 'Status'])
        return data

    def content(self):
        """
        Print the contents of the given file.

        :return: None
        """
        for line in self._content:
            print(line)

    def raw_data(self, module):
        """
        Returns raw data lines for a given module name.

        :arg module: Name of module as returned by summary function.
        :type module: str.
        :return: List of strings which consists of raw data of module.
        """
        s_pos = next(self._content.index(x) for x in self._content
                     if module in x)
        e_pos = self._content[s_pos:].index(self._m_end)
        raw_data = self._content[s_pos:s_pos+e_pos+1]
        return raw_data

    def clean_data(self, module):
        """
        Returns a cleaned data for the given module.

        :arg module: name of module
        :type module: str
        :return List of strings containing the clean data of module.
        """
        data = [list(filter(None, x.split('\t')))
                for x in self.raw_data(module)[1:-1]]
        data[0][0] = data[0][0][1:]
        return data


# -*- coding: utf-8 -*-
"""
Created on Sun Oct  1 03:00:44 2023

@author: allen
"""

import math

def sc(a, b):
    r = 0
    for i in range(math.ceil(a ** 0.5), (int(b ** 0.5) + 1)):
        r += i ** 2
    return (r)

x = int(input())
s = 1
for i in range(x):
    a = int(input())
    b = int(input())
    print(f"Case {s}: {sc(a, b)}")
    s += 1


'''PROGRAM DESCRIPITON:
HMTL form for registration is created and after filling the data, the student details like name,email, course are stored in the MongoDB "Registration" database.
'''

# PROGRAMMED BY: PULI SNEHITH REDDY
# MAIL ID : snehithreddyp@gmail.com

# DATE    : 23-09-2021

# VERSION : 3.7.9

# CAVEATS : None

# LICENSE : None

from flask import Flask
from flask import render_template
from flask import redirect
from flask import url_for
from flask import request
import json
from pymongo import MongoClient

connection = MongoClient("mongodb://localhost:27017")

def mongo_connection():
    if connection:
        return True
    else:
        return False

def mongodb_list():
   if mongo_connection() == True:
        return connection.list_database_names()

def db_exists( db_name):
    if db_name in mongodb_list():
        return True
    else:
        return False

def create_new_collection(db_name, new_collection):
    if connection:
        db_name = connection[db_name]
        new_collection = db_name[new_collection]
        return new_collection
    else:
        return("error")

# timestand for mongodb
def timestamp():
    import datetime as dt
    return dt.datetime.now()

def insert_data(db_name,collection_name,data):
    if connection:
        connection[db_name][collection_name].insert_one(data)
        return "success"
    else:
        return "error"

def display(db_name,collection_name):
    a=[]
    if connection:
        for i in connection[db_name][collection_name].find():
            a.append(i)

        for i in a:
            print(i)
            print("-----------------------------------------------")

app = Flask(__name__)

def func(name,email,course):
    data={}
    data["name"]=name
    data["email"]=email
    data["course"]=course
    insert_data("Registration","Data",data)

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

@app.route('/submi',methods=['POST'])
def result():
    name=request.form['name']
    email=request.form['email']
    course=request.form['course']
    func(name,email,course)
    return render_template("submit.html")

@app.route('/user')
def user():
    return render_template('user.html')

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

Class Assignments/Storing deatils of HTML form in Mongodb/app.py


import socket
import json
import sys  # for exit

# Create a UDP socket at client side
UDPClientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Initialize variables
udp_port = 1234
local_host = socket.gethostname()
serverAddressPort = (local_host, udp_port)
IPAddr = socket.gethostbyname(local_host)
buffer_size = 1024

UDPClientSocket.connect(serverAddressPort)

def send_msg(sending_data):
    UDPClientSocket.sendto(sending_data.encode(), serverAddressPort)

def request_options():
    options = "Enter 1 -> Send text, 2-> Check for text, 3-> Quit: "
    c_option = input(options)
    return c_option

def receiving_data(data, opt, local_id):
    recv_data, server_add = UDPClientSocket.recvfrom(buffer_size * 2)
    recv_data = json.loads(recv_data.decode())
    if opt == "2":
        print("TEXT RECEIVED: To: {} From: {} Text: {}".format(local_id, recv_data["sender"], recv_data["message"]))
    else:
        print("MESSAGE RECEIVED FROM SERVER: {}".format(recv_data["message"]))

variables = ProcessData()
variables.client_IP = IPAddr

print("Enter your ID as a string")
variables.client_id = input("->")
option = request_options()

while option == "1" or option == "2":
    if option == "1":
        variables.client_code = "T"
        print("Enter dest ID as a string: ")
        variables.dest_id = input("-> ")
        request_send_text = "Enter your text: "
        variables.send_text = input(request_send_text)
        send_data = json.dumps(
            {"code": variables.client_code, "dest_id": variables.dest_id, "client_id": variables.client_id,
             "send_text": variables.send_text, "client_ip": variables.client_IP})
        print("MESSAGE TO SEND: {} To: {} From: {} Text: {}".format(variables.client_code, variables.dest_id,
                                                                    variables.client_id, variables.send_text))
        send_msg(send_data)
        receiving_data(variables, option, variables.client_id)

    elif option == "2":
        variables.client_code = "C"
        print("MESSAGE TO SEND: {} From: {} ".format(variables.client_code, variables.client_id))
        send_data = json.dumps({"code": variables.client_code, "client_id": variables.client_id})
        send_msg(send_data)
        receiving_data(variables, option, variables.client_id)

    option = request_options()

else:
    UDPClientSocket.close()
    sys.exit()


'''
Prepare a word sequence (sentence) with padding
    - convert a sentence String to list of words in sentence
    - convert list of words in sentence to array of word_embedding and padded
'''
import numpy as np
from keras.preprocessing import sequence
from textblob import Sentence
from src.static_variable import load_word_embedding

# Example dialogs
dialogs = [
    "Beijing is a historical city that can be traced back to 3,000 years ago.",
    "The city's history dates back three millennia. As the last of the Four Great Ancient Capitals of China",
    "Beijing has been the political center of the country for much of the past eight centuries",
    "With mountains surrounding the inland city on three sides",
    "When you want to use a different language, select the same Keyboard & Character Viewer item in the menu bar -- although, when more than one language is enabled, the icon will now show the flag or symbol of the current language in use -- and click on the desired language. The Keyboard Viewer will then change layout to represent the keys of the desired language and allow you to insert native characters. To change back to your regular language, once again click on the Keyboard & Character Viewer menu bar item and select the desired input language to switch to."
]

# load pre-trained Word Embedding model
WORD_EMB = load_word_embedding(load_glove=False)

# constant of maximum number of word in sentence (important when padding)
MAX_WORD = 11
N_CHANEL = 1

def generate_wordlist_emb(txt):
    '''
    Process a text string to list of embedded word
    'I love you' -> ['I', 'love', 'you'] -> list([emb('I'), emb('love'), emb('you')])
    :param word_seq: text String
    :return: list of embedded word
    '''
    word_seq = Sentence(txt.lower()).words
    wordlist = []
    for word in word_seq:
        if word in WORD_EMB.vocab:
            wordlist.append(WORD_EMB[word])
        else:
            # shape is depend on embedding dimension
            # use [1., 1., 1., ...] represent a unknown word
            wordlist.append(np.full(shape=[300], fill_value=1.0, dtype=np.float32))
    return wordlist

def generate_sentence_embedding(sentence):
    # get list of embedded words
    new_sentence = generate_wordlist_emb(sentence)

    # padding a sentence by add 0 value at the front until sentence's length = max_word
    return sequence.pad_sequences([new_sentence], maxlen=MAX_WORD, dtype=np.float32)[0]

def generate_dialogs_embedding(dialogs):
    tmp_dialogs = []
    for i, sentence in enumerate(dialogs):
        tmp_dialogs.append(generate_sentence_embedding(sentence))

    # padding a word that lower than max_words
    tmp_dialogs = np.array(tmp_dialogs)

    # n_sample, max_word, emb_dim, = tmp_dialogs.shape[0], tmp_dialogs.shape[1], tmp_dialogs.shape[2]

    # # return with add 1 chanel in the last index
    # return np.reshape(tmp_dialogs, [n_sample, max_word, emb_dim, N_CHANEL])
    return tmp_dialogs

# dialogs_emb = generate_dialogs_embedding(dialogs)


class CSP:
    '''
    Class to solve a problem using CSP approach.
    Contains all the functions relevant to the CSP.
    '''

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

    def degree_heuristic(self, vertices):
        '''
        orders the vertices of the graph based on the degree
        and returns the vertex with max degree.
        '''
        return sorted(vertices.items(), key=lambda x: len(x[1]), reverse=True)[0][0]

    def minimum_remaining_values_heuristic(self, domains):
        '''
        Orders the vertices for which assignment have to be done
        based on the number of valid values available for them in their domain.
        '''
        ordering = sorted(domains.items(), key=lambda x: len(x[1]))
        ties = {}
        for index in range(1,len(ordering)):
            if len(ordering[index][1]) == len(ordering[index-1][1]):
                ties[ordering[index][0]] = self.graph[ordering[index][0]]
                ties[ordering[index-1][0]] = self.graph[ordering[index-1][0]]
            else:
                break
        if ties:
            return self.degree_heuristic(ties)
        return ordering[0][0]

    def select_unassigned_variable(self, assignment, domains):
        '''
        Selects the next vertex for assignment from the set of unassigned
        vertices based on mrv heuristic and uses degree heuristic for tie-breaks.
        '''
        unassigned = set(self.graph.keys())-set(assignment.keys())
        unassigned_domains = {ver:domains[ver] for ver in unassigned}
        return self.minimum_remaining_values_heuristic(unassigned_domains)

    def least_constraining_value(self, vertex, domains):
        '''
        Orders the domain vlaues of the vertex in a way that it maximizes the
        available domain values for its neighbouring vertices.
        '''
        domain_points = {d_val:0 for d_val in domains[vertex]}
        value_domains = {}
        for adj in self.graph[vertex]:
            value_domains[adj] = {}
            for value in domains[vertex]:
                value_domains[adj][value] = list(set(domains[adj])-set([value]))
            sorted_domain = sorted(value_domains[adj].items(), key=lambda x:len(x[1]), reverse=True)
            if sorted_domain:
                domain_points[sorted_domain[0][0]]+=1
        domains[vertex] = list(dict(sorted(domain_points.items(), key=lambda x:x[1], reverse=True)).keys())
        return domains

    def domain_changed(self, adj, ver, domains):
        '''
        Check if the domain is changed and if changed return the changed domain.
        '''
        i=0
        revised = False
        while(len(domains[adj])!=0) and i<len(domains[adj]):
            if not (set(domains[ver])-set([domains[adj][i]])):
                domains[adj].pop(i)
                revised = True
            else:
                i+=1
        return revised, domains

    def arc_consistency(self, vertex, assignment, domains):
        '''
        recursively check the consistency of the neighbouring vertices
        and return false if any of the domains of the adjacent vertices is empty.
        (Same as AC-3 arc consistency method in the textbook)
        '''
        neighbour_unassigned = [(ver, adj)for adj in self.graph[vertex] for ver in (set(self.graph[adj])-set(assignment.keys()))]
        while(len(neighbour_unassigned)!=0):
            ver, adj = neighbour_unassigned.pop(0)
            bool_, domains = self.domain_changed(ver, adj, domains)
            if bool_:
                if not domains[adj]:
                    return False
                neighbour_unassigned+=[(v, adj) for v in (set(self.graph[adj])-set(assignment.keys())-set([ver]))]
        return True

    def is_valid(self, assignment, vertex, value):
        '''
        Check if this assignment is valid.
        '''
        for adj in self.graph[vertex]:
            if adj in assignment.keys():
                if value == assignment[adj]:
                    return False
        return True

    def reduce_domains(self, vertex, value, domains):
        '''
        Remove the value 'v' from the domains of vertices adjacent to vertex.
        '''
        for adj in self.graph[vertex]:
            if value in domains[adj]:
                domains[adj].remove(value)

    def extend_domains(self, vertex, value, domains):
        '''
        Add the value 'v' to the domains of vertices adjacent to vertex.
        '''
        for adj in self.graph[vertex]:
            if value not in domains[adj]:
                domains[adj].append(value)

    def backtracking_search(self, assignment, domains):
        '''
        Main algorithm to implement the above functions.
        1.) Select unassignedd variable/vertex from the avaiable variables.
        2.) order the domains based on least constraing value first
        3.) if the assignment is valid wrt to previous assignments, then move ahead.
        4.) reduce the domains of the adjacent vertices after the assigned value to
        the current vertex is known to be valid.
        5.) Check arc-consistency and if it returns true recursively call the backtrack algorithm.
        6.) Further, if this assignment does not give a complete solution in the future, \
            repopulate the reduced domains of the adjacent vertices.
        7.) Intermedially, if a solution is found, return the solution.
        '''
        import copy
        if len(assignment.keys()) == len(self.graph.keys()):
            return assignment
        vertex = self.select_unassigned_variable(assignment, domains)
        domains = self.least_constraining_value(vertex, domains)
        for value in domains[vertex]:
            if self.is_valid(assignment, vertex, value):
                assignment[vertex] = value
                self.reduce_domains(vertex, value, domains)
                domains_copy = copy.deepcopy(domains)
                if self.arc_consistency(vertex, assignment, domains_copy):
                    result = self.backtracking_search(assignment, domains)
                    if result:
                        return result
                self.extend_domains(vertex, value, domains)
        return False

def make_graph(filename):
    '''
    Construct a graph from the file given as input.
    It constructs a bidirectional graph.
    '''
    filename = './instances/'+filename
    with open(filename, encoding='utf-8') as file:
        lines = file.readlines()
        graph = {}
        for line in lines:
            line = line.split()
            if int(line[1]) in graph.keys():
                graph[int(line[1])].append(int(line[2]))
            else:
                graph[int(line[1])] = [int(line[2])]
            if int(line[2]) not in graph.keys():
                graph[int(line[2])] = []
        for key, value in graph.items():
            graph[key] = list(set(value))
    return graph

def check_graph_color(assignment, graph):
    for key, value in assignment.items():
        for adj in graph[key]:
            if value == assignment[adj]:
                print(adj, assignment[adj])
                print(key, value)
                return False
    return True

def main():
    '''
    Main function
    '''
    filenames = ['anna.col', 'school1.col']
    for filename in filenames:
        print('For file: ', filename)
        graph = make_graph(filename)
        if filename == 'anna.col':
            domains = {ver:[j for j in range(1,12)] for ver in graph.keys()}
        else:
            domains = {ver:[j for j in range(1,43)] for ver in graph.keys()}
        csp_problem = CSP(graph)
        result = csp_problem.backtracking_search(assignment={}, domains=domains)
        if result:
            print("Valid: ", check_graph_color(result, graph))
            print(dict(sorted(result.items(), key=lambda x:x[0])))
            print('No: of colors required = ',sorted(result.items(), key=lambda x:x[1])[-1][-1])
        else:
            print("No result")
        print()

if __name__ == '__main__':
    main()


import pygame
import math

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 250)
RED = (255, 0, 0)
pygame.init()

# Set the width and height of the screen [width, height]
size = (800, 700)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    # --- Game logic should go here

    # --- Drawing code should go here

    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill(WHITE)

    for i in range(200):
        radians_x = i / 20
        radians_y = i / 6
        x = int(75 * math.sin(radians_x)) + 200
        y = int(75 * math.cos(radians_y)) + 200
        pygame.draw.line(screen, BLACK, [x,y], [x+5,y], 5)

    for x_offset in range(30, 300, 30):
        pygame.draw.line(screen,BLACK,[x_offset,100],[x_offset-10,90],2)
        pygame.draw.line(screen,BLACK,[x_offset,90],[x_offset-10,100],2)

    # Draw a rectangle
    pygame.draw.rect(screen,BLACK,[320,20,250,100],2)
    # Draw an ellipse, using a rectangle as the outside boundaries
    pygame.draw.ellipse(screen, BLACK, [320,20,250,100], 2)

    # Draw an arc as part of an ellipse. Use radians to determine what
    # angle to draw.
    pygame.draw.arc(screen, GREEN, [100,300,250,200], math.pi/2, math.pi, 2)
    pygame.draw.arc(screen, BLACK, [100,300,250,200], 0, math.pi/2, 2)
    pygame.draw.arc(screen, RED, [100,300,250,200],3*math.pi/2, 2*math.pi, 2)
    pygame.draw.arc(screen, BLUE, [100,300,250,200], math.pi, 3*math.pi/2, 2)

    # This draws a triangle using the polygon command
    pygame.draw.polygon(screen, BLACK, [[300,300], [300,500], [500,500]], 5)

    # Select the font to use, size, bold, italics
    font = pygame.font.SysFont('Calibri', 25, True, False)
    # Render the text. "True" means anti-aliased text.
    # Black is the color. The variable BLACK was defined
    # above as a list of [0, 0, 0]
    # Note: This line creates an image of the letters,
    # but does not put it on the screen yet.
    text = font.render("My text", True, BLACK)
    # Put the image of the text on the screen at 250x250
    screen.blit(text, [500, 400])

    score = 100
    text = font.render("Score: ", str(score), True, BLACK)

    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
    # --- Limit to 60 frames per second
    clock.tick(60)

# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()


import datetime

from django.shortcuts import render
from django.db.models import Subquery, Count
from django.http import HttpResponseRedirect
from django.views.decorators.cache import cache_page

from port.models import Port
from stats.models import Submission, PortInstallation
from port.filters import PortFilterByMultiple
from utilities import old_search_redirect

@cache_page(60 * 10)
def index(request):
    # Support for old "?search=<QUERY>&search_by=<name,description>" links
    # Check if search query is present
    if request.GET.get('search'):
        return HttpResponseRedirect(old_search_redirect(request))

    ports_count = Port.objects.filter(active=True).count()
    submissions_unique = Submission.objects.filter(timestamp__gte=datetime.datetime.now(tz=datetime.timezone.utc) - datetime.timedelta(days=30)).order_by('user', '-timestamp').distinct('user')
    top_ports = PortInstallation.objects.filter(submission_id__in=Subquery(submissions_unique.values('id')), requested=True).exclude(port__icontains='mpstats').values('port').annotate(num=Count('port')).order_by('-num')[:10]
    recently_added = Port.objects.all().order_by('-created_at').only('name')[:10]

    return render(request, 'index.html', {
        'top_ports': top_ports,
        'recently_added': recently_added,
        'ports_count': ports_count
    })

# Respond to ajax-call triggered by the search box
def search(request):
    query = request.GET.get('search_text', '')
    search_by = request.GET.get('search_by', '')
    ports = PortFilterByMultiple(request.GET, queryset=Port.get_active.all()).qs[:50]

    return render(request, 'filtered_table.html', {
        'ports': ports,
        'query': query,
        'search_by': search_by
    })

def about_page(request):
    return render(request, 'about.html')


"""
the Bot makes everyday posts with some picture+Belarusial legal word and its definition
"""

#!/usr/bin/python3

import telegram
import time

TOKEN = 'your_token_here'
bot = telegram.Bot(token=TOKEN)
chat_id='your_chat_id_here'
f = open('dictionary.txt', 'r', encoding='UTF-8')
words = f.read().split('\n')
f.close()
temp = ''
num=1
for word in words:
    temp += word + '\n'
    if word[-1] == '*':
        post = "#беларуская_лексіка #родныя_словы" + "\n" + "\n" + temp[:-2:]
        #pictures named 1.jpg, 2.jpg, 3.jpg, etc.
        name='folder_with_pictures'+str(num)+'.jpg'
        with open(name, 'rb') as photo:
            bot.send_photo(chat_id, photo, post)
        temp = ''
        num+=1
        time.sleep(86400)


import matplotlib.pyplot as plt
from matplotlib import ticker

# taken from https://scikit-learn.org/stable/auto_examples/manifold/plot_compare_methods.html#sphx-glr-auto-examples-manifold-plot-compare-methods-py

def plot_3d(points, points_color, title):
    x, y, z = points.T

    fig, ax = plt.subplots(
        figsize=(6, 6),
        facecolor="white",
        tight_layout=True,
        subplot_kw={"projection": "3d"},
    )
    fig.suptitle(title, size=16)
    col = ax.scatter(x, y, z, c=points_color, s=50, alpha=0.8)
    ax.view_init(azim=-60, elev=9)
    ax.xaxis.set_major_locator(ticker.MultipleLocator(4))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(4))
    ax.zaxis.set_major_locator(ticker.MultipleLocator(4))

    fig.colorbar(col, ax=ax, orientation="horizontal", shrink=0.6, aspect=60, pad=0.01)
    plt.show()

def plot_2d(points, points_color, title):
    fig, ax = plt.subplots(figsize=(3, 3), facecolor="white", constrained_layout=True)
    fig.suptitle(title, size=16)
    plt.scatter(ax, points, points_color)
    plt.show()


import numpy as np
import tensorflow as tf

def draw_batch(batch_size):
    xs = np.random.choice([0.0, 1.0], [batch_size, 2])
    ys = np.array(list(map(lambda x: [x[0] != x[1]], xs)))
    return (xs, ys)

# first layer - weights + bias
W1 = tf.Variable(tf.random_uniform([2, 2], -1, 1), name="W1")
b1 = tf.Variable(tf.zeros([2]), name="b1")

# second layer - weights + bias
W2 = tf.Variable(tf.random_uniform([2, 1], -1, 1), name="W2")
b2 = tf.Variable(tf.zeros([1]), name="b2")

# input vector, layer outputs and label
x = tf.placeholder(tf.float32, [64, 2], "x")
h1 = tf.sigmoid(tf.matmul(x, W1) + b1)
h2 = tf.sigmoid(tf.matmul(h1, W2) + b2)
y = tf.placeholder(tf.float32, [64, 1], "y")

# network loss and optimizer
loss = tf.losses.mean_squared_error(y, h2)
optimizer = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

for i in range(10000):
    (xs, ys) = draw_batch(64)
    (loss_value, _) = sess.run([loss, optimizer], {x: xs, y: ys})

    if i % 100 == 0:
        print(loss_value)


def handle(client,topic,payload,mem):
    topic_s = topic.split('/')
    if topic_s[2] == 'task1' and topic_s[3] == 'requests':
        return
    if topic_s[2] == 'task1' and topic_s[3] == 'responses':
    #print(mem)
        # identify operation
        id = int(payload[0:4])
        output = str(mem[id]) + ":::" + payload[4:]
        print(output)
    else:
        print("Command not supported yet!")


import sys
if sys.version_info[0] >= 3:
    unicode = str

def get_str(s):
    """
    :param str|unicode|bytes s:
    :rtype: str|unicode
    """
    if isinstance(s, (str, unicode)):
        return s
    if isinstance(s, bytes):
        return s.decode("utf8")
    raise Exception("Type not supported: %r" % s)


from telebot import types
from datetime import date, timedelta
from ...utils import constants

def get_days(room_name: str) -> types.InlineKeyboardMarkup:
    now = date.today()
    markup = types.InlineKeyboardMarkup()
    for day in range(7):
        """ add in InlineKeyboard """
        w_day = now + timedelta(days=day)
        if w_day.weekday() in range(5):
            if now == w_day:
                text = "Сегодня"
                callback_data = f"{constants.DAYS_OF_THE_WEEK[w_day.weekday()]} - " \
                       f"{room_name} - {w_day.strftime('%d-%m-%Y')}"
            else:
                text = f"{constants.DAYS_OF_THE_WEEK[w_day.weekday()]} - " \
                       f"{room_name} - {w_day.strftime('%d-%m-%Y')}"
                callback_data = f"{constants.DAYS_OF_THE_WEEK[w_day.weekday()]} - " \
                       f"{room_name} - {w_day.strftime('%d-%m-%Y')}"
            markup.add(
                types.InlineKeyboardButton(
                    text=text, callback_data=callback_data
                )
            )
    return markup


# 백준 6단계 문자열
# 10809번 알파벳 찾기

import sys

sys.stdin = open('input.txt')

input = sys.stdin.readline

# 여기부터 제출해야 한다.

input_word = input()

list_result = [-1 for i in range(26)]

# print(list_result)

# ord(i)-97로 input world의 문자들이 알파벳의 몇 번째 숫자인지 구한다.
for i in input_word:
    # input_word.find(i)로 처음 나온 알파벳의 위치를 입력해준다.
    list_result[ord(i)-97] = input_word.find(i)

for i in list_result:
    print(i, end=" ")


import cv2
import math
import numpy as np
import pyautogui as gui

cap = cv2.VideoCapture(1)
while(cap.isOpened()):
    ret, img = cap.read()
    #cv2.resizeWindow('window1', 768,1366)
    cv2.rectangle(img, (0,0), (200,200), (0,255,0),0) ##left hand rectangle

    cv2.rectangle(img,(630,200),(430,0),(0,255,0),0) ##right hand rectangle

    crop_img = img[0:200, 0:200]
    crop_img2=img[0:200,430:630]

    grey = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY) ## converted it to the grey scale image
    grey2 = cv2.cvtColor(crop_img2,cv2.COLOR_BGR2GRAY)

    value = (35, 35)
    blurred = cv2.GaussianBlur(grey, value, 0)
    blurred2 = cv2.GaussianBlur(grey2,value,0)
    _, thresh1 = cv2.threshold(blurred, 127, 255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
    _, thresh2 = cv2.threshold(blurred2, 127, 255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
    cv2.imshow('Thresholded', thresh1)
    cv2.imshow('Thresholded2', thresh2)

    # check OpenCV version to avoid unpacking error
    (version, _, _) = cv2.__version__.split('.')

    if version == '3':
        image, contours, hierarchy = cv2.findContours(thresh1.copy(), \
               cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    elif version == '2':
        contours, hierarchy = cv2.findContours(thresh1.copy(),cv2.RETR_TREE, \
               cv2.CHAIN_APPROX_NONE)
    else:
        contours,hierarchy=cv2.findContours(thresh1.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
        contours2,hierarchy1=cv2.findContours(thresh2.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

    # find contour with max area
    cnt = max(contours, key = lambda x: cv2.contourArea(x))
    cnt2= max(contours2, key = lambda x: cv2.contourArea(x))

    x, y, w, h = cv2.boundingRect(cnt)
    x2, y2, w2, h2 = cv2.boundingRect(cnt2)
    M = cv2.moments(cnt)
    M2 = cv2.moments(cnt2)
    cx = int(M['m10']/M['m00'])
    cx2 = int(M2['m10']/M2['m00'])
    cy = int(M['m01']/M['m00'])
    cy2 = int(M2['m01']/M2['m00'])

    cv2.circle(crop_img,(cx,cy),1,(255,0,0),6)
    cv2.circle(crop_img2,(cx2,cy2),1,(255,0,0),6)
    cv2.rectangle(crop_img, (x, y), (x+w, y+h), (0, 0, 255), 0)

    cv2.rectangle(crop_img2, (x2, y2), (x2+w2, y2+h2), (0, 0, 255), 0)

    # finding convex hull
    hull = cv2.convexHull(cnt)

    hull2= cv2.convexHull(cnt2)

    drawing = np.zeros(crop_img.shape,np.uint8)
    drawing2 = np.zeros(crop_img2.shape,np.uint8)
    cv2.drawContours(drawing, [cnt], 0, (0, 255, 0), 0)
    cv2.drawContours(drawing, [hull], 0,(0, 0, 255), 0)

    cv2.drawContours(drawing2, [cnt2], 0, (0, 255, 0), 0)
    cv2.drawContours(drawing2, [hull2], 0,(0, 0, 255), 0)

    hull = cv2.convexHull(cnt, returnPoints=False)
    hull2 = cv2.convexHull(cnt2, returnPoints=False)
    defects = cv2.convexityDefects(cnt, hull)
    defects2 = cv2.convexityDefects(cnt2, hull2)
    count_defects = 0
    count_defects2=0
    cv2.drawContours(thresh1, contours, -1, (0, 255, 0), 3)
    # applying Cosine Rule to find angle for all defects (between fingers)
    # with angle > 90 degrees and ignore defects

    ##LeftWindow
    for i in range(defects.shape[0]):
        s,e,f,d = defects[i,0]

        start = tuple(cnt[s][0])
        end = tuple(cnt[e][0])
        far = tuple(cnt[f][0])

        # find length of all sides of triangle
        a = math.sqrt((end[0] - start[0])**2 + (end[1] - start[1])**2)
        b = math.sqrt((far[0] - start[0])**2 + (far[1] - start[1])**2)
        c = math.sqrt((end[0] - far[0])**2 + (end[1] - far[1])**2)

        # apply cosine rule here
        angle = math.acos((b**2 + c**2 - a**2)/(2*b*c)) * 57

        # ignore angles > 90 and highlight rest with red dots
        if angle <= 90:
            count_defects += 1
            cv2.circle(crop_img, far, 1, [0,0,255], -1)

        cv2.line(crop_img,start, end, [0,255,0], 2)

        if count_defects == 1:
            #cv2.putText(img,"I am Vipul", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2)
            gui.moveTo(cx,cy)
        elif count_defects == 2:
            str = "This is a basic hand gesture recognizer"
            #gui.getWindow("Files").maximize()
        elif count_defects == 3:
            cv2.putText(img,"This is 4 :P", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2)
        elif count_defects == 4:
            cv2.putText(img,"Hi!!!", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2)
        else:
            cv2.putText(img,"Hello World!!!", (50, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, 2)

    cv2.drawContours(thresh2, contours2, -1, (255, 0, 0), 3)
    ##Right window
    for i in range(defects2.shape[0]):
        s2,e2,f2,d2 = defects2[i,0]

        start2 = tuple(cnt2[s2][0])
        end2 = tuple(cnt2[e2][0])
        far2 = tuple(cnt2[f2][0])

        # find length of all sides of triangle
        a2 = math.sqrt((end2[0] - start2[0])**2 + (end2[1] - start2[1])**2)
        b2 = math.sqrt((far2[0] - start2[0])**2 + (far2[1] - start2[1])**2)
        c2 = math.sqrt((end2[0] - far2[0])**2 + (end2[1] - far2[1])**2)

        # apply cosine rule here
        angle2 = math.acos((b2**2 + c2**2 - a2**2)/(2*b2*c2)) * 57

        # ignore angles > 90 and highlight rest with red dots
        if angle2 <= 90:
            count_defects2 += 1
            cv2.circle(crop_img2, far2, 1, [0,0,255], -1)

        cv2.line(crop_img2,start2, end2, [0,255,0], 2)

        if count_defects2 == 1:
            cv2.putText(img,"I am Vipul", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2)
            #gui.moveTo(cx,cy)
        elif count_defects2 == 2:
            str = "This is a basic hand gesture recognizer"
            #gui.getWindow("Files").maximize()
        elif count_defects2 == 3:
            cv2.putText(img,"This is 4 :P", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2)
        elif count_defects2 == 4:
            cv2.putText(img,"Hi!!!", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2)
        else:
            cv2.putText(img,"Hello World!!!", (50, 50),cv2.FONT_HERSHEY_SIMPLEX, 2, 2)

    #cv2.namedWindow('window1',cv2.WINDOW_NORMAL)
    cv2.imshow('window1',img)
    cv2.resizeWindow('window1',(600,600))

    k = cv2.waitKey(10)
    if k == 27:
        break


import config
import classes.player
import classes.club

def create_players():
    '''
    ABOUT:
    Creates the players for the game.
    gametype tells us whether it's a single game or a league so that we can generate the right number of players.
    names set to None will allow us to randomly generate them.

    Need to read in a config file that has the race_lookup as well as info to randomly generate names. Probably hold this in JSON so can also say what sort of race the name is suitable for.

    UPDATE:
    Need to allow it to pick up hard-coded players names for clubs in the config file rather than generate random ones every time.
    Prerequisite for this function is that the clubs exist as this will also try and join the players to a club.

    read game for the clubs
    for each club:
        read config file to see if there are any fixed players associated with that club
        if so call the player class with these attributes fed in for the players
        make up the rest to 15 for each club with calls to player class with no parms. At present don't worry about race as only human. Will need to rethink that soon. Feels like an attribute of team as to what sort of races should be possible.
        add player to club
    '''

    '''
    IDEAS:
    race_lookup = {'Human': Human, 'Elf': Elf} - need to look at how this case statement replacement works. Need to read this in from a config file.

    players = []
    for club in clubs:
        if gametype == 'single':
            for 1 to 15:  # 15 is number of players for single game
                players.append(race_lookup[race]{parms...}
                club.add_player_to_club(players[-1])  # adds last player in list to club
                players[-1].add_player_to_club(club.name)

    return players

    '''
    print("starting create_players")
    # iterate through the clubs attribute of game object
    for club in config.game.clubs:
        # get just the team from the config file that relates to this club
        team_data = next(team for team in config.teams_data if team['name'] == club.name)
        if 'players' in team_data:
            # there are some fixed players so create these players
            for player_uuid in team_data['players']:
                # locate the matching player attributes in the config file
                player_data = next(player for player in config.players_data if player['uuid'] == player_uuid)
                # call Player class to create the new player
                player_class = 'classes.player.' + player_data['race']
                player = eval(player_class)(player_data)  # eval allows us to execute strings
                # store the player in the game
                classes.game.Game.add_player(config.game, player)
                classes.club.Club.add_player_to_club(club, player)

        # now need to create any random players to make up the rest of the team
        # for 15 minus len(team_data)['players']

        for _ in range(config.settings_data['players_per_team'] - len(team_data['players'])):
            # need a way to decide which race this player is. Hardcoded as Human currently.
            player = classes.player.Human()
            classes.game.Game.add_player(config.game, player)
            classes.club.Club.add_player_to_club(club, player)

import classes.game


# -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>`
'''

# Import Python Libs
from __future__ import absolute_import

# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
    MagicMock,
    patch,
    NO_MOCK,
    NO_MOCK_REASON
)

ensure_in_syspath('../../')

# Import Salt Libs
from salt.states import mdadm

# Globals
mdadm.__salt__ = {}
mdadm.__opts__ = {}

@skipIf(NO_MOCK, NO_MOCK_REASON)
class MdadmTestCase(TestCase):
    '''
        Validate the mdadm state
    '''
    def test_present(self):
        '''
            Test to verify that the raid is present
        '''
        ret = [{'changes': {}, 'comment': 'Raid salt already present',
                'name': 'salt', 'result': True},
               {'changes': {},
                'comment': "Devices are a mix of RAID constituents"
                " (['dev0']) and non-RAID-constituents(['dev1']).",
                'name': 'salt', 'result': False},
               {'changes': {},
                'comment': 'Raid will be created with: True', 'name': 'salt',
                'result': None},
               {'changes': {}, 'comment': 'Raid salt failed to be created.',
                'name': 'salt', 'result': False}]

        mock = MagicMock(side_effect=[{'salt': True}, {'salt': False},
                                      {'salt': False}, {'salt': False},
                                      {'salt': False}])
        with patch.dict(mdadm.__salt__, {'raid.list': mock}):
            self.assertEqual(mdadm.present("salt", 5, "dev0"), ret[0])

            mock = MagicMock(side_effect=[0, 1])
            with patch.dict(mdadm.__salt__, {'cmd.retcode': mock}):
                self.assertDictEqual(mdadm.present("salt", 5,
                                                   ["dev0", "dev1"]),
                                     ret[1])

            mock = MagicMock(return_value=True)
            with patch.dict(mdadm.__salt__, {'cmd.retcode': mock}):
                with patch.dict(mdadm.__opts__, {'test': True}):
                    with patch.dict(mdadm.__salt__, {'raid.create': mock}):
                        self.assertDictEqual(mdadm.present("salt", 5, "dev0"),
                                             ret[2])

                with patch.dict(mdadm.__opts__, {'test': False}):
                    with patch.dict(mdadm.__salt__, {'raid.create': mock}):
                        self.assertDictEqual(mdadm.present("salt", 5, "dev0"),
                                             ret[3])

    def test_absent(self):
        '''
            Test to verify that the raid is absent
        '''
        ret = [{'changes': {}, 'comment': 'Raid salt already absent',
                'name': 'salt', 'result': True},
               {'changes': {},
                'comment': 'Raid saltstack is set to be destroyed',
                'name': 'saltstack', 'result': None},
               {'changes': {}, 'comment': 'Raid saltstack has been destroyed',
                'name': 'saltstack', 'result': True}]

        mock = MagicMock(return_value=["saltstack"])
        with patch.dict(mdadm.__salt__, {'raid.list': mock}):
            self.assertDictEqual(mdadm.absent("salt"), ret[0])

            with patch.dict(mdadm.__opts__, {'test': True}):
                self.assertDictEqual(mdadm.absent("saltstack"), ret[1])

            with patch.dict(mdadm.__opts__, {'test': False}):
                mock = MagicMock(return_value=True)
                with patch.dict(mdadm.__salt__, {'raid.destroy': mock}):
                    self.assertDictEqual(mdadm.absent("saltstack"), ret[2])

if __name__ == '__main__':
    from integration import run_tests
    run_tests(MdadmTestCase, needs_daemon=False)


# -*- coding: utf-8 -*-
"""
Created on Wed Apr 12 14:13:33 2017
预处理获取小波系数、重构系数、模极大值
对预处理后的序列进行特征提取，包括能量、归一化能量、能量熵、能量矩、排列熵、近似熵、样本熵、最大Lyapunov指数、灰度矩
分形维数、奇异熵
@author: baishuhua
"""

import pywt
import numpy as np
from scipy import stats
import sys
sys.path.append('E:\\大数据\\基础研究\\HilbertHuang变换')
import HilbertHuang
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False

def DWT(signal,wavelet,level):
    # 实数序列进行dwt变换，返回的是不等长的小波系数，[cAn,cDn,cDn-1,...,cD2,cD1]
#    max_level=pywt.dwt_max_level(data_len=len(signal), filter_len=pywt.Wavelet(wavelet).dec_len)
    Coeffs=pywt.wavedec(signal,wavelet=wavelet,mode='smooth',level=level)
    return Coeffs

def DwtRec(signal,wavelet,level):
    # 返回的是每一层的分量，即将原始信号进行了频带分解，时间长度与原始序列signal等长
    # 每一层对应一行
    CoeffsRev=[]
    Coeffs=DWT(signal,wavelet=wavelet,level=level)
    for row in range(level+1):
        if row==0:
            # 重构近似系数，即低频分量
            leveltype=level;part='a'
        else:
            # 重构细节系数，即高频分量
            leveltype=level-row+1;part='d'
        EachLevelRev=pywt.upcoef(part,Coeffs[row],wavelet=wavelet,level=leveltype,take=len(signal))
        CoeffsRev.append(EachLevelRev)
    return np.array(CoeffsRev)

def DwtModMax(signal,wavelet,level):
    # 返回的是细节系数的模极大值序列
    DetailCoeffs=DWT(signal,wavelet=wavelet,level=level)[1:]
    ExtremeX=[];ExtremeY=[]
    for coeff in DetailCoeffs:
        pos=HilbertHuang.findpeaks(coeff)
        neg=HilbertHuang.findpeaks(-coeff)
        xx=np.concatenate((pos,neg))
        yy=np.concatenate((coeff[pos],coeff[neg]))
        index=np.argsort(xx)
        ExtremeX.append(list(xx[index]));ExtremeY.append(list(yy[index]))
    return np.array(ExtremeX),np.array(ExtremeY)

def GetEnergy(coeffs):
    # 能量'Energy'
    Energy=[];EnergyName=[]
    for order,EachLevelCoeff in enumerate(coeffs):
        Energy.append(np.sum(EachLevelCoeff**2))
        EnergyName.append('Energy-L'+str(len(coeffs)-order))
    return np.array(EnergyName),np.array(Energy)

def GetEnergyRatio(coeffs):
    # 归一化能量'EnergyRatio'
    EnergyName,Energy=GetEnergy(coeffs)
    EnergyRatioName=list(map(lambda x:x.replace('Energy','EnergyRatio'),EnergyName))
    EnergyRatio=Energy/np.sum(Energy)
    return np.array(EnergyRatioName),np.array(EnergyRatio)

def Entropy(pk): # 香农熵,pk参数非负代表的是概率
    entropy=stats.entropy(pk,qk=None,base=None)
    return entropy

def GetEnergyEn(coeffs):
    # 能量熵'EnergyEn'
    WEE=[];WEEName=[]
    for order,coeff in enumerate(coeffs):
        pk=coeff**2/np.sum(coeff**2)
        WEE.append(Entropy(pk))
        WEEName.append('EnergyEn-L'+str(len(coeffs)-order))
    return np.array(WEEName),np.array(WEE)

def GetEnergyTq(coeffs):
    # 归一化能量矩'EnergyTq'
    WET=[];WETName=[]
    for order,coeff in enumerate(coeffs):
        weight=np.linspace(1,len(coeff),num=len(coeff))
        WET.append(np.dot(weight,coeff**2))
        WETName.append('EnergyTq-L'+str(len(coeffs)-order))
    WET/=np.sum(WET)
    return np.array(WETName),np.array(WET)

def GetGrayTq(coeffs):
    # 灰度矩'GrayTq'
    m,n=np.shape(coeffs)
    M=0
    for i,j in zip(np.arange(1,m+1),np.arange(1,n+1)):
        M+=abs(coeffs[i-1,j-1])*np.sqrt((i-1)**2+(j-1)**2)
    M/=(m*n)
    return np.array(['GrayTq']),np.array([M])

def GetSingularEn(coeffs):
    # 奇异熵'SingularEn'
    U,s,V=np.linalg.svd(coeffs,full_matrices=True)
    pk=s/np.sum(s)
    WSE=Entropy(pk)
    return np.array(['SingularEn']),np.array([WSE])

def GetFractalDims(coeffs):
    # 分形维数'FractalDims'
    Ref0=np.log2(np.var(np.sum(coeffs,axis=0))) # 原信号方差的对数
    temp=coeffs[1:]
    xx=np.arange(len(coeffs)-1,0,step=-1).ravel()
    yy=np.log2(np.var(temp,axis=1)).ravel()
    yy=np.insert(yy,0,Ref0);xx=np.insert(xx,0,0)
    index=np.argsort(xx)
    xx=xx[index];yy=yy[index]
    params=np.polyfit(xx,yy,1)
    beta=-params[0];D=1.0/2*(5-beta)
    return np.array(['FractalDims']),np.array([D])

def EuclideanDistance(x1,x2):
    return np.sqrt(np.dot(x1-x2,x1-x2))

def DistanceMatrix(X,method=EuclideanDistance):
    Distance=np.zeros((len(X),len(X)))
    for row in np.arange(0,len(X)-1):
        Xi=X[row]
        for col in np.arange(row,len(X)):
            Xj=X[col]
            Distance[row,col]=method(Xi,Xj)
    Distance+=np.transpose(Distance)
    return Distance

def SearchNearest(Distance):
    # 按照行，返回与之距离最近的行编号和距离值
    XPos0=[];YDist0=[]
    for row,dist in enumerate(Distance):
        temp=np.argsort(dist)
        index=temp[temp!=row][0]
        XPos0.append(index)
        YDist0.append(dist[index])
    return XPos0,YDist0

def GetLyapunov(coeffs):
    # 最大Lyapunov指数 'Lyapunov'
    if len(coeffs)==np.size(coeffs):
        coeffs=coeffs[np.newaxis,:]

    m=3;J=5 # 分别对应嵌入维数和延迟参数
    N=np.shape(coeffs)[-1] # 对应时间序列的长度
    M=N-(m-1)*J # 对应相空间重构矩阵的行数
    Lamda=[];LamdaName=[]
    for order,coeff in enumerate(coeffs):
        X=[] # 对应每层小波系数重构的相空间
        for row in range(m):
            X.append(coeff[int(row*J):int(row*J+M)])
        X=np.transpose(np.array(X))

        Distance=DistanceMatrix(X)
        XPos0,YDist0=SearchNearest(Distance)
        # 第i行代表与第i个样本距离最近的样本索引及其最近距离，公式中的j^与dj(0)
        XRef0=np.arange(0,len(Distance))
        # 与XPos0对应的参考样本索引,公式中的j
        lamda=[]
        for indexRef0,indexPos0 in zip(XRef0,XPos0):
            xx=[0];yy=[np.log(YDist0[indexRef0]+1e-10)]
            for bias in range(min(len(XRef0)-indexRef0,len(XRef0)-indexPos0)-1):
                xx.append(bias+1)
                yy.append(np.log(Distance[indexRef0+bias+1,indexPos0+bias+1]+1e-10))

            if len(xx)>1:
                params=np.polyfit(xx,yy,1)
                lamda.append(params[0])
            else:
                continue
        Lamda.append(max(lamda))
        LamdaName.append('Lyapunov-L'+str(len(coeffs)-order))
    return np.array(LamdaName),np.array(Lamda)

def AbsDistance(signal1,signal2):
    return np.max(np.abs((signal1-signal2)))

def GetApEn(coeffs):
    if len(coeffs)==np.size(coeffs):
        coeffs=coeffs[np.newaxis,:]
    ApEn=[]; # 对应近似熵

    PHY=[];
    N=np.shape(coeffs)[-1] # 对应时间序列的长度
    for m in [2,3]: # 对应嵌入维数
        M=N-m+1 # 对应重构矩阵的行数
        PHY_before=[];ApEnName=[]
        for order,coeff in enumerate(coeffs):
            gama=0.2*np.std(coeff) # 对应相似容限
            X=[] # 对应每层小波系数重构的相空间
            for row in range(M):
                X.append(coeff[int(row):int(row+m)])
            Distance=DistanceMatrix(X,method=AbsDistance)

            total=list(map(lambda x:sum(x<=gama)-1,Distance))
            Ci=np.divide(total,float(M-1))
            Ci=Ci[np.nonzero(Ci)]
            PHY_before.append(np.mean(np.log(Ci))) # 对应phy-m
            ApEnName.append('ApEn-L'+str(len(coeffs)-order))
        PHY.append(PHY_before)
    PHY=np.array(PHY)
    ApEn=PHY[0]-PHY[1]

    return np.array(ApEnName),np.array(ApEn)

def GetSampEn(coeffs):
    if len(coeffs)==np.size(coeffs):
        coeffs=coeffs[np.newaxis,:]
    SampEn=[] # 对应样本熵

    B=[]
    N=np.shape(coeffs)[-1] # 对应时间序列的长度
    for m in [2,3]: # 对应嵌入维数
        M=N-m+1 # 对应重构矩阵的行数
        B_before=[];SampEnName=[]
        for order,coeff in enumerate(coeffs):
            gama=0.2*np.std(coeff) # 对应相似容限
            X=[] # 对应每层小波系数重构的相空间
            for row in range(M):
                X.append(coeff[int(row):int(row+m)])
            Distance=DistanceMatrix(X,method=AbsDistance)

            total=list(map(lambda x:sum(x<=gama)-1,Distance))
            Ci=np.divide(total,float(M-1))
            Ci=Ci[np.nonzero(Ci)]
            B_before.append(np.mean(Ci))
            SampEnName.append('SampEn-L'+str(len(coeffs)-order))
        B.append(B_before)
    B=np.array(B)
    SampEn=-np.log(B[1]/B[0]) # 分别对应近似熵和样本熵
    return np.array(SampEnName),np.array(SampEn)

def GetPermuEn(coeffs):
    # 排列熵 'PermutationEn'
    if len(coeffs)==np.size(coeffs):
        coeffs=coeffs[np.newaxis,:]

    m=3;J=5 # 分别对应嵌入维数和延迟参数
    N=np.shape(coeffs)[-1] # 对应时间序列的长度
    M=N-(m-1)*J # 对应相空间重构矩阵的行数
    PermuEn=[];PermuEnName=[]
    for order,coeff in enumerate(coeffs):
        X=[] # 对应每层小波系数重构的相空间
        for row in range(m):
            X.append(coeff[int(row*J):int(row*J+M)])
        X=np.transpose(np.array(X))
        S=list(map(lambda x:np.argsort(x),X))
        S=np.array(S)

        strS=list(map(str,S))
        strCode=list(map(lambda x:'$'.join(x),strS))

        Counts={}
        for each in strCode:
            if each not in Counts.keys():
                Counts[each]=1
            else:
                Counts[each]+=1
        pk=np.divide(list(Counts.values()),len(S))
        PermuEn.append(Entropy(pk))
        PermuEnName.append('PermuEn-L'+str(len(coeffs)-order))
    return np.array(PermuEnName),np.array(PermuEn)

# 综合Dwt变换域指标

def FeatureExtractDwt(signal):
#    FunctionNames=[GetEnergy,GetEnergyRatio,GetEnergyEn,GetEnergyTq,GetGrayTq,GetSingularEn,\
#                   GetFractalDims,GetLyapunov,GetApEn,GetSampEn,GetPermuEn]
    # 仅提取部分特征
    FunctionNames=[GetSingularEn,GetGrayTq,GetFractalDims]
#    if np.size(signal)==len(signal):
#        signal=signal[:,np.newaxis]
    ResultName=[];Result=[]
    for functionname in FunctionNames:
        featurename,feature=functionname(signal)
        ResultName.append(featurename)
        Result.append(feature)
    FeatureValue=np.concatenate(Result)
    FeatureName=np.concatenate(ResultName)
    return FeatureName,FeatureValue

# 示例

def ReadRecord(file): # 读取录波数据
    ReadFlag=open(file)
    ReadFlag.readline();ReadFlag.readline();ReadFlag.readline()
    segnum=ReadFlag.readline().strip().split(':')[1]
    Time=[]
    for seg in range(int(segnum)):
        SampleAttr=ReadFlag.readline().strip().split(' ')
        [fs,start,terminal]=list(map(int,map(float,SampleAttr)))
        if len(Time)<1:
            Time.extend(1/fs*(np.linspace(1,terminal-start+1,num=terminal-start+1)))
        else:
            Time.extend(Time[-1]+1.0/fs*(np.linspace(1,terminal-start+1,num=terminal-start+1)))
    FaultIndex=int(ReadFlag.readline().strip().split('fault_index:')[1])
    FaultTime=Time[FaultIndex]
    SignalNames=ReadFlag.readline().strip().split(' ')
    SignalNames=[name for name in SignalNames if name!='']
    Data=[];ValidIndex=[];row=0
    for record in ReadFlag:
        detail=record.strip().split(' ')
        if len(detail)==len(SignalNames):
            try:
                Data.append(list(map(float,detail)))
                ValidIndex.append(row)
                row=row+1
            except ValueError:
                row=row+1
        else:
            row=row+1
            continue
    ReadFlag.close()
    ValidIndex=np.array(ValidIndex)
    rows=ValidIndex[ValidIndex<len(Time)]
    Time=np.array(Time);Time=Time[rows];Data=np.array(Data);Data=Data[rows];
    return Time,Data,np.array(SignalNames),FaultTime

def Interp(x,y,kind='slinear',axis=0): # 沿axis轴拟合x，y，因变量y沿axis维度应等于x维度
    from scipy import interpolate
    function=interpolate.interp1d(x,y,kind,axis)
    return function

if __name__=='__main__':
    # 模拟数据
    if 0:
#        fs=1000
#        time=np.arange(0,1,step=1/fs)
#        signal=2*np.cos(2*np.pi*50*time)+4+0.25*np.cos(2*np.pi*100*time)+1*np.cos(2*np.pi*150*time)
        fs=1000;f0=50;f1=350;f2=150
        time=np.arange(0,10,step=1/fs);signal=6*np.cos(2*np.pi*f0*time)+2+0.25*np.cos(2*np.pi*f2*time)
        t1=4;t2=6;signal[(time>=t1)&(time<=t2)]+=0.05*np.cos(2*np.pi*f1*time[(time>=t1)&(time<=t2)])

    # 仿真数据
    if 1:
        file = r'E:\关于项目\江苏涌流识别\仿真\bsh\内部故障\5%匝_AB_[0.1 0.12]s.txt'
        ReadFlag = open(file)
        data = []
        for line in ReadFlag:
            attr = line.strip().split(' ')
            attr = list(map(float,attr))
            data.append(attr)
        data = np.array(data)
        signal = data[:,1]
        time = data[:,0]
        fs = 1/(time[1]-time[0])

        coeffs = DwtRec(signal,wavelet='bior3.5',level=4)
        FeatureName,FeatureValue =  FeatureExtractDwt(coeffs)

    # 实测数据
    if 0:
        import os
        file='E:/大数据/线路故障诊断/解压录波/有效集中128/Test-1/异物_1_0_12_港城站_20140510港遂乙线_SSH850.cfg_sub.dat_AN'
        filename=os.path.basename(file)
        attr=filename.split('_')
        FaultCause=attr[0];FaultPhaseNum=attr[1];FaultPhaseType=attr[-1]
        Time,Data,SignalNames,FaultTime=ReadRecord(file)

        SelectRow=(Time>=FaultTime-0.06)&(Time<=FaultTime+0.1) # 截取故障前2个周波，故障后10个周波进行分析
        Time=Time[SelectRow];Data=Data[SelectRow]
        SelectCol=np.array([False,False,False,True,False,False,False,False])
        Data=Data[:,SelectCol] # 选择A相电流
        fitting=Interp(Time,Data,kind='slinear',axis=0)

        fs=1000 # 插值固定的采样率
        TimeNew=np.arange(min(Time),max(Time),step=1.0/fs)[:-1]
        DataNew=fitting(TimeNew)
        time=TimeNew;signal=DataNew.ravel()

    if 1:

        wavelet='bior3.5';level=4
        coeffsRev=DwtRec(signal,wavelet,level)
        fig,axes=plt.subplots(level+1,1,figsize=(6,6))
        for row,ax in enumerate(axes.ravel(),start=1):
            ax.plot(time,coeffsRev[level+1-row]);ax.set_ylabel('尺度'+str(row))
#        axes[0].set_title(FaultCause)
        plt.show()

        if 1:
            plt.plot(time,signal);plt.ylabel('原始信号');
            yrange=max(signal)-min(signal)
            plt.ylim([min(signal)-1/10*yrange,max(signal)+1/10*yrange])
            plt.show()


import os

Import('CfgmEnv')
env = CfgmEnv.Clone()

setup_sources = [
           'setup.py',
           'requirements.txt',
           'MANIFEST.in',
          ]

setup_sources_rules = []
for file in setup_sources:
    setup_sources_rules.append(env.Install(Dir('.'), File(file).srcnode()))

local_sources = [
                  '__init__.py',
                  'zkclient.py',
                  'exceptions.py',
                  'imid.py',
                  'svc_info.py',
                  'vnc_cpu_info.py',
                  'rest.py',
                  'vnc_plugin_base.py',
                  'vnc_extensions.py',
                  'importutils.py',
                  'analytics_client.py',
                 ]
local_sources_rules = []
for file in local_sources:
    local_sources_rules.append(env.Install("cfgm_common", File(file).srcnode()))

ifmap_sources = [ 'ifmap' ]
ifmap_sources_rules = []
for file in ifmap_sources:
    ifmap_sources_rules.append(env.Install("cfgm_common/", "#/third_party/ifmap-python-client/" + file))

test_sources = [
                'tests/__init__.py',
                'tests/test_analytics_client.py',
                'tests/test_importutils.py',
                'tests/fake.py',
               ]
test_sources_rules = []
for file in test_sources:
    test_sources_rules.append(env.Install("cfgm_common/tests/", File(file).srcnode()))

pkg = [env.SandeshGenPy('#controller/src/config/uve/service_instance.sandesh', 'cfgm_common/uve/', False),
       env.SandeshGenPy('#controller/src/config/uve/vnc_api.sandesh', 'cfgm_common/uve/', False),
       env.SandeshGenPy('#controller/src/config/uve/virtual_machine.sandesh', 'cfgm_common/uve/', False),
       env.SandeshGenPy('#controller/src/config/uve/virtual_network.sandesh', 'cfgm_common/uve/', False),
       env.SandeshGenPy('#controller/src/config/uve/acl.sandesh', 'cfgm_common/uve/', False),
       env.SandeshGenPy('#controller/src/config/uve/cfgm_cpuinfo.sandesh', 'cfgm_common/uve/', False),
]

# Generate the sandesh cpuinfo from base
cpu_info_pkg = env.SandeshGenPy('#controller/src/base/sandesh/cpuinfo.sandesh', 'cfgm_common/uve/cfgm_cpuinfo/', False)
process_info_pkg = env.SandeshGenPy('#controller/src/base/sandesh/process_info.sandesh', 'cfgm_common/uve/cfgm_cpuinfo/', False)
env.Depends(cpu_info_pkg, pkg)
env.Depends(process_info_pkg, pkg)

rel_path = Dir('cfgm_common').path
def BuildInfoAction(target, source, env):
    env.GenerateBuildInfoPyCode(path=rel_path)

build_info_rules = [env.Command(target='buildinfo.py', source = None, action=BuildInfoAction)]

sdist_depends = []
sdist_depends.extend(setup_sources_rules)
sdist_depends.extend(local_sources_rules)
sdist_depends.extend(ifmap_sources_rules)
sdist_depends.extend(test_sources_rules)
sdist_depends.extend(pkg)
sdist_depends.extend(cpu_info_pkg)
sdist_depends.extend(process_info_pkg)
sdist_depends.extend(build_info_rules)

# TODO: deprecate
sdist_gen = env.Command('dist/cfgm_common-0.1dev.tar.gz',
                        'setup.py', 'python setup.py sdist', chdir=Dir('.'))

env.Depends(sdist_gen, sdist_depends)
env.Default(sdist_gen)

def BuildPyTestSetup(env, target, source):
    file = open(target[0].abspath, 'w')
    file.write("[easy_install]\nfind_links =")
    for pkg in source:
        dependency = env.File(pkg)
        file.write(" %s" % os.path.dirname(dependency.abspath))
    file.write("\n")
    file.close()
    return

def GeneratePyTestSetup(env, targets, source):
    """
    Generate a setup.cfg file that contains a list of directories
    where dependent packages can be found. The fact that package directory
    list is being given as a source automatically adds them as dependencies.
    """
    target = env.File('setup.cfg')
    return env.Command(target=target, source=source, action=BuildPyTestSetup);

env.Append(BUILDERS = {'PythonTestSetup': GeneratePyTestSetup})
test_sources += env.PythonTestSetup(source=pkg)

test = env.Command('test.log', test_sources,
                   'python setup.py test',
                   chdir=1)

env.Alias('controller/src/config/common:test', test)

if 'install' in BUILD_TARGETS:
    install_cmd = env.Command(None, 'setup.py',
                              'python setup.py install %s' %
                              env['PYTHON_INSTALL_OPT'],
                              chdir = 1)
    env.Depends(install_cmd, sdist_depends)
    env.Alias('install', install_cmd)


#!/usr/bin/env python3

from argparse import ArgumentParser
from collections import namedtuple
import hashlib
import json
import os
import shutil

LayerInfo = namedtuple('LayerInfo', ['path', 'metadata', 'contenthash'])

def hash(data):
    m = hashlib.sha256()
    m.update(bytes(data, 'utf-8'))
    return m.hexdigest()

if __name__ == '__main__':
    parser = ArgumentParser(description='Build image manifest')
    parser.add_argument('layers', nargs='+')
    parser.add_argument('--config', required=True)
    parser.add_argument('--tag', required=True)
    parser.add_argument('--architecture', required=True)
    parser.add_argument('--os', required=True)
    parser.add_argument('--out', required=True)
    opts = parser.parse_args()

    non_empty_layers = []
    for layer_path in opts.layers:
        if os.path.exists(os.path.join(layer_path, 'metadata.json')):
            with open(os.path.join(layer_path, 'metadata.json')) as f:
                metadata = json.load(f)
            with open(os.path.join(layer_path, 'contentsha256')) as f:
                contenthash = f"sha256:{f.read().strip()}"
            non_empty_layers.append(
                LayerInfo(layer_path, metadata, contenthash))

    with open(opts.config) as f:
        container_config = json.load(f)

    config = json.dumps({
        'created': '1970-01-01T00:00:00Z',
        'rootfs': {
            'type': 'layers',
            'diff_ids': list(map(lambda x: x.contenthash, non_empty_layers))
        },
        'config': container_config,
        'architecture': opts.architecture,
        'os': opts.os,
    })

    config_hash = hash(config)

    manifest = json.dumps({
        'schemaVersion': 2,
        'config': {
            'mediaType': 'application/vnd.oci.image.config.v1+json',
            'size': len(config),
            'digest': 'sha256:{}'.format(config_hash)
        },
        'layers': list(map(lambda x: x.metadata, non_empty_layers))
    })

    manifest_hash = hash(manifest)

    metadata_dict = {
        'mediaType': 'application/vnd.oci.image.manifest.v1+json',
        'size': len(manifest),
        'digest': 'sha256:{}'.format(manifest_hash),
        'platform': {
            'architecture': opts.architecture,
            'os': opts.os,
        }
    }

    if opts.tag != '':
        metadata_dict['annotations'] = {
            'org.opencontainers.image.ref.name': opts.tag
        }

    blobs_path = os.path.join(opts.out, 'blobs', 'sha256')
    os.makedirs(blobs_path)

    def open_file(name):
        return open(os.path.join(opts.out, name), 'w', encoding='utf-8')

    with open_file('config.json') as f:
        f.write(config)
        os.symlink(f.name, os.path.join(blobs_path, config_hash))

    with open_file('manifest.json') as f:
        f.write(manifest)
        os.symlink(f.name, os.path.join(blobs_path, manifest_hash))

    with open_file('metadata.json') as f:
        json.dump(metadata_dict, f)

    for layer in non_empty_layers:
        layer_blobs_path = os.path.join(layer.path, 'blobs', 'sha256')
        for path in os.listdir(layer_blobs_path):
            shutil.copyfile(os.path.join(layer_blobs_path, path),
                            os.path.join(blobs_path, path),
                            follow_symlinks=False)


arr = [-2, -3, 4, -1, -2, -1, 5, -3, 8]

first_index = 0
end_index = 0

s = 0
best = 0
for i in range(1, len(arr)):
    s = s + arr[i]
    if(s > 0):
        best = best + s
        end_index = i
    if(arr[i] >= best):
        best = arr[i]
        s = 0
        first_index = i
        end_index = 0

print(first_index)
print(end_index)
print(best)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for :mod:`orion.algo.evolution_es`."""

import copy
import hashlib

import numpy as np
import pytest

from orion.algo.evolution_es import BracketEVES, EvolutionES, compute_budgets
from orion.algo.space import Fidelity, Real, Space

@pytest.fixture
def space():
    """Create a Space with a real dimension and a fidelity value."""
    space = Space()
    space.register(Real("lr", "uniform", 0, 1))
    space.register(Fidelity("epoch", 1, 9, 1))
    return space

@pytest.fixture
def space1():
    """Create a Space with two real dimensions and a fidelity value."""
    space = Space()
    space.register(Real("lr", "uniform", 0, 1))
    space.register(Real("weight_decay", "uniform", 0, 1))
    space.register(Fidelity("epoch", 1, 8, 2))
    return space

@pytest.fixture
def space2():
    """Create a Space with two real dimensions."""
    space = Space()
    space.register(Real("lr", "uniform", 0, 1))
    space.register(Real("weight_decay", "uniform", 0, 1))
    return space

@pytest.fixture
def budgets():
    """Return a configuration for a bracket."""
    return [(30, 4), (30, 5), (30, 6)]

@pytest.fixture
def evolution(space1):
    """Return an instance of EvolutionES."""
    return EvolutionES(space1, repetitions=1, nums_population=4)

@pytest.fixture
def bracket(budgets, evolution, space1):
    """Return a `Bracket` instance configured with `b_config`."""
    return BracketEVES(evolution, budgets, 1, space1)

@pytest.fixture
def evolution_customer_mutate(space1):
    """Return an instance of EvolutionES."""
    return EvolutionES(
        space1,
        repetitions=1,
        nums_population=4,
        mutate="orion.core.utils.tests.customized_mutate_example",
    )

@pytest.fixture
def rung_0():
    """Create fake points and objectives for rung 0."""
    points = np.linspace(0, 8, 9)
    return dict(
        n_trials=9,
        resources=1,
        results={
            hashlib.md5(str([point]).encode("utf-8")).hexdigest(): (point, (1, point))
            for point in points
        },
    )

@pytest.fixture
def rung_1(rung_0):
    """Create fake points and objectives for rung 1."""
    values = map(
        lambda v: (v[0], (3, v[0])), list(sorted(rung_0["results"].values()))[:3]
    )
    return dict(
        n_trials=3,
        resources=3,
        results={
            hashlib.md5(str([value[0]]).encode("utf-8")).hexdigest(): value
            for value in values
        },
    )

@pytest.fixture
def rung_2(rung_1):
    """Create fake points and objectives for rung 2."""
    values = map(
        lambda v: (v[0], (9, v[0])), list(sorted(rung_1["results"].values()))[:1]
    )
    return dict(
        n_trials=1,
        resources=9,
        results={
            hashlib.md5(str([value[0]]).encode("utf-8")).hexdigest(): value
            for value in values
        },
    )

@pytest.fixture
def rung_3():
    """Create fake points and objectives for rung 3."""
    points = np.linspace(1, 4, 4)
    return dict(
        n_trials=4,
        resources=1,
        results={
            hashlib.md5(str([point]).encode("utf-8")).hexdigest(): (
                point,
                (np.power(2, (point - 1)), 1.0 / point, 1.0 / (point * point)),
            )
            for point in points
        },
    )

@pytest.fixture
def rung_4():
    """Create duplicated fake points and objectives for rung 4."""
    points = np.linspace(1, 4, 4)
    return dict(
        n_trials=4,
        resources=1,
        results={
            hashlib.md5(str([point]).encode("utf-8")).hexdigest(): (
                point,
                (1, point // 2, point // 2),
            )
            for point in points
        },
    )

def test_compute_budgets():
    """Verify proper computation of budgets on a logarithmic scale"""
    # Check typical values
    assert compute_budgets(1, 3, 1, 2, 1) == [[(2, 1), (2, 2), (2, 3)]]
    assert compute_budgets(1, 4, 2, 4, 2) == [[(4, 1), (4, 2), (4, 4)]]

def test_customized_mutate_population(space1, rung_3, budgets):
    """Verify customized mutated candidates is generated correctly."""
    customerized_dict = {
        "function": "orion.testing.state.customized_mutate_example",
        "multiply_factor": 2.0,
        "add_factor": 1,
    }
    algo = EvolutionES(
        space1, repetitions=1, nums_population=4, mutate=customerized_dict
    )
    algo.brackets[0] = BracketEVES(algo, budgets, 1, space1)

    red_team = [0, 2]
    blue_team = [1, 3]
    population_range = 4
    for i in range(4):
        for j in [1, 2]:
            algo.brackets[0].eves.population[j][i] = list(rung_3["results"].values())[
                i
            ][1][j]
        algo.brackets[0].eves.performance[i] = list(rung_3["results"].values())[i][0]

    org_data = np.stack(
        (
            list(algo.brackets[0].eves.population.values())[0],
            list(algo.brackets[0].eves.population.values())[1],
        ),
        axis=0,
    ).T

    org_data = copy.deepcopy(org_data)

    algo.brackets[0]._mutate_population(
        red_team, blue_team, rung_3["results"], population_range
    )

    mutated_data = np.stack(
        (
            list(algo.brackets[0].eves.population.values())[0],
            list(algo.brackets[0].eves.population.values())[1],
        ),
        axis=0,
    ).T

    # Winner team will be [0, 2], so [0, 2] will be remained, [1, 3] will be mutated.
    assert org_data.shape == mutated_data.shape
    assert (mutated_data[0] == org_data[0]).all()
    assert (mutated_data[2] == org_data[2]).all()
    assert (mutated_data[1] != org_data[1]).any()
    assert (mutated_data[3] != org_data[3]).any()
    assert (mutated_data[1] != org_data[0]).any()
    assert (mutated_data[3] != org_data[2]).any()

    # For each individual, mutation occurs in only one dimension chosen from two.
    # Customized test mutation function is divided by 2 for real type.
    if mutated_data[1][0] == org_data[0][0] / customerized_dict["multiply_factor"]:
        assert mutated_data[1][1] == org_data[0][1]
    else:
        assert (
            mutated_data[1][1] == org_data[0][1] / customerized_dict["multiply_factor"]
        )

    if mutated_data[3][0] == org_data[2][0] / customerized_dict["multiply_factor"]:
        assert mutated_data[3][1] == org_data[2][1]
    else:
        assert (
            mutated_data[3][1] == org_data[2][1] / customerized_dict["multiply_factor"]
        )

class TestEvolutionES:
    """Tests for the algo Evolution."""

    def test_register(self, evolution, bracket, rung_0, rung_1):
        """Check that a point is registered inside the bracket."""
        evolution.brackets = [bracket]
        bracket.hyperband = evolution
        bracket.eves = evolution
        bracket.rungs = [rung_0, rung_1]
        point = (1, 0.0)
        point_hash = hashlib.md5(str([0.0]).encode("utf-8")).hexdigest()

        evolution.observe([point], [{"objective": 0.0}])

        assert len(bracket.rungs[0])
        assert point_hash in bracket.rungs[0]["results"]
        assert (0.0, point) == bracket.rungs[0]["results"][point_hash]

class TestBracketEVES:
    """Tests for `BracketEVES` class.."""

    def test_get_teams(self, bracket, rung_3):
        """Test that correct team is promoted."""
        bracket.rungs[0] = rung_3
        rung, population_range, red_team, blue_team = bracket._get_teams(0)
        assert len(list(rung.values())) == 4
        assert bracket.search_space_remove_fidelity == [1, 2]
        assert population_range == 4
        assert set(red_team).union(set(blue_team)) == {0, 1, 2, 3}
        assert set(red_team).intersection(set(blue_team)) == set()

    def test_mutate_population(self, bracket, rung_3):
        """Verify mutated candidates is generated correctly."""
        red_team = [0, 2]
        blue_team = [1, 3]
        population_range = 4
        for i in range(4):
            for j in [1, 2]:
                bracket.eves.population[j][i] = list(rung_3["results"].values())[i][1][
                    j
                ]
            bracket.eves.performance[i] = list(rung_3["results"].values())[i][0]

        org_data = np.stack(
            (
                list(bracket.eves.population.values())[0],
                list(bracket.eves.population.values())[1],
            ),
            axis=0,
        ).T

        org_data = copy.deepcopy(org_data)

        bracket._mutate_population(
            red_team, blue_team, rung_3["results"], population_range
        )

        mutated_data = np.stack(
            (
                list(bracket.eves.population.values())[0],
                list(bracket.eves.population.values())[1],
            ),
            axis=0,
        ).T

        # Winner team will be [0, 2], so [0, 2] will be remained, [1, 3] will be mutated.
        assert org_data.shape == mutated_data.shape
        assert (mutated_data[0] == org_data[0]).all()
        assert (mutated_data[2] == org_data[2]).all()
        assert (mutated_data[1] != org_data[1]).any()
        assert (mutated_data[3] != org_data[3]).any()
        assert (mutated_data[1] != org_data[0]).any()
        assert (mutated_data[3] != org_data[2]).any()

        # For each individual, mutation occurs in only one dimension chosen from two.
        if mutated_data[1][0] != org_data[0][0]:
            assert mutated_data[1][1] == org_data[0][1]
        else:
            assert mutated_data[1][1] != org_data[0][1]

        if mutated_data[3][0] != org_data[2][0]:
            assert mutated_data[3][1] == org_data[2][1]
        else:
            assert mutated_data[3][1] != org_data[2][1]

    def test_duplicated_mutated_population(self, bracket, rung_4):
        """Verify duplicated candidates can be found and processed correctly."""
        red_team = [0, 2]
        blue_team = [0, 2]  # no mutate occur at first.
        population_range = 4
        for i in range(4):
            for j in [1, 2]:
                bracket.eves.population[j][i] = list(rung_4["results"].values())[i][1][
                    j
                ]
        points, nums_all_equal = bracket._mutate_population(
            red_team, blue_team, rung_4["results"], population_range
        )

        # In this case, duplication will occur, and we can make it mutate one more time.
        # The points 1 and 2 should be different, while one of nums_all_equal should be 1.
        if points[1][1] != points[2][1]:
            assert points[1][2] == points[2][2]
        else:
            assert points[1][2] != points[2][2]

        assert nums_all_equal[0] == 0
        assert nums_all_equal[1] == 0
        assert nums_all_equal[2] == 1
        assert nums_all_equal[3] == 0

    def test_mutate_points(self, bracket, rung_3):
        """Test that correct point is promoted."""
        red_team = [0, 2]
        blue_team = [0, 2]
        population_range = 4
        for i in range(4):
            for j in [1, 2]:
                bracket.eves.population[j][i] = list(rung_3["results"].values())[i][1][
                    j
                ]
        points, nums_all_equal = bracket._mutate_population(
            red_team, blue_team, rung_3["results"], population_range
        )
        assert points[0] == (1.0, 1.0, 1.0)
        assert points[1] == (2, 1.0 / 2, 1.0 / 4)
        assert (nums_all_equal == 0).all()


import retrogamelib as rgl
import pygame, random, sys, os
from retrogamelib.constants import *

from objects import spritesheet, flip_images

class Intro(object):

    def __init__(self):
        load_image = rgl.util.load_image
        self.oldman1 = spritesheet("data/lawn-mower.png", (96, 96))
        self.bubbman1 = spritesheet("data/bubbman.png", (24, 26))[:3]
        self.bubbman2 = flip_images(self.bubbman1)
        self.ground = spritesheet("data/grass-2.png", (24, 24))[1]
        self.fg = load_image("data/hills-front-1.png")
        self.fg2 = load_image("data/hills-back.png")
        self.bg = load_image("data/background-1.png")
        self.font_white = rgl.font.Font(NES_FONT, (255, 255, 255))
        self.font_black = rgl.font.Font(NES_FONT, (1, 1, 1))
        self.frame = 0
        self.pos = 0
        self.bpos = [200, 240-26-20]
        self.opos = [0, 240-96-20]
        self.ochasing = True
        self.run_away = False
        self.stopped = None
        self.boom = rgl.util.play_sound("data/motor.ogg", 0.5)
        self.boom.stop()

    def loop(self):
        self.running = True
        self.ypos = 256
        pygame.mixer.music.stop()
        while self.running:
            self.frame += 1
            rgl.clock.tick()
            rgl.button.handle_input()
            screen = rgl.display.get_surface()
            screen.blit(self.bg, (0, 0))
            xpos = (self.pos/4) % 256
            screen.blit(self.fg2, (xpos, 50))
            screen.blit(self.fg2, (xpos+256, 50))
            screen.blit(self.fg2, (xpos-256, 50))
            xpos = (self.pos/2) % 256
            screen.blit(self.fg, (xpos, 50))
            screen.blit(self.fg, (xpos+256, 50))
            screen.blit(self.fg, (xpos-256, 50))
            for x in range(256/24 + 2):
                p = self.pos % 256
                screen.blit(self.ground, (((x*24 - 24) + p % 24), 240-24))
            if rgl.button.is_pressed(START) or rgl.button.is_pressed(A_BUTTON):
                self.running = False
            bframe = 0
            oframe = 0
            if self.bpos[0] > 128 and not self.run_away:
                self.bpos[0] -= 3
                bframe = self.frame/4%2 + 1
            else:
                if self.stopped == None:
                    self.stopped = 60
                self.stopped -= 1
                if self.stopped == 30:
                    rgl.util.play_sound("data/yell.ogg")
                if self.stopped < 30:
                    self.render_text(screen, "Get off my lawn!!", (128+self.opos[0], 100), 1)
                if self.stopped <= 0:
                    self.run_away = True
            if self.run_away:
                self.bpos[0] += 3
                self.opos[0] += 3
                bframe = self.frame/4%2 + 1
                oframe = self.frame/4%2
                self.bubbman2 = self.bubbman1
                if not pygame.mixer.get_busy():
                    self.boom.play(-1)
            if self.opos[0] > 280:
                self.running = False
            if self.opos[0] > 270:
                self.boom.stop()
            screen.blit(self.bubbman2[bframe], self.bpos)
            screen.blit(self.oldman1[oframe], self.opos)
            rgl.display.update()
        self.boom.stop()

    def render_text(self, surface, text, pos, center=False):
        ren1 = self.font_black.render(text)
        ren2 = self.font_white.render(text)
        p = pos
        if center:
            p = (pos[0] - ren1.get_width()/2, pos[1])
        surface.blit(ren1, (p[0], p[1]+1))
        surface.blit(ren1, (p[0], p[1]-1))
        surface.blit(ren1, (p[0]+1, p[1]))
        surface.blit(ren1, (p[0]-1, p[1]))
        surface.blit(ren2, (p[0], p[1]))
        del ren1, ren2


#!/usr/bin/env python3

import argparse
import sys

from KaSaAn.functions import prefixed_snapshot_analyzer

def main(args=None):
    if args is None:
        args = sys.argv[1:]
    parser = argparse.ArgumentParser(
        description='Get cumulative and mean distribution of complex sizes, plus distribution of number of species,'
                    ' based on snapshots sharing a common prefix, like "t_one_snap_7.ka" having the prefix "t_one_".'
                    ' Snapshots must contain the word "snap" and end in ".ka". Files will be produced in the same'
                    ' directory as the snapshots are. They will be prefixed accordingly, e.g.'
                    ' [prefix]distribution_cumulative.csv')
    parser.add_argument('-p', '--prefix', type=str, default='',
                        help='Prefix identifying snapshots to analyze; e.g. "foo_snap_" is the prefix for'
                             ' "foo_snap_76.ka". Files must end with [number].ka')
    parser.add_argument('-d', '--working_directory', type=str, default='./',
                        help='The directory where snapshots are held, and where distribution files will be saved to.')
    parser.add_argument('-v', '--verbosity', action='store_true',
                        help='Print extra information, like number of snapshots found, directory understood, and'
                             ' file names used for output.')
    args = parser.parse_args()
    prefixed_snapshot_analyzer(base_directory=args.working_directory, snap_prefix=args.prefix, verbosity=args.verbosity)

if __name__ == '__main__':
    main()