from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _

from account.api.serializers import UserSerializer
from account.api.serializers import ParticipantSerializer
from question.api.serializers import QuestionSerializer
from quiz.models import Quiz, QuizParticipant
from question.models import ParticipantAnswer

User = get_user_model()

class QuizSerializer(serializers.ModelSerializer):
    owner_id = serializers.SerializerMethodField()
    owner_name = serializers.SerializerMethodField()
    course_name = serializers.SerializerMethodField()
    participants = ParticipantSerializer(many=True)
    questions = QuestionSerializer(many=True)

    class Meta:
        model = Quiz
        fields = (
            'id',
            'owner_id',
            'owner_name',
            'course',
            'course_name',
            'name',
            'description',
            'start',
            'end',
            'be_graded',
            'percentage',
            'is_private',
            'participants',
            'questions',
        )
        extra_kwargs = {
            'percentage': {'max_digits': 100, 'decimal_places': 2}
        }

    def get_owner_id(self, instance):
        return instance.owner.id

    def get_owner_name(self, instance):
        return instance.owner.username

    def get_course_name(self, instance):
        if instance.course:
            return instance.course.name
        return None

class QuizCreateUpdateSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = Quiz
        fields = (
            'id',
            'name',
            'description',
            'course',
            'participants',
            'questions',
            'start',
            'end',
            'be_graded',
            'percentage'
        )

class QuizAppendSerializer(serializers.ModelSerializer):

    class Meta:
        model = Quiz
        fields = (
            'id',
        )

class QuizParticipantAnswerSerializer(serializers.ModelSerializer):
    question = QuestionSerializer(many=False)

    class Meta:
        model = ParticipantAnswer
        fields = (
            'id',
            'question',
            'answer',
            'participant_id',
            'is_correct',
            'is_validated',
            'point',
        )

class QuizParticipantSerializer(serializers.ModelSerializer):
    participant = UserSerializer(many=False)

    class Meta:
        model = QuizParticipant
        fields = '__all__'


"""interpret the output of `docker compose` commands"""

import json
import re

def try_match(pattern, subject):
    return re.fullmatch(pattern, subject, re.DOTALL)

def parse_docker_compose_up_line(line):
    # service_log: {service, payload}
    match = try_match(
        r'(?P<service>\S+)(?P<delimiter>[_-])\d+\s*\| (?P<payload>.*)\n', line)
    if match is not None:
        # Some docker compose setups (versions?) prefix the service name by the
        # project name, while others don't.  The parts of the name are
        # delimited by either underscores or hyphens, and we don't use service
        # names with either delimiter in them, so we can pull apart the name
        # here.
        delimiter = match.groupdict()['delimiter']
        parts = match.groupdict()['service'].split(delimiter)
        if len(parts) == 2:
            service = parts[1]
        elif len(parts) == 1:
            service = parts[0]
        else:
            raise Exception(
                f"Log line's service name has unexpected format: {match.groupdict()} in: {line}"
            )
        return ('service_log', {
            'service': service,
            'payload': match.groupdict()['payload']
        })

    # begin_create_container: {container}
    begin_create_container = r'\s*(Rec|C)reating (?P<container>\S+)\s*\.\.\.\s*'
    match = try_match(begin_create_container, line)
    if match is not None:
        return ('begin_create_container', {
            'container': match.groupdict()['container']
        })

    # finish_create_container: {container}
    match = try_match(begin_create_container + r'done\s*', line)
    if match is not None:
        return ('finish_create_container', {
            'container': match.groupdict()['container']
        })

    # Different docker compose setups (versions?) produce different output
    # when a container is creating/created.  Here are the other flavors of
    # begin_create_container and finish_create_container.

    # begin_create_container: {container}
    match = try_match(r'\s*Container (?P<container>\S+)\s+Creating\s*', line)
    if match is not None:
        return ('begin_create_container', {
            'container': match.groupdict()['container']
        })

    # finish_create_container: {container}
    match = try_match(r'\s*Container (?P<container>\S+)\s+Created\s*', line)
    if match is not None:
        return ('finish_create_container', {
            'container': match.groupdict()['container']
        })

    # attach_to_logs:  {'containers': [container, ...]}
    match = try_match(r'\s*Attaching to (?P<containers>\S+(, \S+)*\s*)', line)
    if match is not None:
        return ('attach_to_logs', {
            'containers': [
                container.strip()
                for container in match.groupdict()['containers'].split(', ')
            ]
        })

    # image_build_success: {image}
    match = try_match(r'\s*Successfully built (?P<image>\S+)\s*', line)
    if match is not None:
        return ('image_build_success', {'image': match.groupdict()['image']})

    return ('other', {'payload': line})

def parse_docker_compose_down_line(line):
    match = try_match(r'\s*Removing network (?P<network>\S+)\n', line)
    if match is not None:
        return ('remove_network', {'network': match.groupdict()['network']})

    begin_stop_container = r'\s*Stopping (?P<container>\S+)\s*\.\.\.\s*'
    match = try_match(begin_stop_container, line)
    if match is not None:
        return ('begin_stop_container', {
            'container': match.groupdict()['container']
        })

    match = try_match(begin_stop_container + r'done\s*', line)
    if match is not None:
        return ('end_stop_container', {
            'container': match.groupdict()['container']
        })

    begin_remove_container = r'\s*Removing (?P<container>\S+)\s*\.\.\.\s*'
    match = try_match(begin_remove_container, line)
    if match is not None:
        return ('begin_remove_container', {
            'container': match.groupdict()['container']
        })

    match = try_match(begin_remove_container + r'done\s*', line)
    if match is not None:
        return ('end_remove_container', {
            'container': match.groupdict()['container']
        })

    return ('other', {'payload': line})

def parse_trace(log_line):
    """Return a trace (list of list of dict) parsed from the specified
    `log_line`, or return `None` if `log_line` is not a trace.
    """
    try:
        trace = json.loads(log_line)
    except json.decoder.JSONDecodeError:
        return None

    if not isinstance(trace, list):
        return None

    return trace

def parse_access_log_sync_line(log_line):
    # Return a `dict` containing the sync token parsed from the specified
    # `log_line` if `log_line` is from the nginx access log for a sync request.
    # Otherwise, return `None`.
    match = try_match(rf'.*"GET /sync\?token=(?P<token>\S+) HTTP/1\.1".*',
                      log_line)
    if match is not None:
        return {'token': match.groupdict()['token']}


from django.urls import path
from django.conf.urls import url
from .views import inicio, lista, modo,read,update

urlpatterns = [
    path('', inicio, name='inicio'),
    url(r'^(?P<id>\d+)/read/',read, name="read"),
    url(r'^(?P<id>\d+)/update/',update, name="update"),
    path('lista/', lista, name ="lista"),
    url(r'^(?P<id>\d+)/$', modo, name='modo')

    ]


def main():
    #write your code below this line
    numbers = []

    while True:
        number = int(input())

        if number == -1:
            break

        numbers.append(number)

    query = int(input("Search for?"))
    for i in range(len(numbers)):
        if numbers[i] == query:
            print("{} is at index {}".format(query, i))

if __name__ == '__main__':
    main()


def solution(arr):
    groupby = list(set(arr))
    result = dict()
    for item in groupby:
        result[item] = arr.count(item)

    answer = []

    for v in result.values():
        if v != 1:
            answer.append(v)

    if not len(answer):
        return [-1]

    return answer

print(solution([3,5,7,9,1]))
print(solution([1,2,3,3,3,3,4,4]))
print(solution([3,2,4,4,2,5,2,5,5]))


import pandas as pd
import numpy as np

from collections import OrderedDict

# 連続値から代表値を取得する
def auto_agg(data: pd.DataFrame, group, agg_cols, agg_funcs, orig=None, prefix='', suffix='', how='left', drop=False, as_index=True):
    """
    諸々を指定すると、集計・カラムのリネームを行い、最終結合用のDataFrameを返す。
    -------
    orig: DataFrame. 最後に戻すテーブルを設定する。（行数をそろえるため）
    data: DataFrame. 集計を行いたいDataFrameを設定する。
    group: list or str. 集計を行いたいカラムを設定する。
    agg_cols: list or list. 代表値を取得したいカラムを設定する。
    agg_func: list or list. 集約関数を設定する。
    prefix: str. 頭につけたい名前があれば指定する。
    suffix: str. 後ろにつけたい名前があれば指定する。
    how: str. マージ方法の指定。pandas の merge に依存。
    """
    if isinstance(agg_cols, str):
        agg_cols = [agg_cols]

    if isinstance(agg_funcs, str):
        agg_funcs = [agg_funcs]

    # dic = {col:agg_funcs for col in agg_cols} # make aggregation dictionary
    dic = OrderedDict(([[col, agg_funcs] for col in agg_cols]))
    agg_df = data.groupby(group, as_index=as_index).agg(dic)

    # make rename column list
    col_names = [f'{prefix}{key}_{value}{suffix}' for key in dic for value in dic[key]]
    agg_df.columns = col_names

    if orig is None:
        return agg_df

    # for final merge
    agg_df.reset_index(inplace=True)

    df = orig[group] # make dataset for merge
    del orig

    if isinstance(df, pd.Series):
        df = pd.DataFrame(df)

    df = df.merge(agg_df, on=group, how=how)

    if drop:
        df.drop(columns=group, inplace=True)

    return df

# カテゴリ値から個数と割合を算出する。
def auto_cnt_ratio(data: pd.DataFrame, group, tgt_cols, orig=None, prefix='', suffix='', how='left'):
    """
    諸々を指定すると、カテゴリの個数、割合の計算・カラムのリネームを行い、
    最終結合前のDataFrameを返す。
    ------
    orig: DataFrame. 最後に戻すテーブルを設定する。（行数をそろえるため）
    data: DataFrame. 集計を行いたいDataFrameを設定する。
    group: list or str. 集計を行いたいカラムを設定する。
    tgt_cols: list or str. カウントを取得したいカラムを設定する。
    prefix: str. 頭につけたい名前があれば指定する。
    suffix: str. 後ろにつけたい名前があれば指定する。
    how: マージ方法の指定。
    """
    if isinstance(group, str):
        group = [group]

    if isinstance(tgt_cols, str):
        tgt_cols = [tgt_cols]

    all_cols = group + tgt_cols
    df = data[all_cols] # to dataset smaller

    cnt_arr = []
    ratio_arr = []
    for tgt in tgt_cols:
        cnt_tmp_df = pd.crosstab(index=[df[f'{g}'] for g in group],
                                 columns=df[tgt])
        ratio_tmp_df = pd.crosstab(index=[df[f'{g}'] for g in group],
                                   columns=df[tgt],
                                   normalize='index')

        cnt_tmp_df.columns = [f'{prefix}{tgt}Cnt_{cat}{suffix}' for cat in list(cnt_tmp_df.columns)]
        ratio_tmp_df.columns = [f'{prefix}{tgt}Ratio_{cat}{suffix}' for cat in list(ratio_tmp_df.columns)]

        cnt_arr.append(cnt_tmp_df)
        ratio_arr.append(ratio_tmp_df)

    cnt_conc_df = pd.concat(cnt_arr, axis=1)
    ratio_conc_df = pd.concat(ratio_arr, axis=1)

    if orig is None:
        return cnt_conc_df, ratio_conc_df

    cnt_conc_df.reset_index(inplace=True)
    ratio_conc_df.reset_index(inplace=True)

    # make dataset for merge
    cnt_df = orig[group]
    ratio_df = orig[group]
    del data, orig

    cnt_df = cnt_df.merge(cnt_conc_df, on=group, how=how)
    ratio_df = ratio_df.merge(ratio_conc_df, on=group, how=how)

    return cnt_df, ratio_df

def merge_all(orig: pd.DataFrame, tables: list, group):
    """
    配列の長さが一致、結合キーが完全一致しているテーブルについて、
    merge ではなく、numpy array の concat で DataFrame を再生成する。
    -----
    orig: DataFrame. 最後に戻すテーブルを設定する。
    tables: list. 結合したいテーブルをリストで指定する。
    group: list or str. 集計を行いたいカラムを設定する。
    """
    assert type(tables) == list, 'tables must be list.'

    df = pd.concat([orig, *[t.drop(columns=group) for t in tables]], axis=1)

    return df


from scipy.sparse import csr_matrix
from sklearn import preprocessing
import implicit
import numpy as np
import pickle
import pandas as pd

class ALSRecommender:
    def __init__(self, factors=50, regularization=0.01, iterations=15):
        self.data_sparse = None
        self.le = None
        self.model = None
        self.factors = factors
        self.regularization = regularization
        self.iterations = iterations

    def fit(self, data, save=False, filename=None):
        data["rating"] = 1.0  # add column with ratings
        data["rating"] = data["rating"].astype("float32")
        data = data.drop_duplicates(["track_id", "user_id"])  # remove duplicates

        self.le = preprocessing.LabelEncoder()
        self.le.fit(data["track_id"])

        chunk_size = 5000
        chunks = [x for x in range(0, data.shape[0], chunk_size)]
        new_df = pd.concat([data.iloc[ chunks[i]:chunks[i + 1] - 1 ].pivot(index='track_id', columns='user_id', values='rating') for i in range(0, len(chunks) - 1)])

        #wide_data = data.pivot(index="track_id", columns="user_id", values="rating").fillna(0)
        wide_data = new_df.fillna(0)
        self.data_sparse = csr_matrix(wide_data.values)

        self.model = implicit.als.AlternatingLeastSquares(factors=self.factors, regularization=self.regularization,
                                                          iterations=self.iterations)
        self.model.fit(self.data_sparse)

        if save:
            if filename is None:
                filename = "ALS_trained_m.sav"
            pickle.dump(self, open(filename, 'wb'))

    def refit(self, factors=50, regularization=0.01, iterations=15):
        # keep the sparse matrix, but retrain the model with different parameters
        # creating the sparse matrix takes a lot longer than training itself
        self.factors = factors
        self.regularization = regularization
        self.iterations = iterations

        self.model = implicit.als.AlternatingLeastSquares(factors=self.factors, regularization=self.regularization,
                                                          iterations=self.iterations)
        self.model.fit(self.data_sparse)

    def load_model(self, filename):
        with open(filename, "rb") as f:
            loaded_model = pickle.load(f)
            self.model = loaded_model.model
            self.data_sparse = loaded_model.data_sparse
            self.le = loaded_model.le

        del loaded_model

    def predict(self, input_ids, k, banned_ids=None, disliked_ids=None):
        if k == "all":
            k = len(self.le.classes_)

        input_ids = list(set(input_ids) & set(self.le.classes_))  # filter inputs unseen during training
        if not input_ids:
            raise RuntimeError("None of the input ids are in the dataset.")

        if banned_ids is not None:
            banned_ids = list(set(banned_ids) & set(self.le.classes_))
            banned_ids_tr = self.le.transform(banned_ids)
        else:
            banned_ids_tr = []

        if disliked_ids is not None:
            disliked_ids = list(set(disliked_ids) & set(self.le.classes_))
            disliked_ids_tr = self.le.transform(disliked_ids)
        else:
            disliked_ids_tr = []

        input_ids_tr = self.le.transform(input_ids)
        user_input = np.zeros((len(self.le.classes_), 1))
        user_input[input_ids_tr] = 1
        user_input[disliked_ids_tr] = -100

        recs = self.model.recommend(0, csr_matrix(user_input.T), filter_already_liked_items=True,
                                    recalculate_user=True, N=k, filter_items=banned_ids_tr)
        recs = [x[0] for x in recs]
        return self.le.inverse_transform(recs)


# coding=utf-8
import datetime

import factory
import factory.fuzzy
from teryt_tree.factories import JednostkaAdministracyjnaFactory

class RESPFactory(factory.django.DjangoModelFactory):
    institution = factory.SubFactory("epuap_watchdog.institutions.factories.InstitutionFactory")
    name = factory.Sequence("resp-name-{0}".format)

    @factory.lazy_attribute_sequence
    def data(self, n):
        return {'adres': 'UL. WILEŃSKA {}'.format(n),
                'kod_pocztowy': "{0:02.0f}-{0:03.0f}".format(n),
                'miejscowosc': 'ŁÓDŹ',
                'name': self.name,
                'regon': n * 1000}

    class Meta:
        model = 'institutions.RESP'

class InstitutionFactory(factory.django.DjangoModelFactory):
    name = factory.Sequence("institution-name-{0}".format)
    epuap_id = factory.Sequence("institution-epuap_id-{0}".format)
    regon = factory.Sequence("{0:014.0f}".format)
    active = factory.Sequence(lambda n: n % 2 == 0)

    class Meta:
        model = 'institutions.Institution'

class ESPFactory(factory.django.DjangoModelFactory):
    institution = factory.SubFactory("epuap_watchdog.institutions.factories.InstitutionFactory")
    name = factory.Sequence("esp-name-{0}".format)
    active = factory.Sequence(lambda n: n % 2 == 0)

    class Meta:
        model = 'institutions.ESP'

class REGONFactory(factory.django.DjangoModelFactory):
    institution = factory.SubFactory("epuap_watchdog.institutions.factories.InstitutionFactory")
    name = factory.Sequence("regon-name-{0}".format)
    regon = factory.Sequence("{0:014.0f}".format)

    @factory.lazy_attribute_sequence
    def data(self, n):
        return {'adkorgmina_nazwa': '',
                'adkorgmina_symbol': '',
                'adkorkodpocztowy': '',
                'adkorkraj_nazwa': '',
                'adkorkraj_symbol': '',
                'adkormiejscowosc_nazwa': '',
                'adkormiejscowosc_symbol': '',
                'adkormiejscowoscipoczty_symbol': '',
                'adkormiejscowoscpoczty_nazwa': '',
                'adkornazwapodmiotudokorespondencji': '',
                'adkornietypowemiejscelokalizacji': '',
                'adkornumerlokalu': '',
                'adkornumernieruchomosci': '',
                'adkorpowiat_nazwa': '',
                'adkorpowiat_symbol': '',
                'adkorulica_nazwa': '',
                'adkorulica_symbol': '',
                'adkorwojewodztwo_nazwa': '',
                'adkorwojewodztwo_symbol': '',
                'adresemail': 'zlobek28@o2.pl',
                'adresemail2': '',
                'adresstronyinternetowej': '',
                'adsiedzgmina_nazwa': 'Kraków-Podgórze',
                'adsiedzgmina_symbol': '049',
                'adsiedzkodpocztowy': '30868',
                'adsiedzkraj_nazwa': 'POLSKA',
                'adsiedzkraj_symbol': 'PL',
                'adsiedzmiejscowosc_nazwa': 'Kraków',
                'adsiedzmiejscowosc_symbol': '0950960',
                'adsiedzmiejscowoscpoczty_nazwa': 'Kraków',
                'adsiedzmiejscowoscpoczty_symbol': '0950960',
                'adsiedznietypowemiejscelokalizacji': '',
                'adsiedznumerlokalu': '',
                'adsiedznumernieruchomosci': '21',
                'adsiedzpowiat_nazwa': 'm. Kraków',
                'adsiedzpowiat_symbol': '61',
                'adsiedzulica_nazwa': 'ul. Jana Kurczaba',
                'adsiedzulica_symbol': '10434',
                'adsiedzwojewodztwo_nazwa': 'MAŁOPOLSKIE',
                'adsiedzwojewodztwo_symbol': '12',
                'datapowstania': '2001-02-02',
                'datarozpoczeciadzialalnosci': '2011-01-01',
                'dataskresleniazregon': '',
                'datawpisudoregon': '2011-01-04',
                'datawznowieniadzialalnosci': '',
                'datazaistnieniazmiany': '2011-01-04',
                'datazakonczeniadzialalnosci': '',
                'datazawieszeniadzialalnosci': '',
                'formafinansowania_nazwa': 'JEDNOSTKA BUDŻETOWA',
                'formafinansowania_symbol': '2',
                'formawlasnosci_nazwa': 'WŁASNOŚĆ JEDNOSTEK SAMORZĄDU TERYTORIALNEGO LUB SAMORZĄDOWYCH OSÓB PRAWNYCH',
                'formawlasnosci_symbol': '113',
                'jednosteklokalnych': '0',
                'nazwa': 'ŻŁOBEK SAMORZADOWY NR 28',
                'nazwaskrocona': '',
                'nip': "{0:010.0f}".format(n),
                'numerfaksu': '0123456789',
                'numertelefonu': '0123456789',
                'numerwewnetrznytelefonu': '',
                'numerwrejestrzeewidencji': '1200076',
                'organrejestrowy_nazwa': 'WOJEWODA MAŁOPOLSKI',
                'organrejestrowy_symbol': '010120000',
                'organzalozycielski_nazwa': 'WOJEWODA MAŁOPOLSKI',
                'organzalozycielski_symbol': '200120000',
                'podstawowaformaprawna_nazwa': 'JEDNOSTKA ORGANIZACYJNA NIEMAJĄCA OSOBOWOŚCI PRAWNEJ',
                'podstawowaformaprawna_symbol': '2',
                'regon14': self.regon,
                'rodzajrejestruewidencji_nazwa': 'REJESTR ZAKŁADÓW OPIEKI ZDROWOTNEJ',
                'rodzajrejestruewidencji_symbol': '029',
                'szczegolnaformaprawna_nazwa': 'GMINNE SAMORZĄDOWE JEDNOSTKI ORGANIZACYJNE',
                'szczegolnaformaprawna_symbol': '429'}

    class Meta:
        model = 'institutions.REGON'

class JSTConnectionFactory(factory.django.DjangoModelFactory):
    institution = factory.SubFactory("epuap_watchdog.institutions.factories.InstitutionFactory")
    jst = factory.SubFactory("teryt_tree.factories.JednostkaAdministracyjnaFactory")

    class Meta:
        model = 'institutions.JSTConnection'

class REGONErrorFactory(factory.django.DjangoModelFactory):
    regon = factory.SubFactory("epuap_watchdog.institutions.factories.REGONFactory")
    exception = factory.Sequence("regonerror-exception-{0}".format)

    class Meta:
        model = 'institutions.REGONError'

class JSTConnectionFactory(factory.django.DjangoModelFactory):
    institution = factory.SubFactory("epuap_watchdog.institutions.factories.InstitutionFactory")
    jst = factory.SubFactory(JednostkaAdministracyjnaFactory)

    class Meta:
        model = 'institutions.JSTConnection'


import pymunk as pm
import pygame as pg
from utils import *

class Ball():
    def __init__(self, x, y, game):
        self.body = pm.Body()
        self.body.position = x,y
        self.body.velocity = 0,0
        self.body.angular_velocity = 0
        self.body.mass = 1000
        self.rad = 8
        self.shape = pm.Circle(self.body, 8)
        self.shape.density = 1
        self.shape.friction = 1
        self.shape.elasticity = 1
        game.space.add(self.body, self.shape)
        self.color = (0, 240, 0)

    def draw(self, screen):
        x,y = self.body.position
        pg.draw.circle(screen, self.color, (int(x),int(y)), self.rad)

class Wall():
    def __init__(self, vs, game):
        self.body = pm.Body(body_type=pm.Body.KINEMATIC)
        self.shape = pm.Poly(self.body, vs)
        self.shape.elasticity = 1
        self.shape.friction = 1
        self.shape.density = 1
        game.space.add(self.body, self.shape)
        self.color = (0,0,0)

    def draw(self, screen):
        #pg.draw.polygon(screen, BLACK, [self.body.local_to_world(v) for v in self.shape.get_vertices()])
        pg.draw.polygon(screen, self.color, [v for v in self.shape.get_vertices()])

class Goal():
    def __init__(self, pos):
        (left, top, width, height) = pos
        self.goal_loc = pg.Rect(left, top, width, height)
        self.color = (0, 255, 0)

    def draw(self, screen):
        pg.draw.rect(screen, self.color, self.goal_loc)

class GraspZone():
    def __init__(self, y, width):
        self.y = y
        self.width = width
        self.color = (0,0,0)

    def draw(self, screen):
        pg.draw.line(screen, self.color, (0, self.y), (self.width, self.y))

class ToolPart():
    def __init__(self, vs, game):
        self.body = pm.Body(body_type=pm.Body.KINEMATIC)
        self.shape = pm.Poly(self.body, vs)
        self.shape.friction = 1
        self.color = (0, 0, 255)
        game.space.add(self.body, self.shape)

class Tool():
    def __init__(self, parts, game):
        self.toolpart1 = ToolPart(parts[0], game)
        self.toolpart2 = ToolPart(parts[1], game)
        self.game = game
        self.part_list = [self.toolpart1, self.toolpart2]
        self.mode = 'move'
        self.is_grasped = False
        self.grasp_point = pm.Body(body_type=pm.Body.KINEMATIC)

    def draw(self, screen):
        #stays the same as first grasp
        x,y = self.part_list[0].body.center_of_gravity
        for tp in self.part_list:
            #draw tool part
            pg.draw.polygon(screen, tp.color, [tp.body.local_to_world(v) for v in tp.shape.get_vertices()])
        #draw grasper
        if self.is_grasped:
            pg.draw.circle(screen, (255, 0 , 0), self.grasp_point.position, 3)

    def grasp(self, cog, grasp_zone):
        if not self.is_grasped:
            if cog[1] > grasp_zone.y:
                self.is_grasped = True
                self.grasp_point._set_position(cog)
                self.game.space.add(self.grasp_point)
                for tp in self.part_list:
                    old_pos = tp.body.position
                    tp.body._set_center_of_gravity(cog)
                    tp.body._set_position(old_pos)

    def set_mode(self, mode):
        if mode in ['move', 'rotate']:
            self.mode = mode

    def make_move(self, dir, wall_list, ball, grasp_zone):
        if self.is_grasped:
            if self.mode=='move':
                self.move(dir, wall_list, ball, grasp_zone)
            else:
                self.rotate(dir, wall_list, ball)

    def move(self, dir, wall_list, ball, grasp_zone):
        if dir=='u':
            vx, vy = 0, -50
        elif dir=='d':
            vx, vy = 0, 50
        elif dir=='r':
            vx, vy = 50, 0
        elif dir=='l':
            vx, vy = -50, 0

        for tp in self.part_list:
            tp.body.apply_force_at_world_point((vz,vy), self.grasp_point.position)
        """
        #first check if grasp pos will go above grasp zone, stop if so
        if(self.grasp_point.position[1] + (vy/100) < grasp_zone.y):
            self.stop()
            return

        #next check if any tool part will hit a wall, stop if so
        wall_polys = [[wall.body.local_to_world(v) for v in wall.shape.get_vertices()] for wall in wall_list]
        for tp in self.part_list:
            tp_poly = [(tp.body.local_to_world(v)[0] + (vx/100), tp.body.local_to_world(v)[1] + (vy/100))  for v in tp.shape.get_vertices()]
            #if(poly_circle_intersect([tp.body.local_to_world(v) for v in tp.shape.get_vertices()], ball.body.position[0], ball.body.position[1], ball.rad)):
            #    print("here")
            #    self.stop()
            #    return
            for wall_poly in wall_polys:
                if(do_polygons_intersect(tp_poly, wall_poly)):
                    self.stop()
                    return
        for tp in self.part_list:
            tp.body.velocity = vx, vy
        self.grasp_point.velocity = vx, vy
        """

    def rotate(self, dir, wall_list, ball):
        if dir=='r':
            #calc vx and vy (or va?) according to grasp point
            va = .4
        elif dir=='l':
            #calc vx and vy (or va?) according to grasp point
            va = -.4
        else:
            return

        wall_polys = [[wall.body.local_to_world(v) for v in wall.shape.get_vertices()] for wall in wall_list]
        for tp in self.part_list:
            tp_poly = [tp.body.local_to_world(rotate_vertex(tp.body.center_of_gravity, v, va/40)) for v in tp.shape.get_vertices()]
            #if(poly_circle_intersect([tp.body.local_to_world(v) for v in tp.shape.get_vertices()], ball.body.position[0], ball.body.position[1], ball.rad)):
            #    self.stop()
            #    return
            for wall_poly in wall_polys:
                if(do_polygons_intersect(tp_poly, wall_poly)):
                    self.stop()
                    return
        for tp in self.part_list:
            tp.body.angular_velocity = va
            self.game.space.reindex_shapes_for_body(tp.body)

    def flip():
        """ find which tool part is grasped
            get grasp point
            can draw line thru grasp point parallel to bottom line, or side lines
            one of those will be closer to horizontal
            if they click l or r, flip along one thats closer to horizontal
            otherwise, flip along one thats closer to vertical
            get hypothetical flip and see if hits walls or ball
            if not, flip
        """

    def stop(self):
        self.grasp_point.velocity = 0,0
        for tp in self.part_list:
            tp.body.velocity = 0,0
            tp.body.angular_velocity = 0

class GameState():
    def __init__(self, wall_pos, ball_pos, tool_parts, grasp_pos, grasp_width, goal_pos):
        self.space = pm.Space()
        self.init_params = (wall_pos, ball_pos, tool_parts, grasp_pos, grasp_width, goal_pos)
        self.reset()
        self.space.damping =  .4

    def reset(self):
        (wall_pos, ball_pos, tool_parts, grasp_pos, grasp_width, goal_pos) = self.init_params
        self.ball = Ball(ball_pos[0],ball_pos[1], self)
        self.wall_list = [Wall(wp, self) for wp in wall_pos]
        self.tool = Tool(tool_parts, self)
        self.grasp_zone = GraspZone(grasp_pos, grasp_width)
        self.goal = Goal(goal_pos)

    def draw(self, screen):
        self.goal.draw(screen)
        self.ball.draw(screen)
        for wall in self.wall_list:
            wall.draw(screen)
        self.tool.draw(screen)
        self.grasp_zone.draw(screen)


from datetime import datetime
from app import db

class City(db.Model):
   id = db.Column('City',db.Integer,primary_key=True)
   city_name = db.Column(db.Text)
   state_id = db.Column(db.Integer)
   code = db.Column(db.String(15))
   availability_status = db.Column(db.Boolean)
   description = db.Column(db.Text)
   is_default = db.Column(db.Boolean)
   created_at = db.Column(db.DateTime, default=datetime.utcnow)
   updated_at = db.Column(db.DateTime, default=datetime.utcnow)

def __init__(self, city_id,city_name, description, availability_status,is_default,created_at,updated_at):
   self.city_id = id.city_id
   self.city_name = city_name
   self.description = description
   self.availability_status = availability_status
   self.is_default = is_default
   self.created_at = created_at
   self.updated_at = updated_at

def __repr__(self):
    print(self)
    return {}
@property
def serialize(self):
    print(self)
    return {
       'id': self.city_id,
       'city_name': self.city_name,
    }


#!/usr/bin/env python

import argparse
import sys

sys.path.append(".")
import os

import utils

ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
ap.add_argument(
    "-n",
    "--npy_fpath",
    default="./data/okada/01/day1/split/LFP_MEP_1kHz_npy/orig/tt2-1_fp16.npy",
    help="The path of the input lfp file (.npy)",
)
args = ap.parse_args()

## Sets tee
sys.stdout, sys.stderr = utils.general.tee(sys)

## PATHs
lpath_lfp = args.npy_fpath

## Calculates ripple properties
rip_sec_with_props_df = utils.pj.calc_ripple_properties(lpath_lfp)

## Saves
spath = utils.pj.path_converters.LFP_to_ripples(
    lpath_lfp, rip_sec_ver="candi_with_props"
)
utils.general.save(rip_sec_with_props_df, spath)

## EOF


import tkinter as tk
from tkinter import ttk,messagebox, colorchooser
from math import floor, ceil
import os,subprocess,sys

class TextBody:
	def __init__(self,root,master,textWidget):
		self.root = root
		self.master=master
		self.text=textWidget
		self.fontsize=12;self.intrcolor='#00bfff';self.bg='#242424'
		self.fg='#ffffff';self.cursorcolor='#ffffff'
		self.scroll = tk.Scrollbar(self.text,command=self.text.yview, cursor='hand2',width=12 )
		self.scroll.pack(side=tk.RIGHT,fill=tk.Y)
		self.text.config(font=("Consolas",self.fontsize),fg=self.fg,bg=self.bg,insertbackground=self.cursorcolor,yscrollcommand=self.scroll.set)
		self.text.bind('<Key>',self.on_key) #to bind keys to text widget
		self.cmd=None
		self.cmdList=[]
		self.cmdPos=0;self.write=False
		self.text.bind('<Control-l>',lambda event: self.clearText(event))
		self.text.bind('<Control-u>',self.clearLine)
		self.text.bind('<Control-d>',self.clearText)
		self.text.bind('<Control-equal>',self.zoom_in)
		self.text.bind('<Control-minus>',self.zoom_out)
		self.text.bind('<Control-0>',self.zoom_reset)

	def insert_text(self, txt="", end="\n"):
		self.text.insert(tk.END, txt+end)
		self.text.see(tk.END) # make sure it is visible

	def show_prompt(self,interactiveprompt='>>> '):
		if self.write: self.interactiveprompt='write>>'
		self.insert_text(f"{self.interactiveprompt} ", end='')
		self.text.mark_set(tk.INSERT, tk.END) # make sure the input cursor is at the end
		self.cursor = self.text.index(tk.INSERT) # save the input position
		self.text.tag_add("changecolor",floor(float(self.cursor))+0.0,self.cursor)
		self.text.tag_config("changecolor",foreground=self.intrcolor,font=("Courier",self.fontsize,"bold"))

	#basic key func (up, down, left, right keys)
	def on_key(self,event):
		if event.keysym == 'Return':
			self.cmd = self.text.get(self.cursor, tk.END).strip()
			if self.cmd:
				self.cmdList.append(self.cmd)
			self.insert_text()
			self.do(self.cmd)
			self.show_prompt(self.interactiveprompt)
			return "break"
		elif event.keysym == "Up":
			if len(self.cmdList)!=0:
				if self.cmdPos > len(self.cmdList):
					return "break"
				self.cmdPos+=1;
				self.temp=self.cmdList[len(self.cmdList)-self.cmdPos]
				self.text.delete(self.cursor,tk.END)
				self.text.insert(self.cursor,self.temp)
			else:
				pass
			return "break"

		elif event.keysym == "Down":
			if len(self.cmdList)!=0 :
				try:
					if self.cmdPos <= 0:
						return "break"
					self.cmdPos+=(-1);
					self.temp=self.cmdList[len(self.cmdList)-self.cmdPos]
					self.text.delete(self.cursor,tk.END)
					self.text.insert(self.cursor,self.temp)
				except:
					self.text.delete(self.cursor,tk.END)
					return "break"
		elif event.keysym in ("Left","BackSpace"):
			current = self.text.index(tk.INSERT)
			if self.text.compare(current,"==",self.cursor):
				return "break"

	#clear line
	def clearLine(self,*args):
		self.text.delete(self.cursor,tk.END)

	#clear text
	def clearText(self,*args):
		self.text.delete(1.0,tk.END)
		self.show_prompt()

	#zoom in func
	def zoom_in(self,*args):
		self.fontsize+=1
		self.text.config(font=("Consolas",self.fontsize))
		self.text.tag_config("changecolor",foreground=self.intrcolor,font=("Consolas",self.fontsize,"bold"))

	#zoom in func
	def zoom_out(self,*args):
		self.fontsize-=1
		self.text.config(font=("Consolas",self.fontsize))
		self.text.tag_config("changecolor",foreground=self.intrcolor,font=("Consolas",self.fontsize,"bold"))

	#zoon reset func
	def zoom_reset(self,*args):
		self.fontsize=10
		self.text.config(font=("Consolas",self.fontsize))
		self.text.tag_config("changecolor",foreground=self.intrcolor,font=("Consolas",self.fontsize,"bold"))

	#defining colorprefernece
	def colorpreference(self):
		top = tk.Toplevel(self.root)
		top.geometry('400x270') if os.name == 'nt' else top.geometry('500x270')
		self.root.grab_set()
		top.resizable(0,0)
		self.bgColor=tk.StringVar();self.intrColor=tk.StringVar();self.fgColor=tk.StringVar();self.cursorColor=tk.StringVar()
		self.bgColor.set(self.bg);self.intrColor.set(self.intrcolor);self.fgColor.set(self.fg);self.cursorColor.set(self.cursorcolor)
		ttk.Label(top,text='Preference',font=('Consolas','14','bold')).grid(row=0,column=1,padx=15,pady=10)
		ttk.Label(top,text='Background',font=('Consolas','12')).grid(row=1,column=0,padx=15,pady=10)
		ttk.Entry(top,textvariable=self.bgColor).grid(row=1,column=1,padx=10)
		ttk.Button(top,text='Change',command=self.colorBg).grid(row=1,column=2,padx=10)
		ttk.Label(top,text='Foreground',font=('Consolas','12')).grid(row=2,column=0,pady=10)
		ttk.Entry(top,textvariable=self.fgColor).grid(row=2,column=1)
		ttk.Button(top,text='Change',command=self.colorFg).grid(row=2,column=2)
		ttk.Label(top,text='Intr-Color',font=('Consolas','12')).grid(row=3,column=0,pady=10)
		ttk.Entry(top,textvariable=self.intrColor).grid(row=3,column=1)
		ttk.Button(top,text='Change',command=self.colorIntr).grid(row=3,column=2)
		ttk.Label(top,text='Cursor-color',font=('Consolas','12')).grid(row=4,column=0,pady=10)
		ttk.Entry(top,textvariable=self.cursorColor).grid(row=4,column=1)
		ttk.Button(top,text='Change',command=self.colorCursor).grid(row=4,column=2)
		ttk.Button(top,text=' Done ',command=lambda: top.destroy()).place(relx=0.4,rely=0.85)
		top.mainloop()

	#background color
	def colorBg(self):
		self.bg = colorchooser.askcolor(title='Choose Color')[1]
		self.bgColor.set(self.bg)
		self.text.config(fg=self.fg,bg=self.bg,insertbackground=self.cursorcolor)

	#foreground color
	def colorFg(self):
		self.fg = colorchooser.askcolor(title='Choose Color')[1]
		self.fgColor.set(self.fg)
		self.text.config(fg=self.fg,bg=self.bg,insertbackground=self.cursorcolor)

	#cursor color
	def colorCursor(self):
		self.cursorcolor = colorchooser.askcolor(title='Choose Color')[1]
		self.cursorColor.set(self.cursorcolor)
		self.text.config(fg=self.fg,bg=self.bg,insertbackground=self.cursorcolor)

	#interactive prompt color
	def colorIntr(self):
		self.intrcolor = colorchooser.askcolor(title='Choose Color')[1]
		self.intrColor.set(self.intrcolor)
		self.text.tag_config("changecolor",foreground=self.intrcolor,font=("Consolas",self.fontsize,"bold"))


def findRoot(f, a, b, epsilon):
    m = (a+b)/2.0
    print(m)
    if m == 0:
        return m
    elif b-a <= epsilon and b-a >= -epsilon:
        return m
    if (f(a) > 0 and f(m) <0) or (f(a) < 0 and f(m) > 0):
        return findRoot(f, a, m, epsilon)
    else:
        return findRoot(f, m, b,epsilon)


# @Version : Python3.6
# @Time    : 2018/5/27 20:17
# @Author  : zhcf1ess
# @Site    :
# @File    : 算术运算和数据对齐.py
# @Software: PyCharm

import numpy as np
import pandas as pd

# s1 = pd.Series([7.3, -2.5, 3.4, 1.5], index=['a', 'c', 'd', 'e'])
# s2 = pd.Series([-2.1, 3.6, -1.5, 4, 3.1], index=['a', 'c', 'e', 'f', 'g'])

# print(s1 + s2) # 自动将相同索引的数值相加 不重叠的索引值设为nan
# 对于 DataFrame，对齐操作会同时发生在行和列上
f1 = pd.DataFrame(
    np.arange(9.).reshape((3, 3)),
    columns=list('bcd'),
    index=['Ohio', 'Texas', 'Colorado']
)

f2 = pd.DataFrame(
    np.arange(12.).reshape((4, 3)),
    columns=list('bde'),
    index=['Utah', 'Ohio', 'Texas', 'Oregon']
)
# print(f1 + f2)
df1 = pd.DataFrame({'A': [1, 2]})
df2 = pd.DataFrame({'B': [1, 2]})
# print(df1+df2)

notebook/第 05 章 pandas/5.2  基本功能/算术运算和数据对齐.py

算术运算和数据对齐.py


import matplotlib.pyplot as plt
import numpy as np
import tensorflow_probability as tfp

from tensorflow import Tensor
from tensorflow_probability.python.distributions import Distribution

class FlowExample:

    def __init__(self, dim):
        self.dim = dim

    def prob(self, q):
        raise NotImplementedError

    def sample(self, n_samples: int):
        raise NotImplementedError

    def plot(self, x_range, y_range, granularity=100, show_samples: Tensor=None, ax: plt.Axes=None, show=True):
        assert self.dim == 2
        xx, yy = np.meshgrid(np.linspace(*x_range, granularity),
                             np.linspace(*y_range, granularity))
        xy = np.stack([xx.flatten(), yy.flatten()]).T

        proba_image = self.prob(xy).numpy().reshape((granularity, granularity))

        if ax is None:
            ax: plt.Axes = plt.gca()

        ax.imshow(proba_image, extent=(*x_range, *y_range), cmap="coolwarm")

        if show_samples is not None:
            ax.scatter(show_samples[:, 0], show_samples[:, 1])

        if show:
            plt.show()

        return ax

    @classmethod
    def from_tensorflow_distribution(cls, distribution: Distribution or str):
        if type(distribution) is str:
            distribution = getattr(tfp.python.distributions, distribution)()

        distribution: Distribution
        shape = distribution.sample().shape.as_list()
        assert len(shape) == 1

        new_distrib = cls(dim=shape[0])
        new_distrib.prob = distribution.prob
        new_distrib.sample = distribution.sample

        return new_distrib

if __name__ == '__main__':
    gaussian = tfp.python.distributions.MultivariateNormalDiag(loc=np.zeros(2), scale_identity_multiplier=1)
    distrib = FlowExample.from_tensorflow_distribution(gaussian)
    x = distrib.sample(20)
    distrib.plot((-2, 2), (-2, 2), granularity=100, show_samples=x)


import cv2
import numpy as np
import os

def sub_color(src, K):
  z = src.reshape((-1, 3))
  z = np.float32(z)
  criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)

  ret, label, center = cv2.kmeans(z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
  center = np.uint8(center)
  res = center[label.flatten()]

  return res.reshape((src.shape))

def anime_filter(img, K):
  gray = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
  edge = cv2.blur(gray, (3, 3))
  edge = cv2.Canny(edge, 50, 150, apertureSize=3)
  edge = cv2.cvtColor(edge, cv2.COLOR_GRAY2BGR)
  img = sub_color(img, K)

  return cv2.subtract(img, edge)

def main():
  target_path = os.path.join(os.path.abspath(os.curdir), "images")
  img = cv2.imread('./images/shashin.jpg')
  print(os.path.join(target_path, "写真.jpg"))
  anime = anime_filter(img, 10)
  target_path = os.path.join(target_path, "illust.jpg")
  cv2.imwrite(target_path, anime)

if __name__ == '__main__':
  main()


"""Add context column

Revision ID: 06ce7016ca41
Revises: 440e8d7ed37b
Create Date: 2020-02-13 17:44:49.960247

"""
from alembic import op
import sqlalchemy as sa

from sqlalchemy.dialects.postgresql import JSONB

# revision identifiers, used by Alembic.
revision = '06ce7016ca41'
down_revision = '440e8d7ed37b'
branch_labels = None
depends_on = None

def upgrade():
    op.add_column('telegram_user', sa.Column('context', JSONB))

def downgrade():
    op.drop_column('telegram_user', 'context')


# Python 2 and 3
from __future__ import unicode_literals

from ..base import Resource

class Document(Resource):
    _resource_name = 'documents'

    _is_listable = False

    _as_is_fields = [
        'id',
        'href',
        'type',
        'audience',
        'content',
        'mime_type',
    ]
    _date_time_fields_utc = ['date_created']
    _resource_fields = [
        ('booking', 'Booking'),
    ]

class Invoice(Resource):
    _resource_name = 'invoices'

    _is_listable = False

    _as_is_fields = [
        'id',
        'href',
        'audience',
    ]

    _date_time_fields_utc = ['date_created']

    _resource_fields = [
        ('document', Document),
        ('booking', 'Booking'),
    ]


'''
AAMsoftmax loss function copied from voxceleb_trainer: https://github.com/clovaai/voxceleb_trainer/blob/master/loss/aamsoftmax.py
'''

import torch, math
import torch.nn as nn
import torch.nn.functional as F
from utils.tools import *

import numpy as np
import time
DISTANCE_MATRIX = np.array([[ 0. , 32.1, 23.4, 34.4, 68.7, 67.7, 57.1, 79.2, 51.7],
                            [32.1,  0. , 38.2, 24.5, 65.8, 60.7, 49.9, 76.6, 43.7],
                            [23.4, 38.2,  0. , 40.1, 68.6, 70.5, 61.8, 79.1, 55.9],
                            [34.4, 24.5, 40.1,  0. , 66. , 62.6, 54.2, 77.2, 34. ],
                            [68.7, 65.8, 68.6, 66. ,  0. , 67.1, 68.3, 71. , 68.4],
                            [67.7, 60.7, 70.5, 62.6, 67.1,  0. , 40.7, 78. , 63.9],
                            [57.1, 49.9, 61.8, 54.2, 68.3, 40.7,  0. , 76.2, 57.3],
                            [79.2, 76.6, 79.1, 77.2, 71. , 78. , 76.2,  0. , 77. ],
                            [51.7, 43.7, 55.9, 34. , 68.4, 63.9, 57.3, 77. ,  0. ]])
class AAMsoftmax(nn.Module):
    def __init__(self, n_class, m, s):

        super(AAMsoftmax, self).__init__()
        self.m = m
        self.s = s
        self.weight = torch.nn.Parameter(torch.FloatTensor(n_class, 192), requires_grad=True)
        self.ce = nn.CrossEntropyLoss()
        nn.init.xavier_normal_(self.weight, gain=1)
        self.cos_m = math.cos(self.m)
        self.sin_m = math.sin(self.m)
        self.th = math.cos(math.pi - self.m)
        self.mm = math.sin(math.pi - self.m) * self.m

    def forward(self, x, label=None):

        cosine = F.linear(F.normalize(x), F.normalize(self.weight))
        sine = torch.sqrt((1.0 - torch.mul(cosine, cosine)).clamp(0, 1))
        phi = cosine * self.cos_m - sine * self.sin_m
        phi = torch.where((cosine - self.th) > 0, phi, cosine - self.mm)
        one_hot = torch.zeros_like(cosine)
        one_hot.scatter_(1, label.view(-1, 1), 1)
        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
        output = output * self.s

        loss = self.ce(output, label)
        #prec1 = accuracy(output.detach(), label.detach(), topk=(1,))[0]

        return loss

class StandardSimilarityLoss(nn.Module):
    def __init__(self, n_class, n_model=192, loss_function=nn.MSELoss, distance_matrix=DISTANCE_MATRIX):

        super(StandardSimilarityLoss, self).__init__()
        self.linear = nn.Linear(n_model, n_class)
        self.loss_function = loss_function()
        self.distance_matrix = distance_matrix
    def forward(self, x, label):
        n = x.shape[0]
        y_true = torch.zeros((n, 9))
        for i in range(n):
            y_true[i] = torch.from_numpy(100 - self.distance_matrix[label[i]][:9])
        y_true = y_true.to(x.device)
        loss = self.loss_function(self.linear(x), y_true)
        return loss

class PairDistanceLoss(nn.Module):
    def __init__(self, loss_function=nn.MSELoss, distance_matrix=DISTANCE_MATRIX):
        super(PairDistanceLoss, self).__init__()
        self.loss_function = loss_function()
        self.distance_matrix = DISTANCE_MATRIX
    def forward(self, y_pred, labels):
        n = y_pred.shape[0]
        y_true = torch.zeros((n,n))
        for i in range(n):
            for j in range(n):
                y_true[i][j] = self.distance_matrix[labels[i]][labels[j]]
        y_true = y_true.to(y_pred.device)
        dist = torch.cdist(y_pred, y_pred, p=2)
        loss = self.loss_function(dist, y_true)
        return loss


import logging

import torch

from pybrid import utils
from pybrid.models.base import BaseModel
from pybrid.layers import FCLayer

class HybridModel(BaseModel):
    def __init__(
        self,
        nodes,
        amort_nodes,
        act_fn,
        mu_dt=0.01,
        use_bias=False,
        kaiming_init=False,
    ):
        self.nodes = nodes
        self.amort_nodes = amort_nodes
        self.mu_dt = mu_dt

        self.num_nodes = len(nodes)
        self.num_layers = len(nodes) - 1
        self.total_params = 0

        self.layers = []
        self.amort_layers = []
        for l in range(self.num_layers):
            layer_act_fn = utils.Linear() if (l == self.num_layers - 1) else act_fn
            layer = FCLayer(
                in_size=nodes[l],
                out_size=nodes[l + 1],
                act_fn=layer_act_fn,
                use_bias=use_bias,
                kaiming_init=kaiming_init,
            )
            self.layers.append(layer)
            self.total_params = self.total_params + ((nodes[l] * nodes[l + 1]) + nodes[l + 1])

            amort_layer = FCLayer(
                in_size=amort_nodes[l],
                out_size=amort_nodes[l + 1],
                act_fn=layer_act_fn,  # TODO
                use_bias=use_bias,
                kaiming_init=kaiming_init,
                is_amortised=True,
            )
            self.amort_layers.append(amort_layer)

        self.mean_weights, self.mean_biases = self.get_weight_stats()

    def reset(self):
        self.preds = [[] for _ in range(self.num_nodes)]
        self.errs = [[] for _ in range(self.num_nodes)]
        self.q_preds = [[] for _ in range(self.num_nodes)]
        self.q_errs = [[] for _ in range(self.num_nodes)]
        self.mus = [[] for _ in range(self.num_nodes)]

    def reset_mu(self, batch_size, init_std=0.05):
        for l in range(self.num_layers):
            tensor = torch.empty(batch_size, self.layers[l].in_size).normal_(mean=0, std=init_std)
            self.mus[l] = utils.set_tensor(tensor)

    def set_img_batch(self, img_batch):
        self.mus[-1] = img_batch.clone()

    def set_img_batch_amort(self, img_batch):
        self.q_preds[0] = img_batch.clone()

    def set_label_batch(self, label_batch):
        self.mus[0] = label_batch.clone()

    def forward(self, val):
        for layer in self.amort_layers:
            val = layer.forward(val)
        return val

    def backward(self, val):
        for layer in self.layers:
            val = layer.forward(val)
        return val

    def forward_mu(self):
        for l in range(1, self.num_nodes):
            self.q_preds[l] = self.amort_layers[l - 1].forward(self.q_preds[l - 1])

        mus = self.q_preds[::-1]
        for l in range(self.num_nodes):
            self.mus[l] = mus[l].clone()

    def backward_mu(self):
        for l in range(1, self.num_layers):
            self.mus[l] = self.layers[l - 1].forward(self.mus[l - 1])

    def train_batch(
        self,
        img_batch,
        label_batch,
        num_iters=20,
        init_std=0.05,
        fixed_preds=False,
        use_amort=True,
        thresh=None,
        no_backward=False,
    ):
        self.reset()
        if use_amort:
            self.set_img_batch_amort(img_batch)
            self.forward_mu()
            self.set_img_batch(img_batch)
        else:
            if not no_backward:
                self.set_label_batch(label_batch)
                self.backward_mu()
                self.set_img_batch(img_batch)
            else:
                self.reset_mu(img_batch.size(0), init_std)
                self.set_img_batch(img_batch)

        self.set_label_batch(label_batch)
        num_iter, avg_errs = self.train_updates(num_iters, fixed_preds=fixed_preds, thresh=thresh)
        self.update_grads()
        if use_amort:
            self.update_amort_grads()
        return num_iter, avg_errs

    def test_batch(
        self,
        img_batch,
        num_iters=100,
        init_std=0.05,
        fixed_preds=False,
        use_amort=True,
        thresh=None,
    ):
        self.reset()
        if use_amort:
            self.set_img_batch_amort(img_batch)
            self.forward_mu()
        else:
            self.reset_mu(img_batch.size(0), init_std)

        self.set_img_batch(img_batch)
        num_iter, avg_errs = self.test_updates(num_iters, fixed_preds=fixed_preds, thresh=thresh)
        return self.mus[0], num_iter, avg_errs

    def train_updates(self, num_iters, fixed_preds=False, thresh=None):
        for n in range(1, self.num_nodes):
            self.preds[n] = self.layers[n - 1].forward(self.mus[n - 1])
            self.errs[n] = self.mus[n] - self.preds[n]

        avg_errs = []
        avg_err = self.get_errors()[0] / self.total_params
        avg_errs.append(avg_err)

        itr = 0
        for itr in range(num_iters):
            for l in range(1, self.num_layers):
                delta = self.layers[l].backward(self.errs[l + 1]) - self.errs[l]
                self.mus[l] = self.mus[l] + self.mu_dt * (2 * delta)

            for n in range(1, self.num_nodes):
                if not fixed_preds:
                    self.preds[n] = self.layers[n - 1].forward(self.mus[n - 1])
                self.errs[n] = self.mus[n] - self.preds[n]

            avg_err = self.get_errors()[0] / self.total_params
            avg_errs.append(avg_err)
            if thresh is not None and avg_err < thresh:
                break

        return itr, avg_errs

    def test_updates(self, num_iters, fixed_preds=False, thresh=None):
        for n in range(1, self.num_nodes):
            self.preds[n] = self.layers[n - 1].forward(self.mus[n - 1])
            self.errs[n] = self.mus[n] - self.preds[n]

        avg_errs = []
        avg_err = self.get_errors()[0] / self.total_params
        avg_errs.append(avg_err)

        itr = 0
        for itr in range(num_iters):
            delta = self.layers[0].backward(self.errs[1])
            self.mus[0] = self.mus[0] + self.mu_dt * (2 * delta)
            for l in range(1, self.num_layers):
                delta = self.layers[l].backward(self.errs[l + 1]) - self.errs[l]
                self.mus[l] = self.mus[l] + self.mu_dt * (2 * delta)

            for n in range(1, self.num_nodes):
                if not fixed_preds:
                    self.preds[n] = self.layers[n - 1].forward(self.mus[n - 1])
                self.errs[n] = self.mus[n] - self.preds[n]

            avg_err = self.get_errors()[0] / self.total_params
            avg_errs.append(avg_err)
            if thresh is not None and avg_err < thresh:
                break

        return itr, avg_errs

    def update_grads(self):
        for l in range(self.num_layers):
            self.layers[l].update_gradient(self.errs[l + 1])

    def update_amort_grads(self):
        for q, l in zip(reversed(range(1, self.num_nodes)), range(self.num_layers)):
            self.q_errs[q] = self.mus[l] - self.q_preds[q]

        for l in range(self.num_layers):
            self.amort_layers[l].update_gradient(self.q_errs[l + 1])

    def get_errors(self):
        total_err = 0
        for err in self.errs:
            if len(err) > 0:
                total_err = total_err + torch.sum(torch.abs(err)).item()

        q_total_err = 0
        for err in self.q_errs:
            if len(err) > 0:
                q_total_err = q_total_err + torch.sum(torch.abs(err)).item()

        return total_err, q_total_err

    def get_losses(self):
        try:
            return (
                torch.sum(torch.abs(self.errs[-1])).item(),
                torch.sum(torch.abs(self.q_errs[-1])).item(),
            )
        except:
            return torch.sum(torch.abs(self.errs[-1])).item(), 0

    def get_weight_stats(self):
        mean_abs_weights, mean_abs_biases = [], []
        for l in range(self.num_layers):
            mean_abs_weights.append(torch.mean(torch.abs(self.layers[l].weights)).item())
            mean_abs_biases.append(torch.mean(torch.abs(self.layers[l].bias)).item())
        return mean_abs_weights, mean_abs_biases

    def normalize_weights(self):
        for l in range(self.num_layers):
            mean_weights = torch.mean(torch.abs(self.layers[l].weights))
            self.layers[l].weights = self.layers[l].weights * self.mean_weights[l] / mean_weights
            mean_bias = torch.mean(torch.abs(self.layers[l].bias))
            self.layers[l].bias = self.layers[l].bias * self.mean_biases[l] / mean_bias

    @property
    def params(self):
        return self.layers + self.amort_layers

    def __str__(self):
        return f"<HybridModel> {self.nodes}"


import cv2
import numpy as np
from matplotlib import pyplot as plt

print("OpenCV version:", cv2.__version__)

# Morphological transformations are some simple operations based on the image shape
img = cv2.imread('/home/ahu/Workspace/py-video-processing-rsc/opencv-master/samples/data/smarties.png', cv2.IMREAD_GRAYSCALE)
ret, mask = cv2.threshold(img, 220, 255, cv2.THRESH_BINARY_INV)

kernal = np.ones((5, 5), np.uint8)

# Decrease the size of the little black balss
# args : img, kernal (rectangle), iterations nb
dilation = cv2.dilate(mask, kernal, iterations=2)

# Increase the size of the little black balls
erosion = cv2.erode(mask, kernal, iterations=1)

# Opening = Erosion + Dilation
# ars : img, type of morphological operations, kernal
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernal)

# Closing = Dilation + Erosion
closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernal)

# Gradient
mg = cv2.morphologyEx(mask, cv2.MORPH_GRADIENT, kernal)

# Top Hat
th = cv2.morphologyEx(mask, cv2.MORPH_TOPHAT, kernal)

titles = ['image', 'mask', 'dilation', 'erosion', 'opening', 'closing', 'mg', 'th']
images = [img, mask, dilation, erosion, opening, closing, mg, th]

for i in range(8):
    plt.subplot(4, 2, i+1)
    plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([])
    plt.yticks([])

plt.show()


# Encuentre el volumen y el área de la superficie de un toro.
import math

def get_data(string):
    while True:
        try:
            num = int(input(f"\033[1;33mInserte el valor {string}: \033[0;m"))
            return num
        except ValueError:
            print("\033[1;31mCarácter(es) no permitido(s). \033[0;m")

def area(external_r, internal_r):
    result = 4*math.pi**2*external_r*internal_r
    print(round(result, 2))

def volume(external_r, internal_r):
    result = 2*math.pi**2*external_r*internal_r**2
    print(round(result, 2))

def main():
    internal_radius = get_data("del radio interior")
    external_radius = get_data("del radio exterior")
    area(external_radius, internal_radius)
    volume(external_radius, internal_radius)

if __name__ == '__main__':
    main()


import genanki
import tkinter
from tkinter import ttk
from tkinter import filedialog
import loaders

class MainFrame(ttk.Frame):
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.init_gui()
        self.words = {}

    def init_gui(self):
        """Builds GUI."""
        self.root.title('AnkiMaker')
        self.grid(column=0, row=0, sticky='nsew')

        lists_width = 10

        # Loaders frame

        loader_list = [loaders.KindleLoader,
                       loaders.FileLoader,
                       loaders.OEDLoader,
                       loaders.WikLoader]

        self.loaders = []
        for l in loader_list:
            # initialize every loader's frame with the mainframe as parent
            self.loaders.append(l(self))

        # Loaders list

        self.list = tkinter.Listbox(self, width = lists_width,
                                    height = 8,
                                    selectmode = tkinter.SINGLE)
        self.list.grid(column=0, row=0, sticky = 'N')
        for op in self.loaders:
            self.list.insert(tkinter.END, op.name)
        self.list.bind('<<ListboxSelect>>', self.select)

        self.list.selection_set(0)

        # Deck creation frame

        self.dframe = DeckFrame(self)
        self.dframe.grid(column=0, row=1, columnspan = 4)
        self.dframe.disable()

        # Add padding to everything
        for child in self.winfo_children():
            child.grid_configure(padx=5, pady=5)

        self.select()

    def add_words(self, words):
        # Adds entries to the table if they are not there already
        self.dframe.add_words(words)
        for w in words:
            if not w in self.words:
                self.words[w] = {}

#        self.activate_infoloaders()
        self.dframe.activate()

    def get_words(self):
        return self.words.keys()

    def add_info(self, col_name, words):
        # Adds entries to the table if they are not there already
        self.dframe.add_info(col_name, words)
        for w in words:
            if w in self.words:
                self.words[w][col_name] = words[w]

    def select(self, event = None):
        current_selection = self.list.curselection() # a tuple of selected
        if len(current_selection): # if there is a selected one
            index = current_selection[0]
            for l in self.loaders:
                l.grid_forget()
            self.loaders[index].grid(column=1, row=0, sticky = 'N')
            self.loaders[index].grid_configure(padx=5, pady=5)

class DeckFrame(ttk.Frame):

    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        # this dictionary will store the index of every field
#        self.columns = {}
        self.columns = {'Question':'#0', 'Answer':'#1'}
        self.init_frame()

    def init_frame(self):
        columns = ['#' + str(c) for c in range(1, 10)]
        self.words_table = ttk.Treeview(self, columns = columns,
                                        displaycolumns = ['#1'])
        self.words_table.grid(column= 0, row= 0, columnspan= 5)

        # this dictionary will store the index of every field

        self.words_table.heading('#0', text = 'Question',
                                 command = lambda: self.sort_table_by('#0'))
        self.words_table.heading('#1', text = 'Answer',
                                 command = lambda: self.sort_table_by('#1'))

        ttk.Label(self, text='Anki deck name:').grid(column=0, row=1)
        self.name_entry = ttk.Entry(self, width=20)
        self.name_entry.grid(column=1, row=1, columnspan = 1)

        ttk.Label(self, text='File').grid(column=2, row=1)
        self.file_entry = ttk.Entry(self, width=25)
        self.file_entry.grid(column=3, row=1, columnspan = 1)

        self.browse_button = ttk.Button(self, text='Browse',
                                      command=self.select_file)
        self.browse_button.grid(column=4, row=1, columnspan = 1)

        self.create_button = ttk.Button(self, text='Create',
                                      command=self.create_deck)
        self.create_button.grid(column=5, row=1, columnspan = 1)

        # Add padding to everything
        for child in self.winfo_children():
            child.grid_configure(padx=5, pady=5)

    def activate(self):
        self.browse_button.state(['!disabled'])
        self.create_button.state(['!disabled'])

    def disable(self):
        self.browse_button.state(['disabled'])
        self.create_button.state(['disabled'])

    def add_column(self, name):
        if not name in self.columns:
            cid = '#' + str(len(self.columns))
            self.columns[name] = cid
            new_columns = self.words_table.cget('displaycolumns') + (cid,)
            self.words_table.configure(displaycolumns = new_columns)

            sort_command = lambda: self.sort_table_by(cid)
            self.words_table.heading(cid, text = name,
                                     command = sort_command)

    def add_words(self, words):
        # Adds entries to the table if they are not there already
        # words: a list of words to be added
        for w in words:
            if not self.words_table.exists(w):
                self.words_table.insert('', 'end', w, text=w)

    def add_info(self, col_name, info):
        # Adds entries to the table if they are not there already.
        # Columns will be created if they don't exist yet
        # col_name: a string with the name of the relevant field
        # words_info: a dictionary of dictionaries with the words
        # as keys and the information as values

        # Maybe join this methoed with add_words, so that if the
        # words passed to this one don't exists new entries are added
        self.add_column(col_name)
        for w in info:
            if self.words_table.exists(w):
                self.words_table.set(w, self.columns[col_name], info[w])

    def select_file(self):
        options = {'defaultextension':'apkg',
                   'parent':self,
                   'title':'Select the Anki deck location'}
        self.filename = filedialog.asksaveasfilename(**options)
        if self.filename != '':
            self.file_entry.delete(0, tkinter.END)
            self.file_entry.insert(0, self.filename)

    def create_deck(self):

        deck = genanki.Deck(2059400110, self.name_entry.get())

        fields = []
        for f in self.columns.keys(): # for each field
            fields.append({'name':f})
        model = genanki.Model(
            1607392319,
            'Word',
            fields=fields,
            templates=[
                {
                    'name': 'Card 1',
                    'qfmt': '{{Question}}',
                    'afmt': '{{FrontSide}}: {{Answer}}
{{Usage}}'
                }]
        )

        for w in self.parent.words:
            fields = []
            for f in self.columns.keys(): # for each field
                if f == 'Question':
                    fields.append(w)
                else:
                    fields.append(self.parent.words[w][f])
            note = genanki.Note(
                model=model,
                fields=fields
                )
            deck.add_note(note)

        genanki.Package(deck).write_to_file(self.file_entry.get())

    def sort_table_by(self, column):
        print('Sorting by' + column)

if __name__ == '__main__':
    root = tkinter.Tk()
    MainFrame(root)
    root.mainloop()


from automator.def_function import test_function, value_function

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

@test_function
def goto_url(
        driver,
        url
):
    driver.get(url=url)

@test_function
def enter_input(
        current_focus,
        input_xpath='//html',
        value=Keys.RETURN
):
    element = current_focus.find_element_by_xpath(input_xpath)
    element.clear()
    element.send_keys(value)

@test_function
def click(
        current_focus,
        target_xpath='//html'
):
    node = current_focus.find_element_by_xpath(target_xpath)
    node.send_keys(Keys.RETURN)

@test_function
def click_at_index(
        current_focus,
        target_index=0
):
    elements = current_focus.find_elements_by_xpath('*')
    elements[target_index].click()

@test_function
def wait_for(
        driver,
        target_xpath='//html',
        timeout=120
):
    WebDriverWait(driver, timeout).until(
        ec.presence_of_element_located((By.XPATH, target_xpath))
    )

@test_function
def drag_and_drop(
        driver,
        source_element,
        target_element
):
    ActionChains(driver).drag_and_drop(
        source=source_element,
        target=target_element
    ).perform()

@test_function
def scroll_to(
        driver,
        target_element
):
    ActionChains(driver).move_to_element(target_element).perform()

@test_function
def drag_and_drop_by_xpath(
        current_focus,
        source_xpath='//html',
        target_xpath='//html'
):
    source_element = current_focus.find_element_by_xpath(source_xpath)
    target_element = current_focus.find_element_by_xpath(target_xpath)

    drag_and_drop(
        source_element=source_element,
        target_element=target_element
    )

@test_function
def drag_and_drop_by_index(
        current_focus,
        source_index=1,
        target_index=2
):
    elements = current_focus.find_elements_by_xpath('*')

    drag_and_drop(
        source_element=elements[source_index],
        target_element=elements[target_index]
    )

@test_function
def focus(
        current_focus,
        target_xpath='//html'
):
    element = current_focus.find_element_by_xpath(target_xpath)

    return element

@test_function
def focus_by_index(
        current_focus,
        target_index=0
):
    elements = current_focus.find_elements_by_xpath('*')

    if target_index >= len(elements):
        return False

    return elements[target_index]

@value_function
def get_text_of_node(
        current_focus,
        target_xpath='//html'
):
    element = current_focus.find_element_by_xpath(target_xpath)
    return get_text(current_focus=element)

@value_function
def get_texts_of_nodes(
        current_focus,
        target_xpath='//html'
):
    elements = current_focus.find_elements_by_xpath(target_xpath)
    return [get_text(current_focus=element) for element in elements]

@value_function
def get_text(
        current_focus
):
    return current_focus.text


from math import ceil
import sys
import os
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import matplotlib

matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42

dt = []
num_bench = len(sys.argv) - 2
rows = 3
cols = ceil(num_bench / rows)
color = ['#4D678D', '#4D678D', '#4D678D', '#4D678D', '#EA7878']

sns.set(style="darkgrid")
# sns.set(font_scale=1.2)

fig, ax = plt.subplots(rows, cols, sharex='row')
fig.set_figheight(7)
fig.set_figwidth(17)
fig.supylabel('Runtime [s]')

for i in range(num_bench):
    dt.append(pd.read_csv(sys.argv[i + 2]))

for i in range(rows):
    for j in range(cols):
        if (i * cols + j >= num_bench):
            ax[i, j].axis('off')
            continue

        sns.barplot(data=dt[i * cols + j],
                    palette=color,
                    estimator=np.median,
                    ax=ax[i, j])
        bench_name = os.path.splitext(
            os.path.basename(sys.argv[i * cols + j + 2]))[0]
        ax[i, j].set_title(bench_name)
        ax[i, j].set_xticklabels(["GCC", "Clang", "DaCe", "MLIR", "DCIR"],
                                 rotation=90,
                                 ha="center")

        if (i < rows - 1):
            ax[i, j].set(xticklabels=[])

plt.tight_layout()
plt.savefig(sys.argv[1], dpi=300, bbox_inches='tight')


import tensorflow as tf

from finetune.util.shapes import lengths_from_eos_idx
from finetune.base_models.gpt.featurizer import dropout, embed

def textcnn_featurizer(X, encoder, config, train=False, reuse=None, **kwargs):
    """
    The transformer element of the finetuning model. Maps from tokens ids to a dense, embedding of the sequence.

    :param X: A tensor of token indexes with shape [batch_size, sequence_length, token_idx]
    :param encoder: A TextEncoder object.
    :param config: A config object, containing all parameters for the featurizer.
    :param train: If this flag is true, dropout and losses are added to the graph.
    :param reuse: Should reuse be set within this scope.
    :return: A dict containing;
        embed_weights: the word embedding matrix.
        features: The output of the featurizer_final state.
        sequence_features: The output of the featurizer at each timestep.
    """
    initial_shape = tf.shape(input=X)
    X = tf.reshape(X, shape=tf.concat(([-1], initial_shape[-1:]), 0))
    sequence_length = tf.shape(input=X)[1]
    with tf.compat.v1.variable_scope("model/featurizer", reuse=reuse):
        # Name of embed weights variable depends on tokenizer/base model weights file
        if "roberta" in config.base_model_path:
            embed_weights_name = "bert/embeddings/word_embeddings"
            clf_token = encoder.delimiter_token
        else:
            embed_weights_name = "we"
            clf_token = encoder["_classify_"]

        embed_weights = tf.compat.v1.get_variable(
            name=embed_weights_name,
            shape=[encoder.vocab_size, config.n_embed_featurizer],
            initializer=tf.compat.v1.random_normal_initializer(
                stddev=config.weight_stddev
            ),
        )

        if config.train_embeddings:
            embed_weights = dropout(embed_weights, config.embed_p_drop, train)
        else:
            embed_weights = tf.stop_gradient(embed_weights)

        h = tf.gather(embed_weights, X)

        # Keep track of the classify token. Token depends on tokenizer / base model weights file
        # if "roberta" in config.base_model_path:
        #     clf_token = encoder.delimiter_token
        # else:
        #     clf_token = encoder["_classify_"]

        # mask out the values past the classify token before performing pooling
        pool_idx = tf.cast(
            tf.argmax(input=tf.cast(tf.equal(X, clf_token), tf.float32), axis=1),
            tf.int32,
        )
        # mask is past the classify token (i.e. make those results extremely negative)
        mask = tf.expand_dims(
            1.0
            - tf.sequence_mask(pool_idx, maxlen=tf.shape(input=h)[1], dtype=tf.float32),
            -1,
        )

        # Convolutional Layer (this is all the same layer, just different filter sizes)
        pool_layers = []
        conv_layers = []
        for i, kernel_size in enumerate(config.kernel_sizes):
            conv = tf.compat.v1.layers.conv1d(
                inputs=h,
                filters=config.num_filters_per_size,
                kernel_size=kernel_size,
                padding="same",
                activation=tf.nn.relu,
                name="conv" + str(i),
                kernel_initializer=tf.compat.v1.initializers.glorot_normal,
            )
            conv_layers.append(conv)
            pool = tf.reduce_max(input_tensor=conv + mask * -1e9, axis=1)
            pool_layers.append(pool)

        # Concat the output of the convolutional layers for use in sequence embedding
        conv_seq = tf.concat(conv_layers, axis=2)
        seq_feats = tf.reshape(conv_seq, shape=[-1, sequence_length, config.n_embed])

        # Concatenate the univariate vectors as features for classification
        clf_h = tf.concat(pool_layers, axis=1)
        clf_h = tf.reshape(
            clf_h, shape=tf.concat((initial_shape[:-1], [config.n_embed]), 0)
        )

        # note that, due to convolution and pooling, the dimensionality of the features is much smaller than in the
        # transformer base models
        lengths = lengths_from_eos_idx(eos_idx=pool_idx, max_length=sequence_length)

        return {
            "embed_weights": embed_weights,
            "features": clf_h,  # [batch_size, n_embed] for classify, [batch_size, 1, n_embed] for comparison, etc.
            "sequence_features": seq_feats,  # [batch_size, seq_len, n_embed]
            "eos_idx": pool_idx,  # [batch_size]
            "lengths": lengths,
        }


# -*- coding: utf-8 -*-
"""Setup module."""
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

def get_requires():
    """Read requirements.txt."""
    requirements = open("requirements.txt", "r").read()
    return list(filter(lambda x: x != "", requirements.split()))

def read_description():
    """Read README.md and CHANGELOG.md."""
    try:
        with open("README.md") as r:
            description = "\n"
            description += r.read()
        with open("CHANGELOG.md") as c:
            description += "\n"
            description += c.read()
        return description
    except Exception:
        return '''Breathing gymnastics application'''

setup(
    name='nafas',
    packages=['nafas'],
    version='0.6',
    description='Breathing gymnastics application',
    long_description=read_description(),
    long_description_content_type='text/markdown',
    include_package_data=True,
    author='Sepand Haghighi',
    author_email='sepand@pyrgg.ir',
    url='https://github.com/sepandhaghighi/nafas',
    download_url='https://github.com/sepandhaghighi/nafas/tarball/v0.6',
    keywords="python3 python breath breathing meditation",
    project_urls={
        'Source': 'https://github.com/sepandhaghighi/nafas',
        'Discord': 'https://discord.gg/CtZUNKJHP4',
    },
    install_requires=get_requires(),
    python_requires='>=3.5',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: 3.10',
        'Intended Audience :: Developers',
        'Intended Audience :: Education',
        'Intended Audience :: End Users/Desktop',
        'Intended Audience :: Other Audience',
        'Topic :: Games/Entertainment',
        'Topic :: Utilities',
    ],
    license='MIT',
)


from __future__ import absolute_import
from builtins import zip
from builtins import range
import unittest
import os

import numpy as np

from SloppyCell.ReactionNetworks import *

from AlgTestNets import algebraic_net_constraints
base_net = algebraic_net_constraints.copy()
tlist_algebraic_net = np.array([0] + [0.8*x for x in range(1, 51)])

class test_Constraints(unittest.TestCase):
    def test_contraint_fire(self):
        """
        Test that a constraint violation causes an exception.
        """

        net = base_net.copy('test')

        self.assertRaises((Utility.ConstraintViolatedException),
                          Dynamics.integrate, net, tlist_algebraic_net,
                          fill_traj=True, redirect_msgs=True)

    def test_constraint_time(self):
        """
        Test that the constraint violation happens at the right time.
        """
        net = base_net.copy('test')
        try:
            traj = Dynamics.integrate(net, tlist_algebraic_net)
        except Utility.ConstraintViolatedException as cve:
            self.assertAlmostEqual(cve.time, 16.436798814)
            self.assertEqual(cve.message, 'X1 is big!')

    def test_add_constraint(self):
        """
        Test that multiple constraints work.
        """
        net = base_net.copy('test')

        net.addConstraint('TimeTooLarge','lt(time,1.0)','Time got too large')

        self.assertRaises((Utility.ConstraintViolatedException),
                          Dynamics.integrate, net, tlist_algebraic_net,
                          fill_traj=True, redirect_msgs=True)

        try:
            traj = Dynamics.integrate(net, tlist_algebraic_net)
        except Utility.ConstraintViolatedException as cve:
            self.assertAlmostEqual(cve.time, 1.0)

    def test_constraints_off(self):
        """
        Test that events fire properly if the constraints are turned off.
        """
        net = base_net.copy('test')

        net.addConstraint('TimeTooLarge','lt(time,1.0)','Time got too large')

        traj = Dynamics.integrate(net, tlist_algebraic_net, use_constraints=False)

        event_indeces = [net.events.index_by_key('event1'),net.events.index_by_key('event2')]
        (te,ye,ie) = traj.event_info
        for e_ind in event_indeces:
            self.assertEqual(True, e_ind in ie)
        for t1, t2 in zip(te, [13.30131485,
                              18.0]):
            self.assertAlmostEqual(t1, t2)

    def test_constraint_chaining(self):
        """
        Test that an event firing can cause a constraint to fire (by assigning
        model variables such that the model is in an invalid state).
        """
        net = base_net.copy('test')

        eventAssignments = {'X1':10}

        net.addEvent('increase_X1', 'geq(time,2.0)', eventAssignments)

        self.assertRaises((Utility.ConstraintViolatedException),
                          Dynamics.integrate, net, tlist_algebraic_net,
                          fill_traj=True, redirect_msgs=True)

        try:
            traj = Dynamics.integrate(net, tlist_algebraic_net)
        except Utility.ConstraintViolatedException as cve:
            self.assertAlmostEqual(cve.time, 2.0)

    def test_constraints_time_zero(self):
        """
        If checking for constraint violations at time zero.
        """
        net = base_net.copy('test')

        # set X1 to be too big for the constraint
        net.set_var_ic('X1', 0.6)

        self.assertRaises((Utility.ConstraintViolatedException),
                          Dynamics.integrate, net, tlist_algebraic_net,
                          fill_traj=True, redirect_msgs=True)

        try:
            traj = Dynamics.integrate(net, tlist_algebraic_net)
        except Utility.ConstraintViolatedException as cve:
            self.assertAlmostEqual(cve.time, 0.0)

suite = unittest.makeSuite(test_Constraints)
if __name__ == '__main__':
    unittest.main()


import re

o1test = 'data/artificial/ds_O1_test_5011.txt'
o2test = 'data/artificial/ds_O2_test_4977.txt'
o3test = 'data/artificial/ds_O3_test_5159.txt'
o1train = 'data/artificial/ds_O1_train_39977.txt'
o2train = 'data/artificial/ds_O2_train_39945.txt'
o3train = 'data/artificial/ds_O3_train_39811.txt'
o1valid = 'data/artificial/ds_O1_valid_5012.txt'
o2valid = 'data/artificial/ds_O2_valid_5078.txt'
o3valid = 'data/artificial/ds_O3_valid_5030.txt'

class DataEngine(object):
    def LoadData(self, path):
        """out: SeqSeqTokenObj, SeqSeqTokenSrc, SeqStringAli"""
        #read all file contents
        file = open(path)
        contents = file.read()
        file.close()
        #split contents into obj, src, ali
        TokensObj = []
        TokensSrc = []
        for Function in contents.split('<<<sep_out_sample>>>\n'):
            StringObj, StringSrc, _ = Function.split('<<<sep_in_sample>>>\n')
            SeqLineObj = self._tokenize(StringObj, '\n|%[a-z0-9]+|\$|,|\(|\)|\-|:|<|>|\+|[a-zA-Z0-9_]+') # [self._tokenize(LineObj, '%[a-z0-9]+|\$|,|\(|\)|\-|:|<|>|\+|[a-zA-Z0-9_]+') for LineObj in StringObj.split('\n') if LineObj]
            SeqLineSrc = self._tokenize(StringSrc, '\n|if|else|switch|case|default|break|int|float|char|double|long|for|while|do|void|goto|auto|signed|const|extern|register|unsigned|return|continue|enum|sizeof|struct|typedef|union|volatile|\+|\-|/|\*|&|\||\^|~|\?|\(|\)|\[|\]|\{|\}|<|>|=|!|,|\'|"|;|#|\\\|[a-zA-Z0-9_]+') # [self._tokenize(LineSrc, 'if|else|switch|case|default|break|int|float|char|double|long|for|while|do|void|goto|auto|signed|const|extern|register|unsigned|return|continue|enum|sizeof|struct|typedef|union|volatile|\+|\-|/|\*|&|\||\^|~|\?|\(|\)|\[|\]|\{|\}|<|>|=|!|,|\'|"|;|#|\\\|[a-zA-Z0-9_]+') for LineSrc in StringSrc.split('\n') if LineSrc]
            TokensObj.append(SeqLineObj)
            TokensSrc.append(SeqLineSrc)
        return TokensObj, TokensSrc

    def _tokenize(self, str, Pattern):
        """Called by LoadData"""
        SeqToken = re.findall(Pattern, str)
        #split everything thats not a variable name (re [a-zA-Z0-9_]+)
        for Token in SeqToken:
            if Token[0].isdigit():
                TokenIndex = SeqToken.index(Token)
                SeqToken = SeqToken[0:TokenIndex] + list(Token) + SeqToken[TokenIndex + 1:]
            elif Token == '\n':
                TokenIndex = SeqToken.index(Token)
                SeqToken = SeqToken[0:TokenIndex] + ['<nl>'] + SeqToken[TokenIndex + 1:]
        return SeqToken


import torch
import torch.nn as nn

def dwt_init(x):
    x01 = x[:, :, 0::2, :] / 2
    x02 = x[:, :, 1::2, :] / 2
    x1 = x01[:, :, :, 0::2]
    x2 = x02[:, :, :, 0::2]
    x3 = x01[:, :, :, 1::2]
    x4 = x02[:, :, :, 1::2]
    x_LL = x1 + x2 + x3 + x4
    x_HL = -x1 - x2 + x3 + x4
    x_LH = -x1 + x2 - x3 + x4
    x_HH = x1 - x2 - x3 + x4
    return x_LL, torch.cat((x_LL, x_HL, x_LH, x_HH), 1)
class DWT(nn.Module):
    def __init__(self):
        super(DWT, self).__init__()
        self.requires_grad = False

    def forward(self, x):
        return dwt_init(x)

def iwt_init(x):
    r = 2
    in_batch, in_channel, in_height, in_width = x.size()
    out_batch, out_channel, out_height, out_width = in_batch, int(
        in_channel / (r ** 2)), r * in_height, r * in_width
    x1 = x[:, 0:out_channel, :, :] / 2
    x2 = x[:, out_channel:out_channel * 2, :, :] / 2
    x3 = x[:, out_channel * 2:out_channel * 3, :, :] / 2
    x4 = x[:, out_channel * 3:out_channel * 4, :, :] / 2
    h = torch.zeros([out_batch, out_channel, out_height, out_width]).float().to(x.device)

    h[:, :, 0::2, 0::2] = x1 - x2 - x3 + x4
    h[:, :, 1::2, 0::2] = x1 - x2 + x3 - x4
    h[:, :, 0::2, 1::2] = x1 + x2 - x3 - x4
    h[:, :, 1::2, 1::2] = x1 + x2 + x3 + x4
    return h

class IWT(nn.Module):
    def __init__(self):
        super(IWT, self).__init__()
        self.requires_grad = False

    def forward(self, x):
        return iwt_init(x)

class GCWTResDown(nn.Module):
    def __init__(self, in_channels, att_block, norm_layer=nn.BatchNorm2d):
        super().__init__()
        self.dwt = DWT()
        if norm_layer:
            self.stem = nn.Sequential(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=1),
                                      norm_layer(in_channels),
                                      nn.PReLU(),
                                      nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1),
                                      norm_layer(in_channels),
                                      nn.PReLU())
        else:
            self.stem = nn.Sequential(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=1),
                                      nn.PReLU(),
                                      nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1),
                                      nn.PReLU())
        self.conv1x1 = nn.Conv2d(in_channels, in_channels, kernel_size=1, padding=0)
        self.conv_down = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=2)
        #self.att = att_block(in_channels * 2, in_channels * 2)

    def forward(self, x):
        stem = self.stem(x)
        xLL, dwt = self.dwt(x)
        res = self.conv1x1(xLL)
        out = torch.cat([stem, res], dim=1)
        #out = self.att(out)
        return out, dwt

class GCIWTResUp(nn.Module):
    def __init__(self, in_channels, att_block, norm_layer=None):
        super().__init__()
        if norm_layer:
            self.stem = nn.Sequential(
                nn.PixelShuffle(2),
                nn.Conv2d(in_channels // 4, in_channels // 4, kernel_size=3, padding=1),
                norm_layer(in_channels // 4),
                nn.PReLU(),
                nn.Conv2d(in_channels // 4, in_channels // 4, kernel_size=3, padding=1),
                norm_layer(in_channels // 4),
                nn.PReLU(),
            )
        else:
            self.stem = nn.Sequential(
                nn.PixelShuffle(2),
                nn.Conv2d(in_channels // 4, in_channels // 4, kernel_size=3, padding=1),
                nn.PReLU(),
                nn.Conv2d(in_channels // 4, in_channels // 4, kernel_size=3, padding=1),
                nn.PReLU(),
            )
        self.pre_conv_stem = nn.Conv2d(in_channels // 2, in_channels, kernel_size=1, padding=0)
        self.pre_conv = nn.Conv2d(in_channels, in_channels, kernel_size=1, padding=0)
        # self.prelu = nn.PReLU()
        self.post_conv = nn.Conv2d(in_channels // 4, in_channels // 4, kernel_size=1, padding=0)
        self.iwt = IWT()
        self.last_conv = nn.Conv2d(in_channels // 2, in_channels // 4, kernel_size=1, padding=0)
        # self.se = SE_net(in_channels // 2, in_channels // 4)
    def forward(self, x, x_dwt):
        x = self.pre_conv_stem(x)
        stem = self.stem(x)
        x_dwt = self.pre_conv(x_dwt)
        x_iwt = self.iwt(x_dwt)
        x_iwt = self.post_conv(x_iwt)
        out = torch.cat((stem, x_iwt), dim=1)
        out = self.last_conv(out)
        return out


import sys
import unittest
import json
from unittest.mock import patch

sys.path.insert(1, "src/")

from pyclarify.jsonrpc.oauth2 import Authenticator

class TestAuthenticator(unittest.TestCase):
    def setUp(self):
        self.credentials_path = "./tests/mock_data/mock-clarify-credentials.json"

        with open(self.credentials_path) as f:
            self.credentials_dict = json.load(f)

        with open("./tests/mock_data/authentication.json") as f:
            self.mock_authentication = json.load(f)

        self.mock_token = self.mock_authentication["mock_token"]
        self.mock_token2 = self.mock_token
        self.mock_token2["access_token"] = "<YOUR_ACCESS_TOKEN2>"

        self.oauth_request_body = self.mock_authentication["oauth_request_body"]
        self.gettoken = Authenticator(self.credentials_path)

    def test_read_credentials_path(self):
        """
        Test that it can read the credentials from folder path
        """

        token_client = Authenticator(self.credentials_path)
        self.assertEqual(token_client.credentials, self.oauth_request_body)

    def test_read_credentials_string(self):
        """
        Test that it can read the credentials from string
        """
        credentials_string = json.dumps(self.credentials_dict)
        token_client = Authenticator(credentials_string)
        self.assertEqual(token_client.credentials, self.oauth_request_body)

    def test_read_credentials_dict(self):
        """
        Test that it can read the credentials from a dictionary
        """
        token_client = Authenticator(self.credentials_dict)
        self.assertEqual(token_client.credentials, self.oauth_request_body)

    def test_no_input(self):
        """
        Test that it gets a TypeError when not providing an input
        """
        self.assertRaises(TypeError, Authenticator)

    @patch("pyclarify.jsonrpc.oauth2.requests.post")
    def test_get_token(self, mock_request):
        """
        Test that it can get and update the token
        """
        mock_request.return_value.json = lambda: self.mock_token
        response = self.gettoken.get_token()
        self.assertEqual(response, self.mock_token["access_token"])

        mock_request.return_value.json = lambda: self.mock_token2
        response = self.gettoken.get_token()
        self.assertEqual(response, self.mock_token["access_token"])

        self.gettoken._expire_token = None
        response = self.gettoken.get_token()
        self.assertEqual(response, self.mock_token2["access_token"])

if __name__ == "__main__":
    unittest.main()


import frappe
from frappe.model.document import Document
from frappe.query_builder import Case
from frappe.query_builder.functions import Coalesce, Sum
from frappe.utils import flt, nowdate

class Bin(Document):
	def before_save(self):
		if self.get("__islocal") or not self.stock_uom:
			self.stock_uom = frappe.get_cached_value('Item', self.item_code, 'stock_uom')
		self.set_projected_qty()

	def set_projected_qty(self):
		self.projected_qty = (flt(self.actual_qty) + flt(self.ordered_qty)
			+ flt(self.indented_qty) + flt(self.planned_qty) - flt(self.reserved_qty)
			- flt(self.reserved_qty_for_production) - flt(self.reserved_qty_for_sub_contract))

	def get_first_sle(self):
		sle = frappe.qb.DocType("Stock Ledger Entry")
		first_sle = (
				frappe.qb.from_(sle)
					.select("*")
					.where((sle.item_code == self.item_code) & (sle.warehouse == self.warehouse))
					.orderby(sle.posting_date, sle.posting_time, sle.creation)
					.limit(1)
				).run(as_dict=True)

		return first_sle and first_sle[0] or None

	def update_reserved_qty_for_production(self):
		'''Update qty reserved for production from Production Item tables
			in open work orders'''

		wo = frappe.qb.DocType("Work Order")
		wo_item = frappe.qb.DocType("Work Order Item")

		self.reserved_qty_for_production = (
				frappe.qb
					.from_(wo)
					.from_(wo_item)
					.select(Case()
							.when(wo.skip_transfer == 0, Sum(wo_item.required_qty - wo_item.transferred_qty))
							.else_(Sum(wo_item.required_qty - wo_item.consumed_qty))
						)
					.where(
						(wo_item.item_code == self.item_code)
						& (wo_item.parent == wo.name)
						& (wo.docstatus == 1)
						& (wo_item.source_warehouse == self.warehouse)
						& (wo.status.notin(["Stopped", "Completed"]))
						& ((wo_item.required_qty > wo_item.transferred_qty)
							| (wo_item.required_qty > wo_item.consumed_qty))
					)
		).run()[0][0] or 0.0

		self.set_projected_qty()

		self.db_set('reserved_qty_for_production', flt(self.reserved_qty_for_production))
		self.db_set('projected_qty', self.projected_qty)

	def update_reserved_qty_for_sub_contracting(self):
		#reserved qty

		po = frappe.qb.DocType("Purchase Order")
		supplied_item = frappe.qb.DocType("Purchase Order Item Supplied")

		reserved_qty_for_sub_contract = (
				frappe.qb
					.from_(po)
					.from_(supplied_item)
					.select(Sum(Coalesce(supplied_item.required_qty, 0)))
					.where(
						(supplied_item.rm_item_code == self.item_code)
						& (po.name == supplied_item.parent)
						& (po.docstatus == 1)
						& (po.is_subcontracted == "Yes")
						& (po.status != "Closed")
						& (po.per_received < 100)
						& (supplied_item.reserve_warehouse == self.warehouse)
					)
				).run()[0][0] or 0.0

		se = frappe.qb.DocType("Stock Entry")
		se_item = frappe.qb.DocType("Stock Entry Detail")

		materials_transferred = (
				frappe.qb
					.from_(se)
					.from_(se_item)
					.from_(po)
					.select(Sum(
						Case()
							.when(se.is_return == 1, se_item.transfer_qty * -1)
							.else_(se_item.transfer_qty)
						))
					.where(
						(se.docstatus == 1)
						& (se.purpose == "Send to Subcontractor")
						& (Coalesce(se.purchase_order, "") != "")
						& ((se_item.item_code == self.item_code)
							| (se_item.original_item == self.item_code))
						& (se.name == se_item.parent)
						& (po.name == se.purchase_order)
						& (po.docstatus == 1)
						& (po.is_subcontracted == "Yes")
						& (po.status != "Closed")
						& (po.per_received < 100)
					)
				).run()[0][0] or 0.0

		if reserved_qty_for_sub_contract > materials_transferred:
			reserved_qty_for_sub_contract = reserved_qty_for_sub_contract - materials_transferred
		else:
			reserved_qty_for_sub_contract = 0

		self.db_set('reserved_qty_for_sub_contract', reserved_qty_for_sub_contract)
		self.set_projected_qty()
		self.db_set('projected_qty', self.projected_qty)

def on_doctype_update():
	frappe.db.add_index("Bin", ["item_code", "warehouse"])

def update_stock(bin_name, args, allow_negative_stock=False, via_landed_cost_voucher=False):
	'''Called from erpnext.stock.utils.update_bin'''
	update_qty(bin_name, args)

	if args.get("actual_qty") or args.get("voucher_type") == "Stock Reconciliation":
		from erpnext.stock.stock_ledger import update_entries_after, update_qty_in_future_sle

		if not args.get("posting_date"):
			args["posting_date"] = nowdate()

		if args.get("is_cancelled") and via_landed_cost_voucher:
			return

		# Reposts only current voucher SL Entries
		# Updates valuation rate, stock value, stock queue for current transaction
		update_entries_after({
			"item_code": args.get('item_code'),
			"warehouse": args.get('warehouse'),
			"posting_date": args.get("posting_date"),
			"posting_time": args.get("posting_time"),
			"voucher_type": args.get("voucher_type"),
			"voucher_no": args.get("voucher_no"),
			"sle_id": args.get('name'),
			"creation": args.get('creation')
		}, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)

		# update qty in future sle and Validate negative qty
		update_qty_in_future_sle(args, allow_negative_stock)

def get_bin_details(bin_name):
	return frappe.db.get_value('Bin', bin_name, ['actual_qty', 'ordered_qty',
	'reserved_qty', 'indented_qty', 'planned_qty', 'reserved_qty_for_production',
	'reserved_qty_for_sub_contract'], as_dict=1)

def update_qty(bin_name, args):
	bin_details = get_bin_details(bin_name)

	# update the stock values (for current quantities)
	if args.get("voucher_type")=="Stock Reconciliation":
		actual_qty = args.get('qty_after_transaction')
	else:
		actual_qty = bin_details.actual_qty + flt(args.get("actual_qty"))

	ordered_qty = flt(bin_details.ordered_qty) + flt(args.get("ordered_qty"))
	reserved_qty = flt(bin_details.reserved_qty) + flt(args.get("reserved_qty"))
	indented_qty = flt(bin_details.indented_qty) + flt(args.get("indented_qty"))
	planned_qty = flt(bin_details.planned_qty) + flt(args.get("planned_qty"))

	# compute projected qty
	projected_qty = (flt(actual_qty) + flt(ordered_qty)
		+ flt(indented_qty) + flt(planned_qty) - flt(reserved_qty)
		- flt(bin_details.reserved_qty_for_production) - flt(bin_details.reserved_qty_for_sub_contract))

	frappe.db.set_value('Bin', bin_name, {
		'actual_qty': actual_qty,
		'ordered_qty': ordered_qty,
		'reserved_qty': reserved_qty,
		'indented_qty': indented_qty,
		'planned_qty': planned_qty,
		'projected_qty': projected_qty
	})


from eagle import models

class AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    def _prepare_tax_line_vals(self, line, tax):
        vals = super(AccountInvoice, self)._prepare_tax_line_vals(line, tax)
        if line.payment_percentage:
            percentage = line.payment_percentage / 100
            vals.update({
                'base': vals['base'] * percentage,
                'amount': vals['amount'] * percentage,
            })
        return vals


#Accept N numbers from user and filter out only even numbers from that N numbers.
#After that add 2 in every even number.
#After the addition of 2 perform summation of that modified numbers.

def MarvellousFilter(arr):
    brr=[]
    for i in arr:
        if(i%2==0):
            brr.append(i)
    return brr

def MarvellousMap(arr):
    brr=[]
    for i in arr:
        i=i+2
        brr.append(i)
    return brr

def MarvellousReduce(arr):
    brr=[]
    iSum=0
    for i in arr:
        iSum=iSum+i
    return iSum

def main():
    arr=[]
    size=int(input("Enter the number of elements:"))
    for i in range(size):
        iNo=int(input("Enter the element:"))
        arr.append(iNo)
    print("Enter list is:",arr)

    FilterList=MarvellousFilter(arr)
    print("The list after filter is:",FilterList)

    MapList = MarvellousMap(FilterList)
    print("The list after map is:", MapList)

    iSum = MarvellousReduce(MapList)
    print("The list after reduce(Summation of all elements) is:", iSum)

if __name__=="__main__":
    main()

4 Python_Programs/Programs to demo python concepts/filter_map_reduce1_UserDefine.py