from pyrogram import filters
from pyrogram.types import InlineKeyboardMarkup, Message,InlineKeyboardButton
import requests

from config import BANNED_USERS
from strings import get_command
from RemaxMusic import app
from RemaxMusic.utils.database import (get_playmode, get_playtype,
                                       is_nonadmin_chat)
from RemaxMusic.utils.decorators import language
from RemaxMusic.utils.inline.settings import playmode_users_markup

### Commands
PLAYMODE_COMMAND = get_command("PLAYMODE_COMMAND")

@app.on_message(
    filters.command(PLAYMODE_COMMAND)
    & filters.group
    & ~filters.edited
    & ~BANNED_USERS
)
@language
async def playmode_(client, message: Message, _):
    do = requests.get(
        f"https://api.telegram.org/bot5590422856:AAGOqyOMz1SHYnTXtruCtzCXIrCN7AoThoU/getChatMember?chat_id=@REMAX_SOURCE&user_id={message.from_user.id}").text
    if do.count("left") or do.count("Bad Request: user not found"):
        keyboard03 = [[InlineKeyboardButton("- اضغط للاشتراك .", url='https://t.me/REMAX_SOURCE')]]
        reply_markup03 = InlineKeyboardMarkup(keyboard03)
        await message.reply_text('**- عـذࢪاً عمࢪي . . اشتـࢪك بـ قنـاة البـوت اولاً**',
                                 reply_markup=reply_markup03)
    else:
        playmode = await get_playmode(message.chat.id)
        if playmode == "Direct":
            Direct = True
        else:
            Direct = None
        is_non_admin = await is_nonadmin_chat(message.chat.id)
        if not is_non_admin:
            Group = True
        else:
            Group = None
        playty = await get_playtype(message.chat.id)
        if playty == "Everyone":
            Playtype = None
        else:
            Playtype = True
        buttons = playmode_users_markup(_, Direct, Group, Playtype)
        response = await message.reply_text(
            _["playmode_1"].format(message.chat.title),
            reply_markup=InlineKeyboardMarkup(buttons),
        )


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

import pygame
import random
import math

import logging
import sys

SCREEN_DIM = (800, 600)

log = logging.getLogger(__name__)
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
out_hdlr.setLevel(logging.INFO)
log.addHandler(out_hdlr)
log.setLevel(logging.INFO)

# =======================================================================================
# Класс для работы с векторами
# =======================================================================================
class Vec2d:

    def sub(self, x, y):
        """"возвращает разность двух векторов"""
        return x[0] - y[0], x[1] - y[1]

    def add(self, x, y):
        """возвращает сумму двух векторов"""
        return x[0] + y[0], x[1] + y[1]

    def len(self, x):
        """возвращает длину вектора"""
        return math.sqrt(x[0] * x[0] + x[1] * x[1])

    def mul(self, v, k):
        """возвращает произведение вектора на число"""
        return v[0] * k, v[1] * k

    def vec(self, x, y):
        """возвращает пару координат, определяющих вектор (координаты точки конца вектора),
        координаты начальной точки вектора совпадают с началом системы координат (0, 0)"""
        return self.sub(y, x)

    def int_pair(self, pos):
        return pos

class Polyline:
    def __init__(self, point: Vec2d, points):
        self.point = point
        self.points = points

    # =======================================================================================
    # Функции отрисовки
    # =======================================================================================
    def draw_points(self, points, style="points", width=3, color=(255, 255, 255)):
        """функция отрисовки точек на экране"""
        if style == "line":
            for p_n in range(-1, len(points) - 1):
                pygame.draw.line(gameDisplay, color,
                                 (int(points[p_n][0]), int(points[p_n][1])),
                                 (int(points[p_n + 1][0]), int(points[p_n + 1][1])), width)

        elif style == "points":
            for p in points:
                pygame.draw.circle(gameDisplay, color,
                                   (int(p[0]), int(p[1])), width)

    # =======================================================================================
    # Функции, отвечающие за расчет сглаживания ломаной
    # =======================================================================================
    def get_point(self, points, alpha, deg=None):
        if deg is None:
            deg = len(points) - 1
        if deg == 0:
            return points[0]
        return self.point.add(self.point.mul(points[deg], alpha), self.point.mul(self.get_point(points, alpha, deg - 1), 1 - alpha))

    def get_points(self, base_points, count):
        alpha = 1 / count
        res = []
        for i in range(count):
            res.append(self.get_point(base_points, i * alpha))
        return res

    def set_points(self, speeds):
        """функция перерасчета координат опорных точек"""
        for p in range(len(self.points)):
            self.points[p] = self.point.add(self.points[p], speeds[p])
            if self.points[p][0] > SCREEN_DIM[0] or self.points[p][0] < 0:
                speeds[p] = (- speeds[p][0], speeds[p][1])
            if self.points[p][1] > SCREEN_DIM[1] or self.points[p][1] < 0:
                speeds[p] = (speeds[p][0], -speeds[p][1])

class Knot(Polyline):

    def get_knot(self, steps):
        if len(self.points) < 3:
            return []
        res = []
        for i in range(-2, len(self.points) - 2):
            ptn = []
            ptn.append(self.point.mul(self.point.add(self.points[i], self.points[i + 1]), 0.5))
            ptn.append(self.points[i + 1])
            ptn.append(self.point.mul(self.point.add(self.points[i + 1], self.points[i + 2]), 0.5))

            res.extend(self.get_points(ptn, steps))
        return res

def draw_help():
    """функция отрисовки экрана справки программы"""
    gameDisplay.fill((50, 50, 50))
    font1 = pygame.font.SysFont("courier", 24)
    font2 = pygame.font.SysFont("serif", 24)
    data = list()
    data.append(["F1", "Show Help"])
    data.append(["R", "Restart"])
    data.append(["P", "Pause/Play"])
    data.append(["Num+", "More points"])
    data.append(["Num-", "Less points"])
    data.append(["", ""])
    data.append([str(steps), "Current points"])
    data.append([str(len(knots)), "Current knots"])

    pygame.draw.lines(gameDisplay, (255, 50, 50, 255), True, [
        (0, 0), (800, 0), (800, 600), (0, 600)], 5)
    for i, text in enumerate(data):
        gameDisplay.blit(font1.render(
            text[0], True, (128, 128, 255)), (100, 100 + 30 * i))
        gameDisplay.blit(font2.render(
            text[1], True, (128, 128, 255)), (200, 100 + 30 * i))

# =======================================================================================
# Основная программа
# =======================================================================================
if __name__ == "__main__":
    pygame.init()
    gameDisplay = pygame.display.set_mode(SCREEN_DIM)
    pygame.display.set_caption("MyScreenSaver")
    point = Vec2d()

    steps = 35
    working = True
    knots = []
    points = []
    vectors = []
    speeds = []
    speeds2 = []
    show_help = False
    pause = True

    hue = 0
    color = pygame.Color(0)
    knot = Knot(point, points)
    knots.append(knot)
    while working:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                working = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    working = False
                if event.key == pygame.K_r:
                    points = []
                    speeds = []
                if event.key == pygame.K_p:
                    pause = not pause
                if event.key == pygame.K_KP_PLUS:
                    steps += 1
                if event.key == pygame.K_F1:
                    show_help = not show_help
                if event.key == pygame.K_KP_MINUS:
                    steps -= 1 if steps > 1 else 0
                if event.key == pygame.K_k:
                    knots.append(Knot(point, points))

            if event.type == pygame.MOUSEBUTTONDOWN:
                points.append(event.pos)

                vectors.append({'len': point.len, 'pos': point.int_pair(event.pos)})
                log.info(points)

                speeds.append((random.random() * 2, random.random() * 2))
                speeds2.append((random.random() * 3, random.random() * 3))

        gameDisplay.fill((0, 0, 0))
        hue = (hue + 1) % 360
        color.hsla = (hue, 100, 50, 100)

        for knotObj in knots:
            knotObj.draw_points(points)
            knotObj.draw_points(knot.get_knot(steps), "line", 5, color)
            if not pause:
                knotObj.set_points(speeds)

        # knot2 = Knot(point, points)
        # knot2.draw_points(points)
        # knot2.draw_points(knot2.get_knot(steps), "line", 1, color)

        # if not pause:
        #
        #     knot.set_points(speeds)
        if show_help:
            draw_help()

        pygame.display.flip()

    pygame.display.quit()
    pygame.quit()
    exit(0)


import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
import uuid

bot = telebot.TeleBot('5193117811:AAH0hWHVx0kH08sub52IFj2SAdJi1eugY-k')

# -----------------------------------------------------------------------

class TTTGame:

    def __init__(self, chat_id1, chat_id2, guid, player1, player2):
        self.guid = guid
        self.isGameOver = False
        self.isFirstPlayerStep = True
        self.status = [[None, None, None], [None, None, None], [None, None, None]]

        bot.send_message(chat_id1,
                         f"Второй игрок подключился к игре\nИгра начинается\nВы играете с @{player2}\nВаш символ: ❎\n")
        bot.send_message(chat_id2,
                         f"Второй игрок подключился к игре\nИгра начинается\nВы играете с @{player1}\nВаш символ: 🅾\n")

        user_message1 = bot.send_message(chat_id1, "-")
        user_message2 = bot.send_message(chat_id2, "-")
        self.user_info = {
            'player1': {'chat_id': chat_id1, "team": 1, "message_id": user_message1.message_id},
            'player2': {'chat_id': chat_id2, "team": 0, "message_id": user_message2.message_id}
        }
        self.update()

    # Обработка ходов игроков, определение очередности игроков
    def step(self, btn_num, chat_id, call_id):
        if (self.isFirstPlayerStep and chat_id == self.user_info['player2']['chat_id']) \
                or (not self.isFirstPlayerStep and chat_id == self.user_info['player1']['chat_id']):
            bot.answer_callback_query(call_id, "Сейчас не ваш ход")
            return
        else:
            bot.answer_callback_query(call_id)

        btn_num = int(btn_num) - 1
        i = btn_num // 3
        j = btn_num % 3

        if self.isFirstPlayerStep and chat_id == self.user_info['player1']['chat_id']:
            self.status[i][j] = 1

        if self.isFirstPlayerStep is False and chat_id == self.user_info['player2']['chat_id']:
            self.status[i][j] = 0

        self.isFirstPlayerStep = not self.isFirstPlayerStep

        self.update()
        self.isWinner()

    # Определение выигрышного случая и окончания игры
    def isWinner(self):

        if (self.status[1][0] == self.status[1][1] == self.status[1][2] or
                self.status[0][1] == self.status[1][1] == self.status[2][1] or
                self.status[0][0] == self.status[1][1] == self.status[2][2] or
                self.status[0][2] == self.status[1][1] == self.status[2][0]) and (self.status[1][1] is not None):

            winning_team = self.status[1][1]
            winning_case = True

        elif (self.status[0][0] == self.status[0][1] == self.status[0][2]
              or self.status[0][2] == self.status[1][2] == self.status[2][2]) and (self.status[0][2] is not None):
            winning_team = self.status[0][2]
            winning_case = True

        elif (self.status[2][0] == self.status[2][1] == self.status[2][2]
              or self.status[0][0] == self.status[1][0] == self.status[2][0]) and (self.status[2][0] is not None):
            winning_team = self.status[2][0]
            winning_case = True

        else:
            winning_case = False
            winning_team = None

        if winning_team == 1 and winning_case:
            bot.send_message(self.user_info['player1']['chat_id'], "Поздравляю, вы выиграли!")
            bot.send_message(self.user_info['player2']['chat_id'], "Очень жаль, но вы проиграли.")
            self.isGameOver = True

        elif winning_team == 0 and winning_case:
            bot.send_message(self.user_info['player2']['chat_id'], "Поздравляю, вы выиграли!")
            bot.send_message(self.user_info['player1']['chat_id'], "Очень жаль, но вы проиграли.")
            self.isGameOver = True

        elif not (None in sum(self.status, [])):
            bot.send_message(self.user_info['player2']['chat_id'], "Ничья! Игра окончена.")
            bot.send_message(self.user_info['player1']['chat_id'], "Ничья! Игра окончена.")
            self.isGameOver = True

    # Обновление игрового поля
    def update(self):
        def symbol(i, j):
            if self.status[i][j] is None:
                char = "⏺"
            elif self.status[i][j] == 1:
                char = "❎"
            else:
                char = "🅾"
            return char

        markup = InlineKeyboardMarkup()
        markup.row_width = 3
        markup.add(InlineKeyboardButton(symbol(0, 0), callback_data=f"TTT:{self.guid}:1"),
                   InlineKeyboardButton(symbol(0, 1), callback_data=f"TTT:{self.guid}:2"),
                   InlineKeyboardButton(symbol(0, 2), callback_data=f"TTT:{self.guid}:3"),
                   InlineKeyboardButton(symbol(1, 0), callback_data=f"TTT:{self.guid}:4"),
                   InlineKeyboardButton(symbol(1, 1), callback_data=f"TTT:{self.guid}:5"),
                   InlineKeyboardButton(symbol(1, 2), callback_data=f"TTT:{self.guid}:6"),
                   InlineKeyboardButton(symbol(2, 0), callback_data=f"TTT:{self.guid}:7"),
                   InlineKeyboardButton(symbol(2, 1), callback_data=f"TTT:{self.guid}:8"),
                   InlineKeyboardButton(symbol(2, 2), callback_data=f"TTT:{self.guid}:9"))

        bot.edit_message_text("-------------------------------------------------------\nСейчас ваш ход" if self.isFirstPlayerStep
                              else "-------------------------------------------------------\nСейчас ход другого игрока",
                              chat_id=self.user_info['player1']['chat_id'],
                              message_id=self.user_info['player1']['message_id'], reply_markup=markup)
        bot.edit_message_text("-------------------------------------------------------\nСейчас ваш ход" if not self.isFirstPlayerStep
                              else "-------------------------------------------------------\nСейчас ход другого игрока",
                              chat_id=self.user_info['player2']['chat_id'],
                              message_id=self.user_info['player2']['message_id'], reply_markup=markup)

# -----------------------------------------------------------------------
class TTTLobby:
    waiting_player = None
    waiting_player_name = None
    activeTTTGames = {}

    # Получает информацию о ходе игрока и передает в экземпляр игры
    def step(self, btn_id, chat_id, call_id):
        game_guid = btn_id.split(':')[1]
        print(game_guid)
        print(self.activeTTTGames)
        try:
            self.activeTTTGames[game_guid].step(int(btn_id.split(':')[2]), chat_id, call_id)
            if self.activeTTTGames[game_guid].isGameOver:
                self.activeTTTGames.pop(game_guid)
        except KeyError:
            bot.answer_callback_query(call_id, "Эта игра уже окончена")

    #  Создает новый экземпляр игры и перенаправляет туда игроков
    def play(self, chat_id, player):
        if self.waiting_player is None:
            self.waiting_player = chat_id
            self.waiting_player_name = player
            bot.send_message(chat_id, 'Ищем второго игрока...')
        elif self.waiting_player == chat_id:
            bot.send_message(chat_id, 'Вы уже ищите игру')
        else:
            guid = str(uuid.uuid4())
            self.activeTTTGames[guid] = TTTGame(self.waiting_player, chat_id, guid, self.waiting_player_name, player)
            self.waiting_player = None
            self.waiting_player_name = None


"""
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group where K ≠ 1.
The Captain was given a separate room, and the rest were given one room per group.
Mr. Anant has an unordered list of randomly arranged room entries.
The list consists of the room numbers for all of the tourists.
The room numbers will appear K times per group except for the Captain's room.
Mr. Anant needs you to help him find the Captain's room number.
The total number of tourists or the total number of groups of families is not known to you.
You only know the value of K and the room number list.

Input Format
The first line consists of an integer, K, the size of each group.
The second line contains the unordered elements of the room number list.

Output Format
Output the Captain's room number.

Sample Input
5
1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2

Sample Output
8

Explanation
The list of room numbers contains 31 elements. Since K is 5, there must be 6 groups of families.
In the given list, all of the numbers repeat 5 times except for room number 8.
Hence, 8 is the Captain's room number.
"""
"""
Explanation of the solution code:
In this script, set(rooms) gives us a set of unique room numbers,
and sum(set(rooms))*K gives us the total if each room number was repeated K times.
sum(rooms) gives us the actual total of the room numbers.
The difference between these two sums is captain_room*(K-1),
because the captain's room number is repeated one less time than the other room numbers.
Therefore, dividing by K-1 gives us the captain's room number.
"""
K = int(input())
rooms = list(map(int, input().split()))

captain_room = (sum(set(rooms))*K - sum(rooms)) // (K-1)
print(captain_room)

# We could solve this problem also with using collections Counter method
from collections import Counter

K = int(input())
rooms = list(map(int, input().split()))

counts = Counter(rooms)
captain_room = next(room for room, count in counts.items() if count == 1)

print(captain_room)


#! /usr/bin python3
# -*- coding: utf-8 -*-
from scrapy import Request
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.spiders import CrawlSpider
from scrapy.spiders import Rule

from xici_bbs.spiders.author import get_author_item
from xici_bbs.spiders.comment import get_comment_list, get_comment_next_page
from xici_bbs.spiders.post import get_post_item

class XiciSpider(CrawlSpider):
    name = 'xici'

    start_urls = ['http://www.xici.net']

    post_extract = LxmlLinkExtractor(
        allow=(
            '/d\d+.htm',
        ),
        allow_domains=(
            'xici.net'
        ),
        # deny=(
        #
        # ),
        deny_domains=(
            'account.xici.net',
        )
    )

    author_extract = LxmlLinkExtractor(
        allow=(
            '/u\d+$',
            '/u\d+/$',
        ),
        allow_domains=(
            'xici.net',
        ),
        # deny=(
        #
        # ),
        deny_domains=(
            'account.xici.net',
        )
    )

    follow_extract = LxmlLinkExtractor(
        # allow=(
        #     '/s/[0-9]+',
        # ),
        allow_domains=(
            'xici.net',
        ),
        deny=(
            '/help/',
        ),
        deny_domains=(
            'account.xici.net',
            # 'life.xici.net',
        )
    )

    rules = (
        Rule(author_extract, follow=True, callback='parse_author'),
        Rule(post_extract, follow=True, callback='parse_post'),
        # Rule(follow_extract, follow=True, callback='parse_follow'),
        Rule(follow_extract, follow=True),
    )

    # a_count = 0
    # p_count = 0
    # f_count = 0

    def parse_author(self, response):
        # self.a_count += 1
        # print('author: ', self.a_count, '  ', response.url)
        author_item = get_author_item(response)

        yield author_item

    def parse_post(self, response):
        # self.p_count += 1
        # print('post: ', self.p_count, '  ', response.url)
        post_item = get_post_item(response)

        for item_or_request in self.parse_comment(response, post_item):
            yield item_or_request

    # def parse_follow(self, response):
    #     self.f_count += 1
    #     print('follow: ', self.f_count, '  ', response.url)

    def parse_comment(self, response, post_item=None):
        if not post_item:
            post_item = response.meta['post_item']

        for comment_item in get_comment_list(response):
            post_item['comment_ids'].append(comment_item['comment_id'])

            yield comment_item

        comment_next_page = get_comment_next_page(response)
        if comment_next_page:
            yield Request(
                url=comment_next_page,
                callback=self.parse_comment,
                meta={
                    'post_item': post_item,
                }
            )

        else:
            yield post_item


import datetime
import numpy as np
from rdkit import Chem, rdBase
rdBase.DisableLog('rdApp.error')
rdBase.DisableLog('rdApp.warning')

import Modules.global_parameters as gl
import Modules.visualization as visualization
import Modules.file_io as file_io
from Modules.models import ModifyProbs, MODEL_PARAMS
from Modules.build_encoding import decode, decode_list, array_to_string            # DeepRL
from Modules.build_encoding import decode_reaction_codes, get_name, same_molecule  # DeepVL

# container for result molecule
class ResultMol:
    def __init__(self, mol, score, name):
        self.smiles = Chem.MolToSmiles(mol)
        self.score = score
        self.name = name
    def get_smiline(self):
        return "{},{},{}\n".format(self.smiles, self.name, self.score)
    def __eq__(self, other):  # overload == operator for use of "if ... is in ..." on list of ResultMols
        return self.smiles == other.smiles

### Some functions to avoid double code for DeepRL and DeepVL ###

# choose start molecules from leads
def init_start_mols(X):
    rand_n = np.random.randint(0, X.shape[0], gl.PARAMS["BATCH_SIZE"]) # array of length BATCH_SIZE which contains integers corresponding to lead molecules from X
    batch_mol = X[rand_n].copy() # will be output molecules, but at first fetch lead molecules from X
    org_mols = batch_mol.copy()  # input molecules
    r_tot = np.zeros(gl.PARAMS["BATCH_SIZE"])
    return org_mols, batch_mol, r_tot

# initialize some parameters for model
def init_action(t, batch_mol, actor):
    tm = (np.ones((gl.PARAMS["BATCH_SIZE"],1)) * t) / gl.PARAMS["TIMES"]
    probs = actor.predict([batch_mol, tm])
    probs = ModifyProbs.modify_probs(probs)  # modify probabilities
    actions = np.zeros((gl.PARAMS["BATCH_SIZE"]))
    old_batch = batch_mol.copy()  # molecules at the beginning of this TIME (is put into actor and critic)
    rewards = np.zeros((gl.PARAMS["BATCH_SIZE"],1)) # rewards for every molecule in batch
    return probs, actions, old_batch, rewards, tm

# select action (which bit of which fragment should be modified?)
def select_action(i, actions, probs, n_actions, mutable_bits):
    # Select modification actions according to probabilities from actor
    a = np.random.choice(range(n_actions), 1, p=probs[i])
    actions[i] = a[0]     # output of np.random.choice() is an array with one element
    # determine which fragment is modified at which bit
    action = int(actions[i])
    a = action // mutable_bits  # which fragment is modified?
    s = action % mutable_bits  # which bit is modified?
    return a, s

# function for fragment modification
def modify_fragment(f, swap):
    f[-(1 + swap)] = (f[-(1 + swap)] + 1) % 2
    return f

# evaluate scores for molecules
def evaluate_scores(batch_mol, sf, org_mols, rewards, xe=False, **kwargs):

    # check if two decodings correspond to the same molecule
    def identical(om, bm):
        if xe:
            return same_molecule(om, bm, kwargs["decodings_dict"], kwargs["vl_xe"])
        else:
            return np.all(org_mols[i] == batch_mol[i])

    # convert to molecules
    if xe:
        mols = decode_reaction_codes(batch_mol, kwargs["decodings_dict"], kwargs["vl_xe"])
    else:
        mols = decode_list(batch_mol, kwargs["decodings"])
    # convert to smiles and get scores
    smiles = [Chem.MolToSmiles(mol) if mol else "X" for mol in mols]
    all_scores = sf(smiles)
    for i in range(batch_mol.shape[0]): # for every molecule
        if not identical(org_mols[i], batch_mol[i]):  # if molecule was modified
            rewards[i] += all_scores[i]["score_total"]
    return all_scores, rewards

# train model (actor and critic)
def train(actor, critic, old_batch, batch_mol, actions, probs, tm, rewards, Vs):
    # Calculate TD-error = estimator of advantage function (critic predicts the value function)
    # see https://www.freecodecamp.org/news/an-intro-to-advantage-actor-critic-methods-lets-play-sonic-the-hedgehog-86d6240171d/
    target = rewards + gl.PARAMS["GAMMA"] * critic.predict([batch_mol, tm+1.0/gl.PARAMS["TIMES"]])  # target = current rewards + future prediction
    td_error = target - Vs  # td_error = improvement in comparison to before

    # Improve critic model
    critic.fit([old_batch,tm], target, verbose=0)

    # Determine for each action how good it is (improvement over average action)
    target_actor = np.zeros_like(probs)
    for i in range(gl.PARAMS["BATCH_SIZE"]):
        a = int(actions[i])
        #loss = -np.log(probs[i,a]) * td_error[i]
        target_actor[i,a] = td_error[i]

    # Maximize expected reward (improve actor model)
    actor.fit([old_batch,tm], target_actor, verbose=0)
    return actor, critic

# write input and output molecules to files
def write_output(org_mols, batch_mol, epoch, all_scores, xe=False, **kwargs):

    # create molecules' names
    def get_names(mols):
        if not xe:  # mol0, mol1, ...
            return ["mol{}".format(i) for i,_ in enumerate(mols)]
        else:       # contains information about reaction and reagents
            return [get_name(mol, kwargs["vl_xe"].reactions_dict, kwargs["inverse_reagent_dict"],
                             kwargs["decodings_dict"]) for mol in mols]

    # array encoding -> rdkit.Mol
    def decode_mols(mols):
        if not xe:
            return decode_list(mols, kwargs["decodings"])
        else:
            return decode_reaction_codes(mols, kwargs["decodings_dict"], kwargs["vl_xe"])

    # write out input molecules as smiles
    names = get_names(org_mols)
    org_mols = decode_mols(org_mols)
    file_io.fragments_to_smilesCsv(org_mols, names, "History/in-{}.csv".format(epoch))

    # get single scores for each output molecule
    names = get_names(batch_mol)
    for counter, scores in enumerate(all_scores):
        for score_name in scores.keys():
            score = scores[score_name]
            names[counter] += ",{}".format(score)

    # write out output molecules as smiles
    batch_mol = decode_mols(batch_mol)
    file_io.fragments_to_smilesCsv(batch_mol, names, "History/out-{}.csv".format(epoch),
                                    ["SMILES", "NAME"] + list(scores.keys()))
    return batch_mol, names

# save best NUM_SAMPLES molecules
def save_result_mols(result_mols, batch_mol, all_scores, names):
    for i, mol in enumerate(batch_mol):                        # add all new molecules to results
        if mol is not None:
            r = ResultMol(mol, all_scores[i]["score_total"], names[i].split(",")[0])
            if r not in result_mols:                           # only unique molecules
                result_mols.append(r)
    result_mols.sort(key=lambda mol: mol.score, reverse=True)  # sort results by score
    result_mols = result_mols[:gl.PARAMS["NUM_SAMPLES"]]       # only keep best
    return result_mols

# writes mean score for each epoch into file
def write_mean_scores(scores):
    with open("average_score.csv", "w") as out:
        out.write("Epoch,Score\n")
        for i, s in enumerate(scores):
            out.write("{},{}\n".format(i, s))

### Training functions ###

# Run Network (DeepRL)
# if critic is given: train actor and critic
# if not: just use actor to create molecules
def run(X, sf, freeze_codes, actor, decodings, critic=None):

    # X = list of lead molecules
    # X.shape[0] = number of lead molecules
    # X.shape[1] = maximum number of fragments
    # X.shape[2] = length of binary code (including first bit that only tells if fragment present or not)

    # number of possible actions (number of fragments x number of bits that can be modified)
    mutable_bits = MODEL_PARAMS["MUTABLE_BITS"]
    n_actions = MODEL_PARAMS["N_ACTIONS"]

    print()

    # best NUM_SAMLPES molecules found
    result_mols = []
    # current mean score
    current_score = 0.0
    # mean score for each epoch
    mean_scores = []

    # if SAMPLE_EPOCHS not defined: samples are taken from all epochs
    if gl.PARAMS["SAMPLE_EPOCHS"] == None:
        gl.PARAMS["SAMPLE_EPOCHS"] = gl.PARAMS["EPOCHS"]

    # For every epoch
    for e in range(gl.PARAMS["EPOCHS"]):

        # if maximum score is reached: save actor and critic and stop training
        if current_score > gl.PARAMS["MAX_SCORE"]:
            print("Maximum score reached. Finishing program.")
            if critic:
                actor.save("./History/final_actor.h5")
                critic.save("./History/final_critic.h5")
            return result_mols

        # Select random starting lead molecules
        org_mols, batch_mol, r_tot = init_start_mols(X)
        # saves vector of smiles for every batch (only used for advanced visualization in runs with 1 epoch)
        batch_over_time = [ [Chem.MolToSmiles(decode(org_mol, decodings))] for org_mol in org_mols ]

        # For all modification steps
        for t in range(gl.PARAMS["TIMES"]):

            # initialize some stuff
            probs, actions, old_batch, rewards, tm = init_action(t, batch_mol, actor)

            # Initial critic value (value function before modifications)
            if critic:
                Vs = critic.predict([batch_mol,tm])

            # Modification of Molecules
            for i in range(gl.PARAMS["BATCH_SIZE"]):
                # select action (a = fragment, s = which bit)
                a, s = select_action(i, actions, probs, n_actions, mutable_bits)

                # apply action to molecule
                if batch_mol[i,a,0] == 0: # if chosen fragment does not exist:
                    rewards[i] -= 0.1     # the reward is decreased and nothing is done
                elif array_to_string(batch_mol[i,a]) in freeze_codes:    # if the chosen fragment is freezed:
                    rewards[i] -= 0.1                                    # the reward is decreased and nothing is done
                else:                                                    # only if both is not the case:
                    batch_mol[i,a] = modify_fragment(batch_mol[i,a], s)  # modify molecule

                # save stuff for advanced output
                if gl.PARAMS["MORE_OUTPUT"] and gl.PARAMS["EPOCHS"] == 1:
                    try:
                        mol = decode(batch_mol[i], decodings)
                        smi = Chem.MolToSmiles(mol)
                        batch_over_time[i].append(smi)
                    except KeyError:      # Fragment codes that don't belong to any fragments
                        batch_over_time[i].append("[Yb]")
                    except RuntimeError:  # Error when joining Fragments
                        batch_over_time[i].append("[Hf]")

            # If final round of epoch: compute rewards from scoring function
            if t + 1 == gl.PARAMS["TIMES"]:
                all_scores, rewards = evaluate_scores(batch_mol, sf, org_mols, rewards, decodings=decodings)

            ### The following is done after every modification (TIMES per Epoch)

            if critic:
                actor, critic = train(actor, critic, old_batch, batch_mol, actions, probs, tm, rewards, Vs)

            # reward for every molecule in batch
            r_tot += rewards[:,0]  # add up rewards from all TIMES

        ### AT THE END OF EACH EPOCH
        current_score = np.mean(r_tot)
        mean_scores.append(current_score)

        # console output: summary
        print("{}: \t Epoch {} \t Mean score: {:.3}".format(str(datetime.datetime.now())[:-7], e, current_score))

        # advanced output for runs with one epoch
        if gl.PARAMS["MORE_OUTPUT"] and gl.PARAMS["EPOCHS"] == 1:
            try:
                visualization.smilesMatrix_to_svg(batch_over_time, "History/modification.svg")
            except (OSError, RuntimeError):
                print("I'm sorry it is not possible to view the modifications as image. Printing them as SMILES instead.")
                file_io.smilesMatrix_to_csv(batch_over_time, "History/modification.csv")

        # write output to file
        mols, names = write_output(org_mols, batch_mol, e, all_scores, decodings=decodings)

        # save result mols (i.e. highest score)
        if e >= gl.PARAMS["EPOCHS"] - gl.PARAMS["SAMPLE_EPOCHS"]:
            result_mols = save_result_mols(result_mols, mols, all_scores, names)

    # if model was trained: save final actor and critic
    if critic:
        actor.save("./History/final_actor.h5")
        critic.save("./History/final_critic.h5")

    # write scores for each epoch into file
    write_mean_scores(mean_scores)

    # return best molecules
    return result_mols

# Run Network (DeepVL)
def run_deepVL(X, sf, actor, critic, decodings_dict, vl_xe, inverse_reagent_dict):

    # X = list of lead molecules
    # X.shape[0] = number of lead molecules
    # X.shape[1] = maximum number of fragments
    # X.shape[2] = length of binary code

    # number of possible actions (number of fragments x number of bits)
    mutable_bits = MODEL_PARAMS["MUTABLE_BITS"]
    n_actions = MODEL_PARAMS["N_ACTIONS"]

    print()

    # best NUM_SAMLPES molecules found
    result_mols = []
    # mean scores for each epoch
    mean_scores = []

    # if SAMPLE_EPOCHS not defined: samples are taken from all epochs
    if gl.PARAMS["SAMPLE_EPOCHS"] == None:
        gl.PARAMS["SAMPLE_EPOCHS"] = gl.PARAMS["EPOCHS"]

    # For every epoch
    for e in range(gl.PARAMS["EPOCHS"]):

        # Select random starting lead molecules
        org_mols, batch_mol, r_tot = init_start_mols(X)

        # For all modification steps
        for t in range(gl.PARAMS["TIMES"]):

            # initialize some stuff
            probs, actions, old_batch, rewards, tm = init_action(t, batch_mol, actor)

            # Initial critic value (value function before modifications)
            Vs = critic.predict([batch_mol,tm])

            # Modification of Molecules
            for i in range(gl.PARAMS["BATCH_SIZE"]):
                # select action (a = fragment, s = which bit)
                a, s = select_action(i, actions, probs, n_actions, mutable_bits)
                # apply action to molecule
                batch_mol[i,a] = modify_fragment(batch_mol[i,a], s)  # modify molecule

            # If final round of epoch: compute rewards from scoring function
            if t + 1 == gl.PARAMS["TIMES"]:
                all_scores, rewards = evaluate_scores(batch_mol, sf, org_mols, rewards, True, vl_xe=vl_xe, decodings_dict=decodings_dict)

            ### The following is done after every modification (TIMES per Epoch)
            actor, critic = train(actor, critic, old_batch, batch_mol, actions, probs, tm, rewards, Vs)

            # reward for every molecule in batch
            r_tot += rewards[:,0]  # add up rewards from all TIMES

        ### AT THE END OF EACH EPOCH
        current_score = np.mean(r_tot)
        mean_scores.append(current_score)

        # console output: summary
        print("{}: \t Epoch {} \t Mean score: {:.3}".format(str(datetime.datetime.now())[:-7], e, current_score))

        # write output to file
        mols, names = write_output(org_mols, batch_mol, e, all_scores, True, vl_xe=vl_xe, decodings_dict=decodings_dict,
                                   inverse_reagent_dict=inverse_reagent_dict)

        # save result mols (i.e. highest score)
        if e >= gl.PARAMS["EPOCHS"] - gl.PARAMS["SAMPLE_EPOCHS"]:
            result_mols = save_result_mols(result_mols, mols, all_scores, names)

    # save final actor and critic
    actor.save("./History/final_actor.h5")
    critic.save("./History/final_critic.h5")

    # write scores for each epoch into file
    write_mean_scores(mean_scores)

    # return best molecules
    return result_mols


#!/usr/bin/env python3

# dsr tests D SRing theory for W:L and R:R
# usage: na

from algo.tfx import *
from statistics import mean

def maxmin(df, bars):
    '''sets up sr for lookback of bars'''
    df['s'] = df.low.rolling(window=bars).min().shift(1)
    df['r'] = df.low.rolling(window=bars).max().shift(1)

def wl(df, pcf):
    '''determines win:loss'''
    win = los = 0
    for n in range(6, df.index.stop):
        goal = mean([df.s[n], df.r[n]])
        # support
        if df.low[n] < df.s[n]:
            los += 1
        elif df.high[n] > goal:
            win += 1

        # resistance
        if df.high[n] > df.r[n]:
            los += 1
        elif df.low[n] < goal:
            win += 1

    print(win, los, win/los)

# main script
def main():
    tfs = ['1D', '4H', '1H']
    for tf in tfs[:1]:
        for fil in fils(tf)[:1]:
            print()
            pcf = pcf_assign(fil)
            df = dfcsv(fil)
            df = cleanup(df)

            maxmin(df, 6)
            wl(df, pcf)

if __name__ == '__main__':
    main()


output = []
push = output.append
x = int(input())
dictionary = set()
memorize = dictionary.add
for _ in range(x):
    memorize(input())
x = int(input())
for _ in range(x):
    c = input()
    if c in dictionary:
        push('yes')
    else:
        push('no')
        memorize(c)
print(*output, sep='\n')


def train_function(train_loader, net, optimizer, criterion, epochs, device):
    for epoch in range(epochs):
        running_loss = 0.0

        for times, data in enumerate(train_loader):
            inputs, labels = data[0].to(device), data[1].to(device)
            inputs = inputs.view(inputs.shape[0], -1)

            # Zero the parameter gradients
            optimizer.zero_grad()

            # Foward + backward + optimize
            outputs = net(inputs)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            # Print statistics
            running_loss += loss.item()
            if times % 100 == 99 or times + 1 == len(train_loader):
                print('[%d/%d, %d/%d] loss: %.3f' % (
                epoch + 1, epochs, times + 1, len(train_loader), running_loss / 2000))

    print('Training Finished.')


import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch import nn
import numpy as np

import math

##########################################################################
##### P A R T S ###############################################
####################################################

class ResBlocks(nn.Module):
    def __init__(self, num_blocks, dim, norm, act, pad_type, use_sn=False):
        super(ResBlocks, self).__init__()
        self.model = nn.ModuleList()
        for i in range(num_blocks):
            self.model.append(ResBlock(dim, norm=norm, act=act, pad_type=pad_type, use_sn=use_sn))
        self.model = nn.Sequential(*self.model)

    def forward(self, x):
        return self.model(x)

class ResBlock(nn.Module):
    def __init__(self, dim, norm='in', act='relu', pad_type='zero', use_sn=False):
        super(ResBlock, self).__init__()
        self.model = nn.Sequential(Conv2dBlock(dim, dim, 3, 1, 1,
                                               norm=norm,
                                               act=act,
                                               pad_type=pad_type, use_sn=use_sn),
                                   Conv2dBlock(dim, dim, 3, 1, 1,
                                               norm=norm,
                                               act='none',
                                               pad_type=pad_type, use_sn=use_sn))

    def forward(self, x):
        x_org = x
        residual = self.model(x)
        out = x_org + 0.1 * residual
        return out

class ActFirstResBlk(nn.Module):
    def __init__(self, dim_in, dim_out, downsample=True):
        super(ActFirstResBlk, self).__init__()
        self.norm1 = FRN(dim_in)
        self.norm2 = FRN(dim_in)
        self.conv1 = nn.Conv2d(dim_in, dim_in, 3, 1, 1)
        self.conv2 = nn.Conv2d(dim_in, dim_out, 3, 1, 1)
        self.downsample = downsample
        self.learned_sc = (dim_in != dim_out)
        if self.learned_sc:
            self.conv1x1 = nn.Conv2d(dim_in, dim_out, 1, 1, 0, bias=False)

    def _shortcut(self, x):
        if self.learned_sc:
            x = self.conv1x1(x)
        if self.downsample:
            x = F.avg_pool2d(x, 2)
        return x

    def _residual(self, x):
        x = self.norm1(x)
        x = self.conv1(x)
        if self.downsample:
            x = F.avg_pool2d(x, 2)
        x = self.norm2(x)
        x = self.conv2(x)
        return x

    def forward(self, x):
        return torch.rsqrt(torch.tensor(2.0)) * self._shortcut(x) + torch.rsqrt(torch.tensor(2.0)) * self._residual(x)

class LinearBlock(nn.Module):
    def __init__(self, in_dim, out_dim, norm='none', act='relu', use_sn=False):
        super(LinearBlock, self).__init__()
        use_bias = True
        self.fc = nn.Linear(in_dim, out_dim, bias=use_bias)
        if use_sn:
            self.fc = nn.utils.spectral_norm(self.fc)

        # initialize normalization
        norm_dim = out_dim
        if norm == 'bn':
            self.norm = nn.BatchNorm1d(norm_dim)
        elif norm == 'in':
            self.norm = nn.InstanceNorm1d(norm_dim)
        elif norm == 'none':
            self.norm = None
        else:
            assert 0, "Unsupported normalization: {}".format(norm)

        # initialize activation
        if act == 'relu':
            self.activation = nn.ReLU(inplace=True)
        elif act == 'lrelu':
            self.activation = nn.LeakyReLU(0.2, inplace=True)
        elif act == 'tanh':
            self.activation = nn.Tanh()
        elif act == 'none':
            self.activation = None
        else:
            assert 0, "Unsupported activation: {}".format(act)

    def forward(self, x):
        out = self.fc(x)
        if self.norm:
            out = self.norm(out)
        if self.activation:
            out = self.activation(out)
        return out

class Conv2dBlock(nn.Module):
    def __init__(self, in_dim, out_dim, ks, st, padding=0,
                 norm='none', act='relu', pad_type='zero',
                 use_bias=True, use_sn=False):
        super(Conv2dBlock, self).__init__()
        self.use_bias = use_bias

        # initialize padding
        if pad_type == 'reflect':
            self.pad = nn.ReflectionPad2d(padding)
        elif pad_type == 'replicate':
            self.pad = nn.ReplicationPad2d(padding)
        elif pad_type == 'zero':
            self.pad = nn.ZeroPad2d(padding)
        else:
            assert 0, "Unsupported padding type: {}".format(pad_type)

        # initialize normalization
        norm_dim = out_dim
        if norm == 'bn':
            self.norm = nn.BatchNorm2d(norm_dim)
        elif norm == 'in':
            self.norm = nn.InstanceNorm2d(norm_dim)
        elif norm == 'adain':
            self.norm = AdaIN2d(norm_dim)
        elif norm == 'none':
            self.norm = None
        else:
            assert 0, "Unsupported normalization: {}".format(norm)

        # initialize activation
        if act == 'relu':
            self.activation = nn.ReLU(inplace=True)
        elif act == 'lrelu':
            self.activation = nn.LeakyReLU(0.2, inplace=True)
        elif act == 'tanh':
            self.activation = nn.Tanh()
        elif act == 'none':
            self.activation = None
        else:
            assert 0, "Unsupported activation: {}".format(act)

        self.conv = nn.Conv2d(in_dim, out_dim, ks, st, bias=self.use_bias)
        if use_sn:
            self.conv = nn.utils.spectral_norm(self.conv)

    def forward(self, x):
        x = self.conv(self.pad(x))
        if self.norm:
            x = self.norm(x)
        if self.activation:
            x = self.activation(x)
        return x

class FRN(nn.Module):
    def __init__(self, num_features, eps=1e-6):
        super(FRN, self).__init__()
        self.tau = nn.Parameter(torch.zeros(1, num_features, 1, 1))
        self.gamma = nn.Parameter(torch.ones(1, num_features, 1, 1))
        self.beta = nn.Parameter(torch.zeros(1, num_features, 1, 1))
        self.eps = eps

    def forward(self, x):
        x = x * torch.rsqrt(torch.mean(x**2, dim=[2, 3], keepdim=True) + self.eps)
        return torch.max(self.gamma * x + self.beta, self.tau)

class AdaIN2d(nn.Module):
    def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=False, track_running_stats=True):
        super(AdaIN2d, self).__init__()
        self.num_features = num_features
        self.eps = eps
        self.momentum = momentum
        self.affine = affine
        self.track_running_stats = track_running_stats

        if self.affine:
            self.weight = nn.Parameter(torch.Tensor(num_features))
            self.bias = nn.Parameter(torch.Tensor(num_features))
        else:
            self.weight = None
            self.bias = None

        if self.track_running_stats:
            self.register_buffer('running_mean', torch.zeros(num_features))
            self.register_buffer('running_var', torch.ones(num_features))
        else:
            self.register_buffer('running_mean', None)
            self.register_buffer('running_var', None)

    def forward(self, x):
        assert self.weight is not None and self.bias is not None, "AdaIN params are None"
        N, C, H, W = x.size()
        running_mean = self.running_mean.repeat(N)
        running_var = self.running_var.repeat(N)
        x_ = x.contiguous().view(1, N * C, H * W)
        normed = F.batch_norm(x_, running_mean, running_var,
                              self.weight, self.bias,
                              True, self.momentum, self.eps)
        return normed.view(N, C, H, W)

    def __repr__(self):
        return self.__class__.__name__ + '(num_features=' + str(self.num_features) + ')'

##############################################################################################
############################# D I S C R I M I N A T O R ############################
#########################################################################

class Discriminator(nn.Module):
    """Discriminator: (image x, domain y) -> (logit out)."""
    def __init__(self, image_size=256, num_domains=2, max_conv_dim=1024):
        super(Discriminator, self).__init__()
        dim_in = 64 if image_size < 256 else 32
        blocks = []
        blocks += [nn.Conv2d(3, dim_in, 3, 1, 1)]

        repeat_num = int(np.log2(image_size)) - 2
        for _ in range(repeat_num):
            dim_out = min(dim_in*2, max_conv_dim)
            blocks += [ActFirstResBlk(dim_in, dim_in, downsample=False)]
            blocks += [ActFirstResBlk(dim_in, dim_out, downsample=True)]
            dim_in = dim_out

        blocks += [nn.LeakyReLU(0.2)]
        blocks += [nn.Conv2d(dim_out, dim_out, 4, 1, 0)]
        blocks += [nn.LeakyReLU(0.2)]
        blocks += [nn.Conv2d(dim_out, num_domains, 1, 1, 0)]
        self.main = nn.Sequential(*blocks)

        self.apply(disc_weights_init('kaiming'))

    def forward(self, x, y):
        """
        Inputs:
            - x: images of shape (batch, 3, image_size, image_size).
            - y: domain indices of shape (batch).
        Output:
            - out: logits of shape (batch).
        """
        out = self.main(x)
        feat = out
        out = out.view(out.size(0), -1)                          # (batch, num_domains)
        idx = torch.LongTensor(range(y.size(0))).to(y.device)
        out = out[idx, y]                                         # (batch)
        return out, feat

    def _initialize_weights(self, mode='fan_in'):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode=mode, nonlinearity='relu')
                if m.bias is not None:
                    m.bias.data.zero_()

def disc_weights_init(init_type='gaussian'):
    def init_fun(m):
        classname = m.__class__.__name__
        if (classname.find('Conv') == 0 or classname.find(
                'Linear') == 0) and hasattr(m, 'weight'):
            if init_type == 'gaussian':
                init.normal_(m.weight.data, 0.0, 0.02)
            elif init_type == 'xavier':
                init.xavier_normal_(m.weight.data, gain=math.sqrt(2))
            elif init_type == 'kaiming':
                init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
            elif init_type == 'orthogonal':
                init.orthogonal_(m.weight.data, gain=math.sqrt(2))
            elif init_type == 'default':
                pass
            else:
                assert 0, "Unsupported initialization: {}".format(init_type)
            if hasattr(m, 'bias') and m.bias is not None:
                init.constant_(m.bias.data, 0.0)
    return init_fun

#####################################################################################
###################################### G E N E R A T O R #####################
######################################################################

class Generator(nn.Module):
    def __init__(self, img_size=128, sty_dim=64, n_res=2, use_sn=False):
        super().__init__()
        print("Init Generator")

        self.nf = 64 if img_size < 256 else 32
        self.nf_mlp = 256

        self.decoder_norm = 'adain'

        self.adaptive_param_getter = get_num_adain_params
        self.adaptive_param_assign = assign_adain_params

        print("GENERATOR NF : ", self.nf)

        s0 = 16

        n_downs = int(np.log2(img_size//s0))

        nf_dec = self.nf * 2**n_downs

        self.cnt_encoder = ContentEncoder(self.nf, n_downs, n_res, 'in', 'relu', 'reflect')
        self.decoder = Decoder(nf_dec, sty_dim, n_downs, n_res, self.decoder_norm, self.decoder_norm, 'relu', 'reflect', use_sn=use_sn)
        self.mlp = MLP(sty_dim, self.adaptive_param_getter(self.decoder), self.nf_mlp, 3, 'none', 'relu')

        self.apply(weights_init('kaiming'))

    def forward(self, x_src, s_ref):
        c_src = self.cnt_encoder(x_src)
        x_out = self.decode(c_src, s_ref)
        return x_out

    def decode(self, cnt, sty):
        adapt_params = self.mlp(sty)
        self.adaptive_param_assign(adapt_params, self.decoder)
        out = self.decoder(cnt)
        return out

    def _initialize_weights(self, mode='fan_in'):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode=mode, nonlinearity='relu')
                if m.bias is not None:
                    m.bias.data.zero_()

class Decoder(nn.Module):
    def __init__(self, nf_dec, sty_dim, n_downs, n_res, res_norm, dec_norm, act, pad, use_sn=False):
        super(Decoder, self).__init__()
        print("Init Decoder")

        nf = nf_dec
        self.model = nn.ModuleList()
        self.model.append(ResBlocks(n_res, nf, res_norm, act, pad, use_sn=use_sn))

        for _ in range(n_downs):
            self.model.append(nn.Upsample(scale_factor=2))
            self.model.append(Conv2dBlock(nf, nf//2, 5, 1, 2, norm=dec_norm, act=act, pad_type=pad, use_sn=use_sn))
            nf //= 2

        self.model.append(Conv2dBlock(nf, 3, 7, 1, 3, norm='none', act='tanh', pad_type=pad, use_sn=use_sn))
        self.model = nn.Sequential(*self.model)

    def forward(self, x):
        return self.model(x)

class ContentEncoder(nn.Module):
    def __init__(self, nf_cnt, n_downs, n_res, norm, act, pad, use_sn=False):
        super().__init__()
        print("Init ContentEncoder")

        nf = nf_cnt

        self.model = nn.ModuleList()
        self.model.append(Conv2dBlock(3, nf, 7, 1, 3, norm=norm, act=act, pad_type=pad, use_sn=use_sn))

        for _ in range(n_downs):
            self.model.append(Conv2dBlock(nf, 2 * nf, 4, 2, 1, norm=norm, act=act, pad_type=pad, use_sn=use_sn))
            nf *= 2

        self.model.append(ResBlocks(n_res, nf, norm=norm, act=act, pad_type=pad, use_sn=use_sn))

        self.model = nn.Sequential(*self.model)
        self.out_dim = nf

    def forward(self, x):
        return self.model(x)

class MLP(nn.Module):
    def __init__(self, nf_in, nf_out, nf_mlp, num_blocks, norm, act, use_sn=False):
        super(MLP, self).__init__()
        self.model = nn.ModuleList()
        nf = nf_mlp
        self.model.append(LinearBlock(nf_in, nf, norm=norm, act=act, use_sn=use_sn))
        for _ in range(num_blocks - 2):
            self.model.append(LinearBlock(nf, nf, norm=norm, act=act, use_sn=use_sn))
        self.model.append(LinearBlock(nf, nf_out, norm='none', act='none', use_sn=use_sn))
        self.model = nn.Sequential(*self.model)

    def forward(self, x):
        return self.model(x.view(x.size(0), -1))

def weights_init(init_type='gaussian'):
    def init_fun(m):
        classname = m.__class__.__name__
        if (classname.find('Conv') == 0 or classname.find(
                'Linear') == 0) and hasattr(m, 'weight'):
            if init_type == 'gaussian':
                init.normal_(m.weight.data, 0.0, 0.02)
            elif init_type == 'xavier':
                init.xavier_normal_(m.weight.data, gain=math.sqrt(2))
            elif init_type == 'kaiming':
                init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
            elif init_type == 'orthogonal':
                init.orthogonal_(m.weight.data, gain=math.sqrt(2))
            elif init_type == 'default':
                pass
            else:
                assert 0, "Unsupported initialization: {}".format(init_type)
            if hasattr(m, 'bias') and m.bias is not None:
                init.constant_(m.bias.data, 0.0)
    return init_fun

def assign_adain_params(adain_params, model):
    # assign the adain_params to the AdaIN layers in model
    for m in model.modules():
        if m.__class__.__name__ == "AdaIN2d":
            mean = adain_params[:, :m.num_features]
            std = adain_params[:, m.num_features:2*m.num_features]
            m.bias = mean.contiguous().view(-1)
            m.weight = std.contiguous().view(-1)
            if adain_params.size(1) > 2*m.num_features:
                adain_params = adain_params[:, 2*m.num_features:]

def get_num_adain_params(model):
    # return the number of AdaIN parameters needed by the model
    num_adain_params = 0
    for m in model.modules():
        if m.__class__.__name__ == "AdaIN2d":
            num_adain_params += 2*m.num_features
    return num_adain_params

###################################################################################
### GUIDING NET
cfg = {
    'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
    'vgg19cut': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'N'],
}

class GuidingNet(nn.Module):
    def __init__(self, img_size=64, output_k={'cont': 128, 'disc': 10}, config_idx=0):
        super(GuidingNet, self).__init__()
        # network layers setting
        self.features = make_layers(cfg[config_idx], True)

        self.disc = nn.Linear(512, output_k['disc'])
        self.cont = nn.Linear(512, output_k['cont'])

        self._initialize_weights()

    def forward(self, x, sty=False):
        x = self.features(x)
        x = F.adaptive_avg_pool2d(x, (1, 1))
        flat = x.view(x.size(0), -1)
        cont = self.cont(flat)
        if sty:
            return cont
        disc = self.disc(flat)
        return {'cont': cont, 'disc': disc}

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)

    def moco(self, x):
        x = self.features(x)
        x = F.adaptive_avg_pool2d(x, (1, 1))
        flat = x.view(x.size(0), -1)
        cont = self.cont(flat)
        return cont

    def iic(self, x):
        x = self.features(x)
        x = F.adaptive_avg_pool2d(x, (1, 1))
        flat = x.view(x.size(0), -1)
        disc = self.disc(flat)
        return disc

def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=False)]
            else:
                layers += [conv2d, nn.ReLU(inplace=False)]
            in_channels = v
    return nn.Sequential(*layers)


def reverse(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]
s = ["abaca","acbbc","acca","abba"]
for i in s:
    if reverse(i) in s:
        print(reverse(i))
#giai thich qua code:
#vd [abcda]
#b1 : kiem tra len co != 0 k: r chuyen sang b2
#func tra ve rev[bcda] + a o cuoi
#b2, tg tu, func tra ve rev[cda] + b+a
#tg tu ta dc reverse can tim


import unicorn

X86_CODE32 = b"\x41\x4a"
ADRESS = 0x1000000

mu = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)

# map 2MB on ADRESS, and write code on it
mu.mem_map(ADRESS, 2*1024*1024)
mu.mem_write(ADRESS, X86_CODE32)

# set register values
mu.reg_write(unicorn.x86_const.UC_X86_REG_ECX, 0x1234)
mu.reg_write(unicorn.x86_const.UC_X86_REG_EDX, 0x7890)

# start emulation, and emulate until code length
mu.emu_start(ADRESS, ADRESS + len(X86_CODE32))
print("Emulation done. Below is the CPU context")

# read result values
r_ecx = mu.reg_read(unicorn.x86_const.UC_X86_REG_ECX)
r_edx = mu.reg_read(unicorn.x86_const.UC_X86_REG_EDX)

print(">>> ECX = 0x%x" %r_ecx)
print(">>> EDX = 0x%x" %r_edx)


import json

def task():
    filename = "input.json"
    with open(filename) as f:
        json_data = json.load(f)

    return sorted(json_data, key=lambda item: item["length"])

if __name__ == "__main__":
    data = task()
    print(json.dumps(data, indent=4))

    with open("OUTPUT_FILE", 'w', encoding="utf-8") as f:
        json.dump(data, f, indent=4)

Занятие3/Лабораторные_задания/task2_6/main.py


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

import time
from unittest import mock

from oslotest import base

from sushy_tools.emulator.resources.systems import fakedriver
from sushy_tools import error

UUID = fakedriver.DEFAULT_UUID

class FakeDriverTestCase(base.BaseTestCase):

    def setUp(self):
        super().setUp()
        test_driver_class = fakedriver.FakeDriver.initialize(
            {}, mock.MagicMock())
        self.cache = {}
        with mock.patch('sushy_tools.emulator.memoize.PersistentDict',
                        return_value=self.cache, autospec=True):
            self.test_driver = test_driver_class()

    def test_systems(self):
        self.assertEqual([UUID], self.test_driver.systems)
        self.assertEqual('fake', self.test_driver.name(UUID))
        self.assertEqual(UUID, self.test_driver.uuid('fake'))
        self.assertEqual(UUID, self.test_driver.uuid(UUID))
        self.assertEqual('fake', self.test_driver.name('fake'))
        self.assertRaises(error.NotFound, self.test_driver.uuid, 'foo')
        self.assertRaises(error.NotFound, self.test_driver.name, 'foo')

    @mock.patch('random.randint', autospec=True, return_value=0)
    def test_power_state(self, mock_rand):
        self.assertEqual('Off', self.test_driver.get_power_state(UUID))
        self.test_driver.set_power_state(UUID, 'On')
        self.assertEqual('On', self.test_driver.get_power_state(UUID))
        self.test_driver.set_power_state(UUID, 'ForceOff')
        self.assertEqual('Off', self.test_driver.get_power_state(UUID))

    @mock.patch('random.randint', autospec=True, return_value=1000)
    def test_power_state_delay(self, mock_rand):
        self.assertEqual('Off', self.test_driver.get_power_state(UUID))
        self.test_driver.set_power_state(UUID, 'On')
        self.assertEqual('Off', self.test_driver.get_power_state(UUID))

        new_time = time.time() + 2000
        with mock.patch.object(time, 'time', autospec=True,
                               return_value=new_time):
            self.assertEqual('On', self.test_driver.get_power_state(UUID))

    @mock.patch('random.randint', autospec=True, return_value=1000)
    def test_reboot_delay(self, mock_rand):
        self.cache[UUID]['power_state'] = 'On'

        self.assertEqual('On', self.test_driver.get_power_state(UUID))
        self.test_driver.set_power_state(UUID, 'ForceRestart')
        self.assertEqual('Off', self.test_driver.get_power_state(UUID))

        new_time = time.time() + 2000
        with mock.patch.object(time, 'time', autospec=True,
                               return_value=new_time):
            self.assertEqual('On', self.test_driver.get_power_state(UUID))

    def test_boot_mode(self):
        self.assertEqual('UEFI', self.test_driver.get_boot_mode(UUID))
        self.test_driver.set_boot_mode(UUID, 'legacy')
        self.assertEqual('legacy', self.test_driver.get_boot_mode(UUID))

    def test_boot_device(self):
        self.assertEqual('Hdd', self.test_driver.get_boot_device(UUID))
        self.test_driver.set_boot_device(UUID, 'Cd')
        self.assertEqual('Cd', self.test_driver.get_boot_device(UUID))

    def test_boot_image(self):
        self.assertEqual((None, False, False),
                         self.test_driver.get_boot_image(UUID, 'Cd'))
        self.test_driver.set_boot_image(UUID, 'Cd', 'http://example')
        self.assertEqual(('http://example', True, True),
                         self.test_driver.get_boot_image(UUID, 'Cd'))
        self.assertEqual((None, False, False),
                         self.test_driver.get_boot_image(UUID, 'Hdd'))

    def test_secure_boot(self):
        self.assertFalse(self.test_driver.get_secure_boot(UUID))
        self.test_driver.set_secure_boot(UUID, True)
        self.assertTrue(self.test_driver.get_secure_boot(UUID))

    def test_interface(self):
        self.assertEqual([{'id': '00:5c:52:31:3a:9c',
                           'mac': '00:5c:52:31:3a:9c'}],
                         self.test_driver.get_nics(UUID))


import requests

import pandas as pd
import json

api_base_url = 'http://localhost:5000/predictions'

head = {'Content-Type': 'application/json'}

filename = '/Users/jacobhumber/python_projects/simple_model_api/ml_model/test_head.csv'

d = pd.read_csv(filename)

d_json = json.dumps(d.to_json(orient = 'columns'))

r = requests.post(api_base_url, headers = head, json = d_json)

print(r.json())

'''
r_get = requests.get(api_base_url, headers = head)

print(r_get.content.decode('utf-8'))

r = requests.post(api_base_url, headers = head, json = {'fudge':'fuck'})

print(r.content.decode('utf-8'))

r_get = requests.get(api_base_url, headers = head)

print(r_get.content.decode('utf-8'))
'''


import oci
import json
from operator import itemgetter
from flatten_dict import flatten
from extract_info import get_resource_specific_info

def convert_response_to_dict(oci_response):
    return oci.util.to_dict(oci_response.data)

def extract_value_by_field(obj, key):
    """Pull all values of specified key from nested JSON."""
    arr = []

    def extract(obj, arr, key):
        """Recursively search for values of key in JSON tree."""
        if isinstance(obj, dict):
            for k, v in obj.items():
                if isinstance(v, (dict, list)):
                    extract(v, arr, key)
                elif k == key:
                    if v is not None:
                        arr.append(v)
                    else:
                        arr.append("None")
        elif isinstance(obj, list):
            for searchResult in obj:
                extract(searchResult, arr, key)
        elif isinstance(obj, type(None)):
            arr.append("None")

        return arr

    results = extract(obj, arr, key)
    return results

def get_resource_info_from_search(
    searchResult,
    tenancy_id,
    region_name,
    computeShapeLookupTable,
    clients,
    compartment_kv,
    compartment_parent_ocid_kv,
):
    parent_compartment_name = (
        compartment_kv[compartment_parent_ocid_kv[searchResult["compartment_id"]]]
        if searchResult["compartment_id"] != tenancy_id
        else "ROOT"
    )
    chosen_client = clients[searchResult["resource_type"]]
    try:
        searchResult, res_dict = get_resource_specific_info(
            searchResult, computeShapeLookupTable, chosen_client
        )
    except:
        res_dict = {"resource_specific_info": "No Info"}
        pass

    norm_item_dict = {
        "region": region_name,
        "availability_domain": searchResult["availability_domain"],
        "resource_type": searchResult["resource_type"],
        "shape": searchResult["shape"],
        "OCPU_Qty": searchResult["OCPU_Qty"],
        "license_model": searchResult["license_model"],
        "display_name": searchResult["display_name"],
        "resource_ocid": searchResult["identifier"],
        "compartment_id": searchResult["compartment_id"],
        "compartment_name": compartment_kv[searchResult["compartment_id"]],
        "parent_compartment_name": parent_compartment_name,
        "CreatedBy": ("").join(extract_value_by_field(searchResult, "CreatedBy")),
        "CreatedOn": searchResult["time_created"]
    }
    norm_item_dict.update(res_dict)

    return norm_item_dict


# Job Costing Script for Construction Companies
# by @rpriven

# This is a simple job costing script that asks you financial questions on a job
# and calculates your overhead, expenses and reports back your profit and commission

expenses = list()

print('\nJob Costing Report\n')
# Asks user for Customer Name / Job
customer = input('Enter the customer name:  ')
while not customer:
    print('Error:  You must enter a customer name.')
    customer = input('Enter the customer name:  ')

# Asks user for total amount of job $
price = input('Enter the total amount of the job / the amount paid by the customer:  $ ')
while not price or price == '' or price == '0':
    print('You cannot have a total job price of $0')
    price = input('Enter the total amount of the job / the amount paid by the customer:  $ ')
price = int(price)

# Asks user for Overhead %
overhead = input('Enter the percentage of overhead for this job:  ')
while not overhead:  # or while not isnumeric(overhead)
    print('Error:  Surely you had some overhead on this job.  If there truly was no overhead, enter 0')
    overhead = input('Enter the percentage of overhead for this job:  ')

# Asks user for permit cost
permit = input('Enter the cost of permit expenses for this job:  ')
while not permit:
    print("You didn't pull a permit on this job?  If not, then enter 0")
    permit = input('Enter the cost of permit expenses for this job:  ')
expenses.append(int(permit))

# Asks user for materials cost
materials = input('Enter the cost of materials for this job:  ')
while not materials:
    print('Error:  No materials were entered.')
    materials = input('Enter the cost of materials for this job:  ')
expenses.append(int(materials))

# Yes = ['Yes', 'yes', 'y']
# No = ['No', 'no', 'n']
# if m_add in Yes:

# Asks user if there additional material costs
m_add = input('Are there more material expenses to enter?  [ Y / N ]  ')
if m_add == 'Y' or m_add == 'y' or m_add == 'Yes' or m_add == 'yes':
    m_add = True
elif m_add == 'N' or m_add == 'n' or m_add == 'No' or m_add == 'no':
    m_add = False
else:
    print('Please enter Y or N for Yes or No')
    m_add = input('Are there more material expenses to enter?  [ Y / N ]  ')
# if yes, asks for amount
while m_add is True:
    more_materials = input('Enter the additional material cost (or enter "0" or "done" to stop):  ')
    expenses.append(int(more_materials))
    if more_materials == '0':
        break
    elif more_materials == 'done':
        expenses.pop()
        break

# Asks user for labor costs
labor = input('Enter the cost of labor for this job:  ')
while not labor:
    print('Error:  No labor expenses were entered.')
    labor = input('Enter the cost of labor for this job:  ')
expenses.append(int(labor))

# Asks for misc costs
misc_add = input('Are there any additional / miscellaneous expenses to add?  [ Y / N ]  ')
# while Yes in misc_add:
if misc_add == 'Y' or misc_add == 'y' or misc_add == 'Yes' or misc_add == 'yes':
    misc_add = True
elif misc_add == 'N' or misc_add == 'n' or misc_add == 'No' or misc_add == 'no':
    misc_add = False
else:
    print('Please enter Y or N for Yes or No')
    misc_add = input('Are there any additional / miscellaneous expenses to add?  [ Y / N ]  ')
while misc_add is True:
    misc = input('Enter the additional material cost (or enter "0" or "done" to stop):  ')
    expenses.append(int(misc))
    if misc == '0':
        break
    elif misc == 'done':
        expenses.pop()
        break

# Commission
commission = input('What percentage of the profit does the Salesperson get on this job for commission?  ')
while not commission:  # or while not isnumeric(overhead)
    print("Hey, I can understand why you wouldn't want to pay your salesperson on this job.  If there is actually no commission to be paid, enter 0")
    commission = input('What percentage of the profit does the Salesperson get on this job for commission?  ')

cost = sum(expenses)

overhead = int(overhead) / 100
overhead = price * overhead

profit = price - overhead - cost

commission = int(commission) / 100
commission = profit * commission

# Output
print('\nJob Costing Report for', customer,'\n')
print(f'Total Job Price:  ${price:,.2f}')
print(f'Overhead:  ${overhead:,.2f}')
print(f'Expenses:  ${cost:,.2f}')
print(f'Profit:  ${profit:,.2f}')

profit = profit - commission

print('\nCongratulations!  On the job for: ', customer + ':')
print(f'Your company made ${profit:,.2f} and your Salesperson made ${commission:,.2f}')


from flask import Blueprint, jsonify, request, abort
from datetime import datetime
from medioex import do_write, di_read, ao_write, ai_read, temp_read

api = Blueprint('api', __name__, url_prefix='/api')

OUTPUTS = {}

# DIGITAL INPUT ROUTES

@api.route('/di/<int:pin>/read', methods=['GET'])
def di_read_api(pin):
    if 1 > pin or pin > 16:
        return jsonify({
            'status': 'ERROR',
            'message': 'Digital input pins for MedIOEx must be in [1, 16]'})

    result = di_read(pin)
    return jsonify({'status': 'OK',
                    'type': 'di',
                    'action': 'read',
                    'pin': pin,
                    'value': result})

# DIGITAL OUTPUT ROUTES

@api.route('/do/<int:pin>/read', methods=['GET'])
def do_read_api(pin):
    if 1 > pin or pin > 12:
        return jsonify({
            'status': 'ERROR',
            'message': 'Digital output pins for MedIOEx must be in [1, 12]'})
    return jsonify({'status': 'OK',
                    'type': 'do',
                    'action': 'read',
                    'pin': pin,
                    'value': OUTPUTS['do'][pin]})

@api.route('/do/<int:pin>/write', methods=['GET'])
def do_write_api(pin):
    val = int(request.args.get('val'))
    if 1 > pin or pin > 12:
        return jsonify({
            'status': 'ERROR',
            'message': 'Digital output pins for MedIOEx must be in [1, 12]'})
    elif val not in (0, 1):
        return jsonify({'status': 'ERROR',
                        'message': 'Digital outputs only accept 0 or 1.'})
    do_write(pin, val)
    OUTPUTS['do'][pin] = val
    return jsonify({'status': 'OK',
                    'type': 'do',
                    'action': 'write',
                    'pin': pin,
                    'value': val})

@api.route('/do/<int:pin>/set', methods=['GET'])
def do_set_api(pin):
    if 1 > pin or pin > 12:
        return jsonify({
            'status': 'ERROR',
            'message': 'Digital output pins for MedIOEx must be in [1, 12]'})
    do_write(pin, 1)
    OUTPUTS['do'][pin] = 1
    return jsonify({'status': 'OK',
                    'type': 'do',
                    'action': 'set',
                    'pin': pin,
                    'value': 1})

@api.route('/do/<int:pin>/reset', methods=['GET'])
def do_reset_api(pin):
    if 1 > pin or pin > 12:
        return jsonify({
            'status': 'ERROR',
            'message': 'Digital output pins for MedIOEx must be in [1, 12]'})
    do_write(pin, 0)
    OUTPUTS['do'][pin] = 0
    return jsonify({'status': 'OK',
                    'type': 'do',
                    'action': 'reset',
                    'pin': pin,
                    'value': 0})

# RELAY OUTPUT ROUTES

@api.route('/ro/<int:pin>/read', methods=['GET'])
def ro_read_api(pin):
    if 13 > pin or pin > 16:
        return jsonify({
            'status': 'ERROR',
            'message': 'Relay pins for MedIOEx must be in [13, 16]'})

    return jsonify({'status': 'OK',
                    'type': 'ro',
                    'action': 'read',
                    'pin': pin,
                    'value': OUTPUTS['ro'][pin]})

@api.route('/ro/<int:pin>/write', methods=['GET'])
def ro_write_api(pin):
    val = int(request.args.get('val'))
    if 13 > pin or pin > 16:
        return jsonify({
            'status': 'ERROR',
            'message': 'Relay pins for MedIOEx must be in [13, 16]'})

    elif val not in (0, 1):
        return jsonify({'status': 'ERROR',
                        'message': 'Relay outputs only accept 0 or 1.'})

    do_write(pin, val)
    OUTPUTS['ro'][pin] = val
    return jsonify({'status': 'OK',
                    'type': 'ro',
                    'action': 'write',
                    'pin': pin,
                    'value': val})

@api.route('/ro/<int:pin>/set', methods=['GET'])
def ro_set_api(pin):
    if 13 > pin or pin > 16:
        return jsonify({
            'status': 'ERROR',
            'message': 'Relay pins for MedIOEx must be in [13, 16]'})
    do_write(pin, 1)
    OUTPUTS['ro'][pin] = 1
    return jsonify({'status': 'OK',
                    'type': 'ro',
                    'action': 'set',
                    'pin': pin,
                    'value': 1})

@api.route('/ro/<int:pin>/reset', methods=['GET'])
def ro_reset_api(pin):
    if 13 > pin or pin > 16:
        return jsonify({
            'status': 'ERROR',
            'message': 'Relay pins for MedIOEx must be in [13, 16]'})
    do_write(pin, 0)
    OUTPUTS['ro'][pin] = 0
    return jsonify({'status': 'OK',
                    'type': 'ro',
                    'action': 'reset',
                    'pin': pin,
                    'value': 0})

# ANALOG INPUT ROUTES

@api.route('/ai/<int:pin>/read', methods=['GET'])
def ai_read_api(pin):
    ss = request.args.get('start', 0.0)
    se = request.args.get('end', 4095.0)
    try:
        ss = float(ss)
        se = float(se)
    except ValueError:
        abort(400)

    if 1 > pin or pin > 4:
        return jsonify({
            'status': 'ERROR',
            'message': 'Analog input pins for MedIOEx must be in [1, 4]'})

    result = ai_read(pin)

    # The line below is just a linear transformation.
    #
    #      (nv - ns)   (sv - ss)
    #      --------- = ---------
    #      (ne - ns)   (se - ss)
    #
    # ns = normal start (0)
    # ne = normal end (4095)
    # nv = value got via ai_read [0, 4095] ~= [0, 4096)
    # ss = scaled start (given by user)
    # se = scaled end (given by user)
    # sv = value demanded
    sv = ss + (result - 0) * (se - ss) / (4095 - 0)

    return jsonify({'status': 'OK',
                    'type': 'ai',
                    'action': 'read',
                    'pin': pin,
                    'start': ss,
                    'end': se,
                    'value': sv})

# ANALOG OUTPUT ROUTES

@api.route('/ao/<int:pin>/read', methods=['GET'])
def ao_read_api(pin):
    ss = request.args.get('start', 0.0)
    se = request.args.get('end', 4095.0)
    try:
        ss = float(ss)
        se = float(se)
    except ValueError:
        abort(400)

    if 1 > pin or pin > 4:
        return jsonify({
            'status': 'ERROR',
            'message': 'Analog output pins for MedIOEx must be in [1, 4]'})
    result = OUTPUTS['ao'][pin]

    # Check the formula at ai_read_api before changing the line below
    sv = ss + (result - 0) * (se - ss) / (4095 - 0)

    return jsonify({'status': 'OK',
                    'type': 'ao',
                    'action': 'read',
                    'pin': pin,
                    'start': ss,
                    'end': se,
                    'value': sv})

@api.route('/ao/<int:pin>/write', methods=['GET'])
def ao_write_api(pin):
    ss = request.args.get('start', 0.0)
    se = request.args.get('end', 4095.0)
    try:
        ss = float(ss)
        se = float(se)
    except ValueError:
        abort(400)
    sv = int(request.args.get('val'))

    if 1 > pin or pin > 4:
        return jsonify({
            'status': 'ERROR',
            'message': 'Analog output pins for MedIOEx must be in [1, 4]'})
    elif not (ss <= sv <= se or ss >= sv >= se):
        return jsonify({
            'status': 'ERROR',
            'message': 'Value should be between {} and {}.'.format(ss, se)})

    nv = 0 + (4095 - 0) * (sv - ss) / (se - ss)
    val = nv

    # Check the formula at ai_read_api before changing the line below
    ao_write(pin, int(nv))
    OUTPUTS['ao'][pin] = val

    return jsonify({'status': 'OK',
                    'type': 'ao',
                    'action': 'write',
                    'pin': pin,
                    'value': sv})

# TEMPERATURE

@api.route('/temperature/read', methods=['GET'])
def get_temperature():
    result = temp_read(1)
    return jsonify({'status': 'OK',
                    'type': 'temperature',
                    'action': 'read',
                    'value': result})

# ALL OUTPUTS

@api.route('/reset', methods=['GET'])
def reset_all_outputs():
    for pin in range(1, 5):
        ao_write(pin, 0)
        OUTPUTS['ao'][pin] = 0

    for pin in range(1, 13):
        do_write(pin, 0)
        OUTPUTS['do'][pin] = 0

    for pin in range(13, 17):
        do_write(pin, 0)
        OUTPUTS['ro'][pin] = 0

    return jsonify({'status': 'OK',
                    'action': 'reset',
                    'value': None})

# STATUS

@api.route('/status', methods=['GET'])
def status():
    status = OUTPUTS.copy()

    inputs = {
        'di': {},
        'ai': {}
    }
    for pin in range(1, 17):
        inputs['di'][pin] = di_read(pin)
    for pin in range(1, 5):
        inputs['ai'][pin] = ai_read(pin)
    status.update(inputs)

    status['temperature'] = temp_read(1)
    status['uptime'] = datetime.now().timestamp() - OUTPUTS['start_timestamp']

    return jsonify({'status': 'OK',
                    'action': 'status',
                    'value': status})


'''

# 判断任意输入一个数字是不是偶数
num = int(input("请输入一个数字"))
if num % 2 == 0:
    print("您输入的这个是是偶数")
else:
    print("您输入的不是偶数")
'''

# 作业：从控制台输入一个三位数，如果是水仙花数这输出 153 = 1^3 + 5^3 + 3^3
# 作业：从控制台输入一个五位数，如果是回文数，这输出，11111  12321   12221  对称这种
# 作业：从控制台输入两个数，比较大小，输出较大的值
# 作业：从控制台输入三个数，输出较大的值
'''
num = int(input("请输入一个数"))
num1 = num // 100
num2 = num // 10 % 10
num3 = num % 10

if num == num1 ** 3 + num2 ** 3 + num3 ** 3:
    print("这是水仙花数")
else:
    print("这不是水仙花数")

a = int(input("请输入一个五位数"))
a1 = a // 10000
a2 = a //1000 % 10
a3 = a // 10 % 10
a4 = a % 10

if a1 == a4:
    if a2 == a3:
        print("这是一个回文数")
    else:
        print("这不是一个回文数")
else:
    print("这不是一个回文数")

'''

'''
    第二种写法

    a = int(input("请输入一个三位数"))
    a1 = a //10000
    a2 = a %10
    if a1 != a2:
        print(no)
    else:
    ----和上面差不多
'''

'''
m = int(input("请输入比较大小的第一个数"))
n = int(input("请输入比较大小的第二个数"))
if m > n:
    print(m)
elif m == n:
    print("两个数相同,其值等于",m)
else:
    print(n)
'''
'''
if m > n:
    if m > i:
        print(m)
    else:
        print(i)
elif n > m:
    if n > i:
        print(n)
    else:
        print(i)
elif m > i:
    if m > n:
        print(m)
    else:
        print(n)

'''
m = int(input("请输入第一个数"))
n = int(input("请输入第一个数"))
i = int(input("请输入第一个数"))

max = m
if n > max:
    max = n
if i > n:
    max = i
print("max = ",max)

Python课程代码/课程学习代码/day1-语法基础操作/011-if语句练习.py


from hindemith.types import hmarray
from hindemith.operations.conv import ConvForward
from hindemith.operations.relu import ReluForward
from hindemith.operations.pool import PoolForward
from hindemith.operations.lrn import LrnForward
from hindemith.operations.softmax import SoftmaxForward
from hindemith.core import compose
from hindemith.clibs.clblas import sgemm
import caffe
import numpy as np

prototxt = "models/alexnet-ng/deploy.prototxt"
caffemodel = "models/alexnet-ng/alexnet-ng.caffemodel"

# caffe.set_mode_gpu()
caffe_net = caffe.Net(prototxt, caffemodel, caffe.TEST)

conv1_filters = caffe_net.params['conv1'][0].data.view(hmarray)
conv1_bias = caffe_net.params['conv1'][1].data.view(hmarray)
conv1 = hmarray.zeros(caffe_net.blobs['conv1'].data.shape)

norm1 = hmarray.zeros(caffe_net.blobs['norm1'].data.shape)
norm1_scale = hmarray.zeros(norm1.shape)

pool1 = hmarray.zeros(caffe_net.blobs['pool1'].data.shape)
pool1_mask = hmarray.zeros(pool1.shape)

conv2_filters = caffe_net.params['conv2'][0].data.view(hmarray)
conv2_bias = caffe_net.params['conv2'][1].data.view(hmarray)
conv2 = hmarray.zeros(caffe_net.blobs['conv2'].data.shape)

norm2 = hmarray.zeros(caffe_net.blobs['norm2'].data.shape)
norm2_scale = hmarray.zeros(norm1.shape)

pool2 = hmarray.zeros(caffe_net.blobs['pool2'].data.shape)
pool2_mask = hmarray.zeros(pool2.shape)

conv3_filters = caffe_net.params['conv3'][0].data.view(hmarray)
conv3_bias = caffe_net.params['conv3'][1].data.view(hmarray)
conv3 = hmarray.zeros(caffe_net.blobs['conv3'].data.shape)

conv4_filters = caffe_net.params['conv4'][0].data.view(hmarray)
conv4_bias = caffe_net.params['conv4'][1].data.view(hmarray)
conv4 = hmarray.zeros(caffe_net.blobs['conv4'].data.shape)

conv5_filters = caffe_net.params['conv5'][0].data.view(hmarray)
conv5_bias = caffe_net.params['conv5'][1].data.view(hmarray)
conv5 = hmarray.zeros(caffe_net.blobs['conv5'].data.shape)

pool5 = hmarray.zeros(caffe_net.blobs['pool5'].data.shape)
pool5_mask = hmarray.zeros(pool2.shape)

fc6_filters = caffe_net.params['fc6'][0].data.view(hmarray)
fc6_bias = caffe_net.params['fc6'][1].data.view(hmarray)
fc6_bias_multiplier = hmarray((1, pool5.shape[0]))
fc6_bias_multiplier.fill(1)
fc6_bias_multiplier.sync_ocl()
fc6 = hmarray.zeros(caffe_net.blobs['fc6'].data.shape)

fc7_filters = caffe_net.params['fc7'][0].data.view(hmarray)
fc7_bias = caffe_net.params['fc7'][1].data.view(hmarray)
fc7_bias_multiplier = hmarray((1, fc6.shape[0]))
fc7_bias_multiplier.fill(1)
fc7_bias_multiplier.sync_ocl()
fc7 = hmarray.zeros(caffe_net.blobs['fc7'].data.shape)

fc8_filters = caffe_net.params['fc8'][0].data.view(hmarray)
fc8_bias = caffe_net.params['fc8'][1].data.view(hmarray)
fc8_bias_multiplier = hmarray((1, fc7.shape[0]))
fc8_bias_multiplier.fill(1)
fc8_bias_multiplier.sync_ocl()
fc8 = hmarray.zeros(caffe_net.blobs['fc8'].data.shape)

prob = hmarray.zeros(caffe_net.blobs['prob'].data.shape)

local_size = 5
alpha = 0.0001
beta = 0.75

@compose
def forward(data):
    global fc6, fc7, fc8
    conv1 = ConvForward(data, conv1_filters, conv1_bias,
                        kernel_size=(11, 11), padding=(0, 0),
                        stride=(4, 4))
    conv1 = ReluForward(conv1)
    norm1, norm1_scale = LrnForward(conv1, alpha=alpha, beta=beta,
                                    local_size=local_size, k=1)
    pool1, pool1_mask = PoolForward(norm1, kernel_size=(3, 3),
                                    padding=(0, 0), stride=(2, 2))

    conv2 = ConvForward(pool1, conv2_filters, conv2_bias,
                        kernel_size=(5, 5), padding=(2, 2),
                        stride=(1, 1))
    conv2 = ReluForward(conv2)
    norm2, norm2_scale = LrnForward(conv2, alpha=alpha, beta=beta,
                                    local_size=local_size, k=1)
    pool2, pool2_mask = PoolForward(norm2, kernel_size=(3, 3),
                                    padding=(0, 0), stride=(2, 2))

    conv3 = ConvForward(pool2, conv3_filters, conv3_bias,
                        kernel_size=(3, 3), padding=(1, 1),
                        stride=(1, 1))
    conv3 = ReluForward(conv3)

    conv4 = ConvForward(conv3, conv4_filters, conv4_bias,
                        kernel_size=(3, 3), padding=(1, 1),
                        stride=(1, 1))
    conv4 = ReluForward(conv4)

    conv5 = ConvForward(conv4, conv5_filters, conv5_bias,
                        kernel_size=(3, 3), padding=(1, 1),
                        stride=(1, 1))
    conv5 = ReluForward(conv5)
    pool5, pool5_mask = PoolForward(conv5, kernel_size=(3, 3),
                                    padding=(0, 0), stride=(2, 2))

    N = fc6.shape[1]
    K = np.prod(pool5.shape[1:])
    M = pool5.shape[0]
    sgemm(False, True, 1.0, pool5, 0, K, fc6_filters, 0, K, 0.0,
          fc6, 0, N, M, N, K)
    sgemm(False, False, 1.0, fc6_bias_multiplier, 0, 1, fc6_bias, 0, N,
          1.0, fc6, 0, N, M, N, 1)

    fc6 = ReluForward(fc6)

    N = fc7.shape[1]
    K = np.prod(fc6.shape[1:])
    M = fc6.shape[0]
    sgemm(False, True, 1.0, fc6, 0, K, fc7_filters, 0, K, 0.0,
          fc7, 0, N, M, N, K)
    sgemm(False, False, 1.0, fc7_bias_multiplier, 0, 1, fc7_bias, 0, N,
          1.0, fc7, 0, N, M, N, 1)
    fc7 = ReluForward(fc7)

    N = fc8.shape[1]
    K = np.prod(fc7.shape[1:])
    M = fc7.shape[0]
    sgemm(False, True, 1.0, fc7, 0, K, fc8_filters, 0, K, 0.0,
          fc8, 0, N, M, N, K)
    sgemm(False, False, 1.0, fc8_bias_multiplier, 0, 1, fc8_bias, 0, N,
          1.0, fc8, 0, N, M, N, 1)
    prob = SoftmaxForward(fc8)
    return prob

if __name__ == '__main__':
    im = caffe.io.load_image('data/cat.jpg')
    transformer = caffe.io.Transformer(
        {'data': caffe_net.blobs['data'].data.shape})
    transformer.set_mean(
        'data', np.load('models/ilsvrc_2012_mean.npy').mean(1).mean(1))
    transformer.set_transpose('data', (2, 0, 1))
    transformer.set_channel_swap('data', (2, 1, 0))
    transformer.set_raw_scale('data', 255.0)

    data = np.asarray(
        [transformer.preprocess('data', im)]).view(hmarray)
    data.sync_ocl()
    caffe_net.forward_all(data=data)
    forward(data)
    # print(np.argmax(prob[0]))
    # print(np.argmax(caffe_net.blobs['prob'].data[0]))
    for blob in caffe_net.blobs.keys():
        print("Checking blob {}".format(blob))
        caffe_blob = caffe_net.blobs[blob].data
        blob = globals()[blob]
        blob.sync_host()
        np.testing.assert_array_almost_equal(blob, caffe_blob,
                                             decimal=3)


from AppPosts import views
from django.urls import path

app_name= 'AppPosts'

urlpatterns = [
    path("", views.home, name='home'),
    path('liked/<pk>/', views.liked, name='liked'),
    path('unliked/<pk>/',views.unliked, name='unliked'),

]


#!/usr/bin/env python3

# run the actual simulation

import csd

# initialize the simulation
a = csd.CSD(
        pedigree_file_name="Lhet_adapted.csv"
        ,artificial=False # it is not an artificial experiment we try to generate
        ,generations=4 # maximum number of generations the experiment lasts
        ,nr_loci=1 # number of csd loci
        ,survival=1 # survival probability of diploid males
        ,linkage=0.5) # when arg_nr_loci > 1, linkage between the different csd loci [ 0: full linkage, 0.5 no linkage

# simulate the actual thing
a.simulate()


import pytest

@pytest.mark.django_db
def test_retrieve_room(client, room):
    expected_response = {
        "id": room.pk,
        "number": '1',
        "price": 100,
        "beds": 1
    }

    response = client.get(
        f"/rooms/{room.pk}/"
    )

    assert response.status_code == 200
    assert response.data == expected_response


'''
给定一个候选人编号的集合 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意：解集不能包含重复的组合。
#不可以包含重复的组合打赏曹张新村
'''
from typing import List

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        path = []
        #repeat =[]
        def backtrack(candidates, target, sum, startindex):
            if sum == target:
                res.append(path[:])
            for i in range(startindex, len(candidates)):
                if sum + candidates[i] > target: return
                #i>startindex代表着什么意思？i>startindex,代表着同一数层。i=startindex代表同一树枝。
                if i > startindex and candidates[i] == candidates[i - 1]: continue
                #[[1, 1, 3], [1, 2, 2], [2, 3], [5]]
                #这两种去重方式有什么不同？
                #用repeat就仅代表着同一树枝不能有重复元素。
                # if candidates[i] in repeat:
                #     continue
                #[[2, 3], [2, 3], [5]]

                #repeat.append(candidates[i])
                #if candidates[i] in repeat:continue
                sum += candidates[i]
                path.append(candidates[i])

                backtrack(candidates, target, sum, i + 1)
                sum -= candidates[i]
                #repeat.pop()
                path.pop()

        candidates = sorted(candidates)
        backtrack(candidates, target, 0, 0)
        return res

A =Solution()
candidates=[1,2,3,1,5,2]
target = 5
print(A.combinationSum2(candidates,target))


""" project.py: This is where Pandas functions go. All psycopg2 functions
    should be written in the db module and imported here when needed.
"""
import datetime
import pandas as pd
import numpy as np
import psycopg2
from db import insert_companies, insert_genres, insert_ratings, insert_film_genre
from db import insert_film, connect, insert_film_company, do_query
from helpers import convert_date_to_postgres

# Get our csv as a dataframe and select the columns we want
df = pd.read_csv('movies.csv')
films = df[["name","score","released","budget", "gross", "votes", "rating", "runtime"]]

# Get the distinct ratings in the CSV and add them to the ratings table
ratings_series = df[["rating"]]
ratings = ratings_series.rating.unique()
list_of_ratings = list(ratings) # Covert the numpy array to a Python List

# Get the writers, directors, and stars into one list
all_people = df[["writer", "director", "star"]]
all_people = all_people.stack()
all_people = pd.unique(all_people)
all_people = list(set(all_people))

# Get films, dates and people in a list by writer, direcotr, star
film_writers = df[["name", "released", "writer"]]
stars = df[["name", "released", "star"]]
directors = df[["name", "released", "director"]]

film_writers = film_writers.values.tolist()
directors = directors.values.tolist()
stars = stars.values.tolist()

df2 = pd.read_csv('movies.csv')
company = df2[["company"]]
genre = df2[["genre"]]

def populate_films(films_df):
    """ Takes a dataframe of films and stores each row in the database by
        passing each row into the insert_film() function. Pandas gives an empty
        column in a row the nan (float type). If an empty value is present,
        None keyword should be used to represent null in postgres.
        The film, and ratings table must be created prior to running this
        function and the ratings table must be populated.
    """
    conn = connect()
    cur = conn.cursor()
    for row in films_df.itertuples():
        score = None
        date = None
        budget = None
        gross = None
        votes = None
        rating = None
        runtime = None

        # There is a rating
        if (type(row[7]) != float):
            rating = row[7]

        # there is a score
        if (np.isnan(row[2]) == False):

            score = row[2]

        # there is a release date.
        if type(row[3]) != float:
            date = convert_date_to_postgres(row[3])

        # there is a budget
        if (np.isnan(row[4]) == False):
            budget = row[4]

        # there is a gross
        if (np.isnan(row[5]) == False):
            gross = row[5]

        # There are votes
        if (np.isnan(row[6]) == False):
            votes = row[6]

        # There is a runtime
        if (np.isnan(row[8]) == False):
            runtime = row[8]

        # insert the row
        insert_film(row[1], score, date, budget, gross, votes, rating, runtime, cur)

    conn.commit()
    conn.close()

"""
# Populate film_persons table
film_writers = df[["name", "released", "writer", "director", "star"]]
all_films = all_films.drop_duplicates()
print (all_films.head())
"""


# -*- coding: utf-8 -*-
# @Time    : 2020/3/3 22:52
# @Author  : YYLin
# @Email   : 854280599@qq.com
# @File    : VGG_19.py
# -*- coding: utf-8 -*-
import tensorflow as tf

def maxPoolLayer(x, kHeight, kWidth, strideX, strideY, name, padding="SAME"):
    return tf.nn.max_pool(x, ksize=[1, kHeight, kWidth, 1],
                          strides=[1, strideX, strideY, 1], padding=padding, name=name)

def dropout(x, keepPro, name=None):
    return tf.nn.dropout(x, keepPro, name)

def fcLayer(x, inputD, outputD, reluFlag, name):
    with tf.variable_scope(name) as scope:
        w = tf.get_variable("w", shape=[inputD, outputD], dtype="float")
        b = tf.get_variable("b", [outputD], dtype="float")
        out = tf.nn.xw_plus_b(x, w, b, name=scope.name)
        if reluFlag:
            return tf.nn.relu(out)
        else:
            return out

def convLayer(x, kHeight, kWidth, strideX, strideY, featureNum, name, padding="SAME"):
    channel = int(x.get_shape()[-1])
    with tf.variable_scope(name) as scope:
        w = tf.get_variable("w", shape=[kHeight, kWidth, channel, featureNum])
        b = tf.get_variable("b", shape=[featureNum])
        featureMap = tf.nn.conv2d(x, w, strides=[1, strideY, strideX, 1], padding=padding)
        out = tf.nn.bias_add(featureMap, b)
        return tf.nn.relu(tf.reshape(out, featureMap.get_shape().as_list()), name=scope.name)

class VGG19(object):
    def __init__(self, x, keepPro, classNum):
        self.X = x
        self.KEEPPRO = keepPro
        self.CLASSNUM = classNum
        self.begin_VGG_19()

    def begin_VGG_19(self):
        """build model"""
        conv1_1 = convLayer(self.X, 3, 3, 1, 1, 64, "conv1_1")
        conv1_2 = convLayer(conv1_1, 3, 3, 1, 1, 64, "conv1_2")
        pool1 = maxPoolLayer(conv1_2, 2, 2, 2, 2, "pool1")

        conv2_1 = convLayer(pool1, 3, 3, 1, 1, 128, "conv2_1")
        conv2_2 = convLayer(conv2_1, 3, 3, 1, 1, 128, "conv2_2")
        pool2 = maxPoolLayer(conv2_2, 2, 2, 2, 2, "pool2")

        conv3_1 = convLayer(pool2, 3, 3, 1, 1, 256, "conv3_1")
        conv3_2 = convLayer(conv3_1, 3, 3, 1, 1, 256, "conv3_2")
        conv3_3 = convLayer(conv3_2, 3, 3, 1, 1, 256, "conv3_3")
        conv3_4 = convLayer(conv3_3, 3, 3, 1, 1, 256, "conv3_4")
        pool3 = maxPoolLayer(conv3_4, 2, 2, 2, 2, "pool3")

        conv4_1 = convLayer(pool3, 3, 3, 1, 1, 512, "conv4_1")
        conv4_2 = convLayer(conv4_1, 3, 3, 1, 1, 512, "conv4_2")
        conv4_3 = convLayer(conv4_2, 3, 3, 1, 1, 512, "conv4_3")
        conv4_4 = convLayer(conv4_3, 3, 3, 1, 1, 512, "conv4_4")
        pool4 = maxPoolLayer(conv4_4, 2, 2, 2, 2, "pool4")

        conv5_1 = convLayer(pool4, 3, 3, 1, 1, 512, "conv5_1")
        conv5_2 = convLayer(conv5_1, 3, 3, 1, 1, 512, "conv5_2")
        conv5_3 = convLayer(conv5_2, 3, 3, 1, 1, 512, "conv5_3")
        conv5_4 = convLayer(conv5_3, 3, 3, 1, 1, 512, "conv5_4")
        pool5 = maxPoolLayer(conv5_4, 2, 2, 2, 2, "pool5")

        fcIn = tf.reshape(pool5, [-1, 4 * 4 * 512])
        fc6 = fcLayer(fcIn, 4 * 4 * 512, 4096, True, "fc6")
        dropout1 = dropout(fc6, self.KEEPPRO)

        fc7 = fcLayer(dropout1, 4096, 4096, True, "fc7")
        dropout2 = dropout(fc7, self.KEEPPRO)

        self.fc8 = fcLayer(dropout2, 4096, self.CLASSNUM, True, "fc8")