#!/usr/bin/env python

# Import PyGame library
import pygame
import adapter
import MD3Buttons
import RetroflagSnes
import ArduinoMicro
from actions import *

import logger

controllers = { MD3Buttons, RetroflagSnes, ArduinoMicro, }

pad = {}
joysticks = {}

currentGuid = ""
currentAdapter = -1

def pressButton(btn):
  try:
    logger.debug(f"Button {btn} pressed.")
    btnValue = pad[btn]
    adapter.pressButton(btnValue)
  except KeyError:
    logger.debug("Button not managed")

def releaseButton(btn):
  try:
    logger.debug(f"Button {btn} released.")
    btnValue = pad[btn]
    adapter.releaseButton(btnValue)
  except KeyError:
    logger.debug("Button not managed")

def manageAxis(axis, value):
  logger.debug(f"Axis change: axis: {axis} value: {value}")
  axisValue = f"{axis}_{value}"
  try:
    btnValue = pad[axisValue]
    adapter.performAction(btnValue)
  except KeyError:
    logger.debug("Axis not managed.")

def manageHat(hat, value):
  logger.debug(f"Hat change: hat: {hat} value: {value}")
  try:
    first = value[0]
    second = value[1]

    fisrtHatValue = f"{hat}_1_{first}"
    secondHatValue = f"{hat}_2_{second}"

    btnValue = pad[fisrtHatValue]
    adapter.performAction(btnValue)

    btnValue = pad[secondHatValue]
    adapter.performAction(btnValue)
  except KeyError:
    logger.debug("Hat not managed.")

def checkConnections():
  global currentAdapter
  global currentGuid
  foundGuid = False
  if currentAdapter == adapter.NOT_INITIALIZED:
    logger.info(f"Adapter not initialized")
    pad.clear()
  elif currentAdapter == adapter.NOT_CONNECTED:
    logger.info(f"No adapter connected")
    pad.clear()
  elif currentGuid == "":
    logger.info(f"No controller connected")
    pad.clear()
  else:
    for controller in controllers:
      if controller.guid == currentGuid:
        foundGuid = True
        logger.info(f"{controller.name} connected")
        mapController(controller)
    if foundGuid == False:
      logger.info(f"Unknown controller")
      pad.clear()

def mapController(controller): # Add try / catch if adapter not defined for controller
  pad.clear()
  try:
    if currentAdapter == adapter.MEGADRIVE:
      logger.info(f"Map for Sega Megadrive")
      pad.update(controller.sega_md)
    elif currentAdapter == adapter.SUPER_NES:
      logger.info(f"Map for Super Nintendo")
      pad.update(controller.snes)
    elif currentAdapter == adapter.SATURN:
      logger.info(f"Map for Sega Saturn")
      pad.update(controller.saturn)
    else:
      logger.info(f"Unknown adapter")
  except AttributeError:
    logger.warning(f"Controller not usable with this adapter")

def main():
  global currentAdapter
  global currentGuid
  logger.info("!!!!!!!!!!!!!! START !!!!!!!!!!!!!!")

  adapter.init()
  currentAdapter = adapter.currentAdapter

  # Initialize Joystick(s).
  pygame.init()

  while True:
    for event in pygame.event.get():
      if event.type == pygame.JOYHATMOTION:
        manageHat(event.hat, event.value)

      if event.type == pygame.JOYAXISMOTION:
        manageAxis(event.axis, round(event.value))

      if event.type == pygame.JOYBUTTONDOWN:
        pressButton(f"{event.button}")

      if event.type == pygame.JOYBUTTONUP:
        releaseButton(f"{event.button}")

      if event.type == pygame.JOYDEVICEADDED:
          joy = pygame.joystick.Joystick(event.device_index)
          joysticks[joy.get_instance_id()] = joy
          name = joy.get_name()
          logger.debug(f"Joystick {joy.get_instance_id()} connected\nname: {name}, id: {joy.get_id()}, guid: {joy.get_guid()}\naxes: {joy.get_numaxes()}, buttons: {joy.get_numbuttons()}, balls: {joy.get_numballs()}, hats: {joy.get_numhats()}")
          currentGuid = joy.get_guid()
          checkConnections()

      if event.type == pygame.JOYDEVICEREMOVED:
        del joysticks[event.instance_id]
        logger.debug(f"Joystick {event.instance_id} disconnected")
        currentGuid = ""
        checkConnections()

    pluggedAdapter = adapter.currentAdapter
    if pluggedAdapter != currentAdapter:
      logger.debug(f"Adapter status changed: {pluggedAdapter}")
      currentAdapter = pluggedAdapter
      checkConnections()

main()


from setuptools import setup, find_packages
from os.path import join
import sys

version = '2.2.dev0'
readme = open("README.rst").read()
history = open(join('docs', 'HISTORY.txt')).read()

install_requires = ['setuptools', 'gocept.munin', 'Products.ZServerViews>=0.2']
if sys.version_info < (2, 5):
    install_requires.append('threadframe')

setup(name = 'munin.zope',
      version = version,
      description = 'Munin plugins for Zope/Plone.',
      long_description = readme[readme.find('\n\n'):] + '\n' + history,
      classifiers = [
        'Development Status :: 3 - Alpha',
        'Programming Language :: Python',
        'Framework :: Plone',
        'Framework :: ZODB',
        'Framework :: Zope2',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: GNU General Public License (GPL)',
        'Programming Language :: Python',
        'Topic :: System :: Networking :: Monitoring',
        'Topic :: Software Development :: Libraries :: Python Modules',
      ],
      keywords = 'plone zope munin monitoring',
      author = 'Andrew Mleczko',
      author_email = 'andrew.mleczko@redturtle.it',
      url = 'http://plone.org/products/munin.zope',
      license = 'GPL',
      packages = find_packages('src'),
      package_dir = {'': 'src'},
      namespace_packages = ['munin'],
      include_package_data = True,
      platforms = 'Any',
      zip_safe = False,
      install_requires = install_requires,
      extras_require={
              'test': ['plone.app.testing'],
              },
      entry_points = """
          [console_scripts]
          munin = munin.zope.plugins:run
          [z3c.autoinclude.plugin]
          target = plone
      """,
)


import urllib.request
import json
import dml
import prov.model
import datetime
import uuid

class trans_school(dml.Algorithm):
    contributor = 'kobesay'
    reads = ['kobesay.publicschool', 'kobesay.nonpublicschool']
    writes = ['kobesay.regionschool', 'kobesay.regionpublicschool', 'kobesay.regionnonpublicschool']

    @staticmethod
    def execute(trial = False):
        '''Retrieve some data sets (not using the API here for the sake of simplicity).'''
        startTime = datetime.datetime.now()

        # Set up the database connection.
        client = dml.pymongo.MongoClient()
        repo = client.repo
        repo.authenticate('kobesay', 'kobesay')

        repo.dropCollection("regionschool")
        repo.createCollection("regionschool")
        repo.dropCollection("regionpublicschool")
        repo.createCollection("regionpublicschool")
        repo.dropCollection("regionnonpublicschool")
        repo.createCollection("regionnonpublicschool")

        # select zip code and school of public schools
        # count number of public schools for each region
        items_publicschool = {}
        publicschool = repo.kobesay.publicschool.find()
        for x in publicschool:
            zipcode = x['fields']['zipcode'].split('-')[0]
            items_publicschool[zipcode] = items_publicschool.get(zipcode, 0) + 1
        r = [{'zipcode': zipcode, 'num': items_publicschool[zipcode]} for zipcode in items_publicschool]
        repo['kobesay.regionpublicschool'].insert_many(r)

        # select zip code and school of nonpublic schools
        # count number of nonpublic schools for each region
        items_nonpublicschool = {}
        nonpublicschool = repo.kobesay.nonpublicschool.find()
        for x in nonpublicschool:
            zipcode = x['properties']['ZIP'].split('-')[0]
            items_nonpublicschool[zipcode] = items_nonpublicschool.get(zipcode, 0) + 1
        r = [{'zipcode': zipcode, 'num': items_nonpublicschool[zipcode]} for zipcode in items_nonpublicschool]
        repo['kobesay.regionnonpublicschool'].insert_many(r)

        # merge result of public school and private school
        # count number of all public/private schools for each region
        items = {}
        for zipcode in items_publicschool:
            items[zipcode] = items.get(zipcode, 0) + items_publicschool[zipcode]
        for zipcode in items_nonpublicschool:
            items[zipcode] = items.get(zipcode, 0) + items_nonpublicschool[zipcode]
        r = [{'zipcode': zipcode, 'num': items[zipcode]} for zipcode in items]
        repo['kobesay.regionschool'].insert_many(r)

        repo.logout()

        endTime = datetime.datetime.now()

        return {"start":startTime, "end":endTime}

    @staticmethod
    def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None):
        '''
            Create the provenance document describing everything happening
            in this script. Each run of the script will generate a new
            document describing that invocation event.
            '''

        # Set up the database connection.
        client = dml.pymongo.MongoClient()
        repo = client.repo
        repo.authenticate('kobesay', 'kobesay')
        doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in <folder>#<filename> format.
        doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in <user>#<collection> format.
        doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.
        doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.
        doc.add_namespace('bdp', 'https://data.cityofboston.gov/resource/') # City of Boston Data Portal
        doc.add_namespace('bwod', 'https://boston.opendatasoft.com/explore/dataset/') # Boston Wicked Open Data
        doc.add_namespace('bod', 'http://bostonopendata.boston.opendata.arcgis.com/datasets/') # BostonMaps: Open Data

        this_script = doc.agent('alg:kobesay#trans_school', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extension':'py'})
        publicschool = doc.entity('dat:kobesay#publicschool', {'prov:label':'public school', prov.model.PROV_TYPE:'ont:DataSet'})
        nonpublicschool = doc.entity('dat:kobesay#nonpublicschool', {'prov:label':'non public school', prov.model.PROV_TYPE:'ont:DataSet'})
        get_regionschool = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime, {'prov:label':'get region school'})
        get_regionpublicschool = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime, {'prov:label':'get region public school'})
        get_regionnonpublicschool = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime, {'prov:label':'get region non public school'})
        doc.wasAssociatedWith(get_regionschool, this_script)
        doc.wasAssociatedWith(get_regionpublicschool, this_script)
        doc.wasAssociatedWith(get_regionnonpublicschool, this_script)

        regionschool = doc.entity('dat:kobesay#regionschool', {prov.model.PROV_LABEL:'region school', prov.model.PROV_TYPE:'ont:DataSet'})
        doc.wasAttributedTo(regionschool, this_script)
        doc.wasGeneratedBy(regionschool, get_regionschool, endTime)
        doc.wasDerivedFrom(regionschool, publicschool, get_regionschool, get_regionschool, get_regionschool)
        doc.wasDerivedFrom(regionschool, nonpublicschool, get_regionschool, get_regionschool, get_regionschool)

        regionpublicschool = doc.entity('dat:kobesay#regionschool', {prov.model.PROV_LABEL:'region public school', prov.model.PROV_TYPE:'ont:DataSet'})
        doc.wasAttributedTo(regionpublicschool, this_script)
        doc.wasGeneratedBy(regionpublicschool, get_regionpublicschool, endTime)
        doc.wasDerivedFrom(regionpublicschool, publicschool, get_regionpublicschool, get_regionpublicschool, get_regionpublicschool)

        regionnonpublicschool = doc.entity('dat:kobesay#regionnonpublicschool', {prov.model.PROV_LABEL:'region non public school', prov.model.PROV_TYPE:'ont:DataSet'})
        doc.wasAttributedTo(regionnonpublicschool, this_script)
        doc.wasGeneratedBy(regionnonpublicschool, get_regionnonpublicschool, endTime)
        doc.wasDerivedFrom(regionnonpublicschool, nonpublicschool, get_regionnonpublicschool, get_regionnonpublicschool, get_regionnonpublicschool)

        #repo.record(doc.serialize())
        repo.logout()

        return doc
"""
# TEST
trans_school.execute()
doc = trans_school.provenance()
print(doc.get_provn())
print(json.dumps(json.loads(doc.serialize()), indent=4))
"""
## eof


import argparse
import sys

from ft_config import load_config

# check python version >= 3.6
assert sys.version_info >= (3, 6)

# read config.json
config = load_config()

# parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('--action',
                    required=True,
                    help="Action to perform: 'init', 'regex', "
                         "'nn_query', 'spell_checker', 'remove', "
                         "'vocabulary'")
parser.add_argument('--bin',
                    required=False,
                    default=config['BIN_FILE'],
                    help="Fasttext model in binary format")
parser.add_argument('--vec',
                    required=False,
                    default=config['VEC_FILE'],
                    help="Fasttext vectors in plain-text format")
parser.add_argument('--output',
                    required=False,
                    default=config['OUT_FILE'],
                    help="Decrapped vectors in plain-text format")
parser.add_argument('--vocab',
                    required=False,
                    default=config['VOCAB_FILE'],
                    help="Decrapped vocabulary")
args = parser.parse_args()

# actions
ACTION = args.action.lower()
if ACTION == 'init':
    from ft_dbconnect import MysqlDB
    db = MysqlDB(config)

    db.initialize_database()
    sys.exit(0)

elif ACTION == 'regex':
    import ft_regex
    ft_regex.regex_vecfile(config, args.vec)
    sys.exit(0)

elif ACTION == 'nn_query':
    import ft_nn_query
    ft_nn_query.run_nn_random(config, args.bin)
    sys.exit(0)

elif ACTION == 'spell_checker':
    import ft_spell_checker
    ft_spell_checker.run_spell_checker(config)
    sys.exit(0)

elif ACTION == 'remove':
    import ft_remove_garbage
    ft_remove_garbage.remove_garbage_from_vecfile(config,
                                                  args.vec,
                                                  args.output)
    ft_remove_garbage.add_header_to_vecfile(args.output)
    sys.exit(0)

elif ACTION == 'vocabulary':
    import ft_vocab
    ft_vocab.create_vocab_file(config, args.output, args.vocab)
    sys.exit(0)

else:
    print(f'Error: Action {ACTION} not found')
    sys.exit(5)


from django.contrib import admin
from django.urls import path, include
from .views import register_view, login_view, index, profile_view, oikawakuroo

urlpatterns = [
    path('home/', index, name='home'),
    path('register/', register_view, name='register'),
    path('login/', login_view, name='login'),
    path('profile/', profile_view, name='profile'),
    path('oikawakuroo/',oikawakuroo, name = 'oikawakuroo' )
]


from django import forms
from django.forms import ValidationError

from pgweb.core.models import Organisation
from .models import Event

class EventForm(forms.ModelForm):
    form_intro = 'Before submitting an event, please read the current policy for News and Events'

    toggle_fields = [
        {
            'name': 'isonline',
            'invert': True,
            'fields': ['city', 'state', 'country', ]
        },
    ]

    def __init__(self, *args, **kwargs):
        super(EventForm, self).__init__(*args, **kwargs)
        self.fields['startdate'].help_text = 'Use format YYYY-MM-DD'
        self.fields['enddate'].help_text = 'Use format YYYY-MM-DD'

    def filter_by_user(self, user):
        self.fields['org'].queryset = Organisation.objects.filter(managers=user, approved=True)

    def clean(self):
        cleaned_data = super(EventForm, self).clean()
        if not cleaned_data.get('isonline'):
            # Non online events require city and country
            # (we don't require state, since many countries have no such thing)
            if not cleaned_data.get('city'):
                self._errors['city'] = self.error_class(['City must be specified for non-online events'])
                del cleaned_data['city']
            if not cleaned_data.get('country'):
                self._errors['country'] = self.error_class(['Country must be specified for non-online events'])
                del cleaned_data['country']
        return cleaned_data

    def clean_startdate(self):
        if self.instance.pk and self.instance.approved:
            if self.cleaned_data['startdate'] != self.instance.startdate:
                raise ValidationError("You cannot change the dates on events that have been approved")
        return self.cleaned_data['startdate']

    def clean_enddate(self):
        if self.instance.pk and self.instance.approved:
            if self.cleaned_data['enddate'] != self.instance.enddate:
                raise ValidationError("You cannot change the dates on events that have been approved")
        if 'startdate' in self.cleaned_data and self.cleaned_data['enddate'] < self.cleaned_data['startdate']:
            raise ValidationError("End date cannot be before start date!")
        return self.cleaned_data['enddate']

    class Meta:
        model = Event
        exclude = ('submitter', 'approved', 'description_for_badged')


import math
from random import random
import pytest
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from starter.ml import model

@pytest.fixture
def dummy_data():
    data_df = pd.DataFrame({
        "id": list(range(100)),
        "numerical_feat": [random()*100 for i in range(100)],
    })
    data_df["target_feat"] = [
        "yes" if i > 80 else "no" for i in data_df["numerical_feat"].values]
    return data_df

def test_train_model(dummy_data):
    X = dummy_data[['numerical_feat']]
    y = dummy_data['target_feat']
    trained_model = model.train_model(X, y)
    assert isinstance(
        trained_model, RandomForestClassifier), "Wrong model type"

def test_compute_model_metrics():
    y = [1, 0, 0]
    y_preds = [1, 1, 0]
    precision, recall, fbeta = model.compute_model_metrics(y, y_preds)
    assert precision == 0.5, "Precision incorrect"
    assert recall == 1.0, "Recall incorrect"
    assert math.isclose(fbeta, 0.6666, rel_tol=1e-04), "fbeta incorrect"

def test_inference(dummy_data):
    X = dummy_data[['numerical_feat']]
    y = dummy_data['target_feat']
    dummy_model = RandomForestClassifier()
    _dummy_model = dummy_model.fit(X, y)
    preds = model.inference(_dummy_model, X)
    assert isinstance(preds, np.ndarray), "The output type is not np.ndarray"
    assert len(preds) == X.shape[0], "Length of the output is not matched"


from llmstudio.llm import LLM

name = "version"
__version__ = "0.2.27"

__requirements__ = [
    "pydantic",
    "requests",
    "numpy",
    "torch",
    "sentence-transformers",
    "fastapi",
    "uvicorn",
    "PyYaml",
    "openai>=1.0",
    "tiktoken",
    "google-auth",
    "google-cloud-aiplatform",
    "langchain",
    "anthropic>=0.3.0",
    "python-dotenv",
    "cohere",
    "tokenizer",
]


import torch.nn as nn
import torch

resl_to_ch = {
    4    : (512, 512),
    8    : (512, 512),
    16   : (512, 512),
    32   : (512, 512),
    64   : (512, 256),
    128  : (256, 128),
    256  : (128, 64),
    512  : (64, 32),
    1024 : (32, 16),
}

resl_to_batch = {
    4    : 512,
    8    : 512,
    16   : 512,
    32   : 256,
    64   : 128,
    128  : 64,
    256  : 32,
    512  : 16,
    1024 : 12
}

resl_to_lr = {
    4    : 0.001,
    8    : 0.001,
    16   : 0.001,
    32   : 0.001,
    64   : 0.0015,
    128  : 0.0015,
    256  : 0.002,
    512  : 0.003,
    1024 : 0.003
}

class EqualizedLR(nn.Module):
    def __init__(self, layer):
        super().__init__()

        nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")

        layer.bias.data.fill_(0)

        self.wscale = layer.weight.data.detach().pow(2.).mean().sqrt()
        layer.weight.data /= self.wscale

        self.layer = layer

    def forward(self, x):
        return self.layer(x * self.wscale)

class PixelWiseNorm(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        x_square_mean = x.pow(2).mean(dim=1, keepdim=True)
        denom = torch.rsqrt(x_square_mean + 1e-8)
        return x * denom

class ToRGBLayer(nn.Module):
    def __init__(self, resl, rgb_channel):
        super().__init__()
        _, in_c  = resl_to_ch[resl]

        self.conv = nn.Sequential(
            EqualizedLR(nn.Conv2d(in_c, rgb_channel, 1)),
            nn.Tanh()
        )

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

class ReslBlock(nn.Module):
    def __init__(self, resl):
        super().__init__()
        in_c, out_c  = resl_to_ch[resl]

        self.conv = nn.Sequential(
            EqualizedLR(nn.Conv2d(in_c, out_c, 3, 1, 1)),
            PixelWiseNorm(),
            nn.LeakyReLU(negative_slope=0.2, inplace=True),
            EqualizedLR(nn.Conv2d(out_c, out_c, 3, 1, 1)),
            PixelWiseNorm(),
            nn.LeakyReLU(negative_slope=0.2, inplace=True),
        )

    def forward(self, x):
        up   = F.interpolate(x, scale_factor=2)
        conv = self.conv(up)
        return conv

class G(nn.Module):
    def __init__(self, resl=4, rgb_channel=3):
        super().__init__()
        self.resl = resl
        self.rgb_channel = rgb_channel

        in_c, out_c = resl_to_ch[resl]

        self.resl_blocks = nn.Sequential(
            # Original Repo using "tf.nn.conv2d_transpose"
            EqualizedLR(nn.ConvTranspose2d(in_c, out_c, 4)),
            # nn.Upsample(size=(4, 4)),
            # EqualizedLR(nn.Conv2d(in_c, out_c, 1, 1, 0)),
            PixelWiseNorm(),
            nn.LeakyReLU(negative_slope=0.2, inplace=True),
            EqualizedLR(nn.Conv2d(out_c, out_c, 3, 1, 1)),
            PixelWiseNorm(),
            nn.LeakyReLU(negative_slope=0.2, inplace=True),
        )

        self.rgb_l = None
        self.rgb_h = ToRGBLayer(self.resl, self.rgb_channel)
        self.alpha = 0

    def forward(self, x, phase):
        if phase == "transition":
            return self.transition_forward(x)
        elif phase == "stabilization":
            return self.stabilization_forward(x)

    def grow_network(self):
        self.resl *= 2
        self.resl_blocks = nn.Sequential(*self.resl_blocks, ReslBlock(self.resl))
        self.rgb_l = self.rgb_h
        self.rgb_h = ToRGBLayer(self.resl, self.rgb_channel)
        self.alpha = 0

    def transition_forward(self, x):
        x = self.resl_blocks[:-1](x)

        # experiment candidate : apply rgb_l first and succeeding interpolate
        # low resolution path
        x_up = F.interpolate(x, scale_factor=2)
        rgb_l = self.rgb_l(x_up)

        # high resolution path
        x = self.resl_blocks[-1](x)
        rgb_h = self.rgb_h(x)

        return self.alpha * (rgb_h - rgb_l) + rgb_l

    def stabilization_forward(self, x):
        x = self.resl_blocks(x)
        rgb_h = self.rgb_h(x)
        return rgb_h

    def update_alpha(self, delta):
        self.alpha += delta
        self.alpha = min(1, self.alpha)

if __name__ == '__main__':
    gg = G()
    print(gg)
    print('-'*100)

#    gg.grow_network()
#    print(gg)
#    print('-'*100)
#
#    gg.grow_network()
#    print(gg)
#    print('-'*100)


import ssl
from telnetlib import *
from telnetlib.option import TelnetOption

class TelnetOptionAuthentication( TelnetOption ):
    """
        RFC 2941, Telnet Authentication Option
    """
    AUTH_TYPE_NULL          = chr( 0 )
    AUTH_TYPE_KERBEROS_V4   = chr( 1 )
    AUTH_TYPE_KERBEROS_V5   = chr( 2 )
    AUTH_TYPE_SPX           = chr( 3 )
    AUTH_TYPE_MINK          = chr( 4 )
    AUTH_TYPE_SRP           = chr( 5 )
    AUTH_TYPE_RSA           = chr( 6 )
    AUTH_TYPE_SSL           = chr( 7 )
    AUTH_TYPE_unassigned1   = chr( 8 )
    AUTH_TYPE_unassigned2   = chr( 9 )
    AUTH_TYPE_LOKI          = chr( 10 )
    AUTH_TYPE_SSA           = chr( 11 )
    AUTH_TYPE_KEA_SJ        = chr( 12 )
    AUTH_TYPE_KEA_SJ_INTEG  = chr( 13 )
    AUTH_TYPE_DSS           = chr( 14 )
    AUTH_TYPE_NTLM          = chr( 15 )

    AUTHENTICATION_IS       = chr( 0 )
    AUTHENTICATION_SEND     = chr( 1 )
    AUTHENTICATION_REPLY    = chr( 2 )
    AUTHENTICATION_NAME     = chr( 3 )

    def Do( self, telnet ):
        self.log.debug( "IAC WILL AUTHENTICATION" )
        telnet._sock.sendall( IAC + WILL + AUTHENTICATION )
        return
    # end def

    def Execute( self, telnet, sbdataq ):
        self.log.debug( "enter TelnetOptionAuthentication.Execute()" )
        self.log.info( "sbdataq = [%s]" % ( sbdataq.encode( 'hex' ) ) )
        if sbdataq[ 0 ] == AUTHENTICATION:
            action = sbdataq[ 1 ]
            if action == self.AUTHENTICATION_SEND:
                if sbdataq[ 2 ] == self.AUTH_TYPE_SSL:
                    self.log.info( 'AUTHENTICATION.SEND = %d SSL' % ( ord( action ) ) )
                    # <= "ff:fa:25:00:07:00:01:ff:f0"
                    #   IAC SB
                    #       AUTHENTICATION SEND 00 01
                    #   IAC SE
                    self.log.info( 'AUTHENTICATION.IS SSL %02X %02X' % ( 0, 1 ) )
                    self._SendIacSbSe( telnet._sock, AUTHENTICATION + self.AUTHENTICATION_IS + self.AUTH_TYPE_SSL + chr( 0 ) + chr( 1 ) )
                # end if
            elif action == self.AUTHENTICATION_REPLY:
                if sbdataq[ 2 ] == self.AUTH_TYPE_SSL:
                    # => "ff:fa:25:02:07:00:02:ff:f0""
                    #   IAC SB
                    #       AUTHENTICATION REPLY SSL 00 02
                    #   IAC SE
                    self.log.info( 'AUTHENTICATION.REPLY = %d SSL' % ( ord( action ) ) )
                    """
                        Now this start the SSL/TLS connection
                    """
                    sslsock = ssl.wrap_socket( telnet._sock,
                                ciphers="HIGH:-aNULL:-eNULL:-PSK:RC4-SHA:RC4-MD5",
                                # ssl_version=ssl.PROTOCOL_TLSv1,
                                ssl_version=ssl.PROTOCOL_SSLv23 | ssl.PROTOCOL_TLSv1,
                                cert_reqs=ssl.CERT_NONE,
                                ca_certs='/etc/ssl/certs/ca-certificates.crt'
                                )
                    # Start the negotiate
                    sslsock.getpeercert()
                    # Swap the sockets on the TELNET class
                    sock            = telnet._sock
                    telnet._sock    = sslsock
                    telnet._sockssl = sock
                # end if
            else:
                self.log.info( 'AUTHENTICATION.(%d) unsupported' % ( ord( action ) ) )
            # end if
        else:
            # IAC SB <option-bytes> IAC SE
            self.log.info( "IAC SB [%s] IAC SE is unsupported" % ( sbdataq.encode( 'hex' ) ) )
            pass
        # end if
        self.log.debug( "leave TelnetOptionAuthentication.Execute()" )
        return
    # end def
# end class


import math
import random

list=[]
for i in range(0,100):
    z = random.uniform(-14.5,14.5)
    t = random.uniform(-14.5,14.5)
    d = z+t*1j
    list.append(d)

for i in range(0,100):
    u=list[i].real
    z=list[i].imag
    print(i,u,z)

def modul(z):
    return math.sqrt((z.real)**2+(z.imag)**2)

def zwroc_kolidujace():
    for i in range(0,100):
        for j in range(i+1,100):
            if modul(list[i]-list[j])<1:
                return(i,j)
print(zwroc_kolidujace()) #zeby moc sprawdzic czy dziala

def rozsun():
    for i in range(0,100):
        for j in range(i+1,100):
            if modul(list[i]-list[j])<1:
                if list[j].real<13.5 and list[j].imag<13.5:
                    list[j] = list[j]+1+1j
                else:
                     list[j]=list[j]-1-1j
    for i in range(0,100):
        print(i,list[i].real,list[i].imag)
print(rozsun())


"""
Handling mouse events in pygame

Drag and drop an image
"""

import pygame

BLACK = 0, 0, 0
WHITE = 255, 255, 255
RED = 255, 0, 0
GREEN = 0, 255, 0
BLUE = 0, 0, 255

pygame.init()
canvas = pygame.display.set_mode((500, 600))

people = pygame.image.load('assets/people.png')

# Start with image at 0, 0
people_rect = people.get_rect()

# Are we dragging the image?
dragging = False

done = False
while not done:
    # Blank canvas
    canvas.fill(BLACK)

    mouse_x, mouse_y = pygame.mouse.get_pos()
    for event in pygame.event.get():

        # If mouse button pressed,
        if event.type == pygame.MOUSEBUTTONDOWN:
            # If the mouse pointer is on top
            # of the image
            if people_rect.collidepoint(mouse_x, mouse_y):

                # Start dragging
                dragging = True

        # If the mouse button was released, stop dragging
        elif event.type == pygame.MOUSEBUTTONUP:
            dragging = False

        # Exit when 'q' is pressed
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_q:
            done = True

    # When dragging, move the image to the current
    # mouse position
    if dragging:
        people_rect.left = mouse_x
        people_rect.top = mouse_y

    # Show the image at the (new) location
    canvas.blit(people, people_rect)

    pygame.display.flip()


import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import ticker

PATH = "statistics/results"

df = pd.read_csv(PATH+'.csv', index_col=0).round(2)
timings = [10**i for i in range(2, 6)]

fig, ax =plt.subplots(figsize=(4,3))
ax.axis('tight')
ax.axis('off')
the_table = ax.table(cellText=df.values, colLabels=df.columns, rowLabels=df.index, loc='center', cellLoc='center')
pp = PdfPages("statistics/results.pdf")
pp.savefig(fig, bbox_inches='tight')
pp.close()

fig, ax =plt.subplots(figsize=(8, 6))
ax.plot(timings, df.loc['array (μs)'], label='std::array')
ax.plot(timings, df.loc['vector (μs)'], label='std::vector')
ax.plot(timings, df.loc['set (μs)'], label='std::set')
ax.set_yscale("log")
ax.set_xscale("log")
ax.get_xaxis().set_major_formatter(ticker.ScalarFormatter())
ax.grid()
ax.set_xlabel("log size")
ax.set_ylabel("log time")

plt.legend(loc='best')
plt.savefig(PATH+'_plot.pdf')
# print(df.loc['array (μs)'])


# fixtures are functions that are run by the pytest before the actual test functions
# eg= setup database connection, initialize webdriver
import pytest

# define fixtures function (parent method)
@pytest.fixture()
def setup_list():
    print("\n in fixtures..\n")
  #  city2 = ["new york", "london", "mumbai"]
    city = ["new york","london","mumbai"]
    return city

# getting data from setup_list function , inherits its properties
def test_getItem(setup_list):  # (child method1)
    print(setup_list[1:3])
    assert setup_list[0] == "new york"
    assert setup_list[::2] == ["new york", "mumbai"]


"""
Created on 7 Apr 2018

@author: john.dwan

ELEVATION PROFILE APP GENERATOR
ideagora geomatics-2018
http://geodose.com
"""

import json
from math import asin, cos, radians, sin, sqrt
import urllib.request

import matplotlib.pyplot as plt
from shapely.geometry import LineString

from siteline import config

def haversine(lat1, lon1, lat2, lon2):
	"""
	Given the coordinates of two points as floats

	Returns the distance between these two point in km
	"""
	lat1_rad = radians(lat1)
	lat2_rad = radians(lat2)
	lon1_rad = radians(lon1)
	lon2_rad = radians(lon2)
	delta_lat = lat2_rad - lat1_rad
	delta_lon = lon2_rad - lon1_rad
	a = sqrt((sin(delta_lat / 2)) ** 2 + cos(lat1_rad) * cos(lat2_rad) * (sin(delta_lon / 2)) ** 2)
	d = 2 * 6371000 * asin(a)
	return d

def plot_profile(
		a_end_name, a_end_lat, a_end_lon, b_end_name, b_end_lat, b_end_lon, a_end_agl=10, b_end_agl=20, num_points=1000):
	"""
	Takes a customer site (a_end_name=str), it's coordinates (a_end_lat=Float, a_end_lon=Float) and a
	Highsite (b_end_name=str) and it's coordinates (b_end_lat=Float, b_end_lon=Float)
	and optionally number of points along a line (num_points=Integer) which is max 1000 on open-elevation.com API,
	Note: no limit if running open-elevation locally.

	Saves a elevation profile between these two points as a .png
	"""

	# NUMBER OF POINTS
	interval_lat = (b_end_lat - a_end_lat) / num_points  # interval for latitude
	interval_lon = (b_end_lon - a_end_lon) / num_points  # interval for longitude

	# LATITUDE AND LONGITUDE LIST
	lat_list = [a_end_lat]
	lon_list = [a_end_lon]

	# GENERATING POINTS
	for i in range(num_points):
		lat_step = a_end_lat + interval_lat
		lon_step = a_end_lon + interval_lon
		a_end_lon = lon_step
		a_end_lat = lat_step
		lat_list.append(lat_step)
		lon_list.append(lon_step)

	# DISTANCE CALCULATION
	d_list = []
	for j in range(len(lat_list)):
		lat_p = lat_list[j]
		lon_p = lon_list[j]
		dp = haversine(a_end_lat, a_end_lon, lat_p, lon_p) / 1000  # km
		d_list.append(dp)
	d_list_rev = d_list[::-1]  # reverse list

	# CONSTRUCT JSON
	location = {}
	d_ar = [{}] * len(lat_list)
	for i in range(len(lat_list)):
		d_ar[i] = {"latitude": lat_list[i], "longitude": lon_list[i]}
	location['locations'] = d_ar
	json_data = json.dumps(location, skipkeys=int).encode('utf8')

	# SEND REQUEST
	response = urllib.request.Request(config.URL, json_data, headers={'Content-Type': 'application/json'})
	fp = urllib.request.urlopen(response)

	# RESPONSE PROCESSING
	res_byte = fp.read()
	res_str = res_byte.decode("utf8")
	js_str = json.loads(res_str)
	fp.close()

	# GETTING ELEVATION
	response_len = len(js_str['results'])
	elev_list = []
	for j in range(response_len):
		elev_list.append(js_str['results'][j]['elevation'])

	# BASIC STAT INFORMATION
	# mean_elev = round((sum(elev_list) / len(elev_list)), 3)
	# min_elev = min(elev_list)
	# max_elev = max(elev_list)
	distance = d_list_rev[-1]

	# LoS
	a_list = []
	for i in range(0, len(d_list_rev) - 1):
		a_tuple = (d_list_rev[i], elev_list[i])
		a_list.append(a_tuple)
	terrain = LineString(a_list)
	los_path = LineString(
		[(d_list_rev[0], elev_list[0] + a_end_agl), (d_list_rev[-1], elev_list[-1] + b_end_agl)])

	path_colour = '--g'
	print(terrain.intersection(los_path))
	if terrain.intersection(los_path):
		print('No LoS')
		path_colour = '--r'

	# PLOT ELEVATION PROFILE
	# with context('fivethirtyeight'):
	base_reg = 0
	plt.figure(figsize=(10, 4))
	plt.plot(d_list_rev, elev_list)
	plt.plot(
		[d_list_rev[0],
		d_list_rev[-1]],
		[elev_list[0] + a_end_agl,
		elev_list[-1] + b_end_agl],
		path_colour,
		label='LoS 10m AGL customer site to 20m highsite'
	)
	plt.fill_between(d_list_rev, elev_list, base_reg, alpha=0.1)
	plt.text(d_list_rev[0], elev_list[0], a_end_name)
	plt.text(d_list_rev[-1], elev_list[-1], b_end_name)
	plt.xlabel('Distance(km)    ' + str(round(distance)) + 'km')
	plt.ylabel('Elevation(m)    ' + str(elev_list[-1] - elev_list[0]) + 'm')
	plt.grid()
	plt.legend(fontsize='small')
	fname = a_end_name + '__to__' + b_end_name + '.png'
	plt.savefig(config.OUT_PATH.joinpath(fname))
	plt.close()


# Створіть програму для отримання курсу валют за певний період.
# - отримати від користувача дату (це може бути як один день так і інтервал - початкова і кінцева дати,
# продумайте механізм реалізації) і назву валюти
# - вивести курс по відношенню до гривні на момент вказаної дати (або за кожен день у вказаному інтервалі)
# - не забудьте перевірку на валідність введених даних

import requests
from pprint import pprint
import re
from HT_14.task_2.exchangefunks import currently_exchange_rate, history_of_exchange_rates, period_exchange_information

date_pattern = re.compile(r'^(?:19|20)\d\d,(?:0[1-9]|1[0-2]),(?:0[1-9]|[12][0-9]|3[01])$')

def exchanger():
    print("Choose necessary function of exchange manager you need:")
    menu_options = {"1": "currently_exchange_rate",
                    "2": "history_of_exchange_rates",
                    "3": "period_exchange_information",
                    "4": "exit"}
    for key, value in menu_options.items():
        print(f"{key} <-------- {value}")
    choice = input("Enter your choice using number: ")
    if choice in menu_options.keys():
        if choice == "1":
            currency = input("Enter currency you interested in by using international "
                             "format RUB,EUR,USD,UAH with coma separator: ").upper().split(",")
            result = currently_exchange_rate(currency)["quotes"]
            for curency, rate in result.items():
                print(f"{curency} ---- {rate}")
        if choice == "2":
            currency = input("Enter currency you interested in by using international "
                             "format RUB,EUR,USD,UAH with coma separator: ").upper().split(",")
            try:
                input_date = input("Enter start date in format YYYY,MM,DD: ")
                if date_pattern.match(input_date):
                    search_date = input_date.split(",")
            except ValueError:
                print("Invalid date format. Please enter in YYYY,MM,DD format.")
            result = history_of_exchange_rates(income_date=search_date, income_currencies=currency)
            date = result["date"]
            quote = result["quotes"].items()
            print(f"For {date} exchange rate was: ")
            for curency, rate in quote:
                print(f"{curency} ---- {rate}")
        if choice == "3":
            try:
                input_start = input("Enter start date in format YYYY,MM,DD: ")
                if date_pattern.match(input_start):
                    start_date = input_start.split(",")
            except ValueError:
                print("Invalid date format. Please enter in YYYY,MM,DD format.")
            try:
                input_end = input("Enter end date in format YYYY,MM,DD: ")
                if date_pattern.match(input_end):
                    end_date = input_end.split(",")
            except ValueError:
                print("Invalid date format. Please enter in YYYY,MM,DD format.")

            currency = input("Enter currency you interested in by using international "
                             "format RUB,EUR,USD,UAH with coma separator: ").upper().split(",")
            result = period_exchange_information(income_start=start_date, income_end=end_date,
                                                 income_currencies=currency)
            quote = result["quotes"].items()
            print(f"The exchange rate in period from {input_start} to {input_end} was:")
            for date, rate_dict in quote:
                for code, rate in rate_dict.items():
                    print(f"On {date} for {code} was {rate} rate")
        if choice == "4":
            return "Good bye"

print(exchanger())


import abc
from typing import TYPE_CHECKING

from ml_deeco.estimators import Estimate

if TYPE_CHECKING:
    from ml_deeco.simulation import Experiment

class ComponentMeta(abc.ABCMeta):
    """
    Metaclass for Component. Uses a counter to automatically generate the component ID.
    """

    def __new__(mcs, name, bases, namespace):
        namespace['_count'] = 0  # initialize the counter
        return super().__new__(mcs, name, bases, namespace)

class Component(metaclass=ComponentMeta):
    """
    Base class for all components.

    Attributes
    ----------
    id : str
        Identifier of the component. Generated automatically.
    """
    id: str
    _count = 0  # Number of components of each type

    def __init__(self):
        # generate the ID
        cls = type(self)
        cls._count += 1
        self.id = "%s_%d" % (cls.__name__, cls._count)

    def actuate(self):
        """
        Behavior of the component which is executed once per time step. Should be developed by the framework user.
        """
        pass

    def collectEstimatesData(self):
        """
        Collects data for Estimates. This is called from the simulation after a step is performed.
        """
        estimates = [fld for (fldName, fld) in type(self).__dict__.items()
                     if not fldName.startswith('__') and isinstance(fld, Estimate)]
        for estimate in estimates:
            estimate.collectInputs(self)
            estimate.collectTargets(self)

    @classmethod
    def initEstimates(cls, experiment: 'Experiment'):
        """Assigns the experiment to the estimates. This is necessary when the estimator was specified as a string in
        the 'using' method."""
        estimates = [fld for (fldName, fld) in cls.__dict__.items()
                     if not fldName.startswith('__') and isinstance(fld, Estimate)]
        for estimate in estimates:
            estimate.linkExperiment(experiment)

    def __repr__(self) -> str:
        return self.id


"""
Problem Set 3
"""

def pretty_print_fwd(fwd_struct):
    """
    Arma cuadro para visualizar una estructura forward.
    Parámetros:
        fwd_struct : Estructura de tasas forward
    """
    for t, fwds in fwd_struct.items():
        fwds_txt = ', '.join(f'{tt:3}: {r:6.2%}' for tt, r in fwds.items())
        print(f'{t:3}: {{', fwds_txt, '}')

if __name__ == '__main__':
    import json

    data = json.loads(open('C:\\Users\\FedericoMenendez\\Desktop\\PYTHON\\FinanzasPython\\data\\c4_mkt_data.json').read())


# -*- coding: utf-8 -*-
# __author__ = 'Administrator'
import time

from core import get_info

start = 0
end = 0

def main(s, e):
    """
    起始学号s，结束学号e，遍历。
    模拟登录教务系统获取学生信息，
    写入到ninfo.txt文件中。
    """
    for i in range(s, e, 1):
        counts = 0
        mdic = get_info.get_info(i)
        print(i)
        while len(mdic) == 0 and counts < 3:
            mdic = get_info.get_info(i)
            counts += 1
        if len(mdic) != 0:
            time.sleep(1)
            print(mdic)
            ff = open("ninfo.txt", "a", encoding="utf-8")
            ff.write(mdic.__str__()+",\n")
            ff.close()

if __name__ == '__main__':
    main(start, end)


"""Common methods and classes used for mesh client"""
from collections import namedtuple
import os
import json
import boto3

REGION_NAME = os.environ.get("AWS_REGION", "eu-west-2")

class SingletonCheckFailure(Exception):
    """Singleton check failed"""

    def __init__(self, msg=None):
        super().__init__()
        self.msg = msg

class AwsFailedToPerformError(Exception):
    """Errors raised by AWS functions"""

    def __init__(self, msg=None):
        super().__init__()
        self.msg = msg

class MeshCommon:
    """Common"""

    MIB = 1024 * 1024
    DEFAULT_CHUNK_SIZE = 20 * MIB

    @staticmethod
    def singleton_check(mailbox, my_step_function_name):
        """Find out whether there is another step function running for my mailbox"""
        sfn_client = boto3.client("stepfunctions", region_name="eu-west-2")
        response = sfn_client.list_state_machines()
        # Get my step function arn
        my_step_function_arn = None
        for step_function in response.get("stateMachines", []):
            if step_function.get("name", "") == my_step_function_name:
                my_step_function_arn = step_function.get("stateMachineArn", None)

        # TODO add this check to tests
        if not my_step_function_arn:
            raise SingletonCheckFailure(
                "No executing step function arn for "
                + f"step_function={my_step_function_name}"
            )

        response = sfn_client.list_executions(
            stateMachineArn=my_step_function_arn,
            statusFilter="RUNNING",
        )
        currently_running_step_funcs = []
        for execution in response["executions"]:
            currently_running_step_funcs.append(execution["executionArn"])

        exec_count = 0
        for execution_arn in currently_running_step_funcs:
            response = sfn_client.describe_execution(executionArn=execution_arn)
            step_function_input = json.loads(response.get("input", "{}"))
            input_mailbox = step_function_input.get("mailbox", None)
            if input_mailbox == mailbox:
                exec_count = exec_count + 1
            if exec_count > 1:
                raise SingletonCheckFailure("Process already running for this mailbox")

        return True

    @staticmethod
    def convert_params_to_dict(params):
        """Convert paramater dict to key:value dict"""
        new_dict = {}
        for entry in params:
            name = entry.get("Name", None)
            if name:
                var_name = os.path.basename(name)
                new_dict[var_name] = entry.get("Value", None)
        return new_dict

    @staticmethod
    def return_failure(log_object, status, logpoint, mailbox, message=""):
        """Return a failure response with retry"""
        log_object.write_log(logpoint, None, {"mailbox": mailbox, "error": message})
        return {
            "statusCode": status,
            "headers": {
                "Content-Type": "application/json",
                "Retry-After": 18000,
            },
            "body": {
                "internal_id": log_object.internal_id,
                "error": message,
            },
        }

    @staticmethod
    def get_params(path, recursive=False, decryption=True):
        """
        Get parameters from SSM and secrets manager
        """
        ssm_client = boto3.client("ssm", region_name=REGION_NAME)
        params_result = ssm_client.get_parameters_by_path(
            Path=path,
            Recursive=recursive,
            WithDecryption=decryption,
        )
        params = params_result.get("Parameters", {})
        new_params_dict = {}
        for entry in params:
            name = entry.get("Name", None)
            if name:
                var_name = os.path.basename(name)
                new_params_dict[var_name] = entry.get("Value", None)
        if os.environ.get("use_secrets_manager") == "true":
            secrets_client = boto3.client("secretsmanager", region_name=REGION_NAME)
            all_secrets_dict = secrets_client.list_secrets()
            all_secrets_list = all_secrets_dict["SecretList"]
            for secret in all_secrets_list:
                name = secret["Name"]
                if name.startswith(path):
                    secret_value = secrets_client.get_secret_value(SecretId=name)[
                        "SecretString"
                    ]
                    var_name = os.path.basename(name)
                    new_params_dict[var_name] = secret_value
        return new_params_dict

# Named tuple for holding Mesh Message info
MeshMessage = namedtuple(
    "MeshMessage",
    [
        "filename",
        "body",
        "src_mailbox",
        "dest_mailbox",
        "workflow_id",
        "message_id",
    ],
)


from factsumm import FactSumm
import jsonlines

factsumm = FactSumm()

with jsonlines.open('/home/tiezheng/workspace/FidSum/data/qmsum/processed_data_no_sent_split/test.jsonl') as F:
    article = []
    target = []
    for item in F:
        article.append(item['src'])
        target.append(item['tgt'])

with open('src.txt', 'w') as F:
    F.writelines([item+'\n' for item in article])

with open('tgt.txt', 'w') as F:
    F.writelines([item+'\n' for item in target])

# with open('/home/tiezheng/workspace/FidSum/data/qmsum/test_results/12_512_no_KA_in_generation_penalty1_maxlen256.results') as F:

#     summary = F.readlines()
#     summary = [item.strip('\n') for item in summary]

# # factsumm(article[0], summary[0], device="cuda")

# article = "Lionel Andrés Messi (born 24 June 1987) is an Argentine professional footballer who plays as a forward and captains both Spanish club Barcelona and the Argentina national team. Often considered as the best player in the world and widely regarded as one of the greatest players of all time, Messi has won a record six Ballon d'Or awards, a record six European Golden Shoes, and in 2020 was named to the Ballon d'Or Dream Team."
# summary = "Lionel Andrés Messi (born 24 Aug 1997) is an Spanish professional footballer who plays as a forward and captains both Spanish club Barcelona and the Spanish national team."
# factsumm(article, summary, verbose=True, device="gpu")


from card import Card

suits = ('Spades', 'Clubs', 'Hearts', 'Diamonds')
values = ('A', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')

class Deck:
    def __init__(self):
        self.deck = []
        for x in suits:
            for y in values:
                self.deck.append(Card(x, y))


from odoo import models, api
from odoo.exceptions import UserError

class ReportTrainingList(models.AbstractModel):
    _name = 'report.training.report_training_list'

    def _get_training(self, data):
        trainer = data['form'].get('trainer_id')[0]
        date_from = data['form'].get('date_from') or None
        date_to = data['form'].get('date_to') or None
        domain = [('trainer_id', '=', trainer)]
        if date_from:
            domain.append(('date_from', '>=', date_from))
        if date_to:
            domain.append(('date_to', '>=', date_to))
        trainings = self.env['training.training'].search(domain)
        ### ista stvar sa cistim sql
        sql = '''
            select
              id
            from
              training_training
            where
              trainer_id = {0}
            '''.format(trainer)
        if date_from:
            sql += ''' and 'date_from' >= {}'''.format(date_from)
        if date_to:
            sql += ''' and 'date_to' <= {}'''.format(date_to)
        self.env.cr.execute(sql)
        trainings = self.env['training.training'].browse([line[0] for line in self.env.cr.fetchall()])
        #### Dobivam listu sa cistim ID-evima i odmah ih pretvaram u objekte i sibam dalje
        return trainings

    @api.model
    def render_html(self, docids, data=None):
        if not data.get('form') or not self.env.context.get('active_model') or not self.env.context.get('active_id'):
            raise UserError(_("Form content is missing, this report cannot be printed."))
        ### Ako ne dobijemo form u data varijabli baci error, nuzno je da iz wizarda dobijemo podatke koje trebamo prikazati
        docs = self.env['training.report.wizard'].browse(self.env.context.get('active_id'))
        ### Ocekuje neki model nad kojem je napravljen model, prosljedjujem mu model wizarda koji se dize
        docargs = {
            'doc_ids': docids,
            'doc_model': 'training.report.wizard',
            'data': data,
            'docs': docs,
            'training_list': self._get_training(data)
        }
        ### neke defaultne vrijednosti koje ova metoda ocekuje, sa iznimkom training_list koja je nasa varijabla koja vraca listu
        ### treninga
        return self.env['report'].render('training.report_training_list', docargs)
        ### ovdje vracamo naziv reporta koji zovemo


import sys
sys.stdin = open("swap.in", "r")
sys.stdout = open("swap.out", "w")

n,m,k = map(int, input().split())
order = [tuple(map(int, input().split())) for _ in range(m)]

cows = list(range(1,n+1))
record = [tuple(cows)]
for i in range(k):
    for a,b in order:
        cows[a-1:b] = cows[a-1:b][::-1]
    cur_cows = tuple(cows)
    if cur_cows not in record:
        record.append(tuple(cows))
    else:
        for cow in record[k%len(record)]:
            print(cow)
        exit()
for cow in record[-1]:
    print(cow)


"""
Validating Credit Card Numbers

https://www.hackerrank.com/challenges/validating-credit-card-number/problem
"""

import re

for _ in range(int(input())):
    num = input()

    ok1 = bool(re.match(r"^[456]\d{15}$", num))
    ok2 = bool(re.match(r"^[456]\d{3}\-\d{4}\-\d{4}\-\d{4}$", num))
    num = num.replace("-", "")
    ok3 = bool(re.match(r"(?!.*(\d)(-?\1){3})", num))
    if (ok1 or ok2) and ok3:
        print("Valid")
    else:
        print("Invalid")


def solution(n, m, x, y, r, c, k):
    answer = ''
    graph = [[0 for _ in range(m+1)] for _ in range(n+1)]
    route = []

    def DFS(x, y, troute, cnt):
        if cnt == k and x == r and y == c:
            route.append(troute)
        if cnt >= k:
            return
        remain = k - cnt + 1
        short = abs(x-r) + abs(y-c)
        if remain < short:
            return
        nx = [1, 0, 0, -1]
        ny = [0, -1, 1, 0]
        t = ['d', 'l', 'r', 'u']
        for i in range(4):
            dx = nx[i] + x
            dy = ny[i] + y
            if 1 <= dx <= n and 1 <= dy <= m:
                if route:
                    return
                else:
                    DFS(dx, dy, troute + t[i], cnt+1)
    DFS(x, y, '', 0)
    route.sort()
    if route:
        answer = route[0]
    else:
        answer = 'impossible'
    return answer

미로 탈출 명령어.py


class Node():
    def __init__(self, value):
        self.value = value
        self.next = None
class LinkedList():
    def __init__(self):
        self.head = None
        self.tail = None
        self.index = 0

    def print_list(self):
        current = self.head
        linked_list = ""
        while(current is not None):
            if current.next is None:
                linked_list += str(current.value.value)
            else:
                linked_list += str(current.value.value) + "=>"
            current = current.next
        return linked_list

    def add_first(self, value):
        new_node = Node(value)
        if self.is_empty():
            self.head = new_node
            self.tail = new_node
        else:
            new_node.next = self.head
            self.head = new_node
        self.index += 1

    def add_last(self, value):
        new_node = Node(value)
        if self.is_empty():
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node
        self.index += 1

    def delete_first(self):
        if self.is_empty():
            raise Exception("LinkedList is empty")
        if self.head == self.tail:
            self.head = None
            self.tail = None
        else:
            second = self.head.next
            self.head.next = None
            self.head = second
        self.index -= 1

    def delete_last(self):
        last = None
        if self.is_empty():
            raise Exception("LinkedList is empty")
        if self.head == self.tail:
            last = self.head
            self.head = None
            self.tail = None
        else:
            last = self.tail
            previous = self.get_previous(self.tail)
            self.tail = previous
            previous.next = None
        self.index -= 1
        return last.value

    def contains(self, value):
        return self.index_of(value) != -1

    def index_of(self, value):
        count = 0
        current = self.head
        while (current is not None):
            if current.value == value:
                return count
            current = current.next
            count += 1
        return -1

    def is_empty(self):
        return self.head is None

    def get_previous(self, node):
        current = self.head
        while current is not None:
            if current.next == node: return current
            current = current.next
        return None

    def size(self):
        return self.index

    def to_array(self):
        array = []
        current = self.head
        while (current is not None):
            array.append(current.value)
            current = current.next
        return array

    def reverse(self):
        if self.is_empty(): return

        previous = self.head
        current = self.head.next
        while current is not None:
            next = current.next
            current.next = previous
            current = next
            previous = current

        self.tail = self.head
        self.tail.next = None
        self.head = previous

    def get_kth_from_the_end(self, k):
        if k <= 0 or self.is_empty(): return
        if k > self.size(): return

        first = self.head
        second = self.head
        for i in range(k):
            second = second.next
        while second is not None:
            first = first.next
            second = second.next
        return first.value

    def print_middle(self):
        if self.is_empty(): return
        if self.head.next is None: return self.head.value

        first = self.head
        second = self.head

        while second != self.tail and second.next != self.tail:
            second = second.next.next
            first = first.next
        if second == self.tail:
            return first.value
        else:
            return (first.value, first.next.value)

    def has_loop(self):
        if self.is_empty(): return
        if self.head.next is None: return self.head.value

        first = self.head
        second = self.head
        while second.next.next is not None:
            second = second.next.next
            first = first.next
            if second.next is None:
                return False
            if second.value == first.value:
                return True
        return False

class KeyValuePair():
    def __init__(self, key, value) -> None:
        self.key = key
        self.value = value
class HashTable():
    def __init__(self, size
    ) -> None:
        self.items = [None] * size
        self.count = 0
        self.size = size

    def put(self, key, value):
        if (self.count < self.size):
            hash_value = self.hash(key)
            key_value = KeyValuePair(key, value)
            if (self.items[hash_value] is None):
                linked_list = LinkedList()
                linked_list.add_last(key_value)
                self.items[hash_value] = linked_list
            else:
                current = self.items[hash_value].head
                while current is not None:
                    print(current.value.key, key)
                    if current.value.key == key:
                        current.value.value = value
                        return
                    current = current.next

                self.items[hash_value].add_last(key_value)
            self.count += 1
        else:
            raise Exception("Hashtable is full")

    def hash(self, key):
        return key % self.size

    def get(self, key):
        hash_value = self.hash(key)
        if self.items[hash_value] is None:
            raise Exception("Key does not exist")
        head = self.items[hash_value].head

        while head is not None:
            key_value = head.value
            if key_value.key == key:
                return key_value.value
            head = head.next
        return None

    def remove(self , key):
        hash_value = self.hash(key)
        linked_list = self.items[hash_value]
        if linked_list is None:
            raise Exception("Key does not exist")
        if linked_list.size() > 1:
            # Check if head is key
            if (linked_list.head.value.key == key):
                linked_list.delete_first()
                return

            # Check if its at the end
            if (linked_list.tail.value.key == key):
                linked_list.delete_last()
                return

            # Check if it is somewhere in the middle
            current = linked_list.head
            while current is not None:
                key_value = current.value
                if key_value.key == key:
                    previous = linked_list.get_previous(current)
                    previous.next = current.next
                    return
                current = current.next
            raise Exception("Key does not exist")
        else:
            self.items[hash_value] = None

    def print(self):
        print("=========PRINT=========")
        for i in range(self.size):
            if self.items[i] is not None:
                print(self.items[i].print_list(), end="\n")

# hashTable = HashTable(5)
# hashTable.put(1, "Gonzalo")
# hashTable.put(3, "Garcia")
# hashTable.put(4, "Martinez")
# hashTable.put(6, "Juan")
# hashTable.put(6, "Test")

# hashTable.print()
# hashTable.remove(3)
# hashTable.remove(1)
# hashTable.print()
# print("=========GET=========")
# print(hashTable.get(1))
# print(hashTable.get(6))
# print(hashTable.get(2))

def find_first_non_repeated_character(string):
    dict = {}
    for i in string:
        if i != ' ':
            if i not in dict:
                dict[i] = 1
            else:
                dict[i] += 1
    for i in dict:
        if dict[i] == 1:
            return i

# print(find_first_non_repeated_character('a green apple'))

# my_set = set((1, 1, 2 ,3 ,4, 5 , 6))
# print(my_set)
# print(1 in my_set)

def first_first_repeated_character(string):
    dict = set()
    for i in string:
        if i != ' ':
            if i not in dict:
                dict.add(i)
            else:
                return i

# print(first_first_repeated_character('green apple'))

def hash(number):
    return number % 100

def most_frequent(array):
    dict = {}
    for item in array:
        if item in dict:
            dict[item] += 1
        else:
            dict[item] = 1
    max = -1
    result = 0
    for key in dict:
        if dict[key] > max:
            max = dict[key]
            result = key
    print(result)

# most_frequent([1,2,2,3,3,3,4])

def count_pairs_with_diff(nums, k):
    num_dict = {}
    count = 0

    for num in nums:
        num_dict[num] = num_dict.get(num, 0) + 1
    for num in num_dict:
        if num + k in num_dict:
            count += 1

    print(count)

# count_pairs_with_diff([1, 7, 5, 9, 2, 12, 3], 2)

def two_sum(array, target):
    dict = {}
    for index, item in enumerate(array):
        dict[item] = index

    for index, item in enumerate(array):
        if target - item in array:
            print (dict[item], dict[target - item])
            return

# two_sum([2, 7, 11, 15], 9)

class HashTableLinearProbing:
    def __init__(self, size
    ) -> None:
        self.items = [None] * size
        self.count = 0
        self.size = size

    def put(self, key, value):
        index = self.hash(key)
        key_value = KeyValuePair(key, value)
        if self.items[index] is None:
            self.items[index] = key_value
        else:
            old_index = index
            while True:
                if index == self.size:
                    index = 0
                if self.items[index] is None:
                    self.items[index] = key_value
                    return
                index += 1
                if index == old_index:
                    raise Exception("Hashtable is full")

    def get(self, key):
        index = self.hash(key)
        old_index = index
        while(True):
            if self.items[index].key == key:
                if self.items[index].value == "TOMBSTONE":
                    return None
                return  self.items[index].value
            index +=1
            if index == self.size:
                index = 0
            if index == old_index:
                    raise Exception("Item not found")

    def remove(self, key):
        index = self.hash(key)
        while (True):
            if self.items[index].key == key:
                self.items[index].value = "TOMBSTONE"
                return
            index+=1

    def size(self):
        return self.size

    def hash(self, number):
        return number % self.size

    def print(self):
        for item in self.items:
            print(item.value, end=" ")

hash_probing = HashTableLinearProbing(5)
hash_probing.put(6, 'A')
hash_probing.put(11, 'C')
hash_probing.put(8, 'B')
hash_probing.put(16, 'D')
hash_probing.put(21, 'E')
# hash_probing.put(26, 'F')
hash_probing.print()
print()
print(hash_probing.get(8))
hash_probing.remove(11)
hash_probing.print()
print()
print("======GET======")
print(hash_probing.get(21))
print(hash_probing.get(1))


import heapq
def solution(time, works):
    answer = 0
    for i in range(len(works)):
        works[i]=-works[i]
    heapq.heapify(works)
    while time>0 and works:
        a=heapq.heappop(works)
        if a==0:
            continue
        a+=1
        time-=1
        heapq.heappush(works,a)

    for i in works:
        answer+=i**2

    return answer
print(solution(4,[4,3,3]))

프로그래머스/야근 지수.py


from math import inf
from collections import deque
from tracemalloc import start

def dijkstra(wmat, start, end=-1):
    n = len(wmat)

    dist = [inf] * n
    dist[start] = wmat[start][start]  # 0

    spVertex = [False] * n
    parent = [-1] * n

    path = [{}] * n

    for count in range(n - 1):
        minix = inf
        u = 0

        for v in range(len(spVertex)):
            if spVertex[v] == False and dist[v] <= minix:
                minix = dist[v]
                u = v

        spVertex[u] = True
        for v in range(n):
            if not (spVertex[v]) and wmat[u][v] != 0 and dist[u] + wmat[u][v] < dist[v]:
                parent[v] = u
                dist[v] = dist[u] + wmat[u][v]

    for i in range(n):
        j = i
        s = []
        while parent[j] != -1:
            s.append(j)
            j = parent[j]
        s.append(start)
        path[i] = s[::-1]

    return (dist[end], path[end]) if end >= 0 else (dist, path)

def checkbipartite(graph):
    N = len(graph)
    col = [-1] * N
    for i in range(N):
        if col[i] != -1:
            continue
        q = deque()
        q.append((0, 0))
        # bfs
        while q:
            node, color = q.popleft()
            if col[node] == -1:
                col[node] = color
                for nx in graph[node]:
                    q.append((nx, color ^ 1))
        if col[node] != color:
            return False
    return True

def getdegree(graph):
    for ind in range(len(graph)):
        count = 0
        x = graph[ind]
        for i in x:
            if i > 0:
                count += 1
        print("degree of " + str(ind) + " is " + str(count))

def isConnected(graph, V):
    # Mark all the vertices as not visited
    visited = [False] * (V)

    #  Find a vertex with non-zero degree
    for i in range(V):
        if len(graph[i]) > 1:
            break

    # If there are no edges in the graph, return true
    if i == V - 1:
        return True

    # Start DFS traversal from a vertex with non-zero degree
    DFSUtil(graph, i, visited)

    # Check if all non-zero degree vertices are visited
    for i in range(V):
        if visited[i] == False and len(graph[i]) > 0:
            return False

    return True

def DFSUtil(graph, v, visited):
    # Mark the current node as visited
    visited[v] = True

    # Recur for all the vertices adjacent to this vertex
    for i in graph[v]:
        if visited[i] == False:
            DFSUtil(graph, i, visited)

def isEulerian(graph, V):
    # Check if all non-zero degree vertices are connected
    if isConnected(graph, V) == False:
        return 0
    else:
        # Count vertices with odd degree
        odd = 0
        for i in range(V):
            if len(graph[i]) % 2 != 0:
                odd += 1

        '''If odd count is 2, then semi-eulerian.
        If odd count is 0, then eulerian
        If count is more than 2, then graph is not Eulerian
        Note that odd count can never be 1 for undirected graph'''
        if odd == 0:
            return 2
        elif odd == 2:
            return 1
        elif odd > 2:
            return 0

def testeuler(graph):
    res = isEulerian(graph, len(graph))
    if res == 0:
        print("graph is not Eulerian")
    elif res == 1:
        print("graph has a Euler path")
    else:
        print("graph has a Euler cycle")

def findpaths(graph, start, end):
    def dfs(node, path, output):
        if node == end:
            output.append(path)
        for nx in range(len(graph[node])):
            if nx not in path:
                if graph[node][nx] > 0:
                    dfs(nx, path + [nx], output)

    output = []
    dfs(start, [start], output)
    return output

testgraph = [[0, 2, 0, 0, 0, 1, 0, 0],
             [2, 0, 2, 2, 4, 0, 0, 0],
             [0, 2, 0, 0, 3, 0, 0, 1],
             [0, 2, 0, 0, 4, 3, 0, 0],
             [0, 4, 3, 4, 0, 0, 7, 0],
             [1, 0, 0, 3, 0, 0, 5, 0],
             [0, 0, 0, 0, 7, 5, 0, 6],
             [0, 0, 1, 0, 0, 0, 6, 0]]
start = 0
end = 3

print("==>> paths")
print(findpaths(testgraph, start, end))
print("==>> check euler")
testeuler(testgraph)
print("==>> check degree")
getdegree(testgraph)
print("==>> isbiparite " + str(checkbipartite(testgraph)))
print("==>> dijkstra ", dijkstra(testgraph, start, end)[1])


""" HSC Datasets """

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from . import hsc_utils
from . import astroimage_utils

from tensor2tensor.data_generators import generator_utils
from tensor2tensor.data_generators import image_utils
from tensor2tensor.data_generators import problem
from tensor2tensor.layers import modalities, common_layers
from tensor2tensor.utils import metrics

from galaxy2galaxy.utils import registry

from scipy.ndimage import gaussian_filter

import tensorflow as tf
import numpy as np
import fits2hdf.pyhdfits as fits
from astropy.table import Table
from astropy.visualization import make_lupton_rgb
import h5py
import os

# HSC default pixel scale
_HSC_PIXEL_SCALE=0.168 #arcsec
# Path to sql files for HSC samples
_HSC_SAMPLE_SQL_DIR=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')

def _resize_image(im, size):
  centh = im.shape[0]/2
  centw = im.shape[1]/2
  lh, rh = int(centh-size/2), int(centh+size/2)
  lw, rw = int(centw-size/2), int(centw+size/2)
  cropped = im[lh:rh, lw:rw, :]
  assert cropped.shape[0]==size and cropped.shape[1]==size, f"Wrong size! Still {cropped.shape}"
  return cropped

@registry.register_problem
class Img2imgHSC(astroimage_utils.AstroImageProblem):
  """Base class for image problems created from HSC Public Data Release.
  """

  # START: Subclass interface
  def hparams(self, defaults, model_hparams):
    p = defaults
    p.img_len = 64
    p.filters = ['HSC-G', 'HSC-R', 'HSC-I', 'HSC-Z']
    p.sql_file = os.path.join(_HSC_SAMPLE_SQL_DIR, 'hsc_pdr2_wide_anomaly_small.sql')
    p.data_release = 'pdr2'
    p.rerun = 'pdr2_wide'

  @property
  def num_bands(self):
    """Number of bands."""
    p = self.get_hparams()
    return len(p.filters)

  def generator(self, data_dir, tmp_dir, dataset_split, task_id=-1):
    """ Generator yielding individual postage stamps.
    """
    p = self.get_hparams()

    # Step 1: Maybe regenerate the dataset
    self.maybe_build_dataset(tmp_dir)
    import timeit

    # Step 2: Extract postage stamps, resize them to requested size
    catalog = Table.read(os.path.join(tmp_dir, 'catalog.fits'))
    with h5py.File(os.path.join(tmp_dir, 'cutouts.hdf'),'r') as cutouts:
        # Loop through the examples, resize cutout to desired size
        for row in catalog:
          cutout = cutouts[str(row['object_id'])]
          im = [cutout[f]['HDU0']['DATA'][:] for f in p.filters]

          try:
              im = np.stack(im, axis=-1).astype('float32')
          except:
              print('Failure to stack bands', [i.shape for i in im])
              continue

          # Images may not have exactly the right number of pixels
          im = _resize_image(im, p.img_len)

          serialized_output = {"image/encoded": [im.tostring()],
                               "image/format": ["raw"]}

          # If attributes are requested, let's add them to the dataset
          if hasattr(p, 'attributes'):
            for k in p.attributes:
              serialized_output['attrs/'+k] = [np.asscalar(row[k])]

          yield serialized_output

  def preprocess_example(self, example, unused_mode, unused_hparams):
    """ Preprocess the examples, can be used for further augmentation or
    image standardization.
    """
    p = self.get_hparams()
    image = example["inputs"]

    # TODO: apply some pre-processing/normalization to the images

    if hasattr(p, 'attributes'):
      example["attributes"] = tf.stack([example[k] for k in p.attributes])

    example["inputs"] = image
    example["targets"] = image
    return example

  # END: Subclass interface
  @property
  def is_generate_per_split(self):
    return False

  def maybe_build_dataset(self, tmp_dir):
    """ Check that the HSC dataset is downloaded and ready in tmp_dir, otherwise
    redownload it from the server.
    """
    p = self.get_hparams()
    if (not os.path.isfile(os.path.join(tmp_dir, 'catalog.fits')) or
        not os.path.isfile(os.path.join(tmp_dir, 'cutouts.hdf')) ):
      hsc_utils.build_hsc_sample(p.sql_file,
                                 out_dir=tmp_dir,
                                 tmp_dir=os.path.join(tmp_dir,'tmp'),
                                 cutout_size=(1.5+p.img_len)*_HSC_PIXEL_SCALE/2, # Requesting slightly larger pixel size to avoid roundoff errors
                                 filters=p.filters,
                                 data_release=p.data_release,
                                 rerun=p.rerun)

@registry.register_problem
class Img2imgHSCAnomaly(Img2imgHSC):
  """ Dataset for anomaly detection on HSC data.
  """

  def hparams(self, defaults, model_hparams):
    p = defaults
    p.img_len = 128
    p.filters = ['HSC-G', 'HSC-R', 'HSC-I']
    p.sql_file = os.path.join(_HSC_SAMPLE_SQL_DIR, 'hsc_pdr2_wide_anomaly.sql')
    p.data_release = 'pdr2'
    p.rerun = 'pdr2_wide'
    p.attributes = ['g_cmodel_mag', 'r_cmodel_mag', 'i_cmodel_mag', 'z_cmodel_mag']
    p.modality = {"inputs": modalities.ModalityType.IDENTITY,
                  "attributes":  modalities.ModalityType.IDENTITY,
                  "targets": modalities.ModalityType.IDENTITY}
    p.vocab_size = {"inputs": None,
                    "attributes": None,
                    "targets": None}

  def preprocess_example(self, example, unused_mode, unused_hparams):
    """ Luptonize the examples, so that we can use t2t models easily
    """
    p = self.get_hparams()
    image = example["inputs"]

    # Apply Luptonic Asinh stretch, and return uint8 rgb images
    def my_func(x):
      return make_lupton_rgb(x[...,2], x[...,1], x[...,0], Q=15, stretch=0.5, minimum=0)

    int_image = tf.py_func(my_func, [image], tf.uint8)
    int_image.set_shape(image.shape)
    image = common_layers.convert_rgb_to_symmetric_real(int_image)

    if hasattr(p, 'attributes'):
      example["attributes"] = tf.stack([example[k] for k in p.attributes])

    example["inputs"] = image
    example["targets"] = image
    return example

@registry.register_problem
class Img2imgHSCAnomalySmall(Img2imgHSCAnomaly):
  """ Dataset for anomaly detection on HSC data, but smaller.
  """

  def hparams(self, defaults, model_hparams):
    p = defaults
    p.img_len = 128
    p.filters = ['HSC-G', 'HSC-R', 'HSC-I']
    p.sql_file = os.path.join(_HSC_SAMPLE_SQL_DIR, 'hsc_pdr2_wide_anomaly_small.sql')
    p.data_release = 'pdr2'
    p.rerun = 'pdr2_wide'
    p.attributes = ['g_cmodel_mag', 'r_cmodel_mag', 'i_cmodel_mag', 'z_cmodel_mag']
    p.modality = {"inputs": modalities.ModalityType.IDENTITY,
                  "attributes":  modalities.ModalityType.IDENTITY,
                  "targets": modalities.ModalityType.IDENTITY}
    p.vocab_size = {"inputs": None,
                    "attributes": None,
                    "targets": None}

@registry.register_problem
class Img2photozHSC(Img2imgHSC):
  """ Dataset for photoz estimation on HSC data.
  """

  def hparams(self, defaults, model_hparams):
    p = defaults
    p.img_len = 64
    p.filters = ['HSC-G', 'HSC-R', 'HSC-I', 'HSC-Z', 'HSC-Y']
    p.sql_file = os.path.join(_HSC_SAMPLE_SQL_DIR, 'hsc_pdr2_wide_photoz.sql')
    p.data_release = 'pdr2'
    p.rerun = 'pdr2_wide'
    p.attributes = ['a_g', 'a_r', 'a_i', 'a_z', 'a_y',
                   'g_cmodel_mag', 'r_cmodel_mag', 'i_cmodel_mag', 'z_cmodel_mag',
                   'specz_redshift', 'specz_redshift_err']
    p.modality = {"inputs": modalities.ModalityType.IDENTITY,
                  "attributes":  modalities.ModalityType.IDENTITY,
                  "targets": modalities.ModalityType.IDENTITY}
    p.vocab_size = {"inputs": None,
                    "attributes": None,
                    "targets": None}

  def preprocess_example(self, example, unused_mode, unused_hparams):
    """ Luptonize the examples, so that we can use t2t models easily
    """
    p = self.get_hparams()
    image = example["inputs"]

    if hasattr(p, 'attributes'):
      example["attributes"] = tf.stack([example[k] for k in p.attributes])

    example["inputs"] = image
    example["targets"] = example['specz_redshift']
    return example


import numpy as np
import cv2
import time
from framecounter import FrameCounter

fcount = FrameCounter()

cv2.startWindowThread()
# cap = cv2.VideoCapture('walking.mp4')
cap = cv2.VideoCapture(0)

i = 0
while(True):
    i+=1
    ret, frame = cap.read()

    fcount.start()
    frame = cv2.resize(frame,(640,360))
    #frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
    # ret,frame = cv2.threshold(frame,80,255,cv2.THRESH_BINARY)

    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
       # breaking the loop if the user types q
       # note that the video window must be highlighted!
       break
    fcount.stop()

    if i%10==0:
        print(fcount)

cap.release()
# cv2.destroyAllWindows()
# the following is necessary on the mac,
# maybe not on other platforms:
# cv2.waitKey(1)


def run(model):
	import pandas as pd

	n_rows = None

	print("____ Loading Data")
	x_train = pd.read_csv('csv/traffic/x_train.csv', nrows=n_rows)
	x_test = pd.read_csv('csv/traffic/x_test.csv', nrows=n_rows)

	y_train = pd.read_csv('csv/traffic/y_train.csv', nrows=n_rows)
	y_test = pd.read_csv('csv/traffic/y_test.csv', nrows=n_rows)

	x_train_weather = pd.read_csv('csv/weather/x_train.csv', nrows=n_rows)
	x_test_weather = pd.read_csv('csv/weather/x_test.csv', nrows=n_rows)

	y_train_weather = pd.read_csv('csv/weather/y_train.csv', nrows=n_rows)
	y_test_weather = pd.read_csv('csv/weather/y_test.csv', nrows=n_rows)

	assert x_train.shape[0] == x_train_weather.shape[0]
	assert x_test.shape[0] == x_test_weather.shape[0]

	print("____ Training model")

	model.train_unsurpevised(x_train, x_train_weather, load=False)

	model.train_greed(x_train, x_train_weather, y_train, x_test, x_test_weather, y_test)

def cross(model):
	import pandas as pd
	from sklearn.model_selection import LeaveOneGroupOut
	n_rows = 120

	x_traffic = pd.read_csv('x_traffic.csv', nrows= n_rows)
	y_traffic = pd.read_csv('y_traffic.csv', nrows= n_rows)

	x_weather = pd.read_csv('x_weather.csv', nrows= n_rows)
	y_weather = pd.read_csv('y_weather.csv', nrows= n_rows)
	if n_rows:
		m = pd.read_csv('mounths_test.csv')
	else:
		m = pd.read_csv('mounths.csv')

	logo = LeaveOneGroupOut()
	metrics = []
	for train_index, x_test_index in logo.split(x_traffic , groups = m['m']):
		x_train, x_test = x_traffic.iloc[train_index], x_traffic.iloc[x_test_index]
		y_train, y_test = x_traffic.iloc[train_index], x_traffic.iloc[x_test_index]
		x_train_weather, x_test_weather = x_weather.iloc[train_index], x_weather.iloc[x_test_index]
		y_train_weather, y_test_weather = y_weather.iloc[train_index], y_weather.iloc[x_test_index]

		try:
			model.train_unsurpevised(x_train, x_train_weather, load=True)
		except:
			model.train_unsurpevised(x_train, x_train_weather, load=True)

		metrics = model.train_greed(x_train, x_train_weather, y_train, x_test, x_test_weather, y_test, metrics=metrics)

	metrics = pd.Dataframe(metrics)
	log_msg = 'Execution on {}: \n\n \
		Results: \n\n \
		Training set\n \
		MSE: {}({}) \n \
		MAE: {}({})\n \
		MAPE:{}({}) \n \
		R^2: {}({}) \n\n \
		Teste set\n \
		MSE: {}({})\n \
		MAE: {}({})\n \
		MAPE:{}({})\n \
		R^2: {}({}) \n\n ---------------- \n\n\n'.format(datetime.now().strftime("%Y-%m-%d_%H:%M"), metrics[0].mean(), metrics[0].std(), metrics[1].mean(), metrics[1].std(), metrics[2].mean(), metrics[2].std(), metrics[3].mean(), metrics[3].std(), metrics[4].mean(), metrics[4].std(), metrics[5].mean(), metrics[5].std(), metrics[6].mean(), metrics[6].std(), metrics[7].mean(), metrics[7].std())
	print(log_msg)
	with open('log_stat_{}.txt'.format('{}'.format(model.name)), 'a') as fid:
		fid.write(log_msg)


def factorial(number):

    if number == 1 or number == 0:
        return 1

    handle_odd = False
    goal = number

    if number % 2 == 1:
        goal -= 1
        handle_odd = True

    next_sum = goal
    next_multi = goal
    factorial = 1

    while next_sum >= 2:
        factorial *= next_multi
        next_sum -= 2
        next_multi += next_sum

    if handle_odd:
        factorial *= number

    return factorial

print(sum([int(x) for x in str(factorial(100))]))


from django.conf.urls.defaults import *
from django.contrib.auth.views import login, logout_then_login
from dpro.bilet.views import * #index, doldur, listele, csvdeneme, degistir,

urlpatterns = patterns(
    '',
    (r'^bilet/admin/',   include('django.contrib.admin.urls')),
    (r'^bilet/login/$',  login, {'template_name': 'login.html'}),
    (r'^bilet/logout/$', logout_then_login),
    (r'^bilet/index/$',  index),
    (r'^bilet/biletdoldur/([H, O, D])/(\d{1,})/$', doldur),
    (r'^bilet/biletlistele/(\d{1,})/$',    listele),
#    (r'^bilet/csvdeneme/$', csvdeneme),
    (r'^bilet/degistir/(\d{1,})/$', degistir),
    (r'^bilet/biletsil/(\d{1,})/$', sil),
    (r'^bilet/ara/$', ara),
)


import pickle
import shutil

import torch
import numpy as np
import unittest

from openfold.data.data_pipeline import DataPipeline
from openfold.data.templates import TemplateHitFeaturizer
from openfold.model.embedders import (
    InputEmbedder,
    RecyclingEmbedder,
    TemplateAngleEmbedder,
    TemplatePairEmbedder,
)
import tests.compare_utils as compare_utils

if compare_utils.alphafold_is_installed():
    alphafold = compare_utils.import_alphafold()
    import jax
    import haiku as hk

class TestDataPipeline(unittest.TestCase):
    @compare_utils.skip_unless_alphafold_installed()
    def test_fasta_compare(self):
        # AlphaFold runs the alignments and feature processing at the same
        # time, taking forever. As such, we precompute AlphaFold's features
        # using scripts/generate_alphafold_feature_dict.py and the default
        # databases.
        with open("tests/test_data/alphafold_feature_dict.pickle", "rb") as fp:
            alphafold_feature_dict = pickle.load(fp)

        template_featurizer = TemplateHitFeaturizer(
            mmcif_dir="tests/test_data/mmcifs",
            max_template_date="2021-12-20",
            max_hits=20,
            kalign_binary_path=shutil.which("kalign"),
            _zero_center_positions=False,
        )

        data_pipeline = DataPipeline(
            template_featurizer=template_featurizer,
        )

        openfold_feature_dict = data_pipeline.process_fasta(
            "tests/test_data/short.fasta",
            "tests/test_data/alignments"
        )

        openfold_feature_dict["template_all_atom_masks"] = openfold_feature_dict["template_all_atom_mask"]

        checked = []

        # AlphaFold and OpenFold process their MSAs in slightly different
        # orders, which we compensate for below.
        m_a = alphafold_feature_dict["msa"]
        m_o = openfold_feature_dict["msa"]

        # The first row of both MSAs should be the same, no matter what
        self.assertTrue(np.all(m_a[0, :] == m_o[0, :]))

        # Each row of each MSA should appear exactly once somewhere in its
        # counterpart
        matching_rows = np.all((m_a[:, None, ...] == m_o[None, :, ...]), axis=-1)
        self.assertTrue(
            np.all(
                np.sum(matching_rows, axis=-1) == 1
            )
        )

        checked.append("msa")

        # The corresponding rows of the deletion matrix should also be equal
        matching_idx = np.argmax(matching_rows, axis=-1)
        rearranged_o_dmi = openfold_feature_dict["deletion_matrix_int"]
        rearranged_o_dmi = rearranged_o_dmi[matching_idx, :]
        self.assertTrue(
            np.all(
                alphafold_feature_dict["deletion_matrix_int"] ==
                rearranged_o_dmi
            )
        )

        checked.append("deletion_matrix_int")

        # Remaining features have to be precisely equal
        for k, v in alphafold_feature_dict.items():
            self.assertTrue(
                k in checked or np.all(v == openfold_feature_dict[k])
            )

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


import random
import pytz
import json

from django.dispatch import receiver
from django.db.models.signals import pre_save

from django_celery_beat.models import CrontabSchedule, PeriodicTask
from .models import Agent

days = {
    "sun": 0,
    "mon": 1,
    "tue": 2,
    "wed": 3,
    "thu": 4,
    "fri": 5,
    "sat": 6,
}

@receiver(pre_save, sender=Agent)
def handle_schedules(sender, instance: Agent, **kwargs):
    """
        Triggers everytime a backup or offsite schedule is created or changed
        If schedule already exists, first deletes the associated periodic tasks
        then recreates based on new schedule
    """

    if instance.pk is not None:

        schedule = sender.objects.get(pk=instance.pk).backup_schedule

        if not schedule == instance.backup_schedule:
            # schedule has been changed

            tasks = PeriodicTask.objects.filter(
                name__startswith=f"{instance.hostname}-{instance.pk}-backup"
            )

            if tasks:
                tasks.delete()

            for day, times in instance.backup_schedule.items():
                day_of_week = days.get(day)
                hours = ",".join(str(x) for x in times)

                if hours:

                    schedule, _ = CrontabSchedule.objects.get_or_create(
                        minute=str(random.randint(0, 4)),
                        hour=hours,
                        day_of_week=day_of_week,
                        day_of_month="*",
                        month_of_year="*",
                        timezone=pytz.timezone("America/Los_Angeles"),
                    )

                    PeriodicTask.objects.create(
                        crontab=schedule,
                        name=f"{instance.hostname}-{instance.pk}-backup-day{day_of_week}",
                        task="core.tasks.incremental_backup_task",
                        enabled=instance.backups_enabled,
                        args=json.dumps([instance.pk]),
                    )

        tasks = PeriodicTask.objects.filter(
            name__startswith=f"{instance.hostname}-{instance.pk}-backup"
        )

        for task in tasks:
            task.enabled = instance.backups_enabled
            task.save(update_fields=["enabled"])


# 100. Same Tree

# https://leetcode.com/problems/same-tree/discuss/
# https://discuss.leetcode.com/topic/14561/shortest-simplest-python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if p and q:
            return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        return p is q  # True for both p and q are None

        # if p is None and q is None:
        #     return True
        # elif (not p and q) or (p and not q):
        #     return False

        # if not p.val == q.val:
        #     return False
        # return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)