import pandas as pd
import numpy as np
from Node import Node

from sklearn.model_selection import train_test_split

class myDecisionTreeREPrune:

    def __init__(self, criterion, prune):
        self.criterion = criterion # Guarda o valor de criterion
        self.prune = prune # Guarda o valor do prune

    def fit(self, x_train, y_train):

        global dtf

        dtf = pd.DataFrame(data = x_train[0:, 0:], index=[i for i in range(x_train.shape[0])], columns=h1[0,0:])

        dtf.insert(len(dtf.columns), "class", y_train, True)

        print(dtf)

        global tree
        global target_class
        target_class = "class"

        tree = ID3(dtf, dtf, dtf.columns[:-1], target_class="class")

        print("\nPrint Tree")
        print_tree(tree, queue={})

        if (self.prune=="True"):
            # Teria de fazer o prune
            print("\nDevia fazer o prune...")

    def score(self, x_test, y_test):

        data = pd.DataFrame(data=x_test[0:, 0:], index=[i for i in range(x_test.shape[0])], columns=h1[0, 0:])

        data.insert(len(data.columns), "class", y_test, True)

        queries = data.iloc[:, :-1].to_dict(
            orient="records")  # Cria dicionario de queries organizados por [{coluna: valor, ...}], exemplo: [{outlook: sunny, ...}]

        previsoes = pd.DataFrame(columns=[
            "previsoes"])  # Cria uma DataFrame vazia em cuja a coluna chamada previsões guarda as previsões para cada querie

        for i in range(len(data)):  # Calcula a exatidao das previsões
            previsoes.loc[i, "previsoes"] = previs(queries[i], tree)

        resultado = np.sum(previsoes["previsoes"] == data["class"]) / len(data)

        return resultado

def entropy(target_col): # Calcula a Entropia

    elementos, el_ocorrencias = np.unique(target_col, return_counts=True)
    # elementos -> lista de elementos da colunas classe que existem para um determinado atributo
    # el_ocorrencias -> lista com nº de ocorrencias para cada elemento da lista acima

    for i in range(len(elementos)):
        entropy = np.sum([(-el_ocorrencias[i] / np.sum(el_ocorrencias)) * np.log2(el_ocorrencias[i] / np.sum(el_ocorrencias))])

    return entropy

def gini(target_col): # Calcula o Gini

    elementos, el_ocorrencias = np.unique(target_col, return_counts=True)

    if len(elementos) == 1:
        gini = 0
        return gini

    gini = 1

    for i in range(len(elementos)):
        gini = gini * (el_ocorrencias[i] / np.sum(el_ocorrencias))

    return gini

def InfoGain(data, split_attribute_name, target_name):
    """
    Calcula a info_gain para a data. Recebe 3 parametros:
    1. data = É data para cada atributo que o IG deve calcular
    2. split_attribute_name = nome do atributo split
    3. target_name = o nome da coluna da target_classe, decidimos usar como default o nome de "class" para a coluna target.
    """
    total_entropy = entropy(data[target_name]) # Calcula a entropia da database total

    total_gini = gini(data[target_name]) # Calcula o gini da database total

    # Depois do split, calcula para cada atributo existente o numero de ocorrencias
    atr, atr_ocorr = np.unique(data[split_attribute_name], return_counts=True)

    # Calcula o peso da entropia
    Peso_Entropy = np.sum(
        [(atr_ocorr[i] / np.sum(atr_ocorr)) * entropy(data.where(data[split_attribute_name] == atr[i]).dropna()[target_name])
         for i in range(len(atr))])

    # Calcula o peso do gini
    Peso_Gini = np.sum(
        [(atr_ocorr[i] / np.sum(atr_ocorr)) * 2 * gini(
            data.where(data[split_attribute_name] == atr[i]).dropna()[target_name])
         for i in range(len(atr))])

    # Calcula a Info_Gain depedendo do paramentro do classifier ("entropy" ou "gini")
    if (classifier.criterion == "entropy"):

        Information_Gain = total_entropy - Peso_Entropy

    elif (classifier.criterion == "gini"):

        Information_Gain = total_gini - Peso_Gini

    return Information_Gain

def ID3(data, original_data, features, target_class):
    """
    ID3 Algorithm: Esta função tem 4 argumentos:
    1. data = data que vai sendo alterada dependendo do atributo escolhido
    2. original_data = É a data original que se mantem sempre inalterada
    3. features = conjunto de atributos do data
    4. target_class = o nome da classe target, definida por nos como default = "class"
    """

    root = Node(None)

    if len(np.unique(data[target_class])) <= 1: # Se todos os valores do atributo forem iguais retorna esse mesmo valor
        return np.unique(data[target_class])[0]

    elif len(data) == 0: # Se a data estiver vazia retorna o valor maior/mais provavel presente na original_data
        return np.unique(original_data[target_class])[
            np.argmax(np.unique(original_data[target_class], return_counts=True)[1])]

    elif len(features) == 0:
        root = Node(None)
        return root

    else:

        # Seleciona o atributo que melhor divide a data
        item_values = [InfoGain(data, feature, target_class) for feature in
                       features]  # Retorna a info_gain para cada atributo

        best_feature_index = np.argmax(item_values) # Guarda o indice do melhor atributo

        best_feature = features[best_feature_index] # Guarda o melhor atributo

        root.label = best_feature # Inicializa a arvore. A raiz/root vai ser o nome do atributo classificado como (best_feature)

        features = [i for i in features if i != best_feature] # Remove o atributo com melhor info_gain da lista de atributos

        for value in np.unique(data[best_feature]):

            value = value

            sub_data = data.where(data[best_feature] == value).dropna() # Faz split da data ao longo dos valores dos atributos com mais info_gain e cria as sub_data

            subtree = ID3(sub_data, data, features, target_class) # Chama o algortimo ID3 recursivamente para cada sub_data com os novos parametros

            root.children[value] = subtree # Adiciona a subtree

        return root

def maxprob(original_data, target_class):
    return np.unique(original_data[target_class])[
        np.argmax(np.unique(original_data[target_class], return_counts=True)[1])]

def previs(query, tree):

    for key in list(query.keys()):

        if key == tree.label:
            temp = query[key]
            if temp in list(tree.children.keys()):

                try:
                    result = tree.children.get(temp)

                except:
                    return maxprob(dtf, target_class)

                result = tree.children.get(temp)

                if isinstance(result, dict):
                    return previs(query, result)

                elif isinstance(result, Node):
                    return previs(query, result)

                else:
                    return result

def print_tree(tree, queue):

    if tree.label != None:
        print(tree.label)

    queue.update(tree.children)
    print(tree.children)
    kkeys = list(queue.keys())

    for x in range(len(kkeys)):

        if type(queue[kkeys[x]]) is not Node:
            del queue[kkeys[x]]

        elif type(queue[kkeys[x]]) is Node:
            tree = queue[kkeys[x]]
            del queue[kkeys[x]]
            return print_tree(tree, queue)

if __name__ == '__main__':

    data = np.genfromtxt("weather.nominal.csv", delimiter=",", dtype=None, encoding=None)

    global h1
    h1 = data[0:1, 0:-1]

    xdata = data[1:, 0:-1]  # dados: da segunda à ultima linha, da primeira à penúltima coluna

    ydata = data[1:, -1]  # classe: da segunda à ultima linha, só última coluna

    x_train, x_test, y_train, y_test = train_test_split(xdata, ydata, random_state=0)

    classifier = myDecisionTreeREPrune(criterion="entropy", prune="False")

    classifier.fit(x_train, y_train)

    result = classifier.score(x_test, y_test)

    print("\nPercentagem de casos corretamente classificados {:2.2%}".format(result))


import random

def hangman(word):  # Функция с игрой, параметр - слово, которое нужно отгадать
    words = ['idiot', 'retard', 'motherfucker', 'asshole', 'bastard']
    random_word = random.randint(0, 4)
    word = words[random_word]
    wrong = 0  # Кол-во ошибок в отгадывании букв
    stages = ['',  # Список с рисунком человека
              '________        ',
              '|               ',
              '|         |     ',
              '|         0     ',
              '|        /|\    ',
              '|         |     ',
              '|        / \    ',
              '|               '
              ]
    rletters = list(word)  # Переменная со списком неотгаданных букв
    board = ['__'] * len(word)  # Переменная, отвечающая за подсказки (отгаданные буквы) и выводящая _
    win = False  # Чтобы сразу не победил
    print('Welcome to the execution!')  # Начало игры
    while wrong < len(stages) - 1:  # Игра продолжается пока кол-во неправильных букв меньше кол-ва строк в рисунке
        print('\n')  # Сразу выводим пустую область для украшения
        msg = 'Input a letter: '  # Принимаем догадку игрока
        guess = input(msg)  # Сохраняем догадку в переменной
        if guess in rletters:  # Если догадка есть в списке неотгаданных букв
            cind = rletters.index(guess)  # Назначаем переменной индекс отгаданной буквы в самом слове
            board[cind] = guess  # Вставляем отгаданную букву в список слова
            rletters[cind] = '$'  # Если в слове 2 одинаковых буквы, первую заменяем на $
        else:  # Догадка была неправильной
            wrong += 1  # Увеличиваем значение на 1
        print((' '.join(board)))  # Выводим строчку с рез-том угадывания
        e = wrong + 1  # Назначаем переменную индекса с кол-вом ошибок + 1
        print('\n'.join(stages[0: e]))  # Делаем срез строки с человечком от 0 до wrong + 1
        if '__' not in board:  # Если мы отгадали все буквы
            print('You won! The word was: ')
            print(''.join(board))  # Выводим слово
            win = True  # Прерываем цикл
            break
    if not win:  # Если проиграл
        print('\n'.join(stages[0: wrong]))  # Выводится рисунок полностью
        print('You lost! The word was: '
              '{}.'.format(word))  # Вывод строки с указанием слова, которое игрок не смог угадать

hangman('execution')


import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import sympy as sp

x_0 = [1.0,1.0]

x1,x2,f = sp.symbols('x1,x2,f')

f = (x1 + x2**2)**2 #Symbolic representation of f(x1,x2)

grad_f = [sp.diff(f,x1),sp.diff(f,x2)] #Symbolic representation of the gradient

hessian = np.array([[sp.diff(sp.diff(f,x1),x1),sp.diff(sp.diff(f,x1),x2)], \
					[sp.diff(sp.diff(f,x2),x1),sp.diff(sp.diff(f,x2),x2)]])

def eval_grad(x_k):
	'''Takes in two points, and evaluates the predefined symbolic represetation of the gradient at those points
		and returns the subsequent tuple'''

	p1 = grad_f[0].subs([(x1,x_k[0]),(x2,x_k[1])]).evalf()
	p2 = grad_f[1].subs([(x1,x_k[0]),(x2,x_k[1])]).evalf()

	return (p1,p2)

def eval_function(x_k):
	''' #Returns tuple after evaluating symbolic representation of f at x_k'''

	return f.subs([(x1,x_k[0]),(x2,x_k[1])]).evalf()

def eval_hessian(point1,point2):
	'''Returns 2x2 numpy array of the symbolic hessian function evaluated at (point1,point2)'''

	p1_1 = hessian[0][0].subs([(x1,point1),(x2,point2)]).evalf()
	p1_2 = hessian[0][1].subs([(x1,point1),(x2,point2)]).evalf()
	p2_1 = hessian[1][0].subs([(x1,point1),(x2,point2)]).evalf()
	p2_2 = hessian[0][1].subs([(x1,point1),(x2,point2)]).evalf()

	return np.array([[p1_1,p1_2],[p2_1,p2_2]])

x_k = x_0

x_k_list = []
x_k_list.append(x_k)

function_value = eval_function(x_0) #inital value of the function

f_list = []
f_list.append(function_value)

while function_value > 1E-8:

	gradient = eval_grad(x_k)

	grad_norm = np.sqrt(float(gradient[0]**2 + gradient[1]**2))

	p_k = (-1.0) * (gradient / grad_norm)

	#~~~~~~~~Backtracking~~~~~~~~~~~~~~~~~#

	alpha_bar = 1
	rho = 0.5
	c = 1E-4
	alpha = alpha_bar

	function_value = eval_function(x_k + p_k * alpha)

	test_value = eval_function(x_k) + c * alpha * p_k.dot(gradient)

	while function_value > test_value:

		alpha = rho * alpha

		function_value = eval_function(x_k + p_k * alpha)

		test_value = eval_function(x_k) + c * alpha * p_k.dot(gradient)

	#~~~~~~~~End Backtracking~~~~~~~~~~~~~~~~~#

	alpha_k = alpha #This is the alpha to use for this step in the process

	function_value = eval_function(x_k) #regaining current value of the function for logging purposes

	print("alpha_k = {}, x_k = {}, function_value = {}, p_k = {}".format(alpha_k,x_k,function_value,p_k)) #Correct order of things

	x_k = x_k + alpha_k*p_k

	x_k_list.append(x_k)
	f_list.append(function_value)

#Plot original function

fig = plt.figure()
ax = fig.gca(projection='3d')

X = np.arange(-1.5, 1.5, 0.01)
Y = np.arange(-1.5, 1.5, 0.01)
X, Y = np.meshgrid(X, Y)

Z = (X + Y**2)**2

surf = ax.plot_surface(X, Y, Z,cmap=cm.coolwarm,linewidth=-1, antialiased=True)

#plot the x_k values

for i in range(len(x_k_list)):
	ax.scatter(x_k_list[i][0],x_k_list[i][1],f_list[i],c= 'black',marker = '^',s = 25)# place down x_k markers

xs = [x_k_list[i][0] for i in range(len(x_k_list))]
ys = [x_k_list[i][1] for i in range(len(x_k_list))]

ax.plot(xs,ys,f_list,c = 'red')

plt.show()


import scrapy
from datetime import datetime
from datetime import timedelta

from craigslist.items import CraigslistItem

lastrun = None

class CraigslistSpider(scrapy.Spider):
    name = "craigslist"
    allowed_domains = ["pullman.craigslist.org"]
    start_urls = ["https://pullman.craigslist.org/rnr"]
    global lastrun
    try:
        with open("lastrun") as f:
            lastrun = f.read().strip()
            lastrun = datetime.strptime(lastrun, '%Y-%m-%d %H:%M:%S')

    except (IOError, ValueError):
        lastrun = datetime.now() - timedelta(days=1)

    with open("lastrun", "w") as f:
        now = datetime.now()
        now = str(now).split('.')[0]
        f.write(now)

    def parse(self, response):
        cl_rows = response.xpath('//*[@id="sortable-results"]/div[@class="rows"]/p')
        for row in cl_rows:
            item = CraigslistItem()
            item['url'] = response.urljoin(row.xpath('./a/@href').extract()[0])
            item['time_posted'] = row.xpath('.//*/time/@datetime').extract()[0]
            posted_date = datetime.strptime(item['time_posted'], '%Y-%m-%d %H:%M')
            delta = lastrun-posted_date
            if delta.days < 0:
                yield scrapy.Request(item['url'], callback=self.parse_post, meta={'item': item})
            else:
                pass

    def parse_post(self, response):
        item = response.meta['item']
        item['title'] = response.xpath('//*[@id="pagecontainer"]//*/span[@id="titletextonly"]/text()').extract()[0]
        item['content'] = ''.join(response.xpath('//*[@id="postingbody"]/text()').extract())
        yield item


#! /usr/bin/env python
#
# Copyright (c) 2011 Jason Ish
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from __future__ import print_function

import os
import os.path
import io

import idstools.rule

class Ruleset(object):

    def __init__(self, config):
        self.config = config
        self.directory = os.path.abspath(
            os.path.join("sources", self.config["name"]))

        # Rules keyed by (gid, sid).  Loaded by load_rules.
        self.rules = {}

        # Cache for the filenames.
        self._filenames = None

    def get_filenames(self):

        if self._filenames is not None:
            return self._filenames

        self._filenames = []

        for dirpath, dirnames, filenames in os.walk(self.directory):
            for filename in filenames:
                path = os.path.join(dirpath[len(self.directory) + 1:], filename)
                if not path in self.config["ignore-files"]:
                    self._filenames.append(path)

        return self._filenames

    def total_count(self):
        return len(self.rules)

    def enabled_count(self):
        return len([rule for rule in self.rules.values() if rule.enabled])

    def get_fileobj(self, filename):
        return open(os.path.join(self.directory, filename), "rb")

    def load_rules(self):
        for filename in self.get_filenames():
            if not filename.endswith(".rules"):
                continue
            for rule in idstools.rule.parse_fileobj(
                    self.get_fileobj(filename), filename):
                if rule.id in self.rules:
                    print("warning: duplicate rule id found")
                else:
                    self.rules[rule.id] = rule

    def set_policy(self, policy):
        for rule in self.rules.values():
            if policy in self.get_policies(rule):
                rule.enabled = True
            else:
                rule.enabled = False

    def get_policies(self, rule):
        policies = []
        for item in rule.metadata:
            if item.startswith("policy"):
                parts = item.split()
                policies.append(parts[1])
        return policies


# coding=utf-8
import importlib
import json
from collections import OrderedDict

from django.core.paginator import Paginator
import re
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.template import loader, TemplateDoesNotExist, RequestContext
from django.template.defaultfilters import slugify
from django.utils.translation import LANGUAGE_SESSION_KEY
from django.views.generic import TemplateView, DetailView, View
from django.conf import settings
from django.views.generic.detail import BaseDetailView
from elasticsearch_dsl import Search, Q
from django.contrib import messages
from solotodo.forms.product_new_rating_form import ProductNewRatingForm
from solotodo.forms.product_price_history_form import ProductPriceHistoryForm
from solotodo.forms.product_redirect_to_store_form import \
    ProductRedirectToStoreForm
from solotodo.models import Country, ProductType, Store, Product
from solotodo.models.product_type_ranking import ProductTypeRanking
from solotodo.utils import milliseconds_since_epoch, \
    is_mobile_to_media_id
from decimal import Decimal

class IndexView(TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        from frontpage_slider.models import FrontpageContent
        from hardware.models import Budget

        context = super(IndexView, self).get_context_data(**kwargs)

        conn = settings.CONNECTOR

        country = self.request.session.get('country', Country.get_default())

        secondary_products = Product.objects.filter(
            instance_model__unicode_representation__icontains='prepago')

        # Popular

        popular_products_raw = conn.query_products_with_ordering(
            ordering='visits',
            countries=[country],
            product_types=[pt.id for pt in ProductType.objects.all()],
            secondary_products=secondary_products,
            limit=10
        )[0]

        popular_products_html = []

        for product_entry in popular_products_raw:
            popular_products_html.append(
                product_entry[0].suggested_alternative_display(
                    country, product_entry[1][0][1],
                    'Visto ' + str(product_entry[2]) + ' veces!'))

        # Offers

        offer_products_raw = conn.query_products_with_ordering(
            ordering='discount',
            countries=[country],
            product_types=[pt.id for pt in ProductType.objects.all()],
            secondary_products=secondary_products,
            limit=10
        )[0]

        offer_products_html = []

        for product_entry in offer_products_raw:
            offer_products_html.append(
                product_entry[0].suggested_alternative_display(
                    country, product_entry[1][0][1],
                    'Bajó ' + str(int(round(product_entry[2]))) + '%!'))

        context['popular_products'] = popular_products_html
        context['offer_products'] = offer_products_html
        context['MEDIA_URL'] = settings.MEDIA_URL
        context['articles'] = FrontpageContent.get_latest()
        context['budgets'] = Budget.frontpage_selections(country)
        context['dfp_category'] = 'Home'

        return context

class SessionChangeCountryView(View):
    def get(self, request, country_code, *args, **kwargs):
        c = get_object_or_404(Country, code=country_code)
        self.request.session['country'] = c
        self.request.session[LANGUAGE_SESSION_KEY] = c.language_code

        next_url = self.request.GET.get('next', reverse('index'))
        return HttpResponseRedirect(next_url)

class UserPaymentMethodsAndStoresMixin(object):
    """
    Adds the functionality to quickly select the user available paymet methods
    and preferred stores from any view
    """

    def get_payment_methods_and_stores(self, user):
        if user.is_authenticated():
            profile = user.userprofile
            payment_methods = profile.payment_methods.all()
            stores = profile.stores.all()
        else:
            payment_methods = None
            stores = None

        return payment_methods, stores

class ProductTypeDetailView(UserPaymentMethodsAndStoresMixin, DetailView):
    model = ProductType
    template_name = 'product_type_detail.html'

    def additional_context(self):
        result = {}

        if self.object.pk in settings.LG_REMARKETING['PRODUCT_TYPES']:
            result['lg_remarketing_tracking_code'] = \
                settings.LG_REMARKETING['TRACKING_CODE']

        return result

    def get_country_currency(self):
        return None

    def get_context_data(self, **kwargs):
        context = super(ProductTypeDetailView, self).get_context_data(**kwargs)

        form_class = self.object.searchformmodel.get_form()

        country = self.request.session.get('country', Country.get_default())

        # First attempt: Make the search form completely from the GET data
        form = form_class(country, self.request.GET)

        if not form.is_valid():
            # Second attempt: Make a pre-filled form and only update the
            # parameters that have changed.
            form_data = form_class.get_default_form(country).data
            form_data.update(self.request.GET.dict())
            form_data['products'] = self.request.GET.getlist('products')

            form = form_class(country, form_data)
            if not form.is_valid():
                # Third attempt, just use the default form
                form = form_class.get_default_form(country)

        payment_methods, stores = \
            self.get_payment_methods_and_stores(self.request.user)

        products_data = form.get_products(
            payment_methods, stores, [country])

        min_price = form.result_min_price
        max_price = form.result_max_price

        form.update_price_range(min_price, max_price)

        start_index, end_index = form.get_results_range_indices(products_data)

        context['start_index'] = start_index
        context['end_index'] = end_index

        country_currency = self.get_country_currency()

        products_html = []
        for product_data in products_data:
            products_html.append(product_data[0].render_as_search_result(
                product_data[1], country, country_currency))

        context['products_html'] = products_html

        context['form'] = form
        context['google_analytics_visit_type'] = 'Category search'
        context['google_analytics_product_type'] = unicode(self.object)
        context['dfp_category'] = unicode(self.object.meta_model)

        context.update(self.additional_context())

        return context

class ProductDetailView(UserPaymentMethodsAndStoresMixin, DetailView):
    model = Product
    template_name = 'product_details.html'

    def get_template_names(self):
        if self.object.product_type.id == 6:
            return ['cell_details.html']
        else:
            return ['product_details.html']

    def get(self, request, **kwargs):
        self.object = self.get_object()
        if self.request.path != self.object.get_absolute_url():
            return HttpResponseRedirect(self.object.get_absolute_url())
        else:
            return super(ProductDetailView, self).get(request, **kwargs)

    def get_country_currency(self):
        return None

    def get_context_data(self, **kwargs):
        from django.conf import settings

        context = super(ProductDetailView, self).get_context_data(**kwargs)

        payment_methods, stores = \
            self.get_payment_methods_and_stores(self.request.user)

        country = self.request.session['country']

        product = self.object

        active_prices = product.active_prices(
            payment_methods, stores, [country])

        store_prices = []
        store_for_ratings = []

        secondary_products_ids = []

        for store, prices in active_prices:
            store_for_ratings.append(store)
            secondary_products_ids.extend(e[0] for e in prices)

        store_ratings = Store.batch_average_ratings(store_for_ratings)

        resolution = Decimal('0.01')

        base_redirect_url = reverse('product_redirect_to_store',
                                    kwargs={'pk': product.id})

        secondary_products_dict = dict(
            [(p.id, p) for p in Product.objects.filter(
                pk__in=secondary_products_ids)])

        s = Search(using=settings.ES, index=settings.ES_INDEX)
        elastic_result = s.query("match",
                                 product_id=product.id).execute().hits[0]

        country_currency = self.get_country_currency()
        country_for_formatting = country
        if country_currency:
            country_for_formatting = country_currency

        for store, prices in active_prices:
            rating = store_ratings[store]
            product_prices = []
            if rating:
                rating = str(rating.quantize(resolution))
            for secondary_product_id, secondary_product_offer_price, \
                    secondary_product_normal_price in prices:
                if country_currency:
                    secondary_product_normal_price = \
                        country_currency.convert_currency(
                            secondary_product_normal_price, country)
                    secondary_product_offer_price = \
                        country_currency.convert_currency(
                            secondary_product_offer_price, country)

                formatted_offer_price = \
                    country_for_formatting.format_currency(
                        secondary_product_offer_price)
                formatted_normal_price = \
                    country_for_formatting.format_currency(
                        secondary_product_normal_price)
                secondary_product_url = \
                    base_redirect_url + '?store=' + str(store.id)

                if secondary_product_id:
                    secondary_product = secondary_products_dict[
                        secondary_product_id]
                    secondary_product_url += '&secondary_product=' + \
                                             str(secondary_product_id)
                else:
                    secondary_product = None
                product_prices.append(
                    (secondary_product,
                     (secondary_product_offer_price, formatted_offer_price),
                     (secondary_product_normal_price, formatted_normal_price),
                     secondary_product_url))

            store_prices.append(
                (unicode(store), store.id, product_prices,
                 rating, reverse('store_ratings', kwargs={'pk': store.id})))

        target_price = None
        if active_prices:
            target_price = active_prices[0][1][0][1]

        suggested_alternatives, search_url = product.get_suggested(
            elastic_result,
            target_price,
            payment_methods,
            stores,
            [country]
        )

        rankings = ProductTypeRanking.objects.filter(
            product_type=product.product_type
        ).order_by('ordering')

        rankings_with_css = []

        for ranking in rankings:
            max_score = ranking.max_score
            try:
                score = elastic_result[ranking.es_field]
            except KeyError:
                score = 0
            if score >= max_score * 0.75:
                css_name = 'primary'
            elif score >= max_score * 0.5:
                css_name = 'success'
            elif score >= max_score * 0.25:
                css_name = 'warning'
            else:
                css_name = 'danger'

            rankings_with_css.append((ranking, css_name, score,
                                      min(int(100.0*score/max_score), 100)))

        suggested_alternatives_html = []

        for suggested_product, price in suggested_alternatives:
            suggested_alternatives_html.append(
                suggested_product.suggested_alternative_display(
                    country, price))
        rating = product.average_rating()
        if rating:
            rating = str(rating.quantize(Decimal('0.1')))

        comment_disclaimer = False

        if product.instance_model.model.name in settings.PRODUCT_TYPE_HARDWARE:
            comment_disclaimer = True

        # Obtain the product variations

        variations = product.get_bucket(payment_methods, stores)

        alternatives_dict = {}
        for variation in variations:
            for key, association in variation['associations'].items():
                alternatives_dict[key] = []
                for alternative in association['alternatives']:
                    alternatives_dict[key].append(
                        {
                            'name': unicode(alternative),
                            'url': alternative.get_absolute_url()
                        }
                    )

        context['product'] = product
        context['rating'] = rating
        context['render_details'] = product.render_as_details()
        context['store_prices'] = store_prices
        context['suggested_alternatives_html'] = suggested_alternatives_html
        context['suggested_alternatives_url'] = search_url
        context['disqus_identifier'] = product.id
        context['product_price_history_form'] = ProductPriceHistoryForm()
        context['static_url'] = settings.STATIC_URL
        context['elastic_doc'] = elastic_result
        context['rankings'] = rankings_with_css
        context['google_analytics_visit_type'] = 'Product detail'
        context['google_analytics_product_type'] = \
            unicode(product.product_type)
        context['comment_disclaimer'] = comment_disclaimer
        context['variations'] = variations
        context['alternatives_dict'] = json.dumps(alternatives_dict)
        context['dfp_category'] = unicode(product.product_type.meta_model)

        for function_path in settings.ADDITIONAL_PRODUCT_DETAILS_CONTEXT:
            path_components = function_path.split('.')
            module = importlib.import_module('.'.join(path_components[:-1]))
            additional_context_function = getattr(module, path_components[-1])
            additional_context = additional_context_function(
                context, self.request.GET, payment_methods, stores,
                country)
            if additional_context:
                context.update(additional_context)

        context.update(self.additional_context(product, elastic_result))

        return context

    def additional_context(self, product, elastic_doc):
        result = {}

        if product.product_type.pk in settings.LG_REMARKETING['PRODUCT_TYPES']:
            result['lg_remarketing_tracking_code'] = \
                settings.LG_REMARKETING['TRACKING_CODE']

        return result

class ProductRedirectToStoreView(UserPaymentMethodsAndStoresMixin,
                                 BaseDetailView):
    model = Product

    def get(self, request, *args, **kwargs):
        product = self.get_object()
        payment_methods = self.get_payment_methods_and_stores(
            self.request.user
        )[0]
        form = ProductRedirectToStoreForm(request.GET)

        if form.is_valid():
            conn = settings.CONNECTOR

            store = form.cleaned_data['store']
            secondary_product = form.cleaned_data['secondary_product']

            if store:
                stores = [store]
            else:
                stores = []

            if secondary_product:
                secondary_products = [secondary_product]
            else:
                secondary_products = []

            is_sponsored = bool(form.cleaned_data['is_sponsored'])

            result = conn.product_best_store_data(
                product,
                secondary_products,
                payment_methods,
                stores,
                # [request.session['country']],
                is_sponsored=is_sponsored,
            )

            url = result['url']
            coupon_code = result['coupon_code']

            if not url:
                raise Http404

            product.register_external_visit(store, self.request.user,
                                            is_sponsored)

            if coupon_code:
                if result['coupon_requires_instructions']:
                    try:
                        template = loader.get_template(
                            'coupons/{0}.html'.format(slugify(coupon_code)))
                    except TemplateDoesNotExist:
                        template = loader.get_template(
                            'redirect_to_store.html')

                    context = RequestContext(request, {
                        'url': url,
                        'coupon_code': coupon_code,
                    })
                    return HttpResponse(template.render(context))
                else:
                    return HttpResponseRedirect(url)
            elif store and store.pk == 15:
                template = loader.get_template('sistemax_redirect.html')
                context = RequestContext(request, {
                    'url': url,
                    'product': product
                })
                return HttpResponse(template.render(context))
            else:
                # Finally... redirect to the store website
                return HttpResponseRedirect(url)

        raise Http404

class StoreRatingsView(DetailView):
    model = Store
    template_name = 'store_ratings.html'

    def get_context_data(self, **kwargs):
        context = super(StoreRatingsView, self).get_context_data(**kwargs)

        store = self.object
        conn = settings.CONNECTOR

        ratings = conn.get_product_store_ratings(store=store)

        average_rating = Decimal(0)
        for r in ratings:
            average_rating += r['store_rating']

        if ratings:
            average_rating /= len(ratings)
            average_rating = str(average_rating.quantize(Decimal('0.1')))
        else:
            average_rating = None
        context['store'] = store
        context['ratings'] = ratings
        context['average_rating'] = average_rating
        context['static_url'] = settings.STATIC_URL
        context['dfp_category'] = 'Home'

        return context

class ProductRatingsView(DetailView):
    model = Product
    template_name = 'product_ratings.html'

    def get_context_data(self, **kwargs):
        context = super(ProductRatingsView, self).get_context_data(**kwargs)

        product = self.object
        conn = settings.CONNECTOR

        ratings = conn.get_product_store_ratings(product=product)

        average_rating = Decimal(0)
        for r in ratings:
            average_rating += r['product_rating']

        if ratings:
            average_rating /= len(ratings)
            average_rating = str(average_rating.quantize(Decimal('0.1')))
        else:
            average_rating = None

        context['ratings'] = ratings
        context['average_rating'] = average_rating
        context['static_url'] = settings.STATIC_URL
        context['dfp_category'] = unicode(product.product_type.meta_model)

        return context

class ProductNewRatingView(DetailView):
    model = Product
    template_name = 'product_new_rating.html'

    def get_context_data(self, **kwargs):
        context = super(ProductNewRatingView, self).get_context_data(**kwargs)

        form = ProductNewRatingForm(self.object)

        context['form'] = form
        context['static_url'] = settings.STATIC_URL
        context['site'] = 'Solotodo'
        context['dfp_category'] = unicode(self.object.product_type.meta_model)

        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = ProductNewRatingForm(self.object, request.POST, request.FILES)

        if form.is_valid():
            form.submit()
            messages.success(request, u'Rating enviado exitosamente ¡Gracias!')
            return HttpResponseRedirect(
                self.object.get_absolute_url()
            )
        else:
            context = self.get_context_data()
            context['form'] = form

            return self.render_to_response(context)

class ProductRegisterVisitView(BaseDetailView):
    model = Product

    def post(self, *args, **kwargs):
        self.get_object().register_visit(self.request.user)
        return HttpResponse()

    def get(self, *args, **kwargs):
        return HttpResponse()

class ProductCloneView(BaseDetailView):
    model = Product

    def get(self, request, *args, **kwargs):
        product = get_object_or_404(Product, pk=kwargs['pk'])
        cloned_product = product.clone(request.user.id)
        cloned_product_url = reverse('metamodel_instance_detail',
                                     args=[cloned_product.instance_model.id])
        return HttpResponseRedirect(cloned_product_url)

class JSONResponseMixin(object):
    """
    Adds JSON export capabilities to a view.

    On request renders the 'json_payload' of the context
    """
    def render_to_response(self, context):
        return self.get_json_response(self.convert_context_to_json(context))

    def get_json_response(self, content, **httpresponse_kwargs):
        return HttpResponse(content, content_type='application/json',
                            **httpresponse_kwargs)

    def convert_context_to_json(self, context):
        return json.dumps(context['json_payload'], indent=4)

class ProductPriceHistoryView(JSONResponseMixin,
                              UserPaymentMethodsAndStoresMixin,
                              BaseDetailView):
    """
    Returns the prices for the given product for each date given in
    the parameters for this URL given in the range defined in
    ProductPriceHistoryForm

    The results are filtered by the payment methods and stores
    selected by the user in his/her control panel.
    """

    model = Product

    def get_context_data(self, **kwargs):
        context = super(ProductPriceHistoryView, self).get_context_data(
            **kwargs)

        payment_methods, stores = self.get_payment_methods_and_stores(
            self.request.user)

        form = ProductPriceHistoryForm(self.request.GET)

        if form.is_valid():
            conn = settings.CONNECTOR

            # If we are given a specific store, grab the prices only for
            # that store. Otherwise use the existing value, that is, the
            # stores the user has selected in his control panel.
            form_store = form.cleaned_data['store']

            if form_store:
                stores = [form_store]

            result = conn.query_product_price_history(
                self.object,
                form.cleaned_data['start_date'],
                form.cleaned_data['end_date'],
                payment_methods,
                stores,
                [self.request.session['country']]
            )

            data = []

            for serie_name, date_prices in result.items():
                subresult = {
                    'name': serie_name
                }

                subresult_data = []
                for date_price in date_prices:
                    formatted_price = date_price[1]
                    if isinstance(formatted_price, Decimal):
                        formatted_price = int(formatted_price)

                    subresult_data.append([
                        milliseconds_since_epoch(date_price[0]),
                        formatted_price
                    ])

                subresult['data'] = subresult_data

                data.append(subresult)

        else:
            data = []

        context['json_payload'] = data
        return context

class ProductRedirectCellsView(DetailView):
    model = Product

    def get(self, request, *args, **kwargs):
        next_url = reverse('product_detail', kwargs=kwargs)
        return HttpResponseRedirect(next_url)

class ProductSearchKeywordsView(TemplateView,
                                UserPaymentMethodsAndStoresMixin):
    template_name = 'search_keywords.html'

    def additional_filters(self):
        return Q('match_all')

    def get_context_data(self, **kwargs):
        context = \
            super(ProductSearchKeywordsView, self).get_context_data(**kwargs)
        if 'keywords' in self.request.GET:
            keywords = self.request.GET['keywords']

            keywords = re.sub(r'\W+', ' ', keywords)

            results = Search(
                using=settings.ES,
                index=settings.ES_INDEX)

            query = self.additional_filters()

            for keyword in keywords.split():
                query &= Q('wildcard', keywords=u'*' + keyword.lower() + u'*')

            results = results.query(query)

            results = results[:10000].execute()

            payment_methods, stores = \
                self.get_payment_methods_and_stores(self.request.user)

            country = self.request.session['country']
            products = Product.objects.filter(
                id__in=[k.product_id for k in results])
            conn = settings.CONNECTOR
            products_prices = conn.query_products_with_ordering(
                'price',
                products=products,
                payment_methods=payment_methods,
                stores=stores,
                countries=[country]
            )[0]

            #############
            # Bucketing
            #############

            buckets_containers = conn.get_product_buckets(
                [e[0] for e in products_prices],
                query_type='search')

            product_bucket_dict = {}

            for bucket_container in buckets_containers:
                for bucket in bucket_container['buckets']:
                    bucket_key = tuple(bucket['bucket'])
                    for product in bucket['products']:
                        product_bucket_dict[product] = bucket_key

            product_prices_dict = {
                e[0].id: e for e in products_prices
            }

            bucketed_products_dict = OrderedDict()
            bucketed_products = []

            for product_es in results:
                entry = product_prices_dict.get(product_es.product_id, None)
                if not entry:
                    continue
                product = entry[0]

                key = product_bucket_dict[product]
                if not key:
                    bucketed_products.append(entry)

                if not key or key in bucketed_products_dict:
                    continue

                bucketed_products_dict[key] = entry
                bucketed_products.append(entry)

            # End bucketing

            products_html = []

            paginator = Paginator(bucketed_products, 12)

            try:
                page = int(self.request.GET.get('page'))
            except (ValueError, TypeError):
                page = 1

            if page < 0:
                page = 1
            elif page > paginator.num_pages:
                page = paginator.num_pages

            products_page = paginator.page(page)

            for product_data in products_page:
                products_html.append(product_data[0].render_as_search_result(
                    product_data[1], country))
            page_offset = 2

            page_range = [
                i for i in xrange(page - page_offset, page + (page_offset + 1))
                if 1 <= i <= paginator.num_pages]

            dots_subcontainer_initial = None
            dots_subcontainer_final = None

            if page_range and page_range[0] > page_offset - 1:
                dots_subcontainer_initial = \
                    '<li class="disabled"><a href=#>...</a></li>'

            if page_range and page_range[-1] < paginator.num_pages:
                dots_subcontainer_final = \
                    '<li class="disabled"><a href=#>...</a></li>'

            context.update({
                'products_html': products_html,
                'keywords': keywords,
                'keywords_user': self.request.GET['keywords'],
                'results_page': products_page,
                'page_range': page_range,
                'dot_container_initial': dots_subcontainer_initial,
                'dot_container_final': dots_subcontainer_final,
                'dfp_category': 'Home'
            })

            return context

class ChromeView(TemplateView):
    template_name = 'chrome.html'


from i3pystatus import Status
from i3pystatus.weather import weathercom
from i3pystatus.calendar import google
from i3pystatus.mail import imap

import logging

# check out i3pystatus.core.settings.get_setting_from_keyring()
# for implementing a keyring ourselves
from get_gpw import gkey
from get_cpw import ckey

status = Status(logfile='/home/yman/var/i3pystatus.log')

status.register("clock",
    format="📆 %D %a 🕒 %I:%M %p",)

status.register('weather',
    format='🌈 {condition} {current_temp}{temp_unit}[ {update_error}] 💦 {humidity}%',
    interval=900,
    colorize=True,
    hints={'markup': 'pango'},
    backend=weathercom.Weathercom(
        location_code='85721:4:US', # UofA
        #location_code='85704:4:US', # Apt
        units='imperial',
        update_error='!',
        log_level=logging.DEBUG,
    ),
)

status.register("calendar",
    format="📅 {title}",
    update_interval=10,
    urgent_blink=True,
    backend=google.Google(
        credential_path='/home/yman/.gcalcli_gmail/oauth',
        days=2))

status.register("calendar",
    format="📅 {title}",
    update_interval=10,
    urgent_blink=True,
    backend=google.Google(
        credential_path='/home/yman/.gcalcli_catmail/oauth',
        days=2))

status.register("cmus",
    format="🎵 {song_elapsed} {title}",
    format_not_running="")

status.register("pulseaudio",
    format="🔉 {volume}")

status.register("mail",
    email_client="/usr/bin/mutt",
    format="📨 Gmail: {unread} new email",
    format_plural="Gmail: {unread} new emails",
    backends=[imap.IMAP(
        host='imap.gmail.com',
        username='dlut.manym',
        keyring_backend=gkey,
        mailbox="[Gmail]/Important",
        account='dlut.manym@gmail.com')])

status.register("mail",
    email_client="/usr/bin/mutt",
    format="📨 Catmail: {unread} new email",
    format_plural="Catmail: {unread} new emails",
    backends=[imap.IMAP(
        host='imap.gmail.com',
        username='yman@email.arizona.edu',
        keyring_backend=ckey,
        account='yman@email.arizona.edu@gmail.com')])

#status.register("net_speed")

status.run()


# Notepaper - uses lines
from Glib import *
y = 60                          # Height at which to start
startdraw(400, 600)             # Begin drawing things
background(255)                 # Paper should be white
stroke (0, 0, 200)              # Fill color = pixel color = blue
for n in range (0, 27):         # Draw 30 horizontal blue lines
    line (0, y, Width(), y)     # Draw a blue horizontal line
    y = y + 20                  # The next line is 20 pixels down
stroke (200, 0, 0)              # Pixel color red
line (25, 0, 25, Height())      # Draw a vertical red line
enddraw()


#!/usr/bin/env python

from datetime import datetime
from pandas import DataFrame
from utils import parse_level_args, github_raw_dataframe, dataframe_output, merge_previous

# Confirmed and deaths come from different CSV files, parse them separately first
confirmed = github_raw_dataframe('cedricguadalupe/FRANCE-COVID-19', 'france_coronavirus_time_series-confirmed.csv')
deaths = github_raw_dataframe('cedricguadalupe/FRANCE-COVID-19', 'france_coronavirus_time_series-deaths.csv')
for df in (confirmed, deaths):
    df.set_index('Date', inplace=True)

# Iterate through all date-region combinations
regions = confirmed.columns.tolist()
df = DataFrame(columns=['Date', '_RegionLabel', 'Confirmed', 'Deaths']).set_index(['Date', '_RegionLabel'])
for region in regions:
    if region == 'Total': continue
    for date, value in zip(confirmed.index, confirmed[region]):
        df.loc[(date, region), 'Confirmed'] = value
    for date, value in zip(deaths.index, deaths[region]):
        df.loc[(date, region), 'Deaths'] = value

# Dates need converted to ISO format
df = df.sort_values(['Date', '_RegionLabel']).reset_index()
df['Date'] = df['Date'].apply(lambda date: datetime.strptime(date, '%d/%m/%Y').date().isoformat())

# Output the results
dataframe_output(df, 'FR')


# -*- coding: utf-8 -*-
"""
Created on Fri May  4 10:45:26 2018

@author: George
"""

from scipy import ndimage
from scipy import misc
import glob, os
import numpy as np

imgPath = r"C:\Users\George\Desktop\YOLO\buildingImages\zoom_17\gt"

#size = 200 #int gives 200%
size = 0.5 #float gives fration of size
#size = (2500,2500) #tuple gives actual size

os.chdir(imgPath)
fileList = []
for file in glob.glob("*.tif"):
    fileList.append(file)

for file in fileList:

    img = ndimage.imread(file, flatten=False)
    resize = misc.imresize(img, size, interp='bilinear', mode=None)
    saveName = file.split(".")[0] + ".jpg"
    misc.imsave(saveName,resize)


from copy import deepcopy

def expandOptionsToList(allOptions, loopKeysOrder=None):
    # print(allOptions)
    baseTable = {}
    loopKeys = []
    loopKeys_full = []
    loopValues = {}
    nValuesEachLoopKey = []
    nTablesTotal = 1
    debug = False

    loopFromFirstToLast = True

    #  find which variables are to be looped over, and gather in a separate table
    for key_full,val in allOptions.items():
        if key_full[:4] == 'tbl_':
            key = key_full[5:]

            loopKeys_full.append(key_full)
            loopKeys.append(key)

            # loopValues[keyName] = v
            if len(val) == 0:
                print('val', val)
                print('options', allOptions)

                raise ValueError('Key %s has 0 array entries\n' % key)

            if debug:
                print('key %s has %d entries' % (key, len(val)))

            nValuesEachLoopKey.append(len(val))
            nTablesTotal = nTablesTotal * (len(val))
        else:
            baseTable[key_full] = val

    if debug:
        print('NTotal = ', nTablesTotal)

    if loopKeysOrder is not None:
        if isinstance(loopKeysOrder, str):
            loopKeysOrder = [loopKeysOrder]

        if len(set(loopKeysOrder)) != len(loopKeysOrder):
            raise ValueError('Loop keys order table should have not have duplicate entries')

        putInFirst = True
        idx_loopKeys_setOrder_first = []
        idx_loopKeys_setOrder_last  = []
        for i, key in enumerate(loopKeysOrder):
            if key == '':
                putInFirst = False
            else:
                if key not in loopKeys:
                    raise ValueError('No such field %s in table' % key)
                idx = loopKeys.index(key)

                if putInFirst:
                    idx_loopKeys_setOrder_first.append(idx)
                else:
                    idx_loopKeys_setOrder_last.append(idx)

        loopKeys_other_idxs = [x for x in range(len(loopKeys))
                               if x not in idx_loopKeys_setOrder_first + idx_loopKeys_setOrder_last]
        # print('other=', loopKeys_other_idxs)
        idx_new_order = idx_loopKeys_setOrder_first + loopKeys_other_idxs + idx_loopKeys_setOrder_last

        loopKeys_full = [loopKeys_full[i] for i in idx_new_order]
        loopKeys = [loopKeys[i] for i in idx_new_order]
        nValuesEachLoopKey = [nValuesEachLoopKey[i] for i in idx_new_order]

            # print(loopKeys)
            # return;

    #  initialize loop variables
    nLoopFields = len(nValuesEachLoopKey)
    loopIndices = {}
    for i in range(nLoopFields):
        loopIndices[i] = 0  # 1

    # fieldIdxStart, fieldInc, fieldIdxStop
    if loopFromFirstToLast:
        fieldIdxStart = 0
        fieldInc = 0
        fieldIdxStop = nLoopFields+1   # TODO: check
    else:
        fieldIdxStart = nLoopFields
        fieldInc = -1
        fieldIdxStop = 0

    #  loop over all the loop-variables, assign to table.

    allTables = []
    for j in range(nTablesTotal):
        tbl_i = deepcopy(baseTable)

        allTables.append(tbl_i)

        if len(loopIndices) == 0:
            break

        for i in range(nLoopFields):

            if type(allOptions[loopKeys_full[i]]) != 'table':
                raise ValueError('Field %s is not a table' % (loopKeys_full[i]))

            vals_field_i = deepcopy( allOptions[loopKeys_full[i]] )

            if not '_and_' not in loopKeys[i]:
                tbl_i[loopKeys[i]] = vals_field_i[loopIndices[i]]
            else:
                sub_fields = loopKeys[i].replace('_and_', ',').split(',')
                #for sub_fld in string.gmatch(string.gsub(loopKeys[i], '_and_', ','), "[%a_]+"):
                #    sub_fields.append(sub_fld)

                for k in range(len(sub_fields)):
                    tbl_i[sub_fields[k]] = vals_field_i[loopIndices[i]][k]

        curFldIdx = fieldIdxStart  #  loop from first to last

        loopIndices[curFldIdx] = loopIndices[curFldIdx] + 1
        while loopIndices[curFldIdx] > nValuesEachLoopKey[curFldIdx]:
            loopIndices[curFldIdx] = 1
            curFldIdx = curFldIdx + fieldInc  #  loop from first to last

            if curFldIdx == fieldIdxStop:   #  loop from first to last
                assert j == nTablesTotal
                break
            loopIndices[curFldIdx] = loopIndices[curFldIdx]+1

    return allTables

def testExpandOptionsToList():
    options_test = dict(netType='ConvNet',
                        poolStrides=2,
                        tbl_doPooling=[False, True],
                        tbl_allNStates=[1, 2],
                        # tbl_allNStates_and_test = { { 1 , 'B'}, {2, 'C'}  },
                        tbl_filtsizes=[[6, 16], [12, 32]])

    list_test = expandOptionsToList(options_test)

    print('Initial options table')
    print(options_test)

    print('\n\nFinal list of tables:')
    for i, v in enumerate(list_test):
        print('-- Table #%d --' % i)
        print(v)


import openqcs.tools as tools
import numpy as np
from scipy.linalg import expm

def multi_gate_(pidx, bit=0, nbits=2):
    # pidx = Pauli index
    # 0 -> identity
    # 1 -> X
    # 2 -> Y
    # 3 -> Z

    if bit>=nbits:
        raise ValueError("bit not assigned")

    tmp = 1
    for i in reversed(range(nbits)):
        if i == bit:
            tmp=np.kron(tmp, tools.Pauli[pidx])
        else:
            tmp=np.kron(tmp, tools.Pauli[0])
    return tmp

def H_(a, b, N=2, boundary="o"):
    valid_bound_expr=["o", "p"]
    if not boundary in valid_bound_expr:
        raise ValueError("cannot interpret the boundary condition\n valid expressions are:\n\"o\" for open \n\"p\" for periodic")
    H = np.matrix(np.zeros((2**N, 2**N), dtype=np.complex))

    # Z part
    for i in range(N-1):
        H-=a*multi_gate_(3,bit=i,nbits=N)@multi_gate_(3,bit=i+1,nbits=N)

    if boundary=="p":
        H-=a*multi_gate_(3,bit=N-1,nbits=N)@multi_gate_(3,bit=0,nbits=N)

    # X part
    for i in range(N):
        H+=b*multi_gate_(1,bit=i,nbits=N)

    H = H.real
    return H

def T_(H, dt=0.1):
    T = expm(-1j*H*dt)
    return np.matrix(T)


import time

import pipx.animate
from pipx.animate import (
    CLEAR_LINE,
    EMOJI_ANIMATION_FRAMES,
    NONEMOJI_ANIMATION_FRAMES,
    EMOJI_FRAME_PERIOD,
    NONEMOJI_FRAME_PERIOD,
)

def check_animate_output(
    capsys, test_string, frame_strings, frame_period, frames_to_test
):
    expected_string = "".join(frame_strings)

    chars_to_test = 1 + len("".join(frame_strings[:frames_to_test]))

    with pipx.animate.animate(test_string, do_animation=True):
        time.sleep(frame_period * (frames_to_test - 1) + 0.5)
    captured = capsys.readouterr()

    assert captured.err[:chars_to_test] == expected_string[:chars_to_test]

def test_delay_suppresses_output(capsys, monkeypatch):
    monkeypatch.setattr(pipx.animate, "stderr_is_tty", True)

    test_string = "asdf"

    with pipx.animate.animate(test_string, do_animation=True, delay=0.9):
        time.sleep(0.5)
    captured = capsys.readouterr()
    assert test_string not in captured.err

def test_line_lengths_emoji(capsys, monkeypatch):
    # emoji_support and stderr_is_tty is set only at import animate.py
    # since we are already after that, we must override both here
    monkeypatch.setattr(pipx.animate, "stderr_is_tty", True)
    monkeypatch.setattr(pipx.animate, "emoji_support", True)

    frames_to_test = 4

    # 40-char test_string counts columns e.g.: "0204060810 ... 363840"
    test_string = "".join([f"{x:02}" for x in range(2, 41, 2)])

    columns_to_test = [45, 46, 47]
    expected_message = [f"{test_string:.{45-6}}...", f"{test_string}", f"{test_string}"]

    for i, columns in enumerate(columns_to_test):
        monkeypatch.setenv("COLUMNS", str(columns))

        frame_strings = [
            f"{CLEAR_LINE}\r{x} {expected_message[i]}" for x in EMOJI_ANIMATION_FRAMES
        ]
        check_animate_output(
            capsys, test_string, frame_strings, EMOJI_FRAME_PERIOD, frames_to_test
        )

def test_line_lengths_no_emoji(capsys, monkeypatch):
    # emoji_support and stderr_is_tty is set only at import animate.py
    # since we are already after that, we must override both here
    monkeypatch.setattr(pipx.animate, "stderr_is_tty", True)
    monkeypatch.setattr(pipx.animate, "emoji_support", False)

    frames_to_test = 2

    # 40-char test_string counts columns e.g.: "0204060810 ... 363840"
    test_string = "".join([f"{x:02}" for x in range(2, 41, 2)])

    columns_to_test = [43, 44, 45]
    expected_message = [f"{test_string:.{43-4}}", f"{test_string}", f"{test_string}"]

    for i, columns in enumerate(columns_to_test):
        monkeypatch.setenv("COLUMNS", str(columns))

        frame_strings = [
            f"{CLEAR_LINE}\r{expected_message[i]}{x}" for x in NONEMOJI_ANIMATION_FRAMES
        ]

        check_animate_output(
            capsys, test_string, frame_strings, NONEMOJI_FRAME_PERIOD, frames_to_test
        )


from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader, Context
from django.db.models.aggregates import Sum
from ajustesLogica.models import RegionAuditoria, Ajuste, ImagenAjuste
from ajustesLogica.Config import Configuracion

@login_required(login_url=Configuracion.LOGIN_URL)
def AjusteSinEvidencia(request):
    template = loader.get_template('reportes/AjustesSinEvidencia.html')
    regiones=RegionAuditoria.objects.PorPermiso(request.user).order_by("NombreRegion")
    region=-1
    tda=""
    fechainicial=""
    fechafinal=""
    error=False
    msg=""
    datos=None
    if request.method == 'POST':
        tda=request.POST["txtTienda"]
        region=request.POST["cmbRegion"]
        try:
            fechainicial=request.POST["fechaInicial"]
            fechainicial=datetime.strptime(fechainicial,"%d/%m/%Y")
        except:
            error=True
            msg="La fecha inicial esta en formato incorrecto, debe ser dd/mm/aaaa"
        try:
            fechafinal=request.POST["fechaFinal"]
            fechafinal=datetime.strptime(fechafinal,"%d/%m/%Y")
        except:
            error=True
            msg="La fecha final esta en formato incorrecto, debe ser dd/mm/aaaa"
        try:
            tda=int(tda)
        except:
            tda=0
        if type(fechainicial) is datetime and type(fechafinal) is datetime and fechainicial>=fechafinal:
            error=True
            msg ="La fecha final debe ser mayor a la fecha inicial"
        if not error:
            if tda>0:
                datos=Ajuste.objects.filter(Finalizado=False,Activo=True,Tienda=tda, FechaRecepcion__gte=fechainicial, FechaRecepcion__lte=fechafinal).exclude(id__in=ImagenAjuste.objects.all().values_list('CorrespondeAjuste__id', flat=True)).order_by("FechaRecepcion","Tienda")
            else:
                if int(region)>0:
                    datos=Ajuste.objects.filter(Finalizado=False,Activo=True,Region__id=region, FechaRecepcion__gte=fechainicial, FechaRecepcion__lte=fechafinal).exclude(id__in=ImagenAjuste.objects.all().values_list('CorrespondeAjuste__id', flat=True)).order_by("FechaRecepcion","Tienda")
                else:
                    datos=Ajuste.objects.filter(Finalizado=False,Activo=True,FechaRecepcion__gte=fechainicial, FechaRecepcion__lte=fechafinal).exclude(id__in=ImagenAjuste.objects.all().values_list('CorrespondeAjuste__id', flat=True)).order_by("FechaRecepcion","Tienda")
    context = RequestContext(request, {
                'regiones':regiones,
                'Datos':datos,
                'FechaInicial':fechainicial,
                'FechaFinal':fechafinal,
                'Tienda':tda,
                'Error':error,
                'MensajeError':msg,
                'Region':int(region),
        })
    return HttpResponse(template.render(context))


import sqlite3, csv
from decimal import Decimal
connection = sqlite3.connect("db.sqlite3")
cursor =connection.cursor()

reader = csv.reader(open('join.csv','r'), delimiter=',')

for row in reader:
    to_db = [row[0], row[1], row[2],float(row[3])]
    cursor.execute("INSERT INTO vorulisti_product (product_id, title, sku, weight) VALUES (?,?,?,?);", to_db)

connection.commit()


def dfs(i, cnt):
    print(i)
    if i == n:
        return cnt == k

    if cnt == k:
        return True

    if dfs(i+1, cnt) or dfs(i+1, cnt+a[i]):
        return True

    return False

n, k = map(int, input().split())
a = list(map(int, input().split()))
print('Yes' if dfs(0, 0) else 'No')


nums = [int(x) for x in input()[1:-1:1].split(",")]
a, b, count1, count2 = [0, 0, 0, 0]
res = []
for x in nums:
    if x == a:
        count1 += 1
    elif x == b:
        count2 += 1
    elif count1 == 0:
        a = x
        count1 = 1
    elif count2 == 0:
        b = x
        count2 = 1
    else:
        count1 -= 1
        count2 -= 1
if count1 > len(nums) // 3:
        res.append(a)
if count2 > len(nums) // 3:
        res.append(b)
print(res)


"""
This module launches the user interface for the inventory management system
"""
import sys

from inventory_management.market_prices import get_latest_price
from inventory_management.inventory_class import Inventory
from inventory_management.furniture_class import Furniture
from inventory_management.electric_appliances_class import ElectricAppliances

FULL_INVENTORY = []

def main_menu(user_prompt=None):
    valid_prompts = {"1": add_new_item,
                     "2": item_info,
                     "q": exit_program}
    options = list(valid_prompts.keys())

    while user_prompt not in valid_prompts:
        options_str = ("{}" + (", {}") * (len(options) - 1)).format(*options)
        print(f"Please choose from the following options ({options_str}):")
        # print("Please choose from the following options:")
        print("1. Add a new item to the inventory")
        print("2. Get item information")
        print("q. Quit")
        user_prompt = input(">")
    return valid_prompts.get(user_prompt)

# def get_price(item_code):
#    print("Get price")

def add_new_item():
    # global FULL_INVENTORY
    item_code = input("Enter item code: ")
    item_description = input("Enter item description: ")
    item_rental_price = input("Enter item rental price: ")

    # Get price from the market prices module
    item_price = get_latest_price(item_code)
    new_item_dict = {'product_code': item_code,
                     'description': item_description,
                     'market_price': item_price,
                     'rental_price': item_rental_price
                     }

    is_furniture = input("Is this item a piece of Furniture? (Y/N): ")
    if is_furniture.lower() == "y":
        item_material = input("Enter item material: ")
        item_size = input("Enter item size (S,M,L,XL): ")
        new_item = Furniture(material=item_material, size=item_size,
                             **new_item_dict)
    else:
        is_electric_appliance = input("Is this item an electric appliance? \
(Y/N): ")
        if is_electric_appliance.lower() == "y":
            item_brand = input("Enter item brand: ")
            item_voltage = input("Enter item voltage: ")
            new_item = ElectricAppliances(brand=item_brand,
                                          voltage=item_voltage,
                                          **new_item_dict)
        else:
            new_item = Inventory(**new_item_dict)
    FULL_INVENTORY.append(new_item)
    print("New inventory item added")

def item_info():
    item_code = input("Enter item code: ")
    # filter() returns an iterator that pass the function check,
    # so we can use next() to get these items.
    found_it = next(filter(lambda x: x.product_code == item_code,
                           FULL_INVENTORY), None)

    if found_it is not None:
        print(found_it)
    else:
        print("Item not found in inventory")

def exit_program():
    sys.exit()

if __name__ == '__main__':
    while True:
        # for item in FULL_INVENTORY:
        #   print(item)
        main_menu()()
        input("Press Enter to continue...........")


nnum=int(input()) # Given a number N followed by an array of N integers, replace every element with the greatest element on the right side(to that element) in the array. Replace last element with 0 as there no element on the right side of it.
lt=[int(i) for i in input().split()]
k=0
lt[0]=max(lt)
for i in range(1,nnum-1):
  max=lt[i+1]
  for j in range(i+1,nnum):
    if(lt[j]>max):
      max=lt[j]
    lt[i]=max
lt[len(lt)-1]=0
for i in lt:
  print(i,end=" ")


import tempfile
import os

from PIL import Image

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse

from rest_framework import status
from rest_framework.test import APIClient

from core.models import Recipe, Tag, Ingredient

from recipe.serializers import RecipeSerializer, RecipeDetailSerializer

RECIPE_URL = reverse('recipe:recipe-list')

def image_upload_url(recipe_id):
    """Return URL for recipe image upload"""
    return reverse('recipe:recipe-upload-image', args=[recipe_id])

def detail_url(recipe_id):
    """Retorna a url de detalhe da receita"""
    return reverse('recipe:recipe-detail', args=[recipe_id])

def sample_tag(user, name='Main course'):
    """Cria uma tag de exemplo"""
    return Tag.objects.create(user=user, name=name)

def sample_ingredient(user, name='Cinnamon'):
    """Cria um ingrediente de exemplo"""
    return Ingredient.objects.create(user=user, name=name)

def sample_recipe(user, **params):
    """Cria e retorna uma receita"""
    defaults = {
        'title': 'Receita exemplo',
        'time_minutes': 10,
        'price': 5.50
    }
    defaults.update(params)
    return Recipe.objects.create(user=user, **defaults)

class PublicRecipeApi(TestCase):
    """Testa acesso sem autenticação"""

    def setUp(self) -> None:
        self.client = APIClient()

    def test_auth_required(self):
        """Testa que autenticacao é necessaria"""
        res = self.client.get(RECIPE_URL)

        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)

class PrivateRecipeApiTests(TestCase):
    """Testes autenticados na api de receitas"""

    def setUp(self) -> None:
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            'teste@gmail.com',
            'testpass'
        )
        self.client.force_authenticate(self.user)

    def test_retrieve_recipes(self):
        """Testa a obtençaõ de receitas"""
        sample_recipe(user=self.user)
        sample_recipe(user=self.user)

        res = self.client.get(RECIPE_URL)

        recipes = Recipe.objects.all().order_by('-id')
        serializer = RecipeSerializer(recipes, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)

    def test_recipes_limited_to_user(self):
        """Testando que apenas o usuario pode ver a suas receitas"""
        user2 = get_user_model().objects.create_user(
            'teste2@gmail.com',
            'testpass2'
        )
        sample_recipe(user=user2)
        sample_recipe(user=self.user)
        res = self.client.get(RECIPE_URL)

        recipes = Recipe.objects.filter(user=self.user)
        serializer = RecipeSerializer(recipes, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(len(res.data), 1)
        self.assertEqual(res.data, serializer.data)

    def test_view_recipe_detail(self):
        """Testa a visualização de detalhes de uma receita"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))
        recipe.ingredients.add(sample_ingredient(user=self.user))

        url = detail_url(recipe.id)
        res = self.client.get(url)

        serializer = RecipeDetailSerializer(recipe)
        self.assertEqual(res.data, serializer.data)

    def test_create_basic_recipe(self):
        """Testa a criacao de uma receita"""
        payload = {
            'title': 'Chocolate cheesecake',
            'time_minutes': 30,
            'price': 5.00
        }

        res = self.client.post(RECIPE_URL, payload)
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        for key in payload.keys():
            self.assertEqual(payload[key], getattr(recipe, key))

    def test_create_recipe_with_tags(self):
        """Testa a criacao de uma receita cm tags"""
        tag1 = sample_tag(user=self.user, name='Vegan')
        tag2 = sample_tag(user=self.user, name='Dessert')
        payload = {
            'title': 'Avocado lime cheesecake',
            'tags': [tag1.id, tag2.id],
            'time_minutes': 60,
            'price': 20.00
        }

        res = self.client.post(RECIPE_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        tags = recipe.tags.all()
        self.assertEqual(tags.count(), 2)
        self.assertIn(tag1, tags)
        self.assertIn(tag2, tags)

    def test_create_recipe_with_ingredient(self):
        """Testa a criacao de uma receita cm ingredientes"""
        ingredient1 = sample_ingredient(user=self.user, name='Prawns')
        ingredient2 = sample_ingredient(user=self.user, name='Ginger')
        payload = {
            'title': 'Thai prawn red curry',
            'ingredients': [ingredient1.id, ingredient2.id],
            'time_minutes': 20,
            'price': 7.00
        }

        res = self.client.post(RECIPE_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        ingredients = recipe.ingredients.all()
        self.assertEqual(ingredients.count(), 2)
        self.assertIn(ingredient1, ingredients)
        self.assertIn(ingredient2, ingredients)

    def test_partial_update_recipe(self):
        """Testa atualizacao de receita via patch"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))
        new_tag = sample_tag(user=self.user, name='Curry')

        payload = {
            'title': 'Chicken tikka', 'tags': [new_tag.id]
        }

        url = detail_url(recipe.id)
        self.client.patch(url, payload)

        recipe.refresh_from_db()
        self.assertEqual(recipe.title, payload['title'])
        tags = recipe.tags.all()
        self.assertEqual(len(tags), 1)
        self.assertIn(new_tag, tags)

    def test_full_update_recipe(self):
        """Testa a atualiza de uma receita via PUT"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))
        payload = {
            'title': 'Spaghetti carbonara',
            'time_minutes': 25,
            'price': 5.00
        }
        url = detail_url(recipe.id)
        self.client.put(url, payload)

        recipe.refresh_from_db()
        self.assertEqual(recipe.title, payload['title'])
        self.assertEqual(recipe.time_minutes, payload['time_minutes'])
        self.assertEqual(recipe.price, payload['price'])
        tags = recipe.tags.all()
        self.assertEqual(len(tags), 0)

class RecipeImageUploadTests(TestCase):

    def setUp(self) -> None:
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            'teste@gmail.com',
            'testpass123'
        )
        self.client.force_authenticate(self.user)
        self.recipe = sample_recipe(user=self.user)

    def tearDown(self) -> None:
        self.recipe.image.delete()

    def test_upload_image_to_recipe(self):
        """Testa o uplaod de uma imagem de receita"""
        url = image_upload_url(self.recipe.id)
        with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
            img = Image.new('RGB', (10, 10))
            img.save(ntf, format='JPEG')
            ntf.seek(0)
            res = self.client.post(url, {'image': ntf}, format='multipart')

        self.recipe.refresh_from_db()
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertIn('image', res.data)
        self.assertTrue(os.path.exists(self.recipe.image.path))

    def test_upload_bad_image(self):
        """Testa a carga de uma imagem invalida"""
        url = image_upload_url(self.recipe.id)
        res = self.client.post(url, {'image': 'notimage'}, format='multipart')
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_filter_recipes_by_tags(self):
        """Testa o retorno com tags especificas"""
        recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry')
        recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini')
        tag1 = sample_tag(user=self.user, name='Vegan')
        tag2 = sample_tag(user=self.user, name='Vegetarian')
        recipe1.tags.add(tag1)
        recipe2.tags.add(tag2)
        recipe3 = sample_recipe(user=self.user, title='Fish and chips')

        res = self.client.get(
            RECIPE_URL,
            {'tags': f'{tag1.id},{tag2.id}'}
        )

        serializer1 = RecipeSerializer(recipe1)
        serializer2 = RecipeSerializer(recipe2)
        serializer3 = RecipeSerializer(recipe3)

        self.assertIn(serializer1.data, res.data)
        self.assertIn(serializer2.data, res.data)
        self.assertNotIn(serializer3.data, res.data)

    def test_filter_recipes_by_ingredients(self):
        """Testa o retorno com ingredientes especificos"""
        recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry')
        recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini')
        ingredient1 = sample_ingredient(user=self.user, name='Cheese')
        ingredient2 = sample_ingredient(user=self.user, name='Chicken')
        recipe1.ingredients.add(ingredient1)
        recipe2.ingredients.add(ingredient2)
        recipe3 = sample_recipe(user=self.user, title='Steak')

        res = self.client.get(
            RECIPE_URL,
            {'ingredients': f'{ingredient1.id}, {ingredient2.id}'}
        )

        serializer1 = RecipeSerializer(recipe1)
        serializer2 = RecipeSerializer(recipe2)
        serializer3 = RecipeSerializer(recipe3)

        self.assertIn(serializer1.data, res.data)
        self.assertIn(serializer2.data, res.data)
        self.assertNotIn(serializer3.data, res.data)


import cv2
import time

def main():

    cap = cv2.VideoCapture(0)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1440)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 810)

    t_end = time.time() + 3
    while time.time() < t_end:

        ret, frame = cap.read()

        cv2.imshow("frame", frame)
        cv2.waitKey(10)

main()