import torch
import torch.nn as nn
from .neurons import _SpikeTensor, _SpikeTorchConv, LIF

class Synaptic(LIF):
    """
    2nd order leaky integrate and fire neuron model accounting for synaptic
    conductance.
    The synaptic current jumps upon spike arrival, which causes a jump in
    membrane potential.
    Synaptic current and membrane potential decay exponentially with rates
    of alpha and beta, respectively.
    For :math:`U[T] > U_{\\rm thr} ⇒ S[T+1] = 1`.

    If `reset_mechanism = "subtract"`, then :math:`U[t+1]` will have
    `threshold` subtracted from it whenever the neuron emits a spike:

    .. math::

            I_{\\rm syn}[t+1] = αI_{\\rm syn}[t] + I_{\\rm in}[t+1] \\\\
            U[t+1] = βU[t] + I_{\\rm syn}[t+1] - RU_{\\rm thr}

    If `reset_mechanism = "zero"`, then :math:`U[t+1]` will be set to `0`
    whenever the neuron emits a spike:

    .. math::

            I_{\\rm syn}[t+1] = αI_{\\rm syn}[t] + I_{\\rm in}[t+1] \\\\
            U[t+1] = βU[t] + I_{\\rm syn}[t+1] - R(βU[t] + I_{\\rm syn}[t+1])

    * :math:`I_{\\rm syn}` - Synaptic current
    * :math:`I_{\\rm in}` - Input current
    * :math:`U` - Membrane potential
    * :math:`U_{\\rm thr}` - Membrane threshold
    * :math:`R` - Reset mechanism: if active, :math:`R = 1`, otherwise \
        :math:`R = 0`
    * :math:`α` - Synaptic current decay rate
    * :math:`β` - Membrane potential decay rate

    Example::

        import torch
        import torch.nn as nn
        import snntorch as snn

        alpha = 0.9
        beta = 0.5

        # Define Network
        class Net(nn.Module):
            def __init__(self, num_inputs, num_hidden, num_outputs):
                super().__init__()

                # initialize layers
                self.fc1 = nn.Linear(num_inputs, num_hidden)
                self.lif1 = snn.Synaptic(alpha=alpha, beta=beta)
                self.fc2 = nn.Linear(num_hidden, num_outputs)
                self.lif2 = snn.Synaptic(alpha=alpha, beta=beta)

            def forward(self, x, syn1, mem1, spk1, syn2, mem2):
                cur1 = self.fc1(x)
                spk1, syn1, mem1 = self.lif1(cur1, syn1, mem1)
                cur2 = self.fc2(spk1)
                spk2, syn2, mem2 = self.lif2(cur2, syn2, mem2)
                return syn1, mem1, spk1, syn2, mem2, spk2

    :param alpha: synaptic current decay rate. Clipped between 0 and 1
        during the forward-pass. May be a single-valued tensor (i.e.,
        equal decay rate for all neurons in a layer), or multi-valued
        (one weight per neuron).
    :type alpha: float or torch.tensor

    :param beta: membrane potential decay rate. Clipped between 0 and 1
        during the forward-pass. May be a single-valued tensor (i.e., equal
        decay rate for all neurons in a layer), or multi-valued (one weight
        per neuron).
    :type beta: float or torch.tensor

    :param threshold: Threshold for :math:`mem` to reach in order to generate
        a spike `S=1`. Defaults to 1
    :type threshold: float, optional

    :param spike_grad: Surrogate gradient for the term dS/dU. Defaults to None
        (corresponds to Heaviside surrogate gradient. See `snntorch.surrogate`
        for more options)
    :type spike_grad: surrogate gradient function from snntorch.surrogate,
        optional

    :param surrogate_disable: Disables surrogate gradients regardless of
        `spike_grad` argument. Useful for ONNX compatibility. Defaults
        to False
    :type surrogate_disable: bool, Optional

    :param init_hidden: Instantiates state variables as instance variables.
        Defaults to False
    :type init_hidden: bool, optional

    :param inhibition: If `True`, suppresses all spiking other than the
        neuron with the highest state. Defaults to False
    :type inhibition: bool, optional

    :param learn_alpha: Option to enable learnable alpha. Defaults to False
    :type learn_alpha: bool, optional

    :param learn_beta: Option to enable learnable beta. Defaults to False
    :type learn_beta: bool, optional

    :param learn_threshold: Option to enable learnable threshold. Defaults
        to False
    :type learn_threshold: bool, optional

    :param reset_mechanism: Defines the reset mechanism applied to :math:`mem`
        each time the threshold is met. Reset-by-subtraction: "subtract",
        reset-to-zero: "zero", none: "none". Defaults to "subtract"
    :type reset_mechanism: str, optional

    :param state_quant: If specified, hidden states :math:`mem` and \
    :math:`syn` are quantized to a valid state for the forward pass. \
        Defaults to False
    :type state_quant: quantization function from snntorch.quant, optional

    :param output: If `True` as well as `init_hidden=True`, states are
        returned when neuron is called. Defaults to False
    :type output: bool, optional

    Inputs: \\input_, syn_0, mem_0
        - **input_** of shape `(batch, input_size)`: tensor containing \
        input features
        - **syn_0** of shape `(batch, input_size)`: tensor containing \
        input features
        - **mem_0** of shape `(batch, input_size)`: tensor containing \
        the initial membrane potential for each element in the batch.

    Outputs: spk, syn_1, mem_1
        - **spk** of shape `(batch, input_size)`: tensor containing the \
        output spikes.
        - **syn_1** of shape `(batch, input_size)`: tensor containing the \
        next synaptic current for each element in the batch
        - **mem_1** of shape `(batch, input_size)`: tensor containing the \
        next membrane potential for each element in the batch

    Learnable Parameters:
        - **Synaptic.alpha** (torch.Tensor) - optional learnable weights \
        must be manually passed in, of shape `1` or (input_size).
        - **Synaptic.beta** (torch.Tensor) - optional learnable weights must \
        be manually passed in, of shape `1` or (input_size).
        - **Synaptic.threshold** (torch.Tensor) - optional learnable \
        thresholds must be manually passed in, of shape `1` or`` (input_size).

    """

    def __init__(
        self,
        alpha,
        beta,
        threshold=1.0,
        spike_grad=None,
        surrogate_disable=False,
        init_hidden=False,
        inhibition=False,
        learn_alpha=False,
        learn_beta=False,
        learn_threshold=False,
        reset_mechanism="subtract",
        state_quant=False,
        output=False,
    ):
        super(Synaptic, self).__init__(
            beta,
            threshold,
            spike_grad,
            surrogate_disable,
            init_hidden,
            inhibition,
            learn_beta,
            learn_threshold,
            reset_mechanism,
            state_quant,
            output,
        )

        self._alpha_register_buffer(alpha, learn_alpha)

        if self.init_hidden:
            self.syn, self.mem = self.init_synaptic()

    def forward(self, input_, syn=False, mem=False):

        if hasattr(syn, "init_flag") or hasattr(
            mem, "init_flag"
        ):  # only triggered on first-pass
            syn, mem = _SpikeTorchConv(syn, mem, input_=input_)
        elif mem is False and hasattr(
            self.mem, "init_flag"
        ):  # init_hidden case
            self.syn, self.mem = _SpikeTorchConv(
                self.syn, self.mem, input_=input_
            )

        if not self.init_hidden:
            self.reset = self.mem_reset(mem)
            syn, mem = self._build_state_function(input_, syn, mem)

            if self.state_quant:
                syn = self.state_quant(syn)
                mem = self.state_quant(mem)

            if self.inhibition:
                spk = self.fire_inhibition(mem.size(0), mem)
            else:
                spk = self.fire(mem)

            return spk, syn, mem

        # intended for truncated-BPTT where instance variables are
        # hidden states
        if self.init_hidden:
            self._synaptic_forward_cases(mem, syn)
            self.reset = self.mem_reset(self.mem)
            self.syn, self.mem = self._build_state_function_hidden(input_)

            if self.state_quant:
                self.syn = self.state_quant(self.syn)
                self.mem = self.state_quant(self.mem)

            if self.inhibition:
                self.spk = self.fire_inhibition(self.mem.size(0), self.mem)
            else:
                self.spk = self.fire(self.mem)

            if self.output:
                return self.spk, self.syn, self.mem
            else:
                return self.spk

    def _base_state_function(self, input_, syn, mem):
        base_fn_syn = self.alpha.clamp(0, 1) * syn + input_
        base_fn_mem = self.beta.clamp(0, 1) * mem + base_fn_syn
        return base_fn_syn, base_fn_mem

    def _base_state_reset_zero(self, input_, syn, mem):
        base_fn_syn = self.alpha.clamp(0, 1) * syn + input_
        base_fn_mem = self.beta.clamp(0, 1) * mem + base_fn_syn
        return 0, base_fn_mem

    def _build_state_function(self, input_, syn, mem):
        if self.reset_mechanism_val == 0:  # reset by subtraction
            state_fn = tuple(
                map(
                    lambda x, y: x - y,
                    self._base_state_function(input_, syn, mem),
                    (0, self.reset * self.threshold),
                )
            )
        elif self.reset_mechanism_val == 1:  # reset to zero
            state_fn = tuple(
                map(
                    lambda x, y: x - self.reset * y,
                    self._base_state_function(input_, syn, mem),
                    self._base_state_reset_zero(input_, syn, mem),
                )
            )
        elif self.reset_mechanism_val == 2:  # no reset, pure integration
            state_fn = self._base_state_function(input_, syn, mem)
        return state_fn

    def _base_state_function_hidden(self, input_):
        base_fn_syn = self.alpha.clamp(0, 1) * self.syn + input_
        base_fn_mem = self.beta.clamp(0, 1) * self.mem + base_fn_syn
        return base_fn_syn, base_fn_mem

    def _base_state_reset_zero_hidden(self, input_):
        base_fn_syn = self.alpha.clamp(0, 1) * self.syn + input_
        base_fn_mem = self.beta.clamp(0, 1) * self.mem + base_fn_syn
        return 0, base_fn_mem

    def _build_state_function_hidden(self, input_):
        if self.reset_mechanism_val == 0:  # reset by subtraction
            state_fn = tuple(
                map(
                    lambda x, y: x - y,
                    self._base_state_function_hidden(input_),
                    (0, self.reset * self.threshold),
                )
            )
        elif self.reset_mechanism_val == 1:  # reset to zero
            state_fn = tuple(
                map(
                    lambda x, y: x - self.reset * y,
                    self._base_state_function_hidden(input_),
                    self._base_state_reset_zero_hidden(input_),
                )
            )
        elif self.reset_mechanism_val == 2:  # no reset, pure integration
            state_fn = self._base_state_function_hidden(input_)
        return state_fn

    def _alpha_register_buffer(self, alpha, learn_alpha):
        if not isinstance(alpha, torch.Tensor):
            alpha = torch.as_tensor(alpha)
        if learn_alpha:
            self.alpha = nn.Parameter(alpha)
        else:
            self.register_buffer("alpha", alpha)

    def _synaptic_forward_cases(self, mem, syn):
        if mem is not False or syn is not False:
            raise TypeError(
                "When `init_hidden=True`, Synaptic expects 1 input argument."
            )

    @classmethod
    def detach_hidden(cls):
        """Returns the hidden states, detached from the current graph.
        Intended for use in truncated backpropagation through time where
        hidden state variables are instance variables."""

        for layer in range(len(cls.instances)):
            if isinstance(cls.instances[layer], Synaptic):
                cls.instances[layer].syn.detach_()
                cls.instances[layer].mem.detach_()

    @classmethod
    def reset_hidden(cls):
        """Used to clear hidden state variables to zero.
        Intended for use where hidden state variables are
        instance variables."""

        for layer in range(len(cls.instances)):
            if isinstance(cls.instances[layer], Synaptic):
                cls.instances[layer].syn = _SpikeTensor(init_flag=False)
                cls.instances[layer].mem = _SpikeTensor(init_flag=False)


list1 = []
list = []
while True:
    n = input('Nome: ')
    i = int(input('Idade: '))
    if i >= 60:
        list1.append([n])
    if i <= 59:
        list.append([n])
    res = input('Quer continuar?[S/N]')
    if res in 'Nn':
        break
resp = input('Quer limpar as listas?[S/N]')
if resp in 'Ss':
 list.clear()
 list1.clear()
print('A lista de pacientes preferências foi',  list1)
print('A lista geral com ordem de chegada',  list)

Projeto M4/Ylaine, Kleytiane Wellen/test.py


import sys
input = sys.stdin.readline

    #Input
n,m,b = map(int,input().split())    #b: 인벤토리
case = []   #블록 input 저장
max_block = 0   #input중 max
min_block = 256 #input중 min
sum_block = 0   #input 총합
for i in range(n):  #입력받기
    lst = list(map(int,input().split()))
    if max(lst) > max_block:    #최대 층
        max_block = max(lst)
    if min(lst) < min_block:    #최소 층
        min_block = min(lst)
    sum_block += sum(lst)       #총 갯수
    case.append(lst)

ans = -1    #정답 - 시간
ans_block = False   #정답 - 층수
for blocks in range(max_block,min_block -1,-1):
    if blocks * m * n > sum_block +b:   #제작 가능성 판단
        continue    #기존 인벤토리로 해당 층으로 매끈하게 못하면 pass
    time_block = 0      #걸리는 시간 초기화
    flag = False        #true면 탐색 종료(이미 최소값보다 커질때 True로)
    for i in range(n):
        for j in range(m):
            if case[i][j] < blocks: #기준보다 낮음 >> 쌓기(1초)
                time_block += blocks - case[i][j]
                if time_block >= ans and ans != -1:
                     #이미 최소값 초과 & 최초의 데이터가 아님
                    flag = True #이미 최소값 오버로 패스 판단
                    break
            elif case[i][j] > blocks: #기준보다 높음 >> 제거(2초)
                time_block += 2 * (case[i][j] - blocks)
                if time_block >= ans and ans != -1:
                     #이미 최소값 초과 & 최초의 데이터가 아님
                    flag = True #이미 최소값 오버로 패스 판단
                    break
        if flag:
            break

    if flag == False:
        if ans == -1:
            ans = time_block
            ans_block = blocks
        else:
            if time_block < ans:
                ans = time_block
                ans_block = blocks

print(ans,ans_block)


# Question Generation Suite - Question Generation
# Tanay Bennur, Alexandra Knox, Kevin Ren

import math
import queue

from setup import *
from templating import *

""" Ranking Functions """
# Scores question via key entiteis present
def get_score(text, key_entities):
  total = 0
  for (entity, score) in key_entities:
    if entity in text:
      total += score
  return score * math.log(len(text.split(" ")))

""" Generation Functions """
# Finds score of question
def get_score(text, key_entities):
  total = 0
  for (entity, score) in key_entities:
    if entity in text:
      total += score
  return score * math.log(len(text.split(" ")))

# Generates all questions for a given sentence
def generate_sentence_questions(processed_text, key_entities, templates, escape_character, split_character, seperator_character):
  questions = []
  processed_text = nlp(processed_text.text)
  for template in templates:
    [text_template, question_template, score_multiplier, should_grammaticize] = template.split(seperator_character)
    if test_template(processed_text, text_template, split_character):
      entities = extract_entities(processed_text, text_template, split_character)
      question_text = merge_text(processed_text, question_template, escape_character, split_character, entities)
      question_score = float(score_multiplier) * get_score(question_text, key_entities)
      questions.append((question_text + chr(5) + should_grammaticize, question_score))
  return questions

# Reranks questions to include question template frequency
def frequency_rank_questions(questions):
  frequency_dict = {}
  final_queue = queue.PriorityQueue()
  while not questions.empty():
    score, question = questions.get()
    start_word = question.split()[0].lower()
    if start_word not in frequency_dict:
      frequency_dict[start_word] = 0
    frequency_dict[start_word] += 1
    final_queue.put((score * frequency_dict[start_word], question))
  return final_queue

# Generates all questions for given body of text
def generate_questions(sentences, key_entities, templates, escape_character, split_character, seperator_character, max_questions):
  questions = queue.PriorityQueue()
  for sentence in sentences:
    sentence_questions = generate_sentence_questions(sentence, key_entities, templates, escape_character, split_character, seperator_character)
    for question, score in sentence_questions:
      if questions.qsize() > max_questions:
        return frequency_rank_questions(questions)
      questions.put(((1 / score, question)))
  return frequency_rank_questions(questions)

""" Post Processing Functions """
# Grammaticizes and prints questions
def finalize_questions(questions, num_questions):
  questions_asked = 0
  prev_asked = None
  while questions_asked < int(num_questions) and not questions.empty():
    _, question = questions.get()
    input_sentence, should_grammaticize = question.split(chr(5))
    if input_sentence == prev_asked:
      continue
    prev_asked = input_sentence
    questions_asked += 1
    if (should_grammaticize == 'N'):
      print(input_sentence + "?")
      continue
    batch = tokenizer(input_sentence + "?", return_tensors='pt')
    generated_ids = model.generate(batch['input_ids'])
    generated_sentence = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
    print(generated_sentence[0])
  if questions_asked < num_questions:
    print(f"Only {questions_asked} out of {num_questions} could be generated. Sorry about that!")
  else:
    print("All questions generated.")


#
# @lc app=leetcode id=371 lang=python3
#
# [371] Sum of Two Integers
#

# @lc code=start

class Solution:
    def getSum(self, a: int, b: int) -> int:

        add = lambda a, b: add(a ^ b, (a & b) << 1) if b else a
        inv = lambda x: add(~x, 1)

        if a * b < 0:
            if a > 0:
                a, b = b, a
            ia = inv(a)
            if ia == b:
                return 0
            if ia < b:
                ib = inv(b)
                return inv(add(ia, ib))
        return add(a, b)

# @lc code=end


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Transform the checksums task into an actual task description.
"""

import copy
import logging

from taskgraph.transforms.base import TransformSequence
from taskgraph.util.schema import resolve_keyed_by

from gecko_taskgraph.util.attributes import release_level
from gecko_taskgraph.util.scriptworker import get_release_config

logger = logging.getLogger(__name__)

transforms = TransformSequence()

@transforms.add
def handle_keyed_by(config, jobs):
    """Resolve fields that can be keyed by project, etc."""
    fields = [
        "run.config",
        "run.extra-config",
    ]
    for job in jobs:
        job = copy.deepcopy(job)
        for field in fields:
            resolve_keyed_by(
                item=job,
                field=field,
                item_name=job["name"],
                **{"release-level": release_level(config.params["project"])}
            )
        yield job

@transforms.add
def interpolate(config, jobs):
    release_config = get_release_config(config)
    for job in jobs:
        mh_options = list(job["run"]["options"])
        job["run"]["options"] = [
            option.format(
                version=release_config["version"],
                build_number=release_config["build_number"],
            )
            for option in mh_options
        ]
        yield job


#1. Функция num_translate возвращает строку перевод. Или возвращает None, если перевести невозможно.
#2.Обратите внимание, что возвращается None как объект, а не как строка "None". Не путайте печать значения (print) и его возврат из функции (return).
# Функция принимает параметр - строку слово для перевода, и другие параметры, если нужно - по вашему усмотрению. В примере специально они не указаны.
# 3.Здесь нет требований на регистр входного слова. Возвращается результат в нижнем регистре.
# 4. Выполнить вызов функции для нескольких слов и вывести на экран результаты.
def num_translate (slovo):
    numbers = dict(zero='ноль',one='один',two='два',three='три',four='четыре',five='пять',six='шесть',
    seven='семь',eight='восемь',nine='девять',ten='десять')
    c = numbers[slovo]
    print(c)
num_translate('one')
num_translate('nine')
num_translate('four')


from pitch.sequence.executor import SequenceLoader
from pitch.plugins.utils import loader as plugin_loader
from pitch.runner.structures import PitchRunner

def start_process(sequence, logger):
    sequence_loader = SequenceLoader(sequence)
    runner = PitchRunner(sequence_loader, logger=logger)
    runner.run()

def bootstrap(**kwargs):
    scheme = kwargs['sequence_file']
    logger = kwargs['logger']
    plugin_loader(
        kwargs.get('request_plugins'),
        kwargs.get('response_plugins')
    )

    start_process(scheme, logger=logger)


from person import *

persons = []
records = []

def load_data():
	load_names()
	load_records()

def load_names():
	with open('names.txt', 'r', encoding='utf-8') as rfile:
		lines = rfile.readlines()
		for name in lines:
			id, name = name.split(',')
			persons.append(Person(int(id), name.strip()))

def load_records():
	with open('records.txt', 'r', encoding='utf-8') as rfile:
		lines = rfile.readlines()
		for line in lines:
			#5, 龙四, 白嫖, 36, 高五, -1
			point = line.split(',')
			p1 = find_person(point[0])
			p2 = find_person(point[3].strip())
			if p1 == None  or p2 == None:
				continue
			action = point[2].strip()
			score = int(point[5].strip())

			r = Record(p1, action, score)
			p2.add_record(r)

def find_person(id):
	ps = [p for p in persons if p.id == int(id)]
	if len(ps):
		return ps[0]

load_data()
#for p in persons:
#	print(f'{p.name} has {len(p.records)}')


import requests
import json

class TestFlask(object):
    def __init__(self, endpoint):
        self.url = "http://localhost:8001" + endpoint
        print(self.url)
        self.headers = {"Content-Type": "application/json"}

    def get_all(self):
        resp = requests.get(self.url)
        print(resp.status_code)
        print (json.dumps(resp.json(), indent=4, sort_keys=True))
        return resp

    def get_a(self, object_id):
        resp = requests.get(self.url + "/" + str(object_id))
        print(resp.status_code)
        print (json.dumps(resp.json(), indent=4, sort_keys=True))
        return resp

    def post(self, data):
        resp = requests.post(url=self.url,headers=self.headers,data=data)
        print(resp.status_code)
        print (json.dumps(resp.json(), indent=4, sort_keys=True))
        return resp

    def put(self,object_id, data):
        resp = requests.put(url=self.url + "/" + str(object_id), headers=self.headers, data=data)
        print(resp.status_code)
        try:
            print (json.dumps(resp.json(), indent=4, sort_keys=True))
        except:
            print(resp.text)
        return resp


import random
class Character:
    dodge_chance = 0
    agility = 1
    strength = 1
    intellect = 1
    level = 1
    to_next_level = 10
    m_stat_name = ""
    name = ""
    health = 100
    damage = 1
    defence = 1
    dodge = 0
    mana = 50
    choice = ""

    def __init__(self, name, health, damage, defence, intellect, strength, agility, level, dodge, mana, m_stat_name, to_next_level):
        self.name = name
        self.health = health
        self.damage = damage
        self.defence = defence
        self.intellect = intellect
        self.strength = strength
        self.agility = agility
        self.level = level
        self.dodge = dodge
        self.mana = mana
        self.m_stat_name = m_stat_name
        self.to_next_level = to_next_level

    def __str__(self):
        return f"{self.name} Уровень - {self.level}  До След. Уровня - {self.level}\n" \
               f"Здоровье - {self.health}\n" \
               f"Сила - {self.strength}\n" \
               f"Ловкость - {self.agility}\n" \
               f"Интелект - {self.intellect}\n" \
               f"Урон - {self.damage}\n" \
               f"Мана - {self.mana}\n" \
               f"Основной Стат - {self.m_stat_name}\n" \
               f"Броня - {self.defence}\n" \
               f"Шанс уворота - {self.dodge}\n"

    def stats_and_level(self):
        self.defence += self.agility / 4
        self.mana += self.intellect / 2
        self.health += self.strength / 4
        if self.m_stat_name == "agility":
            self.damage += self.agility / 2
        if self.m_stat_name == "strength":
            self.damage += self.strength / 2
        if self.m_stat_name == "intellect":
            self.damage += self.intellect / 2

    def take_damage(self, damage):
            self.health -= damage

    def attack(self, player):
        if player.fight == True:
            dodge_chance = random.randint(1, 100)
            if self.health > 0:
                print(f"Жив(ая) - {self.name}")
                if dodge_chance < player.dodge:
                    player.take_damage(0)
                    print(f"Уворот так как dodge_chance {dodge_chance} < player.dodge {player.dodge}")
                else:
                    if player.defence > self.damage:
                        player.take_damage(0)
                    else:
                        player.take_damage(self.damage - player.defence)
            else:
                print(f"Погиб - {player.name}")
                print("Бить труп плохо")
                player.fight = False

    def defece(self):
        pass

    def fight(self, player, choice):
        player.stats_and_level()
        self.stats_and_level()
        while True:
            print(f"Уровень - {self.level}-------1-й игрок (вы) {self.name}------------2-й игрок-{player.name}-Уровень - {player.level}\n"
                  f"1-й игрок (вы)---------------------------------------------2-й игрок\n"
                  f"Здоровье - {self.health}                                     Здоровье - {player.health}\n"
                   f"Сила - {self.strength}                                          Сила - {player.strength}\n"
                   f"Ловкость - {self.agility}                                      Ловкость - {player.agility}\n"
                   f"Интелект - {self.intellect}                                       Интелект - {player.intellect}\n"
                   f"Урон - {self.damage}                                         Урон - {player.damage}\n"
                   f"Мана - {self.mana}                                         Мана - {player.mana}\n"
                   f"Основной Стат - {self.m_stat_name}                            Основной Стат - {player.m_stat_name}\n"
                   f"Броня - {self.defence}                                          Броня - {player.defence}\n"
                   f"Шанс уворота - {self.dodge}                                  Шанс уворота - {player.dodge}\n")
            self.choice = input("ваше действие:\n 1-атака, \n2-защита, \n3-сдатся \n")
            if self.choice == "1":
                self.attack()
            elif self.choice == "2":
                self.defece()
            elif self.choice == "3":
                self.health == 0


import cv2
import numpy as np
from Ax12 import Ax12
from rplidar import RPLidar
import time
import math
import os
import queue
import threading

os.system("sudo bash ./camara.sh")
anterior_x = 0
anterior_y = 0

valor_anterior = 180
valor_ant = 0

Ax12.DEVICENAME = '/dev/ttyUSB1' #motores

Ax12.BAUDRATE = 1_000_000

Ax12.connect()

sentido = "izquierda"
final = False
estado = 0
color_nuevo = 0
#0 = yendo a buscar cubo, 1 = alineando estanterias y acercandose a los colores del piso, 2 = buscar el color del piso, 3  = por si no encuentra color, 4 = deja el cubo y vuelve al medio

PORT_NAME = '/dev/ttyUSB0'
lidar = RPLidar(PORT_NAME)

# create AX12 instance with ID 10
motor_id_der = 1
my_dxl_der = Ax12(motor_id_der)

parada = [300, 350]
i = 0

motor_id_izq = 2
my_dxl_izq = Ax12(motor_id_izq)

class VideoCapture:

  def __init__(self, name):
    self.cap = cv2.VideoCapture(name)
    self.cap.set(10, 15)
    self.q = queue.Queue()
    t = threading.Thread(target=self._reader)
    t.daemon = True
    t.start()

  # read frames as soon as they are available, keeping only most recent one
  def _reader(self):
    while True:
      ret, frame = self.cap.read()
      if not ret:
        break
      if not self.q.empty():
        try:
          self.q.get_nowait()   # discard previous (unprocessed) frame
        except Queue.Empty:
          pass
      self.q.put(frame)

  def read(self):
    return self.q.get()

def laser():
    i = 0
    angulo = 0
    distmin = 200000
    angmin = 0
    try:
        lidar.connect()
        a = lidar.get_info()
        for measurment in lidar.iter_measurments():
            if (i == 0):
                angulo = measurment[2]
                i = 1
            if (measurment[2] >= angulo-1 and i != 0 and measurment[2] < angulo):
                break
            if (measurment[3] < distmin and measurment[3] > 0):
                distmin = measurment[3]
                angmin  = measurment[2]
        lidar.stop()
    except:
        print("Error")
    return (distmin, angmin)

def laseratras():
    i = 0
    angulo = 0
    distmin = 200000
    angmin = 0
    try:
        lidar.connect()
        a = lidar.get_info()
        for measurment in lidar.iter_measurments():
            if (i == 0):
                angulo = measurment[2]
                i = 1
            if (measurment[2] >= angulo-1 and i != 0 and measurment[2] < angulo):
                break
            if (measurment[3] < distmin and measurment[3] > 0 and measurment[2] > 165 and measurment[2] < 195):
                distmin = measurment[3]
                angmin  = measurment[2]
        lidar.stop()
    except:
        print("Error lidar")
    return (distmin, angmin)

def laseradelante():
    i = 0
    angulo = 0
    distmin = 200000
    angmin = 0
    try:
        lidar.connect()
        a = lidar.get_info()
        for measurment in lidar.iter_measurments():
            if (i == 0):
                angulo = measurment[2]
                i = 1
            if (measurment[2] >= angulo-1 and i != 0 and measurment[2] < angulo):
                break
            if (measurment[3] < distmin and measurment[3] > 0 and (measurment[2] > 345 or measurment[2] < 15)):
                distmin = measurment[3]
                angmin  = measurment[2]
        lidar.stop()
    except:
        print("Error lidar")
    return (distmin, angmin)

def izquierda(vel):
    my_dxl_der.set_moving_speed(1023+vel)
    my_dxl_izq.set_moving_speed(1023+vel)

def derecha(vel):
    my_dxl_der.set_moving_speed(vel)
    my_dxl_izq.set_moving_speed(vel)

def adelante(vel):
    my_dxl_der.set_moving_speed(1023+vel)
    my_dxl_izq.set_moving_speed(vel)

def atras(vel):
    my_dxl_der.set_moving_speed(vel)
    my_dxl_izq.set_moving_speed(1023+vel)

def parar():
    my_dxl_der.set_moving_speed(0)
    my_dxl_izq.set_moving_speed(0)

def devolver_tupla(color):
    if (color == "amarillo"):
        return(17, 45, 0, 35, 255)
    elif (color == "verde"):
        return (30, 80, 20, 85, 255)
    elif (color == "azul"):
        return (95, 60, 55, 135, 255)
    elif (color == "rojo"):
        return (160, 100, 20, 179, 255)
    elif (color == "negro"):
        return (0, 0, 0, 180, 100)

def buscar_color(h_min, s_min, v_min, h_max, ultimo):
    global cap
    frame = cap.read()
    image =cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    cv2.imshow('camara', frame)
    area = 0
    lower = np.array([h_min, s_min, v_min])
    upper = np.array([h_max, 255, ultimo])
    mask = cv2.inRange(image, lower, upper)
    result = cv2.bitwise_and(frame, frame, mask=mask)
    kernel = np.ones((2,2),np.uint8)
    result = cv2.morphologyEx(result, cv2.MORPH_OPEN, kernel)
    contours,_ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if (len(contours) == 0):
        x = 0
        y = 0
    else:
        big_contour = max(contours, key=cv2.contourArea)
        area = cv2.contourArea(big_contour)
        if (cv2.contourArea(big_contour) > 350):
            M = cv2.moments(big_contour)
            if (M["m00"]==0): M["m00"]=1
            x = int(M["m10"]/M["m00"])
            y = int(M["m01"]/M["m00"])
        else:
            x = 0
            y = 0
    return (x,y, area)

def go_to_goal(x, y, est):
    corrigiendo = False
    if (y > parada[i]):
        if not(325 < x and x < 375):
            if (x < 350):
                izquierda(100)
            else:
                derecha(100)
        else:
            parar()
            time.sleep(0.5)
            global estado
            estado = est
            print("Cambie a estado ", estado)
    else:
        if (not(corrigiendo) and 275 < x and x < 425):
            adelante(180)
        else:
            corrigiendo = True
            if (x < 350):
                izquierda(123)
            else:
                derecha(123)
            corrigiendo = False

def estanterias_atras():
    global estado
    l = laser()
    global valor_ant
    while not(l[1] > 165 and l[1] < 195):
        if (l[1] < 180):
            izquierda(123)
        else:
            derecha(123)
        l1 = laser()
        print(l1[1])
        print(abs(l1[1] - valor_ant))
        if (abs(l1[1] - valor_ant) < 40 or abs(l1[1] - valor_ant) > 320) and l1[1] != 0:
            l = l1
            valor_ant = l1[1]
        print(l[0], l[1])
    if (estado != 3 and estado != 4):
        while not(l[0] > 1500 and l[0] <1600):
            print(l[0])
            if (l[1] < 180):
                izquierda(123)
            else:
                derecha(123)
            adelante(180)
            l = laseratras()
        estado = 2
        print("Cambie a estado", estado)
        global i
        i = (i+1) % 2
    parar()

def estanterias_adelante():
    global valor_anterior
    parar()
    global estado
    l = laser()
    print(l[0], l[1])
    print("Estoy haciendo estanterias adelante")
    while (l[1] > 15 and l[1] < 345 or l[1] == 0):
        if (l[1] > 180):
            izquierda(123)
        else:
            derecha(123)
        l1 = laser()
        if abs(l1[1] - valor_anterior) < 40:
            l = l1
            valor_anterior = l1[1]
        print(l[0], l[1])

    while not(l[0] > 1700 and l[0] < 1800):
        if (l[1] > 180):
            izquierda(123)
        else:
            derecha(123)
        if (l[0] > 1800):
            adelante(180)
        elif (l[0] < 1500):
            atras(120)
        l = laseradelante()
    estado = 0
    print("Cambie a estado", estado)
    global i
    i = (i+1) % 2
    parar()
    print("Termine")

cap = VideoCapture(-1)

while (True):
    if (estado == 0):
        r = devolver_tupla("rojo")
        x_red, y_red, a = buscar_color(r[0], r[1], r[2], r[3], r[4])
        if (x_red == 0):
            x_red, y_red, a = buscar_color(0, 100, 20, 10, 255)
        v = devolver_tupla("verde")
        x_green, y_green, av = buscar_color(v[0], v[1], v[2], v[3], v[4])
        if y_green > 450:
          y_green = 0
          x_green = 0
        az = devolver_tupla("azul")
        x_blue, y_blue, a = buscar_color (az[0], az[1], az[2], az[3], az[4])
        am = devolver_tupla("amarillo")
        x_yellow, y_yellow, aa = buscar_color(am[0], am[1], am[2], am[3], am[4])

        if (math.sqrt(pow(x_yellow - x_green, 2)+pow(y_yellow - y_green, 2))) < 100:
            if (aa < av):
                x_yellow = 0
                y_yellow = 0
            else:
                x_green = 0
                y_green = 0

        if (y_yellow > y_blue):
            if (y_yellow > y_green):
                if (y_yellow > y_red):
                    y = y_yellow
                    x = x_yellow
                    color = "amarillo"
                else:
                    y = y_red
                    x = x_red
                    color = "rojo"
            else:
                if (y_red > y_green):
                    y = y_red
                    x = x_red
                    color = "rojo"
                else:
                    y = y_green
                    x = x_green
                    color = "verde"
        else:
            if (y_blue > y_green):
                if (y_blue > y_red):
                    y = y_blue
                    x = x_blue
                    color = "azul"
                else:
                    y = y_red
                    x = x_red
                    color = "rojo"
            else:
                if (y_red > y_green):
                    y = y_red
                    x = x_red
                    color = "rojo"
                else:
                    y = y_green
                    x = x_green
                    color = "verde"

        if (cv2.waitKey(1) == ord('s')):
            break
        if (y_red == 0 and y_yellow == 0 and y_green == 0 and y_blue == 0):
            #print("hola")
            adelante(100)
        else:
            print(color)
            go_to_goal(x, y, 1)

    elif (estado == 1):
        adelante(170)
        time.sleep(3)
        estanterias_atras()

    elif (estado == 2): #dejamos el cubo en el color correcto
        if (color == "rojo"):
            ar = devolver_tupla("rojo")
            x_red, y_red, aa = buscar_color(0, 100, 20, 10, 255)
            if (x_red == 0 and y_red == 0):
                atras(100)
                print("Cambie a estado", estado)
            else:
                go_to_goal(x_red, y_red, 4)
        elif (color == "verde"):
            av = devolver_tupla("verde")
            x_green, y_green, av = buscar_color(av[0], av[1], av[2], av[3], av[4])
            if (x_green == 0 and y_green == 0):
                atras(100)
                print("Cambie a estado", estado)
            else:
                go_to_goal(x_green, y_green, 4)
        elif (color == "azul"):
            az = devolver_tupla("azul")
            x_blue, y_blue, aa = buscar_color(az[0], az[1], az[2], az[3], az[4])
            if (x_blue == 0 and y_blue == 0):
                atras(100)
                print("Cambie a estado", estado)
            else:
                go_to_goal(x_blue, y_blue, 4)
        elif (color == "amarillo"):
            aa = devolver_tupla("amarillo")
            x_yellow, y_yellow, aa = buscar_color(aa[0], aa[1], aa[2], aa[3], aa[4])
            if (x_yellow == 0 and y_yellow == 0):
                atras(100)
                print("Cambie a estado", estado)
            else:
                go_to_goal(x_yellow, y_yellow, 4)

    elif (estado == 3):
        if (sentido == "izquierda"):
            izquierda(123)
        else:
            derecha(123)
        a = (53/10)
        time.sleep(53/10)
        print("Gire a buscar otro color")

        n = devolver_tupla("negro")
        x_black, y_black, a = buscar_color(n[0], n[1], n[2], n[3], n[4])

        print("coordenadas negro")
        print(x_black, y_black)

        #chequear que no se salga
        ahora = time.time()
        while(x_black != 0 and y_black != 0 and time.time()-ahora < 6):
            print("avanzo")
            n = devolver_tupla("negro")
            x_black, y_black, a = buscar_color(n[0], n[1], n[2], n[3], n[4])
            adelante(170)

        if (x_black == 0 or y_black == 0): #sali porque no veo negro, tengo que ir para el otro lado
            if (sentido == "izquierda"):
                sentido = "derecha"
            else:
                sentido = "izquierda"

            derecha(123)
            time.sleep(18) #180 grados, doy vuelta el sentido
            print("gire 180")

        if (sentido == "izquierda"):
            derecha(123)
        else:
            izquierda(123)
        print("Estoy girandooooooo")
        time.sleep(53/10)
        print("Termine de girar")
        estado = 2 #vuelvo a chequear el color
        print("Cambie a estado", estado)
    elif (estado == 4):
        parar()
        #deberia dejar el cubo
        #deja el cubo
        adelante(123)
        time.sleep(2)
        print("Deje el cubo")
        atras(170)
        time.sleep(5)
        estanterias_adelante()
        estado = 0
    #se alinea con las estanterias al frente

cap.release()
cv2.destroyAllWindows()


from flask import Blueprint, request, jsonify, escape, abort
from .auth.auth import requires_auth
from .models.challenge import Challenge, ChallengeType
from .models.challenge_participants import ChallengeParticipants
from datetime import datetime

bp = Blueprint('challenges', __name__, url_prefix='/challenges')

@bp.route('/', methods=['POST'])
@requires_auth()
def add_challenge(payload):
    request_data = request.get_json()
    challenge_name = escape(request_data['name'])
    new_challenge = Challenge(name=challenge_name, creator_id=payload['id'], start_time=request_data['start_time'],
                              end_time=request_data['end_time'], target_books_count=request_data['target_books'],
                              challenge_type=ChallengeType(request_data['challenge_type']).name)
    new_challenge.insert()

    return jsonify({'challenge': new_challenge.to_dict()})

@bp.route('/<int:challenge_id>/join', methods=['POST'])
@requires_auth()
def join_challenge(payload, challenge_id):
    challenge = Challenge.query.get(challenge_id)
    if challenge is None:
        return abort(404)

    if challenge.challenge_type != ChallengeType.public:
        return abort(403)

    challenge_participant = ChallengeParticipants.query.filter_by(
        user_id=payload['id'], challenge_id=challenge_id)

    if challenge_participant:
        return abort(403)

    new_challenge_participant = ChallengeParticipants(
        challenge_id=challenge_id, user_id=payload['id'], time_joined=datetime.now())
    new_challenge_participant.insert()

    return jsonify({
        'uid': new_challenge_participant.user_id,
        'challenge_id': new_challenge_participant.challenge_id
    })

@bp.route('/<int:challenge_id>')
@requires_auth()
def get_challenge(payload, challenge_id):
    challenge = Challenge.query.get(challenge_id)
    if challenge is None:
        return abort(404)

    challenge_dict = challenge.to_dict()

    if payload['id'] not in challenge_dict['participants'] and challenge_dict['creator_id'] != payload['id']:
        return abort(403)

    return jsonify({'challenge': challenge.to_dict()})


def main():
    N = list(map(int, input()))
    n2018 = {
        2: 0,
        0: 0,
        1: 0,
        8: 0
    }

    for n in N:
        try:
            n2018[n] += 1
        except KeyError:
            print(0)
            break
    else:
        if len(list(filter(lambda e: e > 0, n2018.values()))) == 4:
            if n2018[2] == n2018[0] == n2018[1] == n2018[8]:
                print(8)
            else:
                print(2)
        else:
            print(1)

if __name__ == "__main__":
    main()


"""
Hovmoller Diagram of Monthly Surface Temperature
================================================

This example demonstrates the creation of a Hovmoller diagram with fine control
over plot ticks and labels. The data comes from the Met Office OSTIA project
and has been pre-processed to calculate the monthly mean sea surface
temperature.

"""

import matplotlib.dates as mdates
import matplotlib.pyplot as plt

import iris
import iris.plot as iplt
import iris.quickplot as qplt

def main():
    # load a single cube of surface temperature between +/- 5 latitude
    fname = iris.sample_data_path("ostia_monthly.nc")
    cube = iris.load_cube(
        fname,
        iris.Constraint("surface_temperature", latitude=lambda v: -5 < v < 5),
    )

    # Take the mean over latitude
    cube = cube.collapsed("latitude", iris.analysis.MEAN)

    # Now that we have our data in a nice way, lets create the plot
    # contour with 20 levels
    qplt.contourf(cube, 20)

    # Put a custom label on the y axis
    plt.ylabel("Time / years")

    # Stop matplotlib providing clever axes range padding
    plt.axis("tight")

    # As we are plotting annual variability, put years as the y ticks
    plt.gca().yaxis.set_major_locator(mdates.YearLocator())

    # And format the ticks to just show the year
    plt.gca().yaxis.set_major_formatter(mdates.DateFormatter("%Y"))

    iplt.show()

if __name__ == "__main__":
    main()


import numpy as np
from optimizedParabolicVelocityProfile import OptimizedParabolicVelocityProfile

def ParabolicVelocityProfile(elements, nodes, glbNodeIds, boundary):
    """ Calculate the parabolic velocity profile for the inlet.
        - elements: elements on the inlet
        - nodes: global nodes information
        - glbNodeIds: the corresponding global position for each node

        return: u, int_u
    """

    nNodes = glbNodeIds.shape[0]
    K = np.zeros((nNodes, nNodes))
    f = np.zeros(nNodes)
    Ae = np.zeros(elements.shape[0])

    OptimizedParabolicVelocityProfile(nodes, elements, glbNodeIds, K, f, Ae)

    # Apply zero velocity at the boundary.
    for i in boundary:
        K[i,:] = 0.0
        K[i,i] = 1.0
        f[i] = 0.0

    u = np.linalg.solve(K, f)
    int_u = np.sum(np.mean(u[elements], axis=1) * Ae)

    return u, int_u


import numpy as np
import math
from scipy import signal

def angle(compl_values):
    real_values = np.array([x.real for x in compl_values])
    imag_values = np.array([x.imag for x in compl_values])
    return np.arctan2(imag_values, real_values)

def my_filter(B,A,X):
    n = len(A)
    z = np.zeros(n)      # Creates zeros if input z is omitted
    b = B / A[0]
    a = A / A[0]
    Y = np.zeros(X.shape)
    Y = Y.astype(np.float64)
    z = z.astype(np.float64)
    for m in range(len(Y)):
       Y[m] = b[0] * X[m] + z[0]
       for i in range(1,n):
          z[i - 1] = b[i] * X[m] + z[i] - a[i] * Y[m]
    # z = z[1:n - 1]
    return Y
    # # X is 1-D
    # num_len = len(B)
    # den_len = len(A)
    # # Z = np.zeros((X.shape[0]+num_len-1,1))
    # # Y = np.zeros((X.shape[0]+den_len-1,1))
    # Y = np.zeros((X.shape[0],1))
    # # Z[num_len-1:] = X
    # for i in range(X.shape[0]):
    #     if i==0:
    #         Y[0] = B[0]/A[0]*X[0]
    #     else:
    #         num = 0.0
    #         for p in range(num_len):
    #             if (i-p>=0):
    #                 num += B[p] * X[i-p]
    #                 print(i, p, i-p, B[p], X[i-p])
    #         den = 0.0
    #         for q in range(1,den_len):
    #             if (i-q-1>=0):
    #                 den += A[q] * Y[i-q-1]
    #                 # print(A[q])
    #         Y[i] = 1.0/A[0] * (num-den)
    #         print(num,den,Y[i])
    # return Y

def spec2scaletime(stft, nbChannels, nbChOct, sr_time, nfft_scale):
    '''
    spec2scaletime transforms a spectrograms into a time vs. scales (in
    cycles/hz or cycles/octaves) representation. Each time slice is fourrier
    transform wrt the frequency axis (in octaves or hertz).
    '''
    LgtTime = stft.shape[0]
    modulationScale = np.zeros((LgtTime, nfft_scale), dtype=complex)
    phaseScale = np.zeros((LgtTime, nfft_scale))
    # perform a FFT for each time slice
    for i in range(LgtTime):
        modulationScale[i, :] = np.fft.fft(stft[i, :], nfft_scale)
        phaseScale[i, :] = angle(modulationScale[i, :])
    modulationScale = np.abs(modulationScale)  # modulus of the fft
    scales = np.linspace(0, nfft_scale + 1, nbChOct)
    times = np.linspace(0, modulationScale.shape[1] + 1, LgtTime / sr_time)
    return modulationScale, phaseScale, times, scales

def scaletime2scalerate(modulationScale, nbChannels, nbChOct, sr_time, nfft_rate, nfft_scale):
    # scaletime2scalerate transforms a scale vs. time representation into a scale vs. rate
    # representation. Each scale slice is fourrier transform wrt the time axis.
    #
    # inputs parameters:
    #  modulationScale  : scale vs. time representation (rows: time, columns:
    #  scales)
    #  nbChannels       : number of channels of the spectrogram
    #  nbChOct          : number of channels per octave
    #  sr_time          : sample rate
    #  nfft_rate        : number of points of the DFT
    #
    # output parameters:
    #  scaleRate        : modulus of the rate vs. scale reprsentation
    #  phaseScaleRate   : phase of the rate vs. scale representation
    #  rates            : rate axis (in Hz)"
    #  scales           : scale axis (in Cycles/Octaves or Cycles/Hertz)
    # function [scaleRate, phaseScaleRate, rates, scales] = scaletime2scalerate(modulationScale, nbChannels, nbChOct, sr_time, nfft_rate, nfft_scale)
    LgtScale = modulationScale.shape[1]
    scaleRate      = np.zeros((nfft_rate, LgtScale), dtype=complex)
    phaseScaleRate = np.zeros((nfft_rate, LgtScale))
    for i in range(LgtScale):
      scaleRate[:, i] = np.fft.fft(modulationScale[:, i], nfft_rate)
      phaseScaleRate[:, i] = angle(scaleRate[:, i])
    scaleRate = np.abs(scaleRate)
    rates  = np.linspace(0, nfft_rate+1, sr_time)
    scales = np.linspace(0, nfft_scale+1, nbChOct)
    return scaleRate, phaseScaleRate, rates, scales

def scaleRate2cortical(scaleRate, phaseScaleRate, stft, scalesVector, ratesVector, nbChOct, sr_time, nfft_scale, nfft_rate, KIND):
    # % scaleRate2cortical transforms a scale vs. rate representation to the
    # % cortical representation
    # %
    # % inputs parameters:
    # %  scaleRate        : modulus of the rate vs. scale reprsentation (rows:
    # %                     time, colums: scales)
    # %  phaseScaleRate   : phase of the rate vs. scale reprsentation
    # %  stft             : auditory
    # %  scalesVector     : central scales of bandpass filerbank
    # %  ratesVector      : central rates of bandpass filerbank
    # %  nbChannels       : number of channels of the spectrogram
    # %  nbChOct          : number of channels per octave
    # %  sr_time          : sample rate
    # %  nfft_scale       : number of points of the DFT
    # %  KIND             : Kind of filter (1. Gabor function 2. Gaussian
    # %  function)
    # %
    # % output parameters:
    # %  corticalRepresentation : 4D cortical representation
    # %                           (time, frequency, scale, rate)
    # %
    # function [corticalRepresentation] = scaleRate2cortical(scaleRate, phaseScaleRate, stft, scalesVector, ratesVector, nbChOct, sr_time, nfft_scale, nfft_rate, KIND)
    LgtRateVector  = len(ratesVector)
    LgtScaleVector = len(scalesVector) # length scale vector
    LgtFreq        = stft.shape[1]
    LgtTime        = stft.shape[0]
    corticalRepresentation = np.zeros((LgtTime, LgtFreq, LgtScaleVector, LgtRateVector), dtype=complex)
    for j in range(LgtRateVector):
        fc_rate = ratesVector[j]
        t = np.arange(nfft_rate/2)/sr_time * abs(fc_rate)
        h = np.sin(2 * math.pi * t) * np.power(t,2) * np.exp(-3.5 * t) * abs(fc_rate)
        h  = h - np.mean(h)

        STRF_rate0 = np.fft.fft(h,  nfft_rate)
        A = angle(STRF_rate0[:nfft_rate//2])
        A[0] = 0.0 # instead of pi
        STRF_rate  = np.absolute(STRF_rate0[:nfft_rate//2])
        STRF_rate  = STRF_rate / np.max(STRF_rate)
        STRF_rate  = STRF_rate * np.exp(1j * A)

        # rate filtering modification
        # STRF_rate                = [STRF_rate(1:nfft_rate/2); zeros(1,nfft_rate/2)']
        STRF_rate.resize((nfft_rate,))
        STRF_rate[nfft_rate//2] = np.absolute(STRF_rate[nfft_rate//2+1])

        if(fc_rate < 0):
            STRF_rate[1:nfft_rate] = np.matrix.conjugate(np.flipud(STRF_rate[1:nfft_rate]))

        z1 = np.zeros((nfft_rate, nfft_scale//2), dtype=complex)
        for m in range(nfft_scale // 2):
            z1[:, m] = STRF_rate * scaleRate[:,m] * np.exp(1j * phaseScaleRate[:, m])

        # z1.resize((nfft_rate,nfft_rate))
        for i in range(nfft_scale//2):
            z1[:,i] = np.fft.ifft(z1[:,i])
        # print(z1[10,:])

        for i in range(LgtScaleVector):
            fc_scale = scalesVector[i]
            R1 = np.arange(nfft_scale/2 )/ (nfft_scale/2) * nbChOct/2 / abs(fc_scale)
            if KIND == 1:
               C1 = 1 / 2 / .3 / .3;
               STRF_scale = np.exp(-C1 * np.power(R1-1,2)) + np.exp(-C1 * np.power(R1+1,2))
            elif KIND == 2:
               R1 = np.power(R1,2)
               STRF_scale = R1 * np.exp(1 - R1)
            z = np.zeros((LgtTime, nfft_scale//2), dtype=complex)
            for n in range(LgtTime):
                temp = np.fft.ifft(STRF_scale * z1[n, :], nfft_scale)
                z[n, :] = temp[:nfft_scale//2]
            corticalRepresentation[: , :, i, j] = z[:LgtTime, :LgtFreq]
    return corticalRepresentation

def _sigmoid(x, fac):
    '''
    Compute sigmoidal function
    '''
    y = x
    if fac > 0:
        y = 1. / (1. + np.exp(-y / fac))
    elif fac == 0:
        y = (y > 0)
    elif fac == -1:
        y = np.max(y, 0)
    elif fac == -3:
        raise ValueError('not implemented')
    return y

def wav2aud(x_, paras, filt='p', VERB=0):
    # Wav2Aud form NSL toolbox
    # http://www.isr.umd.edu/Labs/NSL/Software.htm
    #

    if (filt == 'k'):
        raise ValueError('Please use wav2aud_fir function for FIR filtering!')

    if (filt == 'p_o'):
        COCHBA = np.genfromtxt('COCHBA_aud24_old.txt', dtype=str)
    else:
        COCHBA = np.genfromtxt('COCHBA_aud24.txt', dtype=str)
    # convert str to complex (may be a better way...)
    COCHBA = np.asarray(
        [[complex(i.replace('i', 'j')) for i in COCHBA[row, :]]
         for row in range(len(COCHBA))])

    L, M = COCHBA.shape[0], COCHBA.shape[1]  # p_max = L - 2;
    L_x = len(x_)  # length of input

    # octave shift, nonlinear factor, frame length, leaky integration
    shft = paras[3]  # octave shift
    fac = paras[2]  # nonlinear factor
    L_frm = round(paras[0] * 2**(4 + shft))  # frame length (points)

    alph = math.exp(-1 / (paras[1] * 2**(4 + shft))) if paras[1] else 0

    # hair cell time constant in ms
    haircell_tc = 0.5
    beta = math.exp(-1 / (haircell_tc * 2**(4 + shft)))

    # get data, allocate memory for ouput
    N = math.ceil(L_x / L_frm)
    x = x_.copy()
    x.resize((N * L_frm, 1))  # zero-padding
    v5 = np.zeros((N, M - 1))

    #% last channel (highest frequency)
    p = COCHBA[0, M - 1].real
    B = COCHBA[np.arange(int(p) + 1) + 1, M - 1].real
    A = COCHBA[np.arange(int(p) + 1) + 1, M - 1].imag
    y1 = signal.lfilter(B, A, x, axis=0)
    y2 = _sigmoid(y1, fac)
    if (fac != -2):
        y2 = signal.lfilter([1.0], [1.0, -beta], y2, axis=0)
    y2_h = y2
    # % All other channels
    for ch in range((M - 2), -1, -1):
        # ANALYSIS: cochlear filterbank
        p = COCHBA[0, ch].real
        B = COCHBA[np.arange(int(p) + 1) + 1, ch].real
        A = COCHBA[np.arange(int(p) + 1) + 1, ch].imag
        y1 = signal.lfilter(B, A, x, axis=0)
        y2 = _sigmoid(y1, fac)
        # hair cell membrane (low-pass <= 4 kHz) ---> y2 (ignored for linear)
        if (fac != -2): y2 = signal.lfilter([1.0], [1.0, -beta], y2, axis=0)

        y3 = y2 - y2_h
        y2_h = y2
        # half-wave rectifier ---> y4
        y4 = np.maximum(y3, 0)

        # temporal integration window ---> y5
        if alph:  # leaky integration
            y5 = signal.lfilter([1.0], [1.0, -alph], y4, axis=0)
            v5[:, ch] = y5[L_frm * np.arange(1,N+1) - 1].reshape(-1,)
        else:  # short-term average
            if (L_frm == 1):
                v5[:, ch] = y4
            else:
                v5[:, ch] = np.mean(y4.reshape(L_frm, N), axis=0)

    return v5

if __name__ == "__main__":
    wav2aud()


import matplotlib.pyplot as plt
import csv
with open('in.txt', newline='') as f:
    reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
    # Lines here happen before any data is processed
    environment = []
    for row in reader:
        rowlist = []
        # Lines here happen before each row is processed
        for value in row:
            rowlist.append(value)
            # do something with values.
        # Lines here happen before after row is processed
        environment.append(rowlist)
    # Lines here happen after all the data is processed

plt.imshow(environment)
plt.show()


import time
import threading

from project.app import app, mongo
from project.utils.standart.mongo import get_active_games, update_game, fetch_config
from project.utils.standart.update_profits import update_source, update_city
from project.sockets import broadcast_game

waiting_time = 3

def worker_job():
    cfg = fetch_config()
    games = get_active_games()
    is_updated = False
    for i in games:
        print("Opened #" + str(i["_id"]) + " | current time: {}".format(time.time()))
        for j in i["users"]:
            j["balance"] += j["profit_per_sec"] * waiting_time
        for j in i["sources"]:
            j["remain"] -= j["delta"] * waiting_time
            if j["remain"] < 0:
                is_updated = True
                j["remain"] = 0
                i = update_source(i, j, cfg)

        for j in i["cities"]:
            for k in j["resource_delta"]:
                j["resource_stage"][k] += j["resource_delta"][k] * waiting_time
                if j["resource_stage"][k] >= cfg["cities"]["upgrades_levels"]["level_" + str(j["resource_levels"][k])]:
                    is_updated = True
                    j["resource_stage"][k] = 0
                    j["resource_levels"][k] += 1
                    i = update_city(i, j, cfg)

        update_game(str(i["_id"]), i)
        if is_updated:
            broadcast_game(i)
        print("Closed #" + str(i["_id"]) + " | current time: {}".format(time.time()))

if __name__ == "__main__":
    while True:
        threading.Thread(target=worker_job, args=()).start()
        time.sleep(waiting_time)


# TODO: 4-2
# from operator import add, mul
#
# data = [2, 7, 12, 7, 4, 5, 8, 2]
# kernel = [0.4, 0.2, 0.6]
#
#
# for i in range(len(data)-2):
#     temp = data[i:i+3]
#     res = [mul(x, y) for x, y in zip(temp, kernel)]
#     print(sum(res), res)

# TODO: 4-3
# import numpy as np
#
# def conv(X, filters, stride=1, pad=0):
#     n, c, h, w = X.shape
#     n_f, _, filter_h, filter_w = filters.shape
#     out_h = (h + 2 * pad - filter_h) // stride + 1
#     out_w = (w + 2 * pad - filter_w) // stride + 1
#
#     # add padding to height and width.
#     in_X = np.pad(X, [(0, 0), (0, 0), (pad, pad), (pad, pad)], 'constant')
#     out = np.zeros((n, n_f, out_h, out_w))
#
#     for i in range(n): # for each image.
#         for c in range(n_f): # for each channel.
#             for h in range(out_h): # slide the filter vertically.
#                 h_start = h * stride
#                 h_end = h_start + filter_h
#                 for w in range(out_w): # slide the filter horizontally.
#                     w_start = w * stride
#                     w_end = w_start + filter_w
#                     # Element-wise multiplication.
#                     out[i, c, h, w] = np.sum(in_X[i, :, h_start:h_end, w_start:w_end] * filters[c])
#
#     return out
#
#
#
#
# X = np.array([[[[1,0,2,1,1],
#              [2,0,2,0,2],
#              [2,1,2,1,1],
#              [1,0,1,1,2],
#              [1,2,1,0,1]]]])
#
# kernel = np.array([[[[1,0,-1],
#                    [1,0,-1],
#                    [1,0,-1]]]])
#
# print('Data:', X.shape)
# print('Filters:', kernel.shape)
# out = conv(X, kernel, stride=2, pad=1)
# print('Output:', out.shape)
# print(out)

# TODO: 4-[7~10]
# import numpy as np
#
# U1= np.array([[-0.3, 1.0, 1.2],
#               [1.6, -1.0, -1.1]])
# U2= np.array([[1.0, 1.0, -1.0],
#               [0.7, 0.5, 1.0]])
# U3= np.array([[0.5, -0.8, 1.0],
#               [-0.1, 0.3, 0.4]])
# U4= np.array([[1.0, 0.1, -0.2],
#               [-0.2, 1.3, -0.4]])
# UU = [U1, U2, U3, U4]
# data = np.array([[1, 0]])
# x0 = 1 # bias
#
# def sigmoid(x):
#     return 1 / (1 + np.exp(-x))
#
# def relu(x):
#     return np.maximum(0, x)
#
# def activation(arr, act):
#     result = []
#     for a in arr[0]:
#         if act == 'sigmoid':
#             logit = sigmoid(a)
#             result.append(logit)
#         elif act == 'relu':
#             logit = relu(a)
#             result.append(logit)
#     result = np.array(result).reshape(1, -1)
#     return result
#
# for i in range(4):
#     data = np.insert(data, 0, x0)
#     data = data.reshape(1, -1)
#     data = np.matmul(data, UU[i].T)
#     data = activation(data, 'relu')
#     print(data)

# TODO: [6-3~6-7] (p.373 - 5)
import numpy as np

data = np.array([[3, 2], [2, 1], [2, 3], [1, 4]])
len_data = data.shape[0]

def distance(a, b):
    dist_x = pow(a[0]-b[0], 2)
    dist_y = pow(a[1]-b[1], 2)
    return dist_x + dist_y

def similarity(arr, len_data=len_data):
    S = np.ones((len_data, len_data)) * 99
    for i in range(len_data):
        for j in range(len_data):
            if i == j:
                pass
            else:
                S[i, j] = -distance(data[i], data[j])
    for i in range(len_data):
        for j in range(len_data):
            if i == j:
                S[i, j] = np.amin(S)
    return S

# S = similarity(data)
# print('S: \n', S)

def max_as(S, A, row, index, len_data=len_data):
    values = []
    for k in range(len_data):
        if k == index:
            pass
        else:
            value = A[row, k] + S[row, k]
            values.append(value)
    return max(values)

def responsibility(S, A, len_data=len_data):
    R = np.zeros((len_data, len_data))
    for i in range(len_data):
        for j in range(len_data):
            R[i, j] = S[i, j] - max_as(S, A, row=i, index=j)
    return R

# A = np.zeros((len_data, len_data))
# R = np.zeros((len_data, len_data))
# R = responsibility(S, A)
# print('R: \n', R)

def max_r(R, row, index, len_data=len_data):
    values = []
    for i in range(len_data):
        if (i == row) or (i == index):
            pass
        else:
            value = max(0, R[i, index])
            values.append(value)
    return sum(values)

def available(R, len_data=len_data):
    A = np.zeros((len_data, len_data))
    for i in range(len_data):
        for j in range(len_data):
            if i == j:
                A[i, j] = max_r(R, row=i, index=j)
            else:
                A[i, j] = min(0, R[j, j] + max_r(R, row=i, index=j))
    return A

print('-'*10 + ' t = 0 ' + '-'*10)
S = similarity(data)
print('S: \n', S)
A = np.zeros((len_data, len_data))
R = np.zeros((len_data, len_data))
R = responsibility(S, A)
print('R: \n', R)
A = available(R)
print('A: \n', A)
print('-'*10 + ' t = 1 ' + '-'*10)
R = responsibility(S, A)
A = available(R)
print('R: \n', R)
print('A: \n', A)

# # TODO: [6-8~6-10] (p.373 - 9)
import numpy as np

# A = np.array([[2, 1], [2, 4], [4, 1], [4, 3]])
# A = np.array([[-1, -1.25], [-1, 1.75], [1, -1.25], [1, 0.75]])

from pandas import DataFrame
import pandas as pd

datas:DataFrame = pd.DataFrame({'x':[3, 2, 2, 1],
                                'y':[2, 1, 3, 4]})

A = np.array([[3, 2], [2, 1], [2, 3], [1, 4]])
mean = np.mean(A, axis=0)
A = A - mean

# x = datas['x']
# y = datas['y']

# N = len(datas)

# mu_x = np.mean(x)
# mu_y = np.mean(y)
# print(mu_x, mu_y)

# cov_sample = sum((x-mu_x)*(y-mu_y))/N
# print('{0:.3f}'.format(cov_sample))
# cov = sum((x-mu_x)*(y-mu_y))/(N-1)
# print('{0:.3f}'.format(cov))

# B = np.cov(x, y, ddof=0)
B = np.cov(A[:, 0], A[:, 1], ddof=0)
print('Cov: \n', B)
print()

eigenvalue, eigenvector = np.linalg.eig(B)
eigenvalue = np.round(eigenvalue, 5) # 소수점 5자리로 반올림
eigenvector = np.round(eigenvector, 5) # 소수점 5자리로 반올림
print("Eigen Value: \n", eigenvalue)

print("Eigen Vector Matix P: \n", eigenvector)
print()

print("Dimensionality Reduction with PCA: ")
W = np.array([eigenvector[:, 1]]).T#, eigenvector[:, 1]]).T
print("W = \n", W)
print("A = \n", A)

print("W.T@A.T = Z.T : \n", W.T@A.T)
ZT = W.T@A.T
print("Z = \n", ZT.T)

# import matplotlib.pyplot as plt
#
# plt.plot(ZT[:,0], ZT[:,1])
# plt.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 14:07:15 2018

@author: Manon Romain
"""
import numpy as np
import tensorflow as tf
import math as m

tfd = tf.contrib.distributions

def tricky_divide(x, y):
    return tf.transpose(tf.transpose(x)/y)

def tricky_multiply(x, y):
    return tf.transpose(tf.transpose(x)*y)

def compute_energy_and_penalty(z, gammas, is_training):
    """
    Computes the energy and penalty of the GMM as described
    in Zong, Bo et al. “Deep Autoencoding Gaussian Mixture Model
                        for Unsupervised Anomaly Detection.” (2018).

    K: number of mixtures in the GMM
    N: number of samples
    M: number of features of z

    Args:
        - z :       [N, M] - the reconstruction features concatenated
                    with the latent representation of x

        - gamma :   [N, K] - density of probability - output of the
                    estimation network

    Returns:

        - E(z):     Tensor of shape [batch_size] - energy of the
                    GMM computed by the networks

        - P(sigma): Scalar - Penalty appled to small values in diagonal entries of
                    covariance matrices

    Note: could probably be simplified

    """
    #shapes
    K = gammas.get_shape()[1]
    M = z.get_shape()[1]
    with tf.variable_scope('gmm_parameters'):
        phis = tf.get_variable('phis', shape=[K], initializer=tf.ones_initializer(), dtype=tf.float32, trainable=False)
        mus = tf.get_variable('mus', shape=[K, M], initializer=tf.ones_initializer(), dtype=tf.float32, trainable=False)

        init_sigmas = 0.5 * np.expand_dims(np.identity(M), axis=0)
        init_sigmas = np.tile(init_sigmas, [2, 1, 1])
        init_sigmas = tf.constant_initializer(init_sigmas)
        sigmas = tf.get_variable('sigmas', shape=[K, M, M], initializer=init_sigmas, dtype=tf.float32, trainable=False)

        sums = tf.reduce_sum(gammas, axis=0)
        sums_exp_dims = tf.expand_dims(sums, axis=-1)

        phis_ = tf.reduce_mean(gammas, axis=0)
        mus_ = tf.matmul(gammas, z, transpose_a=True) / sums_exp_dims

        def assign_training_phis_mus():
            with tf.control_dependencies([phis.assign(phis_), mus.assign(mus_)]):
                return [tf.identity(phis), tf.identity(mus)]

        phis, mus = tf.cond(is_training, assign_training_phis_mus, lambda: [phis, mus])
        phis_exp_dims = tf.expand_dims(phis, axis=0)
        phis_exp_dims = tf.expand_dims(phis_exp_dims, axis=-1)
        phis_exp_dims = tf.expand_dims(phis_exp_dims, axis=-1)

        zs_exp_dims = tf.expand_dims(z, 1)
        zs_exp_dims = tf.expand_dims(zs_exp_dims, -1)
        mus_exp_dims = tf.expand_dims(mus, 0)
        mus_exp_dims = tf.expand_dims(mus_exp_dims, -1)

        zs_minus_mus = zs_exp_dims - mus_exp_dims

        sigmas_ = tf.matmul(zs_minus_mus, zs_minus_mus, transpose_b=True)
        broadcast_gammas = tf.expand_dims(gammas, axis=-1)
        broadcast_gammas = tf.expand_dims(broadcast_gammas, axis=-1)
        sigmas_ = broadcast_gammas * sigmas_
        sigmas_ = tf.reduce_sum(sigmas_, axis=0)
        sigmas_ = sigmas_ / tf.expand_dims(sums_exp_dims, axis=-1)
        sigmas_ = add_noise(sigmas_)

        def assign_training_sigmas():
            with tf.control_dependencies([sigmas.assign(sigmas_)]):
                return tf.identity(sigmas)

        sigmas = tf.cond(is_training, assign_training_sigmas, lambda: sigmas)

    inversed_sigmas = tf.expand_dims(tf.matrix_inverse(sigmas), axis=0)
    inversed_sigmas = tf.tile(inversed_sigmas, [tf.shape(zs_minus_mus)[0], 1, 1, 1])
    energy = tf.matmul(zs_minus_mus, inversed_sigmas, transpose_a=True)
    energy = tf.matmul(energy, zs_minus_mus)
    energy = tf.squeeze(phis_exp_dims * tf.exp(-0.5 * energy), axis=[2, 3])
    energy_divided_by = tf.expand_dims(tf.sqrt(2.0 * m.pi * tf.matrix_determinant(sigmas)), axis=0) + 1e-12
    energy = tf.reduce_sum(energy / energy_divided_by, axis=1) + 1e-12
    energy = -1.0 * tf.log(energy)

    penalty = 1.0 / tf.matrix_diag_part(sigmas)
    penalty = tf.reduce_sum(penalty)
    return energy, penalty

def add_noise(mat, stdev=0.001):
    """
    :param mat: should be of shape(k, d, d)
    :param stdev: the standard deviation of noise
    :return: a matrix with little noises
    """
    with tf.name_scope('gaussian_noise'):
        dims = mat.get_shape().as_list()[1]
        noise = stdev + tf.random_normal([dims], 0, stdev * 1e-1)
        noise = tf.diag(noise)
        noise = tf.expand_dims(noise, axis=0)
        noise = tf.tile(noise, (mat.get_shape()[0], 1, 1))
    return mat + noise


"""calendario URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from rest_framework import routers
from Evento.api import viewsets as eventoviewsets
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
   openapi.Info(
      title="API Calendário",
      default_version='v1',
      description="Bem-vindo à documentação da API Calendário da UNIFIP \nNossa API tem como objetivo alimentar o calendário academico da UNIFIP com seus eventos e datas comemorativas.\n A API que falaremos nessa documentação é a v1, onde as datas são representadas. \nFornecemos endpoints com respostas apresentadas em formato JSON. \nUtilizamos o princípio REST, que é simples de integrar, eficiente e seguro.",
      contact=openapi.Contact(email="gerenciati@fiponline.edu.br"),
      license=openapi.License(name="Apache 2.0"),
   ),
   public=False,
   permission_classes=(permissions.AllowAny,),
)

route = routers.DefaultRouter()

route.register(r'evento', eventoviewsets.EventoViewsets, basename="Evento")

urlpatterns = [
    re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    path('admin/', admin.site.urls),
    path("", include(route.urls))
]


class Solution:
    def checkStraightLine(self, coordinates: list[list[int]]) -> bool:
        """
        You are given an array coordinates, coordinates[i] = [x, y], where
        [x, y] represents the coordinate of a point. Check if these points make
        a straight line in the XY plane.
        """
        if len(coordinates) == 2:
            return True

        x_equality = True
        y_equality = True

        for coord in coordinates[1:]:
            if coord[0] != coordinates[0][0]:
                x_equality = False

            if coord[1] != coordinates[0][1]:
                y_equality = False

            if not x_equality and not y_equality:
                break

        if x_equality or y_equality:
            return True

        s_coords = sorted(coordinates)

        slope = (s_coords[1][1] - s_coords[0][1]) / ((s_coords[1][0] - s_coords[0][0]) if (s_coords[1][0] - s_coords[0][0]) != 0 else -10)

        for i, coord in enumerate(coordinates[1:], 1):
            if (s_coords[i][1] - s_coords[i-1][1]) / ((s_coords[i][0] - s_coords[i-1][0]) if (s_coords[i][0] - s_coords[i-1][0]) else -10) != slope:
                return False

        return True


import requests
import datetime

url = "https://api.telegram.org/bot1134951364:AAGpKHO2-SsyFXsxmbpnk68l1vUFE0M8-ik/"

def get_updates_json(request):
    response = requests.get(request + 'getUpdates')
    return response.json()

def last_update(data):
    results = data['result']
    total_updates = len(results) - 1
    return results[total_updates]

def get_chat_id(update):
    chat_id = update['message']['chat']['id']
    return chat_id

def send_mess(chat, text):
    params = {'chat_id': chat, 'text': text}
    response = requests.post(url + 'sendMessage', data=params)
    return response

def main():
    update_id = last_update(get_updates_json(url))['update_id']
    while True:
        if  update_id == last_update(get_updates_json(url))['update_id']:
            print("Hi")
 #           text = get_updates_json(url)
  #          print(text)
            send_mess(get_chat_id(last_update(get_updates_json(url))), 'test')
            update_id += 1

chat_id = get_chat_id(last_update(get_updates_json(url)))
send_mess(chat_id, 'Готов узнать кто ты из шиноби мира МК?')

if __name__ == 'main':
    main()


import numpy as np
import datetime
import random

class DataSet():
    def __init__(self, filename):
        self.filename = filename
        self.sentences = []
        self.tags = []
        sentence = []
        tag = []
        word_num = 0
        file = open(filename, encoding='utf-8')
        while True:
            line = file.readline()
            if not line:
                break
            if line == '\n':
                self.sentences.append(sentence)  # [[word1,word2,...],[word1...],[...]]
                self.tags.append(tag)  # [[tag1,tag2,...],[tag1...],[...]]
                sentence = []
                tag = []
            else:
                sentence.append(line.split()[1])  # [word1,word2,...]
                tag.append(line.split()[3])  # [tag1,tag2,...]
                word_num += 1
        self.sentences_num = len(self.sentences)  # 统计句子个数
        self.word_num = word_num  # 统计词语个数

        print('{}:共{}个句子,共{}个词。'.format(filename, self.sentences_num, self.word_num))
        file.close()

    def split(self):
        data = []
        temp_list = []
        for i in range(len(self.sentences)):
            for j in range(len(self.sentences[i])):  # j为词在句子中的序号
                temp_list.append((self.sentences[i][j], self.tags[i][j]))  # [(句子1,1,词性),(句子1,2,词性)...]
            data.append(temp_list)
            temp_list = []
        return data

class global_liner_model(object):
    def __init__(self, train_file, dev_file, test_file):
        self.train_data = DataSet(train_file)  # 处理训练集文件
        self.dev_data = DataSet(dev_file)  # 处理开发集文件
        self.test_data = DataSet(test_file) # 处理测试集文件
        self.features = {}  # 存放所有特征及其对应编号的字典
        self.tag_to_index = {}  # 存放所有词性及其对应编号的字典
        self.index_to_tag = {}
        self.tag_list = []  # 存放所有词性的列表
        self.weights = []  # 特征权重矩阵
        self.v = []
        self.BOS = 'BOS'

    def create_bigram_feature(self, pre_tag):
        return ['01:' + pre_tag]

    def create_unigram_feature(self, sentence, position):
        template = []
        cur_word = sentence[position]
        cur_word_first_char = cur_word[0]
        cur_word_last_char = cur_word[-1]
        if position == 0:
            last_word = '##'
            last_word_last_char = '#'
        else:
            last_word = sentence[position - 1]
            last_word_last_char = sentence[position - 1][-1]

        if position == len(sentence) - 1:
            next_word = '$$'
            next_word_first_char = '$'
        else:
            next_word = sentence[position + 1]
            next_word_first_char = sentence[position + 1][0]

        template.append('02:' + cur_word)
        template.append('03:' + last_word)
        template.append('04:' + next_word)
        template.append('05:' + cur_word + '*' + last_word_last_char)
        template.append('06:' + cur_word + '*' + next_word_first_char)
        template.append('07:' + cur_word_first_char)
        template.append('08:' + cur_word_last_char)

        for i in range(1, len(sentence[position]) - 1):
            template.append('09:' + sentence[position][i])
            template.append('10:' + sentence[position][0] + '*' + sentence[position][i])
            template.append('11:' + sentence[position][-1] + '*' + sentence[position][i])
            if sentence[position][i] == sentence[position][i + 1]:
                template.append('13:' + sentence[position][i] + '*' + 'consecutive')

        if len(sentence[position]) > 1 and sentence[position][0] == sentence[position][1]:
            template.append('13:' + sentence[position][0] + '*' + 'consecutive')

        if len(sentence[position]) == 1:
            template.append('12:' + cur_word + '*' + last_word_last_char + '*' + next_word_first_char)

        for i in range(0, 4):
            if i > len(sentence[position]) - 1:
                break
            template.append('14:' + sentence[position][0:i + 1])
            template.append('15:' + sentence[position][-(i + 1)::])
        return template

    def create_feature_template(self, sentence, position, pre_tag):
        template = []
        template.extend(self.create_bigram_feature(pre_tag))
        template.extend(self.create_unigram_feature(sentence, position))
        return template

    def create_feature_space(self):
        for i in range(len(self.train_data.sentences)):
            sentence = self.train_data.sentences[i]
            tags = self.train_data.tags[i]
            for j in range(len(sentence)):
                if j == 0:
                    pre_tag = self.BOS
                else:
                    pre_tag = tags[j - 1]
                template = self.create_feature_template(sentence, j, pre_tag)
                for f in template:
                    if f not in self.features:
                        self.features[f] = len(self.features)
                for tag in tags:
                    if tag not in self.tag_list:
                        self.tag_list.append(tag)
        self.tag_list = sorted(self.tag_list)
        self.tag_to_index = {t: i for i, t in enumerate(self.tag_list)}
        self.index_to_tag = {i: t for i, t in enumerate(self.tag_list)}
        self.weights = np.zeros((len(self.features), len(self.tag_list)))
        self.v = np.zeros((len(self.features), len(self.tag_list)))
        self.update_times = np.zeros((len(self.features), len(self.tag_list)))
        self.bigram_features = [self.create_bigram_feature(prev_tag) for prev_tag in self.tag_list]
        print("特征的总数是：{}".format(len(self.features)))

    def get_score(self, feature, averaged=False):
        if averaged:
            scores = [self.v[self.features[f]] for f in feature if f in self.features]
        else:
            scores = [self.weights[self.features[f]] for f in feature if f in self.features]
        return np.sum(scores, axis=0)

    def predict(self, sentence, averaged):
        length = len(sentence)
        delta = np.zeros((length, len(self.tag_list)))
        path = np.zeros((length, len(self.tag_list)), dtype=int)
        feature_first = self.create_feature_template(sentence, 0, self.BOS)
        delta[0] = self.get_score(feature_first, averaged)
        path[0] = -1
        bigram_scores = np.array([self.get_score(bigram_feature, averaged) for bigram_feature in self.bigram_features])
        # 对于每一个bigram_feature其实就是对于每一个pre_tag
        for i in range(1, length):
            unigram_features = self.create_unigram_feature(sentence, i)
            unigram_scores = self.get_score(unigram_features, averaged)
            scores = np.transpose(bigram_scores + unigram_scores) + delta[i - 1]
            path[i] = np.argmax(scores, axis=1)
            delta[i] = np.max(scores, axis=1)
        predict_tag_list = []
        tag_index = np.argmax(delta[length - 1])
        predict_tag_list.append(self.index_to_tag[tag_index])
        for i in range(length - 1):
            tag_index = path[length - 1 - i][tag_index]
            predict_tag_list.insert(0, self.index_to_tag[tag_index])
        return predict_tag_list

    def update_v(self, findex, tindex, update_time, last_w_value):
        last_update_time = self.update_times[findex][tindex]  # 上一次更新所在的次数
        current_update_time = update_time  # 本次更新所在的次数
        self.update_times[findex][tindex] = update_time
        self.v[findex][tindex] += (current_update_time - last_update_time - 1) * last_w_value + self.weights[findex][
            tindex]

    def evaluate(self, data, averaged):
        total_num = 0
        correct_num = 0
        for i in range(len(data.sentences)):
            sentence = data.sentences[i]
            tags = data.tags[i]
            total_num += len(tags)
            predict = self.predict(sentence, averaged)
            for j in range(len(tags)):
                if tags[j] == predict[j]:
                    correct_num += 1
        return correct_num, total_num, correct_num / total_num

    def perceptron_online_training(self, iterator, stop_iterator, shuffle, averaged):
        max_dev_precision = 0
        counter = 0
        update_time = 0
        max_iterator = -1
        data = self.train_data.split()
        if averaged:
            print("使用累加特征权重：")
        else:
            print("不使用累加特征权重：")
        for iter in range(iterator):
            print('iterator: {}'.format(iter))
            start_time = datetime.datetime.now()
            if shuffle:
                print('\t正在打乱训练数据...')
                random.shuffle(data)
                print("\t数据已打乱，正在进行预测...")
            bigram_features = [self.create_bigram_feature(pre_tag) for pre_tag in self.tag_list]
            for i in range(len(self.train_data.sentences)):
                sentence = self.train_data.sentences[i]
                tags = self.train_data.tags[i]
                predict = self.predict(sentence, averaged)
                if predict != tags:
                    update_time += 1
                    for j in range(len(sentence)):
                        unigram_feature = self.create_unigram_feature(sentence, j)
                        if j == 0:
                            gold_bigram_feature = self.create_bigram_feature(self.BOS)
                            predict_bigram_feature = self.create_bigram_feature(self.BOS)
                        else:
                            gold_pre_tag = tags[j - 1]
                            predict_pre_tag = predict[j - 1]
                            gold_bigram_feature = bigram_features[self.tag_to_index[gold_pre_tag]]
                            predict_bigram_feature = bigram_features[self.tag_to_index[predict_pre_tag]]

                        for f in unigram_feature:
                            if f in self.features:
                                findex = self.features[f]
                                tindex = self.tag_to_index[tags[j]]
                                last_w_value = self.weights[findex][tindex]
                                self.weights[findex][tindex] += 1
                                self.update_v(findex, tindex, update_time, last_w_value)

                                findex = self.features[f]
                                tindex = self.tag_to_index[predict[j]]
                                last_w_value = self.weights[findex][tindex]
                                self.weights[findex][tindex] -= 1
                                self.update_v(findex, tindex, update_time, last_w_value)

                        for f in gold_bigram_feature:
                            if f in self.features:
                                findex = self.features[f]
                                tindex = self.tag_to_index[tags[j]]
                                last_w_value = self.weights[findex][tindex]
                                self.weights[findex][tindex] += 1
                                self.update_v(findex, tindex, update_time, last_w_value)
                                # self.weights[self.features[f]][self.tag2id[tags[j]]] += 1

                        for f in predict_bigram_feature:
                            if f in self.features:
                                findex = self.features[f]
                                tindex = self.tag_to_index[predict[j]]
                                last_w_value = self.weights[findex][tindex]
                                self.weights[findex][tindex] -= 1
                                self.update_v(findex, tindex, update_time, last_w_value)
            # 本次迭代完成
            current_update_times = update_time  # 本次更新所在的次数
            for i in range(len(self.v)):
                for j in range(len(self.v[i])):
                    last_w_value = self.weights[i][j]
                    last_update_times = self.update_times[i][j]  # 上一次更新所在的次数
                    if current_update_times != last_update_times:
                        self.update_times[i][j] = current_update_times
                        self.v[i][j] += (current_update_times - last_update_times - 1) * last_w_value + self.weights[i][j]

            train_correct_num, total_num, train_precision = self.evaluate(self.train_data, averaged)
            print('\t' + 'train准确率：{} / {} = {}'.format(train_correct_num, total_num, train_precision))
            test_correct_num, test_num, test_precision = self.evaluate(self.test_data, averaged)
            print('\t' + 'test准确率：{} / {} = {}'.format(test_correct_num, test_num, test_precision))
            dev_correct_num, dev_num, dev_precision = self.evaluate(self.dev_data, averaged)
            print('\t' + 'dev准确率：{} / {} = {}'.format(dev_correct_num, dev_num, dev_precision))

            if dev_precision > max_dev_precision:
                max_dev_precision = dev_precision
                max_iterator = iter
                counter = 0
            else:
                counter += 1
            end_time = datetime.datetime.now()
            print("\t迭代执行时间为：" + str((end_time - start_time).seconds) + " s")
            if counter >= stop_iterator:
                break
        print('最优迭代轮次 = {} , 开发集准确率 = {}'.format(max_iterator, max_dev_precision))

if __name__ == '__main__':
    train_data_file = 'data/train.conll'  # 训练集文件
    dev_data_file = 'data/dev.conll'  # 开发集文件
    test_data_file = 'data/test.conll'  # 测试集文件
    iterator = 100  # 最大迭代次数
    stop_iterator = 10  # 连续多少次迭代没有提升效果就退出
    shuffle = True  # 每次迭代是否打乱数据
    averaged = False  # 是否使用averaged percetron

    total_start_time = datetime.datetime.now()
    lm = global_liner_model(train_data_file, dev_data_file, test_data_file)
    lm.create_feature_space()
    lm.perceptron_online_training(iterator, stop_iterator, shuffle, averaged)
    total_end_time = datetime.datetime.now()
    print("总执行时间为：" + str((total_end_time - total_start_time).seconds) + " s")


import os

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import animation

# Nos colocamos en la carpeta de este archivo.
def setup():
    workpath = os.path.dirname(os.path.abspath(__file__))
    os.chdir(workpath)

# Devolvemos f(x, y, z, t), donde (x, y, z) estan en
# S2 \ {(0,0,-1)} y t en [0, 1].
def transform_tan(x, y, z, t):
    l = (1 - t) + np.tan(t * np.arctan(1 + z))
    return x / l, y / l, -t + z * (1 - t)

# Dado un tiempo t, una colección de puntos de la superficie
# (x, y, z) y de la curva (x_, y_, z_) calculamos f_t para
# cada uno de ellos.
def animate(x, y, z, x_, y_, z_, t):

    xt, yt, zt = transform_tan(x, y, z, t)
    x_t, y_t, z_t = transform_tan(x_, y_, z_, t)

    ax = plt.axes(projection='3d')

    # Fijamos los ejes para ver fielmente la deformación.
    ax.set_xlim3d(-1, 1)
    ax.set_ylim3d(-1, 1)
    ax.set_zlim3d(-1, 1)

    # Pintamos la superficie deformada en tiempo t.
    ax.plot_surface(xt, yt, zt, rstride=1, cstride=1,
                    cmap='jet', edgecolor='none')

    # Pintamos la curva gamma deformada en tiempo t.
    ax.plot(x_t, y_t, z_t, '-b', c="white", zorder=3)
    return ax,

# Ejercicio 3
def exercise3():
    # Parametrización discreta de la esfera.
    u = np.linspace(0, np.pi, 30)
    v = np.linspace(0, 2 * np.pi, 60)

    x = np.outer(np.sin(u), np.sin(v))
    y = np.outer(np.sin(u), np.cos(v))
    z = np.outer(np.cos(u), np.ones_like(v))

    # Parametrización discreta de la curva gamma.
    tetha = np.linspace(0, np.pi, 500)

    z2 = np.sin(tetha) * np.sin(17.5 * tetha)
    y2 = np.sin(tetha) * np.cos(17.5 * tetha)
    x2 = np.cos(tetha)

    # Generamos la animacion.
    fig = plt.figure(figsize=(6, 6))
    ani = animation.FuncAnimation(fig, lambda t: animate(x, y, z, x2, y2, z2, t),
                                  np.arange(0, 1, 0.0125), interval=80)

    ani.save("projected_sphere_tangent_version.gif", fps=10)

if __name__ == "__main__":
    setup()
    exercise3()


import json
import randomgeneration as rg
import randomgrader as grader
import chevron
import lxml.html
import prairielearn as pl
import random

# INTIALIZE PARAMETERS
RANDOMIZED_QUESTION = False
FEEDBACK = True
MARKERFEEDBACK = False

# MARKING
MAX_GRADE = 10
MAX_ATTEMPTS = None
ENTITY_NAME = 0.2
ENTITY_ATTRIBUTES = 0.1
ENTITY_KEY = 0.2
EXTRA_ENTITY_PENALTY = 0.25
WEAK_ENTITY = 0.5
RELATIONSHIP = 0.5
CARDINALITY = 0.25
EXTRA_RELATIONSHIP_PENALTY = 0.25
# CARDINALITY_TEXT = 0.25

# RANDOMIZED QUESTION

def prepare(element_html, data):
    element = lxml.html.fragment_fromstring(element_html)
    randomized_question = pl.get_boolean_attrib(element, 'random', RANDOMIZED_QUESTION)
    data['params']['oldAnswer'] = None
    data['params']['feedback'] = None
    data['params']['answer'] = []
    if randomized_question is False:
        setup_question(element, data)
        setup_answer(element, data)
    else:
        question = rg.generate_random(data)
        data['params']['question_data'] = question['question']
        data['params']['answer'] = [{"answer": question['answer']}]

    required_attribs = [

    ]
    optional_attribs = [
        'random',  # false (default), or true to randomize question
        'feedback',  # true (default), or false for no feedback
        'max-grade',  # 10 (default), or a float
        'marker-feedback' #false (default), or true for feedback after final attempt
    ]
    pl.check_attribs(element, required_attribs=required_attribs, optional_attribs=optional_attribs)

def setup_question(element, data):
    for child in element:
        is_question = (child.tag in ['uml-question', 'uml_question'])
        if is_question:
            data['params']['question_data'] = pl.inner_html(child)

def setup_answer(element, data):
    for child in element:
        is_answer = (child.tag in ['uml-answer', 'uml_answer'])
        if is_answer:
            data['params']['answer'].append({"answer": (pl.inner_html(child))})

def setup_marking(element_html, data):
    element = lxml.html.fragment_fromstring(element_html)
    global ENTITY_NAME
    global ENTITY_ATTRIBUTES
    global ENTITY_KEY
    global EXTRA_ENTITY_PENALTY
    global WEAK_ENTITY
    global RELATIONSHIP
    global CARDINALITY
    global EXTRA_RELATIONSHIP_PENALTY
    # global CARDINALITY_TEXT
    for child in element:
        is_marking = (child.tag in ['uml-marking', 'uml_marking'])
        if is_marking:
            ENTITY_NAME = pl.get_float_attrib(child, 'entity-name', ENTITY_NAME)
            ENTITY_ATTRIBUTES = pl.get_float_attrib(child, 'entity-attributes', ENTITY_ATTRIBUTES)
            ENTITY_KEY = pl.get_float_attrib(child, 'entity-key', ENTITY_KEY)
            EXTRA_ENTITY_PENALTY = pl.get_float_attrib(child, 'extra-entity-penalty', EXTRA_ENTITY_PENALTY)
            WEAK_ENTITY = pl.get_float_attrib(child, 'weak-entity', WEAK_ENTITY)
            RELATIONSHIP = pl.get_float_attrib(child, 'relationship', RELATIONSHIP)
            CARDINALITY = pl.get_float_attrib(child, 'cardinality', CARDINALITY)
            EXTRA_RELATIONSHIP_PENALTY = pl.get_float_attrib(child, 'extra-relationship-penalty',
                                                             EXTRA_RELATIONSHIP_PENALTY)
            # CARDINALITY_TEXT= pl.get_float_attrib(child, 'cardinality_text', CARDINALITY_TEXT)
    maximum_grade = pl.get_float_attrib(element, 'max-grade', MAX_GRADE)
    grader.setMaxGrade(maximum_grade)
    grader.setMarkingCriteria(ENTITY_NAME, ENTITY_ATTRIBUTES, ENTITY_KEY, EXTRA_ENTITY_PENALTY, WEAK_ENTITY,
                              RELATIONSHIP, CARDINALITY, EXTRA_ENTITY_PENALTY)
    # grader.setMarkingCriteria(ENTITY_NAME, ENTITY_ATTRIBUTES, ENTITY_KEY, EXTRA_ENTITY_PENALTY, WEAK_ENTITY,
    #                           RELATIONSHIP, CARDINALITY, EXTRA_ENTITY_PENALTY,CARDINALITY_TEXT)
    return maximum_grade

def render(element_html, data):
    element = lxml.html.fragment_fromstring(element_html)
    give_feedback = pl.get_boolean_attrib(element, 'feedback', FEEDBACK)
    final_feedback = pl.get_boolean_attrib(element, 'marker-feedback', MARKERFEEDBACK)
    data['params']['oldAnswer'] = data['submitted_answers'].get('c', '')
    if data['panel'] == 'question':
        html_params = {
            'question_data': data['params']['question_data'],
            'oldAnswer': data['params']['oldAnswer'],
        }
        with open('uml-element.mustache', 'r', encoding='utf-8') as f:
            html = chevron.render(f, html_params).strip()

    elif data['panel'] == 'submission':
        if give_feedback is True:
            try:
                feedback = data['partial_scores']['uml_answer'].get('feedback', None)
            except KeyError:
                feedback = ''
        else:
            feedback = ''
        html_params = {
            'submission': True,
            'feedback': feedback,
            'oldAnswer': data['params']['oldAnswer'],
        }
        with open('uml-submission.mustache', 'r', encoding='utf-8') as f:
            html = chevron.render(f, html_params).strip()

    elif data['panel'] == 'answer':
        if final_feedback is True:
            try:
                marker_feedback = data['partial_scores']['uml_answer'].get('marker_feedback', None)
            except KeyError:
                marker_feedback = ''
        else:
            marker_feedback = ''
        html_params = {
            'answer': True,
            'finalFeedback': marker_feedback,
            'oldAnswer': data['params']['oldAnswer'],
        }
        with open('uml-answer.mustache', 'r', encoding='utf-8') as f:
            html = chevron.render(f, html_params).strip()
    # else:
    #     raise Exception('Invalid panel type: %s' % data['panel'])

    return html

def grade(element_html, data):
    maximum_grade = setup_marking(element_html, data)
    graded_question = grader.grade_question(data)
    score = graded_question['params']['score']
    feedback = graded_question['params']['feedback']
    marker_feedback = graded_question['params']['marker_feedback']
    data['params']['feedback'] = feedback
    data['partial_scores']['uml_answer'] = {
        'score': score,
        'weight': maximum_grade,
        'feedback': feedback,
        'marker_feedback': marker_feedback
    }


# Code Written by Myeong-Gyu.Lee
import os, zipfile

def unzip(parent_list):
    current_dir = os.path.abspath(os.path.dirname(__file__))
    parent_dir = os.path.abspath(current_dir + "/../../")

    if '2019-3rd-ml-month-with-kakr' in parent_list:
        DatasetPath = os.path.join(parent_dir, '2019-3rd-ml-month-with-kakr')
        print('Current Dataset Path : ' + DatasetPath)

        file_list_zip = [file for file in os.listdir(DatasetPath) if file.endswith(".zip")]

        for i in range(len(file_list_zip)):
            NewFolderpath = os.path.join(DatasetPath, os.path.splitext(file_list_zip[i])[0])

            if not (os.path.isdir(NewFolderpath)):  # 디렉토리 존재여부 확인
                os.makedirs(NewFolderpath)
                print("New directory '" + str(NewFolderpath) + "' has been created.")

            print('Now Unzip :', NewFolderpath)
            zip = zipfile.ZipFile(os.path.join(DatasetPath, file_list_zip[i]))
            zip.extractall(NewFolderpath)
            zip.close()
            print('Done :', NewFolderpath)

            if os.path.isfile(os.path.join(DatasetPath, file_list_zip[i])):
                os.remove(os.path.join(DatasetPath, file_list_zip[i]))
                print(file_list_zip[i] + ' has been removed.')
    else:
        print('Go https://www.kaggle.com/c/14724/download-all and download & unzip dataset to ' + parent_dir + '.')
        raise NotImplementedError


""" Game called Higher Lower, where we decide who has higher followers on Instagram
"""
from art import logo, vs
from game_data import data
from os import system
from random import randint

system('clear')

num_of_data_elements = len(data)
current_score = 0
#pick a random data value from data
data_item_num_A = randint(0, num_of_data_elements-1)
play = True

while play:
	#display higher lower
	print(f"{logo}\n")

	#display A
	data_item_A = data[data_item_num_A]
	print(f"Compare A: {data_item_A['name']}, {data_item_A['description']} from {data_item_A['country']}\n")

	#display vs
	print(f"{vs}\n")

	#pick a random data value from data and display as B. Ensure B and A are not the same
	data_item_num_B = randint(0, num_of_data_elements-1)
	while data_item_num_B == data_item_num_A:
		data_item_num_B = randint(0, num_of_data_elements-1)

	data_item_B = data[data_item_num_B]
	print(f"Against B: {data_item_B['name']}, {data_item_B['description']} from {data_item_B['country']}\n")

	#get user input A or B
	inp = input("Who has more followers? Type 'A' or 'B' ")

	#copy followers for A and B
	followers_A = data_item_A['follower_count']
	followers_B = data_item_B['follower_count']

	if followers_A > followers_B:
		ans = 'A'
	else:
		ans = 'B'

	system('clear')
	#verify user input to be correct or false
	if ans == inp:
		current_score += 1
		print(f"You're right! Current Score: {current_score}")
		data_item_num_A = data_item_num_B
	else:
		play = False
		print(f"The answer is wrong! Your score is {current_score}")