# -*- coding: utf-8 -*-
"""
Created on Sat Apr  3 14:36:46 2021

"""

import numpy as np
import pandas as pd
from scipy import stats

def splitgroups(array):
    hasGroup = []
    noGroup = []
    hasSadex = 0
    noSadex = 0
    for index in array:
        if(index[1] == 1):
            hasGroup.append(index[0])
            hasSadex += index[0]
        else:
            noGroup.append(index[0])
            noSadex += index[0]
    return [hasSadex, noSadex, hasGroup, noGroup]

sadex1 = np.genfromtxt('Sadex1.txt')
sadex2 = np.genfromtxt('Sadex2.txt')
sadex3 = np.genfromtxt('Sadex3.txt')
sadex4 = np.genfromtxt('Sadex4.txt')

s1 = pd.DataFrame(data=sadex1)
s2 = pd.DataFrame(data=sadex2)
s3 = pd.DataFrame(data=sadex3)
s4 = pd.DataFrame(data=sadex4)

groupSums = splitgroups(sadex1)
hasMean = groupSums[0]/(sadex1.shape[0]/2)
noHaveMean = groupSums[1]/(sadex1.shape[0]/2)
diffMean = noHaveMean - hasMean
study1 = stats.ttest_ind(groupSums[2], groupSums[3]).pvalue
diffMean2 = s2[0].mean() - s2[1].mean()
study2 = stats.ttest_ind(s2[0], s2[1]).pvalue
groupSums2 = splitgroups(sadex3)
study3 = stats.ttest_ind(groupSums2[2], groupSums2[3]).pvalue
study4 = stats.ttest_ind(s4[0], s4[1]).pvalue
standardDev4 = s4.std()
clinicalSig = (s4[0].mean() - s4[1].mean())/standardDev4[1]


import subprocess
from exceptions import *

def run_cmd(cmd, wd):
    p = subprocess.Popen(cmd, cwd=wd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    output, errors = p.communicate()
    if p.returncode is not 0:
        raise CmdFailure(cmd, "Exec of cmd failed")
    return output, errors

def exec_rubocop(cookbook_dir):
    o, e = run_cmd('/usr/bin/rubocop .', cookbook_dir)
    print(o)
    print(e)

def exec_rubytailor(cookbook_dir):
    o, e = run_cmd('/usr/bin/tailor .', cookbook_dir)
    print(o)
    print(e)

def exec_chefspec(cookbook_dir):
    o, e = run_cmd('/usr/bin/rspec -c', cookbook_dir)
    print(o)
    print(e)

def main():
    exec_rubytailor()
    exec_rubocop()
    exec_chefspec()

if __name__ == '__main__':
    main()


"""Transparent Origami
https://adventofcode.com/2021/day/13
"""
import re

import numpy as np

def solve_a(s: str) -> int:
    """
    Examples:
    >>> solve_a(test_string)
    17
    """
    ixs, folds = s.split("\n\n")
    ixs = np.array(
        [line.split(",") for line in ixs.strip("\n").split("\n")], dtype=int
    )[:, ::-1].T
    n, m = ixs.max(axis=1) + 1
    mat = np.zeros((n, m), dtype=bool)
    mat[ixs[0], ixs[1]] = True

    folds = [
        re.match(r"fold along (\w)=(\d+)", line).groups() for line in folds.split("\n")
    ][0:1]
    for along, _ in folds:
        mat = fold_mat(along, mat)

    return mat.sum()

def fold_mat(along: str, mat: list[list[str]]) -> list[list[str]]:
    n, m = mat.shape
    if along == "y":
        new_mat = mat[0 : n // 2, :] | mat[: n // 2 : -1, :]
    if along == "x":
        new_mat = mat[:, 0 : m // 2] | mat[:, : m // 2 : -1]
    return new_mat

def solve_b(s: str) -> int:
    ixs, folds = s.split("\n\n")
    ixs = [line.split(",") for line in ixs.strip("\n").split("\n")]
    ixs = [(int(x), int(y)) for y, x in ixs]

    n, m = max(x for x, _ in ixs) + 1, max(y for _, y in ixs) + 1
    mat = np.zeros((n, m), dtype=bool)
    for i, j in ixs:
        mat[i][j] = True

    folds = [
        re.match(r"fold along (\w)=(\d+)", line).groups() for line in folds.split("\n")
    ]
    for along, _ in folds:
        mat = fold_mat(along, mat)
    print("\n".join(["".join(["1" if x else " " for x in row]) for row in mat]))
    return 0

test_string = """6,10
0,14
9,10
0,3
10,4
4,11
6,0
6,12
4,1
0,13
10,12
3,4
3,0
8,4
1,10
2,14
8,10
9,0

fold along y=7
fold along x=5"""


import os, re
from src.zendesk_weeklog import ZendeskWeekloger
from src.controller import Controller, _last_week_date

ZENDESK_CUSTOM_FIELD = 360028226411

def test_bad_zd_assignee():
    "with a bad assignee we should get an empty dict"
    zen = ZendeskWeekloger(
        os.environ["ZENDESK_HOST"],
        os.environ["ZENDESK_KEY"],
        "this_is_not_a_person@lies.com",
    )

    tickets = zen._fetch_zendesk_tasks(test_last_week_date())
    assert isinstance(tickets, dict)
    assert len(tickets) == 0

def test_last_week_date():
    "check the returned string matches the right format"

    date = _last_week_date(7)
    assert isinstance(date, str)
    match = re.match("[0-9]{4}-[0-2][0-9]-[0-3][0-9]", date)

    assert match is not None
    return date

def test_bad_zd_response():
    """Checks type handling of zd response"""
    zen = ZendeskWeekloger(
        os.environ["ZENDESK_HOST"], os.environ["ZENDESK_KEY"], "not_a_person@lies.com"
    )
    zen._convert_zendesk_tasks_to_work_items(["123", 456, None])
    bad_dict = {"Hello there": "hi!", 123: 456, "test3": None}
    zen._convert_zendesk_tasks_to_work_items(bad_dict)

def test_filter():
    """Checks whether or not the assignee is filtered properly"""

    zen = ZendeskWeekloger(
        os.environ["ZENDESK_HOST"], os.environ["ZENDESK_KEY"], os.environ["TEST_EMAIL"]
    )
    time = zen._get_time_total_for_task(1236377, "2022-05-17")
    assert time == 0
    time = zen._get_time_total_for_task(1236377, "2022-05-01")
    assert time == 1260


# -*- coding: utf-8 -*-
from annoying.decorators import render_to
from apps.control.utils import can_access
from apps.seo.models import Metadata
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect
from rollyourown.seo.admin import get_path_form
from rollyourown.seo.base import create_metadata_instance
from django.shortcuts import get_object_or_404

@can_access()
@render_to('control/seo_form.html')
def seo_form(request):
    site = Site.objects.get_current()
    url = request.GET['url']
    model_class = Metadata._meta.get_model('path')

    if request.method == 'POST':
        metadata, md_created = model_class.objects.get_or_create(_path=url, _site=Site.objects.get_current())
        metadata.title = request.POST['title']
        metadata.heading = request.POST['heading']
        metadata.keywords = request.POST['keywords']
        metadata.description = request.POST['description']
        metadata.tooltip = request.POST['tooltip']
        metadata.paginator = request.POST['paginator']
        metadata._site_id = Site.objects.get_current().id
        metadata.save()
        return HttpResponseRedirect(request.POST['_path'])
    else:
        form = get_path_form(Metadata)
        try:
            metadata = model_class.objects.get(_path=url, _site=Site.objects.get_current())
        except model_class.DoesNotExist:
            metadata = None
    return {
        'form': form,
        'site': site,
        'url': url,
        'obj':metadata
    }


import os
import subprocess

mainpath = os.getcwd()

Test_Cases = ['b+tree', 'backprop', 'bfs', 'cfd', 'heartwall', 'hotspot', 'hotspot3D', 'kmeans', 'lavaMD', 'leukocyte', 'lud', 'myocyte', 'nn', 'nw', 'particlefilter', 'pathfinder', 'srad', 'streamcluster']

original_size = []
IR_size = []

idx = 0

def update_idx(index):
    index+=1
    print(Test_Cases[index-1])
    return index

def getllvmsize(command):
    if os.path.exists("temp.txt"):
        os.remove("temp.txt")
    f = open("temp.txt", "w")
    f.close()
    os.system(command + " > temp.txt")
    with open('temp.txt') as f:
        res = f.readlines()
    f.close()
    os.remove("temp.txt")
    return int(res[0][:-6])

for _ in Test_Cases:
    original_size.append(0)
    IR_size.append(0)

def parsefiles(benchmark):
    if benchmark == 'leukocyte':
        os.chdir(mainpath + '/' + benchmark + '/OpenMP')
    else:
        os.chdir(mainpath + '/' + benchmark)
    if benchmark == 'cfd':
        original_size[idx] += os.path.getsize('euler3d_cpu.cpp')
        os.system("clang++ -Wno-everything -S -emit-llvm euler3d_cpu.cpp")
        size = getllvmsize(mainpath + '/LLVMEst.exe ' + 'euler3d_cpu.ll')
        print(size)
        IR_size[idx] += size
    elif benchmark == 'heartwall':
        for path, directories, files in os.walk('.'):
            os.chdir(path)
            for file in files:
                if file.endswith(".c") or file.endswith(".cpp"):
                    original_size[idx] += os.path.getsize(file)
        os.system("clang -Wno-everything -S -emit-llvm main.c")
        os.system("clang -Wno-everything -S -emit-llvm avilib.c")
        os.system("clang -Wno-everything -S -emit-llvm avimod.c")
        size = getllvmsize(mainpath + '/LLVMEst.exe ' + 'main.ll')
        print(size)
        IR_size[idx] += size
        size = getllvmsize(mainpath + '/LLVMEst.exe ' + 'avilib.ll')
        print(size)
        IR_size[idx] += size
        size = getllvmsize(mainpath + '/LLVMEst.exe ' + 'avimod.ll')
        print(size)
        IR_size[idx] += size
    elif benchmark == 'myocyte':
        for path, directories, files in os.walk('.'):
            os.chdir(path)
            for file in files:
                if file.endswith('.c'):
                    original_size[idx] += os.path.getsize(file)
        os.system("clang -Wno-everything -S -emit-llvm main.c")
        size = getllvmsize(mainpath + '/LLVMEst.exe main.ll')
        print(size)
        IR_size[idx] += size
    elif benchmark == 'nn':
        original_size[idx] += os.path.getsize('nn_openmp.c')
        os.system("clang -Wno-everything -S -emit-llvm nn_openmp.c")
        size = getllvmsize(mainpath + '/LLVMEst.exe ' + 'nn_openmp.ll')
        print(size)
        IR_size[idx] += size
    else:
        for path, directories, files in os.walk('.'):
            os.chdir(path)
            for file in files:
                if file.endswith(".c"):
                    original_size[idx] += os.path.getsize(file)
                    os.system("clang -Wno-everything -S -emit-llvm " + file)
                    size = getllvmsize(mainpath + '/LLVMEst.exe ' + file[:-2] + '.ll')
                    print(size)
                    IR_size[idx] += size
                if file.endswith(".cpp"):
                    original_size[idx] += os.path.getsize(file)
                    os.system("clang++ -Wno-everything -S -emit-llvm " + file)
                    size = getllvmsize(mainpath + '/LLVMEst.exe ' + file[:-4] + '.ll')
                    print(size)
                    IR_size[idx] += size

for x in Test_Cases:
    parsefiles(x)
    idx = update_idx(idx)

os.chdir(mainpath)
if os.path.exists("Names.txt"):
    os.remove("Names.txt")
f = open("Names.txt", "w")
for x in Test_Cases:
    f.write(x + "\n")

if os.path.exists("Orig_size.txt"):
    os.remove("Orig_size.txt")
f = open("Orig_size.txt", "w")
for x in original_size:
    f.write(str(x) + "\n")

if os.path.exists("IR_size.txt"):
    os.remove("IR_size.txt")
f = open("IR_size.txt", "w")
for x in IR_size:
    f.write(str(x) + "\n")


import heapq

# ヒープの要素はタプルに出来ます。これは、追跡される主レコードとは別に (タスクの優先度のような) 比較値を指定するときに便利です:
# >>> h = []
# >>> heappush(h, (5, 'write code'))
# >>> heappush(h, (7, 'release product'))
# >>> heappush(h, (1, 'write spec'))
# >>> heappush(h, (3, 'create tests'))
# >>> heappop(h)
# (1, 'write spec')

def dijkstra(s):
    hq = [(0, s)]
    heapq.heapify(hq) # リストを優先度付きキューに変換
    cost = [float('inf')] * n # 行ったことのないところはinf
    cost[s] = 0 # 開始地点は0
    while hq:
        c, v = heapq.heappop(hq)
        if c > cost[v]: # コストが現在のコストよりも高ければスルー   # なぜこのステップが必要なのか全くわからん。これに引っかかるパターンは既に下の操作で排除されているのではないのか。
            continue
        for d, u in e[v]:
            tmp = d + cost[v]
            if tmp < cost[u]:
                cost[u] = tmp
                heapq.heappush(hq, (tmp, u))
    return cost

n,m = map(int,input().split())
e = [[] for _ in range(n)]
for _ in range(m):
    a,b,t = map(int,input().split())
    a,b = a-1, b-1
    e[a].append((t, b))
    e[b].append((t, a))
ans = float('inf')
for i in range(n):
    dist = dijkstra(i)
    ans = min(ans, max(dist))
print(ans)
# print(e)                  # [[(10, 1)], [(10, 0), (10, 2)], [(10, 1)]]
# in 3 2
#    1 2 10
#    2 3 10


from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
NORTH = 90
SOUTH = 270
WEST = 180
EAST = 0

class Snake:

    def __init__(self):
        self.segments = []
        self.create_snake()
        self.head = self.segments[0]
        self.position = 2
        self.move_distance = [10, 15, 20]

    def create_snake(self):
        for position in STARTING_POSITIONS:
            self.add_segment(position)

    def add_segment(self, position):
        new_segment = Turtle("square")
        new_segment.color("white")
        new_segment.penup()
        new_segment.goto(position)
        self.segments.append(new_segment)

    def append_segment(self):
        self.position += 1
        self.add_segment(position=(self.position, 0))

    def move_easy(self):
        for seg_num in range(len(self.segments) - 1, 0, -1):
            new_x = self.segments[seg_num - 1].xcor()
            new_y = self.segments[seg_num - 1].ycor()
            self.segments[seg_num].goto(new_x, new_y)
        self.head.forward(self.move_distance[0])

    def move_medium(self):
        for seg_num in range(len(self.segments) - 1, 0, -1):
            new_x = self.segments[seg_num - 1].xcor()
            new_y = self.segments[seg_num - 1].ycor()
            self.segments[seg_num].goto(new_x, new_y)
        self.head.forward(self.move_distance[1])

    def move_hard(self):
        for seg_num in range(len(self.segments) - 1, 0, -1):
            new_x = self.segments[seg_num - 1].xcor()
            new_y = self.segments[seg_num - 1].ycor()
            self.segments[seg_num].goto(new_x, new_y)
        self.head.forward(self.move_distance[2])

    def up(self):
        if not self.head.heading() == SOUTH:
            self.head.setheading(NORTH)

    def down(self):
        if not self.head.heading() == NORTH:
            self.head.setheading(SOUTH)

    def right(self):
        if not self.head.heading() == WEST:
            self.head.setheading(EAST)

    def left(self):
        if not self.head.heading() == EAST:
            self.head.setheading(WEST)


import numpy as np

scenarios = input() # reading the number of scenarios

for scenariosIndex in range (int(scenarios)):

    bugs = input().split(" ")

    bugsQuantity = int(bugs[0])
    bugsInteractions = int(bugs[1])

    controlArray = np.zeros(bugsQuantity + 1, dtype=int)

    suspiciousBug = False

    for i in range(bugsInteractions):
        relation = input().split(" ")
        bugA = int(relation[0])
        bugB = int(relation[1])

        print(controlArray)

        # bugA and bugB without sex
        if (controlArray[bugA] == 0) and (controlArray[bugB] == 0):
            controlArray[bugA] = 1  # 1 for male
            controlArray[bugB] = 2  # 2 for female
        else:
            if((controlArray[bugA] != 0) and (controlArray[bugB] != 0)):
                if(controlArray[bugA] == controlArray[bugB]):
                    suspiciousBug = True
                else:
                    suspiciousBug = False

            if (controlArray[bugA] == 0):   # bugA has no sex
                if (controlArray[bugB] == 1):
                    controlArray[bugA] = 2
                else:
                    controlArray[bugA] = 1
            else:                           # bugB has no sex
                if (controlArray[bugA] == 1):
                    controlArray[bugB] = 2
                else:
                    controlArray[bugB] = 1

    if suspiciousBug:
        print("Scenario #" + str(scenariosIndex+1) + ":")
        print("Suspicious bugs found!")
    else:
        print("Scenario #" + str(scenariosIndex+1) + ":")
        print("No suspicious bugs found!")


import sys
sys.path.insert(0,"..") ## Set path to main directory

import os
import time
import copy
import numpy as np

import models.data_manager as data_manager

import warnings
warnings.filterwarnings("ignore")

start_time = time.time()

data_manager = data_manager()

data_path = "../../Data/CSV/"
output_path = "../../Data/output/"

### Load acceleration data
filenames = ['7501394_rec16112018_PRincon_PHAAET_S1_',
        '7501709_rec18112018_PRincon_PHAAET_S1_',
        '7501755_rec27112018_PRincon_PHAAET_AXY_S1',
        '8200163_rec14052019_PRoque_PHAAET_S1',
        '8200445_rec29042019_PRincon_PHAAET_S1',
        '8200473_rec24052019_PRincon_PHAAET_S1',
        '8200487_rec04052019_PRincon_PHAAET_S1',
        '8200718_PHAAET_rec08032019_PRincon',
        '8201653_PHAAET_rec21012021_ICima_Ninho39_36_S1',
        '8201667_PHAAET_rec21012021_ICima_Ninho68_21_S1',
        '8201720_rec31122020_ICima_PHAAET_ninho 71_21_S11_S1',
        '8201959_rec29122020_ICima_PHAAET_ninho 31_36_S1']

all_data = []

print("Starting...")
for filename in filenames:
    # Load data and filter acceleration signals with a butterworth filter
    initial_data = data_manager.load_data(filename, data_path)
    current_data = copy.deepcopy(initial_data)
    current_data.filter_accelerations(4, 0.4)
    all_data.append(current_data)
    print("Data loaded: " + filename)

### Extract the data
np.save(os.path.join(output_path, 'all_data.npy'), all_data)


from django.contrib import admin
from .models import Post, Category

# Register your models here.

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ["title", "user", "created", "published"]
    list_filter = ["user", "created", "published", "tags"]
    list_per_page = 20
    search_fields = ("title", "body", "user")
    date_hierarchy = "created"
    prepopulated_fields = {"slug": ("title",)}

@admin.register(Category)
class Category(admin.ModelAdmin):
    list_display = ["title", "slug", "available"]
    list_filter = ["title", "available"]
    search_fields = ["title"]
    prepopulated_fields = {"slug": ("title",)}


import random

class NameList:

    # Will store full names by alphanumeric code
    listOfNames: "dict[int, list[str]]" = {}

    def __init__(self):

        self.listOfNames = {}

    def set_sample(self):

        self.listOfNames = {}

        # Gets list of first names from file
        firstNames: list[str] = list()
        with open("first-names.txt") as f:
            lines = f.readlines()
        for name in lines:
            firstNames.append(name[:-1].lower())

        # Gets list of surnames from file
        lastNames: list[str] = list()
        with open("last-names.txt") as f:
            lines = f.readlines()
        for name in lines:
            lastNames.append(name[:-1].lower())

        # Produces 100 names by combining a random first name with a random surname
        while len(self.listOfNames) < 101:
            randFirstName = firstNames[random.randrange(len(firstNames))]
            randLastName = lastNames[random.randrange(len(lastNames))]
            name = randFirstName.capitalize() + " " + randLastName.capitalize()

            # Gets alphanumeric code for the generated name
            code = self.getNameCode(randFirstName) + self.getNameCode(randLastName)
            if code not in self.listOfNames:
                self.listOfNames[code] = [name]
            else:
                self.listOfNames[code].append(name)

    # Returns an alphanumeric code for the specified name
    def getNameCode(self, name: str) -> int:
        total = 0
        for c in name:
            if ord(c) != 32:  # Ignores spaces
                total += (ord(c) - 96)
        return total

    # Prints the alphanumeric code followed by a list of names with this code
    def printReport(self):
        for k in self.listOfNames.keys():
            print(str(k) + ": " + str(self.listOfNames[k]))


from adding_source import answer_add
from aiogram import executor, types
from connecting_VK_account import answer_connect
from create_bot import dp
from database_queries import add_new_user, disconnect_vk_account, get_user_info
from deleting_source import answer_delete
from handler import get_info_about_current_account, get_list_of_sources, is_user_added, is_vk_account_connected, set_status_to_OFF, set_status_to_ON
from KeyBoards import kb_account_VK_off, kb_account_VK_on, kb_configuring_sources, kb_main
from post_handler import get_posts
import asyncio

start_message = '''
Привет! \U0001F44B

Я помогу сэкономить время на листании ленты ВКонтакте и буду сам присылать тебе новые посты от необходимых сообществ и пользователей, список источников ты сможешь настроить сам \U0001f440

Чтобы узнать, как пользоваться мной, жми кнопку «Помощь» \u2B07
'''

help_message = '''
Прежде чем VK_Reposter начнёт свою работу необходимо подключить аккаунт от социальной сети ВКонтакте. Это можно сделать перейдя в раздел «Аккаунт ВКонтакте». В этом же разделе в будущем вы сможете отключить свой аккаунт (если пожелаете его сменить), либо узнать, какой аккаунт подключён в данный момент. Без подключенного аккаунта VK_Reposter работать не может!

Раздел «Настройка источников» предназначен для изменения списка сообществ и пользователей, от которых вы хотите получать посты. Для добавления нового источника потребуется ссылка на него.

Внимание!\u2757\u2757\u2757
— VK_Reposter работает исключительно с сообществами и пользователями социальной сети ВКонтакте.
— При нахождении в каком-либо разделе меню посты не приходят. Это сделано для удобства при настройке бота. Поэтому всегда возвращайтесь в главное меню!
— Для корректной настройки бота всё взаимодействие с ним должно происходить при помощи встроенной мини-клавиатуры, расположенной под текстовым полем для отправки сообщения.
'''

@dp.message_handler(commands=['start'])
async def start_command(message: types.Message):
    id_tg = message.from_user.id

    if not is_user_added(id_tg):
        add_new_user(id_tg)

    await message.answer(start_message, reply_markup=kb_main)

@dp.message_handler()
async def other_commands(message: types.Message):
    id_tg = message.from_user.id

    if message.text == 'Помощь':
        await message.answer(help_message, parse_mode='html')

    if message.text == 'Аккаунт ВКонтакте':
        set_status_to_OFF(id_tg)
        kb = kb_account_VK_on if is_vk_account_connected(id_tg) else kb_account_VK_off
        await message.answer('Аккаунт ВКонтакте \u2B07', reply_markup=kb)

    if message.text == 'Настройка источников':
        if not is_vk_account_connected(id_tg):
            await message.answer('Для доступа к настройке источников необходимо подключить аккаунт ВКонтакте \u274C')
        else:
            set_status_to_OFF(id_tg)
            await message.answer('Настройка источников \u2B07', reply_markup=kb_configuring_sources)

    if message.text == 'Подключить аккаунт':
        await answer_connect(message)

    if message.text == 'Отключить аккаунт':
        disconnect_vk_account(id_tg)
        await message.answer('Аккаунт ВК отключён \u2705', reply_markup=kb_account_VK_off)

    if message.text == 'Текущий аккаунт':
        if not is_vk_account_connected(id_tg):
            await message.answer('Аккаунт не подключён \u274C')
        else:
            info_about_current_account = get_info_about_current_account(id_tg)
            photo = info_about_current_account['url_of_photo']
            first_name = info_about_current_account['first_name']
            last_name = info_about_current_account['last_name']
            screen_name = info_about_current_account['screen_name']
            await message.answer_photo(photo, f'{first_name} {last_name} (@{screen_name})')

    if message.text == 'Список источников':
        list_of_sources = get_list_of_sources(id_tg)
        group_list = list_of_sources['group_list']
        user_list = list_of_sources['user_list']
        groups = ' не добавлены' if not group_list else '\n- ' + '\n- '.join(group_list)
        users = ' не добавлены' if not user_list else '\n- ' + '\n- '.join(user_list)
        await message.answer(f'Сообщества:{groups}\n\nПользователи:{users}', parse_mode='html')

    if message.text == 'Добавить источник':
        await answer_add(message)

    if message.text == 'Удалить источник':
        user_info = get_user_info(id_tg)
        if not user_info['group_ids'] and not user_info['user_ids']:
            await message.answer('Источники отсутствуют \u274C')
        else:
            await answer_delete(message)

    if message.text == 'Назад':
        set_status_to_ON(id_tg)
        await message.answer('Главное меню \u2B07', reply_markup=kb_main)

async def on_startup(x):
    asyncio.create_task(get_posts())

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True, on_startup=on_startup)


board = {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '7h': 'bqueen', '3e': 'wking'}
c = [  '1a','2a','3a','4a','5a','6a','7a','8a',
                '1b','2b','3b','4b','5b','6b','7b','8b',
                '1c','2c','3c','4c','5c','6c','7c','8c',
                '1d','2d','3d','4d','5d','6d','7d','8d',
                '1e','2e','3e','4e','5e','6e','7e','8e',
                '1f','2f','3f','4f','5f','6f','7f','8f',
                '1g','2g','3g','4g','5g','6g','7g','8g',
                '1h','2h','3h','4h','5h','6h','7h','8h'              ]
def isValidChessBoard(board):
    blackPieces= 0
    whitePieces= 0
    blackPawns = 0
    whitePawns = 0
    for piece in board.values():
        if (piece[0] == 'w'):
            whitePieces += 1
            print('number of whitePieces ' + (str(whitePieces)))
        else:
            blackPieces += 1
            print('number of blackPieces ' + (str(blackPieces)))
        if (piece == 'bpawn'):
            blackPawns += 1
            print('number of bpawns ' + (str(blackPawns)))
        if (piece == 'wpawn'):
            whitePawns += 1
            print('number of whitePawns ' + (str(whitePawns)))

    for place in board.keys():
        print(place)
        if (place not in c):
            return False

    if (blackPieces > 16 or whitePieces > 16 or blackPawns > 8 or whitePawns > 8):
        return False

    return True

if isValidChessBoard(board):
    print('true')
else:
    print('false')

Chapter 5 Data structures and dictionaries/Chess Dictionary Validator.py


DOF = 3
import numpy as np
import pandas as pd
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core import World
from omni.isaac.core.articulations import Articulation
import math_type_define.dyros_math as DyrosMath
import math
import wheelcontroller.differential as diffcontroller

np.set_printoptions(precision=3, suppress=True)

class WheelController:
    def __init__(self, hz: float, world:World, pkg_path:str, is_two_wheel:bool) -> None:
        self.hz = hz
        self.world = world
        self.tick = 0
        self.play_time = 0
        self.control_mode = "none"
        self.is_mode_changed = False
        self.pkg_path = pkg_path
        self.file_names = ["Circle", "Square", "Eight", "VelCommand"]
        self.is_two_wheel = is_two_wheel
        self.initDimension()
        self.initModel()
        self.initFile()

    def initDimension(self)->None:
        self.pose_init = np.zeros(DOF) # x, y, theta
        self.pose = np.zeros(DOF)
        self.pose_desired = np.zeros(DOF)
        # self.pose_dot_init = np.zeros(DOF) # Vx, Vy, W (for world frame)
        self.pose_dot = np.zeros(DOF)
        self.pose_dot_desired = np.zeros(DOF)
        # self.v_init = np.zeros(DOF) # Vx, Vy, W (for base frame)
        self.v = np.zeros(DOF)
        self.v_desired = np.zeros(DOF)

        # self.joint_vel_init = np.zeros(4) # Wheel velocity
        if(self.is_two_wheel):
            self.joint_vel = np.zeros(2)
            self.joint_vel_desired = np.zeros(2)
            self.dummy_joint_vel = np.zeros(4) # For visual
            self.dummy_joint_vel_desired = np.zeros(4)
        else:
            self.joint_vel = np.zeros(4)
            self.joint_vel_desired = np.zeros(4)

    def initModel(self)->None:
        self.husky = self.world.scene.add(Articulation(prim_path="/World/husky", name="husky",))

    def initFile(self)->None:
        for i in range(len(self.file_names)):
            file_path = self.pkg_path + "/data/" + self.file_names[i] + ".txt"
            globals()['self.file_'+str(i)] = open(file_path, 'w')

    def printState(self)->None:
        if( self.world.current_time_step_index % 50 == 0 ):
            print("----------------------------")
            print("Time[sec]")
            print(round(self.world.current_time, 2))
            print("\npose[m, m, rad] : ")
            print(self.pose_desired)
            print(self.pose)
            print("\nLinear velocity[m/s, m/s, rad/s] : ")
            print(self.v_desired)
            print(self.v)
            print("\nJoint velocity[rad/s] : ")
            print(self.joint_vel_desired)
            print(self.joint_vel)
            print("----------------------------")
            print("\n\n\n")

    def Quater2Yaw(self, quaternion:np.array)->float:
        yaw = math.atan2(2*(quaternion[0]*quaternion[3] + quaternion[1]*quaternion[2]), 1 - 2*(quaternion[2]**2 + quaternion[3]**2))
        return yaw

    def getTrajData(self, file_name:str)->np.array:
        traj_data = pd.read_table(self.pkg_path+"/trajectory"+file_name, sep=" ", header=None)
        traj = traj_data.to_numpy()
        return traj # x, y, theta (from global frame), vx, vy, w(from base frame)

    def Kanayama(self, traj_data: np.array, traj_type: str)->None:
        index = self.tick - self.tick_init
        if index < 0 or index >= traj_data.shape[0]:
            self.v_desired = np.zeros(DOF)
            self.pose_desired = self.pose
        else:
            Kx = 9
            Ky = 9
            Kth = 4.5

            ref_pose = traj_data[index, 0:3] # x, y, theta wrt global frame
            ref_vel  = traj_data[index, 3:6] # vx, vy, w wrt base frame

            Rz = np.array([[ math.cos(self.pose[2]), math.sin(self.pose[2]), 0],
                           [-math.sin(self.pose[2]), math.cos(self.pose[2]), 0],
                           [0,                       0,                      1]])

            error_pose = Rz @ (ref_pose - self.pose) # Error pose wrt base frame
            error_pose[2] = math.atan2(math.sin(error_pose[2]), math.cos(error_pose[2])) # Angle error correction

            # Feedback velocity command
            self.v_desired[0] = ( ref_vel[0] * math.cos(error_pose[2]) ) + Kx *  error_pose[0]
            self.v_desired[2] = ref_vel[2] + ref_vel[0] * ( Ky * error_pose[1] + Kth * math.sin(error_pose[2]) )

            # Desired pose
            self.pose_desired = np.array([traj_data[index, 0], traj_data[index, 1], traj_data[index, 2]])

        if self.is_two_wheel:
            self.joint_vel_desired = diffcontroller.DifferentialController(wheel_radius=0.1651,
                                                                           wheel_distance=0.5708,
                                                                           linear_velocity=self.v_desired.item(0),
                                                                           angular_velocity=self.v_desired.item(2),
                                                                           max_linear_speed=1.0,
                                                                           max_angular_speed=2.0,
                                                                           is_skid=False,
                                                                           wheel_distance_multiplier=1.0)
            self.dummy_joint_vel_desired = np.concatenate([self.joint_vel_desired ,self.joint_vel_desired], axis=0)
        else:
            self.joint_vel_desired = diffcontroller.DifferentialController(wheel_radius=0.1651,
                                                                           wheel_distance=0.5708,
                                                                           linear_velocity=self.v_desired.item(0),
                                                                           angular_velocity=self.v_desired.item(2),
                                                                           max_linear_speed=1.0,
                                                                           max_angular_speed=2.0,
                                                                           is_skid=True,
                                                                           wheel_distance_multiplier=1.875)
        if traj_type == "Kanayama Circle":
            self.record(0, traj_data.shape[0]/self.hz)
        if traj_type == "Kanayama Square":
            self.record(1, traj_data.shape[0]/self.hz)
        if traj_type == "Kanayama Eight":
            self.record(2, traj_data.shape[0]/self.hz)

    def VelControl(self, traj_data: np.array, traj_type: str)->None:
        index = self.tick - self.tick_init
        if index < 0 or index >= traj_data.shape[0]:
            self.v_desired = np.zeros(DOF)
            self.pose_desired = self.pose
        else:
            # Desired velocity
            self.v_desired = traj_data[index, 3:6]

            # Desired pose
            self.pose_desired = np.array([traj_data[index, 0], traj_data[index, 1], traj_data[index, 2]])

        if self.is_two_wheel:
            self.joint_vel_desired = diffcontroller.DifferentialController(wheel_radius=0.1651,
                                                                           wheel_distance=0.5708,
                                                                           linear_velocity=self.v_desired.item(0),
                                                                           angular_velocity=self.v_desired.item(2),
                                                                           max_linear_speed=1.0,
                                                                           max_angular_speed=2.0,
                                                                           is_skid=False,
                                                                           wheel_distance_multiplier=1.0)
            self.dummy_joint_vel_desired = np.concatenate([self.joint_vel_desired ,self.joint_vel_desired], axis=0)
        else:
            self.joint_vel_desired = diffcontroller.DifferentialController(wheel_radius=0.1651,
                                                                           wheel_distance=0.5708,
                                                                           linear_velocity=self.v_desired.item(0),
                                                                           angular_velocity=self.v_desired.item(2),
                                                                           max_linear_speed=1.0,
                                                                           max_angular_speed=2.0,
                                                                           is_skid=True,
                                                                           wheel_distance_multiplier=1.875)
        if traj_type == "Velocity Circle":
            self.record(0, traj_data.shape[0]/self.hz)
        if traj_type == "Velocity Square":
            self.record(1, traj_data.shape[0]/self.hz)
        if traj_type == "Velocity Eight":
            self.record(2, traj_data.shape[0]/self.hz)

    def VelCommand(self, linvel_desired:float, angvel_desired:float, duration:float)->None:
        if self.play_time <= self.control_start_time + duration:
            self.v_desired = np.array([linvel_desired, 0, angvel_desired])
        else:
            self.v_desired = np.zeros(3)
        if self.is_two_wheel:
            self.joint_vel_desired = diffcontroller.DifferentialController(wheel_radius=0.1651,
                                                                           wheel_distance=0.5708,
                                                                           linear_velocity=self.v_desired.item(0),
                                                                           angular_velocity=self.v_desired.item(2),
                                                                           max_linear_speed=1.0,
                                                                           max_angular_speed=2.0,
                                                                           is_skid=False,
                                                                           wheel_distance_multiplier=1.0)
            self.dummy_joint_vel_desired = np.concatenate([self.joint_vel_desired , self.joint_vel_desired], axis=0)
        else:
            self.joint_vel_desired = diffcontroller.DifferentialController(wheel_radius=0.1651,
                                                                           wheel_distance=0.5708,
                                                                           linear_velocity=self.v_desired.item(0),
                                                                           angular_velocity=self.v_desired.item(2),
                                                                           max_linear_speed=1.0,
                                                                           max_angular_speed=2.0,
                                                                           is_skid=True,
                                                                           wheel_distance_multiplier=1.875)
        self.record(3, duration)

    def UpdateData(self)->None:
        position, orientation = self.husky.get_world_pose()
        self.pose[:2] = position[:2]
        self.pose[2] = self.Quater2Yaw(orientation)

        linvel = self.husky.get_linear_velocity()
        angvel = self.husky.get_angular_velocity()
        self.pose_dot[:2] = linvel[:2]
        self.pose_dot[2] = angvel[2]

        self.v[0] =  self.pose_dot[0] * math.cos(self.pose[2]) + self.pose_dot[1] * math.sin(self.pose[2])
        self.v[1] = -self.pose_dot[0] * math.sin(self.pose[2]) + self.pose_dot[1] * math.cos(self.pose[2])
        self.v[2] = angvel[2]

        if self.is_two_wheel:
            self.joint_vel = self.husky.get_joint_velocities()[4:]
            self.dummy_joint_vel = self.husky.get_joint_velocities()[:4]
        else:
            self.joint_vel = self.husky.get_joint_velocities()

    def initPosition(self)->None:
        self.pose_init = self.pose
        self.pose_desired = self.pose_init
        self.v_desired = self.v
        self.joint_vel_desired = self.joint_vel
        if self.is_two_wheel:
            self.dummy_joint_vel_desired = self.dummy_joint_vel

    def setMode(self, mode:str)->None:
        self.is_mode_changed = True
        self.control_mode = mode
        print("Current mode (changed) : "+self.control_mode)

    def compute(self)->None:
        if(self.is_mode_changed):
            self.is_mode_changed = False
            self.control_start_time = self.play_time
            self.pose_init = self.pose
            self.tick_init = self.tick

        if self.control_mode == "init":
            self.husky.set_world_pose(position=np.array([0.,0.,0.0780]),
                                      orientation=np.array([1.,0.,0.,0.]))
            if self.is_two_wheel:
                self.joint_vel_desired = np.zeros(2)
                self.dummy_joint_vel_desired = np.zeros(4)
            else:
                self.joint_vel_desired = np.zeros(4)

        elif self.control_mode == "Kanayama Circle":
            self.Kanayama(self.getTrajData("/circle.txt"), self.control_mode)
        elif self.control_mode == "Kanayama Square":
            self.Kanayama(self.getTrajData("/square.txt"), self.control_mode)
        elif self.control_mode == "Kanayama Eight":
            self.Kanayama(self.getTrajData("/eight.txt"), self.control_mode)
        elif self.control_mode == "Velocity Circle":
            self.VelControl(self.getTrajData("/circle.txt"), self.control_mode)
        elif self.control_mode == "Velocity Square":
            self.VelControl(self.getTrajData("/square.txt"), self.control_mode)
        elif self.control_mode == "Velocity Eight":
            self.VelControl(self.getTrajData("/eight.txt"), self.control_mode)
        elif self.control_mode == "Velocity Command":
            linear_vel = 0.25
            angular_vel = 0.125
            duration = 2*2*math.pi / linear_vel
            # duration = 5
            self.VelCommand(linear_vel, angular_vel, duration)

        self.printState()
        self.play_time = self.world.current_time
        self.tick = self.world.current_time_step_index

    def getPose(self)->np.array:
        return self.pose

    def getVel(self)->np.array:
        return self.v

    def write(self)->None:
        if self.is_two_wheel:
            self.husky.set_joint_velocities(velocities=np.concatenate([self.dummy_joint_vel_desired, self.joint_vel_desired], axis=0))
        else:
            self.husky.set_joint_velocities(self.joint_vel_desired)

    def record(self, file_name_index:int, duration:float):
        if self.play_time < self.control_start_time + duration + 1.0:
            data = str(self.play_time - self.control_start_time) + " " + str(self.pose*1000)[1:-1] + " " + str(self.v*1000)[1:-1]
            globals()["self.file_"+str(file_name_index)].write(data + "\n" )

    def closeFile(self)->None:
        for i in range(len(self.file_names)):
            globals()['self.file_'+str(i)].close()


import numpy as np
from numpy import sqrt, pi, exp
from scipy.special import erf
from scipy.optimize import minimize
from numba import jit, prange

@jit
def fit_mu_sig(x, mean, var):
    mu = np.array(x[0])
    logvar = np.array(x[1])

    sigma = np.exp(logvar/2)

    testmean = mu - sqrt(2)*sigma*exp(-1/2*(mu - 4)**2/sigma**2)/(sqrt(pi)*(erf(-1/2*sqrt(2)*(mu - 4)/sigma) - 1))
    testvar = sigma**2*(
        sqrt(2)*(mu - 4)*exp(-1/2*(mu - 4)**2/sigma**2)/(sqrt(pi)*sigma*(erf(-1/2*sqrt(2)*(mu - 4)/sigma) - 1))
        - 2*exp(-(mu - 4)**2/sigma**2)/(pi*(erf(-1/2*sqrt(2)*(mu - 4)/sigma) - 1)**2)
        + 1)

    return (testmean - mean)**2 + (testvar - var)**2

@jit(parallel=True)
def find_mu_sig(sample_preds):
    """Samples are passed in as [n_batch, n_samples]. Returns [n_batch, 2] for (mu, sigma) pairs for a distribution cutoff at 4"""
    sample_preds = sample_preds.T
    result = []
    for i in prange(sample_preds.shape[1]):
        to_fit = sample_preds[:, i]
        mean = np.average(to_fit) #=mu + (gauss_pdf(alpha))/Z
        var = np.std(to_fit)**2

        x0 = np.array([mean, np.log(var)])
        out = minimize(fit_mu_sig, x0, args=(mean, var), bounds=[(4, 20), (-1, 2)]).x

        mu = out[0]
        sig = np.exp(out[1]/2)

        result.append([mu, sig])

    return np.array(result)

from scipy.stats import truncnorm

@jit
def fit_mu_sig_likelihood(x0, x):
    mu = np.array(x0[0])
    logvar = np.array(x0[1])

    std = np.exp(logvar/2)
    a = (4-mu)/std
    b = np.inf

    return truncnorm.nnlf([a, b, mu, std], x)

@jit(parallel=True)
def find_mu_sig_likelihood(sample_preds):
    """Samples are passed in as [n_batch, n_samples]. Returns [n_batch, 2] for (mu, sigma) pairs for a distribution cutoff at 4"""
    sample_preds = sample_preds.T
    result = []
    for i in prange(sample_preds.shape[1]):
        to_fit = sample_preds[:, i]
        mean = np.average(to_fit) #=mu + (gauss_pdf(alpha))/Z
        var = np.std(to_fit)**2

        x0 = np.array([mean, np.log(var)])
        out = minimize(fit_mu_sig_likelihood, x0, args=(to_fit), bounds=[(4, 20), (-1, 2)]).x

        mu = out[0]
        sig = np.exp(out[1]/2)

        result.append([mu, sig])

    return np.array(result)


def funcion(x):
    x = 2 * (x ** 2) + 4 * (x ** 3) + x ** (1/2)
    return x

def integral( a, b, n):
    algo = 0
    suma = 0
    while algo < n:
        d = (b - a) / n
        area = d * funcion(a + d * algo)
        suma = suma + area
        algo = algo + 1
    return suma

def run():
    n = int(input("Ingresa el número de particiones: "))
    a = float(input("Ingresa el punto de inicio: "))
    b = float(input("Ingresa el punto final: "))
    integral_problema = integral(a, b, n)
    print(integral_problema)

if __name__ == "__main__":
    run()


__author__ = 'callix'

from tests_framework.ui_building_blocks.screen import Screen
import logging
import tests_framework.ui_building_blocks.KSTB.constants as CONSTANTS
from time import sleep,time

''' Constants '''
START_STREAMING_TIMEOUT = 10

class ZapList(Screen):
    def __init__(self, test):
        Screen.__init__(self, test, "zap_list_tv")

    def navigate(self, direction = "up"):
        logging.info("Navigate to zap list")
        screen = self.test.milestones.get_current_screen()
        if screen == self.screen_name:
            return True

        if screen != "fullscreen":
            self.test.say('need to navigate to fullscreen')
            self.test.screens.fullscreen.navigate()

        logging.info("Navigating to zaplist, current step : fullscreen")
        if direction == "down":
            logging.info("pressing down key")
            self.test.appium.key_event("KEYCODE_DPAD_DOWN")
            self.test.wait(2)
            self.test.appium.key_event("KEYCODE_DPAD_UP")
        else:
            logging.info("pressing up key")
            self.test.appium.key_event("KEYCODE_DPAD_UP")
            self.test.wait(2)
            self.test.appium.key_event("KEYCODE_DPAD_DOWN")

        self.test.wait_for_screen(CONSTANTS.WAIT_TIMEOUT, "zap_list_tv")
        self.verify_active()
        return True

    def verify_zaplist_showing(self, elements=None):
        if elements is None:
            elements = self.test.milestones.getElements()

        screen = self.test.milestones.get_value_by_key(elements, "screen")
        if screen == "zap_list_tv":
            return True
        else:
            logging.error("ZapList is not displayed on the screen but {0}".format(screen))
        return False

    def zaplist_timeout_to_fullscreen(self):
        '''
        Go to fullscreen from zaplist by waiting for SCREEN_TIMEOUT duration
        :return: True when on fullscreen after SCREEN_TIMEOUT seconds
        '''
        status = self.test.wait_for_screen(CONSTANTS.WAIT_TIMEOUT, "zap_list_tv")
        if not status:
            logging.error("Not in zaplist")
            return False
        logging.info("In zaplist")
        status = self.test.wait_for_screen(CONSTANTS.SCREEN_TIMEOUT + 1, "zap_list_tv", "!=" )
        if not status:
            logging.error("wait for zaplist to timeout failed")
            return False
        status = self.test.wait_for_screen(CONSTANTS.WAIT_TIMEOUT, "fullscreen")
        if not status:
            logging.error("wait for fullscreen timed out")
            return False
        logging.info("In fullscreen")
        return status

    def to_nextchannel(self, direction="up"):
        '''
        Go to next channel in zaplist
        :param direction: button to press. "up" or "down"
        :return: True when on new channel. Still on zaplist screen
        '''
        status = self.test.wait_for_screen(CONSTANTS.WAIT_TIMEOUT, "zap_list_tv")
        if not status:
            logging.error("wait for zaplist timed out")
            return False
        logging.info("In zaplist")

        actualFocusedChannelNumber = self.test.milestones.get_value_by_key(self.test.milestones.getElements(),"focused_channel_number")
        start_time = time()
        current_time = start_time
        if direction == "down":
            # logging.info("Pressing down key")
            self.test.appium.key_event("KEYCODE_DPAD_DOWN")
        else:
            # logging.info("Pressing up key")
            self.test.appium.key_event("KEYCODE_DPAD_UP")

        nextFocusedChannelNumber = actualFocusedChannelNumber
        time_out = (current_time - start_time) >= CONSTANTS.WAIT_TIMEOUT
        focused_ok = nextFocusedChannelNumber == actualFocusedChannelNumber
        while (not focused_ok) and (not time_out):
            current_time = time()
            time_out = (current_time - start_time) >= CONSTANTS.WAIT_TIMEOUT
            nextFocusedChannelNumber = self.test.milestones.get_value_by_key(self.test.milestones.getElements(),"focused_channel_number")
            focused_ok = nextFocusedChannelNumber == actualFocusedChannelNumber
            sleep(0.2)

        if time_out:
            logging.error("focused item change timed out in zaplist")
            return False
        # logging.info("focused item has changed in zaplist")
        return focused_ok

    def tune_to_channel_by_sek(self, channel_id, handle_pincode_screen=True, verify_streaming_started=True):
        '''
        Navigate till the wanted channel number then zap on it by validating it
        :param channel_id:
        :param handle_pincode_screen:
        :param verify_streaming_started:
        :return:
        '''
        status = self.test.wait_for_screen(CONSTANTS.WAIT_TIMEOUT, "zap_list_tv")
        if not status:
            logging.error("wait for zap_list_tv timed out")
            logging.error("not in zap_list_tv")
            return False
        logging.info("In zap_list_tv")
        pin_code = self.test.screens.pincode
        elements = self.test.milestones.getElements()

        firstFocusedChannelNumber = self.test.milestones.get_value_by_key(elements, "focused_channel_number")

        channel_found = False
        cycle_not_completed = True
        actualFocusedChannelNumber = firstFocusedChannelNumber

        while cycle_not_completed:
            if str(actualFocusedChannelNumber) == str(int(channel_id)):
                channel_found = True
                # print ("Tuning to channel %s" % channel_id)
                self.test.appium.key_event("KEYCODE_DPAD_CENTER")
                sleep(1)

                if self.test.screens.pincode.is_active(1, ignoreNotification=True):
                    if handle_pincode_screen:
                        youth_pincode = self.test.he_utils.getYouthpincode()
                        pin_code.enter_pin(youth_pincode)
                    else:
                        break
                if verify_streaming_started:
                    for i in range(START_STREAMING_TIMEOUT):
                        playback_status = self.test.milestones.getPlaybackStatus()
                        state = playback_status["playbackState"]
                        if state == "PLAYING":
                            return True
                        sleep(1)
                    elements = self.test.milestones.getElements()
                    error_msg = self.test.milestones.get_value_by_key(elements, "msg_text")
                    logging.error("Playback streaming failed playing : error_msg = " + str(error_msg))
                    return False
                break

            self.test.appium.key_event("KEYCODE_DPAD_DOWN")
            sleep(1)
            elements = self.test.milestones.getElements()
            actualFocusedChannelNumber = self.test.milestones.get_value_by_key(elements, "focused_channel_number")

            cycle_not_completed = int(actualFocusedChannelNumber) != int(firstFocusedChannelNumber)

        if not channel_found:
            logging.info("Could not find channel_id %s in zaplist" % channel_id)
            return False
        else:
            return True
        # self.test.log_assert(channel_found, "Could not find channel_id %s in zaplist" % channel_id)


import argparse
import logging

import logger
import ui
from randomizer import Randomizer
from utils import prog_name

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        prog=prog_name,
        description='meow')
    parser.add_argument("--game_path", type=str, default=None)
    parser.add_argument('--no_gui', action='store_true')
    parser.add_argument("--settings_path", type=str, default="settings.json")
    parser.add_argument('-s', '--seed', type=str, default=None,
                        help='seed used to determine randomization. the same seed will always crate the same '
                             'randomization.')
    parser.add_argument('-f', '--force_extract', action='store_true', help='force (re-)extraction of the game files')
    parser.add_argument('-d', '--dry', '--dry-run', action='store_true',
                        help='do not create output other then a log file')
    parser.add_argument('-p', '--placement-folder', '--placement',
                        help='do not create output other then a log file')
    args = parser.parse_args()
    logger.setup_logging()
    if args.no_gui:
        rando = Randomizer()
        rando.setup_from_args(args, True)
        rando_gen = rando.run()
        logger = logging.getLogger('cyber_empire')
        for i in rando_gen:
            logger.debug(i)
    else:
        ui.run_ui(args)


################################################################################
#
# @Author: Mark_T
# @Title: VideoScreen Template
# @Credit: Qt Designer (Came with Pyside2)
# @version: 1.0
#
################################################################################

#Import needed libraries
from videoplayer import *

class Ui_Functions(QMainWindow):
    ########################################################################
    # MAXIMIZE/RESTORE
    ########################################################################
    def maximize_restore(self):
        global GLOBAL_STATE
        status = GLOBAL_STATE
        if status == 0:
            self.showMaximized()
            GLOBAL_STATE = 1
            self.ui.btn_maximize_restore.setToolTip("Restore")
            self.ui.btn_maximize_restore.setIcon(QIcon(u":/16x16/icons/16x16/cil-window-restore.png"))
            self.ui.label_appName.hide()
            self.ui.frame_logo.hide()

        else:
            GLOBAL_STATE = 0
            self.showNormal()
            #self.resize(self.width()+1, self.height()+1)
            self.ui.btn_maximize_restore.setToolTip("Maximize")
            self.ui.btn_maximize_restore.setIcon(QIcon(u":/16x16/icons/16x16/cil-window-maximize.png"))
            self.ui.label_appName.show()
            self.ui.frame_logo.show()

    def hideCtrlAnimate(self):
        # ANIMATION
        self.animation = QPropertyAnimation(self.ui.frame_controls, b"maximumHeight")
        self.animation.setDuration(400)
        self.animation.setStartValue(100)
        self.animation.setEndValue(10)
        self.animation.setEasingCurve(QEasingCurve.InOutQuart)
        self.animation.start()
        #self.ui.frame_controls.hide()


import cv2
import numpy as np
import math
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from scipy.stats import itemfreq
from extract_features import load_image,glcm_feature
from skimage.feature import hog
# 用于提取HOG特征

class Hog_descriptor():
    def __init__(self, img, cell_size=16, bin_size=8):
        self.img = img
        self.img = np.sqrt(img / np.max(img))
        self.img = img * 255
        self.cell_size = cell_size
        self.bin_size = bin_size
        self.angle_unit = 360 / self.bin_size

    def extract(self):
        height, width = self.img.shape
        gradient_magnitude, gradient_angle = self.global_gradient()
        gradient_magnitude = abs(gradient_magnitude)
        cell_gradient_vector = np.zeros((int(height / self.cell_size), int(width / self.cell_size), int(self.bin_size)))
        for i in range(cell_gradient_vector.shape[0]):
            for j in range(cell_gradient_vector.shape[1]):
                cell_magnitude = gradient_magnitude[i * self.cell_size:(i + 1) * self.cell_size,
                                 j * self.cell_size:(j + 1) * self.cell_size]
                cell_angle = gradient_angle[i * self.cell_size:(i + 1) * self.cell_size,
                             j * self.cell_size:(j + 1) * self.cell_size]
                cell_gradient_vector[i][j] = self.cell_gradient(cell_magnitude, cell_angle)

        hog_image = self.render_gradient(np.zeros([height, width]), cell_gradient_vector)
        hog_vector = []
        # 判断hog_image是否为0矩阵，如果是0矩阵，就不做处理
        # 构造一个0矩阵，判断hog_image==0矩阵
        zero_array = np.zeros(hog_image.shape)
        if (hog_image == zero_array).all() == True:
            return None, None
        else:
            for i in range(cell_gradient_vector.shape[0] - 1):
                for j in range(cell_gradient_vector.shape[1] - 1):
                    block_vector = []
                    block_vector.extend(cell_gradient_vector[i][j])
                    block_vector.extend(cell_gradient_vector[i][j + 1])
                    block_vector.extend(cell_gradient_vector[i + 1][j])
                    block_vector.extend(cell_gradient_vector[i + 1][j + 1])
                    mag = lambda vector: math.sqrt(sum(i ** 2 for i in vector))
                    magnitude = mag(block_vector)
                    if magnitude != 0:
                        normalize = lambda block_vector, magnitude: [element / magnitude for element in block_vector]
                        block_vector = normalize(block_vector, magnitude)
                        hog_vector.append(block_vector)
            return hog_vector, hog_image

    def global_gradient(self):
        gradient_values_x = cv2.Sobel(self.img, cv2.CV_64F, 1, 0, ksize=5)
        gradient_values_y = cv2.Sobel(self.img, cv2.CV_64F, 0, 1, ksize=5)
        gradient_magnitude = cv2.addWeighted(gradient_values_x, 0.5, gradient_values_y, 0.5, 0)
        gradient_angle = cv2.phase(gradient_values_x, gradient_values_y, angleInDegrees=True)
        return gradient_magnitude, gradient_angle

    def cell_gradient(self, cell_magnitude, cell_angle):
        orientation_centers = [0] * self.bin_size
        for i in range(cell_magnitude.shape[0]):
            for j in range(cell_magnitude.shape[1]):
                gradient_strength = cell_magnitude[i][j]
                gradient_angle = cell_angle[i][j]
                min_angle, max_angle, mod = self.get_closest_bins(gradient_angle)
                orientation_centers[min_angle] += (gradient_strength * (1 - (mod / self.angle_unit)))
                orientation_centers[max_angle] += (gradient_strength * (mod / self.angle_unit))
        return orientation_centers

    def get_closest_bins(self, gradient_angle):
        idx = int(gradient_angle / self.angle_unit)
        mod = gradient_angle % self.angle_unit
        return idx, (idx + 1) % self.bin_size, mod

    def render_gradient(self, image, cell_gradient):
        cell_width = self.cell_size / 2
        max_mag = np.array(cell_gradient).max()
        for x in range(cell_gradient.shape[0]):
            for y in range(cell_gradient.shape[1]):
                cell_grad = cell_gradient[x][y]
                cell_grad /= max_mag
                angle = 0
                angle_gap = self.angle_unit
                for magnitude in cell_grad:
                    angle_radian = math.radians(angle)
                    if math.isnan(magnitude):
                        break
                    else:
                        x1 = int(x * self.cell_size + magnitude * cell_width * math.cos(angle_radian))
                        y1 = int(y * self.cell_size + magnitude * cell_width * math.sin(angle_radian))
                        x2 = int(x * self.cell_size - magnitude * cell_width * math.cos(angle_radian))
                        y2 = int(y * self.cell_size - magnitude * cell_width * math.sin(angle_radian))
                        cv2.line(image, (y1, x1), (y2, x2), int(255 * math.sqrt(magnitude)))
                        angle += angle_gap
        return image

def hog_feature(image):
    hog = Hog_descriptor(image, cell_size=8, bin_size=9)
    vector, image_hog = hog.extract()
    if vector is None or image_hog is None:
        return None
    else:
        array_vector = np.array(vector)
        # # 对数组中nan值进行处理
        # for i in range(array_vector.shape[0]):
        #     for j in range(array_vector.shape[1]):
        #         if math.isnan(array_vector[i][j]):
        #             break
        # 要获取全部的特征还需要做归一化处理
        lbpTranpose = array_vector.transpose()
        pca = PCA(n_components=1)
        pca.fit(lbpTranpose)
        newData = pca.transform(lbpTranpose)
        hogTranpose = np.array(newData).transpose()
        return hogTranpose
    # orientations = 9
    # pixels_per_cell = [5, 5]
    # cells_per_block = [3, 3]
    # visualize = False
    # transform_sqrt = True
    # hog_feature = hog(image, orientations, pixels_per_cell, cells_per_block, visualise=visualize, transform_sqrt=transform_sqrt)
    # return hog_feature

# for i in range(1):
#     img = cv2.imread('./eddyData/train/eddy/'+str(i)+'.tif', cv2.IMREAD_GRAYSCALE)
#     imagere = cv2.resize(img, (280, 280), interpolation=cv2.INTER_CUBIC)
#     hog = Hog_descriptor(imagere, cell_size=8, bin_size=8)
#     vector, image = hog.extract()
#     print(np.array(vector).shape)
# # print(vector)
# # with open("HOG特征向量.txt", "a") as myfile:
# #     myfile.write(str(vector) + "\n")
# # histogram=itemfreq(image)
# # Calculate the histogram
# # x = itemfreq(image.ravel())
# # Normalize the histogram
# # hist = x[:, 1]/sum(x[:, 1])
# # 线图
# # plt.subplot(121)
# # plt.plot(hist)
# # 直方图
# # plt.subplot(121)
# # plt.hist(hist)
# # plt.subplot(122)
# #     plt.imshow(image, cmap='gray')
# #     plt.show()
#     lbpTranpose = np.array(vector).transpose()
#     pca = PCA(n_components=1)
#     pca.fit(lbpTranpose)
#     newData = pca.transform(lbpTranpose)
#     hogTranpose = np.array(newData).transpose()
#     print(hogTranpose.shape)
#     print("读写"+str(i)+"图片")
#     with open("HOG特征向量.txt", "a") as myfile:
#         for i in range(32):
#             myfile.write(str(hogTranpose[0][i]) + " ")
#         myfile.write("\n")
#     myfile.close()

# if __name__ =='__main__':
#     for i in range(4938):
#         image = load_image(i)
#         if image is not None:
#             hog = Hog_descriptor(image, cell_size=8, bin_size=9)
#             vector, image_hog = hog.extract()
#             array_vector = np.array(vector)
#             # 要获取全部的特征还需要做归一化处理
#             lbpTranpose = array_vector.transpose()
#             pca = PCA(n_components=1)
#             pca.fit(lbpTranpose)
#             newData = pca.transform(lbpTranpose)
#             hogTranpose = np.array(newData).transpose()
#             print(hogTranpose.shape)
#             # GLCM的4个特征
#             contrast, correlation, energy, homogeneity = glcm_feature(image)
#             # 写入文件
#             with open("./features/GLCM_HOG_pca_feature.txt", "a") as myfile:
#                 for i in range(36):
#                     myfile.write(str(hogTranpose[0][i]) + " ")
#                 myfile.write(str(contrast) + ' ' + str(correlation) + ' ' + str(energy) + ' ' + str(homogeneity) + ' ')
#                 myfile.write("\n")
#             myfile.close()
#             # print(array_vector.shape)
#             # normalised_blocks, hog_image = hog(image, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(8, 8),
#             #                                    block_norm='L2-Hys', visualise=True, feature_vector=True)
#             # print(normalised_blocks.shape)


import sys

import matplotlib.pyplot as plt
import numpy as np

file = sys.argv[1]
print(file)

plot = np.loadtxt(file, delimiter=",", unpack=True)

fig = plt.figure(figsize=(4, 2))
plt.scatter(range(0, len(plot)), plot, marker="o", s=(72. / fig.dpi)**2)
plt.ylabel("Amps")
plt.xlabel("Samples")
plt.show()


import numpy as np
import pickle as pk
def size(mi, ma) :
    n = int(input())
    if mi <= n <= ma :
        return n
    print("Enter it again ! ")
    return size(mi, ma )

def isPrime(n, i=2):
    if n <2 :
        return False
    if i <= n//2 :
        return n % i != 0 and isPrime(n, i+1)
    return True

def fillPrimeNumbers (primi, n) :
    prime = 2
    for i in range (n) :
        primi[i] = prime
        prime +=1
        while not isPrime(prime) :
            prime +=1

def getPrime(primi,arr1,n) :
    prime =primi[0]
    number = n
    count = 0
    l = 0
    le = 0
    while n >= prime :
        if number % prime != 0 :
            l+=1
            prime = primi[l]
            arr1[le] = count
            le+= 1
            count = 0

        else :
            count +=1
            number //= prime

def power(a , b) :
    if b > 1 :
        return a * power(a, b-1)
    return a

def init(arr, length):
    for i in range (length):
        arr[i] = 0

def ppcm(p, q) :
    n = (p+q) //2
    print(n)
    thePrimes = np.array([int] * n)# array of prime numbers
    fillPrimeNumbers(thePrimes, n )
    arr1 = np.array([int] * n ) # array of the numbers of p
    arr2 = np.array([int] * n )# array of the numbers of q
    init(arr1, n )
    init(arr2, n )
    getPrime(thePrimes, arr1 , p)
    getPrime(thePrimes, arr2 , q)
    print(arr1)
    res =1

    for i in range (n):
        if arr1[i] > 0 or arr2[i] > 0 :
            if arr1[i] > arr2[i] :
                res *= power(thePrimes[i],arr1[i])
            else :
                res *= power(thePrimes[i],arr2[i])

    return res

def saveFile(n) :
    myfile = open("result.dat", "wb")
    for i in range (n) :
        print("Give  p ")
        p = size(1, 1000)
        print("Give q ")
        q = size(1 , 1000)
        pk.dump({
            "a" : p,
            "b" : q ,
            "ppcm" : ppcm(p,q)
        }, myfile)

    myfile.close()

def Show(n):
    myFile=  open("result.dat" , "rb")
    for i in range (n):
        obj = pk.load(myFile)
        print("PPCM(", obj["a"] , ",",obj["b"] , ") = " , obj["ppcm"])
    myFile.close()

print("Enter n ! ")
n = size(2 , 100)
saveFile(n)
Show(n)


import pydot
import queue
from engine import *

# --- CLASS NODO ---#
class Node:
    def __init__(self, state, value, operators, operator=None, parent=None, objective=None):
        self.state = state
        self.value = value
        self.children = []
        self.parent = parent
        self.operator = operator
        self.objective = objective
        self.level = 0
        self.operators = operators
        self.v = 0

    def add_child(self, value, state, operator):
        node = type(self)(value=value, state=state, operator=operator, parent=self, operators=self.operators)
        node.level = node.parent.level + 1
        self.children.append(node)
        return node

    def add_node_child(self, node):
        node.level = node.parent.level + 1
        self.children.append(node)
        return node

    # Devuelve todos los estados según los operadores aplicados
    def getchildrens(self):
        return [
            self.getState(i)
            if not self.repeatStatePath(self.getState(i))
            else None for i, op in enumerate(self.operators)]

    def getState(self, index):
        pass

    def __eq__(self, other):
        return self.state == other.state

    def __lt__(self, other):
        return self.f() < other.f()

    def repeatStatePath(self, state):
        n = self
        while n is not None and n.state != state:
            n = n.parent
        return n is not None

    def pathObjective(self):
        n = self
        result = []
        while n is not None:
            result.append(n)
            n = n.parent
        return result

    def heuristic(self):
        return 0

    def cost(self):
        return 1

    def f(self):
        return self.cost() + self.heuristic()

    # Crear método para criterio objetivo
    # Por defecto vamos a poner que sea igual al estado objetivo, para cada caso se puede sobreescribir la función
    def isObjective(self):
        return self.state == self.objective

        # --- CLASS ÁRBOL ---#

class Tree:
    def __init__(self, root, operators):
        self.root = root
        self.operators = operators

    def printPath(self, n):
        stack = n.pathObjective()
        path = stack.copy()
        while len(stack) != 0:
            node = stack.pop()
            if node.operator is not None:
                print(f'operador:  {self.operators[node.operator]} \t estado: {node.state}')
            else:
                print(f' {node.state}')
        return path

    def reinitRoot(self):
        self.root.operator = None
        self.root.parent = None
        self.root.objective = None
        self.root.children = []
        self.root.level = 0

    # Primero a lo ancho
    def breadthFirst(self, endState):
        self.reinitRoot()
        pq = queue.Queue()
        pq.put(self.root)
        while not pq.empty():
            node = pq.get()
            children = node.getchildrens()
            for i, child in enumerate(children):
                if child is not None:
                    newChild = node.add_child(value=node.value + '-' + str(i), state=child, operator=i)
                    pq.put(newChild)
                    if endState == child:
                        return newChild

    # Primero en profundidad
    def dephFirst(self, endState):
        self.reinitRoot()
        pq = []
        pq.append(self.root)
        while len(pq) > 0:
            node = pq.pop()
            if (node.parent is not None):
                node.parent.add_node_child(node)
            children = node.getchildrens()
            temp = []
            for i, child in enumerate(children):
                if child is not None:
                    newChild = type(self.root)(value=node.value + '-' + str(i), state=child, operator=i, parent=node,
                                               operators=node.operators)
                    temp.append(newChild)
                    if endState == child:
                        node.add_node_child(newChild)
                        return newChild
            # Adicionar los hijos en forma inversa para que salga primero el primero que se adicionó
            temp.reverse()
            for e in temp:
                pq.append(e)

    # Costo uniforme
    def costUniform(self, endState):
        self.reinitRoot()
        pq = queue.PriorityQueue()
        pq.put((self.root.cost(), self.root))
        while not pq.empty():
            node = pq.get()[1]
            children = node.getchildrens()
            for i, child in enumerate(children):
                if child is not None:
                    newChild = node.add_child(value=node.value + '-' + str(i),
                                              state=child, operator=i)
                    pq.put((newChild.cost(), newChild))
                    if endState == child:
                        return newChild

    # Primero el mejor
    def bestFirst(self, endState):
        self.reinitRoot()
        pq = queue.PriorityQueue()
        pq.put((self.root.heuristic(), self.root))
        while not pq.empty():
            node = pq.get()[1]
            children = node.getchildrens()
            for i, child in enumerate(children):
                if child is not None:
                    newChild = node.add_child(value=node.value + '-' + str(i),
                                              state=child, operator=i)
                    pq.put((newChild.heuristic(), newChild))
                    if endState == child:
                        return newChild

    # A*
    def Aasterisk(self, endState):
        self.reinitRoot()
        pq = queue.PriorityQueue()
        pq.put((self.root.f(), self.root))
        while not pq.empty():
            node = pq.get()[1]
            children = node.getchildrens()
            for i, child in enumerate(children):
                if child is not None:
                    newChild = node.add_child(value=node.value + '-' + str(i),
                                              state=child, operator=i)
                    pq.put((newChild.f(), newChild))
                    if endState == child:
                        return newChild

        # Generar los hijos del nodo

    def AlfaBeta(self, depth):
        self.root.v = self.AlfaBetaR(self.root, depth, float('-inf'), float('inf'), True)
        ## Comparar los hijos de root
        values = [c.v for c in self.root.children]
        maxvalue = max(values)
        index = values.index(maxvalue)
        return self.root.children[index]

    def AlfaBetaR(self, node, depth, alfa, beta, maxPlayer):
        if depth == 0 or node.isObjective():  # if depth == 0:
            node.v = node.heuristic()
            return node.heuristic()
        ## Generar los hijos del nodo
        children = node.getchildrens()
        ## Según el jugador que sea en el árbol
        if maxPlayer:
            value = float('-inf')
            for i, child in enumerate(children):
                if child is not None:
                    newChild = type(self.root)(value=node.value + '-' + str(i), state=child, operator=i, parent=node,
                                               operators=node.operators, player=False, game=node.game)
                    newChild = node.add_node_child(newChild)
                    value = max(value, self.AlfaBetaR(newChild, depth - 1, alfa, beta, False))
                    alfa = max(alfa, value)
                    if alfa >= beta:
                        break

        else:
            value = float('inf')
            for i, child in enumerate(children):
                if child is not None:
                    newChild = type(self.root)(value=node.value + '-' + str(i), state=child, operator=i, parent=node,
                                               operators=node.operators, player=True, game=node.game)
                    newChild = node.add_node_child(newChild)
                    value = min(value, self.AlfaBetaR(newChild, depth - 1, alfa, beta, True))
                    beta = min(beta, value)
                    if alfa >= beta:
                        break
            # return value
        node.v = value
        return value

    # Método para dibujar el árbol
    def draw(self, path):
        graph = pydot.Dot(graph_type='graph')
        nodeGraph = pydot.Node(str(self.root.state) + "-" + str(0),
                               label=str(self.root.state), shape="circle",
                               style="filled", fillcolor="red")
        graph.add_node(nodeGraph)
        path.pop()
        return self.drawTreeRec(self.root, nodeGraph, graph, 0, path.pop(), path)

class Battleship(Node):

    def __init__(self, player, game, **kwargs):  # def __init__(self, root, operators):
        # **kwargs evita la necesidad de ingresar nuevamente los atributos del método anterior
        super(Battleship, self).__init__(**kwargs)
        self.game = game
        self.player = player
        if self.player:
            self.v = float('-inf')
        else:
            self.v = float('inf')

    def getState(self, index):  # dado un operador determinado calcula un estado al que se llega
        nextState = self.game.player1.search[index]
        return nextState

    # Costo acumulativo(valor 1 en cada nivel)
    def cost(self):
        return self.level

    def heuristic(self):

        # setup
        search = self.game.player1.search if self.game.player1_turn else self.game.player2.search
        unknown = [i for i, square in enumerate(search) if square == "U"]
        hits = [i for i, square in enumerate(search) if square == "H"]

        # search in neighborhood of hits
        unknown_with_neighboring_hits = []
        unknown_with_neighboring_hits_2 = []

        for u in unknown:
            # Busca hits
            if u + 1 in hits or u - 1 in hits or u - 10 in hits or u + 10 in hits:  # hit a la derecha o a la izquierda (1 recuadro)
                unknown_with_neighboring_hits.append(u)
            if u + 2 in hits or u - 2 in hits or u - 20 in hits or u + 20 in hits:  # hit a la derecha o a la izquierda (2 recuadros)
                unknown_with_neighboring_hits_2.append(u)

        # pick "U" square that has neighbors both marked as "H"
        for u in unknown:

            if u in unknown_with_neighboring_hits and u in unknown_with_neighboring_hits_2:
                if self.game.computer_turn:  # VERIFICACIÓN DEL TURNO DE LA IA
                    self.game.make_move(u)
                return 2

        if len(unknown_with_neighboring_hits) > 0:
            if self.game.computer_turn:  # VERIFICACIÓN DEL TURNO DE LA IA
                self.game.make_move(random.choice(unknown_with_neighboring_hits))
            return 1

        # checker board pattern
        checker_board = []
        for u in unknown:
            row = u // 10
            col = u % 10
            if (row + col) % 2 == 0:
                checker_board.append(u)
        if len(checker_board) > 0:
            if self.game.computer_turn:  # VERIFICACIÓN DEL TURNO DE LA IA
                self.game.make_move(random.choice(checker_board))
            return 0


"""
https://leetcode.com/problems/unique-paths-ii/
"""

from typing import List

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        maxRow, maxCol = len(obstacleGrid) - 1, len(obstacleGrid[0]) - 1
        board = [[0] * (maxCol + 1) for _ in range(maxRow + 1)]
        # Check obstacles in the maxRow and maxCol.
        for row in range(maxRow, -1, -1):
            if obstacleGrid[row][maxCol]:
                break

            board[row][maxCol] = 1

        for col in range(maxCol, -1, -1):
            if obstacleGrid[maxRow][col]:
                break

            board[maxRow][col] = 1

        for col in range(maxCol - 1, -1, -1):
            for row in range(maxRow - 1, -1, -1):
                if obstacleGrid[row][col]:
                    board[row][col] = 0
                else:
                    board[row][col] = board[row + 1][col] + board[row][col + 1]

        return board[0][0]

obstacleGrid = [
    [0, 1]
]

print(Solution().uniquePathsWithObstacles(obstacleGrid))


from __future__ import annotations

import copy
import math
from typing import Optional, Tuple, Type, TypeVar, TYPE_CHECKING, Union

from data.render_order import RenderOrder

if TYPE_CHECKING:
    from components.ai import BaseAI
    from components.stats import Stats
    from components.inventory import Inventory
    from components.level import Level
    from game_map import GameMap

T = TypeVar('T', bound='Entity')

class Entity:
    parent: Union[GameMap, Inventory]

    def __init__(
        self,
        parent: Optional[GameMap] = None,
        x: int = 0,
        y: int = 0,
        char: str = '?',
        color: Tuple[int, int, int] = (255, 255, 255),
        name: str = '<Todd Howard>',
        blocks_movement: bool = False,
        render_order: RenderOrder = RenderOrder.CORPSE,
    ):
        self.x = x
        self.y = y
        self.char = char
        self.color = color
        self.name = name
        self.blocks_movement = blocks_movement
        self.render_order = render_order

        if parent:
            self.parent = parent
            parent.entities.add(self)

    @property
    def gamemap(self) -> GameMap:
        return self.parent.gamemap

    @property
    def position(self) -> Tuple[int, int]:
        return (self.x, self.y)

    def spawn(self: T, gamemap: GameMap, x: int, y: int):
        clone = copy.deepcopy(self)
        clone.x = x
        clone.y = y
        clone.parent = gamemap
        gamemap.entities.add(clone)
        return clone

    def place(self, x: int, y: int, gamemap: Optional[GameMap] = None) -> None:
        """Place entity."""
        self.x = x
        self.y = y
        if gamemap:
            if hasattr(self, 'parent'):
                if self.parent is self.gamemap:
                    self.gamemap.entities.remove(self)
            self.parent = gamemap
            gamemap.entities.add(self)

    def distance(self, x: int, y: int) -> float:
        return math.sqrt((x - self.x) ** 2 + (y - self.y) ** 2)

    def move(self, x: int, y: int) -> None:
        self.x += x
        self.y += y

class Actor(Entity):
    def __init__(
            self,
            *,
            gamemap: Optional[GameMap] = None,
            x: int = 0,
            y: int = 0,
            char: str = '?',
            color: Tuple[int, int, int] = (255, 255, 255),
            name: str = '<Actor Todd Howard>',
            ai_cls: Type[BaseAI],
            stats: Stats,
            inventory: Inventory,
            # equipment: Equipment,
            # fighter: Fighter,
            level: Level,
    ):
        super().__init__(
            x=x,
            y=y,
            char=char,
            color=color,
            name=name,
            blocks_movement=True,
            render_order=RenderOrder.ACTOR,
        )
        # Setting `Ai`
        self.ai: Optional[BaseAI] = ai_cls(self)

        # Setting `Stats`
        self.stats = stats
        self.stats.parent = self
        # Setting `Inventory`
        self.inventory = inventory
        self.inventory.parent = self
        # Setting `Level`
        self.level = level
        self.level.parent = self
        # TODO

    @property
    def is_alive(self) -> bool:
        return bool(self.ai)

class Item(Entity):
    pass


# Computer assignment 1
# Av Lucas Kallenberg
import time

import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from scipy.sparse import csr_matrix
from scipy.sparse import csgraph
from matplotlib.collections import LineCollection
from scipy.spatial import cKDTree

def read_coordinate_file(filename):  # Create a function that reads the txtfile and rename it as file
    """ Reads a textfile and converts the numbers into coordinates

    :param filename: Textfile containing coordinate points that has '{' and '}' around them
    :type filename: txt file

    :return: Array of coordinates
    :rtype: Numpy array of arrays of floats
    """

    with open(filename, 'r') as file:
        lst =[]  # Create an empty list to store my arrays
        r =1
        line = file.readline()  # Read the first line before we remove all unwanted characters with the while loop
        while line:
            line = line.strip()
            line = line.strip('{')
            line = line.strip('}')
            line = line.split(',')  # Split the arrays in the , mark
            line = [r*np.pi*float(line[1])/180, r*np.log(np.tan(np.pi/4+np.pi*float(line[0])/360))]
            lst.append(line)  # Save x,y into a list
            line = file.readline()
    arr = np.array(lst)  # Converts the list into a numpy array

    return arr

def plot_points(coord, indices,path):
    """ Plots the 'coords' as points and then drawing lines between chosen 'indices'
    and then drawing the shortest path of two points on the lines

    :param coord: Coordinates that sould be ploted
    :type: Array of arrays
    :param indices: Specific points of which coords that lines should be between
    :type: Arrays of arrays
    :param path: The shortest path between two predefined points on top of the lines
    :type: Array of int

    :return: Shows a plot
    :rtype: Have no type
    """
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)   # Create a subplot in the figure to be able to add stuff later
    plt.scatter(coord[:,0],coord[:,1], s = 2, c= 'r')  # Plot the coords as nodes
    seg = np.empty((len(indices),2,2))

    for i,p in enumerate(indices): #Take each array in indices
        seg[i,:,0] = [coord[p[0]][0], coord[p[1]][0]]   #x
        seg[i,:,1] = [coord[p[0]][1],coord[p[1]][1]]   #y
    ax.add_collection(LineCollection(seg,color= 'gray',linewidths= 0.2))    # Drawing the lines to the plot

    seg = np.empty((len(path), 2, 2))
    for i in range(len(path)-1):
        # Segments between points
        seg[i,:,0] = [coord[path[i]][0],coord[path[i+1]][0]]
        seg[i,:,1] = [coord[path[i]][1],coord[path[i+1]][1]]
    ax.add_collection(LineCollection(seg,color= 'blue',linewidths= 1))    # Drawing the lines to the plot

    plt.gca().set_aspect('equal')
    plt.show()

def construct_graph_connections(coord_list, radius):
    """ Creates two lists, one with the distances between coordinates that are within a certain radius
    and a list of the numbers of the coordinates

    :param coord_list: Checking if the coordinats ar within a certain radius of each other and storying those values
    :type: Array of arrays
    :param radius: Predefined value that the function checks against
    :type: Float

    :return: Distances between coords within the radius. Also returns which number of the coords the distance is between
    :rtype: 'distance' list of floats, 'coords' list of arrays
    """
    distance = []
    coords = []
    for n, a in enumerate(coord_list):  # Create a number infront of the arrays and then we loop over the arrays (For me to understand)
        for i in range(n+1, len(coord_list)):  # Takes the second array of the coord_list
            dist = np.linalg.norm(a - coord_list[i])  # Calculates the distance using pythagoras of the coords
            if dist <= radius:  #Checks if the coords are within a certain radius
                distance.append(dist)
                coords.append([n,i])

    distance = np.array(distance) # Converting into numpy arrays
    coords = np.array(coords)
    return distance , coords

def construct_graph(distance, indices,N):
    """ Creates a sparse matrix

    :param distance: The distance between the coordinates of the indices.
    :type: List of floats
    :param indices: The numbers of the coordinates that the distances are between
    :type: A list of arrays
    :param N: A predefined int that is the length of the list distance
    :type: int

    :return: A sparse matrix with the numbers of the coordinates and distances between them
    :rtype: csr_matrix
    """
    indices = indices.T     # Transpose to get the right input
    s = sp.sparse.csr_matrix((distance, indices), shape=[N,N])   # Saves the numbers between the points and the distance in a sparce matrix
    return s

def find_shortest_path(graph, start_node, end_node):
    """
    nodes, shortdist = find_shortest_path(sparsegrahp, start, end)

    :param graph: The sparse matrix that the function checks the values of
    :type: csr matrix
    :param start_node: A predefined value of which coordinate number to start at
    :type: int
    :param end_node: A predefined value of which coordinate number to end at
    :type: int

    :return: 'list' A list of the shortest path of the nodes that it goes through
    'shortestdistance' is the sum of distances between all the connecting nodes in the list from start to end
    :rtype: 'list' is array of ints, 'shortestdistance' is a float
    """

    dist, path = csgraph.shortest_path(graph, directed= False, return_predecessors= True, indices= (start_node))
    # dist = the shortest distance from each node from the starting node, path = last node before
    shortesdistance = dist[end_node]    # We take the distance from the end node

    list = [end_node]
    last = end_node
    # This while loop will be checking if we are back at the start node by starting at our last node and working its
    # way back by looking at the last nodes predecessor and so on
    while last > 0:
        list.append(path[last])     # Add the preceding node of the last node
        last = path[last]
        if last == -9999:   # If there is no path the value of list/last will be -9999
            del list[-1]    # Delete the last value of the list

    list.reverse()   # Get the order from start to end node
    list = np.array(list)
    return list, shortesdistance

def construct_fast_graph_connections(coord_list, radius):
    """Creates two lists, one with the distances between coordinates that are within a certain radius
    and a list of the numbers of the coordinates

    :param coord_list: Checking if the coordinats ar within a certain radius of each other and storying those values
    :type: Array of arrays
    :param radius: Predefined value that the function checks against
    :type: Float

    :return: 'dist' distances between coords within the radius. 'indices' returns which number of the coords the distance is between
    :rtype: 'dist' list of floats, 'indices' list of arrays
    """
    tree = sp.spatial.cKDTree(coord_list)
    dist = []
    indices = []
    points = tree.query_ball_point(coord_list, r=radius)     # Creates lists with the nearby nodes withing range of the choosen coordinate

    for i, point in enumerate(points):      # Check if the element is larger than i to make it undirected
        for j in point:
            if j >= i:
                indices.append(np.array([i, j]))

    speed = np.array(indices)
    up = np.array([coord_list[speed[:, 0]], coord_list[speed[:,1]]])
    dist = np.linalg.norm(up[0]-up[1], axis=-1)

    indices = np.array(indices)   # Convert
    dist = np.array(dist)

    return indices, dist

if __name__=='__main__':

    # Choose file to read: 1 = Sample, 2 = Hungary, 3 = Germany
    Choose = 2

    # Choose fast or slow graph conections: True or False
    Fast = False

    if Choose == 1:
        start_time = time.time()
        arr = read_coordinate_file('SampleCoordinates.txt')
        end_time = time.time()
        print('read_coordinate_file \t\t\t time: ',end_time-start_time)
        radius = 0.08
        start = 0
        end = 5

    elif Choose == 2:
        start_time = time.time()
        arr = read_coordinate_file('HungaryCities.txt')
        end_time = time.time()
        print('read_coordinate_file \t\t\t time: ', end_time - start_time)
        radius = 0.005
        start = 311
        end = 702

    elif Choose == 3:
        start_time = time.time()
        arr = read_coordinate_file('GermanyCities.txt')
        end_time = time.time()
        print('read_coordinate_file \t\t\t time: ', end_time - start_time)
        radius = 0.0025
        start = 1573
        end = 10584

    else:
        print('Wrong input. Choose either 1, 2 or 3 ')

    if Fast == False:
        start_time = time.time()
        distance, coords = construct_graph_connections(arr, radius)
        end_time = time.time()
        print('construct_graph_connections \t time: ', end_time - start_time)

    elif Fast == True:
        start_time = time.time()
        coords , distance = construct_fast_graph_connections(arr,radius)
        end_time = time.time()
        print('construct_fast_graph \t\t\t time: ', end_time - start_time)

    else:
        print('Write in true or false')

    N = len(distance)

    start_time = time.time()
    sparsegrahp = construct_graph(distance, coords,N)
    end_time = time.time()
    print('construct_graph \t\t\t\t time: ', end_time - start_time)

    start_time = time.time()
    nodes, shortdist = find_shortest_path(sparsegrahp, start, end)
    end_time = time.time()
    print('find_shortest_path \t\t\t\t time: ', end_time - start_time)

    start_time = time.time()
    plot_points(arr, coords,nodes)
    end_time = time.time()
    print('plot_points \t\t\t\t\t time: ', end_time - start_time)


# Проверка на нечетность

from isOdd import isOdd

print(isOdd(3))
print(isOdd(5))

# Прогресс-бар

from progress.bar import Bar

bar = Bar('Processing', max=20)
for i in range(20):
    # Do some work
    bar.next()
bar.finish()


from __future__ import division, print_function, unicode_literals

# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '.'))
#
import cocos
import cocos.director
from math import sin, cos, pi
from random import randint
from pyglet.window import key
from cocos.actions.interval_actions import RotateTo,MoveBy,Delay,ScaleTo
from cocos.actions.instant_actions import CallFunc,Repeat

class MainScene(cocos.scene.Scene):
	def __init__(self):
		super().__init__()
		self.bg=cocos.layer.util_layers.ColorLayer(150,150,150,0,200,200)
		self.bg.position=(0,0)
		self.add(self.bg)
		#Фон
		self.add(Phon())
		################################
		#Variable
		razmer = (900 , 900)
		self.redcoordinat = (400, 400)
		self.bluecoordinat = razmer[0] - self.redcoordinat[0], razmer[1] - self.redcoordinat[1]
		#--------------
		self.add(Player('red',self.redcoordinat,razmer ))

class Phon (cocos.layer.Layer):
	def __init__(self):
		super().__init__()
		self.phon = cocos.sprite.Sprite("phon.jpg")
		self.phon.position=(450,450)
		self.add(self.phon)
class Player(cocos.layer.Layer):
	is_event_handler = True
	def __init__(self,name,pos,razmer):
		super().__init__()
		#Создание игроков
		if name =='red' :
			self.sprite = cocos.sprite.Sprite("red.jpg")
			#Начальное положение и угол поворота
			self.sprite.position=pos
			self.rot = 0

		if name == 'blue':
			self.sprite = cocos.sprite.Sprite("blue.jpg")
			#Начальное положение и угол поворота
			self.sprite.position=pos
			self.rot = pi
		self.add(self.sprite)
		self.sprite.do(ScaleTo(0.4, 0))
		self.name = name

		self.bomb = 3
		self.keys=set()

		#Граница поля, скорость, бомбы
		self.xmax=razmer[0]-30
		self.xmin=30
		self.ymax=razmer[1]-30
		self.ymin=30
		self.v=4
		self.maxbomb=3
		self.timereload=5

		#Запускаем
		self.sprite.do(Repeat(Delay(0.001)+CallFunc(self.phizic)))

	def reload(self):
		self.bomb += 1
		if self.bomb < self.maxbomb :
			self.sprite.do(Delay(self.timereload)+CallFunc(self.reload))
	def on_key_release(self, keys, mod):
		self.keys.remove(keys)
	def on_key_press(self, keys, mod):
		# LEFT,a: выстрел
		# RIGTH,d: поворот
		self.keys.add(keys)

		#BOMB
		if (key.LEFT in self.keys and self.name=='red')or (key.A in self.keys and self.name=='blue'):
			if self.bomb == self.maxbomb:
				self.sprite.do(Delay(self.timereload)+CallFunc(self.reload))
			if self.bomb > 0 :
				self.bomb -= 1
				x, y = self.sprite.position
				#Работа с выстрелом
				self.do(Delay(0.001))
				self.parent.add(Pula(self.v,self.rot,x,y))

	def phizic(self):
		deltarot=0.1
		timerot=0.01
		x, y = self.sprite.position
		if (key.RIGHT in self.keys and self.name=='red') or (key.D in self.keys and self.name=='blue'):
			self.rot = self.rot +deltarot

		Vx = self.v*sin(self.rot)
		Vy = self.v*cos(self.rot)

		if (x+Vx<self.xmax) and (x+Vx>self.xmin):
			x = x + Vx
		if (y+Vy<self.ymax) and (y+Vy>self.ymin):
			y = y + Vy
		#Выдача координат директору
		if self.name == 'red':
			#import pdb; pdb.set_trace()
			self.parent.redcoordinat  = x , y
		if self.name == 'blue':
			self.parent.bluecoordinat = x , y
		#Изменение координат и угла
		self.sprite.position = x, y
		self.sprite.rotation = (self.rot*(180/pi))

class Pula (cocos.sprite.Sprite):
	def __init__(self,v,rot,x,y):
		super().__init__("kramnik.jpg")

		#Выдача скорости и поворота
		self.v0=v*2.5
		self.rot=rot
		#Вывод на экран
		self.do(ScaleTo(0.4, 0))
		self.position=(x,y)
		#Начинаем полет
		self.do(Repeat(CallFunc(self.phizic)+Delay(0.001)))
	def phizic (self):
		#Изменение координат
		Vx = self.v0*sin(self.rot)
		Vy = self.v0*cos(self.rot)
		x, y = self.position

		#Проверка расположения
		if x<=890 and x>=10 and y<=890 and y>= 10 :
			self.position = x+Vx,y+Vy
		else:
			self.parent.remove(self)
			#self.parent.remove(self.parent.namebomb[self.num])

cocos.director.director.init(width =900,height =900)
cocos.director.director.run(MainScene())


from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Habit',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('place', models.CharField(max_length=30, verbose_name='место')),
                ('time', models.TimeField(verbose_name='время')),
                ('action', models.CharField(max_length=60, verbose_name='действие')),
                ('pleasant_habit', models.BooleanField(verbose_name='приятная привычка')),
                ('frequency', models.IntegerField(default=1, verbose_name='периодичность')),
                ('award', models.CharField(blank=True, max_length=200, null=True, verbose_name='вознаграждение')),
                ('time_to_complete', models.TimeField(verbose_name='время на выполнение')),
                ('public', models.BooleanField(default=True, verbose_name='публичная')),
                ('last_execution', models.DateField(blank=True, null=True, verbose_name='последнее выполнение')),
                ('related_habit', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='habits.habit', verbose_name='связанная привычка')),
            ],
            options={
                'verbose_name': 'привычка',
                'verbose_name_plural': 'привычки',
            },
        ),
    ]


"""最终版2018/11/23"""
import re
import json
import time
import asyncio
import aiohttp
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
}
"""
新浪新闻 最热评论-最新评论
"""
class Sina_Comment:
    def __init__(self,url):
        self.url = url
        self.cmnt_list = []
        self.hot_list = []

    async def geturl(self,i,u):
        channels = ['jc', 'gn', 'gj', 'cj', 'kj', 'ty', 'yl', 'qc', 'yx', 'shuo', 'qz', 'wj', 'gy', 'fo', 'tousu', 'sf',
                    'sh','pl']
        url = u
        # url = 'https://finance.sina.com.cn/roll/2018-11-07/doc-ihmutuea7787670.shtml'
        p1 = re.compile(r'doc-i(.*?).shtml', re.S)
        cuturl = re.findall(p1, url)
        for c in channels:  # 遍历正确的js页
            pageurl = 'http://comment5.news.sina.com.cn/page/info?version=1&format=js&channel={0}&newsid=comos-{1}&group=&compress=0&ie=gbk&oe=gbk&page={2}&page_size=20&jsvar=loader_1541659646912_32229203'.format(
                c, cuturl[0], i)
            async with aiohttp.ClientSession() as session:
                async with session.get(pageurl, headers=headers) as html:
                    response = await html.text(encoding="utf-8")
                    if len(response) > 1000:
                        return response

    async def parse(self,page,u):
        response = await self.geturl(page,u)
        p2 = re.compile(r'=(.*)', re.S)
        cutjson = re.findall(p2, response)
        respjson = cutjson[0]
        html = json.loads(respjson)
        cmnt_items = html['result']['cmntlist']  # 最新评论
        hot_items = html['result']['hot_list']  # 最热评论
        for cmnt in cmnt_items:
            Mid = cmnt['mid']  # ID
            Name = cmnt['nick']  # 名称
            Area = cmnt['area']  # 位置
            Time = cmnt['time']  # 评论时间
            Content = cmnt['content']  # 评论内容
            Newsid = cmnt['newsid']  # Newsid
            Agree = cmnt['agree']  # 点赞数
            self.cmnt_list.append(
                {'Mid': Mid, 'Newsid': Newsid, 'Name': Name, 'Area': Area, 'Content': Content, 'Agree': Agree,
                 'Time': Time})
        for hot in hot_items:
            Mid = hot['mid']  # ID
            Name = hot['nick']  # 名称
            Area = hot['area']  # 位置
            Time = hot['time']  # 评论时间
            Content = hot['content']  # 评论内容
            Newsid = cmnt['newsid']  # Newsid
            Agree = cmnt['agree']  # 点赞数
            if len(self.hot_list) < 3:
                self.hot_list.append(
                    {'Mid': Mid, 'Newsid': Newsid, 'Name': Name, 'Area': Area, 'Content': Content, 'Agree': Agree,
                     'Time': Time})
            else:
                break
    def main(self):
        T1 = time.time()
        loop = asyncio.get_event_loop()
        tasks = [self.parse(i,self.url) for i in range(1, 50)]
        loop.run_until_complete(asyncio.wait(tasks))
        loop.close()
        T2 = time.time()
        sina_commment_dict = {'最新评论': self.cmnt_list, '最热评论': self.hot_list,'type':'xinlang'}
        return sina_commment_dict
        # print(T2 - T1)