from typing import List

class Solution:
    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
        if not A:
            return 0
        def sameNum(arr: List[int]) -> dict:
            result = {}
            for i in arr:
                if i in result:
                    result[i] += 1
                else:
                    result[i] = 1
            return result

        def zeroSubtraction(da: dict, db: dict) -> dict:
            result: dict = {}
            for a in da.keys():
                for b in db.keys():
                    if result.__contains__((a + b)):
                        result[(a + b)] += da[a] * db[b]
                    else:
                        result[(a + b)] = da[a] * db[b]
            return result

        def theEnd(da: dict, db: dict) -> int:
            result = 0
            for a in da.keys():
                if db.__contains__(-a):
                    result += da[a] * db[-a]
            return result

        da = sameNum(A)
        db = sameNum(B)
        dc = sameNum(C)
        dd = sameNum(D)

        d1 = zeroSubtraction(da, db)
        d2 = zeroSubtraction(dc, dd)
        result = theEnd(d1, d2)

        return result

if __name__ == '__main__':
    print(Solution().fourSumCount([-1,-1],[-1,1], [-1,1],[1,-1]))


import math
import sys
import imutils

sys.path.append("..")
import cv2
import torch
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from DatasetBuilding.drivingDataset import DrivingDataset
from torch.utils.data import DataLoader
from modelCNN import CNN

def drawLivePredictions(frame, acceleration, steering):
   OPEN_ANGLE   = 120
   LINE_LENGTH  = 120
   CENTER       = (int(frame.shape[1]/2), frame.shape[0])
   CENTER_ANGLE = -90
   ACCEL_DISPLAY_OFFSET = 150

   # Angles
   angleLeft   = CENTER_ANGLE - int(OPEN_ANGLE/2)
   angleRight  = CENTER_ANGLE + int(OPEN_ANGLE/2)
   anglePred   = CENTER_ANGLE + int(OPEN_ANGLE/2*steering)

   # Left
   x_left = int(CENTER[0] + math.cos(math.radians(angleLeft)) * LINE_LENGTH)
   y_left = int(CENTER[1] + math.sin(math.radians(angleLeft)) * LINE_LENGTH)

   # Right
   x_right = int(CENTER[0] + math.cos(math.radians(angleRight)) * LINE_LENGTH)
   y_right = int(CENTER[1] + math.sin(math.radians(angleRight)) * LINE_LENGTH)

   # Prediction
   x_pred = int(CENTER[0] + math.cos(math.radians(anglePred)) * LINE_LENGTH)
   y_pred = int(CENTER[1] + math.sin(math.radians(anglePred)) * LINE_LENGTH)

   cv2.line(frame, CENTER, (x_left,  y_left),  (0, 255, 0), 3)
   cv2.line(frame, CENTER, (x_right, y_right), (0, 255, 0), 3)
   cv2.line(frame, CENTER, (x_pred,  y_pred),  (0, 0, 255), 3)

   accelerationColor = (0, 255, 0)
   if acceleration < 0:
      accelerationColor = (0, 0, 255)
   cv2.line(frame, (CENTER[0] - ACCEL_DISPLAY_OFFSET, CENTER[1]), (CENTER[0] - ACCEL_DISPLAY_OFFSET,  int(CENTER[1] - LINE_LENGTH)),  (0, 0, 0), 10)
   cv2.line(frame, (CENTER[0] - ACCEL_DISPLAY_OFFSET, CENTER[1]), (CENTER[0] - ACCEL_DISPLAY_OFFSET,  int(CENTER[1] - LINE_LENGTH * acceleration)),  accelerationColor, 5)

   return frame

# Device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Load Model
model = CNN()
model.load_state_dict(torch.load("../../res/models/FINAL_CNN_epochs_500_3.0"))
model.eval()

# Load Data
dataset = DrivingDataset("../../res/datasets/full.txt", isTrainSet=False, minAcceleration=0.20)
dataloader = DataLoader(dataset, batch_size=100, shuffle=False)
# inputs, targets = next(iter(dataloader))

end = False
while not end:
   for batchIdx, (batchData, targets) in enumerate(dataloader):
      for frame in batchData:
         preds = model(frame.view(1, 1, frame.shape[1], frame.shape[2]))
         preds = preds.flatten().detach().numpy()
         accel = preds[0]
         steer = preds[1]
         steer = max(min(steer, 1), -1)

         frame = frame[0].numpy().astype(np.uint8)
         frame = np.dstack((frame, frame))
         frame = np.dstack((frame, frame))
         frame = imutils.resize(frame, width=500)

         drawLivePredictions(frame, acceleration=accel, steering=steer)

         frame = imutils.resize(frame, width=1000)

         cv2.imshow('Live Model Decisions', frame)
         if cv2.waitKey(100) & 0xFF == ord('q'):
            end = True
            break
      if end:
         break

cv2.destroyAllWindows()


import torch
import numpy as np

from utils.misc import soft_update

from model.BCAgent import BCAgent
from model.utils.model import *

class BahaviorClone(object):

    def __init__(self, name, params):

        self.name = name
        self.lr = params.lr
        self.gamma = params.gamma
        self.tau = params.tau

        self.obs_dim = params.obs_dim
        self.action_dim = params.action_dim
        self.batch_size = params.batch_size // 2
        self.device = params.device
        self.discrete_action = params.discrete_action_space

        self.agent_index = params.agent_index
        self.num_agents = len(self.agent_index)

        self.cross_entropy_loss = torch.nn.CrossEntropyLoss()

        params.critic.obs_dim = (self.obs_dim + self.action_dim)

        self.agents = [BCAgent(params) for _ in range(self.num_agents)]
        [agent.to(self.device) for agent in self.agents]

    def act(self, observations, sample=False):
        observations = torch.Tensor(observations).to(self.device)

        actions = []
        for agent, obs in zip(self.agents, observations):
            agent.eval()
            actions.append(agent.act(obs, explore=sample).squeeze())
            agent.train()
        return np.array(actions)

    def update(self, replay_buffer, logger, step):
        sample = replay_buffer.sample(self.batch_size, nth=self.agent_index)
        obses, actions, rewards, next_obses, dones = sample

        # split each joint into two single trajectories
        # need to check
        obses = (torch.cat([obses[:, 0], obses[:, 1]], dim=0))
        actions = (torch.cat([actions[:, 0], actions[:, 1]], dim=0))
        rewards = (torch.cat([rewards[:, 0], rewards[:, 1]], dim=0))
        next_obses = (torch.cat([next_obses[:, 0], next_obses[:, 1]], dim=0))
        dones = (torch.cat([dones[:, 0], dones[:, 1]], dim=0))

        if self.discrete_action:
            actions = number_to_onehot(actions)
            actions = torch.max(actions.long(), 1)[1]

        for agent_i, agent in enumerate(self.agents):
            agent.policy_optimizer.zero_grad()
            agent_actions = agent.policy(obses)
            loss = self.cross_entropy_loss(agent_actions, actions)
            loss.backward()
            agent.policy_optimizer.step()

    def save(self, filename):
        raise NotImplementedError

    def load(self, filename):
        raise NotImplementedError


while True:
	try:
		a=input()
		a=list(a)
		break
	except:
		print("Invalid input")
		break
b=sorted(a,reverse=True)
if(a<b):
	print(''.join(str(x) for x in b))
else:
	print("impossible")


from django.utils.translation import gettext_lazy as _
from django.db import models
import uuid
from internal_users.models import InternalUser
from customer_users.models import CustomerUser
from homepageapp.models import RepairOrdersNewSQL02Model as RepairOrder
from django.utils import timezone
from core_operations.models import FormattedPhoneNumberField

APPT_STATUS_NOT_SUBMITTED = 0
APPT_STATUS_PENDING = 1
APPT_STATUS_CONFIRMED = 2
APPT_STATUS_REJECTED = 3
APPT_STATUS_RESCHEDULED = 4
APPT_STATUS_PORGRESSING = 5
APPT_STATUS_COMPLETED = 10
APPT_STATUS_CANCELLED = -20

class AppointmentRequest(models.Model):
    STATUS_CHOICES = (
        (APPT_STATUS_NOT_SUBMITTED, _('00_Not_Submitted')),
        (APPT_STATUS_PENDING, _('01_Pending')),
        (APPT_STATUS_CONFIRMED, _('02_Confirmed')),
        (APPT_STATUS_REJECTED, _('03_Rejected')),
        (APPT_STATUS_RESCHEDULED, _('04_Rescheduled')),
        (APPT_STATUS_PORGRESSING, _('05_Progressing (tracking status via repair order)')),
        (APPT_STATUS_COMPLETED, _('10_Completed')),
        (APPT_STATUS_CANCELLED, _('-20_Cancelled')),
    )
    REASON_CHOICES = (
        (0, '00-not selected.'),
        (1, '01-oil change and maintenance.'),
        (2, '02-a/c diagnosis, compressors etc.'),
        (3, '03-brakes, transmission'),
        (4, '04-service lights, engine related'),
        (5, '05-just inqurires, others'),
    )
    appointment_id = models.BigAutoField(primary_key=True)
    # appointment_date = models.DateField()
    appointment_requested_datetime = models.DateTimeField(
        null=True, blank=True, verbose_name='Requested Apptmnt Time')
    appointment_confirmed_datetime = models.DateTimeField(
        null=True, blank=True, verbose_name='Confirmed Apptmnt Time')
    appointment_reason_for_visit = models.PositiveSmallIntegerField(
        choices=REASON_CHOICES, default=0, verbose_name='Reason for visit?')
    appointment_customer_user = models.ForeignKey(
        CustomerUser, on_delete=models.SET_NULL, null=True, verbose_name='your linked user account')
    appointment_first_name = models.CharField(
        max_length=50, null=True, blank=True)
    appointment_last_name = models.CharField(
        max_length=50, null=True, blank=True)
    appointment_phone_number = FormattedPhoneNumberField(
        help_text='we will send appointment reminders to this number.')
    appointment_phone_number_digits_only = models.CharField(
        max_length=20, null=True)
    # recording either customer_user or internal_user
    appointment_user_type = models.CharField(
        max_length=50, blank=True, null=True)
    appointment_email = models.EmailField(null=True)
    appointment_vehicle_year = models.CharField(
        max_length=4, null=True, blank=True)
    appointment_vehicle_make = models.CharField(
        max_length=100, null=True, blank=True)
    appointment_vehicle_model = models.CharField(
        max_length=100, null=True, blank=True)
    appointment_vehicle_license_plate = models.CharField(
        max_length=20, null=True, blank=True)
    appointment_vehicle_license_state = models.CharField(
        max_length=2, null=True, blank=True)
    appointment_vehilce_vin_number = models.CharField(
        max_length=30, null=True, blank=True)
    appointment_vehicle_detail = models.TextField()
    appointment_vehicle_detail_in_json = models.CharField(
        max_length=4000, null=True)  # {'year': 2003, 'model': VW, ...}
    appointment_concern_description = models.TextField(blank=True)

    # check the status of the appointment
    appointment_status = models.CharField(
        max_length=50, choices=STATUS_CHOICES, default=APPT_STATUS_NOT_SUBMITTED, verbose_name='Appointment Status')
    appointment_status_comments = models.CharField(
        max_length=4000, null=True, blank=True)
    appointment_is_active = models.BooleanField(default=True)
    appointment_preferred_contact_method = models.CharField(
        max_length=100, blank=True, null=True)
    appointment_repair_order = models.ForeignKey(
        RepairOrder, on_delete=models.SET_NULL, null=True, related_name='appointment_repair_order')
    appointment_is_converted_to_ro = models.BooleanField(default=False)
    appointment_confirmation_id = models.UUIDField(
        default=uuid.uuid4, editable=False,  verbose_name='your appointment confirmation id')  # unique=True,
    # appointment can either be created by anoymous user, a signed-in customer_user or created by an internal_user when a customer shows up on the physical store.
    appointment_created_by_internal_user = models.ForeignKey(
        InternalUser, on_delete=models.SET_NULL, null=True, related_name='appointment_created_by')  # when null, it means its created by customer user
    appointment_created_at = models.DateTimeField(auto_now_add=True)
    appointment_last_updated_at = models.DateTimeField(auto_now=True)

    @property
    def appointment_full_name(self):
        return f"{self.appointment_first_name} {self.appointment_last_name}"

    class Meta:
        db_table = 'appointments'
        ordering = ['-appointment_id']

    def __str__(self):
        return f"Name: {self.appointment_first_name} {self.appointment_last_name}-Time: {self.appointment_requested_datetime}"

class AppointmentImages(models.Model):
    image_id = models.BigAutoField(primary_key=True)
    appointment = models.ForeignKey(AppointmentRequest, on_delete=models.SET_NULL,
                                    null=True, related_name='appointment_appointmentimages')
    appointment_image = models.FileField(
        upload_to='appointment_images')  # the bucket's subfolder
    uploaded_date = models.DateTimeField(auto_now_add=True)
    image_is_active = models.BooleanField(default=True)

    class Meta:

        db_table = 'appointment_images'
        ordering = ['-image_id']
        verbose_name = 'appointment_image'
        verbose_name_plural = 'appointment_images'


# brute force solution
# don't have flexibility
# for learning purposes only

value = 200  # how many we want to collect
ways  = 0    # how many ways to collect the target

for coin200 in range(value, -1, -200):
  for coin100 in range(coin200, -1, -100):
    for coin50 in range(coin100, -1, -50):
      for coin20 in range(coin50, -1, -20):
        for coin10 in range(coin20, -1, -10):
          for coin5 in range(coin10, -1, -5):
            for coin2 in range(coin5, -1, -2):
              ways += 1

print(ways)


# 인식시킬 사진을 Clova API를 통해 요청을 보내, 인식 결과를 받아온다.
# req(파일)   : 파일 데이터 전송

# 1. requests를 통해 Clova API 주소에 요청을 보낸다.
# 2. 응답 받은 json을 파싱하여 원하는 결과를 출력한다.

import requests
import os
from pprint import pprint as pp

naver_id = os.getenv('NAVER_ID')
naver_secret = os.getenv('NAVER_SECRET')

url = "https://openapi.naver.com/v1/vision/celebrity"

headers = {
    'X-Naver-Client-Id': naver_id ,
    'X-Naver-Client-Secret': naver_secret
}

# 1. 해당하는 image_url에 요청을 보낸다\
image_url = "http://www.kbstve.com/news/photo/201604/681_616_1746.jpg"
image_res = requests.get(image_url, stream=True)  # 옵션 아는 법 google : python requests 문서 찾아보기
# print(image_res.raw.read())

# 2. 파일 데이터를 받아 저장해둔다
files = {
    'image': open('ho.jpg', 'rb')   # open : 파일을 열때 쓰는 함수 = image에 파일을 넣어줌
    #'image' : image_res.raw.read()
}

res = requests.post(url, headers=headers, files=files)
result = res.json()

name = result['faces'][0]['celebrity']['value']
percent =  round(result['faces'][0]['celebrity']['confidence']*100)

print("닮은 연예인은 {}입니다.\n{}% 확신할 수 있습니다.".format(name,percent))


import os
import logging
from xdg.BaseDirectory import xdg_config_home, xdg_state_home
from typing import Dict

import yaml

from .log import LogManager
from cfancontrol import __version__ as VERSION

class Environment(object):

    APP_NAME: str = "cfancontrol"
    APP_FANCY_NAME: str = "Commander²"
    APP_VERSION: str = VERSION
    LOG_FILE: str = 'cfancontrol.log'
    CONFIG_FILENAME: str = 'config.yaml'
    SENSORS_FILE: str = 'sensors3.conf'

    is_root: bool = False
    log_path: str = ''
    log_full_name: str = ''
    settings_path: str = ''
    config_full_name: str = ''
    pid_path: str = ''
    sensors_config_file: str = ''

    @staticmethod
    def prepare_environment():
        if os.geteuid() == 0:
            Environment.is_root = True
            Environment.log_path = "/var/log"
            Environment.settings_path = os.path.join("/etc", Environment.APP_NAME)
            Environment.sensors_config_file = os.path.join("/etc", Environment.SENSORS_FILE)
            Environment.pid_path = "/var/run"
        else:
            Environment.log_path = os.path.join(xdg_state_home, Environment.APP_NAME)
            Environment.settings_path = os.path.join(xdg_config_home, Environment.APP_NAME)
            Environment.sensors_config_file = os.path.join(Environment.settings_path, Environment.SENSORS_FILE)
            Environment.pid_path = f"/var/run/user/{os.geteuid()}"
        if not os.path.isdir(Environment.log_path):
            os.makedirs(Environment.log_path, mode=0o755, exist_ok=True)
        if not os.path.isdir(Environment.settings_path):
            os.makedirs(Environment.settings_path, mode=0o755, exist_ok=True)
        if not os.path.isfile(Environment.sensors_config_file):
            os.mknod(Environment.sensors_config_file, mode=0o755)
        Environment.log_full_name = os.path.join(Environment.log_path, Environment.LOG_FILE)
        Environment.config_full_name = os.path.join(Environment.settings_path, Environment.CONFIG_FILENAME)

class Config(object):
    interval: float = 10.0
    auto_start: bool = False
    profile_file: str = ''
    log_level: int = logging.INFO
    theme: str = 'light'

    @classmethod
    def from_arguments(cls, **kwargs):
        for attr in kwargs:
            setattr(cls, attr, kwargs[attr])
        if cls.profile_file:
            if os.path.isfile(os.path.expanduser(cls.profile_file)):
                cls.profile_file = os.path.expanduser(cls.profile_file)
            else:
                cls.profile_file = ''
                cls.auto_start = False
        else:
            cls.auto_start = False

    @classmethod
    def get_settings(cls) -> Dict:
        return {name: value for name, value in vars(cls).items() if not callable(getattr(cls, name)) and not name.startswith("__")}

    @classmethod
    def load_settings(cls):
        if Environment.config_full_name:
            cls._load_from_file(Environment.config_full_name)

    @classmethod
    def _load_from_file(cls, file_name: str):
        if file_name is not None and os.path.isfile(file_name):
            LogManager.logger.debug(f'Loading configuration from {file_name}')
            with open(file_name) as config_file:
                config = yaml.safe_load(config_file)
                if config:
                    cls.from_arguments(**config)

    @classmethod
    def save_settings(cls):
        if Environment.config_full_name:
            cls._save_to_file(Environment.config_full_name)

    @classmethod
    def _save_to_file(cls, file_name: str):
        if file_name is not None:
            LogManager.logger.debug(f'Saving configuration: {repr(cls.get_settings())}')
            with open(file_name, 'w') as config_file:
                yaml.safe_dump(cls.get_settings(), config_file)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""http://www.pythonchallenge.com/pc/rock/arecibo.html:kohsamui:thailand"""

__author__ = "子風"
__copyright__ = "Copyright 2015, Sun All rights reserved"
__version__ = "1.0.0"

import get_challenge
from PIL import Image
import copy
import time

def getdata(url):
    f = get_challenge.download(url, "kohsamui", "thailand")
    flag = -1
    size = []
    hor = []
    ver = []
    temp = [size, hor, ver]
    for i in f.getvalue().decode().split('\n'):
        if i == '':
            pass
        elif i[0] == '#':
            flag += 1
        else:
            temp[flag].append(list(map(int, i.split())))

    return (size[0][0], size[0][1], hor, ver)

def genv(v, l, marks):
    '''遞歸方式獲取可能的排列
    v=描述串(列表) l=行/列長度 marks=(填滿,留空)
    '''
    r = []
    if v:
        for i in range(l-(len(v)-1)-sum(v)+1):  # 長度-中間留空-總填滿 = 可移動空間
            ri = marks[1]*i + marks[0]*v[0]  #開頭
            if len(v) == 1:
                r += [ri + marks[1]*(l-len(ri))]  # 剩下留空
            else:
                rr = genv(v[1:], l-len(ri)-1, marks)  # 長度少 1 因需留空
                r += [ri + marks[1] + vv for vv in rr]
        return r
    else:
        return [marks[1]*l]

# 必定的值
def confirmedSingle(origin, idx, l):
    '''檢查 l 中所有 item 的第 idx 項是否一致，不一致則返回原值，否則返回這項的值'''
    for item in l:
        if item[idx] != l[0][idx]:
            return origin
    return l[0][idx]

# 填滿確定值
def confirmed(table, hl, vl):
    '''table 填入所有確定的值'''

    for j, l in enumerate(hl):
        for i in range(len(l[0])):
            table[j][i] = confirmedSingle(table[j][i], i, l)

    for i, l in enumerate(vl):
        for j in range(len(l[0])):
            table[j][i] = confirmedSingle(table[j][i], j, l)

    return table

# 檢查是否符合
def checkMatch(tl, l):
    for i in range(len(tl)):
        if tl[i] != "?" and tl[i] != l[i]:
            return False
    return True

# 去掉不符合的組合
def removeMismatch(table, hls, vls):
    thl = []
    tvl = []
    for j, hl in enumerate(hls):
        t = []
        for rl in hl:
            if checkMatch(table[j], rl):
                t.append(rl)
        if t:
            thl.append(t)

    for i, vl in enumerate(vls):
        t = []
        for cl in vl:
            if checkMatch([l[i] for l in table], cl):
                t.append(cl)
        if t:
            tvl.append(t)

    return (thl, tvl)

# 檢查所有組合的可能性
def combineAll(tables, hl, vl, size, checktable=[], xy=(0, 0), getOne=False):
    # print(xy)
    if hl:  # 利用 hl 組合可能的 table
        # 利用 hl 檢查可能的 vl
        for l in hl[0]:
            tvl = []
            for i, vs in enumerate(vl):
                t = []
                for col in vs:
                    if col[xy[1]] == l[i]:
                        t.append(col)
                if not t:
                    tvl = []
                    break
                tvl.append(t)
            if not tvl:
                continue

            checktable.append(l)

            print('\n', xy)
            print('\n'.join(checktable))
            ans = combineAll(tables, hl[1:], tvl, size, checktable, xy=(xy[0], xy[1]+1), getOne=getOne)
            if ans:
                tables.append(copy.deepcopy(ans))
            if tables and getOne:
                return None
            # 回覆原本的狀態
            checktable.pop()

        return None

    else:  # if len(vl) == size[1]:
        return checktable

def measureTime(func):
    def with_measureTime(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = (time.perf_counter() - start)
        print("get elapsed:", elapsed)
        input("pause...")
        return result
    return with_measureTime

@measureTime
def solved(width, height, hnum, vnum):
    # print(width, height, hnum, vnum)
    table = [["?" for _ in range(width)] for _ in range(height)]

    Hlist = [genv(a, width, ('1', '0')) for a in hnum]
    Vlist = [genv(a, height, ('1', '0')) for a in vnum]
    # print('all possible row/col generated.')
    # 此部分還可改進速度，將 confirmed & removeMismatch 合併寫，如 solvedFast
    # 但考慮可讀性就不修了
    while True:
        sumH = sum([len(x) for x in Hlist])
        sumV = sum([len(x) for x in Vlist])

        table = confirmed(table, Hlist, Vlist)
        Hlist, Vlist = removeMismatch(table, Hlist, Vlist)

        print('H after: ',)
        print(','.join([str(len(x)) for x in Hlist]))
        print('V after: ',)
        print(','.join([str(len(x)) for x in Vlist]))
        sumHt = sum([len(x) for x in Hlist])
        sumVt = sum([len(x) for x in Vlist])

        if sumH == sumHt and sumV == sumVt:
            break

    # print('removeMismatch')
    tables = []
    combineAll(tables, Hlist, Vlist, (width, height), getOne=True)

    # print(tables)
    if tables:
        print("\nfinish")
        for t in tables:
            print('\n'.join(t))
    else:
        print("no solution")

    imgs = []
    for t in tables:
        img = Image.new('L', (width, height))
        img.putdata([(x == '0') and 255 or 0 for l in t for x in l])
        imgs.append(img.resize((width*10, height*10)))

    return imgs

@measureTime
def solvedFast(width, height, hnum, vnum):
    # print(width, height, hnum, vnum)
    table = [["?" for _ in range(width)] for _ in range(height)]

    Hlist = [genv(a, width, ('1', '0')) for a in hnum]
    Vlist = [genv(a, height, ('1', '0')) for a in vnum]

    totalnumber = width*height
    resovlednumber = 0
    itercnt = 1
    resovled = table
    while resovlednumber < totalnumber:
        print('nitercnt=%d' % (itercnt))
        for i, rows in enumerate(Hlist):
            for j in range(width):
                if resovled[i][j] == '?':
                    t = confirmedSingle(None, j, rows)
                    if t:
                        resovled[i][j] = t
                        Vlist[j] = [item for item in Vlist[j] if item[i] == t]  # 馬上用確定的點來減少Vlist對應列的可能數量
                        resovlednumber += 1
        for i, cols in enumerate(Vlist):
            for j in range(height):
                if resovled[j][i] == '?':
                    t = confirmedSingle(None, j, cols)
                    if t:
                        resovled[j][i] = t
                        Hlist[j] = [item for item in Hlist[j] if item[i] == t]  # 馬上用確定的點來減少Hlist對應行的可能數量
                        resovlednumber += 1

        print('H after: ',)
        print(','.join([str(len(x)) for x in Hlist]))
        print('V after: ',)
        print(','.join([str(len(x)) for x in Vlist]))
        itercnt += 1

    # print(tables)
    print("\nfinish")
    print('\n'.join([''.join(l) for l in resovled]))

    img = Image.new('L', (width, height))
    img.putdata([(x == '0') and 255 or 0 for l in resovled for x in l])
    return img.resize((width*10, height*10))

# width, height, hnum, vnum = getdata("http://www.pythonchallenge.com/pc/rock/warmup.txt")
# result = solved(width, height, hnum, vnum)
width, height, hnum, vnum = getdata("http://www.pythonchallenge.com/pc/rock/up.txt")
result = solvedFast(width, height, hnum, vnum)
result = solved(width, height, hnum, vnum)[0]

# google Free" as in "Free speech", not as in "free 可得 beer


import datetime
from django.db import models
from imagekit.models import ImageModel
from structure.models import Author
from video.managers import PublishedVideoManager
from tagging.fields import TagField

class Video(ImageModel):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True)
    pub_date = models.DateTimeField(default=datetime.datetime.now,
        auto_now_add=True)
    link = models.URLField(
        help_text="Insert Link to YouTube or Vimeo video. e.g. \
            http://www.youtube.com/watch?v=vnVkGSAqCIE. Make sure the link is \
            http, not httpS")
    tags = TagField()
    caption = models.TextField()
    photographer = models.ForeignKey(Author, blank=True, null=True)
    screenshot = models.ImageField(upload_to='video_thumbs/%Y/%m/%d',
        help_text='Please convert all images to RGB JPEGs.')
    is_published = models.BooleanField()
    is_tweeted = models.BooleanField(editable=False, default=False)

    objects = models.Manager()
    published = PublishedVideoManager()

    class IKOptions:
        # Defining ImageKit options
        spec_module = 'video.specs'
        cache_dir = 'photo_cache'
        image_field = 'screenshot'

    class Meta:
        ordering = ['-pub_date']

    @models.permalink
    def get_absolute_url(self):
        return ('video.views.video_detail', (), {
            'datestring': self.pub_date.strftime("%Y-%m-%d"),
            'slug': self.slug})

    def get_twitter_message(self):
        return u'Video: %s: %s' % (self.name)

    def model_type(self):
        return self.__class__.__name__

    def __unicode__(self):
        return self.name


"""
167. 两数之和 II - 输入有序数组
给定一个已按照 非递减顺序排列  的整数数组 numbers ，请你从数组中找出两个数满足相加之和等于目标数 target 。

函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ，所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。

你可以假设每个输入 只对应唯一的答案 ，而且你 不可以 重复使用相同的元素。

示例 1：

输入：numbers = [2,7,11,15], target = 9
输出：[1,2]
解释：2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
示例 2：

输入：numbers = [2,3,4], target = 6
输出：[1,3]
示例 3：

输入：numbers = [-1,0], target = -1
输出：[1,2]

提示：

2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers 按 非递减顺序 排列
-1000 <= target <= 1000
仅存在一个有效答案
"""

class Solution:
    """
    方法一：暴力解法 O(n^2)
    方法二：二分查找法 O(nlogn)
    方法三：对撞指针法 O(n)
    """
    def twoSum(self, numbers, target):
        left, right = 0, len(numbers)-1
        while left < right:
            if numbers[left] + numbers[right] == target:
                return [left+1, right+1]
            elif numbers[left] + numbers[right] < target:
                left += 1
            else:
                right -= 1

if __name__ == "__main__":
    A = [2,7,11,15]
    target = 9
    s = Solution()
    print(s.twoSum(A, target))


from flask import Flask, render_template, request, url_for, jsonify
from base64 import b64encode, b64decode

app = Flask(__name__)

img = ""

@app.route('/upload', methods=["POST", "GET"])
def up():
    global img
    img = request.get_json()
    return img["image"]

def main():
    app.run()

if __name__ == "__main__":
    main()


import re
import base64
import xml.dom.minidom
import zlib

from xml.parsers.expat import ExpatError

def repr_saml_request(saml_str, b64=False):
    """Decode SAML request from b64 and b64 deflated
    and return a pretty printed representation
    """
    try:
        msg = base64.b64decode(saml_str).decode() if b64 else saml_str
        dom = xml.dom.minidom.parseString(msg)
    except (UnicodeDecodeError, ExpatError) as err:
        # in HTTP-REDIRECT the base64 must be inflated
        msg = base64.b64decode(saml_str) if b64 else saml_str
        try:
            inflated = zlib.decompress(msg, -15)
        except (zlib.error, TypeError):
            raise err from None

        dom = xml.dom.minidom.parseString(inflated.decode())
    return dom.toprettyxml()

def encode_http_redirect_saml(saml_envelope):
    return base64.b64encode(zlib.compress(saml_envelope.encode()))

def saml_request_from_html_form(html_str):
    regexp = 'name="SAMLRequest" value="(?P<value>[a-zA-Z0-9+=]*)"'
    authn_request = re.findall(regexp, html_str)
    if not authn_request:
        raise ValueError("AuthnRequest not found in htmlform")

    return authn_request[0]


import os, platform, subprocess
from tempfile import TemporaryDirectory
import zipfile

import tkinter as tk
import tkinter.ttk as ttk
import tkinter.scrolledtext as scrolledtext
from tkinter import filedialog

from pdfrw import PdfReader, PdfWriter, PdfDict, PdfName

basedir = os.path.dirname(__file__)

if platform.system() == 'Windows':
    win = True
    LO = "C:\\Program Files\\LibreOffice\\program\\soffice.exe"
else:
    win = False
    LO = "libreoffice"

def run_extern(command, *args, cwd = None, xpath = None, feedback = None):
    """Run an external program.
    Pass the command and the arguments as individual strings.
    The command must be either a full path or a command known in the
    run-time environment (PATH).
    Named parameters can be used to set:
     - cwd: working directory. If provided, change to this for the
       operation.
     - xpath: an additional PATH component (prefixed to PATH).
     - feedback: If provided, it should be a function. It will be called
         with each line of output as this becomes available.
    Return a tuple: (return-code, message).
    return-code: 0 -> ok, 1 -> fail, -1 -> command not available.
    If return-code >= 0, return the output as the message.
    If return-code = -1, return a message reporting the command.
    """
    # Note that using the <timeout> parameter will probably not work,
    # at least not as one might expect it to.
    params = {
        'stdout': subprocess.PIPE,
        'stderr': subprocess.STDOUT,
        'universal_newlines':True
    }
    my_env = os.environ.copy()
    if win:
        # Suppress the console
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        params['startupinfo'] = startupinfo
    if xpath:
        # Extend the PATH for the process
        my_env['PATH'] = xpath + os.pathsep + my_env['PATH']
        params['env'] = my_env
    if cwd:
        # Switch working directory for the process
        params['cwd'] = cwd

    cmd = [command] + list(args)
    try:
        if feedback:
            out = []
            with subprocess.Popen(cmd, bufsize=1, **params) as cp:
                for line in cp.stdout:
                    l = line.rstrip()
                    out.append(l)
                    feedback(l)
            msg = '\n'.join(out)

        else:
            cp = subprocess.run(cmd, **params)
            msg = cp.stdout

        return (0 if cp.returncode == 0 else 1, msg)

    except FileNotFoundError:
        return (-1, _COMMANDNOTPOSSIBLE.format(cmd=repr(cmd)))

def libre_office(in_list, pdf_dir):
    """Convert a list of odt (or docx or rtf, etc.) files to pdf-files.
    The input files are provided as a list of absolute paths,
    <pdf_dir> is the absolute path to the output folder.
    """
# Use LibreOffice to convert the input files to pdf-files.
# If using the appimage, the paths MUST be absolute, so I use absolute
# paths "on principle".
# I don't know whether the program blocks until the conversion is complete
# (some versions don't), so it might be good to check that all the
# expected files have been generated (with a timeout in case something
# goes wrong?).
# The old problem that libreoffice wouldn't work headless if another
# instance (e.g. desktop) was running seems to be no longer the case,
# at least on linux.
    def extern_out(line):
        REPORT(line)

    rc, msg = run_extern(LO, '--headless',
            '--convert-to', 'pdf',
            '--outdir', pdf_dir,
            *in_list,
            feedback = extern_out
        )

def merge_pdf(ifile_list, ofile, pad2sided = False):
    """Join the pdf-files in the input list <ifile_list> to produce a
    single pdf-file. The output is returned as a <bytes> object.
    The parameter <pad2sided> allows blank pages to be added
    when input files have an odd number of pages – to ensure that
    double-sided printing works properly.
    """
    writer = PdfWriter()
    for inpfn in ifile_list:
        ipages = PdfReader(inpfn).pages
        if pad2sided and len(ipages) & 1:
            # Make sure we have an even number of pages by copying
            # and blanking the first page
            npage = ipages[0].copy()
            npage.Contents = PdfDict(stream='')
            ipages.append(npage)
        writer.addpages(ipages)
    writer.write(ofile)

def get_input():
    text.delete('1.0', tk.END)

#    files = filedialog.askopenfilenames(
#        parent=root,
##            initialdir='/',
##            initialfile='tmp',
#        filetypes=[
#            ("All files", "*"),
#            ("Word", "*.docx"),
#            ("LibreOffice", "*.odt"),
#            ("RTF", "*.rtf")
#        ]
#    )

    idir = filedialog.askdirectory(parent=root)
    if idir:
        conjoindir(idir)

def get_zip():
    text.delete('1.0', tk.END)

    zfile = filedialog.askopenfilename(
        parent=root,
#            initialdir='/',
#            initialfile='tmp',
        filetypes=[("Zip-Dateien", ".zip*")]
    )
    if zfile:
        with TemporaryDirectory() as zdir:
            # Extract archive
            try:
                with zipfile.ZipFile(zfile, mode="r") as archive:
                    archive.extractall(zdir)
            except zipfile.BadZipFile as error:
                REPORT(f"FEHLER: {error}")
                return

            # Handle files not in a subfolder
            conjoindir(zdir, name=os.path.basename(zfile.rsplit(".", 1)[0]))

            # Handle subfolders
            for d in sorted(os.listdir(zdir)):
                sdir = os.path.join(zdir, d)
                if os.path.isdir(sdir):
                    conjoindir(sdir)

def conjoindir(idir, name=None):
    #print("???", idir)
    files = []
    for f in sorted(os.listdir(idir)):
        try:
            b, e = f.rsplit(".", 1)
        except ValueError:
            continue
        if e in ("odt", "docx", "rtf"):
            files.append(os.path.join(idir, f))

    if files:
        idir = os.path.dirname(files[0])
        with TemporaryDirectory() as odir:

            root.config(cursor="watch")
            text.config(cursor="watch") # Seems to be needed additionally!
            root.update_idletasks()

            libre_office(files, odir)
            root.config(cursor="")
            text.config(cursor="")
            pfiles = []
            REPORT("\n *******************************\n")
            for f in files:
                bpdf = os.path.basename(f).rsplit(".", 1)[0] + ".pdf"
                fpdf = os.path.join(odir, bpdf)
                if os.path.isfile(fpdf):
                    pfiles.append(fpdf)
                else:
                    REPORT(" *** FEHLER, Datei fehlt: {fpdf}")
            if len(files) == len(pfiles):
                sfile = filedialog.asksaveasfilename(
                    parent=root,
                    defaultextension=".pdf",
                    #initialdir=idir,
                    initialfile=(name or os.path.basename(idir)) + ".pdf",
                    filetypes=[("PDF", "*.pdf")]
                )
                if sfile:
                    if not sfile.endswith(".pdf"):
                        sfile += ".pdf"
                    merge_pdf(pfiles, sfile,
                        pad2sided=twosided.instate(['selected'])
                    )
                    REPORT(f" --> {sfile}")

def REPORT(line):
    text.insert(tk.END, line.rstrip() + "\n")
    root.update_idletasks()
    text.yview(tk.END)

if __name__ == "__main__":
    root = tk.Tk()
    try:
        root.tk.call('tk_getOpenFile', '-foobarbaz')
    except:
        pass
    try:
        #root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1')
        root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0')
    except:
        pass

    root.title("Conjoin2pdf")
    root.iconphoto(True, tk.PhotoImage(file=os.path.join(basedir, 'conjoin2pdf.png')))
    #root.geometry('300x300')
    bt = ttk.Button(
        root,
        text="Eingabe von Ordner (mit odt-, docx-, rtf-Dateien)",
        command=get_input
    )
    bt.pack(fill=tk.X, padx=3, pady=3)
    btz = ttk.Button(
        root,
        text="Eingabe von Zip-Datei",
        command=get_zip
    )
    btz.pack(fill=tk.X, padx=3, pady=3)
    twosided = ttk.Checkbutton(root, text="Doppelseitige Ausgabe")
    twosided.pack(fill=tk.X, padx=3, pady=3)
    #twosided.state(['!alternate', '!selected'])
    twosided.state(['!alternate', 'selected'])
    #print("?$?", twosided.state())
    #print("?$?", twosided.instate(['selected']))
    text = scrolledtext.ScrolledText(root)#, state=tk.DISABLED)
    text.bind("<Key>", lambda e: "break")
    text.pack()
    root.update()
    w, h = root.winfo_width(), root.winfo_height()
    #print(f"w={w}, h={h}")
    x = int(root.winfo_screenwidth()/2 - w/2)
    y = int(root.winfo_screenheight()/2 - h/2)
    #x, y = 200, 100
    root.geometry(f"+{x}+{y}")
    root.mainloop()


class Node:
    def __init__(self, node) -> None:
        self.node = node
        self.next = None

    def __str__(self) -> str:
        data = self
        output = ""

        while data:
            output += str(data.node) + " "
            data = data.next
        return output

class LinkedList:
    def __init__(self) -> None:
        self.head = None
        self.length = 0

    def append(self, element):
        node = Node(element)
        current = None
        if self.head == None:
            self.head = node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = node
        self.length += 1

    def removeAt(self, position):
        if position > -1 and position < self.length:
            current = self.head
            previous = current
            index = 1
            if position == 0:
                self.head = current.next

            else:
                while index <= position:
                    previous = current
                    current = current.next
                    index += 1
                previous.next = current.next

            self.length -= 1

linkedList = LinkedList()
linkedList.append(5)
linkedList.append(2)
print(linkedList.head)
linkedList.removeAt(1)
print(linkedList.head)


import math

from .vector_math import *

import numpy as np
from time import time
# from memory_profiler import profile

icosahedron_G = 0.5*(1.0+math.sqrt(5.0))
icosahedron_b = 1.0/math.sqrt(1.0+icosahedron_G*icosahedron_G)
icosahedron_a = icosahedron_b*icosahedron_G

icosahedron_corners = (
    (icosahedron_a,  -icosahedron_b,            0.0),
    (icosahedron_a,   icosahedron_b,            0.0),
    (-icosahedron_a,  icosahedron_b,            0.0),
    (-icosahedron_a, -icosahedron_b,            0.0),
    (           0.0,  icosahedron_a, -icosahedron_b),
    (           0.0,  icosahedron_a,  icosahedron_b),
    (           0.0, -icosahedron_a,  icosahedron_b),
    (           0.0, -icosahedron_a, -icosahedron_b),
    (-icosahedron_b,            0.0,  icosahedron_a),
    (icosahedron_b,            0.0,   icosahedron_a),
    (icosahedron_b,            0.0,  -icosahedron_a),
    (-icosahedron_b,            0.0, -icosahedron_a),
)

icosahedron_triangles = (
    (1,  0,  10),  # 1
    (0,  1,  9),   # 0
    (0,  9,  6),   # 12
    (9,  8,  6),   # 9
    (0,  7,  10),  # 16
    (6,  7,  0),   # 6
    (7,  6,  3),   # 7
    (6,  8,  3),   # 14
    (11, 10, 7),   # 11
    (7,  3,  11),  # 18
    (3,  2,  11),  # 3
    (2,  3,  8),   # 2
    (10, 11, 4),   # 10
    (2,  4,  11),  # 19
    (5,  4,  2),   # 5
    (2,  8,  5),   # 15
    (4,  1,  10),  # 17
    (4,  5,  1),   # 4
    (5,  9,  1),   # 13
    (8,  9,  5)    # 8
)

class SphericalCap:
    def __init__(self, view_dir, inner_view_cos, outer_view_cos):
        """
        Construct a SphericalCap from its direction and aperture.
        - view_dir a unit vector indicating the direction.
        - inner_view_cos cosinus of the aperture.
        - inner_view_cos cosinus of the aperture + max angular size of triangle in level
        """
        self._view_dir = view_dir
        self._inner_view_cos = inner_view_cos
        self._outer_view_cos = outer_view_cos

    def inside_inner(self, v):
        x = vector_dot(v, self._view_dir)
        return x >= self._inner_view_cos

    def inside_outer(self, c):
        x = vector_dot(c, self._view_dir)
        return x >= self._outer_view_cos

class GeodesicSearchResult:
    """ Result of grid search
    """
    def __init__(self, max_level):
        self.zone_lists = [None] * (max_level + 1)
        self.inside_indexes = [None] * (max_level + 1)
        self.border_indexes = [None] * (max_level + 1)
        self.max_level = max_level

        for i in range(max_level+1):
            n = GeodesicGrid.nr_of_zones(i)
            self.zone_lists[i] = [0] * n

        self.reset()

    def reset(self):
        for i in range(self.max_level+1):
            self.inside_indexes[i] = 0
            self.border_indexes[i] = GeodesicGrid.nr_of_zones(i)

    def add_inside_index(self, lev, index):
        self.zone_lists[lev][self.inside_indexes[lev]] = index
        self.inside_indexes[lev] += 1

    def add_border_index(self, lev, index):
        self.border_indexes[lev] -= 1
        self.zone_lists[lev][self.border_indexes[lev]] = index

class GeodesicSearchBorderIterator:
    """ Iterates over border triangles
    """
    def __init__(self, search_result, level):
        self._search_zones = search_result.zone_lists[level]
        self._index = search_result.border_indexes[level]

    def next(self):
        if self._index >= len(self._search_zones):
            return -1
        ret = self._search_zones[self._index]
        self._index += 1
        return ret

class GeodesicSearchInsideIterator:
    """ Iterates over inside triangles
    """
    def __init__(self, search_result, max_level):
        self._search_result = search_result
        self._level = 0
        self._max_level = max_level
        self._max_count = 1 << (max_level << 1)  # 4^maxLevel
        self._lev_zones = search_result.zone_lists[0]
        self._cur_index = 0
        self._end_index = search_result.inside_indexes[0]
        self._index = self._lev_zones[0] * self._max_count
        self._count = 0 if self._end_index > 0 else self._max_count

    def next(self):
        if self._count < self._max_count:
            ret = self._index + self._count
            self._count += 1
            return ret

        self._cur_index += 1

        if self._cur_index < self._end_index:
            self._index = self._lev_zones[self._cur_index] * self._max_count
            self._count = 1
            return self._index

        while self._level < self._max_level:
            self._level += 1
            self._max_count = self._max_count >> 2
            self._lev_zones = self._search_result.zone_lists[self._level]
            self._cur_index = 0
            self._end_index = self._search_result.inside_indexes[self._level]
            if self._end_index > 0:
                self._index = self._lev_zones[0] * self._max_count
                self._count = 1
                return self._index

        return -1

class GeodesicGrid:
    """
    GeodesicGrid: a library for dividing the sphere into triangle zones by subdividing the icosahedron
    Based on work of Johannes Gajdosik, 2006
    """
    @staticmethod
    def nr_of_zones(level):
        return 20 << (level << 1)

    # @profile
    def __init__(self, level):
        # tm = time()
        self.max_level = level
        if level >= 0:
            self._triangles = [None] * (level+1)
            self._triangle_centers = [None] * (level+1)
            nr_of_triangles = 20
            for i in range(level+1):
                self._triangles[i] = [None] * nr_of_triangles
                self._triangle_centers[i] = [None] * nr_of_triangles
                nr_of_triangles *= 4
            for i in range(20):
                corners = icosahedron_triangles[i]
                self._init_triangle(0, i, icosahedron_corners[corners[0]], icosahedron_corners[corners[1]], icosahedron_corners[corners[2]])
        else:
            self._triangles = None
        # print("#################### Geodesic grid within {} s".format(str(time()-tm)), flush=True)

    def to_np_arrays(self):
        for i in range(self.max_level+1):
            self._triangles[i] = np.array(self._triangles[i])
            self._triangle_centers[i] = np.array(self._triangle_centers[i])

    def get_triangle_corners(self, lev, index):
        h0, h1, h2 = None, None, None
        if lev <= 0:
            corners = icosahedron_triangles[index]
            h0 = icosahedron_corners[corners[0]]
            h1 = icosahedron_corners[corners[1]]
            h2 = icosahedron_corners[corners[2]]
        else:
            lev -= 1
            i = index >> 2
            t = self._triangles[lev][i]
            x = index & 3
            if x == 0:
                c0, c1, c2 = self.get_triangle_corners(lev, i)
                h0, h1, h2 = c0, t[2], t[1]
            elif x == 1:
                c0, c1, c2 = self.get_triangle_corners(lev, i)
                h0, h1, h2 = t[2], c1, t[0]
            elif x == 2:
                c0, c1, c2 = self.get_triangle_corners(lev, i)
                h0, h1, h2 = t[1], t[0], c2
            elif x == 3:
                h0, h1, h2 = t[0], t[1], t[2]
        return h0, h1, h2

    def get_partner_triangle(self, lev, index):
        if lev == 0:
            return index+1 if (index&1) == 1 else index-1

        x = index & 7
        if x == 2 or x == 6:
            return index+1
        if x == 3 or x == 7:
            return index-1
        if x == 0:
            return index+5 if lev == 1 else (self.get_partner_triangle(lev-1, index >> 2) << 2)+1
        if x == 1:
            return index+3 if lev == 1 else (self.get_partner_triangle(lev-1, index >> 2) << 2)+0
        if x == 4:
            return index-3 if lev == 1 else (self.get_partner_triangle(lev-1, index >> 2) << 2)+1
        if x == 5:
            return index-5 if lev == 1 else (self.get_partner_triangle(lev-1, index >> 2) << 2)+0
        return 0

    def _init_triangle(self, lev, index, c0, c1, c2, center=None):
        t = (vector_norm_add(c1, c2), vector_norm_add(c2, c0), vector_norm_add(c0, c1))
        self._triangles[lev][index] = t
        if center is None:
            center = vector_norm_add3(c0, c1, c2)
        self._triangle_centers[lev][index] = center
        lev += 1
        if lev <= self.max_level:
            index *= 4
            self._init_triangle(lev, index+0, c0, t[2], t[1])
            self._init_triangle(lev, index+1, t[2], c1, t[0])
            self._init_triangle(lev, index+2, t[1], t[0], c2)
            self._init_triangle(lev, index+3, t[0], t[1], t[2], center)

    def search_zones(self, lev_spherical_caps, search_result, max_search_level):
        if max_search_level < 0:
            max_search_level = 0
        elif max_search_level > self.max_level:
            max_search_level = self.max_level

        corner_in_inner = []

        for i in range(12):
            corner_in_inner.append(lev_spherical_caps[0].inside_inner(icosahedron_corners[i]))

        for i in range(20):
            if lev_spherical_caps[0].inside_outer(self._triangle_centers[0][i]):
                corners = icosahedron_triangles[i]
                self._search_zones(0, i, lev_spherical_caps,
                                   corner_in_inner[corners[0]], corner_in_inner[corners[1]], corner_in_inner[corners[2]],
                                   search_result, max_search_level)

    def _search_zones(self, lev, index, lev_spherical_caps,
                      corner0_in_inner, corner1_in_inner, corner2_in_inner,
                      search_result, max_search_level):

        if corner0_in_inner and corner1_in_inner and corner2_in_inner:
            search_result.add_inside_index(lev, index) # totally inside
            return True
        else:
            if lev >= max_search_level:
                search_result.add_border_index(lev, index)
                return True

            master_lev = lev
            master_index = index

            t = self._triangles[lev][index]
            lev += 1
            index <<= 2

            edge0_in_inner = lev_spherical_caps[lev].inside_inner(t[0])
            edge1_in_inner = lev_spherical_caps[lev].inside_inner(t[1])
            edge2_in_inner = lev_spherical_caps[lev].inside_inner(t[2])

            in1 = False
            in2 = False
            in3 = False
            in4 = False

            if lev_spherical_caps[lev].inside_outer(self._triangle_centers[lev][index+0]):
                in1 = self._search_zones(lev, index+0, lev_spherical_caps,
                                         corner0_in_inner, edge2_in_inner, edge1_in_inner,
                                         search_result, max_search_level)

            if lev_spherical_caps[lev].inside_outer(self._triangle_centers[lev][index+1]):
                in2 = self._search_zones(lev, index+1, lev_spherical_caps,
                                         edge2_in_inner, corner1_in_inner, edge0_in_inner,
                                         search_result, max_search_level)

            if lev_spherical_caps[lev].inside_outer(self._triangle_centers[lev][index+2]):
                in3 = self._search_zones(lev, index+2, lev_spherical_caps,
                                         edge1_in_inner, edge0_in_inner, corner2_in_inner,
                                         search_result, max_search_level)

            if lev_spherical_caps[lev].inside_outer(self._triangle_centers[lev][index+3]):
                in4 = self._search_zones(lev, index+3, lev_spherical_caps,
                                         edge0_in_inner, edge1_in_inner, edge2_in_inner,
                                         search_result, max_search_level)

            if in1 or in2 or in3 or in4:
                search_result.add_border_index(master_lev, master_index)
                return True
            return False

    def visit_triangles(self, max_visit_level, visit_func):
        if visit_func and max_visit_level >= 0:
            if max_visit_level > self.max_level:
                max_visit_level = self.max_level
            for i in range(20):
                corners = icosahedron_triangles[i]
                self._visit_triangles(0, i,
                                      icosahedron_corners[corners[0]],
                                      icosahedron_corners[corners[1]],
                                      icosahedron_corners[corners[2]],
                                      max_visit_level, visit_func)

    def _visit_triangles(self, lev, index, c0, c1, c2, max_visit_level, func):
        func(lev, index, c0, c1, c2)
        lev += 1
        if lev <= max_visit_level:
            t = self._triangles[lev-1][index]
            index *= 4
            self._visit_triangles(lev, index+0, c0, t[2], t[1], max_visit_level, func)
            self._visit_triangles(lev, index+1, t[2], c1, t[0], max_visit_level, func)
            self._visit_triangles(lev, index+2, t[1], t[0], c2, max_visit_level, func)
            self._visit_triangles(lev, index+3, t[0], t[1], t[2], max_visit_level, func)


"""
Plain Python definition of the builtin functions oriented towards
functional programming.
"""
import operator
from __pypy__ import resizelist_hint, newlist_hint
from __pypy__ import specialized_zip_2_lists

# ____________________________________________________________

def apply(function, args=(), kwds={}):
    """call a function (or other callable object) and return its result"""
    return function(*args, **kwds)

# ____________________________________________________________

def sorted(iterable, cmp=None, key=None, reverse=False):
    "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list"
    sorted_lst = list(iterable)
    sorted_lst.sort(cmp, key, reverse)
    return sorted_lst

def any(seq):
    """any(iterable) -> bool

Return True if bool(x) is True for any x in the iterable."""
    for x in seq:
        if x:
            return True
    return False

def all(seq):
    """all(iterable) -> bool

Return True if bool(x) is True for all values x in the iterable."""
    for x in seq:
        if not x:
            return False
    return True

def sum(sequence, start=0):
    """sum(sequence[, start]) -> value

Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).  When the sequence is
empty, returns start."""
    if isinstance(start, basestring):
        raise TypeError("sum() can't sum strings")

    # Avoiding isinstance here, since subclasses can override `+`
    if type(start) is list:
        return _list_sum(sequence, start)

    if type(start) is tuple:
        return _tuple_sum(sequence, start)

    return _regular_sum(sequence, start)

def _regular_sum(sequence, start):
    # Default implementation for sum (no specialization)
    last = start
    for x in sequence:
        # Very intentionally *not* +=, that would have different semantics if
        # start was a mutable type, such as a list
        last = last + x
    return last

def _list_sum(sequence, start):
    # Specialization avoiding quadratic complexity for lists
    iterator = iter(sequence)

    try:
        first = next(iterator)
    except StopIteration:
        return start

    if type(first) is not list:
        return _regular_sum(iterator, start + first)

    last = start + first
    for item in iterator:
        if type(item) is list:
            last += item
        else:
            # Non-trivial sum. Use _regular_sum.
            return _regular_sum(iterator, last + item)

    return last

def _tuple_sum(sequence, start):
    # Specialization avoiding quadratic complexity for tuples
    iterator = iter(sequence)

    try:
        first = next(iterator)
    except StopIteration:
        return start

    if type(first) is not tuple:
        return _regular_sum(iterator, start + first)

    last = list(start)
    last.extend(first)
    for item in iterator:
        if type(item) is tuple:
            last.extend(item)
        else:
            # Non-trivial sum. Cast back to tuple and use regular_sum.
            return _regular_sum(iterator, tuple(last) + item)

    return tuple(last)

class _Cons(object):
    def __init__(self, prev, iter):
        self.prev = prev
        self.iter = iter

    def fetch(self):
        # recursive, loop-less version of the algorithm: works best for a
        # fixed number of "collections" in the call to map(func, *collections)
        prev = self.prev
        if prev is None:
            args1 = ()
            stop = True
        else:
            args1, stop = prev.fetch()
        iter = self.iter
        if iter is None:
            val = None
        else:
            try:
                val = next(iter)
                stop = False
            except StopIteration:
                self.iter = None
                val = None
        return args1 + (val,), stop

def map(func, *collections):
    """map(function, sequence[, sequence, ...]) -> list

Return a list of the results of applying the function to the items of
the argument sequence(s).  If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length.  If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence)."""
    if not collections:
        raise TypeError("map() requires at least two arguments")
    num_collections = len(collections)
    none_func = func is None
    if num_collections == 1:
        if none_func:
            return list(collections[0])
        # Special case for the really common case of a single collection
        seq = collections[0]
        with _ManagedNewlistHint(operator._length_hint(seq, 0)) as result:
            for item in seq:
                result.append(func(item))
            return result

    # Gather the iterators into _Cons objects and guess the
    # result length (the max of the input lengths)
    c = None
    max_hint = 0
    for seq in collections:
        c = _Cons(c, iter(seq))
        max_hint = max(max_hint, operator._length_hint(seq, 0))

    with _ManagedNewlistHint(max_hint) as result:
        while True:
            args, stop = c.fetch()
            if stop:
                return result
            if none_func:
                result.append(args)
            else:
                result.append(func(*args))

class _ManagedNewlistHint(object):
    """ Context manager returning a newlist_hint upon entry.

    Upon exit the list's underlying capacity will be cut back to match
    its length if necessary (incase the initial length_hint was too
    large).
    """

    def __init__(self, length_hint):
        self.length_hint = length_hint
        self.list = newlist_hint(length_hint)

    def __enter__(self):
        return self.list

    def __exit__(self, type, value, tb):
        if type is None:
            extended = len(self.list)
            if extended < self.length_hint:
                resizelist_hint(self.list, extended)

sentinel = object()

def reduce(func, sequence, initial=sentinel):
    """reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty."""
    iterator = iter(sequence)
    if initial is sentinel:
        try:
            initial = next(iterator)
        except StopIteration:
            raise TypeError("reduce() of empty sequence with no initial value")
    result = initial
    for item in iterator:
        result = func(result, item)
    return result

def filter(func, seq):
    """filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true.  If
function is None, return the items that are true.  If sequence is a tuple
or string, return the same type, else return a list."""
    if func is None:
        func = bool
    if isinstance(seq, str):
        return _filter_string(func, seq, str)
    elif isinstance(seq, unicode):
        return _filter_string(func, seq, unicode)
    elif isinstance(seq, tuple):
        return _filter_tuple(func, seq)
    with _ManagedNewlistHint(operator._length_hint(seq, 0)) as result:
        for item in seq:
            if func(item):
                result.append(item)
    return result

def _filter_string(func, string, str_type):
    if func is bool and type(string) is str_type:
        return string
    length = len(string)
    result = newlist_hint(length)
    for i in range(length):
        # You must call __getitem__ on the strings, simply iterating doesn't
        # work :/
        item = string[i]
        if func(item):
            if not isinstance(item, str_type):
                raise TypeError("__getitem__ returned a non-string type")
            result.append(item)
    return str_type().join(result)

def _filter_tuple(func, seq):
    length = len(seq)
    result = newlist_hint(length)
    for i in range(length):
        # Again, must call __getitem__, at least there are tests.
        item = seq[i]
        if func(item):
            result.append(item)
    return tuple(result)

def zip(*sequences):
    """zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences.  The returned list is truncated
in length to the length of the shortest argument sequence."""
    l = len(sequences)
    if l == 2:
        # A very fast path if the two sequences are lists
        seq0 = sequences[0]
        seq1 = sequences[1]
        try:
            return specialized_zip_2_lists(seq0, seq1)
        except TypeError:
            pass
        # This is functionally the same as the code below, but more
        # efficient because it unrolls the loops over 'sequences'.
        # Only for two arguments, which is the most common case.
        iter0 = iter(seq0)
        iter1 = iter(seq1)
        hint = min(100000000,   # max 100M
                   operator._length_hint(seq0, 0),
                   operator._length_hint(seq1, 0))

        with _ManagedNewlistHint(hint) as result:
            while True:
                try:
                    item0 = next(iter0)
                    item1 = next(iter1)
                except StopIteration:
                    return result
                result.append((item0, item1))

    if l == 0:
        return []

    # Gather the iterators and guess the result length (the min of the
    # input lengths).  If any of the iterators doesn't know its length,
    # we use 0 (instead of ignoring it and using the other iterators;
    # see lib-python's test_builtin.test_zip).
    iterators = []
    hint = 100000000   # max 100M
    for seq in sequences:
        iterators.append(iter(seq))
        hint = min(hint, operator._length_hint(seq, 0))

    with _ManagedNewlistHint(hint) as result:
        while True:
            try:
                items = [next(it) for it in iterators]
            except StopIteration:
                return result
            result.append(tuple(items))


"""
What is a loop?
A loop is a sequence of statements that is repeated until a certain condition is met.
An example is a loop that prints out the numbers from 1 to 10.
"""

#  There are two types of loops in Python:
#  1. For loops
#  2. While loops

#  1. For loops
"""
A for loop is used to iterate over a sequence (e.g. a list) and execute
a block of code for each element.
"""

#  Syntax
"""
for <variable> in <iterable>:
    <code to execute>
"""

#  Example

students = ["John", "Paul", "George", "Ringo"]

for s in students:
    print('This student is named '+s)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum = 0
for n in numbers:
    sum+=n
print(sum)

# Exercise
"""
1) Using for loop, write a program that prints out your name in this format:
    N
    a
    m
    e
2) Using for loop, write a program that prints out the positive numbers from
    this list [1, -2, 3, -4, 5, -6, 7, -8, 9, -10]
"""

# Assignment

"""
Write a program that simulates a dictionary, a user can search for
a word and the program will return what the word means. If the word does not
exist in the program then it will return "Word not found". The program should
be case insensitive. The program should allow users to search for words 10 times only.
"""

dictionary = {
    "name": "An identity given to a person or thing",
    "orange": "A round mostly orange colored fruit",
    "elephant": "A giant animal mostly found in the forest",
    "cake": "A pastry made with flour, butter and sugar",
    "computer": "A machine that aids in calculation"
}

for d in dictionary:
    word = input("Search for a word: ")
    word = word.lower().strip()
    if dictionary.get(word):
        print(dictionary.get(word))
    else:
        print("Word not found")


#!/usr/bin/env python3
from sys import exit

from multilanguage import Env, Lang, TALcolors
from TALinputs import TALinput

import pirellone_lib as pl

# METADATA OF THIS TAL_SERVICE:
args_list = [
    ('coding',str),
]

ENV =Env(args_list)
TAc =TALcolors(ENV)
LANG=Lang(ENV, TAc, lambda fstring: eval(f"f'{fstring}'"))

# START CODING YOUR SERVICE:
TAc.print(LANG.render_feedback("insert-num-rows", 'Insert the number of rows:'), "yellow", ["bold"])
m=TALinput(int, 1, TAc=TAc)[0]
TAc.print(LANG.render_feedback("insert-num-col", 'Insert the number of columns:'), "yellow", ["bold"])
n=TALinput(int, 1, TAc=TAc)[0]

if ENV['seed']=='random_seed':
    pirellone, seed=pl.random_pirellone(m, n, seed="random_seed", solvable=True)
else:
    pirellone, seed=pl.random_pirellone(m, n, ENV['seed'], solvable=True)

TAc.print(LANG.render_feedback("instance-seed",f"Instance (of seed {seed}): "), "yellow", ["bold"])
pl.print_pirellone(pirellone)

if ENV['coding']=='seq':
    TAc.print(LANG.render_feedback("sequence-r-c","Sequence of rows and columms: "), "yellow", ["bold"])
    solu=TALinput(str, sep=" ",  regex="^((r|c)[0-9]{0,9})+$", TAc=TAc, LANG=LANG)
elif ENV['coding']=='subset':
    TAc.print(LANG.render_feedback("rows-sol","Rows solution: "), "yellow", ["bold"])
    rs = TALinput(int, num_tokens=m)
    TAc.print(LANG.render_feedback("col-sol","Columns solution: "), "yellow", ["bold"])
    cs = TALinput(int, num_tokens=n)
    solu=[]
    for i in range(len(rs)):
        if rs[i]:
            solu.append(f'r{i+1}')
    for j in range(len(cs)):
        if cs[j]:
            solu.append(f'c{j+1}')

b,solvable=pl.check_off_lights(pirellone,solu,LANG, TAc)
if b and solvable=='s':
    TAc.OK()
    TAc.print(LANG.render_feedback('correct',"This sequence turns off all lights."), "green", ["bold"])
if b==False and solvable=='s':
    TAc.NO()
    TAc.print(LANG.render_feedback('not-correct',"This sequence doesn't turn off all lights see what happens using your solution:"), "red", ["bold"])
    pl.print_pirellone(pirellone)

if b and solvable=='n':
    TAc.OK()
    TAc.print(LANG.render_feedback('no-more-lights',"You can not turn off more lights."), "green", ["bold"])
if b==False and solvable=='n':
    TAc.NO()
    TAc.print(LANG.render_feedback('do-better',"You can turn off more lights, check it: "), "red", ["bold"])
    pl.print_pirellone(pirellone)

exit(0)


#!/usr/bin/env python3

from sys import stdin, stdout, exit

from hades import db
from hades.models.event import Events

def send_help():
    print('Enter to continue, d to delete, e to edit, h for help, Ctrl C/D to exit')

tables = db.engine.table_names()
for i in range(len(tables)):
    table = tables[i]
    current_event = db.session.query(Events).get(table)
    if current_event is None:
        print('Please run `db_setup.py` prior to using this!')
        exit(1)
    else:
        print(f'{i + 1}. {current_event.name} - {current_event.full_name}')

try:
    while True:
        ch = int(
            input(
                'Enter the number of the table you wish to interact with, enter/Ctrl C/D to exit\ntable: '
            )
        )
        table = tables[ch - 1]
        send_help()
        current_event = db.session.query(Events).get(table)
        stdout.write(f'{table} -> ')
        stdout.flush()
        ch = stdin.read(1)
        if ch == 'h':
            send_help()
        elif ch == 'd':
            db.session.delete(current_event)
            db.session.commit()
            print(f'Deleted {table}')
        elif ch == 'e':
            current_event.full_name = input(f'Enter full name for table {table}: ')
            db.session.commit()
            print(f'Updated {table} full name to {current_event.full_name}')
except EOFError:
    print('Exiting!')
except KeyboardInterrupt:
    print('Exiting!')
except IndexError:
    print('No such table, exiting!')
except ValueError:
    print('Exiting!')


import time
import pyautogui as pg
import userlist
import pyperclip

def log():
    while True:
        time.sleep(1)
        print(pg.position())

def goto_tribe_room():
    pg.moveTo(1075,820, 1)
    pg.click()
    pg.moveTo(1680, 600, 1)
    pg.click()
    time.sleep(3)

def execute_lua(luadata):
    pg.press("Enter")
    pg.write("/lua")
    pyperclip.copy(luadata)
    pg.press("Enter")
    pg.moveTo(1425,430)
    pg.click()
    time.sleep(0.2)
    pg.hotkey("ctrl", "a")
    pg.press("backspace")
    pg.hotkey("ctrl", "v")
    pg.moveTo(1440, 580)
    pg.click()
    pg.moveTo(1290,820)
    pg.click()
    pg.write("/room 1")
    pg.press("Enter")

def inviter(luadata):
    goto_tribe_room()
    with open('userlist.txt', 'r') as f:
        arr = [line.strip() for line in f]

    for i in arr:
        pyperclip.copy(i)
        pg.press('enter')
        pg.write("/inv ")
        pg.hotkey("ctrl", "v")
        time.sleep(1)
        pg.press("Enter")

    execute_lua(luadata)

def change_room(room_list):
    arr = []
    for i in room_list:
        pg.press("Enter")
        pg.write("/room " + i)
        time.sleep(1)
        pg.press("Enter")
        time.sleep(3)
        arr = arr + ulist()
        pg.press("Enter")
    print(set(arr), len(arr))
    return set(arr)

def silence():
    pg.press("Enter")
    pg.write("/silence Incorrect version, try to reload the game.")
    pg.press("Enter")
    time.sleep(2)

def ulist():
    arr = userlist.getUserlist()
    #print(arr, len(arr))
    return arr

def get_data():
    room_list = ["vanilla2", "vanilla1", "1", "5", "survivor787", "survivor esek", "survivor", "racing1", "racing96846468"]
    arr = change_room(room_list)
    with open('userlist.txt', 'w') as f:
        for i in arr:
            f.write(f"{i}\n")

def clear_userlist():
    with open("userlist.txt", "w") as f:
        f.write("")
        f.close()

def main(luadata):

    #log()
    silence()
    get_data()
    inviter(luadata=luadata)
    #clear_userlist()

if __name__ == '__main__':
    luadata = """data = 3
function eventLoop (datA)
    if data == 0 then
        for i = 0, 9999
        do
            tfm.exec.addShamanObject(4,-100,-200,0,0,0,false)
        end
    else
        print(data)
        data = data - 1
    end
end
--Incorrect version, try to reload the game."""
    main(luadata=luadata)


from aws_cdk import (
    aws_rds as rds,
    aws_ec2 as ec2,
    aws_kms as kms,
    core
)

class RDSStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, vpc,sg,redissg, kmskey, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        rdskey = kms.Key.from_key_arn(self,"rdskey",
            key_arn=kmskey
        )

        db_mysql = rds.DatabaseCluster(self,"Dev_MySQL",
            default_database_name="msadev",
            engine=rds.DatabaseClusterEngine.AURORA_MYSQL,
            engine_version="5.7.12",
            master_user=rds.Login(username="admin"),
            instance_props=rds.InstanceProps(
                vpc=vpc,
                vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.ISOLATED),
                instance_type=ec2.InstanceType(instance_type_identifier="t3.medium")
            ),
            instances=1,
            parameter_group=rds.ClusterParameterGroup.from_parameter_group_name(
                self,"paramter-group-msadev",
                parameter_group_name="default.aurora-mysql5.7"
            ),
            kms_key=rdskey

        )
        sgId = ec2.SecurityGroup.from_security_group_id(self,"sgid",sg)
        redis_sg=ec2.SecurityGroup.from_security_group_id(self,"redissgid",redissg)

        db_mysql.connections.allow_default_port_from(sgId,"Access from Bastion")
        db_mysql.connections.allow_default_port_from(redis_sg,"Access from Redis")


import asyncio
import contextlib
from contextlib import closing
from unittest import mock

import pytest

from server import ServerContext
from server.core import Service
from server.lobbyconnection import LobbyConnection
from server.protocol import DisconnectedError, QDataStreamProtocol
from tests.utils import exhaust_callbacks, fast_forward

class MockConnection:
    def __init__(self):
        self.protocol = None
        self.peername = None
        self.user_agent = None
        self.version = None
        self.on_connection_lost = mock.AsyncMock()

    async def on_connection_made(self, protocol, peername):
        self.protocol = protocol
        self.peername = peername
        self.protocol.writer.write_eof()
        self.protocol.reader.feed_eof()

    async def on_message_received(self, msg):
        pass

@pytest.fixture
def mock_connection():
    return MockConnection()

@pytest.fixture
def mock_service():
    return mock.create_autospec(Service)

@pytest.fixture
async def mock_context(mock_connection, mock_service):
    ctx = ServerContext("TestServer", lambda: mock_connection, [mock_service])
    yield await ctx.listen("127.0.0.1", None), ctx
    await ctx.stop()
    await ctx.shutdown()

@pytest.fixture
async def context(mock_service):
    def make_connection() -> LobbyConnection:
        return LobbyConnection(
            database=mock.Mock(),
            game_service=mock.Mock(),
            players=mock.Mock(),
            nts_client=mock.Mock(),
            geoip=mock.Mock(),
            ladder_service=mock.Mock(),
            party_service=mock.Mock(),
            rating_service=mock.Mock(),
            oauth_service=mock.Mock(),
        )

    ctx = ServerContext("TestServer", make_connection, [mock_service])
    yield await ctx.listen("127.0.0.1", None), ctx
    await ctx.stop()
    await ctx.shutdown()

async def test_serverside_abort(
    event_loop,
    mock_context,
    mock_connection,
    mock_service
):
    srv, ctx = mock_context
    reader, writer = await asyncio.open_connection(*srv.sockets[0].getsockname())
    with closing(writer):
        proto = QDataStreamProtocol(reader, writer)
        await proto.send_message({"some_junk": True})
        await exhaust_callbacks(event_loop)

        mock_connection.on_connection_lost.assert_any_call()
        mock_service.on_connection_lost.assert_called_once()

async def test_connection_broken_external(context):
    """
    When the connection breaks while the server is calling protocol.send from
    somewhere other than the main read - response loop. Make sure that this
    still triggers the proper connection cleanup.
    """
    srv, ctx = context
    _, writer = await asyncio.open_connection(*srv.sockets[0].getsockname())
    writer.close()
    # Need this sleep for test to work, otherwise closed protocol isn't detected
    await asyncio.sleep(0)

    proto = next(iter(ctx.connections.values()))
    proto.writer.transport.set_write_buffer_limits(high=0)

    # Might raise DisconnectedError depending on OS
    with contextlib.suppress(DisconnectedError):
        await proto.send_message({"command": "Some long message" * 4096})

    await asyncio.sleep(0.1)
    assert len(ctx.connections) == 0

async def test_unexpected_exception(event_loop, context, caplog, mocker):
    srv, ctx = context

    mocker.patch.object(
        ctx.protocol_class,
        "read_message",
        mock.AsyncMock(
            side_effect=RuntimeError("test")
        )
    )

    with caplog.at_level("TRACE"):
        _, writer = await asyncio.open_connection(*srv.sockets[0].getsockname())

    with closing(writer):
        assert "Exception in protocol" in caplog.text

async def test_unexpected_exception_in_connection_lost(context, caplog):
    srv, ctx = context

    ctx._services[0].on_connection_lost = mock.Mock(
        side_effect=RuntimeError("test"),
        __name__="on_connection_lost"
    )

    with caplog.at_level("TRACE"):
        _, writer = await asyncio.open_connection(*srv.sockets[0].getsockname())
        writer.close()
        await asyncio.sleep(0.1)

    assert "Unexpected exception in on_connection_lost" in caplog.text

@fast_forward(20)
async def test_drain_connections(context):
    srv, ctx = context
    _, writer = await asyncio.open_connection(*srv.sockets[0].getsockname())

    with pytest.raises(asyncio.TimeoutError):
        await asyncio.wait_for(
            ctx.drain_connections(),
            timeout=10
        )

    writer.close()

    await asyncio.wait_for(
        ctx.drain_connections(),
        timeout=3
    )


# app.py
from flask import Flask, render_template
from urls import get_urls

app = Flask(__name__)

@app.route('/')
def index():
    urls = get_urls()
    return render_template('index.html', urls=urls)

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


#!/usr/bin/env python3

import numpy
import opt_analy
import matplotlib
import matplotlib.pyplot as plt

def plot(az_list, el_list, dx_list, dy_list, file_list, raw=True):

    if raw == True:
        dx_avg, dy_avg, dx_std, dy_std, *_ = opt_analy.process_static(file_list, clip_sigma=(3.,3.))
    else:
        az = [e for inner_list in az_list for e in inner_list]
        el = [e for inner_list in el_list for e in inner_list]
        dx = [e for inner_list in dx_list for e in inner_list]
        dy = [e for inner_list in dy_list for e in inner_list]
        dx_avg, dy_avg, dx_std, dy_std = numpy.average(dx), numpy.average(dy), numpy.std(dx), numpy.std(dy)

    nrow = 3
    ncol = 2
    nax = ncol * nrow
    figsize = (ncol * 4, nrow * 4)

    fig = plt.figure(figsize=figsize)
    fig.subplots_adjust(wspace=0.4, hspace=0.4)
    ax = [fig.add_subplot(nrow, ncol, i+1) for i in range(nax-1)]

    matplotlib.rcParams['savefig.dpi'] = 200
    matplotlib.rcParams['font.size'] = 14

    for az, el, dx, dy in zip(az_list, el_list, dx_list, dy_list):
        ax[0].plot(az, dx, '.', label='diff')
        ax[1].plot(el, dx, '.', label='diff')
        ax[2].plot(az, dy, '.', label='diff')
        ax[3].plot(el, dy, '.', label='diff')
        ax[4].plot(dx, dy, '.', label='diff')

    ax[0].set_xlabel('Az [deg.]')
    ax[0].set_ylabel('dx [arcsec.]')
    ax[0].set_title('Az vs dx')

    ax[1].set_xlabel('El [deg.]')
    ax[1].set_ylabel('dx [arcsec.]')
    ax[1].set_title('El vs dx')

    ax[2].set_xlabel('Az [deg.]')
    ax[2].set_ylabel('dy [arcsec.]')
    ax[2].set_title('Az vs dy')

    ax[3].set_xlabel('El [deg.]')
    ax[3].set_ylabel('dy [arcsec.]')
    ax[3].set_title('El vs dy')

    ax[4].set_xlabel('dx [arcsec.]')
    ax[4].set_ylabel('dy [arcsec.]')
    ax[4].set_title('dx vs dy')

    [_ax.grid() for _ax in ax]

    if len(file_list) < 8:
        tbl_loc = 'lower center'
        legend_loc = (1.1, 0.35)
    else:
        tbl_loc = 'bottom'
        legend_loc = (1.1, 0.02)

    tbl = fig.add_subplot(3,2,6)
    col_labels=['average','std dev',]
    row_labels=[' dx ',' dy ', ' unite ']
    tbl_vals=[["{:.2e}".format(dx_avg), "{:.2f}".format(dx_std)],
              ["{:.2e}".format(dy_avg), "{:.2f}".format(dy_std)],
              ["{:.2e}".format(numpy.sqrt(dx_avg**2+dy_avg**2)), "{:.2e}".format(numpy.sqrt(dx_std**2+dy_std**2))]
    ]

    tbl.table(cellText=tbl_vals, rowLabels=row_labels, colLabels=col_labels, loc=tbl_loc)

    tbl.set_axis_off()
    fig.tight_layout()
    ax[4].legend(labels=file_list, loc=legend_loc)

    plt.show()


#Trim a Peptide Leaderboard
AminoAcid = ['G','A','S','P','V','T','C','I','L','N','D','K','Q','E','M','H','F','R','Y','W']
AminoAcidMass = [57,71,87,97,99,101,103,113, 113,114,115,128, 128,129, 131,137,147,156,163,186]
def LinearSpectrum(peptide):
        prefixMass  = [0]*len(peptide)
        for i in range(len(peptide)):
            for j in range(20):
                if AminoAcid[j] == peptide[i]:
                    prefixMass[i] = prefixMass[i-1] + AminoAcidMass[j]
        LinearSpectrum = []
        LinearSpectrum.append(0)
        for i in range(len(peptide)):
            for j in range(i+1,len(peptide)):
                LinearSpectrum.append(prefixMass[j]-prefixMass[i])
        for element in prefixMass:
            LinearSpectrum.append(element)
        return sorted(LinearSpectrum)
def LinearScore (t_spectrum, spectrum):
    score = 0
    mass = list(set(spectrum+t_spectrum))
    for m in mass:
        score += min(t_spectrum.count(m),spectrum.count(m))

    return score
def TRIM(Leaderboard, Spectrum, N):
    LinearScores = []
    res = []
    for j in range (len(Leaderboard)):
        peptide = Leaderboard[j]
        theoreticalSpectrum = LinearSpectrum(peptide)
        LinearScores.append(LinearScore(theoreticalSpectrum, Spectrum))
    for i in range (N):
        # move top N scores to result
        index = LinearScores.index(max(LinearScores))
        maxScore = LinearScores[index]
        res.append(Leaderboard[index])
        Leaderboard.pop(index)
        LinearScores.pop(index)
        while maxScore in LinearScores:
            index = LinearScores.index(max(LinearScores))
            res.append(Leaderboard[index])
            Leaderboard.pop(index)
            LinearScores.pop(index)

    return res
if __name__ == "__main__":
    input = "".join(open('input.txt')).split()
    # read input
    Leaderboard = []
    Spectrum = []
    N = 0
    for i in range(len(input)):

        if input[i].isdigit():
            Spectrum.append(int(input[i]))
        else:
            Leaderboard.append(input[i])
    N = Spectrum[-1]
    Spectrum = Spectrum[:-1]

    res = TRIM (Leaderboard, Spectrum, N)

    print(*res)


# the simplest solution - simply run this script at startup
# - output will go to console and alert if there is a diff
# For first run will compare with specified html file
# 	or create new one if nonexistant
import time
import urllib.request as ur
import sys, getopt
import os.path
from datetime import datetime
import difflib
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import logging

##   If you are going to recommit this file with your own information, look for no-comit hooks
   # These hooks will filter sensitive information on my machine, but will not do so on your machine

# logging setup
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='tmp.log',
                    filemode='w')

### default params, can be passed as flags to change
secondsToSleep = 3600 # 3600s = 1hr
numberOfRuns = -1 #-1 is infinite
urlToCheck = "www.Google.com" #no-commit
fileToWrite = "sourceOfLastRun.html" # file with last source of site
verbose = True # if True, print
log = True # if True, write to log

# email parameters
sendEmailFlag = True
emailDest = ["www.Google.com"]  #no-commit, make a list if multiple recipients
emailType = 'html' # can also be html.  Other values will break!
#############

### Values to be set by modifying this file only, not thru command line
emailSrc = emailDest[0] # change here if dest is different than from
emailSrcPass = "www.Google.com"  #no-commit this password generated from https://support.google.com/accounts/answer/185833
									# refer to README.md for more details
#############

def checkUrl():
	with ur.urlopen(urlToCheck) as openedUrl:
		fetchedHtml = str(openedUrl.read().decode('utf-8'))

	if (os.path.isfile(fileToWrite)):
		currentFileHtml = open(fileToWrite).read()
		if (currentFileHtml == fetchedHtml):
			writeLine("same at " + createTimeStamp())
		else:
			writeFileBack(fetchedHtml)
			writeLine("diff at " + createTimeStamp())
			diff = getDiffString(currentFileHtml, fetchedHtml)
			emailDiff(diff)

	else:
		writeFileBack(fetchedHtml, True)
		checkUrl()

# feel free to modify this function as needed to 'prettify' your email bodies
def emailDiff(diff):
	if (sendEmailFlag):
		server = smtplib.SMTP('smtp.gmail.com', 587)
		server.starttls()
		server.login(emailSrc, emailSrcPass)

		msg = createMIMEMsg(diff)

		server.sendmail(emailSrc, emailDest, msg.as_string())
		server.quit()

def createMIMEMsg(txt):
	msg = MIMEMultipart('alternative')
	msg['Subject'] = 'Latest diff of webpage "www.Google.com"' #no-commit
	msg['To'] = emailDest[0]

	txt += "\n\n\n\n\n\nURL of webpage: " + urlToCheck
	html =  MIMEText(txt, emailType)

	msg.attach(html)
	return msg

def writeFileBack(src, created = False,):
	with open(fileToWrite, 'w') as f:
		f.write(src)
	if (created):
		action = 'created'
	else:
		action = 'overwritten'

	writeLine("		File " + action + " at " + createTimeStamp())

def getDiffString(orig, new):
	diff = list(difflib.context_diff(orig.splitlines(), new.splitlines()))
	diff = [line[1:] for line in diff if line[0] == '!'] # the '!' corresponds with difflib for diff presentation
	return '\n'.join(list(diff))

# prints a simple time stamp for readibility
def createTimeStamp():
	now = datetime.now()
	return now.strftime("%b %d, %Y at %I:%M.%S %p")

def writeLine(s):
	if verbose:
		print(s)
	if log:
		logging.info(s)

if __name__ == "__main__":
	opts, args = getopt.getopt(sys.argv[1:],"hs:r:",["seconds=", "runs="])

	for opt, arg in opts:
		if opt == '-h':
			print('python checkURLNoTask.py -s <seconds>')
			sys.exit()
		elif opt in ("-s", "--seconds"):
			secondsToSleep = int(arg)
		elif opt in ("-r", "--runs"):
			numberOfRuns = int(arg)

	line = "checking url: " + urlToCheck + " every " + str(secondsToSleep) + " seconds " + str(numberOfRuns) + " times with email sending: " + str(sendEmailFlag)
	writeLine(line)

	runCount = 0
	while runCount != numberOfRuns:
		checkUrl()
		runCount+=1
		time.sleep(secondsToSleep)

	writeLine("Checked URL " + str(numberOfRuns) + ", ending script")


class Complex:
    def __init__(self, a, b):
        """
        :param a: real part of a complex number
        :param b: imaginary part of a complex number
        """
        if not isinstance(a, int):
            raise ValueError("a must be an integer")
        if not isinstance(b, int):
            raise ValueError("b must be an integer")
        self.__complex_a = a
        self.__complex_b = b

    @property
    def get_a(self):
        return self.__complex_a

    @property
    def get_b(self):
        return self.__complex_b

    def set_a(self, a):
        if not isinstance(a, int):
            raise ValueError("a must be an integer")
        self.__complex_a = a

    def set_b(self, b):
        if not isinstance(b, int):
            raise ValueError("b must be an integer")
        self.__complex_b = b

    def __str__(self):
        if self.get_b == 0:
            return str(self.get_a)
        elif self.get_a == 0:
            if self.get_b == 1:
                return 'i'
            elif self.get_b == -1:
                return '-i'
            else:
                return str(self.get_b) + 'i'
        elif self.get_b < 0:
            if self.get_b != - 1:
                return str(self.get_a) + str(self.get_b) + 'i'
            else:
                return str(self.get_a) + '-i'
        else:
            if self.get_b != 1:
                return str(self.get_a) + '+' + str(self.get_b) + 'i'
            else:
                return str(self.get_a) + '+i'


import re
from dataclasses import dataclass
from pprint import pprint

import pygame
import pyscroll
import pytmx
from random import randint, seed

from src import player
from src.player import NPC, Player
from lib_dijkstra import Point

verbose = False
# seed(1)

def groups_in_list(lst, code='X', blank=' '):
    """Find a list of continuous signs. This is used to try to reduce memory usage.
    >>> groups_in_list ((' ', ' ', 'X', 'X', 'X', 'X', 'X', ' ', 'X', 'X', ' '))
    [(2, 6), (8, 9)]
    >>> groups_in_list ((' ', ' ', 'X', 'X', 'X', 'X', 'X', ' ', 'X', 'X'))
    [(2, 6), (8, 9)]
    """
    walls = []
    again = True
    current = 0
    while again:
        try:
            first = lst.index(code, current)
        except ValueError:
            break

        try:
            last = lst.index(blank, first + 1)
        except ValueError:
            last = len(lst)

        if last:
            walls.append((first, last - 1))
            current = last
        else:
            again = False
    return walls

@dataclass
class Portal:
    from_world: str
    origin_point: str
    target_world: str
    teleport_point: str

# Vient de https://coderslegacy.com/pygame-platformer-coins-and-images/
class Coin(pygame.sprite.Sprite):
    # Intentionally, there are more 1 point coins than 50 points coins.
    values = (1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 5, 5, 5, 10, 10, 20, 50)

    def __init__(self, pos):
        super().__init__()
        self.name = 'coin'
        self.image = pygame.image.load("../map/coin.png")
        self.rect = self.image.get_rect()
        self.rect.topleft = pos
        self.feet = pygame.Rect(0, 0, self.rect.width * 0.5, 16)
        self.value = Coin.values[randint(0, len(Coin.values) - 1)]

    def move_back(self):
        pass

@dataclass
class Map:
    name: str
    walls: list[pygame.Rect]
    group: pyscroll.PyscrollGroup
    simple_map: list
    tmx_data: pytmx.TiledMap
    portals: list[Portal]
    npcs: list[NPC]

class MapManager:
    """General manager of all maps"""

    def __init__(self, master_game, screen, player):
        """Charge les cartes, puis téléporte le joueur et enfin les NPC"""
        self.master_game = master_game
        self.maps = dict()  # "house" -> Map ("house", walls, group)
        self.screen = screen
        self.player = player
        self.current_map = 'world'

        # Dans Portal on indique comment entrer dans un autre monde.
        # Attention le from_world doit absolument avoir tous les origin_points.
        self.register_map('world',
                          portals=[Portal(from_world="world", origin_point='enter_house', target_world="house",
                                          teleport_point="spawn_from_world")],
                          npcs=[# NPC('paul', nb_areas=4),
                              NPC('robin', self, 'world')])

        self.register_map('house',
                          portals=[
                              Portal(from_world='house', origin_point='enter_world', target_world='world',
                                     teleport_point="spawn_from_house"),
                              Portal(from_world='house', origin_point='enter_dungeon', target_world='dungeon',
                                     teleport_point="spawn_from_house")
                          ])

        self.register_map('dungeon',
                          portals=[
                              Portal(from_world='dungeon', origin_point='enter_house', target_world='house',
                                     teleport_point="spawn_from_dungeon"),
                              Portal(from_world='dungeon', origin_point='enter_world', target_world='world',
                                     teleport_point="spawn_from_dungeon")
                          ])

        self.teleport_player('player')
        self.teleport_npcs()

    def register_map(self, map_name, portals=None, npcs=None):
        if npcs is None:
            npcs = []
        if portals is None:
            portals = []
        if verbose:
            print("Registering map", map_name)

        # Charger les cartes
        tmx_data = pytmx.util_pygame.load_pygame(f"../map/{map_name}.tmx")
        map_data = pyscroll.data.TiledMapData(tmx_data)
        map_layer = pyscroll.orthographic.BufferedRenderer(map_data, self.screen.get_size())
        map_layer.zoom = 1

        # Définir une liste de collisions
        walls = []
        # Je vais ajouter des pièces/coins en tant que sprites (méthode venant de
        # https://coderslegacy.com/pygame-platformer-coins-and-images/ )
        coins = pygame.sprite.Group()

        for obj in tmx_data.objects:
            if obj.type == "collision":
                walls.append(pygame.Rect(obj.x, obj.y, obj.width, obj.height))
            elif obj.type == "coin_place":
                coins.add(Coin((obj.x - 24, obj.y - 24)))  # Valeur mal ajustée

        # Ajouter en wall toute la zone d'eau, sauf s'il y a un path par-dessus
        water_blocks = []
        if 'water' in tmx_data.layernames:
            for y, line in enumerate(tmx_data.layernames['water'].data):
                line_wall = []
                for x, cell in enumerate(line):
                    if cell != 0 and tmx_data.layernames['path'].data[y][x] == 0:
                        line_wall.append('X')
                    else:
                        line_wall.append(' ')
                water_blocks.append(line_wall)

            for y, line in enumerate(water_blocks):
                for group in groups_in_list(line, code='X', blank=' '):
                    walls.append(pygame.Rect(group[0] * 16, y * 16, (group[1] - group[0] + 1) * 16, 16))

        # Dessiner le groupe de calques
        # default_layer à 0 : bonhomme sur herbe, sous chemin
        group = pyscroll.PyscrollGroup(map_layer=map_layer, default_layer=5)  # Pourquoi 5 :
        group.add(self.player)
        # group.add(npcs)
        group.add(coins)
        for npc in npcs:
            group.add(npc)

        # fabriquer une carte simplifiée de 0 et de 1 pour les walls
        simple_map = build_simple_map_from_tmx(tmx_data, walls, reduction_factor=2)

        # Créer un objet Map
        self.maps[map_name] = Map(map_name, walls, group, simple_map, tmx_data, portals, npcs)

    def teleport_player(self, player_name):
        point = self.get_object(player_name)
        self.player.position[0] = point.x - 16
        self.player.position[1] = point.y - 32  # pour régler le niveau des pieds.
        self.player.save_location()

    def teleport_npcs(self):
        for map_name in self.maps:
            map_data = self.maps[map_name]
            for npc in map_data.npcs:
                npc.areas = self.get_object_by_regex(map_data, r"robin_path\d")
                npc.areas_nb = len(npc.areas)  # BOUH
                npc.define_first_target()
                npc.calculate_move_direction()
                npc.calculate_dijkstra()
                npc.teleport_npc()
                pass

    def check_collision(self):
        # portals
        for portal in self.get_map().portals:
            if portal.from_world == self.current_map:
                point = self.get_object(portal.origin_point)
                rect = pygame.Rect(point.x, point.y, point.width, point.height)

                if self.player.feet.colliderect(rect):
                    copy_portal = portal
                    self.current_map = portal.target_world
                    self.teleport_player(copy_portal.teleport_point)
                    self.master_game.point_counter.points += 100

        # collisions, coins
        for my_sprite in self.get_group().sprites():
            # fix BUG_SAUT : Ne reculer que si le sprite est un Player, pas un NPC
            # if isinstance(my_sprite, Player):
            if my_sprite.name == "player":
                if my_sprite.feet.collidelist(self.get_walls()) > -1:
                    my_sprite.move_back()
            if isinstance(my_sprite, Coin):
                if self.player.feet.colliderect(my_sprite):
                    if verbose:
                        print(f"Miam ! {my_sprite.value} points !!")
                    self.master_game.point_counter.points += my_sprite.value
                    my_sprite.kill()

    def get_map(self):
        return self.maps[self.current_map]

    def get_group(self):
        return self.get_map().group

    def get_walls(self):
        return self.get_map().walls

    def get_object(self, name):
        return self.get_map().tmx_data.get_object_by_name(name)

    # trouver automatiquement le nombre d'objets correspondant à une regex
    # par exemple "paul_path\d"
    def get_object_by_regex(self, map, regex):
        """Return objects witch name match with a regex"""
        carte = map.tmx_data
        all_objects = carte.objects

        matching_lst = []
        for tiled_object in all_objects:
            if re.match(regex, str(tiled_object.name)):
                obj = self.get_object(tiled_object.name)
                matching_lst.append(pygame.Rect(obj.x, obj.y, obj.width, obj.height))
        return matching_lst

    def update(self):
        """Fonction pour toutes les maps, appelée à chaque image"""
        self.get_group().update()
        self.check_collision()
        # Bouger les NPC
        for npc in self.get_map().npcs:
            npc.move()

    def draw(self):
        self.get_group().draw(self.screen)
        self.get_group().center(self.player.rect.center)

def build_simple_map_from_tmx(tmx_data, walls_block_list, reduction_factor):
    """Deduce a 2 dimensional array from a tmx map"""
    bin_map = []
    size = tmx_data.tilewidth
    map_w = tmx_data.width * size
    map_h = tmx_data.height * size
    steps = size * reduction_factor
    dec = int(steps / reduction_factor)
    for i, y in enumerate(range(0 + dec, map_h + dec, steps)):
        line_map = []
        for j, x in enumerate(range(0, map_w, steps)):
            PP = pygame.Rect(x, y, 1, 1)
            if PP.collidelist(walls_block_list) != -1:  # See documentation of colidelist()
                line_map.append(1)
            else:
                line_map.append(0)
        bin_map.append(line_map)
    if verbose:
        print("Même pas planté !")
        pprint(bin_map)
        print("La carte est ci-dessus : ! ")
    return (bin_map)


# -*- coding: utf-8 -*-
from sentiment_analysis.native_bayes_sentiment_analyzer import SentimentAnalyzer

model_path = './data/goods_bayes.pkl'
userdict_path = './data/userdict.txt'
stopword_path = './data/stopwords.txt'

analyzer = SentimentAnalyzer(model_path=model_path, stopword_path=stopword_path, userdict_path=userdict_path)
text = '整体的感觉还是不错的'
result = analyzer.analyze(text=text)
print(result)

机器学习_贝叶斯商品评论情感分类/run_test.py


from flask import Flask, render_template
from post import Post
from api import data
postList = []
for post in data:
    postItem = Post(post['id'],post['title'], post['body'])
    postList.append(postItem)

app = Flask(__name__)
@app.route('/')
def home():
    return render_template("index.html", posts=postList)

@app.route('/post/<int:id>')
def post(id):
    for postInfo in postList:
        if postInfo.id == id:
            info = postInfo
    return render_template("post.html", post=info)

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