"""
MIT License

Copyright (c) 2021 TheHamkerCat

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import asyncio
import os
from datetime import datetime
from random import shuffle

from pykeyboard import InlineKeyboard
from pyrogram import filters
from pyrogram.errors.exceptions.bad_request_400 import (
    ChatAdminRequired,
    UserNotParticipant,
)
from pyrogram.types import (
    ChatPermissions,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    Message,
    User,
)

from wbb import SUDOERS, WELCOME_DELAY_KICK_SEC, app
from wbb.core.decorators.errors import capture_err
from wbb.core.decorators.permissions import adminsOnly
from wbb.utils.dbfunctions import (
    captcha_off,
    captcha_on,
    del_welcome,
    get_captcha_cache,
    get_welcome,
    is_captcha_on,
    is_gbanned_user,
    set_welcome,
    update_captcha_cache,
)
from wbb.utils.filter_groups import welcome_captcha_group
from wbb.utils.functions import generate_captcha

__MODULE__ = "Greetings"
__HELP__ = """
/captcha [ENABLE|DISABLE] - Enable/Disable captcha.

/set_welcome - Reply this to a message containing correct
format for a welcome message, check end of this message.

/del_welcome - Delete the welcome message.
/get_welcome - Get the welcome message.

**SET_WELCOME ->**

The format should be something like below.

```
**Hi** {name} Welcome to {chat}

~ #This separater (~) should be there between text and buttons, remove this comment also

button=[Duck, https://duckduckgo.com]
button2=[Github, https://github.com]
```

**NOTES ->**

for /rules, you can do /filter rules to a message
containing rules of your groups whenever a user
sends /rules, he'll get the message
"""

answers_dicc = []
loop = asyncio.get_running_loop()

async def get_initial_captcha_cache():
    global answers_dicc
    answers_dicc = await get_captcha_cache()
    return answers_dicc

loop.create_task(get_initial_captcha_cache())

@app.on_message(filters.new_chat_members, group=welcome_captcha_group)
@capture_err
async def welcome(_, message: Message):
    global answers_dicc
    """ Get cached answers from mongodb in case of bot's been restarted or crashed. """
    answers_dicc = await get_captcha_cache()
    """Mute new member and send message with button"""
    if not await is_captcha_on(message.chat.id):
        return
    for member in message.new_chat_members:
        try:
            if member.id in SUDOERS:
                continue  # ignore sudos
            if await is_gbanned_user(member.id):
                await message.chat.kick_member(member.id)
                await message.reply_text(
                    f"{member.mention} was globally banned, and got removed,"
                    + " if you think this is a false gban, you can appeal"
                    + " for this ban in support chat."
                )
                continue
            if member.is_bot:
                continue  # ignore bots
            await message.chat.restrict_member(member.id, ChatPermissions())
            text = (
                f"{(member.mention())} Are you human?\n"
                f"Solve this captcha in {WELCOME_DELAY_KICK_SEC} seconds and 4 attempts or you'll be kicked."
            )
        except ChatAdminRequired:
            return
        # Generate a captcha image, answers and some wrong answers
        captcha = generate_captcha()
        captcha_image = captcha[0]
        captcha_answer = captcha[1]
        wrong_answers = captcha[2]  # This consists of 8 wrong answers
        correct_button = InlineKeyboardButton(
            f"{captcha_answer}",
            callback_data=f"pressed_button {captcha_answer} {member.id}",
        )
        temp_keyboard_1 = [correct_button]  # Button row 1
        temp_keyboard_2 = []  # Botton row 2
        temp_keyboard_3 = []
        for i in range(2):
            temp_keyboard_1.append(
                InlineKeyboardButton(
                    f"{wrong_answers[i]}",
                    callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
                )
            )
        for i in range(2, 5):
            temp_keyboard_2.append(
                InlineKeyboardButton(
                    f"{wrong_answers[i]}",
                    callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
                )
            )
        for i in range(5, 8):
            temp_keyboard_3.append(
                InlineKeyboardButton(
                    f"{wrong_answers[i]}",
                    callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
                )
            )

        shuffle(temp_keyboard_1)
        keyboard = [temp_keyboard_1, temp_keyboard_2, temp_keyboard_3]
        shuffle(keyboard)
        verification_data = {
            "chat_id": message.chat.id,
            "user_id": member.id,
            "answer": captcha_answer,
            "keyboard": keyboard,
            "attempts": 0,
        }
        keyboard = InlineKeyboardMarkup(keyboard)
        # Append user info, correct answer and
        answers_dicc.append(verification_data)
        # keyboard for later use with callback query
        button_message = await message.reply_photo(
            photo=captcha_image,
            caption=text,
            reply_markup=keyboard,
            quote=True,
        )
        os.remove(captcha_image)
        """ Save captcha answers etc in mongodb in case bot gets crashed or restarted. """
        await update_captcha_cache(answers_dicc)
        asyncio.create_task(
            kick_restricted_after_delay(WELCOME_DELAY_KICK_SEC, button_message, member)
        )
        await asyncio.sleep(0.5)

async def send_welcome_message(callback_query, pending_user_id):
    try:
        raw_text = await get_welcome(callback_query.message.chat.id)
    except TypeError:
        return
    raw_text = raw_text.strip().replace("`", "")
    if not raw_text:
        return
    text = raw_text.split("~")[0].strip()
    buttons_text_list = raw_text.split("~")[1].strip().splitlines()
    if "{chat}" in text:
        text = text.replace("{chat}", callback_query.message.chat.title)
    if "{name}" in text:
        text = text.replace("{name}", (await app.get_users(pending_user_id)).mention)
    buttons = InlineKeyboard(row_width=2)
    list_of_buttons = []
    for button_string in buttons_text_list:
        button_string = button_string.strip().split("=")[1].strip()
        button_string = button_string.replace("[", "").strip()
        button_string = button_string.replace("]", "").strip()
        button_string = button_string.split(",")
        button_text = button_string[0].strip()
        button_url = button_string[1].strip()
        list_of_buttons.append(InlineKeyboardButton(text=button_text, url=button_url))
    buttons.add(*list_of_buttons)
    await app.send_message(
        callback_query.message.chat.id,
        text=text,
        reply_markup=buttons,
        disable_web_page_preview=True,
    )

@app.on_callback_query(filters.regex("pressed_button"))
async def callback_query_welcome_button(_, callback_query):
    """After the new member presses the correct button,
    set his permissions to chat permissions,
    delete button message and join message.
    """
    global answers_dicc
    data = callback_query.data
    pressed_user_id = callback_query.from_user.id
    pending_user_id = int(data.split(None, 2)[2])
    button_message = callback_query.message
    answer = data.split(None, 2)[1]
    if len(answers_dicc) != 0:
        for i in answers_dicc:
            if (
                i["user_id"] == pending_user_id
                and i["chat_id"] == button_message.chat.id
            ):
                correct_answer = i["answer"]
                keyboard = i["keyboard"]
    if pending_user_id == pressed_user_id:
        if answer != correct_answer:
            await callback_query.answer("Yeah, It's Wrong.")
            for iii in answers_dicc:
                if (
                    iii["user_id"] == pending_user_id
                    and iii["chat_id"] == button_message.chat.id
                ):
                    attempts = iii["attempts"]
                    if attempts >= 3:
                        answers_dicc.remove(iii)
                        await button_message.chat.kick_member(pending_user_id)
                        await asyncio.sleep(1)
                        await button_message.chat.unban_member(pending_user_id)
                        await button_message.delete()
                        await update_captcha_cache(answers_dicc)
                        return
                    else:
                        iii["attempts"] += 1
                        break
            shuffle(keyboard[0])
            shuffle(keyboard[1])
            shuffle(keyboard[2])
            shuffle(keyboard)
            keyboard = InlineKeyboardMarkup(keyboard)
            await button_message.edit(
                text=button_message.caption.markdown,
                reply_markup=keyboard,
            )
            return
        await callback_query.answer("Captcha passed successfully!")
        await button_message.chat.unban_member(pending_user_id)
        await button_message.delete()
        if len(answers_dicc) != 0:
            for ii in answers_dicc:
                if (
                    ii["user_id"] == pending_user_id
                    and ii["chat_id"] == button_message.chat.id
                ):
                    answers_dicc.remove(ii)
                    await update_captcha_cache(answers_dicc)
        """ send welcome message """
        await send_welcome_message(callback_query, pending_user_id)
        return
    else:
        await callback_query.answer("This is not for you")
        return

async def kick_restricted_after_delay(delay, button_message: Message, user: User):
    """If the new member is still restricted after the delay, delete
    button message and join message and then kick him
    """
    global answers_dicc
    await asyncio.sleep(delay)
    join_message = button_message.reply_to_message
    group_chat = button_message.chat
    user_id = user.id
    await join_message.delete()
    await button_message.delete()
    if len(answers_dicc) != 0:
        for i in answers_dicc:
            if i["user_id"] == user_id:
                answers_dicc.remove(i)
                await update_captcha_cache(answers_dicc)
    await _ban_restricted_user_until_date(group_chat, user_id, duration=delay)

async def _ban_restricted_user_until_date(group_chat, user_id: int, duration: int):
    try:
        member = await group_chat.get_member(user_id)
        if member.status == "restricted":
            until_date = int(datetime.utcnow().timestamp() + duration)
            await group_chat.kick_member(user_id, until_date=until_date)
    except UserNotParticipant:
        pass

@app.on_message(filters.command("captcha") & ~filters.private)
@adminsOnly("can_restrict_members")
async def captcha_state(_, message):
    usage = "**Usage:**\n/captcha [ENABLE|DISABLE]"
    if len(message.command) != 2:
        await message.reply_text(usage)
        return
    chat_id = message.chat.id
    state = message.text.split(None, 1)[1].strip()
    state = state.lower()
    if state == "enable":
        await captcha_on(chat_id)
        await message.reply_text("Enabled Captcha For New Users.")
    elif state == "disable":
        await captcha_off(chat_id)
        await message.reply_text("Disabled Captcha For New Users.")
    else:
        await message.reply_text(usage)

""" WELCOME MESSAGE """

@app.on_message(filters.command("set_welcome") & ~filters.private)
@adminsOnly("can_change_info")
async def set_welcome_func(_, message):
    usage = "You need to reply to a text, check the Greetings module in /help"
    if not message.reply_to_message:
        await message.reply_text(usage)
        return
    if not message.reply_to_message.text:
        await message.reply_text(usage)
        return
    chat_id = message.chat.id
    raw_text = str(message.reply_to_message.text.markdown)
    await set_welcome(chat_id, raw_text)
    await message.reply_text("Welcome message has been successfully set.")

@app.on_message(filters.command("del_welcome") & ~filters.private)
@adminsOnly("can_change_info")
async def del_welcome_func(_, message):
    chat_id = message.chat.id
    await del_welcome(chat_id)
    await message.reply_text("Welcome message has been deleted.")

@app.on_message(filters.command("get_welcome") & ~filters.private)
@adminsOnly("can_change_info")
async def get_welcome_func(_, message):
    chat_id = message.chat.id
    welcome_message = await get_welcome(chat_id)
    await message.reply_text(welcome_message)


"""
  datasources_factory.py

  returns various data sources to be used
"""

import torch
from torchvision import datasets, transforms
import os

def datasources_factory(dataset_name, dataset_params):
     """
         creates one of a few implementations of a data source. we return None if we are unable to create
         the requested data source
     """

     if dataset_name == 'font-1':

         data_transforms = {
             'train': transforms.Compose([
                 transforms.Resize(size=(224, 224)),
                 transforms.ToTensor(),
                 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
             ]),
             'val': transforms.Compose([
                 transforms.Resize(size=(224, 224)),
                 transforms.ToTensor(),
                 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
             ]),
         }

         print("Initializing Datasets and Dataloaders...")

         data_type = dataset_params.get('data_type', ['train','val'])
         # Create training and validation datasets
         image_datasets = {x: datasets.ImageFolder(os.path.join(dataset_params['root_dir'], x), data_transforms[x]) for x in data_type}
         # Create training and validation dataloaders
         dataloaders_dict = {
         x: torch.utils.data.DataLoader(image_datasets[x], batch_size=dataset_params['batch_size'], shuffle=True, num_workers=4) for x in data_type}

         return dataloaders_dict

     return None


# -*- coding: utf-8 -*-
ItemsID   = {0:"Little Boat",
             1:"Walking Shoes",
             2:"Ring Of Life",
             3:"Ring Of Mana",
             4:"Ring Of Healing",
             5:"Mana Renewal Ring",
             6:"Knive",
             7:"Bow",
             8:"Stick of fire",
             9:"Sword",
             10:"Crossbow",
             11:"Hammer",
             12:"Axe",
             13:"Destroying Wand",
             14:"Admin Staff"
             }
cenaItemu = {0:50,
             1:100,
             2:200,
             3:200,
             4:500,
             5:400,
             6:20,
             7:50,
             8:1000,
             9:200,
             10:200,
             11:100,
             12:120,
             13:5000,
             14:1000000000000
             }
ItemsType = {0:[0],
             1:[1],
             2:[2],
             3:[2],
             4:[2],
             5:[2],
             6:[3],
             7:[4],
             8:[3],
             9:[3],
             10:[4],
             11:[4],
             12:[3],
             13:[4],
             14:[5]
             }
# 0 = ostatní, 1 = boty, 2=Prsten(muže mít až 10 ale ne stejných), 3=jednoručná zbraň(muže mít až 2 ale ne stejných), 4=obouručná zbraň, 5=zbran kterou můžou nosit jen postavy, které jsou vytvořeny ručně
ItemsInfo={0:[4,"Little Boat","You can walk over the water","Price: 50"],
           1:[4,"Walking Shoes","+5 move per turn","Price: 100"],
           2:[4,"Ring Of Life","+50 Lives","Price: 200"],
           3:[4,"Ring Of Mana","+50 Mana","Price: 200"],
           4:[4,"Ring Of Healing","+1 Lives per move","Price: 500"],
           5:[4,"Mana Renewal Ring","+1 Mana per move","Price: 400"],
           6:[4,"Knive","Knife attack(-20 hp)","Price: 20"],
           7:[4,"Bow","Bow attack(-30hp)","Price: 50"],
           8:[5,"Stick of fire","Stick strike(-20hp), Firebolt(-25hp,-25mana),","Fireball(-50hp,-60mana), Ignition(-35hp-40mana)","Price: 1000"],
           9:[4,"Sword","Sword swing(-40hp)","Price: 200"],
           10:[4,"Crossbow","Crossbow shoot(-35hp)","Price: 200"],
           11:[4,"Hammer","Hammer slam(-30hp)","Price: 100"],
           12:[4,"Axe","Axe slash(-30hp)","Price: 120"],
           13:[4,"Destroying Wand","Destruction(-10 000hp,-5 000mana)","Price: 5 000"],
           14:[5,"Admin Staff","Server Kick(-100 000 000 000hp)","Only Admin can equip","Price: 1 000 000 000 000"]
           }

popisky={"Knife attack ":["-20 Enemy lives","-0 Your mana"],
         "Bow attack ":["-30 Enemy live","-0 Your mana"],
         "Stick strike ":["-20 Enemy lives","-0 Your mana"],
         "Firebolt ":["-25 Enemy live","-25 Your mana"],
         "Fireball ":["-50 Enemy lives","-60 Your mana"],
         "ignition ":["-35 Enemy lives","-40 Your mana"],
         "Sword swing ":["-40 Enemy lives","-0 Your mana"],
         "Crossbow shoot ":["-35 Enemy lives","-0 Your mana"],
         "Hammer slam ":["-30 Enemy lives","-0 Your mana"],
         "Axe slash ":["-30 Enemy lives","-0 Your mana"],
         "Destruction ":["-10 000 Enemy lives","-5 000 Your mana"],
         "Smash ":["-10 Enemy lives","-0 Your mana"],
         "Server Kick ":["-100 000 000 000 Enemy lives","-0 Your mana"]
         }


def is_prime(n):
    if type(n) != int:
        # type check was missed
        raise TypeError()
    elif n <= 1:
        # value range check was missed
        raise ValueError()

    # error was here: range(2, k) doesn't include k
    # hence, for example, for 9 only divisor 2 will be checked
    for divisor in range(2, int(n ** 0.5) + 1):
        if n % divisor == 0:
            return False
    return True

if __name__ == '__main__':
    n = int(input())
    try:
        answer = is_prime(n)
    except ValueError:
        print('NO')
    else:
        print('YES') if answer else print('NO')

2nd_year/Цели и подходы к тестированию. Создание «самодельных» тестов (без библиотек)/Исправление ошибок в is_prime().py

Исправление ошибок в is_prime().py


import sys, time, os
import argparse
from PD_Amino_Acid_dict import * # import AA convertion dictionary
import re

# function to check stability of delta delta G value
def stability_check(data):

	# list for stability categories
	stab_list = ['highly de-stabilizing', 'de-stabilizing', 'slightly de-stabilizing',
	'neutral',
	'slightly stabilizing', 'stabilizing', 'highly stabilizing']

	# stability criterion
	if (data > 1.84):
		return(stab_list[0]) # highly de-stabilizing
	elif (data <= 1.84) & (data > 0.92):
		return(stab_list[1]) # de-stabilizing
	elif (data <= 0.92) & (data > 0.46):
		return(stab_list[2]) # slightly de-stabilizing
	elif (data <= 0.46) & (data > -0.46):
		return(stab_list[3]) # neutral
	elif (data <= -0.46) & (data > -0.92):
		return(stab_list[4]) # slightly stabilizing
	elif (data <= -0.92) & (data > -1.84):
		return(stab_list[5]) # stabilizing
	else:
		return(stab_list[6]) # highly stabilizing

# function to make tabular info for each mutation with info like Position, delta delta G value, stability
def foldx_process(delta_G_file, mutant_file, repair_pdb_name):

	delta_G_list = [] # list to store delta delta G value
	delta_G_stab = [] # list to store category
	repair_pdb_with_no_extention = repair_pdb_name.split('.')[0] # model names common term

	with open(delta_G_file, 'r') as f_in_delta_G: #open avg delta delta G file
		for line in f_in_delta_G:
			line = line.strip('\n')
			if re.search(repair_pdb_with_no_extention, line): # check only models lines
				line = line.split('\t')
				mut_id_AA = line[0].split('_')[-1] # model ID
				delta_G = line[2]	# delta delta G value
				delta_G_list.append(delta_G) # update list

				# check stability of delta delta G
				stability = stability_check(float(delta_G))
				delta_G_stab.append(stability) # update list

	mut_list = [] # list to store mutation info

	with open(mutant_file, 'r') as f_in_mut: # open mutation file
		for line in f_in_mut:
			# mutation as in file containing original AA, PDB chain, position and replaced AA
			mutation = line.strip('\n').split(';')[0]
			mut_pos = mutation[2:-1] # mutation position

			# original AA,position and replaced AA and position separately
			mut_info = mutation[0] + mutation[2:] + '\t' + mut_pos
			mut_list.append(mut_info) # append the list

	# output data
	output_data = ''
	for item in range(len(delta_G_list)):
		output_data += mut_list[item] + '\t' + delta_G_list[item] + '\t' + delta_G_stab[item] + '\n'

	return(output_data)

def main( ):
	start_time = time.time() # our scripts start time
	input_file = args_.input_argument
	output_file = args_.output_argument

	# root dicrectory containing all AA folders
	input_dir_root = input_file[0]

	# repair PDB file
	repair_pdb_file = input_file[1]
	repair_pdb_info = os.path.split(repair_pdb_file)
	repair_pdb_name = repair_pdb_info[1]

	output_txt = 'Mutation' + '\t' + 'Position'+ '\t' + 'Delta_Delta_G' + '\t' + 'Feature' + '\n'

	# iterate for all AA folders
	for res in one_letter.keys():
		if res == 'UNK':continue
		substitite_res = one_letter[res]
		res_dir = os.path.join(input_dir_root, res) # current AA folder

		# file containing mutations for current AA folder
		mutant_file = ('').join([res_dir, '/', 'individual_list_', substitite_res, '.txt'])

		# FoldX models directory
		foldx_dir = ('').join([res_dir, '/', 'foldx_data'])

		# avg delta dela G file
		avg_delta_G_file = ('').join([foldx_dir,'/','Average_',repair_pdb_name])

		# call foldx_process for current AA
		foldx_result = foldx_process(avg_delta_G_file, mutant_file, repair_pdb_name)

		# append the result
		output_txt += foldx_result

	# write output to a file
	with open(output_file[0], 'w') as f_out:
		f_out.write(output_txt)

if __name__ == "__main__":
	parser = argparse.ArgumentParser(description="A script to make make table for foldx energy")
	parser.add_argument('-i', nargs='+', dest="input_argument",default="something.txt", help="something file")
	parser.add_argument('-o', nargs='+', dest="output_argument",default="something_.txt", help="something file")
	args_ = parser.parse_args()
	main(  )
	print('done')


import librosa
import matplotlib.pyplot as plt

y1, sr1 = librosa.load('../data/orange_uk.wav')
y2, sr2 = librosa.load('../data/orange_ustra.wav')

plt.subplot(1, 2, 1)
mfcc1 = librosa.feature.mfcc(y1, sr1)
plt.imshow(mfcc1)

plt.subplot(1, 2, 2)
mfcc2 = librosa.feature.mfcc(y2, sr2)
plt.imshow(mfcc2)

plt.figure()
from dtw import dtw
from numpy.linalg import norm
dist, cost, acc_cost, path = dtw(mfcc1.T, mfcc2.T, dist=lambda x, y: norm(x - y, ord=1))
print('Normalized distance between the two sounds:', dist)

plt.imshow(cost.T, origin='lower', interpolation='nearest')
plt.plot(path[0], path[1], 'w')
plt.xlim((-0.5, cost.shape[0]-0.5))
plt.ylim((-0.5, cost.shape[1]-0.5))

print(dist)
print(cost)
print(acc_cost)
print(path)

plt.show()


from io import StringIO
from django.core.management import call_command
from django.test import TestCase, RequestFactory
from user_accounts.models import User, Profile
from unittest.mock import patch, create_autospec
from kyc.geth_node_client import GethNodeClient
from web3 import Web3
from kyc.models import WhitelistLog

class AddVerifiedUsersToWhitelistCommandTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(
            id='65888f1a-faa4-4385-8973-1d1eabe22836',
            email='user1@example.com')
        self.profile = Profile(
            user_id=self.user.id,
            first_name='John',
            last_name='Doe',
            address_1='23 Somewhere St',
            suburb='Burleigh Heads',
            postcode='4220',
            state='QLD',
            country='AUS',
            eth_address='0x10594B019de165B051c2dD99ED484DC9DAA20005',
            verified=True
        )
        self.profile.save()

    @patch("kyc.management.commands.add_verified_users_to_whitelist.get_geth_node_client", autospec=True)  # noqa: E501
    def test_add_one_verified_user(self, get_geth_node_client_mock):
        # assert preconditions
        self.assertEqual(
            0,
            WhitelistLog.objects.all().count()
        )

        web3_mock = create_autospec(Web3())
        geth_node_client_mock = create_autospec(GethNodeClient(web3_mock))
        get_geth_node_client_mock.return_value = geth_node_client_mock
        whitelist_contract_address = '0x27db42bd2434944f3c175609d07250d75c542371'  # noqa: E501
        # run process
        out = StringIO()
        call_command(
            'add_verified_users_to_whitelist',
            whitelist_contract_address,
            stdout=out
        )
        # assert results
        self.assertIn(
            f'{self.profile.eth_address} was added to {whitelist_contract_address}',  # noqa: E501
            out.getvalue()
        )
        self.assertEqual(
            1,
            WhitelistLog.objects.all().count()
        )
        whitelist_log = WhitelistLog.objects.first()
        self.assertEqual(
            WhitelistLog.ACTION_ADD,
            whitelist_log.action
        )

    @patch("kyc.management.commands.add_verified_users_to_whitelist.get_geth_node_client", autospec=True)  # noqa: E501
    def test_skip_one_verified_user_already_added(
            self,
            get_geth_node_client_mock):

        web3_mock = create_autospec(Web3())
        geth_node_client_mock = create_autospec(GethNodeClient(web3_mock))
        geth_node_client_mock.is_on_whitelist.return_value = True
        get_geth_node_client_mock.return_value = geth_node_client_mock

        whitelist_contract_address = '0x27db42bd2434944f3c175609d07250d75c542371'  # noqa: E501

        WhitelistLog(
            user=self.user,
            contract_address=whitelist_contract_address,
            eth_address=self.profile.eth_address,
            action=WhitelistLog.ACTION_ADD
        ).save()
        # run process
        out = StringIO()
        call_command(
            'add_verified_users_to_whitelist',
            whitelist_contract_address,
            stdout=out
        )
        # assert results
        self.assertIn(
            f'{self.profile.eth_address} is already added to {whitelist_contract_address}. Nothing to do.',  # noqa: E501
            out.getvalue()
        )
        self.assertEqual(
            1,
            WhitelistLog.objects.all().count()
        )
        whitelist_log = WhitelistLog.objects.first()
        self.assertEqual(
            WhitelistLog.ACTION_ADD,
            whitelist_log.action
        )


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        res = [-float('inf')]
        def dfs(cur):
            if not cur:
                return 0
            left, right = dfs(cur.left), dfs(cur.right)
            res[0] = max(res[0], max(0,left)+cur.val+max(0,right))
            return max(cur.val,left+cur.val,right+cur.val)
        dfs(root)
        return res[0]

LeetCode/124. Binary Tree Maximum Path Sum/solution.py


import openpyxl

def tel_mody(tel):
    tel = tel.replace(' ','')
    tel = tel.replace('-', '')
    tel = tel.replace('(', '')
    tel = tel.replace(')', '')
    if len(tel) == 12 : tel = '+7' + tel[2:]
    if len(tel) == 11: tel = '+7' + tel[1:]
    if len(tel) > 12: tel = ' --- ' + tel + ' --- '
    return tel

# читаем excel-файл
wb = openpyxl.load_workbook('30 набор контакты.xlsx')

# получаем активный лист
sheet = wb.active
my_file = open("import-rodit2.csv", "w", encoding='utf-8')

str_csv = 'Name,' +\
          'Given Name,' \
          'Family Name,' \
          'Group Membership,' \
          'E-mail 1 - Type, E-mail 1 - Value,' \
          'Phone 1 - Value,' \
          'Organization 1 - Name,' \
          'Organization 1 - Title,' \
          'Custom Field 1 - Type,' \
          'Custom Field 1 - Value,' \
          'Custom Field 2 - Type,' \
          'Custom Field 2 - Value,' \
          'Custom Field 3 - Type,' \
          'Custom Field 3 - Value,' \
          'Custom Field 4 - Type,' \
          'Custom Field 4 - Value,'\
          'Custom Field 5 - Type,' \
          'Custom Field 5 - Value,' \
          'Custom Field 6 - Type,' \
          'Custom Field 6 - Value,' \
          'Custom Field 7 - Type,' \
          'Custom Field 7 - Value \n'
my_file.write(str_csv)

rows = sheet.max_row
cols = sheet.max_column
for i in range(3, rows + 1):
    fio = str(sheet.cell(row=i, column=8).value).split()
    tel = str(sheet.cell(row=i, column=9).value)
    mail = str(sheet.cell(row=i, column=10).value)
    rodfio1 = str(sheet.cell(row=i, column=1).value)
    rodtel1 = str(sheet.cell(row=i, column=2).value)
    mail1 = str(sheet.cell(row=i, column=3).value)
    rodfio2 = str(sheet.cell(row=i, column=5).value)
    rodtel2 = str(sheet.cell(row=i, column=6).value)
    mail2 = str(sheet.cell(row=i, column=7).value)
    metro = str(sheet.cell(row=i, column=11).value)

    print(fio)
    if fio[0] == 'None':
        continue
    if len(mail) == 4  :
        mail = ','
    else:
        mail = '*,' + mail

    all_str = fio[0] + ' ' + fio[1] + ',' + \
              fio[0] + ',' + \
              fio[1] + ',' + \
              'ДГ ::: * myContacts,' + \
              mail + ',' + \
              tel_mody(tel) + ',' + \
              'ДГ' +  ',' + \
              'Родитель' + ',' + \
              'Ребенок' + ',' + rodfio1 + ',' + \
              'Телефон Ребенка' + ',' + tel_mody(rodtel1) + ',' + \
              'Email Ребенка' + ',' + mail1 + ',' + \
              'Родитель 1' + ',' + rodfio2 + ',' + \
              'Телефон Р1' + ',' + tel_mody(rodtel2) + ',' + \
              'Email Р1' + ',' + mail2 + ',' + \
              'Метро' + ',' + metro + '\n'
    all_str = all_str.replace('None', '')
    print(all_str)
    my_file.write(all_str)

my_file.close()


import requests
from bs4 import BeautifulSoup as bs
from hangul import recompile_hangul

## HTTP GET Request

i=2020

def crawl(soup):
    brand_list = []

    for data in soup.find_all('div',{'class':'li_inner'}):

    # 1~100위 추출
        brand = data.find('img').get('alt')
        brand_list.append(recompile_hangul(brand))

    f = open(f'rank{i-1}.csv','w', encoding='utf-8')

    f.write(f'rank{i-1}\n')
    for text in brand_list:
        f.write(text+'\n')

## HTML 소스 가져오기
req2019 = requests.get('https://store.musinsa.com/app/usr/brand_rank?d_cat_cd=&u_cat_cd=&range=1y&sex=&popup=&page=1&sort=best')
req2018 = requests.get('https://web.archive.org/web/20181204051916/https://store.musinsa.com/app/usr/brand_rank')

html2019 = req2019.text
soup2019 = bs(html2019, 'html.parser')
crawl(soup2019)

i-=1
html2018 = req2018.text
soup2018 = bs(html2018, 'html.parser')
crawl(soup2018)
i-=1
req2017 = requests.get('https://web.archive.org/web/20171228091726/https://store.musinsa.com/app/usr/brand_rank')
html2017 = req2017.text
soup2017 = bs(html2017, 'html.parser')
crawl(soup2017)


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

# InstanceSegmentation.py

import os
import traceback
import sys

from CocoInstanceSegmentation import *
from Detector2 import Detector2

import Detector2 as det

if __name__ == "__main__":
  filename_prefix = "instance_seg_"

  try:
    (image_filepath, out_image_dir, filters) = det.parse_argv(sys.argv)

    model    = CocoInstanceSegmentation()

    detector = Detector2(model)
    if os.path.isfile(image_filepath):
      detector.detect(image_filepath, out_image_dir, filename_prefix, filters)

    elif os.path.isdir(image_filepath):
      detector.detect_all(image_filepath, out_image_dir, filename_prefix, filters)

    else:
      raise Exception("Unsupported imput_image {}".format(input_image_filepath))

  except:
    traceback.print_exc()

    pass


# hexagonmap.py
#
# Copyright (c) 2016, mar77i <mar77i at mar77i dot ch>
#
# This software may be modified and distributed under the terms
# of the ISC license.  See the LICENSE file for details.

class HexagonMap:
	def __init__(self, tile_size, surf_size):
		self.tile_size = tuple(n - 1 for n in tile_size)
		self.surf_size = surf_size
		self.hexa_odd = tile_size[0] >> 1
		self.hexa_yfact = int(tile_size[1] * .75)
		self.field_size = (
			int((surf_size[0] - (tile_size[0] >> 1)) / self.tile_size[0]),
			int((surf_size[1] - (tile_size[1] >> 2)) / self.hexa_yfact)
		)

	def pixel_coord(self, *pos):
		if len(pos) == 1:
			pos = pos[0]
		return (
			pos[0] * self.tile_size[0] + (self.hexa_odd * (pos[1] % 2)),
			pos[1] * self.hexa_yfact
		)

	def tile_coord(self, *pos):
		if len(pos) == 1:
			pos = pos[0]
		y = pos[1] // self.hexa_yfact
		return ((pos[0] - (self.hexa_odd * (y % 2))) // self.tile_size[0], y)

	def neighbors(self, pos, width=1):
		if width > 1:
			neighbors = set(self.neighbors(pos))
			for x in range(width):
				new = set()
				for n in neighbors:
					new.update(self.neighbors(n))
				neighbors.update(new)
			neighbors.remove(tuple(pos))
			for n in neighbors:
				yield n
			return
		last = (self.field_size[0] - 1, self.field_size[1] - 1)
		nfx, nfy = pos[0] > 0, pos[1] > 0
		nlx, nly = pos[0] < last[0], pos[1] < last[1]
		odd = pos[1] % 2
		d = 0
		if nfx:
			yield (pos[0] - 1, pos[1])
		if nlx:
			yield (pos[0] + 1, pos[1])
		if nfy:
			if pos[0] - (not odd) < last[0]:
				yield (pos[0] + odd, pos[1] - 1)
			if pos[0] + odd > 0:
				yield (pos[0] + odd - 1, pos[1] - 1)
		if nly:
			if pos[0] - (not odd) < last[0]:
				yield (pos[0] + odd, pos[1] + 1)
			if pos[0] + odd > 0:
				yield (pos[0] + odd - 1, pos[1] + 1)

	def rel_angle(self, old_pos, pos):
		odd = old_pos[1] % 2
		if old_pos[1] < pos[1]:
			if old_pos[0] + odd == pos[0]:
				return 300
			return 240
		if old_pos[1] > pos[1]:
			if old_pos[0] + odd == pos[0]:
				return 60
			return 120
		if old_pos[0] > pos[0]:
			return 180
		return 0


N = int(input())
lst = [0] * 1000002
color = list(list(map(int,input().split())) for _ in range(N))
for a , b in color:
    lst[a] += 1
    lst[b + 1] -= 1
ans = 0
tmp_ans = 0
for i in range(1000002):
    tmp_ans += lst[i]
    if tmp_ans > ans:
        ans = tmp_ans
print(ans)


# GY150610

from fileinput import hook_compressed
from os import path
from sys import stdin
from collections import defaultdict as dd

from PySembler.errors import PySembler_IOError

__all__ = ['MultiReader']

class MultiReader(object):
    ''' Automated constructor creating a class for reading fasta/fastq records
    from stdin or files (optionally gz/bz2 compressed) '''

    def __init__(self, filename=None, keepquals=True):

        if filename:

            self.filename = filename
            if not path.exists(self.filename):
                raise PySembler_IOError('Specified file not found')

            fname, ext = path.splitext(self.filename)
            if ext in ('.gz', '.bz2'):
                compressed = True
                fname, ext = path.splitext(fname)
            else:
                compressed = False

            if ext in ('.fq', '.fastq'):
                self.filetype = 'fastq'
                if keepquals:
                    setattr(self.__class__, '__next__', _fq_next_quals)
                else:
                    setattr(self.__class__, '__next__', _fq_next)
            elif ext in ('.fa', '.fasta'):
                self.filetype = 'fasta'
                self._buffer = b' '
                setattr(self.__class__, '__next__', _fa_next)
            else:
                raise PySembler_IOError('Unknown file type')

            if compressed:
                self._fileobj = hook_compressed(filename, 'rb')
            else:
                self._fileobj = open(filename, 'rb')

            setattr(self.__class__, 'close', _file_close)

        else:

            self.filename = 'stdin'

            self._fileobj = stdin.buffer
            self._buffer = b' '

            if keepquals:
                setattr(self.__class__, '__next__', _std_next_quals)
                setattr(self.__class__, 'close', _std_close)
            else:
                setattr(self.__class__, '__next__', _std_next)
                setattr(self.__class__, 'close', _std_close)

    def __repr__(self):
        return 'FASTfile({})'.format(self.filename)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def __iter__(self):
        return self

def _fa_next(self):
    ''' Yields (id,seq,b'') tuples from FASTA files '''
    while self._buffer and self._buffer[0] != 62:
        self._buffer = self._fileobj.readline()
    if not self._buffer:
        raise StopIteration
    seqid = self._buffer[1:].strip()
    self._buffer = self._fileobj.readline()
    seqlines = []
    while self._buffer and self._buffer[0] != 62:
        seqlines.append(self._buffer.strip())
        self._buffer = self._fileobj.readline()
    return seqid, b''.join(seqlines).upper(), b''

def _fq_next_quals(self):
    ''' Yields (id,seq,quals) tuples from FASTQ files '''
    seqid = self._fileobj.readline()[1:].strip()
    seq = self._fileobj.readline().strip().upper()
    self._fileobj.readline()
    quals = self._fileobj.readline().strip()
    if seqid:
        return seqid, seq, quals
    raise StopIteration

def _fq_next(self):
    ''' Yields (id,seq,b'') tuples from FASTQ files '''
    seqid = self._fileobj.readline()[1:].strip()
    seq = self._fileobj.readline().strip().upper()
    self._fileobj.readline(); self._fileobj.readline()
    if seqid:
        return seqid, seq, b''
    raise StopIteration

def _std_next_quals(self):
    while self._buffer and self._buffer[0] not in (62, 64):
        self._buffer = self._fileobj.readline()
    if not self._buffer:
        raise StopIteration
    if self._buffer[0] == 62:
        seqid = self._buffer[1:].strip()
        self._buffer = self._fileobj.readline()
        seqlines = []
        while self._buffer and self._buffer[0] not in (62, 64):
            seqlines.append(self._buffer.strip())
            self._buffer = self._fileobj.readline()
        return seqid, b''.join(seqlines).upper(), b''
    else:
        seqid = self._buffer[1:].strip()
        seq = self._fileobj.readline().strip().upper()
        self._fileobj.readline()
        quals = self._fileobj.readline().strip()
        self._buffer = self._fileobj.readline()
        return seqid, seq, quals

def _std_next(self):
    while self._buffer and self._buffer[0] not in (62, 64):
        self._buffer = self._fileobj.readline()
    if not self._buffer:
        raise StopIteration
    if self._buffer[0] == 62:
        seqid = self._buffer[1:].strip()
        self._buffer = self._fileobj.readline()
        seqlines = []
        while self._buffer and self._buffer[0] not in (62, 64):
            seqlines.append(self._buffer.strip())
            self._buffer = self._fileobj.readline()
        return seqid, b''.join(seqlines).upper(), b''
    else:
        seqid = self._buffer[1:].strip()
        seq = self._fileobj.readline().strip().upper()
        self._fileobj.readline()
        self._fileobj.readline()
        self._buffer = self._fileobj.readline()
        return seqid, seq, b''

def _file_close(self):
    self._fileobj.close()

def _std_close(self):
    pass

if __name__ == '__main__':
    pass


N, M, Y, Z = map(int, input().split())
cToI = dict()

colorPoint = [0] * M

for i in range(M):
    c, p = input().split()
    cToI[c] = i
    colorPoint[i] = int(p)

B = list(map(lambda a: cToI[a], input()))

dp = [[[-10**18] * (M + 1) for _ in range(1 << M)] for _ in range(N + 1)]  # dp[index][state][lastColor]
dp[0][0][M] = 0

for i in range(N):
    nxColor = B[i]
    for state in range(1 << M):
        for color in range(M + 1):
            nxPoint = dp[i][state][color]

            if dp[i + 1][state][color] < nxPoint:  # 使わない
                dp[i + 1][state][color] = nxPoint

            nxPoint += colorPoint[nxColor]
            nxState = state | (1 << nxColor)
            if color == nxColor:
                nxPoint += Y

            if dp[i + 1][nxState][nxColor] < nxPoint:
                dp[i + 1][nxState][nxColor] = nxPoint

ans = 0
dp = dp[N]
for end in range(M + 1):
    for state in range(1 << M):
        point = dp[state][end]
        if state == (1 << M) - 1:
            point += Z
        ans = max(ans, point)
print(ans)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plot TPI scatterplot.

Plot a snow depth vs TPI scatterplot.
"""
from pathlib import Path
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
from matplotlib.colors import LogNorm
from matplotlib.ticker import MultipleLocator
from proc_toolbox import (open_large_raster, rmse)

def plot_scatter(tpi_north, sd_north, stat_vals_north,
                 tpi_south, sd_south, stat_vals_south,
                 output):
    """Plot a scatterplot."""
    # Create figure
    fig = plt.figure(figsize=(3.89, 7), dpi=300,)

    # Create gridspec setting for subplots
    outer_grid = gs.GridSpec(1, 2, wspace=0.05,
                             width_ratios=(1, 0.05))
    left_cell = outer_grid[0, 0]
    left_inner_grid = gs.GridSpecFromSubplotSpec(2, 1, left_cell, hspace=0,)
    right_cell = outer_grid[0, 1]
    right_inner_grid = gs.GridSpecFromSubplotSpec(1, 1, right_cell)

    ax1 = plt.subplot(left_inner_grid[0, 0])
    ax2 = plt.subplot(left_inner_grid[1, 0])
    ax3 = plt.subplot(right_inner_grid[0, 0])

    # Add data
    hex1 = ax1.hexbin(tpi_north,
                      sd_north,
                      gridsize=(200, 200), cmap="plasma",
                      norm=LogNorm(vmin=1, vmax=1e2),
                      mincnt=1)
    ax1.plot(tpi_north,
             tpi_north *
             stat_vals_north["slope"] +
             stat_vals_north["intercept"],
             linestyle="-", linewidth=1, color="black")

    ax1.text(0.7, 0.7,
             "y = %sx+%s\n"
             r"$r^2$ = %s"
             "\nbias= %s"
             "\nrmse = %s\n"
             "N = %s" % (round(stat_vals_north["slope"], 2),
                         round(stat_vals_north["intercept"], 2),
                         round(stat_vals_north["r2"], 2),
                         round(stat_vals_north["bias"], 2),
                         round(stat_vals_north["rmse"], 2),
                         len(tpi_north)
                         ),
             transform=ax1.transAxes,
             fontsize=7,
             ha='left'
             )
    ax1.text(0.02, 0.02, "a)", transform=ax1.transAxes)

    ax2.hexbin(tpi_south,
               sd_south,
               gridsize=(200, 200), cmap="plasma",
               norm=LogNorm(vmin=1, vmax=1e2),
               mincnt=1)
    ax2.plot(tpi_south,
             tpi_south *
             stat_vals_south["slope"] +
             stat_vals_south["intercept"],
             linestyle="-", linewidth=1, color="black")
    ax2.text(0.7, 0.7,
             "y = %sx+%s\n"
             r"$r^2$ = %s"
             "\nbias= %s"
             "\nrmse = %s\n"
             "N = %s" % (round(stat_vals_south["slope"], 2),
                         round(stat_vals_south["intercept"], 2),
                         round(stat_vals_south["r2"], 2),
                         round(stat_vals_south["bias"], 2),
                         round(stat_vals_south["rmse"], 2),
                         len(tpi_south)
                         ),
             transform=ax2.transAxes,
             fontsize=7,
             ha='left'
             )
    ax2.text(0.02, 0.02, "b)", transform=ax2.transAxes)

    # Axes
    plt.gcf().canvas.draw()
    for ax in [ax1, ax2]:
        ax.set_ylim(0, 3)
        ax.set_xlim(-1.5, 1.5)
        ax.set_ylabel("Snow Depth / m")
        ax.set_xlabel("TPI")
        ax.xaxis.set_major_locator(MultipleLocator(0.5))
        ax.xaxis.set_minor_locator(MultipleLocator(0.1))
        ax.yaxis.set_major_locator(MultipleLocator(0.5))
        ax.yaxis.set_minor_locator(MultipleLocator(0.1))
        ax.tick_params(axis='both', which='both', direction='inout', top=True,
                       right=True, left=True,
                       bottom=True, labelsize=8)

    ax1.set_xticklabels([])
    ax3.set_xticklabels([])
    ax3.set_yticklabels([])

    # Remove overlapping labels
    plt.setp(ax2.get_ymajorticklabels()[-2:-1], visible=False)

    # Colorbar
    cbar = fig.colorbar(hex1, cax=ax3, orientation='vertical')
    cbar.set_label('Number of points / cell')

    plt.show()

    fig.savefig(output.joinpath("tpi_sd_correlation.png"), dpi=300,
                bbox_inches="tight")

def calculate_stats(tpi, sd):
    """Calculate statistics."""
    # Compute linear regression
    slope, intercept, r_value, p_value, std_err = stats.linregress(tpi, sd)
    rmse_val = rmse(sd, tpi)
    bias = np.average(np.array(sd) - np.array(tpi))

    # Fill dictionnary
    statdic = {"slope": slope,
               "intercept": intercept,
               "r2": r_value ** 2,
               "rmse": rmse_val,
               "bias": bias}

    return statdic

if __name__ == '__main__':

    # Specify path to output figure
    output_fig = Path("/home/lamarem/Documents/Umiujaq/Papier/Figures")

    # NORTH
    # Specify path to TPI and snow depth files
    tpi_path_north = Path("/home/lamarem/Documents/Umiujaq/Papier/Data/"
                          "TPI_SD_correlation/TPI_Nord_99cm_33px.tif")
    sd_path_north = Path("/home/lamarem/Documents/Umiujaq/Papier/Data/"
                         "TPI_SD_correlation/Nord_neige_99cm.tif")
    # SOUTH
    # Specify path to TPI and snow depth files
    tpi_path_south = Path("/home/lamarem/Documents/Umiujaq/Papier/Data/"
                          "TPI_SD_correlation/TPI_Sud_99cm_33px.tif")
    sd_path_south = Path("/home/lamarem/Documents/Umiujaq/Papier/Data/"
                         "TPI_SD_correlation/Sud_neige_99cm.tif")

    # Open data
    tpi_north = open_large_raster(tpi_path_north)[0]
    sd_north = open_large_raster(sd_path_north)[0]
    tpi_south = open_large_raster(tpi_path_south)[0]
    sd_south = open_large_raster(sd_path_south)[0]

    # Filter values
    tpi_masked_north = np.ma.masked_where(((sd_north <= 0) |
                                           (tpi_north <= -100) |
                                           (np.isnan(sd_north)) |
                                           (np.isnan(tpi_north))),
                                          tpi_north)
    sd_masked_north = np.ma.masked_where(((sd_north <= 0) |
                                          (tpi_north <= -100) |
                                          (np.isnan(sd_north)) |
                                          (np.isnan(tpi_north))),
                                         sd_north)
    tpi_masked_south = np.ma.masked_where(((sd_south <= 0) |
                                           (tpi_south <= -100) |
                                           (np.isnan(sd_south)) |
                                           (np.isnan(tpi_south))),
                                          tpi_south)
    sd_masked_south = np.ma.masked_where(((sd_south <= 0) |
                                          (tpi_south <= -100) |
                                          (np.isnan(sd_south)) |
                                          (np.isnan(tpi_south))),
                                         sd_south)
    # Compress data
    tpi_cm_north = tpi_masked_north.compressed()
    sd_cm_north = sd_masked_north.compressed()
    tpi_cm_south = tpi_masked_south.compressed()
    sd_cm_south = sd_masked_south.compressed()

    # Calculate statistics
    stat_values_north = calculate_stats(tpi_cm_north, sd_cm_north)
    stat_values_south = calculate_stats(tpi_cm_south, sd_cm_south)

    # Plot scatter plot
    plot_scatter(tpi_cm_north, sd_cm_north, stat_values_north,
                 tpi_cm_south, sd_cm_south, stat_values_south,
                 output_fig)


import sys

lines=[l.strip().split() for l in open(sys.argv[1]).readlines()]
glines=[l.strip().split() for l in open(sys.argv[2]).readlines()]

for i in range(len(lines)):
    if len(lines[i])<2:
        print("")
    elif glines[i][0][0] not in ["@","#"] and glines[i][0][:4]!="http" and len(glines[i][0])>1:
        lines[i]=[lines[i][0],'I-'+glines[i][-1],'I-'+lines[i][-1]]
        print(" ".join(lines[i]))


from django.db import models
from django.contrib import admin

from apps.show_calendar.models import *

class VenueAdmin(admin.ModelAdmin):

    list_display = (
        'name',
        'address',
        'city',
        'state',
        'zipcode',
        'website'
    )

class ShowAdmin(admin.ModelAdmin):

    list_display = (
        'title',
        'start_time',
        'end_time',
        'venue',
        'published',
        'festival_show'
    )
    actions = [
        'publish_show',
        'expire_show'
    ]
    search_fields = [
        'title',
        'venue__name',
    ]

    def publish_show(self, request, queryset):
        queryset.update(published=True)

    def expire_show(self, request, queryset):
        queryset.update(published=False)

    publish_show.short_description = "Publish selected shows"
    expire_show.short_description = "Expire selected shows"

admin.site.register(Venue, VenueAdmin)
admin.site.register(Show, ShowAdmin)


"""
Systemd service utilities.

Contains functions to start, stop & poll systemd services.
Probably not very useful outside this spawner.
"""
import asyncio
import shlex

async def start_transient_service(
    unit_name,
    cmd,
    args,
    host=None,
    environment_variables=None,
    properties=None,
    uid=None,
    gid=None,
    slice=None,
):
    """
    Start a systemd transient service with given paramters
    """

    run_cmd = [
        'systemd-run',
        '--unit', unit_name,
    ]

    if host:
        run_cmd += [ '-H', host ]

    if properties:
        for key, value in properties.items():
            if isinstance(value, list):
                run_cmd += ['--property={}={}'.format(key, v) for v in value]
            else:
                # A string!
                run_cmd.append('--property={}={}'.format(key, value))

    if environment_variables:
        run_cmd += [
            '--setenv={}={}'.format(key, value)
            for key, value in environment_variables.items()
        ]

    # Explicitly check if uid / gid are not None, since 0 is valid value for both
    if uid is not None:
        run_cmd += ['--uid', str(uid)]

    if gid is not None:
        run_cmd += ['--gid', str(gid)]

    if slice is not None:
        run_cmd += ['--slice={}'.format(slice)]

    run_cmd += [ shlex.quote(c) for c in cmd ]
    run_cmd += [ shlex.quote(a) for a in args ]

    #
    # XXX: Below removed to add support for remote systemd calls -- MSB
    #

    # We unfortunately have to resort to doing cd with bash, since WorkingDirectory property
    # of systemd units can't be set for transient units via systemd-run until systemd v227.
    # Centos 7 has systemd 219, and will probably never upgrade - so we need to support them.
    #run_cmd += [
    #    '/bin/bash',
    #    '-c',
    #    "cd {wd} && exec {cmd} {args}".format(
    #        wd=shlex.quote(working_dir),
    #        cmd=' '.join([shlex.quote(c) for c in cmd],
    #        args=' '.join([shlex.quote(a) for a in args]
    #    )
    #]

    proc = await asyncio.create_subprocess_exec(*run_cmd)
    return await proc.wait()

async def service_running(unit_name, host=None):
    """
    Return true if service with given name is running (active).
    """
    cmd = [ 'systemctl' ]
    if host:
        cmd += ['-H', host]
    cmd += ['is-active', unit_name]

    proc = await asyncio.create_subprocess_exec(
        *cmd,
        stdout=asyncio.subprocess.DEVNULL
    )
    ret = await proc.wait()

    return ret == 0

async def service_failed(unit_name, host=None):
    """
    Return true if service with given name is in a failed state.
    """
    cmd = [ 'systemctl' ]
    if host:
        cmd += ['-H', host]
    cmd += ['is-failed', unit_name]

    proc = await asyncio.create_subprocess_exec(
        *cmd,
        stdout=asyncio.subprocess.DEVNULL
    )
    ret = await proc.wait()

    return ret == 0

async def stop_service(unit_name, host=None):
    """
    Stop service with given name.

    Throws CalledProcessError if stopping fails
    """
    cmd = [ 'systemctl' ]
    if host:
        cmd += ['-H', host]
    cmd += ['stop', unit_name]

    proc = await asyncio.create_subprocess_exec(
        *cmd,
        stdout=asyncio.subprocess.DEVNULL
    )
    await proc.wait()

async def reset_service(unit_name, host=None):
    """
    Reset service with given name.

    Throws CalledProcessError if resetting fails
    """
    cmd = [ 'systemctl' ]
    if host:
        cmd += ['-H', host]
    cmd += ['reset-failed', unit_name]

    proc = await asyncio.create_subprocess_exec(
        *cmd,
        stdout=asyncio.subprocess.DEVNULL
    )
    await proc.wait()


import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import h5py

origin = str(45)
trajectory = str(60)
sim1 = "/mnt/scratch/sqa/fan_"+origin+"_extradata_orig/"+trajectory+"/"
sim2 = "/mnt/scratch/sqa/fan_"+origin+"_extradata_interact/"+trajectory+"/" #"/mnt/scratch/sqa/45_60_noemabs/"#
indir = "/mnt/scratch/sqa/input_data/fan_"+origin+"/"+trajectory+"/"
nulibfile = "/mnt/scratch/sqa/input_data/NuLib_rho82_temp65_ye51_ng16_ns3_version1.0_20180427.h5"
sgn = 1

filename1 = sim1+"output/2p.dat"
filename2 = sim2+"output/2p.dat"
pfilenamebase = "output/out.dat"
r1 = np.genfromtxt(filename1,usecols=(0))/1e5
r2 = np.genfromtxt(filename2,usecols=(0))/1e5
rmin = min(np.min(r1), np.min(r2))
rmax = 11 #max(np.max(r1), np.max(r2))
print(rmin,rmax)

# constants
h = 6.6260755e-27 # erg s
c = 2.99792458e10 # cm/s
hbarc = h*c/(2.*np.pi)
MeV = 1.60218e-6 # erg

# vacuum mixing
ng=16
grouplist = [0,int(ng/2),ng-1] #range(ng)
dm13 = 2.43e-3 # eV^2
thetaV = .15
eV = 1.60218e-12 # erg
lEtop = np.log(37.48 * 1e6) # eV
lEbottom = np.log(2. * 1e6) # eV
dlE = (lEtop-lEbottom)/(ng-1)
E =  np.array([np.exp(lEbottom + i*dlE) for i in range(ng)])
Vvac = dm13 / (2.*E) * np.cos(2.*thetaV) * eV / hbarc

# self-interaction, matter potentials, probabilities
Ve1 = np.genfromtxt(filename1,usecols=(1 ))[:len(r1)]/hbarc
VSI1 = (np.genfromtxt(filename1,usecols=(2 ))[:len(r1)] \
       - np.genfromtxt(filename1,usecols=(3 ))[:len(r1)])/hbarc # already includes anti-matter subtraction
#       - np.genfromtxt(filename1,usecols=(4 )) \
#       + np.genfromtxt(filename1,usecols=(5 ))
pe1 = np.genfromtxt(filename1,usecols=(9))[:len(r1)]/hbarc
pa1 = np.genfromtxt(filename1,usecols=(10))[:len(r1)]/hbarc

Ve2 = np.genfromtxt(filename2,usecols=(1 ))[:len(r2)]/hbarc
VSI2 = (np.genfromtxt(filename2,usecols=(2 ))[:len(r2)] \
       - np.genfromtxt(filename2,usecols=(3 ))[:len(r2)])/hbarc # already includes anti-matter subtraction
#       - np.genfromtxt(filename2,usecols=(4 )) \
#       + np.genfromtxt(filename2,usecols=(5 ))
pe2 = np.genfromtxt(filename2,usecols=(9))[:len(r2)]/hbarc
pa2 = np.genfromtxt(filename2,usecols=(10))[:len(r2)]/hbarc

# set up plot
fig, ax = plt.subplots(6, 2, squeeze=False)
fig.set_figheight(20)
fig.set_figwidth(15)
plt.subplots_adjust(wspace=0, hspace=0)

#################
# DPHI_DR PLOTS #
#################
filename1 = sim1+"output/dangledr.dat"
filename2 = sim2+"output/dangledr.dat"
rplot1 = np.genfromtxt(filename1,usecols=(0))/1e5
rplot2 = np.genfromtxt(filename2,usecols=(0))/1e5
whereinrange1 = np.where((rplot1>=rmin) & (rplot1<=rmax))
whereinrange2 = np.where((rplot2>=rmin) & (rplot2<=rmax))
phimin = 1e10
phimax = -1e10
thetamin = 1e10
thetamax = -1e10
nm = 2
def get_pos_min(array):
    wherepos = np.where(array>0)
    if len(wherepos[0])>0:
        return np.min(array[wherepos])
    else:
        return 1e100

for ig in grouplist:
    for im in range(nm):
        dthetadr_osc1 = sgn*np.genfromtxt(filename1, usecols=(1 + ig + im*ng + 0*nm*ng))[whereinrange1]
        dphidr_osc1   = sgn*np.genfromtxt(filename1, usecols=(1 + ig + im*ng + 1*nm*ng))[whereinrange1]
        dthetadr_int1 = sgn*np.genfromtxt(filename1, usecols=(1 + ig + im*ng + 2*nm*ng))[whereinrange1]
        dphidr_int1   = sgn*np.genfromtxt(filename1, usecols=(1 + ig + im*ng + 3*nm*ng))[whereinrange1]
        dthetadr_osc2 = sgn*np.genfromtxt(filename2, usecols=(1 + ig + im*ng + 0*nm*ng))[whereinrange2]
        dphidr_osc2   = sgn*np.genfromtxt(filename2, usecols=(1 + ig + im*ng + 1*nm*ng))[whereinrange2]
        dthetadr_int2 = sgn*np.genfromtxt(filename2, usecols=(1 + ig + im*ng + 2*nm*ng))[whereinrange2]
        dphidr_int2   = sgn*np.genfromtxt(filename2, usecols=(1 + ig + im*ng + 3*nm*ng))[whereinrange2]
        ax[3][im].semilogy(rplot1[whereinrange1], dthetadr_osc1,'--' ,color=plt.cm.winter(ig/(ng)))
        ax[3][im].semilogy(rplot1[whereinrange1], dthetadr_int1,'-',color=plt.cm.winter(ig/(ng)))
        ax[3][im].semilogy(rplot2[whereinrange2], dthetadr_osc2,'--' ,color=plt.cm.hot(ig/(ng*1.5)))
        ax[3][im].semilogy(rplot2[whereinrange2], dthetadr_int2,'-',color=plt.cm.hot(ig/(ng*1.5)))
        ax[4][im].semilogy(rplot1[whereinrange1], dphidr_osc1,  '--' ,color=plt.cm.winter(ig/(ng)))
        ax[4][im].semilogy(rplot1[whereinrange1], dphidr_int1,  '-',color=plt.cm.winter(ig/(ng)))
        ax[4][im].semilogy(rplot2[whereinrange2], dphidr_osc2,  '--' ,color=plt.cm.hot(ig/(ng*1.5)))
        ax[4][im].semilogy(rplot2[whereinrange2], dphidr_int2,  '-',color=plt.cm.hot(ig/(ng*1.5)))
        phimin = min(phimin,get_pos_min(dphidr_osc1))
        phimin = min(phimin,get_pos_min(dphidr_int1))
        phimin = min(phimin,get_pos_min(dphidr_osc2))
        phimin = min(phimin,get_pos_min(dphidr_int2))
        phimax = max(phimax,np.max(dphidr_osc1))
        phimax = max(phimax,np.max(dphidr_int1))
        phimax = max(phimax,np.max(dphidr_osc2))
        phimax = max(phimax,np.max(dphidr_int2))

        thetamin = min(thetamin,get_pos_min(dthetadr_osc1))
        thetamin = min(thetamin,get_pos_min(dthetadr_int1))
        thetamin = min(thetamin,get_pos_min(dthetadr_osc2))
        thetamin = min(thetamin,get_pos_min(dthetadr_int2))
        thetamax = max(thetamax,np.max(dthetadr_osc1))
        thetamax = max(thetamax,np.max(dthetadr_int1))
        thetamax = max(thetamax,np.max(dthetadr_osc2))
        thetamax = max(thetamax,np.max(dthetadr_int2))

##############################
# SURVIVAL PROBABILITY PLOTS #
##############################
def rotate_real(R,I,phi):
    return R*np.cos(phi) - I*np.sin(phi)
def rotate_imag(R,I,phi):
    return R*np.sin(phi) + I*np.cos(phi)
def norm2(R,I):
    return R*R + I*I

filename1 = sim1+pfilenamebase
filename2 = sim2+pfilenamebase
#rplot1 = np.genfromtxt(filename1,usecols=(0)) / 1e5
#rplot2 = np.genfromtxt(filename2,usecols=(0)) / 1e5
pmin = [1,1,1]
pmax = [0,0,0]
for ig in grouplist:
    for im in range(2):

        SeeR = np.genfromtxt(filename1,usecols=(1 + 8*im + 8*2*ig))
        SeeI = np.genfromtxt(filename1,usecols=(2 + 8*im + 8*2*ig))
        phi = np.arctan2(SeeI,SeeR)
        SexR = np.genfromtxt(filename1,usecols=(3 + 8*im + 8*2*ig))
        SexI = np.genfromtxt(filename1,usecols=(4 + 8*im + 8*2*ig))
        SxxR = np.genfromtxt(filename1,usecols=(7 + 8*im + 8*2*ig))
        SxxI = np.genfromtxt(filename1,usecols=(8 + 8*im + 8*2*ig))
        Pee = norm2(SeeR,SeeI)
        Pex = norm2(SexR,SexI)
        Pxx = norm2(SxxR,SxxI)

        ax[0][im].plot(rplot1, Pee, color=plt.cm.winter(ig/(ng)))
        ax[1][im].plot(rplot1, Pex, color=plt.cm.winter(ig/(ng)))
        ax[2][im].plot(rplot1, Pxx, color=plt.cm.winter(ig/(ng)))
        pmin[0] = min(pmin[0], np.min(Pee[whereinrange1]))
        pmin[1] = min(pmin[1], np.min(Pex[whereinrange1]))
        pmin[2] = min(pmin[2], np.min(Pxx[whereinrange1]))
        pmax[0] = max(pmax[0], np.max(Pee[whereinrange1]))
        pmax[1] = max(pmax[1], np.max(Pex[whereinrange1]))
        pmax[2] = max(pmax[2], np.max(Pxx[whereinrange1]))

        SeeR = np.genfromtxt(filename2,usecols=(1 + 8*im + 8*2*ig))
        SeeI = np.genfromtxt(filename2,usecols=(2 + 8*im + 8*2*ig))
        phi = np.arctan2(SeeI,SeeR)
        SexR = np.genfromtxt(filename2,usecols=(3 + 8*im + 8*2*ig))
        SexI = np.genfromtxt(filename2,usecols=(4 + 8*im + 8*2*ig))
        SxxR = np.genfromtxt(filename2,usecols=(7 + 8*im + 8*2*ig))
        SxxI = np.genfromtxt(filename2,usecols=(8 + 8*im + 8*2*ig))
        Pee = norm2(SeeR,SeeI)
        Pex = norm2(SexR,SexI)
        Pxx = norm2(SxxR,SxxI)

        ax[0][im].plot(rplot2, norm2(SeeR,SeeI), color=plt.cm.hot(ig/(ng*1.5)))
        ax[1][im].plot(rplot2, norm2(SexR,SexI), color=plt.cm.hot(ig/(ng*1.5)))
        ax[2][im].plot(rplot2, norm2(SxxR,SxxI), color=plt.cm.hot(ig/(ng*1.5)))
        pmin[0] = min(pmin[0], np.min(Pee[whereinrange2]))
        pmin[1] = min(pmin[1], np.min(Pex[whereinrange2]))
        pmin[2] = min(pmin[2], np.min(Pxx[whereinrange2]))
        pmax[0] = max(pmax[0], np.max(Pee[whereinrange2]))
        pmax[1] = max(pmax[1], np.max(Pex[whereinrange2]))
        pmax[2] = max(pmax[2], np.max(Pxx[whereinrange2]))
    print("Done with ig="+str(ig))

###################
# POTENTIAL PLOTS #
###################
if(any(VSI1>0)):
    pVSI1, = ax[5][0].semilogy(r1,VSI1,color="blue", label=r"$V_{\mathrm{SI},1}$")
if(any(VSI2>0)):
    pVSI2, = ax[5][0].semilogy(r2,VSI2,color="red" , label=r"$V_{\mathrm{SI},2}$")
if(any(-VSI1>0)):
    ax[5][0].semilogy(r1,-VSI1,':',color="blue", label=r"$-V_{\mathrm{SI},1}$")
if(any(-VSI2>0)):
    ax[5][0].semilogy(r2,-VSI2,':',color="red", label=r"$-V_{\mathrm{SI},2}$" )

if(r1[-1]>=r2[-1]):
    rplot = r1
    Veplot = Ve1
else:
    rplot=r2
    Veplot = Ve2

pVe,  = ax[5][0].semilogy(rplot, Veplot ,    color="black", label=r"$V_{e}$")
pVvac, = ax[5][0].semilogy(rplot, np.ones(len(rplot))*Vvac[grouplist[0]], color="gray", label=r"$V_\mathrm{vac}$")
for ig in grouplist[1:]:
    ax[5][0].semilogy(rplot, np.ones(len(rplot))*Vvac[ig], color="gray")

potential_max = np.max(Veplot)
potential_max = max(potential_max, np.max(np.abs(VSI1)))
potential_max = max(potential_max, np.max(np.abs(VSI2)))
potential_max = max(potential_max, np.max(Vvac))

potential_min = np.min(Veplot)
potential_min = min(potential_min, np.min(np.abs(VSI1)))
potential_min = min(potential_min, np.min(np.abs(VSI2)))
potential_min = min(potential_min, np.min(Vvac))

##########################
# INTERACTION RATE PLOTS #
##########################
print("Making interaction rate plots")
# read in the interaction rate table
nulib = h5py.File(nulibfile,"r")
rhogrid = nulib["rho_points"]
tempgrid = nulib["temp_points"]
yegrid = nulib["ye_points"]
absopac = np.array(nulib["absorption_opacity"])
scatopac = np.array(nulib["scattering_opacity"])
emis = np.array(nulib["emissivities"])

# get energy grid
E = np.array(nulib["neutrino_energies"])*MeV # erg
ng = len(E)
E1 = np.array(nulib["bin_top"])*MeV # erg
E0 = np.array(nulib["bin_bottom"])*MeV # erg
dE  = [E1[i]    - E0[i]    for i in range(ng)]
dE3 = [E1[i]**3 - E0[i]**3 for i in range(ng)]
ns = 3

def locateLeft(ygrid, yval):
    return next(z for z,val in enumerate(ygrid) if val > yval)-1

def interpolate(array, rho, temp, ye):
    # condition the inputs
    rho  = min(max(rho,  rhogrid[0]), rhogrid[-1])
    temp = min(max(temp,tempgrid[0]),tempgrid[-1])
    ye   = min(max(ye,    yegrid[0]),  yegrid[-1])

    # get the left indices
    irhoL  = locateLeft(rhogrid, rho)
    itempL = locateLeft(tempgrid, temp)
    iyeL   = locateLeft(yegrid, ye)
    irhoR  = irhoL+1
    itempR = itempL+1
    iyeR   = iyeL+1

    # get the left and right coordinates
    lrho0  = np.log10( rhogrid[irhoL   ])
    lrho1  = np.log10( rhogrid[irhoL +1])
    ltemp0 = np.log10(tempgrid[itempL  ])
    ltemp1 = np.log10(tempgrid[itempL+1])
    ye0    =          yegrid[iyeL      ]
    ye1    =          yegrid[iyeL    +1]

    # get the deltas
    lrho  = np.log10(rho)
    ltemp = np.log10(temp)
    dlrhoL  = abs(lrho   - lrho0)
    dlrhoR  = abs(lrho1  - lrho)
    dltempL = abs(ltemp  - ltemp0)
    dltempR = abs(ltemp1 - ltemp)
    dyeL    = abs(ye     - ye0)
    dyeR    = abs(ye1    - ye)
    vol = abs((lrho1-lrho0) * (ltemp1-ltemp0) * (ye1-ye0))

    # get the arrays at the corners
    laLLL = np.log10(array[:,:,iyeL,itempL,irhoL])
    laLLR = np.log10(array[:,:,iyeL,itempL,irhoR])
    laLRL = np.log10(array[:,:,iyeL,itempR,irhoL])
    laLRR = np.log10(array[:,:,iyeL,itempR,irhoR])
    laRLL = np.log10(array[:,:,iyeR,itempL,irhoL])
    laRLR = np.log10(array[:,:,iyeR,itempL,irhoR])
    laRRL = np.log10(array[:,:,iyeR,itempR,irhoL])
    laRRR = np.log10(array[:,:,iyeR,itempR,irhoR])

    # perform the interpolation
    la = 0
    la += laLLL * dyeR * dltempR * dlrhoR
    la += laLLR * dyeR * dltempR * dlrhoL
    la += laLRL * dyeR * dltempL * dlrhoR
    la += laLRR * dyeR * dltempL * dlrhoL
    la += laRLL * dyeL * dltempR * dlrhoR
    la += laRLR * dyeL * dltempR * dlrhoL
    la += laRRL * dyeL * dltempL * dlrhoR
    la += laRRR * dyeL * dltempL * dlrhoL

    return 10**(la/vol)

# get the rho,T,Ye arrays
rlist = np.genfromtxt(indir+"rho.txt", usecols=(0))/1e5
rho  = np.genfromtxt(indir+"rho.txt", usecols=(1))
temp = np.genfromtxt(indir+"temp.txt",usecols=(1))
ye   = np.genfromtxt(indir+"Ye.txt",  usecols=(1))

e = np.ndarray((len(rlist),ng,ns))
a = np.ndarray((len(rlist),ng,ns))
s = np.ndarray((len(rlist),ng,ns))
print(np.shape(e))
for ir in range(len(rlist)):
    s[ir,:,:] = interpolate(scatopac, rho[ir], temp[ir], ye[ir])
    a[ir,:,:] = interpolate(absopac,  rho[ir], temp[ir], ye[ir])
    e[ir,:,:] = interpolate(emis,     rho[ir], temp[ir], ye[ir])
print(np.shape(s))

# make the plots
for species in range(ns):
    if species==0:
        col = "blue"
        label = r"$\nu_e$"
    if species==1:
        col = "red"
        label = r"$\bar{\nu}_e$"
    if species==2:
        col = "black"
        label = r"$\nu_x$"
    for ig in grouplist:
        conversion_factor = h**3 * c**2 * dE[ig] / (E[ig] * dE3[ig]/3.) / MeV
        plotval = (e[:,ig,species] * conversion_factor) + a[:,ig,species] + s[:,ig,species]
        potential_max = max(potential_max,np.max(plotval))
        potential_min = min(potential_min,np.min(plotval))
        if ig==0:
            ax[5][1].semilogy(rlist, plotval,'-',color=col, label=label) # 1/cm
        else:
            ax[5][1].semilogy(rlist, plotval,'-',color=col) # 1/cm
        #ax[5][1].semilogy(rlist, s[:,ig,species],'--',color=col) # 1/cm
        #ax[5][1].semilogy(rlist, e[:,ig,species] * conversion_factor,':',color=col) # 1/(cm.sr)

################
# PLOT OPTIONS #
################
for ix in range(2):
    for iy in range(6):
        ax[iy][ix].set_xlim([rmin,rmax])
        ax[iy][ix].grid()

    for iy in range(3):
        ax[iy][ix].set_ylim([pmin[iy],pmax[iy]])
        ax[iy][ix].xaxis.set_ticklabels([])

    ax[3][ix].set_ylim([thetamin/2., thetamax*2.])
    ax[4][ix].set_ylim([phimin/2., phimax*2.])
    ax[5][ix].set_ylim([potential_min/2., potential_max*2.])

for iy in range(6):
    ax[iy][1].yaxis.set_label_position("right")
    ax[iy][1].yaxis.tick_right()
ax[5][0].legend(bbox_to_anchor=(-0.4, 1), loc=2, borderaxespad=0.)
ax[5][1].legend(bbox_to_anchor=(1.15, 1), loc=2, borderaxespad=0.)
ax[0][0].set_title(sim1, color="blue", fontweight="bold")
ax[0][1].set_title(sim2, color="red", fontweight="bold")
ax[0][0].set_ylabel(r"$P_{ee}$")
ax[1][0].set_ylabel(r"$P_{ex}$")
ax[2][0].set_ylabel(r"$P_{xx}$")
ax[3][0].set_ylabel(r"$d\theta/dr$ (rad/cm)")
ax[4][0].set_ylabel(r"$d\phi/dr$ (rad/cm)")
ax[5][0].set_ylabel("Potential (cm$^{-1}$)")
ax[0][1].set_ylabel(r"$\bar{P}_{ee}$")
ax[1][1].set_ylabel(r"$\bar{P}_{ex}$")
ax[2][1].set_ylabel(r"$\bar{P}_{xx}$")
ax[3][1].set_ylabel(r"$d\theta/dr$ (rad/cm)")
ax[4][1].set_ylabel(r"$d\phi/dr$ (rad/cm)")
ax[5][1].set_ylabel("Interaction Rate (cm$^{-1}$)")
ax[5][0].set_xlabel("Distance (km)")
ax[5][1].set_xlabel("Distance (km)")
ax[0][0].xaxis.set_tick_params(labeltop='on')
ax[0][1].xaxis.set_tick_params(labeltop='on')

plt.savefig("psurv_and_potential_compare_"+origin+"_"+trajectory+".pdf",bbox_inches="tight")


class Corrida():
    def __init__(self, time_inic):
        self.time_inic = time_inic
        self.corredores = []
        self.winner = None
        self.finished = False
        self.last_position = 0

    def add_corredor(self, corredor):
        self.corredores.append(corredor)

    def is_corredor_exist(self, cod):
        corredor = self.find_corredor(cod)

        if corredor != None:
            return True

        return False

    def add_turn(self, cod, turn):
        corredor = self.find_corredor(cod)

        finish = corredor.add_turn(turn)
        if finish:
            if self.winner == None:
                self.set_winner(corredor)

            self.last_position += 1
            corredor.position = self.last_position

    def set_winner(self, corredor):
        self.winner = corredor
        self.finished = True

    def find_corredor(self, cod):
        for corredor in self.corredores:
            if corredor.cod == cod:
                return corredor

        return None

    def is_finished(self):
        return self.finished

    def print_result(self):
        self.order_corredor()

        print('Posiçao', 'Codigo', 'Nome', 'Voltas')
        for corredor in self.corredores:
            print(corredor.position, corredor.cod, corredor.name,  len(corredor.turns))

    def order_corredor(self):
        for inicial in range(0, len(self.corredores) - 1):
            exchanging = False

            for atual in range(0, len(self.corredores) - 1):
                if self.corredores[atual].position > self.corredores[atual + 1].position:
                    self.corredores[atual], self.corredores[atual + 1] = self.corredores[atual + 1], self.corredores[atual]
                    exchanging = True

            if not exchanging:
                break


'''
除留余数法，链冲突，保证不会溢出，重复的元素只保存一个
size 是散列表的大小
数据，建立散列
n
n个插入元素(无输出)
m
m个删除元素(删除元素不在散列表中，输出Delete Error)
r
r个查找元素(在,True，不在,False)
'''
from collections import deque
class HashTable():
	def __init__(self, s):
		self.HashSize = s
		self.Table = [None]*s
	def Insert(self, v):
		i = v % self.HashSize
		if self.Table[i] == None:
			self.Table[i] = deque([v])
		else:
			if v not in self.Table[i]:
				self.Table[i].append(v)
		return i
	def Find(self, v):
		i = v % self.HashSize
		if self.Table[i] != None and v in self.Table[i]:
			return i
		return -1

	def Delete(self, v):
		i = v % self.HashSize
		if self.Table[i] != None and v in self.Table[i]:
			del self.Table[i][self.Table[i].index(v)]
			if len(self.Table[i]) == 0:
				self.Table[i] = None
			return i
		else:
			return -1
	def PrintInf(self):
		print('[i]: v')
		for i in range(self.HashSize):
			print("[%d]:" % i, end=" ")
			print(self.Table[i])

def solve():
	h = HashTable(int(input()))
	for i in [int(b) for b in input().split()]:
		h.Insert(i)
	for i in range(int(input())):
		h.Insert(int(input()))
	for i in range(int(input())):
		if h.Delete(int(input())) == -1: print("Delete Error")
	for i in range(int(input())):
		if h.Find(int(input())) == -1:
			print("False")
		else:
			print("True")

def test01():
	h = HashTable(5)
	print("插入操作:")
	p = [4,2,3,2]
	for a in p:
		h.Insert(a)
	h.PrintInf()
	print("删除操作:")
	p = [2,0]
	for a in p:
		if h.Delete(a) == -1:
			print("Can't find", a, "/Delete Error")
		else:
			print("Delete", a)
	h.PrintInf()

	h.Insert(1)
	h.Insert(10)
	p = [10, 20, 4, 3]
	for a in p:
		if h.Find(a) == -1:
			print("Can't find", a)
		else:
			print("Yes,",a, "in Hash")
	h.PrintInf()

def main():
	test01()
	# solve()
main()


import time
class robot:
    "Hi i am robot class."

    def __init__(self,name='robot',work=None,price=0):

        self.name = name
        self.work = work
        self.price = price

    def show(self):

        print("Name = ",self.name)
        time.sleep(1)
        print("Type = ",self.work)
        time.sleep(1)
        print("Price = ",self.price)
        time.sleep(1)

    def __del__(self):

        print("\n\nDeleting name ",self.name)
        del self.name
        time.sleep(1)
        print("\n\nDeleting work ",self.work)
        del self.work
        time.sleep(1)
        print("\n\nDeleting price ",self.price)
        del self.price
        time.sleep(1)

obj1 = robot()
obj2 = robot('sachin')
obj3 = robot('arpit','comedian')
obj4 = robot('aditi','student',50000)

print("\n\n")
obj1.show()
print("\n\n")
obj2.show()
print("\n\n")
obj3.show()
print("\n\n")
obj4.show()

print("\n\n")


# Part 1: Memory reference
#
# this script is able to run on teach.cs
# First you need to make sure proper "ref" files are in /u/csc369h/summer/pub/a3/traces/ folder
# you can directly run "python3 analysis.py" to see the print output or
# use "python3 analysis.py > analysis.txt" to see the result in a file (here it's analysis.txt)
#

if __name__ == "__main__":
    path = "/u/csc369h/summer/pub/a3/traces/addr-"
    traces = ["blocked.ref", "matmul.ref", "repeatloop.ref", "simpleloop.ref"]
    for i in traces:
        curr_path = path + i
        print("Current: ", curr_path)
        ins_num = 0
        data_num = 0
        store = 0
        load = 0
        modify = 0
        instruction = 0
        Instructions = dict()
        Data = dict()

        with open(curr_path, "r") as curr_file:
            lines = curr_file.readlines()

            address = ""

            for j in lines:
                j = j.strip()

                if j[0] == "S":
                    store += 1
                    address = j.split(" ")[1][:-2]
                    address = address[:-3] + "000"
                    if address in Data.keys():
                        Data[address] += 1
                    else:
                        data_num += 1
                        Data[address] = 1

                elif j[0] == "L":
                    load += 1
                    address = j.split(" ")[1][:-2]
                    address = address[:-3] + "000"
                    if address in Data.keys():
                        Data[address] += 1
                    else:
                        data_num += 1
                        Data[address] = 1

                elif j[0] == "M":
                    modify += 1
                    address = j.split(" ")[1][:-2]
                    address = address[:-3] + "000"
                    if address in Data.keys():
                        Data[address] += 1
                    else:
                        data_num += 1
                        Data[address] = 1

                elif j[0] == "I":
                    instruction += 1
                    address = j.split("  ")[1][:-2]
                    address = address[:-3] + "000"
                    if address in Instructions.keys():
                        Instructions[address] += 1
                    else:
                        ins_num += 1
                        Instructions[address] = 1
        print("The number of instruction pages (I): ", ins_num)
        print("The number of data pages (S, L, M): ", data_num)
        print("Count: ")
        print("  Instructions ", instruction)
        print("  Loads        ", load)
        print("  Stores       ", store)
        print("  Modifies     ", modify)
        print("Instructions: ")
        for k in Instructions:
            print("{},{}".format(k, Instructions[k]))
        print("Data: ")
        for k in Data:
            print("{},{}".format(k, Data[k]))
        print("\n\n")


import tkinter as tk
from tkinter import ttk

class RightNavbarView(tk.Frame):
    """ Navigation Bar """

    def __init__(self, parent, getall_callback, delete_callback, page_popup_callback):
        """ Initialize the nav bar """
        tk.Frame.__init__(self, parent)
        self._parent = parent

        self._getall_callback = getall_callback
        self._delete_callback = delete_callback
        self._page_popup_callback = page_popup_callback

        self._create_widgets()

    def _create_widgets(self):
        """" Creates the widgets for the right navigation view """
        self._get_all_button = tk.Button(self, text="Get All Readings", command=self._getall_callback, width=13)
        self._get_all_button.grid(row=1, column=0, padx=(0,540), pady=(0,8))

        self._update_button = tk.Button(self, text="Update Reading", command=self._page_popup_callback, width=12)
        self._update_button.grid(row=4, column=2, padx=10, pady=(0,155))
        self._delete_button = tk.Button(self, text="Delete Reading", command=self._delete_callback, width=12)
        self._delete_button.grid(row=4, column=2, padx=10, pady=(0,100))

        self.selected_item = ''

        # Data table view
        self._scrollbar = tk.Scrollbar(self, orient=tk.VERTICAL)

        self.table = ttk.Treeview(self, show="headings", yscrollcommand=self._scrollbar.set)
        self._scrollbar.config(command=self.table.yview)
        self.table.bind('<ButtonRelease-1>', self.get_selected_item)
        self.table.grid(row=4, column=0)
        self._scrollbar.grid(row=4, column=1, sticky=tk.N+tk.S+tk.W+tk.E)
        self.table['columns'] = ('id',
                                 'timestamp',
                                 'model',
                                 'min_reading',
                                 'avg_reading',
                                 'max_reading',
                                 'status')
        self.table.heading('id', text="ID")
        self.table.heading('timestamp', text="Date")
        self.table.heading('model', text="Sensor Name")
        self.table.heading('min_reading', text="Min Reading")
        self.table.heading('avg_reading', text="Avg Reading")
        self.table.heading('max_reading', text="Max Reading")
        self.table.heading('status', text="Status")

        self.table.column('id', width=45)
        self.table.column('timestamp', width=170)
        self.table.column('model', width=170)
        self.table.column('min_reading', width=80)
        self.table.column('avg_reading', width=80)
        self.table.column('max_reading', width=80)
        self.table.column('status', width=70)

    def insert_data(self, data):
        """" Insert data into treeview table """
        data_list = []

        for key,value in data.items():
            data_list.append(value)
        self.table.insert('', 'end', values=(data_list))

    def get_selected_item(self, a):
        """" Assigns selected reading properties on mouseclick from treeview table """
        current_item = self.table.focus()
        current_item_dict = self.table.item(current_item)
        self.selected_item = current_item_dict

    def get_selected_row(self):
        """" Get selected reading properties on mouseclick from treeview table"""
        current_row = self.table.focus()
        return self.table.item(current_row)

    def delete_log(self, selected_id):
        """" Remove row by ID from treeview table """
        for row in self.table.get_children():
            if self.table.item(row)["values"][0] == selected_id:
                self.table.delete(row)


from PIL import Image
from array import array
import numpy as np
import os

fileName = 'goku.bmp'

im = Image.open(fileName)
pix = im.load()
w, h = im.size

pixels = np.zeros(w*h, dtype=np.uint16)  # 0xff,  dtype=np.int8)
z=0
for j in range(h):
	for i in range(w):
		r,g,b=pix[i, j]
		pixels[z] = ((int(r / 255 * 31) << 11) | (int(g / 255 * 63) << 5) | (int(b / 255 * 31)))  # ((r&0x1f)<<11) | ((g&0x3f)<<5) | ((b&0x1f)<<0)
		#print(pixels[z])
		z = z+1
outputFileName = fileName + '.bin'
pixels.astype('int16').tofile(outputFileName)
cmd = 'objcopy --input-target=binary --output-target=ihex ' + \
	outputFileName + ' ' + fileName + '.hex'
os.system(cmd)
os.system('cat ' + fileName + '.hex')


# -*- coding: utf-8 -*-
"""
Created on Thu Jan 31 15:18:26 2019

@author: babybearming
"""
import numpy as np
import pandas as pd
from metpy.interpolate import (interpolate_to_points)
import os

def iniset():
    datapath='./Data/'
    folder_name=['PRE']
    ele_name=['pre']
    stationid_name='station_255.txt'
    return datapath,folder_name,ele_name,stationid_name

def stationidread(datapath,stationid_name):
    stationid=pd.read_csv(datapath+stationid_name,sep=' ',header=0)
    return stationid

def rangedate(startday,endday):
    p=pd.date_range(startday,endday,freq='D')
    pstr=p.strftime('%Y%m%d')
    return pstr

datapath,folder_name,ele_name,stationid_name=iniset()
stationid=stationidread(datapath,stationid_name)
xi=stationid[['lon','lat']].values
stanums=len(xi)

year=2018
yearstr=str(year)

startday=yearstr+'-06-01'
endday=yearstr+'-09-30'

ynum=25;xnum=25;tforenum=10;varnum=51;
x_grid=np.arange(110,122.5,0.5)
y_grid=np.arange(33,45.5,0.5)

lon,lat=np.meshgrid(x_grid,y_grid)
lon=lon.reshape((-1,1))
lat=lat.reshape((-1,1))
lonlat=np.concatenate([lon,lat],axis=1)

ecpre_tmp_path='./Data/ecpre_tmp/'

pstr=rangedate(startday,endday)
tnum=len(pstr)

stadatacell=[i for i in range(tforenum)]
for tt in range(tforenum):
    print(tt)
    stadata=np.full([varnum,tnum,stanums],np.nan)
    for var in range(varnum):
        for inx,daystr in enumerate(pstr):
            filename=ecpre_tmp_path+daystr+'.npy'
            try:
                M=np.load(filename)
                fredata=M[tt,var].reshape((-1,1))
                stadata[var,inx,:]=list(interpolate_to_points(lonlat,fredata,xi))
            except:
#                print(filename+' is not exsit!')
                continue
    stadatacell[tt]=stadata
#
stafore2obs=[i for i in range(tforenum)]
for tt in range(tforenum):
    stafore2obs[tt]=np.full([varnum,tnum+tt+1,stanums],np.nan)
    foretmp=np.full([varnum,tnum+tt+1,stanums],np.nan)
    foretmp[:,tt+1:,:]=stadatacell[tt]
    stafore2obs[tt]=foretmp

for tt in range(tforenum):
    filepath='./Data/forecastdata/'+str(tt+1)+'/'
    if not os.path.exists(filepath):
        os.makedirs(filepath)
    np.save(filepath+yearstr+'.npy',stafore2obs[tt])


#Filters nucelotides out of a FASTA file

def filter_fasta_file(fasta_file):
    f = open(fasta_file, "r")
    totalfile = f.read()
    line_list = totalfile.split(">")[1:]
    counter = 0
    for k in line_list:
        line_list[counter] = k.split("\n")
        line_list[counter].remove('')
        counter += 1
    counter = 0
    for line in line_list[:]:
        is_protien = False
        for char in line[1:]:
            if is_protien:
                break
            for char in char[:len(char) - 1]:
                if char not in ['A', 'U', 'G', 'C', 'N', 'X']:
                    is_protien = True
                    break
        if is_protien == False:
            line_list = line_list[:counter] + line_list[counter+1:]
            counter -= 1
        counter += 1
    return line_list

def build_new_fasta_file(fasta_file, line_list, for_blast_cluster):
    dot_index = fasta_file.find(".")
    slash_index = fasta_file.find("/")
    file_extension = '_no_nuc'
    if for_blast_cluster:
        file_extension += '_wa'
        appendage_for_blast_cluster = 0
    if slash_index == -1:
        o = open(fasta_file[: dot_index] + file_extension + ".txt", "w")
    else:
        o = open(fasta_file[slash_index + 1: dot_index] + file_extension + ".txt", "w")
    is_first_line = True
    ########################

    ########################
    for line in line_list:
        is_title = True
        sequence = ""
        for char in line:
            if is_title:
                if is_first_line:
                    protien_prefix = ">" + char[0:4] + "_"
                    is_first_line = False
                else:
                    protien_prefix = "\n" + ">" + char[0:4] + "_"
                protien_suffix = char[5]
                next_suffix_character = 6
                while char[next_suffix_character] != '|':
                    protien_suffix += char[next_suffix_character]
                    next_suffix_character += 1
                protien_name = protien_prefix + protien_suffix
                if for_blast_cluster:
                    protien_name += "_" + str(appendage_for_blast_cluster)
                is_title = False
            else:
                #o.write(char)
                pass
                sequence += char
        if len(sequence) > 10 and len(sequence) < 1001:
            o.write(protien_name + "\n")
            o.write(sequence)
        if for_blast_cluster:
            appendage_for_blast_cluster += 1
    o.close()

def main(fasta_file, for_blast_cluster):
    #If using nucelotide filter for blast cluster, appendage numbers will be added to protien names with same appendage
    #but different cases (e.g. 1O4C_A and 104C_a). This is because blastcluster does not regonize different cases
    line_list = filter_fasta_file(fasta_file)
    build_new_fasta_file(fasta_file, line_list, for_blast_cluster)

main('fasta_2000_2015.txt', True)
#main('fastaXRAY.txt', False)


"""This module will contain fixtures to test graph.py."""

import pytest
from ..depth_first import Graph

@pytest.fixture()
def graph_empty():
    g = Graph()
    return g

@pytest.fixture()
def graph_one():
    g = Graph()
    g.gdict = {
        'A': {'B': 10},
        'B': {'A': 5, 'D': 15, 'C': 20},
        'C': {'E': 1},
        'D': {'A': 5},
        'E': {'F': 2, 'B': 4},
        'F': {'D': 11}
    }
    return g

@pytest.fixture()
def graph_two():
    g = Graph()
    g.gdict = {
        'A': {'B': 10, 'C': 15},
        'B': {'D': 15, 'E': 5, 'C': 2},
        'C': {'F': 50, 'G': 25},
        'D': {},
        'E': {'C': 5},
        'F': {'E': 10},
        'G': {'F': 20}
    }
    return g

@pytest.fixture()
def graph_map():
    map = {
            'Pandora': {'Arendelle': 150, 'Metroville': 82},
            'Arendelle': {'Pandora': 150, 'Metroville': 99, 'New Monstropolis': 42},
            'Metroville': {'Pandora': 82, 'Arendelle': 99, 'New Monstropolis': 105, 'Naboo': 26, 'Narnia': 37},
            'New Monstropolis': {'Arendelle': 42, 'Metroville': 105, 'Naboo': 73},
            'Naboo': {'New Monstropolis': 73, 'Metroville': 26, 'Narnia': 250},
            'Narnia': {'Metroville': 37, 'Naboo': 250}
        }
    g = Graph(map)
    return g

@pytest.fixture()
def graph_three():
    dictionary = {
        'A': {'B': 0, 'D': 0},
        'B': {'A': 0, 'C': 0, 'D': 0},
        'C': {'B': 0, 'G': 0},
        'D': {'A': 0, 'B': 0, 'E': 0, 'H': 0, 'F': 0},
        'E': {'D': 0},
        'F': {'D': 0, 'H': 0},
        'G': {'C': 0},
        'H': {'F': 0, 'D': 0},
        }
    g = Graph(dictionary)
    return g


import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
cur_db = None
cur_col = None

def initMongoUP():
    return myclient

def addDBUP(db_name):
    global cur_db
    dblist = myclient.list_database_names()
    for db in dblist:
        if db == db_name:
            cur_db = myclient[db_name]
            return
    cur_db = myclient[db_name]
    print("数据库创建完成:" + cur_db.name)

def addCollectUP(collect_name):
    global cur_col
    if cur_db:
        collects = cur_db.list_collection_names()
        for col in collects:
            if col == collect_name:
                cur_col = cur_db[collect_name]
                return
        cur_col = cur_db[collect_name]
        print("数据表创建完成:" + cur_col.name)
        # cur_col.create_index([("日期", 1)], unique=True, background=True)
    else:
        print("请先创建数据库!")

def insertUP(sql, isMulti=False):
    if isMulti:
        cur_col.insert_many(sql)
    else:
        cur_col.insert_one(sql)

def findUP(sql=None, filterField=None, isMulti=False):
    if isMulti:
        # 查找所有数据
        return cur_col.find(sql, filterField)
    else:
        # 查找一条数据
        return cur_col.find_one()

    # 需要返回字段设置为1，否则设置为0
    # 除了 _id 你不能在一个对象中同时指定 0 和 1，如果你设置了一个字段为 0，则其他都为 1
    # cur_col.find({}, {"name": 1, "age": 0})
    # 使用sql来选择,并限制返回最大条数为3
    # sql = {"name": "weicong"}
    # 使用正则，配置name首字母为R的记录
    # sql_reg = {"name": {"$regex": "^R"}}
    # cur_col.find(sql).limit(3)
    # 升序
    # cur_col.find(sql).sort("alexa")
    # 降序
    # cur_col.find(sql).sort("alexa", -1)

def updateUP(query_sql, update_sql, isMulti=False):
    if isMulti:
        cur_col.update_many(query_sql, update_sql)
    else:
        cur_col.update_one(query_sql, update_sql)

def deleteUP(sql, isMulti=False):
    if isMulti:
        cur_col.delete_many(sql)
    else:
        cur_col.delete_one(sql)

def dropUP():
    # 删除集合
    cur_col.drop()


import pytest
import os

from sklearn.dummy import DummyClassifier
from mlserver.settings import ModelSettings
from mlserver.errors import InferenceError
from mlserver.types import RequestInput, RequestOutput

from mlserver_sklearn import SKLearnModel
from mlserver_sklearn.sklearn import (
    PREDICT_OUTPUT,
    PREDICT_PROBA_OUTPUT,
    WELLKNOWN_MODEL_FILENAMES,
)

def test_load(model: SKLearnModel):
    assert model.ready
    assert type(model._model) == DummyClassifier

@pytest.mark.parametrize("fname", WELLKNOWN_MODEL_FILENAMES)
async def test_load_folder(fname, model_uri: str, model_settings: ModelSettings):
    model_folder = os.path.dirname(model_uri)
    model_path = os.path.join(model_folder, fname)
    os.rename(model_uri, model_path)

    model_settings.parameters.uri = model_path  # type: ignore

    model = SKLearnModel(model_settings)
    await model.load()

    assert model.ready
    assert type(model._model) == DummyClassifier

async def test_multiple_inputs_error(model: SKLearnModel, inference_request):
    inference_request.inputs.append(
        RequestInput(name="input-1", shape=[2], data=[0, 1], datatype="FP32")
    )

    with pytest.raises(InferenceError):
        await model.predict(inference_request)

async def test_invalid_output_error(model: SKLearnModel, inference_request):
    inference_request.outputs = [RequestOutput(name="something_else")]

    with pytest.raises(InferenceError):
        await model.predict(inference_request)

@pytest.mark.parametrize(
    "req_outputs",
    [
        [],
        [PREDICT_OUTPUT],
        [PREDICT_PROBA_OUTPUT],
        [PREDICT_OUTPUT, PREDICT_PROBA_OUTPUT],
    ],
)
async def test_predict(model: SKLearnModel, inference_request, req_outputs):
    inference_request.outputs = [
        RequestOutput(name=req_output) for req_output in req_outputs
    ]

    response = await model.predict(inference_request)

    input_data = inference_request.inputs[0].data
    if len(req_outputs) == 0:
        # Assert that PREDICT_OUTPUT is added by default
        req_outputs = [PREDICT_OUTPUT]

    assert len(response.outputs) == len(req_outputs)
    for req_output, output in zip(req_outputs, response.outputs):
        assert output.name == req_output
        assert output.shape[0] == len(input_data)  # type: ignore


from multiprocessing import Manager
from Module_Tester.EX_db import db_make
from Module_Tester.EX_RUN_Module import *
from Module_Tester.EX_RUN_Module_FAST import *
from Module_Tester.DB_collector.DB_collector_Module import *
import argparse

FAST = True

class body:
    def __init__(self):
        # 초기 입력 인자 전달 -------------------------------------------------------------------- #
        parser = argparse.ArgumentParser(description='CNS 플랫폼_TE Ver')
        parser.add_argument('--comip', type=str, default='', required=False, help="현재 컴퓨터의 ip [default='']")
        parser.add_argument('--comport', type=int, default=7101, required=False, help="현재 컴퓨터의 port [default=7001]")
        parser.add_argument('--cnsip', type=str, default='192.168.0.93', required=False, help="현재 컴퓨터의 ip [default='']")
        parser.add_argument('--cnsport', type=int, default=7101, required=False, help="현재 컴퓨터의 port [default=7001]")
        self.args = parser.parse_args()
        print('=' * 25 + '초기입력 파라메터' + '=' * 25)

        with open('EX_pro.txt', 'w') as f:                             # 타기능에서 CNS 정보 확인 용
            f.write(f'{self.args.cnsip}\t{self.args.cnsport}')

        print(self.args)
        self.shared_mem = generate_mem().make_mem_structure()
        # ---------------------------------------------------------------------------------------- #
        if FAST:
            pro_list = [RUN_FREEZE_FAST(self.shared_mem, IP=self.args.comip, Port=self.args.comport),  # [1]
                        EX_module(self.shared_mem)  # [3]
                        ]
        else:
            pro_list = [RUN_FREEZE(self.shared_mem, IP=self.args.comip, Port=self.args.comport),    # [1]
                        EX_module(self.shared_mem)                                                  # [3]
                        ]

        self.process_list = pro_list

    def start(self):
        [_.start() for _ in self.process_list]
        [_.join() for _ in self.process_list]

class generate_mem:
    def make_clean_mem(self):
        memory_dict = {'Clean': True, 'Loop': False, 'Run': False}
        print('Clean 메모리 생성 완료')
        return memory_dict

    def make_main_mem_structure(self, max_len_deque=10):
        memory_dict = db_make().make_db_structure(max_len_deque)
        print('Main 메모리 생성 완료')
        return memory_dict

    def make_mem_structure(self):
        print('=' * 25 + '메모리 생성 시작' + '=' * 25)
        memory_list = [Manager().dict(self.make_main_mem_structure(max_len_deque=10)),    # [0]
                       Manager().list(),                                                  # [1]
                       Manager().dict(self.make_clean_mem()),                             # [-1]
                       ]
        print('=' * 25 + '메모리 생성 완료' + '=' * 25)
        return memory_list

if __name__ == '__main__':
    main_process = body()
    main_process.start()


import pyttsx3
import PyPDF2 as pdf

# Speech Engine Initialization
engine = pyttsx3.init()
speaker = engine.getProperty('voice')
engine.setProperty('voice', 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\TTS_MS_EN-US_ZIRA_11.0') # Setting voice property
def speak(speech):
	engine.say(speech)
	engine.runAndWait()
# ---------------------------------------------- #

# User Input's
bookNameInput = input("Enter book name: ")
bookName = bookNameInput + ".pdf"
pageStart = int(input("Enter a page to start from: "))

# Opening/Reading PDF
pdfBook = open(bookName, 'rb')
reader = pdf.PdfFileReader(pdfBook)
pages = reader.numPages # To get the number of pages

for i in range(pageStart, pages+1):
	page = reader.getPage(pageStart)
	texts = page.extractText()
	speak(texts)


import rsa
import zlib
import random
import struct
import socket
import time
import argparse
import ctypes

zlibdll = ctypes.CDLL('libz.so.1.2.11')
zlibdll.crc32_combine.argtypes = [ctypes.c_long, ctypes.c_long, ctypes.c_long]
zlibdll.crc32_combine.restype = ctypes.c_long

parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', type=int, default=1337, help='port, to send packets to')
parser.add_argument('-i', '--packet', required=True, help='packet id')
parser.add_argument('-k', '--key', required=True, help='private key file')
parser.add_argument('-b', '--binary', required=True, help='binary file')
args = parser.parse_args()

with open(args.key, mode='r') as _:
	key_data = _.read()
private_key = rsa.PrivateKey.load_pkcs1(key_data)

with open(args.binary, 'r') as _:
	data = _.read()

data_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = args.port
packet_id = int(eval(args.packet))

sequence_div = 2713
sequence_mod = random.randint(0, sequence_div - 1)

message_div = 257
message_mod = random.randint(0, message_div - 1)

data_len = len(data)
crc32cmb = zlib.crc32(data, 0) & 0xffffffff

sequence = 0
data_crc = 0
for _ in range(9999):
	xor_key = random.randint(0, 0xffff)
	checksums = random.randint(1, 24)
	message = struct.pack('!IIHH', packet_id, sequence, xor_key, checksums)
	xor_key |= xor_key << 16
	while checksums:
		# data_crc = zlib.crc32(data, data_crc) & 0xffffffff
		data_crc = zlibdll.crc32_combine(data_crc, crc32cmb, data_len)
		if sequence % sequence_div == sequence_mod:
			message += struct.pack('!I', (data_crc + 3) ^ xor_key)
		else:
			message += struct.pack('!I', data_crc ^ xor_key)
		sequence += 1
		checksums -= 1
	signature = rsa.sign(message, private_key, 'SHA-256')
	if _ % message_div == message_mod:
		message = message[:12] + '*' + message[13:]
	message += signature
	data_socket.sendto(message, ('127.0.0.1', port))
	time.sleep(0.01 * random.random())
data_socket.close()


from django import forms
from postman.forms import *
from django import forms

from pages.models import Document, Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('commentContent',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['commentContent'].widget.attrs.update({'class':'form-control'},
                                                          rows="1",
                                                          placeholder="Got something to say?",
                                                          maxlength=100)

class CustomWriteForm(WriteForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['recipients'].widget.attrs.update({'class':'form-control'})
        self.fields['body'].widget.attrs.update({'class':'form-control'})
        self.fields['subject'].widget.attrs.update({'class':'form-control'})

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('description', 'document', )