"""
Data-loading classes.
"""
import h5py
import torch
import torch.utils.data as data
import threading as thread
import queue
import numpy as np
from random import randint, shuffle

# ===== ===== Queue-based Multiprocessing HDF5 Loader class ===== =====
from utils.worker_fns import ecoli_worker_fn, bucket_worker_fn
class QueueLoader(object):
    """
    The QueueLoader reads from an HDF5 file and uses multiple cpu-based worker processes
    to continuously push new (signal,sequence) batches onto the queue; the workers perform
    (sampling => one-hot encoding => padding) prior to pushing them onto the queue.

    A Queue object is exposed, but the individual worker threads are not exposed.

    Upon dequeuing, a tuple of batched sequences is either returned as-is (for CPU processing)
    or is dispatched to CUDA via `*.cuda()` during the dequeue operation; the tuple is
    of the form ().
    """
    def __init__(self, dataset_path, num_signal_levels=256, num_workers=1, queue_size=50, batch_size=8, sample_lengths=(90,110),
                 max_iters=100, epoch_size=1000, worker_fn='ecoli'):
        """
        Construct a QueueLoader.
        """
        # save settings:
        self.dataset_path = dataset_path
        self.num_signal_levels = num_signal_levels
        self.num_workers = num_workers
        self.queue_size = queue_size
        self.batch_size = batch_size
        self.sample_lengths = sample_lengths
        self.max_iters = max_iters
        self.epoch_size = epoch_size
        self.num_epochs = 0
        self._cuda = False

        # open HDF5 file:
        try:
            self.dataset = h5py.File(dataset_path, 'r')
        except:
            raise Exception("Could not open HDF5 file: {}".format(dataset_path))

        # list of top-level read names into train/validation set:
        self.reads = list(self.dataset.keys())
        valid_set_size = int(0.3 * len(self.reads)) # 30% of reads go to validation
        self.train_reads = self.reads[valid_set_size:]
        self.valid_reads = self.reads[0:valid_set_size]

        # construct queue, re-entrant lock, and data counter:
        self.train_queue = queue.Queue(queue_size)
        self.valid_queue = queue.Queue(queue_size)
        self.queue_lock = thread.Lock()
        self.global_counter = 0
        self.stop_event = thread.Event()

        # create worker function as a closure:
        assert (worker_fn in ['ecoli', 'buckets'])
        if worker_fn == 'buckets': raise Exception("ERR: bucketed dataset is currently unsupported.")
        def queue_worker(q, reads, stop_evt):
            while True:
                if stop_evt.is_set(): break
                if (self.global_counter > self.max_iters): break
                datavals = ecoli_worker_fn(self.dataset, reads, batch_size=batch_size, sample_lengths=sample_lengths)
                with self.queue_lock:
                    q.put( datavals )
                    self.incr_global_ctr()
        self.queue_worker = queue_worker

        # create workers:
        self.workers = []
        for k in range(num_workers):
            _train_worker = thread.Thread(target=self.queue_worker,
                                          args=(self.train_queue, self.train_reads, self.stop_event),
                                          daemon=True)
            _train_worker.start()
            self.workers.append(_train_worker)
        # only need one validation worker since we dequeue from it so rarely:
        _valid_worker = thread.Thread(target=self.queue_worker,
                                      args=(self.valid_queue, self.valid_reads, self.stop_event),
                                      daemon=True)
        _valid_worker.start()
        self.workers.append(_valid_worker)

    def incr_global_ctr(self):
        self.global_counter += 1
        if (self.global_counter % self.epoch_size == 0): self.num_epochs += 1

    def dequeue(self, from_queue="train"):
        """
        Dequeue a new data sequence tuple from the queue as a list of Variables.
        """
        assert (from_queue in ['train', 'valid'])
        if from_queue == "train":
            try:
                vals = self.train_queue.get(timeout=1)
            except:
                raise StopIteration
        if from_queue == "valid":
            try:
                vals = self.valid_queue.get(timeout=1)
            except:
                raise StopIteration
        if self._cuda:
            return [torch.autograd.Variable(val.cuda()) for val in vals]
        else:
            return [torch.autograd.Variable(val) for val in vals]

    def close(self):
        """
        Gracefully join all threads and close HDF5 file handle.
        """
        # join the processes, with timeout of 2 seconds:
        self.stop_event.set()
        [worker.join(timeout=2) for worker in self.workers]

        # finally close HDF5 dataset file:
        if self.dataset: self.dataset.close()

    def cuda(self):
        self._cuda = True

    def cpu(self):
        self._cuda = False

# ===== ===== Basic HDF5 Loader class ===== =====
class Loader(object):
    """
    Signal and base-sequence loader. Takes a list of datasets in the form of an HDF5 and swaps between them.

    At each call of fetch(), this loader does the following:
    1) randomly chooses a bucket;
    2) randomly chooses a pair of signals and sequences in that bucket and one-hots the signal;
    3) returns them.
    """
    def __init__(self, dataset_path, num_signal_levels=256, max_iters=100, num_epochs=1):
        """Open handle to HDF5 dataset file."""
        self.dataset_path = dataset_path
        self._dataset = h5py.File(dataset_path, 'r')
        self._closed = False
        self.num_epochs = num_epochs
        self.max_iters = max_iters
        self._load_metadata()
        self.counter = 0
        self.epochs = 0
        self.num_signal_levels = num_signal_levels
        self._cuda = False

    def cuda(self):
        self._cuda = True

    def close(self):
        """Close the dataset."""
        self._dataset.close()
        self._closed = True

    def is_closed(self):
        """True if closed, False if opened."""
        return self._closed

    def fetch(self, bucket=None, entry=None):
        """
        Fetch a random signal/sequence pair from the dataset.

        Performs the following steps:
        1) choose a random bucket if bucket == None (else if int, choose that bucket);
        2) choose a random (signal,sequence) pair if entry == None (else if int, choose that entry);
        3) convert to one-hot encoding;
        4) convert to torch tensor format:
             signal ~ torch.FloatTensor variable of shape (1, num_levels, len(signal))
             sequence ~ torch.LongTensor variable of shape (1, len(sequence))
        5) if self.cuda == True, then convert to CUDA variables; return pair of variables.
        """
        ### check if we've hit the maximum number of timesteps; if yes, raise StopIteration
        self._maybe_stop()

        ### choose a random bucket and a random entry:
        bucket_id = randint(0, self._num_buckets-1) if (bucket == None) else bucket
        data_id = randint(0, self._buckets_data[bucket_id]['dataset_size']-1) if (entry == None) else entry

        ### fetch signal, sequence:
        signal = self.one_hot_signal(
            torch.from_numpy(self._dataset['bucket_{}'.format(bucket_id)]['signals']['{}'.format(data_id)][:]).long(),
            num_levels=self.num_signal_levels)
        seq = torch.from_numpy(
            self._dataset['bucket_{}'.format(bucket_id)]['reads']['{}'.format(data_id)][:]).long().unsqueeze(0)

        ### update timestep
        self._tick()

        ### return CUDA or CPU:
        if not self._cuda: return (torch.autograd.Variable(signal), torch.autograd.Variable(seq))
        return (torch.autograd.Variable(signal.cuda()), torch.autograd.Variable(seq.cuda()))

    ### Static Helper Functions:
    @staticmethod
    def one_hot_signal(signal, num_levels):
        """
        One-hot-encode a signal.

        Args:
        * signal: a list of ndarrays; these are the signals themselves.

        Returns:
        A one-hot-encoded signal.
        """
        return torch.zeros(1, num_levels, signal.size(0)).scatter_(1, signal.unsqueeze(0).unsqueeze(0), 1.)

    ### Helper Methods:
    def _load_metadata(self):
        """Load metadata values as attributes."""
        self._num_buckets = self._dataset['meta'].attrs['num_buckets']
        self._bucket_size = self._dataset['meta'].attrs['bucket_size']
        self._signals_path = self._dataset['meta'].attrs['signals_path']
        self._reads_path = self._dataset['meta'].attrs['reads_path']
        self._lengths_tsv_path = self._dataset['meta'].attrs['lengths_tsv_path']
        self._buckets_data = {}
        for k in range(self._num_buckets):
            self._buckets_data[k] = {
                'dataset_size': self._dataset['bucket_{}'.format(k)].attrs['dataset_size'],
                'max_read_length': self._dataset['bucket_{}'.format(k)].attrs['max_read_length'],
                'min_read_length': self._dataset['bucket_{}'.format(k)].attrs['min_read_length'],
                'max_signal_length': self._dataset['bucket_{}'.format(k)].attrs['max_signal_length'],
                'min_signal_length': self._dataset['bucket_{}'.format(k)].attrs['min_signal_length'],
                # n.b.: you have to index these to load them into memory; this is a space-saving
                # technique by design
                'read_lengths': self._dataset['bucket_{}'.format(k)]['read_lengths'],
                'signal_lengths': self._dataset['bucket_{}'.format(k)]['signal_lengths'],
            }
        self._num_sequences = sum([self._buckets_data[k]['dataset_size'] for k in range(self._num_buckets)])

    def _tick(self):
        """Update counter and maybe update epoch"""
        self.counter += 1
        if (self.counter != 0 and self.counter % self._num_sequences == 0): self.epochs += 1

    def _maybe_stop(self):
        """Return True if we are done; return False otherwise"""
        if self.epochs == self.num_epochs or self.counter == self.max_iters:
            raise StopIteration


# We want to create a singly LinkedList class
# We want our LInkedList class to have one method called `add`
# The add method takes one parameter called `value`. The value is always appended to the end of the LinkedList
# We do not care the type of value, anything can be added
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def add(self, value):
        if self.head is None:
            # Case1: LL is empty
            self.head = Node(value)
            self.tail = self.head
        else:
            # Case2: LL is not empty
            self.tail.next = Node(value)
            self.tail = self.tail.next

    def print(self):
        node = self.head
        while node:
            print(node.value)
            node = node.next

linked_list = LinkedList()
linked_list.add(1)
linked_list.add(2)
linked_list.add(3)
linked_list.add(4)

linked_list.print()


"""
Quiz game
- Reading from a file
- JSON library
"""
import json
import random

print("Welcome to the quiz game!\n")

with open("questions.json") as json_file:
    questions = json.load(json_file)

score = 0

while len(questions) != 0:
    question = random.choice(list(questions.keys()))
    answer = input(f"\n{question} ")
    if answer == questions[question]:
        score += 1
    del questions[question]

print(f"\nYour score is: {score}!")


mounth = 0
invest = 333
brutto = 3891
netto = brutto*0.8
suma = 0
bbjon=0
p = 1.08

while mounth < 12:
    suma *= p
    suma += invest
    bbjon+= netto-invest
    mounth +=1
    print((suma)//1,mounth)
print((suma+bbjon)//1)


from turtle import *
from wdi import *
from duze_cyfry import *
from random import *

#Nasza tablica ma 5x5

BOK = 10
tracer(0,1)
SX = 0
SY = 0

def kwadrat(x, y, kolor):
  fillcolor(kolor)
  pu()
  goto(SX + x * BOK, SY + y * BOK)

  begin_fill()
  for i in range(4):
    fd(BOK)
    rt(90)
  end_fill()
  pd()

def Cyferka(N):
  Cyfry[N] = list(map(list, Cyfry[N]))
  rysuj(Cyfry[N])

M1=5
M2=5
T= Array(M1,M2)

#for i in range(M1):
 # for j in range(M2):
  #  printf("T[%d][%d] == %d\n", i, j, T[i][j])

def rysuj(T):
  kolorek=(random(),random(),random())
  for y in range(len(T)):
    for x in range(len(T[y])):
      if T[y][x] == '#':
        kolor = kolorek
      else:
        kolor = 'white'
      kwadrat(x, y, kolor)
  update()
def rysowanie_liczby(liczba):
  global SX
  liczba=list(str(liczba))
  for element in liczba:
    x=element
    if element == '-':
      x=int(10)
    Cyferka(int(x))
    SX=SX+BOK*6
  SX=0


import os
import sys
import urllib.request

# PREWORK (don't modify): import colors, save to temp file and import
tmp = os.getenv("TMP", "/tmp")
color_values_module = os.path.join(tmp, 'color_values.py')
urllib.request.urlretrieve(
    'https://bites-data.s3.us-east-2.amazonaws.com/color_values.py',
    color_values_module
)
sys.path.append(tmp)

# should be importable now
from color_values import COLOR_NAMES  # noqa E402

class Color:
    """Color class.

    Takes the string of a color name and returns its RGB value.
    """
    def __init__(self, color):
        self.color = color
        self.rgb = COLOR_NAMES.get(color.upper(), None)

    @staticmethod
    def hex2rgb(hex_):
        """Class method that converts a hex value into an rgb one"""
        if not hex_.startswith('#') or len(hex_) < 7:
            raise ValueError
        rgb = (hex_[1:3], hex_[3:5], hex_[5:7])
        return tuple(int(x, 16) for x in rgb)

    @staticmethod
    def rgb2hex(rgb):
        """Class method that converts an rgb value into a hex one"""
        if any(x for x in rgb if x not in range(0, 256)):
            raise ValueError
        return f'#{"".join(hex(x).split("x")[1].rjust(2, "0") for x in rgb)}'

    def __repr__(self):
        """Returns the repl of the object"""
        return f"{self.__class__.__name__}('{self.color}')"

    def __str__(self):
        """Returns the string value of the color object"""
        return f'{self.rgb}' if self.rgb else 'Unknown'


'''
Q] You are given a list of tuples with each tuple having three elements of the format (a,b,c) where a,b and c are positive integers.
Create a lambda function that takes three arguments a, b and c and returns the output (a+b)2 +c.
Use this lambda function on the list of tuples with the Python built in map function to generate a new list of answers of lambda expression.
'''

# Program :

# To take input from the user
values = input("Input three comma seprated numbers : ")
list1 = values.split(",")
tuple1 = tuple(list1)
print('Tuple : ',tuple1)

a = int(tuple1[0])
b = int(tuple1[1])
c = int(tuple1[2])

# Lambda Function
lf = lambda a,b,c : (((a+b)*2)+c)
print("Answer :" ,lf(a, b, c))


# coding=utf-8
__author__ = 'Nuno Gouveia'

from string_functions import *

def posDecimal(v):
    try:
        i=v.index(".")
    except ValueError:
        i=-1
    return i

def fUnidades(valor,currency=False):
    digitos = {'0':'ZERO','1':'UM',
               '2':'DOIS','3':'TRÊS',
               '4':'QUATRO','5':'CINCO',
               '6':'SEIS','7':'SETE',
               '8':'OITO','9':'NOVE'}

    retorno =""

    if ( currency == True ):
        num = int(valor)
        if num == 0:
            retorno = ""
        else:
            retorno = digitos.get(valor)
    else:
        retorno = digitos.get(valor)

    return retorno

def fDezenas(valor,currency=False):
    dict1 = {'10':'DEZ','11':'ONZE','12':'DOZE','13':'TREZE','14':'QUATORZE','15':'QUINZE',
             '16':'DEZASSEIS','17':'DEZASSETE','18':'DEZOITO','19':'DEZANOVE'}
    dict2 = {'2':'VINTE','3':'TRINTA',
             '4':'QUARENTA','5':'CINQUENTA',
             '6':'SESSENTA','7':'SETENTA',
             '8':'OITENTA','9':'NOVENTA'}

    result = ""
    done = False
    # Se o valor estiver entre 10 e 19
    num = int(valor[0])
    if  num == 1:
        result = dict1.get(valor)
        done = True
    else: # Se o valor estiver entre 20 e 99
        result = dict2.get(valor[0])

    if (done == False ):
        num = int(valor[1])
        if  num != 0  :
            result = result + " E " + fUnidades(valor[1], currency)
        else:
            result = result + fUnidades(valor[1], currency)

    return result

def fCentenas(valor,currency = False):
    dict1 = { '1':'CEM','10':'CENTO'}
    dict2 = { '2':'DUZENTOS',
              '3':'TREZENTOS','4':'QUATROCENTOS',
              '5':'QUINHENTOS','6':'SEISCENTOS',
              '7':'SETECENTOS','8':'OITOCENTOS','9':'NOVECENTOS'
              }

    result = ""

    num = int(valor)
    v = str(num)

    if len(v) < 3:
        num = 0
        try:
            num = int(v)
        except ValueError:
            pass
        if num < 10:
           result = fUnidades(v,currency)
        else:
            result = fDezenas(v,currency)
    else:
        num = int(v)
        if num == 100:
            result = dict1.get(v[0])
        else:
            num1 = int(v[0:2])
            num2 = int(v[2])
            if  num1 == 10 and  num2 > 0:
                result = dict1.get(v[0:2]) + " E " + fUnidades(v[2], currency)
            else:
                num1 = int(v[1])
                num2 = int(v[2])
                if int(v[1]) >= 1  and int(v[2]) >= 0:
                    result = dict1.get('10') + " E " + fDezenas(v[1:3], currency)

        num = int(v)
        if  num >= 200:
            result = dict2.get(v[0])
            num1 = int(v[1])
            num2 = int(v[2])
            if num1 > 0:
                result = dict2.get(v[0]) + " E " + fDezenas(v[1:3], currency)
            elif num1 == 0 and  num2 > 0:
                result = dict2.get(v[0]) + " E " + fUnidades(v[1:3], currency)

    return result

def ConvertCurrencyToPortuguese(valor,currency=False):
    singular = [" "," MIL ", " MILHÃO ", " BILIÃO "]
    plural   = [" "," MIL ", " MILHÕES ", " BILIÕES "]
    centimos = ""
    euros = ""
    cents = ""
    tmp = ""
    extenso = ""

    if currency:
        euros = " EUROS "
        cents = " CÊNTIMOS"
    else:
        cents = " CENTÉSIMAS"

    v = valor

    # Verificar se Existe Decimais
    pos = posDecimal(v)
    if (pos != -1):
        tmp = v[pos+1:len(v)]
        num = int(tmp)
        if( num >= 10 ):
            centimos = fDezenas(tmp,currency)
        else:
            centimos = fUnidades(tmp,currency)
        # retira ao valor o valor decimal
        v = mid(v,0,pos)

    # Prosseguir com o restante
    pos = len(v)-3

    if pos < 0:
        pos = 0
    count = 0
    tmp = ""
    while (len(v) != 0):
        tmp = mid(v,pos,3)
        num = int(tmp)
        tmp = fCentenas(tmp,currency)

        if trim(extenso) == "ZERO":
            extenso = ""

        if num == 1 and count == 1:
            tmp = singular[count]

        if num == 1 and count > 1:
            tmp = tmp + singular[count]

        if num > 1 and count == 1:
            tmp = tmp + singular[count]

        if num > 1 and count > 1:
            tmp = tmp + plural[count]

        extenso = trim(extenso)
        if len(extenso) != 0:
            extenso = trim(tmp) + " E " + extenso
        else:
            extenso = extenso + trim(tmp)

        v = v[0:pos]
        pos = len(v)-3
        if (pos < 0):
            pos = 0
        elif (pos == 0):
            pos = 0
        count += 1

    if currency:
        if len(centimos) != 0:
            extenso = extenso + euros + " E " + centimos + cents
        else:
            extenso = extenso + euros
    else:
        if len(centimos) != 0:
            extenso = extenso + " E " + centimos + cents

    extenso = extenso
    return extenso

numeros = ['0','1','9','10','14','99','100','101','357','1000','1001','1034','1589','125967','10000']
for i in range(0,len(numeros)):
    print("Numero "+ numeros[i]+ "->" + ConvertCurrencyToPortuguese(numeros[i],False))


"""Disable work start date action handler"""

from datetime import timedelta

from api.actions.base import ActionFactory
from api.models import db
from api.models.event import Event

from .common import find_configuration, find_event_date

class SetEventDate(ActionFactory):  # pylint: disable=too-few-public-methods
    """Sets the event date"""

    def run(self, source_event: Event, params: dict) -> None:
        """Performs the required operations"""
        from api.services.event import EventService  # pylint: disable=import-outside-toplevel

        number_of_days_to_be_added = params.get("start_at")
        event_configuration = find_configuration(source_event, params)
        event = (
            db.session.query(Event)
            .filter(
                Event.work_id == source_event.work_id,
                Event.is_active.is_(True),
                Event.event_configuration_id == event_configuration.id,
            )
            .first()
        )
        event_dict = event.as_dict(recursive=False)
        event_dict["anticipated_date"] = find_event_date(source_event) + timedelta(
            days=number_of_days_to_be_added
        )
        EventService.update_event(event_dict, event.id, True, commit=False)


from utils.utils import *

def visualize_filter_effect_over_iter(saliency_by_groundtruth_vs_iter,path_to_save_folder,
	verbose=0, tab_level=0):
	pm.printvm('visualize_filter_effect_over_iter()', tab_level=tab_level)
	print_saliency_by_groundtruth_vs_iter_data(saliency_by_groundtruth_vs_iter, verbose=0, tab_level=tab_level)

	N_ROW_PER_IMG = 7
	VIEWING_FACTOR = 100.

	for this_iter, this_dict in saliency_by_groundtruth_vs_iter.items():
		for y0, list_of_lrp_filtered_saliency_package in this_dict.items():
			folder_by_y0 = os.path.join(path_to_save_folder, str(y0))
			if not os.path.exists(folder_by_y0):
				os.mkdir(folder_by_y0)

			# for i, lrp_filtered_saliency_package in enumerate(list_of_lrp_filtered_saliency_package):
			n = len(list_of_lrp_filtered_saliency_package)
			n_partition = int(np.ceil(n/N_ROW_PER_IMG))

			for k_th_partition in range(n_partition):
				list_subset_of_lrp_filtered_saliency_package = None
				if k_th_partition+1<n_partition:
					list_subset_of_lrp_filtered_saliency_package = list_of_lrp_filtered_saliency_package[k_th_partition*N_ROW_PER_IMG:(k_th_partition+1)*N_ROW_PER_IMG]
				else:
					list_subset_of_lrp_filtered_saliency_package = list_of_lrp_filtered_saliency_package[k_th_partition*N_ROW_PER_IMG:]

				# one_img, ordered_names, one_col, one_col_pred = prepare_data_for_one_image(k_th_partition, list_subset_of_lrp_filtered_saliency_package)
				# save_images_by_parts(folder_by_y0 , this_iter, y0, k_th_partition, one_img, ordered_names, suffix='', isimg=False)
				one_img_normalized, ordered_names, one_col, one_col_pred, one_col_rep = prepare_data_for_one_image(k_th_partition, list_subset_of_lrp_filtered_saliency_package, normalize=True)
				# save_images_by_parts(folder_by_y0 , this_iter, y0, k_th_partition, one_col, one_col_pred, suffix='_x', isimg=True)
				save_images_by_parts(folder_by_y0 , this_iter, y0, k_th_partition, one_img_normalized, one_col, one_col_pred, one_col_rep, ordered_names, suffix='_norm', isimg=False, VIEWING_FACTOR = VIEWING_FACTOR )

def save_images_by_parts(folder_by_y0, this_iter, y0, k_th_partition, one_img, one_col, one_col_pred, one_col_rep, ordered_names, suffix='', isimg=True, VIEWING_FACTOR = 1.):

	number = 10000000 + this_iter
	filename = str(y0) + '_iter' + str(number)[1:]  +  '_part_' +str(k_th_partition)
	filename = os.path.join(folder_by_y0, filename)
	# print(filename)

	one_img, cmap, this_title = img_subprocessing(one_img, ordered_names, isimg=False)
	one_col_rep, _, _ = img_subprocessing(one_col_rep, ordered_names, isimg=True)
	one_img_x, cmap_x, this_title_x = img_subprocessing(one_col, [int(x) for x in one_col_pred], isimg=True)

	fig = plt.figure()

	absv = np.abs(np.max(np.abs(one_img.reshape(-1))))
	ax = plt.subplot(121)
	im1 = ax.imshow(one_img, cmap=cmap)
	im1.set_clim(vmin=-absv/VIEWING_FACTOR, vmax=absv/VIEWING_FACTOR)

	if len(one_col_rep.shape) == 3:
		ax.imshow(np.dot(one_col_rep, [0.299, 0.587, 0.114]), alpha=0.5, cmap='gray')
	elif len(one_col_rep.shape) == 2:
		ax.imshow((one_col_rep), alpha=0.5, cmap='gray')
	else:
		print('save_images_by_parts(). SKIPPING!')
		return
	ax.set_xticklabels([])
	ax.set_yticklabels([])
	ax.set_title(this_title)
	set_size(9,9)
	plt.axis('off')
	plt.tight_layout()

	absv_x = np.abs(np.max(np.abs(one_col.reshape(-1))))
	ax2 = plt.subplot(122)
	im2 = ax2.imshow(one_img_x, cmap=cmap_x)
	im2.set_clim(vmin=-absv_x, vmax=absv_x)
	ax2.set_xticklabels([])
	ax2.set_yticklabels([])
	ax2.set_title(this_title_x)
	set_size(9,5)

	plt.axis('off')
	plt.tight_layout()
	# plt.colorbar(im1,ax=ax)
	plt.savefig(filename + suffix +'_vf'+str(VIEWING_FACTOR) + '.jpg')
	plt.close()

def img_subprocessing(one_img, ordered_names, isimg=True):
	if isimg:
		# is_img
		cmap = None
		one_img = normalize_numpy_array(one_img,target_min=1e-6,target_max=1.)
		one_img = one_img.transpose(1,2,0)
		s = one_img.shape
		if s[2] == 1:
			cmap = 'bwr'
			one_img = one_img[:,:,0]

	else:
		cmap = 'bwr'
		for c, img_one_channel in enumerate(one_img):
			if c==0:
				temp_img = one_img[0]*0
				temp_img += img_one_channel
			else:
				temp_img += img_one_channel
		one_img = temp_img /len(one_img)

	this_title = '%s'%(str(ordered_names),)
	return one_img, cmap, this_title

def set_size(w,h, ax=None):
    """ w, h: width, height in inches """
    if not ax: ax=plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w)/(r-l)
    figh = float(h)/(t-b)
    ax.figure.set_size_inches(figw, figh)

def prepare_data_for_one_image(k_th_partition, list_subset_of_lrp_filtered_saliency_package, normalize=False):
	one_img= []
	ordered_names = []
	one_col, one_col_pred, one_col_rep = [], [], []
	for i, lrp_filtered_saliency_package in enumerate(list_subset_of_lrp_filtered_saliency_package):
		one_row= []
		for filter_type, filtered_img in lrp_filtered_saliency_package.items():
			if filter_type == 'main':
				x,y0,y1 = filtered_img
				# print(x.shape,y0,y1)
				one_col.append(x)

				one_row_x = []
				for j in range(len(lrp_filtered_saliency_package)-1):
					one_row_x.append(x)
				one_row_x = np.concatenate(one_row_x, axis=2)
				one_col_rep.append(one_row_x)
				one_col_pred.append(y0==y1)
			else:
				if normalize:
					one_row.append(filtered_img/np.abs(np.max(np.abs(filtered_img.reshape(-1)))))
				else:
					one_row.append(filtered_img)
				if i==0:
					ordered_names.append(filter_type)
		one_row = np.concatenate(one_row, axis=2)
		one_img.append(one_row)
	one_img = np.concatenate(one_img, axis=1)
	one_col = np.concatenate(one_col, axis=1)
	one_col_rep = np.concatenate(one_col_rep, axis=1)
	# print(one_col_pred)
	# print(one_col_rep.shape)
	return one_img, ordered_names, one_col, one_col_pred, one_col_rep

def print_saliency_by_groundtruth_vs_iter_data(saliency_by_groundtruth_vs_iter, verbose=0, tab_level=0):
	pm.printvm('print_saliency_by_groundtruth_vs_iter_data()', tab_level=tab_level)

	temp_iter = None
	temp_y0 = None
	for this_iter, this_dict in saliency_by_groundtruth_vs_iter.items():
		pm.printvm(' %8s | %s '%(str(this_iter),str(type(this_dict))), tab_level=tab_level+1, verbose=verbose, verbose_threshold=250)
		if temp_iter is None: temp_iter = this_iter
		for y0, list_of_lrp_filtered_saliency_package in this_dict.items():
			pm.printvm(' %8s | %4s | %s x lrp_filtered_saliency_package '%(str(''),str(y0), str(len(list_of_lrp_filtered_saliency_package))), tab_level=tab_level+1, verbose=verbose, verbose_threshold=250)
			if temp_y0 is None :temp_y0 = y0
		break
	list_of_lrp_filtered_saliency_package = saliency_by_groundtruth_vs_iter[temp_iter][temp_y0]
	a_lrp_filtered_saliency_package = list_of_lrp_filtered_saliency_package[0]

	pm.printvm('a_lrp_filtered_saliency_package:', tab_level=tab_level+1, verbose=verbose, verbose_threshold=250)
	for xkey, this_R in a_lrp_filtered_saliency_package.items():
		if xkey == 'main':
			pm.printvm(' %-20s | %s '%(str(xkey),str(type(this_R))), tab_level=tab_level+2, verbose=verbose, verbose_threshold=250)
		else:
			pm.printvm(' %-20s | %s '%(str(xkey),str(this_R.shape)), tab_level=tab_level+2, verbose=verbose, verbose_threshold=250)
		"""
		a_lrp_filtered_saliency_package:
		   R                    | (1, 28, 28)
		   clamp_(0.0,0.9)      | (1, 28, 28)
		   clamp_(0.0,0.6)      | (1, 28, 28)
		   clamp_(0.0,0.3)      | (1, 28, 28)
		   amp_1.2              | (1, 28, 28)
		   amp_1.5              | (1, 28, 28)
		   amp_2.0              | (1, 28, 28)
		"""


import random
import time

def getFrankNumbers():
    #list so I can add up hotdogs eaten
    hotDogsEaten = [0, 0, 0]
    while hotDogsEaten[0] < 50 and hotDogsEaten[1] < 50 and hotDogsEaten[2] < 50:
        #makes random ints to add up
        tomDogs = random.randrange(1, 6)
        sallyDogs = random.randrange(1, 6)
        fredDogs = random.randrange(1, 6)
        #adds up hotdogs eaten each turn
        hotDogsEaten[0] = hotDogsEaten[0] + tomDogs
        hotDogsEaten[1] = hotDogsEaten[1] + sallyDogs
        hotDogsEaten[2] = hotDogsEaten[2] + fredDogs
        print('Tom has eaten %s franks.' % hotDogsEaten[0])
        print('Sally has eaten %s franks.' % hotDogsEaten[1])
        print('Fred has eaten %s franks.' % hotDogsEaten[2])
        print('\nChomp chomp chompity\n')
        time.sleep(1)
    #compares the index of hotdogs eaten to find the max
    #so I can return it to another function that decides the winner
    global winner
    winner = hotDogsEaten.index(max(hotDogsEaten))
    if winner == 0:
        winner = 'Tom'
    elif winner == 1:
        winner = 'Sally'
    elif winner == 2:
        winner = 'Fred'

def getWinner():
    print('Who do you think will be the first to eat 50 franks?!? (Tom, Sally, Fred)'),
    userGuess = raw_input()
    print('\nRead...Set...Go!')
    print
    getFrankNumbers()
    if userGuess == winner:
        print('Congrats, you guessed correctly!\n')
    else:
        print('Perhaps hot dog betting is not your thing.\n')

def main():
    while True:
        getWinner()
        print('Would you like to play again (Type anything to continue, or type "No")'),
        keepPlaying = raw_input()
        print
        if keepPlaying == 'No'or keepPlaying == 'NO' or keepPlaying == 'no':
            break
#I spent a decent amount of time on this...
#God knows if I did this right
main()


from builtins import zip
import matplotlib
matplotlib.use("Agg")
import numpy as np
import unittest
import lsst.sims.maf.metrics as metrics
import lsst.utils.tests

class TestSimpleMetrics(unittest.TestCase):

    def setUp(self):
        dv = np.arange(0, 10, .5)
        dv2 = np.arange(-10, 10.25, .5)
        self.dv = np.array(list(zip(dv)), dtype=[('testdata', 'float')])
        self.dv2 = np.array(list(zip(dv2)), dtype=[('testdata', 'float')])

    def testMaxMetric(self):
        """Test max metric."""
        testmetric = metrics.MaxMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), self.dv['testdata'].max())

    def testMinMetric(self):
        """Test min metric."""
        testmetric = metrics.MinMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), self.dv['testdata'].min())

    def testMeanMetric(self):
        """Test mean metric."""
        testmetric = metrics.MeanMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), self.dv['testdata'].mean())

    def testMedianMetric(self):
        """Test median metric."""
        testmetric = metrics.MedianMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), np.median(self.dv['testdata']))

    def testAbsMedianMetric(self):
        testmetric = metrics.AbsMedianMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), np.abs(np.median(self.dv['testdata'])))

    def testFullRangeMetric(self):
        """Test full range metric."""
        testmetric = metrics.FullRangeMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), self.dv['testdata'].max()-self.dv['testdata'].min())

    def testCoaddm5Metric(self):
        """Test coaddm5 metric."""
        testmetric = metrics.Coaddm5Metric(m5Col='testdata')
        self.assertEqual(testmetric.run(self.dv), 1.25 * np.log10(np.sum(10.**(.8*self.dv['testdata']))))

    def testRmsMetric(self):
        """Test rms metric."""
        testmetric = metrics.RmsMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), np.std(self.dv['testdata']))

    def testSumMetric(self):
        """Test Sum metric."""
        testmetric = metrics.SumMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), self.dv['testdata'].sum())

    def testCountUniqueMetric(self):
        """Test CountUniqueMetric"""
        testmetric = metrics.CountUniqueMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), np.size(np.unique(self.dv['testdata'])))
        d2 = self.dv.copy()
        d2['testdata'][1] = d2['testdata'][0]
        self.assertEqual(testmetric.run(d2), np.size(np.unique(d2)))

    def testCountMetric(self):
        """Test count metric."""
        testmetric = metrics.CountMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), np.size(self.dv['testdata']))

    def testCountRatioMetric(self):
        """Test countratio metric."""
        testmetric = metrics.CountRatioMetric('testdata', normVal=2.)
        self.assertEqual(testmetric.run(self.dv), np.size(self.dv['testdata'])/2.0)

    def testCountSubsetMetric(self):
        """Test countsubset metric."""
        testmetric = metrics.CountSubsetMetric('testdata', subset=0)
        self.assertEqual(testmetric.run(self.dv), 1)

    def testMaxPercentMetric(self):
        testmetric = metrics.MaxPercentMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), 1.0/len(self.dv)*100.0)
        self.assertEqual(testmetric.run(self.dv2), 1.0/len(self.dv2)*100.0)

    def testAbsMaxPercentMetric(self):
        testmetric = metrics.AbsMaxPercentMetric('testdata')
        self.assertEqual(testmetric.run(self.dv), 1./len(self.dv)*100.)
        self.assertEqual(testmetric.run(self.dv2), 2./len(self.dv2)*100.)

    def testRobustRmsMetric(self):
        """Test Robust RMS metric."""
        testmetric = metrics.RobustRmsMetric('testdata')
        rms_approx = (np.percentile(self.dv['testdata'], 75) - np.percentile(self.dv['testdata'], 25)) / 1.349
        self.assertEqual(testmetric.run(self.dv), rms_approx)

    def testFracAboveMetric(self):
        cutoff = 5.1
        testmetric = metrics.FracAboveMetric('testdata', cutoff=cutoff)
        self.assertEqual(testmetric.run(self.dv),
                         np.size(np.where(self.dv['testdata'] >= cutoff)[0])/float(np.size(self.dv)))
        testmetric = metrics.FracAboveMetric('testdata', cutoff=cutoff, scale=2)
        self.assertEqual(testmetric.run(self.dv),
                         2.0*np.size(np.where(self.dv['testdata'] >= cutoff)[0])/float(np.size(self.dv)))

    def testFracBelowMetric(self):
        cutoff = 5.1
        testmetric = metrics.FracBelowMetric('testdata', cutoff=cutoff)
        self.assertEqual(testmetric.run(self.dv),
                         np.size(np.where(self.dv['testdata'] <= cutoff)[0])/float(np.size(self.dv)))
        testmetric = metrics.FracBelowMetric('testdata', cutoff=cutoff, scale=2)
        self.assertEqual(testmetric.run(self.dv),
                         2.0*np.size(np.where(self.dv['testdata'] <= cutoff)[0])/float(np.size(self.dv)))

    def testNoutliersNsigma(self):
        data = self.dv
        testmetric = metrics.NoutliersNsigmaMetric('testdata', nSigma=1.)
        med = np.mean(data['testdata'])
        shouldBe = np.size(np.where(data['testdata'] > med + data['testdata'].std())[0])
        self.assertEqual(shouldBe, testmetric.run(data))
        testmetric = metrics.NoutliersNsigmaMetric('testdata', nSigma=-1.)
        shouldBe = np.size(np.where(data['testdata'] < med - data['testdata'].std())[0])
        self.assertEqual(shouldBe, testmetric.run(data))

    def testMeanAngleMetric(self):
        """Test mean angle metric."""
        rng = np.random.RandomState(6573)
        dv1 = np.arange(0, 32, 2.5)
        dv2 = (dv1 - 20.0) % 360.
        dv1 = np.array(list(zip(dv1)), dtype=[('testdata', 'float')])
        dv2 = np.array(list(zip(dv2)), dtype=[('testdata', 'float')])
        testmetric = metrics.MeanAngleMetric('testdata')
        result1 = testmetric.run(dv1)
        result2 = testmetric.run(dv2)
        self.assertAlmostEqual(result1, (result2+20)%360.)
        dv = rng.rand(10000)*360.0
        dv = dv
        dv = np.array(list(zip(dv)), dtype=[('testdata', 'float')])
        result = testmetric.run(dv)
        result = result
        self.assertAlmostEqual(result, 180)

    def testFullRangeAngleMetric(self):
        """Test full range angle metric."""
        rng = np.random.RandomState(5422)
        dv1 = np.arange(0, 32, 2.5)
        dv2 = (dv1 - 20.0) % 360.
        dv1 = np.array(list(zip(dv1)), dtype=[('testdata', 'float')])
        dv2 = np.array(list(zip(dv2)), dtype=[('testdata', 'float')])
        testmetric = metrics.FullRangeAngleMetric('testdata')
        result1 = testmetric.run(dv1)
        result2 = testmetric.run(dv2)
        self.assertAlmostEqual(result1, result2)
        dv = np.arange(0, 358, 5)
        dv = np.array(list(zip(dv)), dtype=[('testdata', 'float')])
        result = testmetric.run(dv)
        self.assertAlmostEqual(result, 355)
        dv = rng.rand(10000)*360.0
        dv = np.array(list(zip(dv)), dtype=[('testdata', 'float')])
        result = testmetric.run(dv)
        result = result
        self.assertGreater(result, 355)

class TestMemory(lsst.utils.tests.MemoryTestCase):
    pass

def setup_module(module):
    lsst.utils.tests.init()

if __name__ == "__main__":
    lsst.utils.tests.init()
    unittest.main()


import tensorflow as tf
import numpy as np
from tensorflow.python.ops.rnn_cell import LSTMCell
from tensorflow.python.ops.rnn import bidirectional_dynamic_rnn

def self_attention(inputs, name, return_alphas=False):
    shared = False
    # max_len = inputs.shape[1].value
    hidden_size = inputs.shape[2].value  # D value - hidden size of the RNN layer
    if shared:
        scope_name = 'self_attn'
    else:
        scope_name = 'self_attn' + name
    with tf.variable_scope(scope_name):
        den = True
        if den:
            x_proj = tf.layers.Dense(hidden_size)(inputs)
            x_proj = tf.nn.tanh(x_proj)
        else:
            x_proj = inputs
        u_w = tf.Variable(tf.random_normal([hidden_size, 1], stddev=0.01, seed=1227))
        # x_proj = tf.reshape(x_proj, shape=[-1, hidden_size])
        # x = tf.reshape(tf.matmul(x_proj, u_w), shape=[-1, max_len, 1])
        x = tf.tensordot(x_proj, u_w, axes=1)
        alphas = tf.nn.softmax(x, axis=-1)
        output = tf.matmul(tf.transpose(inputs, [0, 2, 1]), alphas)
        output = tf.squeeze(output, -1)
        if not return_alphas:
            return output
        else:
            return output, alphas

def ffn_layer(inputs, hidden_units, output_units, use_bias=True, bias_init=0., activation=tf.nn.tanh,
              scope="ffn_layer"):
    with tf.variable_scope(scope):
        dim = inputs.get_shape().as_list()[-1]
        # hidden layer
        hidden_weight = tf.get_variable(name="hidden_weight", shape=[dim, hidden_units], dtype=tf.float32)
        hidden_output = tf.matmul(inputs, hidden_weight)
        if use_bias:
            hidden_bias = tf.get_variable(name="hidden_bias", shape=[hidden_units], dtype=tf.float32,
                                          initializer=tf.constant_initializer(bias_init))
            hidden_output = tf.nn.bias_add(hidden_output, hidden_bias)
        hidden_output = activation(hidden_output)
        # output layer
        weight = tf.get_variable(name="weight", shape=[hidden_units, output_units], dtype=tf.float32)
        output = tf.matmul(hidden_output, weight)
        if use_bias:
            bias = tf.get_variable(name="bias", shape=[output_units], dtype=tf.float32,
                                   initializer=tf.constant_initializer(bias_init))
            output = tf.nn.bias_add(output, bias)
        output = activation(output)
        return output

class Model:
    def __init__(self, cfg, vocab_counts):
        # add data placeholders
        self.left_context = tf.placeholder(name="left_context", shape=[None, None], dtype=tf.int32)
        self.left_seq_len = tf.placeholder(name="left_seq_len", shape=[None], dtype=tf.int32)
        self.right_context = tf.placeholder(name="right_context", shape=[None, None], dtype=tf.int32)
        self.right_seq_len = tf.placeholder(name="right_seq_len", shape=[None], dtype=tf.int32)
        self.verb = tf.placeholder(name="verb", shape=[None], dtype=tf.int32)

        # add hyper-parameter placeholders
        self.batch_size = tf.placeholder(name="batch_size", dtype=tf.int32)
        self.is_train = tf.placeholder(name="is_train", shape=[], dtype=tf.bool)
        self.drop_rate = tf.placeholder(name="dropout_rate", dtype=tf.float32)
        self.lr = tf.placeholder(name="learning_rate", dtype=tf.float32)

        # build embedding lookup table
        with tf.device("/gpu:0"):
            with tf.variable_scope("context_lookup_table"):
                self.word_embeddings = tf.Variable(np.load(cfg.pretrained_context)["embeddings"],
                                                   name="word_embeddings",
                                                   dtype=tf.float32,
                                                   trainable=cfg.tune_emb)
                self.word_embeddings = tf.concat([tf.zeros([1, cfg.word_dim]), self.word_embeddings[1:, :]], axis=0)

            with tf.variable_scope("target_lookup_table"):
                self.verb_embeddings = tf.Variable(np.load(cfg.pretrained_target)["embeddings"],
                                                   name="verb_embeddings",
                                                   dtype=tf.float32,
                                                   trainable=cfg.tune_emb)
                #self.verb_embeddings = tf.concat([tf.zeros([1, cfg.word_dim]), self.verb_embeddings[1:, :]], axis=0)

            # negative sampling
            self.neg_ids, _, _ = (tf.nn.fixed_unigram_candidate_sampler(
                true_classes=tf.cast(tf.expand_dims(self.verb, axis=1), dtype=tf.int64),
                num_true=1,
                num_sampled=cfg.neg_sample,
                unique=True,
                range_max=cfg.verb_size,
                distortion=0.75,
                unigrams=vocab_counts))

            print('neg_ids : ', self.neg_ids)

        # embedding lookup
        # with tf.device("/gpu:0"):
            with tf.variable_scope("embedding_lookup"):
                left_context_emb = tf.nn.embedding_lookup(self.word_embeddings, self.left_context)
                right_context_emb = tf.nn.embedding_lookup(self.word_embeddings, self.right_context)
                verb_emb = tf.nn.embedding_lookup(self.verb_embeddings, self.verb)
                neg_verb_emb = tf.nn.embedding_lookup(self.verb_embeddings, self.neg_ids)

        # left context bi-lstm
        with tf.device("/gpu:0"):
            with tf.variable_scope("right_context_representation"):
                cell_fw = LSTMCell(num_units=cfg.num_units)
                cell_bw = LSTMCell(num_units=cfg.num_units)
                h_rc, _ = bidirectional_dynamic_rnn(cell_fw, cell_bw, right_context_emb,
                                                    sequence_length=self.right_seq_len,
                                                    dtype=tf.float32,
                                                    time_major=False,
                                                    scope="bi_lstm")
                h_rc = tf.concat(h_rc, axis=-1)
                # self-attention
                h_rc = self_attention(h_rc, name="self_attn_right")
                r_weight = tf.get_variable(name="r_weight",
                                           shape=[2 * cfg.num_units, 2 * cfg.num_units],
                                           dtype=tf.float32)
                h_rc = tf.nn.tanh(tf.matmul(h_rc, r_weight))
                print("right context shape: {}".format(h_rc.get_shape().as_list()))

            with tf.variable_scope("left_context_representation"):
                cell_fw = LSTMCell(num_units=cfg.num_units)
                cell_bw = LSTMCell(num_units=cfg.num_units)
                h_lc, _ = bidirectional_dynamic_rnn(cell_fw, cell_bw, left_context_emb,
                                                    sequence_length=self.left_seq_len,
                                                    dtype=tf.float32,
                                                    time_major=False,
                                                    scope="bi_lstm")

                h_lc = tf.concat(h_lc, axis=-1)  # shape = (batch_size, max_len, 2 * num_units)

                # self-attention
                h_lc = self_attention(h_lc, name="self_attn_left")  # shape = (batch_size, 2 * num_units)
                l_weight = tf.get_variable(name="l_weight",
                                           shape=[2 * cfg.num_units, 2 * cfg.num_units],
                                           dtype=tf.float32)
                h_lc = tf.nn.tanh(tf.matmul(h_lc, l_weight))

                print("left context shape: {}".format(h_lc.get_shape().as_list()))

            # with tf.device("/gpu:0"):

        with tf.device("/gpu:1"):
            with tf.variable_scope("neural_tensor_network"):
                T = tf.get_variable(name="T",
                                    shape=[cfg.output_units, 2 * cfg.num_units, 2 * cfg.num_units],
                                    dtype=tf.float32)
                W = tf.get_variable(name="W",
                                    shape=[4 * cfg.num_units, cfg.output_units],
                                    dtype=tf.float32)
                b = tf.get_variable(name="b",
                                    shape=[cfg.output_units],
                                    dtype=tf.float32)
                # compute tensors
                ff_product = tf.matmul(tf.concat([h_lc, h_rc], axis=-1), W)
                bilinear_list = []
                for k in range(cfg.output_units):
                    cur_res = tf.reduce_sum(tf.matmul(h_lc, T[k]) * h_rc, axis=1)
                    bilinear_list.append(cur_res)
                context = tf.nn.tanh(tf.reshape(tf.concat(bilinear_list, axis=0), shape=[-1, cfg.output_units]) +
                                     ff_product + b)  # shape = (batch_size, output_units)
                print("context representation shape: {}".format(context.get_shape().as_list()))

        # with tf.device("/gpu:1"):
            with tf.variable_scope("verb_representation"):
                target_verb = ffn_layer(verb_emb, cfg.num_units, cfg.output_units, scope="ffn_layer")
                print("verb representation shape: {}".format(target_verb.get_shape().as_list()))
                tf.get_variable_scope().reuse_variables()
                negative_verbs = ffn_layer(neg_verb_emb, cfg.num_units, cfg.output_units, scope="ffn_layer")
                print("negative verb shape: {}".format(negative_verbs.get_shape().as_list()))

            with tf.variable_scope("compute_loss"):
                true_logits = tf.reduce_sum(context * target_verb, axis=1)
                print("true logits shape: {}".format(true_logits.get_shape().as_list()))
                neg_logits = tf.matmul(context, tf.transpose(negative_verbs, [1, 0]))
                print("negative logits shape: {}".format(neg_logits.get_shape().as_list()))

        # with tf.device("/cpu:0"):

            with tf.variable_scope("nce_loss"):
                # cross-entropy(logits, labels)
                true_xent = tf.nn.sigmoid_cross_entropy_with_logits(logits=true_logits,
                                                                    labels=tf.ones_like(true_logits))
                sampled_xent = tf.nn.sigmoid_cross_entropy_with_logits(logits=neg_logits,
                                                                       labels=tf.zeros_like(neg_logits))

                # NCE-loss is the sum of the true and noise (sampled words) contributions, averaged over the batch.
                self.loss = (tf.reduce_sum(true_xent) + tf.reduce_sum(sampled_xent)) / tf.cast(self.batch_size,
                                                                                dtype=tf.float32)
            optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)
            self.train_op = optimizer.minimize(self.loss)

    def get_feed_dict(self, data, is_train=False, drop_rate=0.0, lr=None):
        feed_dict = {
            self.verb: data["vb"],
            self.left_context: data["lc"],
            self.left_seq_len: data["ll"],
            self.right_context: data["rc"],
            self.right_seq_len: data["rl"],
            self.batch_size: data["batch_size"]
        }
        if lr is not None:
            feed_dict[self.lr] = lr
        feed_dict[self.is_train] = is_train
        feed_dict[self.drop_rate] = drop_rate
        return feed_dict


from utils.utils import *
from pipeline.training.train_alexnet_mnist_debug import *
import pipeline.training.train_smallnet_mnist as mn

def train_alexnet_mnist_0001(config_data, tab_level=0, verbose=0):
	print('train_alexnet_mnist_0001().')
	from pipeline.data.load_data import load_mnist_0001
	from utils.loss import compute_loss

	data_loader = load_mnist_0001(config_data, verbose=0)
	state_tracker = setup_state_tracker(config_data, verbose=verbose, tab_level=tab_level)
	net = new_or_load_model(state_tracker,config_data, verbose=verbose, tab_level=tab_level)
	criterion, optimizer = mn.setup_training_tools_0001(net, config_data,
		verbose=verbose, tab_level=tab_level+1)

	pm.printv('Start training...'%(), tab_level=tab_level)
	total_iter_in_this_run = 0
	l_epoch = 1 + state_tracker.get_latest_saved_epoch()

	for n_epoch in range(l_epoch, l_epoch + config_data['general']['epoch']):
		state_tracker.setup_for_this_epoch(n_epoch)
		for i, data in enumerate(data_loader,0):
			optimizer.zero_grad()

			x, y0 = data
			x = x.to(this_device)

			if DEBUG_train_loop_0001(DEBUG_train_alexnet_mnist_LOOP_SIGNAL, net, x, y0,
				tab_level=tab_level, verbose=verbose): return

			y = net(x)

			loss = compute_loss(criterion, y.squeeze(3).squeeze(2).cpu(), y0)
			loss.backward()
			optimizer.step()

			# FOR LOGGING
			total_iter_in_this_run += 1
			state_tracker.store_loss_by_epoch(loss.item(), n_epoch)

			stop_iter, stop_epoch = DEBUG_train_loop_0002(DEBUG_train_alexnet_mnist_LOOP_SIGNAL2,
				i, n_epoch - l_epoch , tab_level=tab_level+1, verbose=verbose)
			if stop_iter: break
		state_tracker.update_epoch()
		if stop_epoch: break
	state_tracker.update_state(total_iter_in_this_run, config_data)
	mn.save_model_by_n_th_run(net, state_tracker,tab_level=tab_level, verbose=verbose)
	state_tracker.display_end_state(tab_level=tab_level+1, verbose=verbose)

def setup_state_tracker(config_data, for_training=True, verbose=0, tab_level=0):
	from utils.state_tracker import StateTracker
	ckpt_path = os.path.join(config_data['working_dir'],'checkpoint')
	tracker_name = 'alexnet_mnist_0001_'
	training_series_name = tracker_name + str(config_data['training']['series_name'])
	state_tracker = StateTracker(
		mode='load_latest_if_available',
		ckpt_path=ckpt_path,
		training_series_name=training_series_name,
		load_this_n_th_run=None,
		verbose=verbose,
		tab_level=tab_level+1)
	state_tracker = state_tracker.load_latest_if_available(state_tracker.latest_saved_run,for_training=for_training)
	state_tracker.display_simple_state(tab_level=tab_level+1, verbose=verbose)
	return state_tracker

def new_or_load_model(state_tracker, config_data, verbose=0, tab_level=0):
	pm.printvm("new_or_load_model(). latest_saved_run:%s"%(str(state_tracker.latest_saved_run)),
		 tab_level=tab_level,verbose=verbose, verbose_threshold=50)
	from models.networks import AlexNetLike

	if config_data['data_from_torch']['mnist']['resize'] is None:
		net = AlexNetLike(verbose=verbose, tab_level=tab_level)
	else:
		IMG_SIZE = config_data['data_from_torch']['mnist']['resize']
		net = AlexNetLike(set_default_params=False, relprop_mode=config_data['lrp']['relprop_mode'], verbose=verbose, tab_level=tab_level)
		if IMG_SIZE == (140,140):
			from models.networks_Alex import AlexNet_custom_setting0001
			net = AlexNet_custom_setting0001(net)
		else:
			raise Exception('Please manually set params')

	from pipeline.training.train_smallnet_mnist import new_or_load_model_inner
	net = new_or_load_model_inner(state_tracker, net, verbose=verbose, tab_level=tab_level+1)
	return net


class Tree:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

    def insert(self, value):
        if self.value:
            if value < self.value:
                if self.left is None:
                    self.left = Tree(value)
                else:
                    self.left.insert(value)
            elif value > self.value:
                if self.right is None:
                    self.right = Tree(value)
                else:
                    self.right.insert(value)
        else:
            self.value = value

def arrayToBST(arr):
    if len(arr) == 0:
        return None

    mid = len(arr) // 2
    root = Tree(arr[mid])
    root.left = arrayToBST(arr[:mid])
    root.right = arrayToBST(arr[mid+1:])
    return root
array = [1, 2, 3, 4, 5, 6, 7]

root = arrayToBST(array)

def in_order_traversal(tree):
    elements = []
    def dfs(node, depth):
        if node.left != None:
            dfs(node.left, depth + 1)
        elements.append(node.value)
        if node.right != None:
            dfs(node.right, depth + 1)
    dfs(tree, 0)
    return elements

result = in_order_traversal(root)
def check_order(array):
    for i in range(len(array) - 1):
        if(array[i] > array[i+1]):
            return False
    return True

print(check_order(result))


import random
import sys
import time
M=0
N=0
holes=18
#####################################################clase blades##############
class Blades:
    def __init__(self,entrada,salida):
        self.entrada=entrada
        self.salida=salida
        self.opciones=[]
        self.permuto=[]

    def gen_opc(self):
        aux=[]
        for i in range(18):
            if self.entrada[i]!=0:
                aux.append(dev_values(self.salida[i],self.entrada[i]))
        cont=0
        self.permu(aux,cont)

        for j in self.permuto:
            sum=0
            for k in j:
                sum=sum+k
            if sum<M:
                if self.opciones.count(sum)==0:
                    self.opciones.append(sum)

    def getPermuto(self):
        return self.permuto

    def GetOpciones(self):
        return self.opciones

    def permu(self,auxi,cont):
        if cont==len(auxi):
            return
        else:
            multi=1
            for j in range(cont+1,len(auxi)):
                multi=multi*len(auxi[j])
            if cont==0:
                k=0
                for i in auxi[cont]:
                    for j in range(multi):
                        self.permuto.append([i])
            else:
                k=0
                indice=0
                axiliar=auxi[cont]
                for i in range(len(self.permuto)):
                    self.permuto[i].append(axiliar[indice])
                    k=k+1
                    if k==multi:
                        k=0
                        indice=indice+1
                    if indice==len(axiliar):
                        indice=0
        self.permu(auxi,cont+1)

############################funcion main#####################################################
def run():
    band=0
    intentos=[]
    respuesta=0
    iter=0
    while band==0 and iter<M:
        iter=iter+1
        salida=dev_wind()
        output=" ".join(map(str,salida))
        ##########outpu#############
        print(output)
        sys.stdout.flush()
        #########input###############
        entrada = list(map(int,input().split()))
        obj=Blades(entrada,salida)
        obj.gen_opc()
        if len(intentos)==0:
            intentos.append(obj.GetOpciones())
        else:
            probar=obj.GetOpciones()
            aux=[]
            for i in probar:
                for j in intentos[-1]:
                    if i==j:
                        aux.append(i)
            intentos.append(aux)

        if len(intentos[-1])==1:
            band=1
            respuesta=intentos[-1][0]
    print(respuesta)
    sys.stdout.flush()
    veredict=int(input())
    if veredict==-1:
        exit()

##0 1 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 0
# 2 2 2 2 18 3 3 3 3 3 3 4 4 4 4 5 2 2

############################################################################################
def dev_values(blades,n1):
    salida=[]
    z=n1
    salida.append(z)
    while z+blades<M/4:
        salida.append(z+blades)
        z=z+blades
    return salida
#######################################################################################
def dev_wind():
    salida=[]
    for i in range(18):
        var=random.randint(2, 18)
        salida.append(var)
    return salida

t,n,m=map(int,input().split())
N=n
M=m
for _ in range(t):
    run()


from django import forms
from django.db import connection

search_path = "SET search_path to THECIMS"

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

def get_id_koleksi():
    with connection.cursor() as c:
        c.execute(search_path)
        c.execute("SELECT id FROM KOLEKSI")
        res = dictfetchall(c)
    temp_res = [res[i]['id'] for i in range(len(res))]
    return [tuple([i,i]) for i in temp_res]

class createForm(forms.Form):

    # id = forms.CharField(label="ID", widget=forms.Select(choices=get_id_koleksi()))
    id = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'form-control',
        'placeholder': 'ID',
        'type' : 'text',
        'required': True,
    }))

    harga = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'form-control',
        'placeholder': 'Harga',
        'type' : 'integer',
        'required': True,
    }))


url = "https://www.linkedin.com/jobs/search/?currentJobId=3566989713&f_JT=F&geoId=103644278&keywords=electrical%20engineer&location=United%20States&refresh=true"

def get_domain(url):
    regex = r"&keywords=(.*?)&location"
    matches = re.search(regex, url)
    if matches:
        return matches.group(1).replace("%20","_")
    else:
        print("Domain not foudn in URL, enter domain(ex: data_science): ")
        domain = input()
        return domain


import torch
import numpy as np
from PIL import Image
import os, random, math
import sys

sys.path.append(os.path.abspath(os.path.join(__file__, "..", "..")))
from black_box_tool import get_84_transform

sys.path.append(os.path.abspath(os.path.join(__file__, "..", "..")))

def save_image_batch(imgs, output, col=None, size=None, pack=True):
    if isinstance(imgs, torch.Tensor):
        imgs = (imgs.detach().clamp(0, 1).cpu().numpy()*255).astype('uint8')
    base_dir = os.path.dirname(output)
    if base_dir!='':
        os.makedirs(base_dir, exist_ok=True)
    if pack:
        imgs = pack_images( imgs, col=col ).transpose( 1, 2, 0 ).squeeze()
        imgs = Image.fromarray( imgs )
        if size is not None:
            if isinstance(size, (list,tuple)):
                imgs = imgs.resize(size)
            else:
                w, h = imgs.size
                max_side = max( h, w )
                scale = float(size) / float(max_side)
                _w, _h = int(w*scale), int(h*scale)
                imgs = imgs.resize([_w, _h])
        imgs.save(output)
    else:
        #output_filename = output.strip('.png')
        output_filename = output[:-4]
        for idx, img in enumerate(imgs):
            img = Image.fromarray( img.transpose(1, 2, 0).squeeze() )
            img.save(output_filename+'-%d.png'%(idx))

def pack_images(images, col=None, channel_last=False, padding=1):
    # N, C, H, W
    if isinstance(images, (list, tuple) ):
        images = np.stack(images, 0)
    if channel_last:
        images = images.transpose(0,3,1,2) # make it channel first
    assert len(images.shape)==4
    assert isinstance(images, np.ndarray)

    N,C,H,W = images.shape
    if col is None:
        col = int(math.ceil(math.sqrt(N)))
    row = int(math.ceil(N / col))

    pack = np.zeros( (C, H*row+padding*(row-1), W*col+padding*(col-1)), dtype=images.dtype )
    for idx, img in enumerate(images):
        h = (idx // col) * (H+padding)
        w = (idx % col) * (W+padding)
        pack[:, h:h+H, w:w+W] = img
    return pack

def normalize(tensor, mean, std, reverse=False):
    if reverse:
        _mean = [ -m / s for m, s in zip(mean, std) ]
        _std = [ 1/s for s in std ]
    else:
        _mean = mean
        _std = std

    _mean = torch.as_tensor(_mean, dtype=tensor.dtype, device=tensor.device)
    _std = torch.as_tensor(_std, dtype=tensor.dtype, device=tensor.device)
    tensor = (tensor - _mean[None, :, None, None]) / (_std[None, :, None, None])
    return tensor

class Normalizer(object):
    def __init__(self, mean, std):
        self.mean = mean
        self.std = std

    def __call__(self, x, reverse=False):
        return normalize(x, self.mean, self.std, reverse=reverse)

class ImagePool2(object):
    def __init__(self,args, root,num_classes,transform,max_batch_per_class):
        self.args=args
        self.root_support=os.path.join(root,'support')
        self.root_query = os.path.join(root, 'query')
        #support pool
        for c_abs in range(num_classes):
            os.makedirs(os.path.join(self.root_support,str(c_abs)), exist_ok=True)
            os.makedirs(os.path.join(self.root_query, str(c_abs)), exist_ok=True)
        self._idx = [0]*num_classes
        self.max_batch_per_class=max_batch_per_class
        self.ready_class=[]
        self.transform=transform

    def add(self, imgs, c_abs_list=None,synthesis_batch_size_per_class=None,mode=None):
        c_abs_targets=torch.LongTensor(c_abs_list*synthesis_batch_size_per_class)
        for c_abs in c_abs_list:
            if mode=='support':
                root=os.path.join(self.root_support,str(c_abs))
            if mode=='query':
                root=os.path.join(self.root_query,str(c_abs))
            imgs_c=imgs[c_abs_targets==c_abs]
            save_image_batch(imgs_c, os.path.join( root, "%d.png"%(self._idx[c_abs]) ), pack=False)
            self._idx[c_abs]+=1
            self._idx[c_abs]=self._idx[c_abs]%self.max_batch_per_class
            if c_abs not in self.ready_class:
                self.ready_class.append(c_abs)

    def get_random_task(self,num_w,num_s,num_q):
        select_way=random.sample(self.ready_class,num_w)
        support_x=[]
        query_x=[]
        support_y_abs=[]
        query_y_abs = []
        for c_relative,c_abs in enumerate(select_way):
            c_abs_path = os.path.join(self.root_support, str(c_abs))
            image_name_list = os.listdir(c_abs_path)
            image_name_list = random.sample(image_name_list, (num_s+num_q))
            if self.args.dataset!='mix':
                if self.args.dataset == 'omniglot':
                    select_image = [self.transform(Image.open(os.path.join(c_abs_path, image_name)).convert('L')) for image_name in image_name_list]
                else:
                    select_image = [self.transform(Image.open(os.path.join(c_abs_path, image_name)).convert('RGB')) for image_name in image_name_list]
            elif self.args.dataset=='mix':
                if c_abs<=63:
                    transform=get_84_transform(self.args, dataset='cifar100')
                else:
                    transform=get_84_transform(self.args, dataset='cub')
                select_image = [transform(Image.open(os.path.join(c_abs_path, image_name)).convert('RGB')) for
                                image_name in image_name_list]

            select_image = torch.stack(select_image, dim=0)
            support_x.append(select_image[:num_s])
            query_x.append(select_image[num_s:(num_s + num_q)])
            support_y_abs.append(torch.LongTensor([c_abs] * num_s))
            query_y_abs.append(torch.LongTensor([c_abs] * num_q))
        return torch.cat(support_x,dim=0),torch.cat(support_y_abs,dim=0),torch.cat(query_x,dim=0),torch.cat(query_y_abs,dim=0),select_way


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 12 15:57:27 2022

@author: roman
"""

from ps4a_debug import *

def isValidWordTest(wordList):
    """
    Unit Test for isValidWord
    """

    # test 1 wordlist is empty everything else has content
    wordList2 = []
    hand = {'e':1, 'v':1, 'n':1}
    word = 'even'

    try:
        isValidWord(word, hand, wordList2)
    except AssertionError:
        print('TEST 1: SUCCESS')
    except Exception as e:
        print('TEST 1: FAILURE', e)
    else:
        print('TEST 1: FAILURE AN ASSERTION ERROR WAS MEANT TO OCCUR')
    finally:
        print('---------------------------------------------')
        print()

    # test 2 word is empty everything else has content
    word = ''
    try:
        result = isValidWord(word, hand, wordList)
        if (result):
            print('TEST 2: FAILED RESULT WAS MEANT TO BE FALSE')
        else:
            print('TEST 2: SUCCESS')
    except Exception as e:
        print('TEST 2: FAILED', e)
    finally:
        print('---------------------------------------------')
        print()

    # test 3 hand is empty everything else has content
    hand = {}
    word = 'even'
    try:
        isValidWord(word, hand, wordList)
    except AssertionError:
        print('TEST 3: SUCCESS')
    except Exception as e:
        print('TEST 3: FAILURE', e)
    else:
        print('TEST 3: FAILURE AN ASSERTION ERROR WAS MEANT TO OCCUR')
    finally:
        print('---------------------------------------------')
        print()

    # test 4 word has letters that are missing in hand
    hand = {'e':1, 'v':1, 'n':1}
    word = 'apple'
    try:
        result = isValidWord(word, hand, wordList)
        if (result):
            print('TEST 4: FAILED RESULT WAS MEANT TO BE FALSE')
        else:
            print('TEST 4: SUCCESS')
    except Exception as e:
        print('TEST 4: FAILED', e)
    finally:
        print('---------------------------------------------')
        print()

    # test 5 word has letters in hand but occur more
    hand = {'e':1, 'v':1, 'n':1}
    word = 'even'
    try:
        result = isValidWord(word, hand, wordList)
        if (result):
            print('TEST 5: FAILED RESULT WAS MEANT TO BE FALSE')
        else:
            print('TEST 5: SUCCESS')
    except Exception as e:
        print('TEST 5: FAILED', e)
    finally:
        print('---------------------------------------------')
        print()

    # test 6 word and hand are accurate
    hand = {'e':2, 'v':1, 'n':1}
    word = 'even'
    try:
        result = isValidWord(word, hand, wordList)
        if (result):
            print('TEST 6: SUCCESS')
        else:
            print('TEST 6: FAILED RESULT WAS MEANT TO BE TRUE')
    except Exception as e:
        print('TEST 6: FAILED', e)
    finally:
        print('---------------------------------------------')
        print()

    # test 7 word can be made from hand but it doesn't exist
    hand = {'e':2, 'v':1, 'n':1}
    word = 'evn'
    try:
        result = isValidWord(word, hand, wordList)
        if (result):
            print('TEST 7: FAILED RESULT WAS MEANT TO BE FALSE')
        else:
            print('TEST 7: SUCCESS')
    except Exception as e:
        print('TEST 7: FAILED', e)
    finally:
        print('---------------------------------------------')
        print()

wordList = loadWords()
print("----------------------------------------------------------------------")
print("Testing isValidWord...")
isValidWordTest(wordList)


import sys
import openpyxl
import os
from openpyxl import Workbook
from datetime import date
import pandas as pd

def main():
    sales_csv = get_sales_csv()
    orders_directory = create_orders_directory(sales_csv)
    process_sales_data(sales_csv, orders_directory)

# Get path of sales data CSV file from the command line
def get_sales_csv():
    # Check whether command line parameter provided
    # Check whether provide parameter is valid path of file
    if len(sys.argv) < 2:
        print("Error: No Command line parameter is given.")
        sys.exit()
    csv_file = sys.argv[1]
    if not os.path.exists(csv_file):
        print("Error: Given File path does not exist.")

        sys.exit()

    return csv_file

# Create the directory to hold the individual order Excel sheets

def create_orders_directory(sales_csv):
    csv_directory = os.path.dirname(sales_csv)
    today = date.today().strftime('%Y-%m-%d')
    orders_directory = os.path.join(csv_directory, 'Orders' + today)

    if not os.path.exists(orders_directory):
        os.mkdir(orders_directory)

    return orders_directory

    # Get directory in which sales data CSV file resides
    # Determine the name and path of the directory to hold the order data files
    # Create the order directory if it does not already exist

# Split the sales data into individual orders and save to Excel sheets
def process_sales_data(sales_csv, orders_dir):
    # Import the sales data from the CSV file into a DataFrame
    # Insert a new "TOTAL PRICE" column into the DataFrame
    # Remove columns from the DataFrame that are not needed
    # Group the rows in the DataFrame by order ID
    # For each order ID:
        # Remove the "ORDER ID" column
        # Sort the items by item number
        # Append a "GRAND TOTAL" row
        # Determine the file name and full path of the Excel sheet
        # Export the data to an Excel sheet
        # TODO: Format the Excel sheet

    sales_data = pd.read_csv(sales_csv)
    sales_data['TOTAL PRICE'] = sales_data['QUANTITY OF ITEM'] * sales_data['PRICE OF ITEM']
    sales_data = sales_data[['DATE OF ORDER', 'ITEM NUMBER', 'PRODUCT LINE', 'PRODUCT CODE', 'QUANTITY OF ITEM', 'PRICE OF ITEM', 'TOTAL PRICE', 'STATUS', 'CUSTOMER NAME']]
    Orders = sales_data.groupby(by='ORDER ID')

    for Order_id, order_data in Orders:

        Order_data = Order_data.sort_values(by='ITEM NUMBER')
        Order_data = Order_data.reset_index(drop=True)
        grand_total = Order_data['TOTAL PRICE'].sum()
        Order_data = Order_data.append({'ITEM NUMBER': 'GRAND TOTAL', 'TOTAL PRICE': grand_total}, ignore_index=True)

        Order_file = os.path.join(orders_dir, str(Order_id) + ".xlsx")
        Order_data.to_excel(Order_file, Index=False, Engine='openpyxl')
        # TODO: Format the Excel sheet
        wb = openpyxl.load_workbook(Order_file)
        sheet = wb.worksheets[0]
        # Format the Excel sheet
        sheet.column_dimensions['A'].width = 11
        sheet.column_dimensions['B'].width = 13
        sheet.column_dimensions['C'].width = 15
        sheet.column_dimensions['D'].width = 15
        sheet.column_dimensions['E'].width = 15
        sheet.column_dimensions['F'].width = 13
        sheet.column_dimensions['G'].width = 13
        sheet.column_dimensions['H'].width = 10
        sheet.column_dimensions['I'].width = 30

        for row in sheet.item_rows(min_row=2, min_col=4, max_col=5):
            for cell in row:
                cell.number_format = '"$"#,##0.00'
        Workbook.save(Order_file)
        pass

if __name__ == '__main__':
    main()


from flask_restful import Resource
from candidatos.modelos.modelos import db, CandidatoSchema, Candidato
from flask import request
from flask_jwt_extended import jwt_required, create_access_token
from datetime import datetime
from celery import Celery

celery_app = Celery(__name__, broker='redis://127.0.0.1:6379/0')
candidato_schema = CandidatoSchema()

class VistaCandidatosC(Resource):
    @jwt_required()
    def post(self):
        nuevo_candidato = Candidato(nombre=request.json['nombre'],\
                                profesion=request.json['profesion'])
        db.session.add(nuevo_candidato)
        db.session.commit()
        return candidato_schema.dump(nuevo_candidato)

class VistaCandidatoC(Resource):
    @jwt_required()
    def put(self, id_candidato):
        candidato = Candidato.query.get_or_404(id_candidato)
        candidato.nombre = request.json.get('nombre', candidato.nombre)
        candidato.profesion = request.json.get('profesion', candidato.profesion)
        db.session.commit()
        return candidato_schema.dump(candidato)


# 출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

# 코딩테스트 연습 > 연습문제 > 시저암호
# 사용언어 Python3
def solution(s, n):
    s = list(s)
    AZ = list(range(65,91))
    az = list(range(97,123))
    for i, c in enumerate(s):
        if ord(c) <= 90 and ord(c.upper()) + n > 90:
            s[i] = chr(AZ[(ord(c) + n - 90)%26 - 1])
        elif ord(c.upper()) + n > 90:
            s[i] = chr(az[(ord(c) + n - 122)%26 - 1])
        elif c == " ":
            s[i] = c
        else:
            s[i] = chr(ord(c) + n)
    return ''.join(s)
# 아스키 코드표 대문자 (A-Z : 65-90, a-z : 97-122)
# 고려할 사항이 너무 많아서 어려웠다. ord()와 chr()를 사용하기 위해 아스키코드표를 참고.
# 최대 3.50ms
# ====================================================================================
# 다른 코드
def solution(s, n):
    s = list(s)
    for i in range(len(s)):
        if s[i].isupper():
            s[i]=chr((ord(s[i])-ord('A')+ n)%26+ord('A'))
        elif s[i].islower():
            s[i]=chr((ord(s[i])-ord('a')+ n)%26+ord('a'))

    return "".join(s)
# isupper(), islower()을 사용해 대소문자 판별. 아스키코드 자체를 사용하지 않고 ord(s[i])-ord('A')로 길이를 우선 구해서 사용한 것이 내 코드와 가장 다른 점
# 간결한 코드 사용을 위해 더 고민해 볼 필요가 있다.
# 최대 2.60ms


# coding:utf-8
import codecs
import os
import re

from setuptools import setup, find_packages

def find_version(*file_paths):
    """
    Don't pull version by importing package as it will be broken due to as-yet uninstalled
    dependencies, following recommendations at  https://packaging.python.org/single_source_version,
    extract directly from the init file
    """
    here = os.path.abspath(os.path.dirname(__file__))
    with codecs.open(os.path.join(here, *file_paths), 'r', encoding="utf-8") as f:
        version_file = f.read()

    # The version line must have the form
    # __version__ = 'ver'
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

install_requires = [item.strip() for item in open('requirements.txt').readlines()]

tests_require = [item.strip() for item in open('requirements-dev.txt').readlines()]

setup(
    name="quantbube",
    version=find_version("quantbube", "__init__.py"),
    author="Winton Wang",
    keywords=["Quantitative Analysis",
              "Trading Bot",
              "Trading Strategy",
              "Time-series Kit",
              "Investment Framework"],
    author_email="winton@quant.vc",
    description="Quantitative Analysis and Trading Strategy Framework",
    long_description=open("README.rst", encoding="utf-8").read(),
    license="GNU Lesser General Public License v3 or later (LGPLv3+)",
    url="https://github.com/nooperpudd/quantbube",
    packages=find_packages(exclude=["tests", "test.*", "sample"]),
    zip_safe=False,
    install_requires=install_requires,
    tests_require=tests_require,
    classifiers=[
        # https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Science/Research',
        'Operating System :: OS Independent',
        'License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Office/Business',
        'Topic :: Office/Business :: Financial',
        'Topic :: Office/Business :: Financial :: Investment',
        'Topic :: Software Development',
        'Topic :: Software Development :: Libraries',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)


#!/usr/bin/python3

def extend_settings_meta(settings):
    settings['app_title'] = 'Gamelist XML Editor'
    settings['app_license'] = 'GNU GPL v3'
    settings['app_name'] = 'gamelistedit'
    settings['app_author'] = 'Tuncay D.'
    settings['app_copyright_years'] = '2021'
    settings['app_version'] = '0.1.0'
    settings['app_minpython'] = '3.6'
    settings['app_minqt5'] = '5.15'
    settings['app_desc'] = (
        'GUI operation and commandline automation to edit, filter'
        ' and export gamelist.xml files from EmulationStation.')
    return settings

def get_meta(key=None):
    meta = extend_settings_meta({})
    return meta if key is None else meta[key]

# python3 -m modules.meta name version
if __name__ == '__main__':
    import sys

    meta = get_meta()
    if len(sys.argv) > 1:
        for key in sys.argv[1:]:
            print(meta[f'app_{key}'])
    else:
        for key, value in meta.items():
            print(f'{key[4:]}={value}')


from flask import render_template, flash, Blueprint, redirect,url_for
from app.models.hotel import Hotel
from flask_login import current_user
from app.manage_property.forms import ManageForm

manage_blueprint = Blueprint("manage_property",
                             __name__,
                             template_folder="templates/manage_property")

@manage_blueprint.route("/manage", methods=["GET", "POST"])
def manage_property():
    form = ManageForm()

    if form.validate_on_submit():
        hotel = Hotel.query.filter_by(user_id=current_user.id).first()
        hotel_name = form.hotel_name.data
        address = form.address.data
        room_quantity = form.room_quantity.data
        stars = form.stars.data
        if hotel_name:
            hotel.hotel_name = hotel_name
            Hotel.update()
        if address:
            hotel.address = address
            Hotel.update()
        if room_quantity:
            hotel.room_quantity = room_quantity
            Hotel.update()
        if stars:
            hotel.stars = stars
            Hotel.update()
        # old_info = [hotel.hotel_name, hotel.address, hotel.room_quantity, hotel.stars]
        # new_info = [hotel_name, address, room_quantity, stars]
        # for item in new_info:
        #     if item:
        #         old_info[new_info.index(item)] = item
        #         Hotel.update()
        #         print(old_info[new_info.index(item)])

        flash("Item(s) updated successfully")
        return redirect(url_for("manage_property.manage_property"))

    return render_template("manage_property.html", form=form)


class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        #print board
        for i in xrange(9):
            if not Solution.check(board[i]):
                return False
            if not Solution.check(zip(*board)[i]):
                return False
        for i in xrange(0, 9, 3):
            for j in xrange(0, 9, 3):
                target = board[i][j : j + 3] + board[i + 1][j : j + 3] + board[i + 2][j : j + 3]
                if not Solution.check(target):
                    return False
        return True

    @staticmethod
    def check(lst):
        num = lst.count('.')
        return len(lst) == len(set(lst)) if num < 1 else len(lst) - num + 1 == len(set(lst))


testcase_num = int(input())
change_list = []
for i in range(testcase_num):
    change_list.append(int(input()))

for i in range(testcase_num):
    change = change_list[i]
    base_dict = {50000: 0, 10000:0, 5000:0, 1000:0, 500:0, 100:0, 50:0, 10:0}

    for key, val in base_dict.items():
        base_dict[key] = change//key
        change -= key * (change//key)

    print(f'#{i+1}')
    for key, val in base_dict.items():
        print(f'{val} ', end=' ')
    print()


'''
def genSubSeq(arr,i,s,summ,temp_arr):

	if i >=len(arr):

		if s == summ:
			print(temp_arr)

		return

	temp_arr.append(arr[i])

	s +=arr[i]
	genSubSeq(arr,i+1,s,summ,temp_arr)

	s -=arr[i]

	temp_arr.pop()

	genSubSeq(arr,i+1,s,summ,temp_arr)

'''

# If you want to stop recursion on first output
# summ = 4

# [1, 2, 1] when this array print that is first the recursion stops
# [1, 3]
# [1, 3]
# [4]
# Below solution

'''
def genSubSeq(arr,i,s,summ,temp_arr):

	if i >= len(arr):

		if s == summ :
			print(temp_arr)

			return True
		else:
			return False

	s +=arr[i]
	temp_arr.append(arr[i])

	if genSubSeq(arr,i+1,s,summ,temp_arr) : return True

	s -= arr[i]
	temp_arr.pop()
	if genSubSeq(arr,i+1,s,summ,temp_arr) : return True

	return False

'''

# return only Count that how many time a subsequence found having sum= K

def genSubSeq(arr,i,s,summ):

	if i >= len(arr):

		if s == summ :
			return 1
		else:
			return 0

	s += arr[i]

	# temp_arr.append(arr[i])

	left = genSubSeq(arr,i+1,s,summ)

	s -= arr[i]

	right = genSubSeq(arr,i+1,s,summ)

	return left + right

arr = [1,2,1,3,4]

summ = 7
temp_arr = []
count = genSubSeq(arr,0,0,summ)

print(count)


import os
import requests
from dotenv import load_dotenv
from flask import Blueprint, request, jsonify

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

# .env ファイルから API キーを取得
load_dotenv()
X_API_KEY = os.getenv('API_KEY')

base_url = 'https://publicapi.taittsuu.com/publicapi/v0.1'
headers = {'content-type': 'application/json', 'X-API-KEY': X_API_KEY}
public_timelines_url = '/publictimelines'
users_url = '/users'
taiitsus_url = '/taiitsus'
liking_users_url = '/liking_users'
following_url = '/following'
followers_url = '/followers'
search_uel = '/search'

# パブリックタイムラインの取得
@api.route(public_timelines_url, methods=['GET'])
def public_timelines():
    req = request.args
    next_num = req.get('next')
    next_param = f'?next={next_num}' if next_num else ''
    res = requests.get(
            f'{base_url}{public_timelines_url}{next_param}',
            headers=headers
        )
    return res.json()

# ユーザーのタイーツ取得
@api.route(f'{users_url}/<user_id>{taiitsus_url}', methods=['GET'])
def user_taiitsus(user_id):
    req = request.args
    next_num = req.get('next')
    next_param = f'?next={next_num}' if next_num else ''
    res = requests.get(
            f'{base_url}{users_url}/{user_id}{taiitsus_url}{next_param}',
            headers=headers
        )
    return res.json()

# タイーツ情報取得
@api.route(f'{taiitsus_url}/<taiitsu_id>', methods=['GET'])
def taiitsu(taiitsu_id):
    res = requests.get(
            f'{base_url}{taiitsus_url}/{taiitsu_id}',
            headers=headers
        )
    return res.json()

# タイーツのいいね一覧取得
@api.route(f'{taiitsus_url}/<taiitsu_id>{liking_users_url}', methods=['GET'])
def liking_users(taiitsu_id):
    req = request.args
    next_num = req.get('next')
    next_param = f'?next={next_num}' if next_num else ''
    res = requests.get(
            f'{base_url}{taiitsus_url}/{taiitsu_id}{liking_users_url}{next_param}',
            headers=headers
        )
    return res.json()

# ユーザー情報取得
@api.route(f'{users_url}/<user_id>', methods=['GET'])
def user(user_id):
    res = requests.get(
            f'{base_url}{users_url}/{user_id}',
            headers=headers
        )
    return res.json()

# ユーザーのフォロー一覧取得
@api.route(f'{users_url}/<user_id>{following_url}', methods=['GET'])
def user_following(user_id):
    req = request.args
    next_num = req.get('next')
    next_param = f'?next={next_num}' if next_num else ''
    res = requests.get(
            f'{base_url}{users_url}/{user_id}{following_url}{next_param}',
            headers=headers
        )
    return res.json()

# ユーザーのフォロワー一覧取得
@api.route(f'{users_url}/<user_id>{followers_url}', methods=['GET'])
def user_followers(user_id):
    req = request.args
    next_num = req.get('next')
    next_param = f'?next={next_num}' if next_num else ''
    res = requests.get(
            f'{base_url}{users_url}/{user_id}{followers_url}{next_param}',
            headers=headers
        )
    return res.json()

# ユーザー検索
@api.route(f'{search_uel}{users_url}', methods=['GET'])
def search_users():
    req = request.args
    query_word = req.get('query')
    if not query_word:
        return jsonify({'error': {
            'code': 400,
            'message': 'クエリパラメータ"query"は必須です。'
        }})
    next_num = req.get('next')
    params = f'?query={query_word}&next={next_num}' if next_num else f'?query={query_word}'
    res = requests.get(
            f'{base_url}{search_uel}{users_url}{params}',
            headers=headers
        )
    return res.json()

# エラーのハンドリング
@api.errorhandler(400)
@api.errorhandler(404)
def error_handler(error):
    return jsonify({'error': {
        'code': error.description['code'],
        'message': error.description['message']
    }}), error.code


import click
import pandas as pd
from tqdm import tqdm

from ..apply import predict_separator
from ..io import (
    append_column_to_hdf5,
    append_predictions_cta,
    read_telescope_data_chunked,
    drop_prediction_column,
    drop_prediction_groups,
    load_model,
)
from ..configuration import AICTConfig
from ..logging import setup_logging

@click.command()
@click.argument("configuration_path", type=click.Path(exists=True, dir_okay=False))
@click.argument("data_path", type=click.Path(exists=True, dir_okay=False))
@click.argument("model_path", type=click.Path(exists=True, dir_okay=False))
@click.option("-v", "--verbose", help="Verbose log output", is_flag=True)
@click.option(
    "-N",
    "--chunksize",
    type=int,
    help="If given, only process the given number of events at once",
)
@click.option("-y", "--yes", help="Do not prompt for overwrites", is_flag=True)
def main(configuration_path, data_path, model_path, chunksize, yes, verbose):
    """
    Apply loaded model to data.

    CONFIGURATION_PATH: Path to the config yaml file.
    DATA_PATH: path to the FACT/CTA data.
    MODEL_PATH: Path to the pickled model.

    The program adds the following columns to the inputfile:
        `output_name`: the output of model.predict_proba for the
        class name given in the config file.

    If `output_name` is not given in the config file,
    the default value of "gamma_prediction" will be used.
    """
    log = setup_logging(verbose=verbose)

    config = AICTConfig.from_yaml(configuration_path)
    model_config = config.separator

    prediction_column_name = model_config.output_name

    if config.data_format == "CTA":
        drop_prediction_groups(data_path, group_name=model_config.output_name, yes=yes)
    elif config.data_format == "simple":
        drop_prediction_column(
            data_path,
            group_name=config.events_key,
            column_name=prediction_column_name,
            yes=yes,
        )

    log.debug("Loading model")
    model = load_model(model_path)
    log.debug("Loaded model")

    df_generator = read_telescope_data_chunked(
        data_path,
        config,
        chunksize,
        model_config.columns_to_read_apply,
        feature_generation_config=model_config.feature_generation,
    )

    if config.data_format == "CTA":
        chunked_frames = []

    for df_data, start, stop in tqdm(df_generator):
        prediction = predict_separator(df_data[model_config.features], model)
        if config.data_format == "CTA":
            df_data.reset_index(inplace=True)
            for tel_id, group in df_data.groupby("tel_id"):
                d = group[["obs_id", "event_id"]].copy()
                d[prediction_column_name] = prediction[group.index]
                chunked_frames.append(d)
                append_predictions_cta(
                    data_path,
                    d,
                    f"/dl2/event/telescope/{model_config.output_name}/tel_{tel_id:03d}",
                )
        elif config.data_format == "simple":
            append_column_to_hdf5(
                data_path, prediction, config.events_key, model_config.output_name
            )

    # combine predictions
    if config.data_format == "CTA":
        array_table = f"/dl2/event/subarray/{model_config.output_name}"
        d = (
            pd.concat(chunked_frames)
            .groupby(["obs_id", "event_id"], sort=False)
            .agg(["mean", "std"])
        )
        d.columns = d.columns.droplevel(0)
        d.reset_index().to_hdf(data_path, array_table, mode="a", format="table")

if __name__ == "__main__":
    # pylint: disable=no-value-for-parameter
    main()


from duty.objects import dp, SignalEvent, __version__
from duty.utils import ment_user, format_response
import time

@dp.signal_event_register('инфо', 'инфа', 'info')
def sinfo(event: SignalEvent) -> str:
    if event.msg['from_id'] not in event.db.trusted_users:
        message_id = event.send(event.responses['not_in_trusted'])
        time.sleep(3)
        event.api.msg_op(3, msg_id=message_id)
        return "ok"

    owner = event.api('users.get', user_ids=event.db.owner_id)[0]

    event.send(format_response(
        event.responses['info_duty'],
        версия=__version__,
        владелец=ment_user(owner),
        чаты=len(event.db.chats.keys()),
        ид=event.chat.iris_id,
        имя=event.chat.name
    ))
    return "ok"


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 13 02:31:23 2018

@author: longtran
"""

import numpy as np
import tensorflow as tf
import os
from model6 import ConvNet

def train(train_dset, val_dset, log_folder, device='/cpu:0', batch_size=64, num_epochs=1,
          model_type="custom"):
    x, y_media, y_emotion = train_dset
    x_val, y_media_val, y_emotion_val = val_dset
    if model_type == "custom":
        print("Using custom model...")
        model = ConvNet()
    elif model_type == "vgg19":
        from model_vgg19 import VGG19
        print("Using pre-trained VGG19 model...")
        model = VGG19()
    elif model_type == "vgg16":
        from model_vgg16 import VGG16
        print("Using pre-trained VGG16 model...")
        model = VGG16()
    elif model_type == "mobile":
        from model_mobile import MobileNet
        print("Using pre-trained MobileNet model...")
        model = MobileNet()
    elif model_type == "nasnet":
        from model_nasnet import NASNet
        print("Using pre-trained NASNetMobile model...")
        model = NASNet()
#    elif model_type == "densenet":
#        from model_densenet import DenseNet
#        print("Using pre-trained DenseNetMobile model...")
#        model=DenseNet()
    elif model_type == "xception":
        from model_xception import Xception
        print("Using pre-trained Xception model...")
        model = Xception()

    # summarize layers
    # print(model.summary())

    # Compile the model
    optimizer = tf.keras.optimizers.Nadam(lr=0.002)
    model.compile(optimizer=optimizer,
                  loss={'output_media': 'categorical_crossentropy',
                        'output_emotion': 'categorical_crossentropy'},
                  loss_weights={'output_media': 1, 'output_emotion': 1.},
                  metrics=['accuracy'])

    # Save training results to a log file
    log_file = os.path.join(log_folder, 'training_log.csv')
    csv_logger = tf.keras.callbacks.CSVLogger(log_file)

    # Create tensorboard
    tsb_dir = os.path.join(log_folder, 'tensorboard')
    tsb_logger = tf.keras.callbacks.TensorBoard(log_dir=tsb_dir,
                                                histogram_freq=0,
                                                batch_size=batch_size,
                                                write_graph=False,
                                                write_grads=False,
                                                write_images=False)

    # Store best models during training
    media_ckpt_file = os.path.join(log_folder, 'media_ckpt_best.h5')
    media_ckpt = tf.keras.callbacks.ModelCheckpoint(media_ckpt_file,
                                              monitor='val_output_media_acc',
                                              verbose=1, save_weights_only=False,
                                              save_best_only=True, mode='auto',
                                              period=1)

    emotion_ckpt_file = os.path.join(log_folder, 'emotion_ckpt_best.h5')
    emotion_ckpt = tf.keras.callbacks.ModelCheckpoint(emotion_ckpt_file,
                                              monitor='val_output_emotion_acc',
                                              verbose=1, save_weights_only=False,
                                              save_best_only=True, mode='auto',
                                              period=1)

    # Train the model
    model.fit(x, {'output_media': y_media, 'output_emotion': y_emotion},
               epochs=num_epochs, batch_size=batch_size,
               validation_data=(x_val, [y_media_val, y_emotion_val]),
               callbacks=[csv_logger, tsb_logger, media_ckpt, emotion_ckpt])

    # Save the final model
    model_file = os.path.join(log_folder, 'last_ckpt.h5')
    model.save(model_file)


 #Primeiro passo: criar a função

def ano_bi(ano):
    if ano % 4 != 0:
        return False
    elif ano % 100 != 0:
        return True
    elif ano % 400 != 0:
        return False
    else:
        return True

 #Segundo passo: criar listas, 2° lista com valores booleanos

dados_teste = [1900, 2000, 2016, 1987,2020]

resultados_reais = [False, True, True, False, True]

 #Terceiro passo: criar um loop, que: 'para i em tanto (len(dados_teste)):
                                                    #  |_ > len para ler a lista
 # yr ele atribuiu que é igual a lista de dados_teste porém com o valor de i
 # ele vai printar dentro do loop uma seta ( - > ) com end=" " (espaço)
 # cria uma variável result que é igual a ano_bi (função) + yr

for i in range(len(dados_teste)):
    yr = dados_teste[i]
    print(yr, '->', end=" ")
    result = ano_bi(yr)
    if result == resultados_reais[i]:
        print('OK')
    else:
        print('Falha')


import unittest

from em.bot import get_bot
from em.mmapi import send_message

class TestMattermostAPI(unittest.TestCase):
    bot = get_bot()

    def test_send_message(self):
        user_id = 'jxs5xm3b37djjfqohbtp4urpho'
        message = "I've matched token123@nix.co.il with your account.\n" \
                  "Next, click the button at the bottom of this message to get a verification email from cloudflare.\n" \
                  "You will only be sent a single email per address. You must complete verification to receive emails."
        actions = [
            {
                'id': 'hooks',
                'name': 'aaa',
                'integration': {
                    'url': 'http://email-manager.web.svc/hooks/send_email',
                    'context': {
                        'token': 'token123',
                    }
                }
            }
        ]
        result = send_message(self.bot.driver, user_id, message, actions)

        self.assertEqual(True, False)  # add assertion here

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