from .models import Model
import unittest

class DynamodeTest(Model):
    class Meta:
        table_name = 'dynamode-test'
        region = 'us-west-2'
        hash_key = 'hash_test'
        range_key = 'range_test'

    def __init__(self, hash_test, range_test, **kwargs):
        self.hash_test = hash_test
        self.range_test = range_test
        for arg in kwargs:
            self.arg = kwargs[arg]

    def __str__(self):
        return '%s %s' % (self.hash_test, self.range_test)

if not DynamodeTest.exists():
    print('creating Table')
    DynamodeTest.create_table()
    print('complete table creation')

class DynamodeTestCase(unittest.TestCase):
    def setup(self):
        self.test = DynamodeTest

hk1 = 'horse'
rk1 = 'chicken'
obj1 = DynamodeTest(hk1, rk1)
obj2 = DynamodeTest('pinky', 'brain', trick='take over the world')
objs = [obj1, obj2]
DynamodeTest.batch_put(objs)
hk_only = DynamodeTest.query(hash_key=hk1)
hk_rk = DynamodeTest.query(hash_key=hk1, range_key=rk1)
#rk_only = DynamodeTest.query(range_key=rk1)
print('hash key only: ', hk_only)
print('hash and range keys: ', hk_rk)
#print('range key only: ', rk_only)
#assert rk_only

print('scan hashkey', DynamodeTest.scan(hash_test=hk1)[0])
print('scan hash and range', DynamodeTest.scan(range_test=rk1, hash_test=hk1[0]))
print('scan range only', DynamodeTest.scan(range_test=rk1)[0])
print('scan range is in list', DynamodeTest.scan(range_test__is_in=['chicken', 'duck'])[0])
print('scan range contains ick', DynamodeTest.scan(range_test__contains='ick')[0])
print('scan multiple params', DynamodeTest.scan(range_test__contains='ick', hash_test='horse')[0])
print('no matches, bad hash key', DynamodeTest.scan(range_test__contains='ick', hash_test='dog'))
print('hashkey none scan', DynamodeTest.scan(range_test__contains='ick', hash_test=None)[0])

for obj in DynamodeTest.get_all():
    print(obj)


from r import r
import logging

filename = 'history.log'

pubsub = r.pubsub()
pubsub.subscribe('file.new')
pubsub.subscribe('file.changed')

logging.basicConfig(filename=filename, level=logging.DEBUG)

def process_event(event):
    """
    Event has keys: pattern, channel, type, data
    """
    data = event['data']
    if type(data) == bytes:
        logging.info(event['data'].decode())

while True:
    for event in pubsub.listen():
        process_event(event)


LIST_OF_WORDS = ["apple", "trip","rest",
                 "read", "good", "right",
                 "ex", "high",
                 "sir", "slow", "even", "that", "full",
                 "how", "salad", "come", "us",
                 "all", "haze", "rim", "pull",
                 "rum", "pee","burp"]

WORD_LIST_TFILE = "wordslist.txt"
SCORE_FILE = "scores.txt"

import random
from turtle import *
import turtle

def score_write(word):
    ''' function random_list_of_words
        parameters: void
        returns: nothing

        does: Creates a textfile of words from the list of words stored
        in a list in memory and places on disk.
    '''
    try:

        outfile = open(SCORE_FILE, "w")
        outfile.write(word + '\n')
        outfile.close()

    except OSError:
        print("Error trying to write file")

def random_list_of_words():
    ''' function random_list_of_words
        parameters: void
        returns: nothing

        does: Creates a textfile of words from the list of words stored
        in a list in memory and places on disk.
    '''
    try:

        outfile = open(WORD_LIST_TFILE, "w")
        for word in LIST_OF_WORDS:
            outfile.write(word + '\n')
        outfile.close()

    except OSError:
        print("Error trying to write file")

def create_dict_words():
    '''  function create_dict_words
         parameters: void
         returns: dictionary

         does: reads list of words into dictionary from a
         text file.
    '''

    dictionary = {}
    line_num = 1
    try:
        infile = open(WORD_LIST_TFILE, "r")
        words = infile.readlines()
        for word in words:
            dictionary[line_num] = word.strip()
            line_num += 1
        infile.close()
        return dictionary

    except OSError:
        print("Error reading text file")

def random_word():
    '''  function random_word
         parameters: void
         returns: string

         does: selects a random word from a dictionary of words.
    '''
    random_list_of_words()
    words = create_dict_words()
    rand_word = random.choice(words)
    return rand_word

def list_for_checking_for_item(item):
    '''  function list_for_checking_for_item
         parameters: string
         returns: list

         does: turns a string into a list of characters
    '''
    test_list = []

    for i in item:
         test_list.append(i)

    return test_list

def rocket_body():
    ''' function rocket_body
         parameters: void
         returns: nothing

         does: draws the shape of rockets body using turtle
    '''
    word_turtle = Turtle()
    word_turtle.hideturtle()

    word_turtle.penup()
    word_turtle.goto(0,175)
    word_turtle.pendown()
    word_turtle.goto(-50,100)
    word_turtle.goto(-50,-100)
    word_turtle.goto(50,-100)
    word_turtle.goto(50,100)
    word_turtle.goto(0,175)

def left_rocket():
    '''  function left_rocket
         parameters: void
         returns: nothing

         does: draws the shape of rockets left side using turtle
    '''
    word_turtle = Turtle()
    word_turtle.hideturtle()

    word_turtle.penup()
    word_turtle.goto(-70,-50)
    word_turtle.pendown()
    word_turtle.goto(-40,-130)
    word_turtle.goto(-100,-130)
    word_turtle.goto(-70,-50)

def left_flame():
    '''  function left_flame
         parameters: void
         returns: nothing

         does: draws the shape of rockets left flame using turtle
    '''
    word_turtle = Turtle()
    word_turtle.hideturtle()

    word_turtle.penup()
    word_turtle.goto(-100,-130)
    word_turtle.pendown()
    word_turtle.goto(-90,-150)
    word_turtle.goto(-80,-130)
    word_turtle.goto(-70,-160)
    word_turtle.goto(-60,-130)
    word_turtle.goto(-50,-150)
    word_turtle.goto(-40,-130)

def right_rocket():
    '''  function right_rocket
         parameters: void
         returns: nothing

         does: draws the shape of rockets right side using turtle
    '''
    word_turtle = Turtle()
    word_turtle.hideturtle()

    word_turtle.penup()
    word_turtle.goto(70,-50)
    word_turtle.pendown()
    word_turtle.goto(40,-130)
    word_turtle.goto(100,-130)
    word_turtle.goto(70,-50)

def right_flame():
    '''  function right_flame
         parameters: void
         returns: nothing

         does: draws the shape of rockets flame using turtle
    '''
    word_turtle = Turtle()
    word_turtle.hideturtle()

    word_turtle.penup()
    word_turtle.goto(100,-130)
    word_turtle.pendown()
    word_turtle.goto(90,-150)
    word_turtle.goto(80,-130)
    word_turtle.goto(70,-160)
    word_turtle.goto(60,-130)
    word_turtle.goto(50,-150)
    word_turtle.goto(40,-130)

def draw_lines(lines):
    '''  function draw_lines
         parameters: int
         returns: nothing

         does: draws lines according to input value of lines
    '''
    word_turtle = Turtle()
    word_turtle.hideturtle()
    for i in range(lines):
        word_turtle.pendown()
        word_turtle.forward(20)
        word_turtle.penup()
        word_turtle.forward(10)

def draw_words(word, letter):
    '''  function draw_words
         parameters: string, string
         returns: nothing

         does: takes users letter and matches it to the
         approriate space
    '''

    for i in range(len(word)):
        word_turtle = Turtle()
        word_turtle.hideturtle()
        word_turtle.penup()
        word_turtle.setpos(10 + 30 * (word[i]), 1)
        word_turtle.write(letter, move = True, align ='center', font = ('Arial', 15, 'normal'))

def check_count(count):
    '''  function check_count
         parameters: int
         returns: nothing

         does: takes user input int and determines which
         function should be ran according to its value
    '''

    if count == 1:
        rocket_body()

    elif count == 2:
        left_rocket()

    elif count == 3:
        left_flame()

    elif count == 4:
        right_rocket()

    elif count == 5:
        right_flame()

def game_play():
    ''' function game_play
        parameters: void
        returns: string

    does: takes user input string and returns the letter
    '''
    guessed_letter = input("Guess a letter\n")
    guessed_letter = guessed_letter.lower()

    return guessed_letter

def turtle_reset():
    turtle.clearscreen()


import os
import shutil

import torch
import torch.utils.data
from tensorboardX import SummaryWriter
# import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets

import argparse
import re

from helpers import makedir
import model
import push
import prune
import save
from log import create_logger
from preprocess import mean, std, preprocess_input_function

log = print
class_specific = True

from settings import base_architecture, img_size, prototype_shape, num_classes, global_neg, \
                     prototype_activation_function, add_on_layers_type, experiment_run
import model_ada_dist as model_ada

# construct the model
ppnet = model_ada.construct_PPNet(base_architecture=base_architecture,
                              pretrained=True, img_size=img_size,
                              prototype_shape=prototype_shape,
                              num_classes=num_classes,
                              global_neg=global_neg,
                              prototype_activation_function=prototype_activation_function,
                              add_on_layers_type=add_on_layers_type)

#from settings import deneg_global, add_sym, pos_weight, neg_weight
deneg_global=True
add_sym=True
pos_weight = 1.0
neg_weight = -1.0

separation = torch.rand((num_classes, num_classes))
separation = separation * (1. - torch.eye(num_classes)) #zero the diagonal

pci = ppnet.get_new_pci(separation, prototype_shape[0]-ppnet.num_global_prototypes, deneg_global, add_sym, pos_weight, neg_weight)
ppnet.initialize_from_pci(pci)

ppnet = ppnet.cuda()
ppnet_multi = torch.nn.DataParallel(ppnet)

# load the data
from settings import train_dir, test_dir, train_push_dir, \
                     train_batch_size, test_batch_size, train_push_batch_size, crop

if crop:
    log('loading cropped images')
else:
    log('loading uncropped images')

normalize = transforms.Normalize(mean=mean,
                                 std=std)

# all datasets
# train set
train_dataset = datasets.ImageFolder(
    train_dir,
    transforms.Compose([
        transforms.Resize(size=(img_size, img_size)),
        transforms.ToTensor(),
        normalize,
    ]))
train_loader = torch.utils.data.DataLoader(
    train_dataset, batch_size=train_batch_size, shuffle=True,
    num_workers=4, pin_memory=False)
# train eval set
train_eval_dataset = datasets.ImageFolder(
    train_push_dir,
    transforms.Compose([
        transforms.Resize(size=(img_size, img_size)),
        transforms.ToTensor(),
        normalize,
    ]))
train_eval_loader = torch.utils.data.DataLoader(
    train_eval_dataset, batch_size=train_push_batch_size, shuffle=False,
    num_workers=4, pin_memory=False)
# push set
train_push_dataset = datasets.ImageFolder(
    train_push_dir,
    transforms.Compose([
        transforms.Resize(size=(img_size, img_size)),
        transforms.ToTensor(),
    ]))
train_push_loader = torch.utils.data.DataLoader(
    train_push_dataset, batch_size=train_push_batch_size, shuffle=False,
    num_workers=4, pin_memory=False)
# test set
test_dataset = datasets.ImageFolder(
    test_dir,
    transforms.Compose([
        transforms.Resize(size=(img_size, img_size)),
        transforms.ToTensor(),
        normalize,
    ]))
test_loader = torch.utils.data.DataLoader(
    test_dataset, batch_size=test_batch_size, shuffle=False,
    num_workers=4, pin_memory=False)

# we should look into distributed sampler more carefully at torch.utils.data.distributed.DistributedSampler(train_dataset)
log('training set size: {0}'.format(len(train_loader.dataset)))
log('push set size: {0}'.format(len(train_push_loader.dataset)))
log('test set size: {0}'.format(len(test_loader.dataset)))
log('batch size: {0}'.format(train_batch_size))

# evaluate accuracy overlap

import train_and_test_diag as tnt

proto_k = -1.
by_class = False
debug = False

log('test')
# tnt.test(ppnet_multi, ppnet_control_multi, test_loader, proto_k, by_class, log, debug)
tnt.test_protos(ppnet_multi, test_loader, proto_k, by_class, log, debug)

# log('train')
# tnt.test_protos(ppnet_multi, train_eval_loader, proto_k, by_class, log, debug)

#log('train (augmented)')
#tnt.test_protos(ppnet_multi, train_loader, proto_k, by_class, log, debug)


# -*- coding: utf-8 -*-
import io
import json
import logging
import os
import sys

from chaoslib.exceptions import ChaosException
from chaoslib.experiment import ensure_experiment_is_valid, load_experiment,\
    run_experiment
from chaoslib.types import Experiment
import click
from click_plugins import with_plugins
import logzero
from logzero import logger
from pkg_resources import iter_entry_points

from chaostoolkit import __version__
from chaostoolkit.check import check_newer_version

__all__ = ["cli"]

@with_plugins(iter_entry_points('chaostoolkit.cli_plugins'))
@click.group()
@click.version_option(version=__version__)
@click.option('--verbose', is_flag=True, help='Display debug level traces.')
@click.option('--no-version-check', is_flag=True,
              help='Do not search for an updated version of the chaostoolkit.')
@click.option('--change-dir',
              help='Change directory before running experiment.')
def cli(verbose: bool = False, no_version_check: bool = False,
        change_dir: str = None):
    if verbose:
        logzero.loglevel(logging.DEBUG, update_custom_handlers=True)
        fmt = "%(color)s[%(asctime)s %(levelname)s] "\
              "[%(module)s:%(lineno)d]%(end_color)s %(message)s"
    else:
        logzero.loglevel(logging.INFO, update_custom_handlers=True)
        fmt = "%(color)s[%(asctime)s %(levelname)s]%(end_color)s %(message)s"

    logzero.formatter(
        formatter=logzero.LogFormatter(fmt=fmt, datefmt="%Y-%m-%d %H:%M:%S"),
        update_custom_handlers=True)

    if not no_version_check:
        check_newer_version()

    if change_dir:
        logger.warning("Moving to {d}".format(d=change_dir))
        os.chdir(change_dir)

@cli.command()
@click.option('--report-path', default="./chaos-report.json",
              help='Path where to save the report from the plan execution.')
@click.option('--dry', is_flag=True,
              help='Run the experiment without executing activities.')
@click.option('--no-validation', is_flag=True,
              help='Do not validate the experiment before running.')
@click.argument('path', type=click.Path(exists=True))
def run(path: str, report_path: str = "./chaos-report.json", dry: bool = False,
        no_validation: bool = False):
    """Run the experiment given at PATH."""
    experiment = load_experiment(click.format_filename(path))
    if not no_validation:
        try:
            ensure_experiment_is_valid(experiment)
        except ChaosException as x:
            logger.error(str(x))
            logger.debug(x)
            sys.exit(1)

    experiment["dry"] = dry
    journal = run_experiment(experiment)

    with io.open(report_path, "w") as r:
        json.dump(journal, r, indent=2, ensure_ascii=False)

@cli.command()
@click.argument('path', type=click.Path(exists=True))
def validate(path: str):
    """Validate the experiment at PATH."""
    experiment = load_experiment(click.format_filename(path))
    try:
        ensure_experiment_is_valid(experiment)
        logger.info("experiment syntax and semantic look valid")
    except ChaosException as x:
        logger.error(str(x))
        sys.exit(1)


import nest
import pylab

nest.Install("neuron_simulator_models")
neuron = nest.Create("int_fire1", params={'tau': 10., 't_ref': 2.0})
multimeter = nest.Create(
    'multimeter',
    params={"record_from": ["V_m"], "withtime": True, "interval": 0.1}
)

RUN_TIME = 200
SPIKES_START = 1
SPIKES_INTERVAL = 5
SPIKES_NUMBER = 10000
SPIKE_TIMES = [float(i) for i in range(SPIKES_START, SPIKES_NUMBER, SPIKES_INTERVAL)]

generator = nest.Create(
    'spike_generator',
    params={"spike_times": SPIKE_TIMES}
)
detector = nest.Create(
    'spike_detector',
    params={"withtime": True}
)

nest.Connect(multimeter, neuron)
nest.Connect(neuron, detector)
nest.Connect(generator, neuron, syn_spec={
    "delay": 1.0,
    "weight": 0.5,
    "model": "static_synapse"
})
nest.Simulate(RUN_TIME)

pylab.figure("Nest IntFire1")

multimeter_status = nest.GetStatus(multimeter)[0]
multimeter_events = multimeter_status['events']

pylab.subplot(2, 1, 1)
pylab.xlim(0, RUN_TIME)
pylab.plot(multimeter_events['times'], multimeter_events["V_m"], '.')
pylab.ylabel("IntFire1 V_m")

detector_status = nest.GetStatus(detector)[0]
detector_events = detector_status['events']

pylab.subplot(2, 1, 2)
pylab.xlim(0, RUN_TIME)
pylab.ylim(0, 3)
pylab.plot(SPIKE_TIMES, [2] * len(SPIKE_TIMES), "b.", label='generator')
pylab.plot(detector_events['times'], detector_events['senders'], "r.", label='iaf_neuron')
pylab.ylabel("spikes")
pylab.legend()

pylab.show()


# © 2019 Liyben
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta

from odoo import api, fields, models, _, SUPERUSER_ID

class CrmLead(models.Model):
	_inherit = 'crm.lead'

	#def _default_stage_id(self):
	#    if (self.sub_type and self.sub_type == 'notice'):
	#        team = self.env.ref('lyb_avisos.crm_canal_aviso', raise_if_not_found=False)
	#    else:
	#        team = self.env['crm.team'].sudo()._get_default_team_id(user_id=self.env.uid)
	#
	#    return self._stage_find(team_id=team.id, domain=[('fold', '=', False)]).id

	#Campos necesarios para el uso de CRM como AVISOS
	date_begin = fields.Datetime(string='Visitar el', default=fields.Datetime.now)
	date_end = fields.Datetime(string='Fecha fin')
	next_action = fields.Char(string='Acción siguiente')
	date_creation = fields.Datetime(string='Fecha creación', default=fields.Datetime.now, readonly=True, store=True)

	note = fields.Html(string='Descripción')

	#Tracking para el campo Oficial 1
	worker_one = fields.Many2one('res.users', string='Oficial 1', track_visibility='onchange')
	worker_two = fields.Many2one('res.users', string='Oficial 2')
	helpers = fields.Char(string='Ayudante/s')

	#Solo se usa en la migración de datos para guardar de forma temporal el id de la antigua BBDD
	old_id = fields.Integer(string="Id antiguo")

	#Subtipo para la oportunidad
	sub_type = fields.Selection([('notice', 'Aviso'), ('opportunity', 'Oportunidad')], index=True)

	sub_team_id = fields.Many2one('crm.team', string='Team', ondelete='set null')

	#Etapa del crm
	stage_id = fields.Many2one(
		domain="[('team_id', 'in', [team_id, False]), "
			   "('crm_sub_type', 'in', [sub_type, 'both'])]")

	#Calendariza el aviso con el oficial de 1ª
	@api.multi
	def action_schedule_workers(self):

		self.ensure_one()
		action = self.env.ref('calendar.action_calendar_event').read()[0]
		#Lista de Asistentes
		#Añadimos el usuario conectado
		partner_ids = self.env.user.partner_id.ids
		#Añadimos el cliente
		if self.partner_id:
			partner_ids.append(self.partner_id.id)
		#Añadimos el oficial de primera
		if self.worker_one:
			partner_ids.append(self.worker_one.partner_id.id)
		action['context'] = {
			'default_opportunity_id': self.id if self.type == 'opportunity' else False,
			'default_partner_id': self.partner_id.id,
			'default_partner_ids': partner_ids,
			'default_team_id': self.team_id.id,
			'default_name': self.name,
		}
		return action

	@api.model
	def create(self,vals):
		# Creamos el aviso para cambiar los seguidores del documento
		record = super(CrmLead,self.with_context(mail_create_nosubscribe=True)).create(vals)

		#Lista de seguidores
		follower_ids = []

		#Añadimos el trabajador a la lista de seguidores
		if record.worker_one:
			follower_ids.append(record.worker_one.id)

		#Añadimos la lista de seguidores al aviso
		if follower_ids:
			record.message_subscribe_users(user_ids= follower_ids)

		#Mandamos el correo a los seguidores del aviso con los datos de este. También se envia otro correo al comercial
		message = _("
Estimado/a %s,

Ha sido asignado/a al aviso %s.
") % (record.worker_one.name, record.name)
		subject = _("%s : %s") % (record.sequence_code, record.name)
		record.message_post(body=message, message_type='comment', subtype='mail.mt_comment', subject=subject, author_id=record.user_id.partner_id.id)

		return record

	@api.multi
	def write(self,vals):

		follower_ids = []

		old_worker_id = 0

		#Descubribimos el trabajor de la lista de seguidores y guardamos su id
		if self.worker_one:
			follower_ids.append(self.worker_one.id)
			old_worker_id = self.worker_one.id
			self.message_unsubscribe_users(user_ids=follower_ids)
			follower_ids = []

		#Suscribimos el trabajor al aviso y le mandamos el correo si hay cambio de oficial
		if vals.get('worker_one'):
			worker = self.env['res.users'].browse(vals.get('worker_one'))
			follower_ids.append(worker.id)
			self.message_subscribe_users(user_ids=follower_ids)

			if old_worker_id != worker.id:
				message = _("
Estimado/a %s,

Ha sido asignado/a al aviso %s.
") % (worker.name, self.name)
				subject = _("%s : %s") % (self.sequence_code, self.name)
				self.message_post(body=message, message_type='comment', subtype='mail.mt_comment', subject=subject, author_id=self.user_id.partner_id.id)

		return super(CrmLead,self.with_context(mail_create_nosubscribe=True)).write(vals)

	@api.multi
	def copy(self, default=None):
		if default is None:
			default = {}

		#Ponemos el dia actual por defecto en la fecha de creacion
		default['date_creation'] = fields.Datetime.now()

		return super(CrmLead,self).copy(default=default)

	#Funciones redefinidas para el uso del subtipo en las etapas
	@api.model
	def _read_group_stage_ids(self, stages, domain, order):
		ctx_type = self.env.context.get('default_sub_type')
		stages = super(CrmLead, self)._read_group_stage_ids(stages, domain, order)
		search_domain = [('id', 'in', stages.ids)]
		if ctx_type:
			search_domain += [('crm_sub_type', 'in', [ctx_type, 'both'])]
		stage_ids = stages._search(
			search_domain, order=order, access_rights_uid=SUPERUSER_ID)
		return stages.browse(stage_ids)

	def _stage_find(self, team_id=False, domain=None, order='sequence'):
		ctx_type = self.env.context.get('default_sub_type')
		types = ['both']
		if ctx_type:
			types += [ctx_type]
		# check whether we should try to add a condition on sub_type
		avoid_add_type_term = any([
			term for term in domain if len(term) == 3 if term[0] == 'crm_sub_type'
		])
		if avoid_add_type_term:
			return super(CrmLead, self)._stage_find(team_id, domain, order)
		# collect all team_ids by adding given one,
		# and the ones related to the current leads
		team_ids = set()
		if team_id:
			team_ids.add(team_id)
		for lead in self:
			if lead.team_id:
				team_ids.add(lead.team_id.id)
		# generate the domain
		if team_ids:
			search_domain = ['|', ('team_id', '=', False),
							 ('team_id', 'in', list(team_ids))]
		else:
			search_domain = [('team_id', '=', False)]
		search_domain.append(('crm_sub_type', 'in', types))
		# AND with the domain in parameter
		if domain:
			search_domain += list(domain)
		# perform search, return the first found
		return self.env['crm.stage'].search(
			search_domain, order=order, limit=1)

	@api.multi
	def merge_opportunity(self, user_id=False, team_id=False):
		opportunities_head = super(CrmLead, self).merge_opportunity(
			user_id, team_id)
		if opportunities_head.team_id:
			team_stage_ids = self.env['crm.stage'].search(
				[('team_id', 'in', [opportunities_head.team_id.id, False]),
				 ('crm_sub_type', 'in', [opportunities_head.sub_type, 'both'])],
				order='sequence')
			if opportunities_head.stage_id not in team_stage_ids:
				opportunities_head.write({
					'stage_id': team_stage_ids[0] if team_stage_ids else False
				})
		return opportunities_head

	@api.multi
	def _convert_opportunity_data(self, customer, team_id=False):
		value = super(CrmLead, self)._convert_opportunity_data(customer, team_id)
		if not self.stage_id or self.stage_id.crm_sub_type == 'notice':
			stage = self._stage_find(
				team_id=team_id, domain=[('crm_sub_type', 'in',
										  ['opportunity', 'both'])])
			value['stage_id'] = stage.id
			if stage:
				value['probability'] = stage.probability
		return value


# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import base58
import datetime
import hashlib
import logging
import os
from functools import reduce
from flask import Flask, json, jsonify, request
import flask_cors
# from google.appengine.ext import ndb

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

from google.cloud import pubsub_v1

from google.oauth2 import service_account, id_token
import googleapiclient.discovery
import google.auth.transport.requests

from db.user import User
from db.device import Device
from db.user_event import UserEvent

#import requests_toolbelt.adapters.appengine

# Use the App Engine Requests adapter. This makes sure that Requests uses
# URLFetch.
# requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
PROJECT_ID = 'household-iot-277519'
PUBSUB_TIMEOUT = 60     # seconds

# Device commands
COMMAND_OPEN = 'OPEN'

app = Flask(__name__)
flask_cors.CORS(app)

# Initialize APIs
##
## service_api = googleapiclient.discovery.build('iam', 'v1')
## firebase_admin.initialize_app()
## db = firestore.client()

# Use a service account	# Initialize APIs
service_cred = service_account.Credentials.from_service_account_file(
    filename='accounts/backendServiceAccount.json',
    scopes=['https://www.googleapis.com/auth/cloud-platform'])
service_api = googleapiclient.discovery.build(
    'iam', 'v1', credentials=service_cred)
cred = credentials.Certificate('accounts/backendServiceAccount.json')
firebase_admin.initialize_app(cred)
db = firestore.client()

def get_hash(str):
    m = hashlib.sha256()
    m.update(str.encode('utf-8'))
    return base58.b58encode(m.digest()).decode('ascii')[0:25].lower()

def create_service_account(project_id, service_name, display_name):
    """Creates a service account."""
    service_account = service_api.projects().serviceAccounts().create(
        name='projects/' + project_id,
        body={
            'accountId': service_name,
            'serviceAccount': {
                'displayName': display_name
            }
        }).execute()
    logging.info('Created service account: ' + service_account['email'])
    return service_account

def create_service_key(service_account_email):
    """Creates a key for a service account."""
    # pylint: disable=no-member
    key = service_api.projects().serviceAccounts().keys().create(
        name='projects/-/serviceAccounts/' + service_account_email,body={}
        ).execute()
    return key

def create_topic(project_id, topic_name):
    """Create a new Pub/Sub topic."""
    publisher = pubsub_v1.PublisherClient()
    topic_path = publisher.topic_path(project_id, topic_name)
    topic = publisher.create_topic(request={"name": topic_path})

def create_subscription(project_id, topic_name, subscription_name):
    """Create a new pull subscription on the given topic."""
    publisher = pubsub_v1.PublisherClient()
    subscriber = pubsub_v1.SubscriberClient()
    topic_path = publisher.topic_path(project_id, topic_name)
    subscription_path = subscriber.subscription_path(
        project_id, subscription_name)
    subscription = subscriber.create_subscription(
        request={"name": subscription_path, "topic": topic_path})

def set_pubsub_topic_policy(project, topic_name, publisher_account, subscriber_account):
    """Sets the IAM policy for a topic."""
    client = pubsub_v1.PublisherClient()
    topic_path = client.topic_path(project, topic_name)
    policy = client.get_iam_policy({"resource":topic_path})
    # Add the service account policy for the topic.
    publisher_account_member = "serviceAccount:%s" % publisher_account
    subscriber_account_member = "serviceAccount:%s" % subscriber_account
    policy.bindings.add(
        role='roles/pubsub.viewer',
        members=[publisher_account_member, subscriber_account_member])
    policy.bindings.add(
        role='roles/pubsub.admin',
        members=[publisher_account_member])
    policy.bindings.add(
        role='roles/pubsub.editor',
        members=[publisher_account_member])
    policy.bindings.add(
        role='roles/pubsub.subscriber',
        members=[subscriber_account_member])
    # Set the policy
    policy = client.set_iam_policy(
        request={"resource":topic_path, "policy": policy})

def set_pubsub_subscription_policy(project, subscription_name, subscription_account):
    """Sets the IAM policy for a subscription."""
    client = pubsub_v1.SubscriberClient()
    subscription_path = client.subscription_path(project, subscription_name)
    policy = client.get_iam_policy({"resource":subscription_path})
    # Add the service account policy for the topic.
    subscription_account_member = "serviceAccount:%s" % subscription_account
    policy.bindings.add(
        role='roles/pubsub.viewer',
        members=[subscription_account_member])
    policy.bindings.add(
        role='roles/pubsub.subscriber',
        members=[subscription_account_member])
    # Set the policy
    policy = client.set_iam_policy(
        request={"resource":subscription_path, "policy":policy})

def setup_new_device(user, app_id, device_id, device_name):
    device_hash = get_hash(user.id + device_id)
    in_topic_name = "ti-%s" % device_hash
    out_topic_name = "to-%s" % device_hash
    service_account_name = "ds-%s" % device_hash
    app_account_name = "app-%s" % device_hash
    out_sub = "os-%s" % device_hash
    in_sub = "is-%s" % device_hash
    # Create service account, topic and in/out subscriptions
    service_account = create_service_account(PROJECT_ID, service_account_name, "Garage Opener %s" % device_id)
    app_account = create_service_account(PROJECT_ID, app_account_name, "Garage App %s" % user.email)
    service_account_handle = service_account['email']
    app_account_handle = app_account['email']
    service_key = create_service_key(service_account_handle)
    app_key = create_service_key(app_account_handle)

    create_topic(PROJECT_ID, in_topic_name)
    create_topic(PROJECT_ID, out_topic_name)

    set_pubsub_topic_policy(PROJECT_ID, in_topic_name, publisher_account=app_account_handle, subscriber_account=service_account_handle)
    set_pubsub_topic_policy(PROJECT_ID, out_topic_name, publisher_account=service_account_handle, subscriber_account=app_account_handle)

    create_subscription(PROJECT_ID, in_topic_name, in_sub)
    create_subscription(PROJECT_ID, out_topic_name, out_sub)
    set_pubsub_subscription_policy(PROJECT_ID, in_sub, service_account_handle)
    set_pubsub_subscription_policy(PROJECT_ID, out_sub, app_account_handle)

    # Store device info
    device = user.create_device(device_id, service_account_handle,
        out_topic_name, in_topic_name, out_sub, in_sub,
        json.dumps(service_key), json.dumps(app_key), app_id)
    device.save(db)

    device.record_creation(db)
    return device

def send_open_command_to_device(device):
    publisher = pubsub_v1.PublisherClient()
    topic_path = publisher.topic_path(PROJECT_ID, device.in_topic)
    data = u'{}'.format(json.dumps({'command': COMMAND_OPEN}))
    # Data must be a bytestring
    data = data.encode('utf-8')
    future = publisher.publish(topic_path, data = data)
    # future.result(PUBSUB_TIMEOUT)
    future.result(PUBSUB_TIMEOUT)
    device.record_command(db, COMMAND_OPEN)

def get_or_create_user(claims):
    user_email = claims.get('email')
    user = User.load(db, user_email)

    if user is None:
        user_id = claims['sub']
        user_name = claims.get('name')
        user =  User(id = user_id,
                    email = user_email,
                    name = user_name)
        user.save(db)
    return user

def check_authorization(request):
    # Verify Firebase auth.
    if 'Authorization' in request.headers:
        id_token = request.headers['Authorization'].split(' ').pop()
        claims = google.oauth2.id_token.verify_firebase_token(
            id_token, HTTP_REQUEST)
        return claims

    return None

@app.route('/', methods=['GET'])
def hello():
    """Needed to make GCP ingress working."""

    return jsonify({
            "whoami": 'Sizaha API Server v1.0'
        })

@app.route('/device', methods=['POST', 'PUT'])
def create_device():
    """
    Creates a new device:

        {
            "app_id": "app install instance identifier.",
            "device_id": "device identifier.",
            "device_name": "device name."
        }
    """

    # Verify Firebase auth.
    claims = check_authorization(request)
    if claims is None:
        return 'Unauthorized', 401

    user = get_or_create_user(claims)

    data = request.get_json()
    device_id = data['device_id']
    device = user.get_device(db, device_id)
    if device is not None:
        return "Device already exists", 409

    device = setup_new_device(user, data['app_id'], device_id,  data['device_name'])
    return jsonify(device.to_dict()), 200

@app.route('/devices', methods=['GET'])
def list_devices():
    """Returns a list of notes added by the current Firebase user."""

    # Verify Firebase auth.
    claims = check_authorization(request)
    if claims is None:
        return 'Unauthorized', 401

    user = get_or_create_user(claims)
    devices = user.get_devices(db)
    return jsonify(reduce(lambda p, x: p+[x], (device.to_dict() for device in devices), []))

@app.route('/shared_device/<device_id>/share', methods=['POST', 'PUT'])
def share_device(device_id):
    """
    Creates a record of a new shared device:
        {
            "shared_user_email": "device name"
        }
    """

    # Verify Firebase auth.
    claims = check_authorization(request)
    if claims is None:
        return 'Unauthorized', 401

    user = get_or_create_user(claims)
    device = user.get_device(db, device_id)
    if device is None:
        return "Device does not exist", 404

    data = request.get_json()
    device.create_sharing_invitation(data['shared_user_email'])
    return "OK", 200

@app.route('/device/<device_id>/run', methods=['POST', 'PUT'])
def open_device(device_id):
    """
    Opens garage on specific device:

        {
            "command": "device command.",
        }
    """

    # Verify Firebase auth.
    claims = check_authorization(request)
    if claims is None:
        return 'Unauthorized', 401

    data = request.get_json()

    command = data['command']
    if command != COMMAND_OPEN :
        return 'Unknown command', 400

    user = get_or_create_user(claims)
    device = user.get_device(db, device_id)
    if device is None:
        return "Device does not exists", 404

    send_open_command_to_device(device)
    return jsonify(device.to_dict()), 200

@app.errorhandler(500)
def server_error(e):
    # Log the error and stacktrace.
    logging.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500

if __name__ == '__main__':
    for v in ['PORT']:
        if os.environ.get(v) is None:
            print("error: {} environment variable not set".format(v))
            exit(1)

    # start Flask server
    # Flask's debug mode is unrelated to ptvsd debugger used by Cloud Code
    app.run(debug=False, port=int(os.environ.get('PORT')), host='0.0.0.0')


import os
import sys
import ssl
import git
import shutil
import ftplib
import pathlib
import subprocess

def copy(fro, to):
    # Copy either a single file or an entire directory
    fro = pathlib.Path(fro).expanduser()
    to = pathlib.Path(to).expanduser()
    if fro.is_file():
        shutil.copy(fro, to)
    elif fro.is_dir():
        shutil.copytree(fro, to)
    else:
        raise OSError('Cannot copy %s' % fro)

def scp(host, from_path, to_path, port=None):
    # scp file or dir. Must have passwordless ssh set up.
    scp_cmd = 'scp -B -r '
    if port:
        scp_cmd += '-P %s ' % port
    scp_cmd += '%s:%s %s' % (host, from_path, to_path)
    p = subprocess.Popen(scp_cmd,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT,
                         shell=True)
    return_code = p.wait()
    if return_code != 0:
        raise Exception('Could not scp %s' % from_path)
    return return_code

def ftp_retrieve(host, from_path, to_path, port=None, secure=False):
    if secure:
        ftp = ftplib.FTP_TLS(
                context=ssl.create_default_context())
    else:
        ftp = ftplib.FTP()
    host = (host, port) if port else (host,)
    ftp.connect(*host)
    ftp.login()
    with open(to_path, 'wb') as f:
        ftp.retrbinary('RETR ' + from_path, f.write, 1024)
    ftp.close()

def git_clone(url, path, commit_id=None, rm_git=False):
    # Clone the repo
    repo = git.Repo.clone_from(url, path)

    if commit_id:
        # If given a commit_id, switch to that commit
        commit = repo.commit(commit_id)
        repo.head.reference = commit
        repo.head.reset(index=True, working_tree=True)

    # Get the hexsha of the current commit
    hexsha = repo.head.commit.hexsha

    if rm_git:
        # Delete the .git dir to save space after checking out
        shutil.rmtree(repo.git_dir)

    return hexsha

def stringify_config_lists(config):
    """
    In place convert lists into multi-line strings for pip configuration options
    """
    items = list(config.items())
    for key, val in items:
        if isinstance(val, list):
            if all([isinstance(s, str) for s in val]):
                config[key] = '\n'.join(val)
        elif isinstance(val, dict):
            stringify_config_lists(val)


# -*- coding: utf-8 -*-
# @Time    : 2020/12/6
# @Author  : Lart Pang
# @GitHub  : https://github.com/lartpang

from torch import nn

from backbone.origin.from_origin import Backbone_V16_Custumed
from module.BaseBlocks import BasicConv2d
from utils.tensor_ops import cus_sample, upsample_add

class SIM(nn.Module):
    def __init__(self, h_C, l_C):
        super(SIM, self).__init__()
        self.h2l_pool = nn.AvgPool2d((2, 2), stride=2)
        self.l2h_up = cus_sample

        self.h2l_0 = nn.Conv2d(h_C, l_C, 3, 1, 1)
        self.h2h_0 = nn.Conv2d(h_C, h_C, 3, 1, 1)
        self.bnl_0 = nn.BatchNorm2d(l_C)
        self.bnh_0 = nn.BatchNorm2d(h_C)

        self.h2h_1 = nn.Conv2d(h_C, h_C, 3, 1, 1)
        self.h2l_1 = nn.Conv2d(h_C, l_C, 3, 1, 1)
        self.l2h_1 = nn.Conv2d(l_C, h_C, 3, 1, 1)
        self.l2l_1 = nn.Conv2d(l_C, l_C, 3, 1, 1)
        self.bnl_1 = nn.BatchNorm2d(l_C)
        self.bnh_1 = nn.BatchNorm2d(h_C)

        self.h2h_2 = nn.Conv2d(h_C, h_C, 3, 1, 1)
        self.l2h_2 = nn.Conv2d(l_C, h_C, 3, 1, 1)
        self.bnh_2 = nn.BatchNorm2d(h_C)

        self.relu = nn.ReLU(True)

    def forward(self, x):
        h, w = x.shape[2:]

        # first conv
        x_h = self.relu(self.bnh_0(self.h2h_0(x)))
        x_l = self.relu(self.bnl_0(self.h2l_0(self.h2l_pool(x))))

        # mid conv
        x_h2h = self.h2h_1(x_h)
        x_h2l = self.h2l_1(self.h2l_pool(x_h))
        x_l2l = self.l2l_1(x_l)
        x_l2h = self.l2h_1(self.l2h_up(x_l, size=(h, w)))
        x_h = self.relu(self.bnh_1(x_h2h + x_l2h))
        x_l = self.relu(self.bnl_1(x_l2l + x_h2l))

        # last conv
        x_h2h = self.h2h_2(x_h)
        x_l2h = self.l2h_2(self.l2h_up(x_l, size=(h, w)))
        x_h = self.relu(self.bnh_2(x_h2h + x_l2h))

        return x_h

class conv_2nV1(nn.Module):
    def __init__(self, in_hc=64, in_lc=256, out_c=64, main=0):
        super(conv_2nV1, self).__init__()
        self.main = main
        mid_c = min(in_hc, in_lc)
        self.relu = nn.ReLU(True)
        self.h2l_pool = nn.AvgPool2d((2, 2), stride=2)
        self.l2h_up = nn.Upsample(scale_factor=2, mode="nearest")

        # stage 0
        self.h2h_0 = nn.Conv2d(in_hc, mid_c, 3, 1, 1)
        self.l2l_0 = nn.Conv2d(in_lc, mid_c, 3, 1, 1)
        self.bnh_0 = nn.BatchNorm2d(mid_c)
        self.bnl_0 = nn.BatchNorm2d(mid_c)

        # stage 1
        self.h2h_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.h2l_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.l2h_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.l2l_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.bnl_1 = nn.BatchNorm2d(mid_c)
        self.bnh_1 = nn.BatchNorm2d(mid_c)

        if self.main == 0:
            # stage 2
            self.h2h_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
            self.l2h_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
            self.bnh_2 = nn.BatchNorm2d(mid_c)

            # stage 3
            self.h2h_3 = nn.Conv2d(mid_c, out_c, 3, 1, 1)
            self.bnh_3 = nn.BatchNorm2d(out_c)

            self.identity = nn.Conv2d(in_hc, out_c, 1)

        elif self.main == 1:
            # stage 2
            self.h2l_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
            self.l2l_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
            self.bnl_2 = nn.BatchNorm2d(mid_c)

            # stage 3
            self.l2l_3 = nn.Conv2d(mid_c, out_c, 3, 1, 1)
            self.bnl_3 = nn.BatchNorm2d(out_c)

            self.identity = nn.Conv2d(in_lc, out_c, 1)

        else:
            raise NotImplementedError

    def forward(self, in_h, in_l):
        # stage 0
        h = self.relu(self.bnh_0(self.h2h_0(in_h)))
        l = self.relu(self.bnl_0(self.l2l_0(in_l)))

        # stage 1
        h2h = self.h2h_1(h)
        h2l = self.h2l_1(self.h2l_pool(h))
        l2l = self.l2l_1(l)
        l2h = self.l2h_1(self.l2h_up(l))
        h = self.relu(self.bnh_1(h2h + l2h))
        l = self.relu(self.bnl_1(l2l + h2l))

        if self.main == 0:
            # stage 2
            h2h = self.h2h_2(h)
            l2h = self.l2h_2(self.l2h_up(l))
            h_fuse = self.relu(self.bnh_2(h2h + l2h))

            # stage 3
            out = self.relu(self.bnh_3(self.h2h_3(h_fuse)) + self.identity(in_h))
            # 这里使用的不是in_h，而是h
        elif self.main == 1:
            # stage 2
            h2l = self.h2l_2(self.h2l_pool(h))
            l2l = self.l2l_2(l)
            l_fuse = self.relu(self.bnl_2(h2l + l2l))

            # stage 3
            out = self.relu(self.bnl_3(self.l2l_3(l_fuse)) + self.identity(in_l))
        else:
            raise NotImplementedError

        return out

class conv_3nV1(nn.Module):
    def __init__(self, in_hc=64, in_mc=256, in_lc=512, out_c=64):
        super(conv_3nV1, self).__init__()
        self.upsample = nn.Upsample(scale_factor=2, mode="nearest")
        self.downsample = nn.AvgPool2d((2, 2), stride=2)

        mid_c = min(in_hc, in_mc, in_lc)
        self.relu = nn.ReLU(True)

        # stage 0
        self.h2h_0 = nn.Conv2d(in_hc, mid_c, 3, 1, 1)
        self.m2m_0 = nn.Conv2d(in_mc, mid_c, 3, 1, 1)
        self.l2l_0 = nn.Conv2d(in_lc, mid_c, 3, 1, 1)
        self.bnh_0 = nn.BatchNorm2d(mid_c)
        self.bnm_0 = nn.BatchNorm2d(mid_c)
        self.bnl_0 = nn.BatchNorm2d(mid_c)

        # stage 1
        self.h2h_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.h2m_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.m2h_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.m2m_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.m2l_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.l2m_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.l2l_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.bnh_1 = nn.BatchNorm2d(mid_c)
        self.bnm_1 = nn.BatchNorm2d(mid_c)
        self.bnl_1 = nn.BatchNorm2d(mid_c)

        # stage 2
        self.h2m_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.l2m_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.m2m_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1)
        self.bnm_2 = nn.BatchNorm2d(mid_c)

        # stage 3
        self.m2m_3 = nn.Conv2d(mid_c, out_c, 3, 1, 1)
        self.bnm_3 = nn.BatchNorm2d(out_c)

        self.identity = nn.Conv2d(in_mc, out_c, 1)

    def forward(self, in_h, in_m, in_l):
        # stage 0
        h = self.relu(self.bnh_0(self.h2h_0(in_h)))
        m = self.relu(self.bnm_0(self.m2m_0(in_m)))
        l = self.relu(self.bnl_0(self.l2l_0(in_l)))

        # stage 1
        h2h = self.h2h_1(h)
        m2h = self.m2h_1(self.upsample(m))

        h2m = self.h2m_1(self.downsample(h))
        m2m = self.m2m_1(m)
        l2m = self.l2m_1(self.upsample(l))

        m2l = self.m2l_1(self.downsample(m))
        l2l = self.l2l_1(l)

        h = self.relu(self.bnh_1(h2h + m2h))
        m = self.relu(self.bnm_1(h2m + m2m + l2m))
        l = self.relu(self.bnl_1(m2l + l2l))

        # stage 2
        h2m = self.h2m_2(self.downsample(h))
        m2m = self.m2m_2(m)
        l2m = self.l2m_2(self.upsample(l))
        m = self.relu(self.bnm_2(h2m + m2m + l2m))

        # stage 3
        out = self.relu(self.bnm_3(self.m2m_3(m)) + self.identity(in_m))
        return out

class AIM(nn.Module):
    def __init__(self, iC_list, oC_list):
        super(AIM, self).__init__()
        ic0, ic1, ic2, ic3, ic4 = iC_list
        oc0, oc1, oc2, oc3, oc4 = oC_list
        self.conv0 = conv_2nV1(in_hc=ic0, in_lc=ic1, out_c=oc0, main=0)
        self.conv1 = conv_3nV1(in_hc=ic0, in_mc=ic1, in_lc=ic2, out_c=oc1)
        self.conv2 = conv_3nV1(in_hc=ic1, in_mc=ic2, in_lc=ic3, out_c=oc2)
        self.conv3 = conv_3nV1(in_hc=ic2, in_mc=ic3, in_lc=ic4, out_c=oc3)
        self.conv4 = conv_2nV1(in_hc=ic3, in_lc=ic4, out_c=oc4, main=1)

    def forward(self, *xs):
        # in_data_2, in_data_4, in_data_8, in_data_16, in_data_32
        out_xs = []
        out_xs.append(self.conv0(xs[0], xs[1]))
        out_xs.append(self.conv1(xs[0], xs[1], xs[2]))
        out_xs.append(self.conv2(xs[1], xs[2], xs[3]))
        out_xs.append(self.conv3(xs[2], xs[3], xs[4]))
        out_xs.append(self.conv4(xs[3], xs[4]))

        return out_xs

class MINet_VGG16(nn.Module):
    def __init__(self):
        super(MINet_VGG16, self).__init__()
        self.upsample_add = upsample_add
        self.upsample = cus_sample

        self.encoder1, self.encoder2, self.encoder4, self.encoder8, self.encoder16 = Backbone_V16_Custumed(3)
        self.trans = AIM((64, 128, 256, 512, 512), (32, 64, 64, 64, 64))

        self.sim16 = SIM(64, 32)
        self.sim8 = SIM(64, 32)
        self.sim4 = SIM(64, 32)
        self.sim2 = SIM(64, 32)
        self.sim1 = SIM(32, 16)

        self.upconv16 = BasicConv2d(64, 64, kernel_size=3, stride=1, padding=1)
        self.upconv8 = BasicConv2d(64, 64, kernel_size=3, stride=1, padding=1)
        self.upconv4 = BasicConv2d(64, 64, kernel_size=3, stride=1, padding=1)
        self.upconv2 = BasicConv2d(64, 32, kernel_size=3, stride=1, padding=1)
        self.upconv1 = BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1)

        self.classifier = nn.Conv2d(32, 1, 1)

    def forward(self, data):
        in_data = data["image"]
        in_data_1 = self.encoder1(in_data)
        in_data_2 = self.encoder2(in_data_1)
        in_data_4 = self.encoder4(in_data_2)
        in_data_8 = self.encoder8(in_data_4)
        in_data_16 = self.encoder16(in_data_8)

        in_data_1, in_data_2, in_data_4, in_data_8, in_data_16 = self.trans(
            in_data_1, in_data_2, in_data_4, in_data_8, in_data_16
        )

        out_data_16 = self.upconv16(self.sim16(in_data_16) + in_data_16)  # 1024
        out_data_8 = self.upsample_add(out_data_16, in_data_8)
        out_data_8 = self.upconv8(self.sim8(out_data_8) + out_data_8)  # 512
        out_data_4 = self.upsample_add(out_data_8, in_data_4)
        out_data_4 = self.upconv4(self.sim4(out_data_4) + out_data_4)  # 256
        out_data_2 = self.upsample_add(out_data_4, in_data_2)
        out_data_2 = self.upconv2(self.sim2(out_data_2) + out_data_2)  # 64
        out_data_1 = self.upsample_add(out_data_2, in_data_1)
        out_data_1 = self.upconv1(self.sim1(out_data_1) + out_data_1)  # 32
        seg_logits = self.classifier(out_data_1)

        return dict(seg=seg_logits)


from os import path, environ
import json

# Defaults locations
from sts_token_mod.locations import AWS_CRED_ARN_FILE_NAME, AWS_CRED_RESPONSE_FILE_NAME, AWS_CRED_BASH_FILE_NAME, AWS_CRED_WIN_FILE_NAME

PROFILE = 'default'

try:
    with open(AWS_CRED_ARN_FILE_NAME, 'r') as fh:
        ARN_DICT = json.load(fh)
except FileNotFoundError as ferr:
    print(f'ERROR: Credentials File not found.')
    print(f'Please create File: {AWS_CRED_ARN_FILE_NAME}')

def get_arn(profile):
    return ARN_DICT[profile]

def success_message():
    print('For Setting credentials for current shell : Run below commands')
    bash_file_name = str(AWS_CRED_BASH_FILE_NAME).replace('\\', '\\\\')
    print(f'For Bash RUN: . {bash_file_name}')
    print(f'For Windows RUN: {AWS_CRED_WIN_FILE_NAME}')

def write_to_files(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN):
    try:
        # For Bash terminal
        with open(AWS_CRED_BASH_FILE_NAME, 'w') as fh:
            fh.write(f'export AWS_ACCESS_KEY_ID="{AWS_ACCESS_KEY_ID}"\n')
            fh.write(f'export AWS_SECRET_ACCESS_KEY="{AWS_SECRET_ACCESS_KEY}"\n')
            fh.write(f'export AWS_SESSION_TOKEN="{AWS_SESSION_TOKEN}"')
        # For CMD
        with open(AWS_CRED_WIN_FILE_NAME, 'w') as fh:
            fh.write(f'@echo off\n')
            fh.write(f'set AWS_ACCESS_KEY_ID={AWS_ACCESS_KEY_ID}\n')
            fh.write(f'set AWS_SECRET_ACCESS_KEY={AWS_SECRET_ACCESS_KEY}\n')
            fh.write(f'set AWS_SESSION_TOKEN={AWS_SESSION_TOKEN}\n')
            fh.write(f'echo AWS STS Credentials has been set.')
    except Exception:
        return False

    return True


import requests
from bs4 import BeautifulSoup
from datetime import datetime
import json #respose文件转换为str

#设置python默认输出编码方式
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

#抓取所需要的页面
res = requests.get('http://news.sina.com.cn/')
res.encoding = 'utf-8'

#结构化文档，来碗美味的汤
soup = BeautifulSoup(res.text,'html.parser')

#设置文档写入txt的编码方式
f = open(r'G:\杨敬儒的学习生活\python\sinanews.txt','w',encoding='utf-8')

#抓取首页标题及链接
for news in soup.select('.ct_t_01'):
    if len(news.select('h1')) > 0:
        h1 = news.select('h1')[0].text
        a = news.select('a')[0]['href']
        print (h1,a)
        f.write(h1+a+'\n')

#抓取内文页面
article_sources = requests.get('http://news.sina.com.cn/o/2018-01-24/doc-ifyqyesy0928249.shtml')

#结构化内文文档
article_sources.encoding = 'utf-8'
article_soup = BeautifulSoup(article_sources.text,'html.parser')

#抓取标题
article_title = article_soup.select('.main-title')[0].text
f.write (article_title+'\n')

#抓取时间并格式化时间
article_time = article_soup.select('.date')[0].text
dt = datetime.strptime(article_time,'%Y年%m月%d日 %H:%M')
dw = article_soup.select('.source')[0].text
f.write (article_time+' '+dw+'\n')

#抓取正文
article_para = []
for p in article_soup.select('#article p')[:-1]:
    article_para.append (p.text.strip())
article_para = '\n'.join(article_para)
f.write (article_para+'\n')

#抓取编辑
article_editor = article_soup.select('.show_author')[0].text
f.write (article_editor+'\n')

#抓取评论数
article_commentcount = article_soup.select('.num')[0].text
comment_count = requests.get('http://comment5.news.sina.com.cn/cmnt/count?format=json&newslist=gn:comos-fyqyesy0928249:0&callback=jQuery1111024204789867825727_1516967567369&_=1516967567370')
comment_count = comment_count.text
count1 =comment_count.find('(')+1
count2 =comment_count.find(')')
comment_count = list(comment_count)
comment_count = comment_count[count1:count2]
comment_count = ''.join(comment_count)

#json格式转换
comment_count = json.loads(comment_count)
comment_count = dict(comment_count)
f.write("评论数:"+str(comment_count['result']['count']['gn:comos-fyqyesy0928249:0']['total']))
f.close


#!/usr/bin/env python
from matplotlib.pyplot import show
#
import lowtran
from lowtran.plots import plottrans

if __name__=='__main__':

    from argparse import ArgumentParser
    p = ArgumentParser(description='Lowtran 7 interface')
    p.add_argument('-z','--obsalt',help='altitude of observer [km]',type=float,default=0.)
    p.add_argument('-a','--zenang',help='observer zenith angle [deg]',type=float,nargs='+',default=[0,60,80])
    p.add_argument('-w','--wavelen',help='wavelength range nm (start,stop)',type=float,nargs=2,default=(200,30000))
    p.add_argument('--model',help='0-6, see Card1 "model" reference. 5=subarctic winter',type=int,default=5)
    p=p.parse_args()

    c1={'model':p.model,
        'h1': p.obsalt,
        'angle': p.zenang,
        'wlnmlim': p.wavelen,
        }

    TR = lowtran.transmittance(c1)

    plottrans(TR, c1)

    show()


import pdb
import time
from datetime import date
from datetime import datetime
from datetime import timedelta
from dateutil import relativedelta
from pytz import timezone
import pytz, datetime
from dateutil import tz
from odoo import api, fields, models, _
from odoo.exceptions import UserError

class ReportJacketCenterSpecific(models.AbstractModel):
	_name = 'report.sos_uniform.report_jacketcenterspecific'
	_description = 'Specific Center Jacket Report'

	def get_date_formate(self,sdate):
		ss = datetime.datetime.strptime(sdate,'%Y-%m-%d')
		return ss.strftime('%d %b %Y')

	def get_center_projects(self, center_id):
		project_obj = self.env['sos.project']
		self.env.cr.execute("select distinct project_id from sos_post pp, res_partner p where pp.id = p.post_id and p.active = True and center_id = %s"%center_id)
		rec_ids = self.env.cr.dictfetchall()

		project_ids = []
		for rec in rec_ids:
			project_ids.append(rec['project_id'])
		projects = project_obj.search([('id','in',project_ids)])
		return projects

	@api.model
	def _get_report_values(self, docids, data=None):
		date_from = data['form']['date_from'] and data['form']['date_from']
		date_to = data['form']['date_to'] and data['form']['date_to']
		center_id = data['form']['center_id'] and data['form']['center_id'][0]
		res = []

		projects = self.get_center_projects(center_id)

		if projects:
			for project in projects:
				jackets = self.env['sos.jacket.demand'].search([('project_id', '=', project.id),('center_id', '=', center_id),('date', '>=', date_from),('date','<=', date_to),('state', '<>', 'reject')],order='date,center_id, post_id')
				if jackets:
					res.append({
						'project_name' : project.name,
						'jackets': jackets,
						})

		report = self.env['ir.actions.report']._get_report_from_name('sos_uniform.report_jacketcenterspecific')
		return {
			"doc_ids": self._ids,
			"doc_model": report.model,
			"time": time,
			"data": data['form'],
			"docs": self,
			"Center" : res or False,
			"get_date_formate" : self.get_date_formate,
		}


# Creacion de threads en Python utilizando referencias a objetos invocables

import logging
import threading
import time

# Logger Config
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")

# Funcion a ejecutar
def process(msg: str):
    logging.info(msg)
    time.sleep(3)

thread = threading.Thread(target=process, args=("Un saludo con un poco de espera",))
thread.start()


from django.conf.urls import url
from .views import (
    ForumListView,
    ForumDetailView,
    ForumCreateView,
    ForumUpdateView,
    ForumDeleteView,
    add_comment_to_forum,
    reply_to_comment,
    comment_remove,
    reply_remove,
    CommentUpdateView,
    ReplyUpdateView,
)

app_name = 'forums'

urlpatterns = [
    url(r'^$', ForumListView.as_view(), name='forum_list'),
    url(r'^(?P<pk>\d+)$', ForumDetailView.as_view(), name='forum_detail'),
    url(r'^new/$', ForumCreateView.as_view(), name='create_forum'),
    url(r'^(?P<pk>\d+)/edit/$', ForumUpdateView.as_view(), name='update_forum'),
    url(r'^(?P<pk>\d+)/delete/$', ForumDeleteView.as_view(), name='delete_forum'),
    url(r'^(?P<pk>\d+)/comment/$',
        add_comment_to_forum,
        name="add_comment_to_forum"),
    url(r'^comment/(?P<pk>\d+)/edit/$',
        CommentUpdateView.as_view(),
        name="comment_update"),
    url(r'^(?P<pk>\d+)/comment/(?P<pk1>\d+)/delete/$',
        comment_remove,
        name="comment_remove"),
    url(r'^(?P<pk>\d+)/comment/(?P<pk1>\d+)/reply/$',
        reply_to_comment,
        name="reply_to_comment"),
    url(r'^comment/reply/(?P<pk>\d+)/edit/$',
        ReplyUpdateView.as_view(),
        name="reply_update"),
    url(r'^(?P<pk>\d+)/comment/(?P<pk1>\d+)/reply/(?P<pk2>\d+)/delete/$',
        reply_remove,
        name="reply_remove")
    # url(r'^(?P<pk>\d+)/edit/$', BlogUpdateView.as_view(), name='blog_update'),
    # url(r'^(?P<pk>\d+)/delete/$', BlogDeleteView.as_view(),
    #     name='blog_delete'),
]


#!/usr/bin/env python
# -*- coding: utf-8 -*-
class board:
    class pawn:
        def __init__(self, location, texture, move_type, checks, status):
            self.location = location
            self.texture = texture
            self.move_type = move_type
            self.checks = checks
            self.status = status

    tower1 = pawn('A1', 'T', 'tower', '', True)
    horse1 = pawn('B1', 'H', 'horse', '', True)
    runner1 = pawn('C1', 'R', 'runner', '', True)
    hetman = pawn('D1', 'Q', 'hetman', '', True)
    king = pawn('E1', 'K', 'king', '', True)
    pawn1 = pawn('A2', 'P', 'pawn', '', True)
    empty = pawn('none', '_', 'none', '', True)
    tower11 = pawn('A8', 't', 'tower', '', True)
    horse11 = pawn('B8', 'h', 'horse', '', True)
    runner11 = pawn('C8', 'r', 'runner', '', True)
    hetman1 = pawn('D8', 'q', 'hetman', '', True)
    king1 = pawn('E8', 'k', 'king', '', True)
    pawn11 = pawn('A7', 'p', 'pawn', '', True)

    class dataclass:
        def __init__(self, numbers_vector, numbers_row, insert_place, numbers_row_int, number_row_reversed,
                     insert_place_reversed):
            self.numbers_vector = numbers_vector
            self.numbers_row = numbers_row
            self.insert_place = insert_place
            self.numbers_row_ints = numbers_row_int
            self.number_row_reversed = number_row_reversed
            self.insert_place_reversed = insert_place_reversed

    data = dataclass(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ['1', '2', '3', '4', '5', '6', '7', '8'],
                     {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, }, [1, 2, 3, 4, 5, 6, 7, 8],
                     [8, 7, 6, 5, 4, 3, 2, 1], {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H'})

    def insert(self, pawn, place, board):
        pawn.location = place
        for i in self.data.numbers_row:
            if i in pawn.location:
                for x in self.data.numbers_vector:
                    if x in pawn.location:
                        board[self.data.number_row_reversed[int(i) - 1] - 1].pop(self.data.insert_place.get(x))
                        board[self.data.number_row_reversed[int(i) - 1] - 1].insert(self.data.insert_place.get(x),
                                                                                pawn.texture)
                        return board

    def is_pawn_here(self, loc, board):
        try:
            for i in self.data.numbers_row:
                if i in loc:
                    for x in self.data.numbers_vector:
                        if x in loc:
                            if board[self.data.number_row_reversed[int(i) - 1] - 1][
                                self.data.insert_place.get(x)] != '_':
                                return board[self.data.number_row_reversed[int(i) - 1] - 1][
                                    self.data.insert_place.get(x)]
                            else:
                                return False
        except TypeError:
            return False

    def move(self, pawn, _from, to, board, type):
        pos = []
        roszade = False
        horse_dict1 = {'A': 'B', 'B': 'C', 'C': 'D', 'D': 'E', 'E': 'F', 'F': 'G', 'G': 'H'}
        horse_dict2 = {'H': 'G', 'G': 'F', 'F': 'E', 'E': 'D', 'D': 'C', 'C': 'B', 'B': 'A'}
        horse_dict3 = {'A': 'C', 'B': 'D', 'C': 'E', 'D': 'F', 'E': 'G', 'F': 'H'}
        horse_dict4 = {'C': 'A', 'D': 'B', 'E': 'C', 'F': 'D', 'G': 'E', 'H': 'F'}
        for i in self.data.numbers_row:
            if i in _from:
                for x in self.data.numbers_vector:
                    if x in _from:
                        if pawn.move_type == 'pawn':
                            if ord(pawn.texture) < 100:
                                if i == '7':
                                    pos.append(x + str(int(i) - 2))
                                if self.is_pawn_here(x + str(int(i) - 1), board) == False:
                                    pos.append(x + str(int(i) - 1))
                                if horse_dict1.get(x) != None and self.is_pawn_here(horse_dict1.get(x) + str(int(i) - 1), board) != False:
                                    pos.append(horse_dict1.get(x) + str(int(i) - 1))
                                if horse_dict2.get(x) != None and self.is_pawn_here(horse_dict2.get(x) + str(int(i) - 1), board) != False:
                                    pos.append(horse_dict2.get(x) + str(int(i) - 1))
                            else:
                                if i == '2':
                                    pos.append(x + str(int(i) + 2))
                                if self.is_pawn_here(x + str(int(i) + 1), board) == False:
                                    pos.append(x + str(int(i) + 1))
                                if horse_dict1.get(x) != None and self.is_pawn_here(horse_dict1.get(x) + str(int(i) + 1), board) != False:
                                    pos.append(horse_dict1.get(x) + str(int(i) + 1))
                                if horse_dict2.get(x) != None and self.is_pawn_here(horse_dict2.get(x) + str(int(i) + 1), board) != False:
                                    pos.append(horse_dict2.get(x) + str(int(i) + 1))
                        if pawn.move_type == 'tower':
                            lock_up = False
                            lock_row = False
                            for a in range(1, 7):
                                    if not lock_up:
                                        pos.append(x + str(int(i) + a))
                                        if self.is_pawn_here(x + str(int(i) + a), board) != False and self.is_pawn_here(x + str(int(i) + a), board) != pawn.texture:
                                            lock_up = True
                            for m in self.data.numbers_vector:
                                if not lock_row:
                                    pos.append(m + i)
                                    if self.is_pawn_here(m + i, board) != False and self.is_pawn_here(m + i, board) != pawn.texture:
                                        lock_row = True
                        if pawn.move_type == 'horse':
                            if horse_dict1.get(x) != None:
                                pos.append(horse_dict1.get(x) + str(int(i) + 2))
                                pos.append(horse_dict1.get(x) + str(int(i) - 2))
                            if horse_dict2.get(x) != None:
                                pos.append(horse_dict2.get(x) + str(int(i) + 2))
                                pos.append(horse_dict2.get(x) + str(int(i) - 2))
                            if horse_dict3.get(x) != None:
                                pos.append(horse_dict3.get(x) + str(int(i) + 1))
                                pos.append(horse_dict3.get(x) + str(int(i) - 1))
                            if horse_dict4.get(x) != None:
                                pos.append(horse_dict4.get(x) + str(int(i) + 1))
                                pos.append(horse_dict4.get(x) + str(int(i) - 1))

                        if pawn.move_type == 'runner':
                            u = x
                            lock = False
                            z = 1
                            c = 0
                            while not lock and c < 8:
                                if horse_dict1.get(u) != None:
                                    pos.append(horse_dict1.get(u) + str(int(i) + z))
                                    if self.is_pawn_here(horse_dict1.get(u) + str(int(i) + z), board) != False:
                                        lock = True
                                c += 1
                                u = horse_dict1.get(u)
                                z += 1
                            lock = False
                            u = x
                            z = 1
                            c = 0
                            while not lock and c < 8:
                                if horse_dict1.get(u) != None:
                                    pos.append(horse_dict1.get(u) + str(int(i) - z))
                                    if self.is_pawn_here(horse_dict1.get(u) + str(int(i) - z), board) != False:
                                        lock = True
                                c += 1
                                u = horse_dict1.get(u)
                                z += 1
                            lock = False
                            u = x
                            c = 0
                            z = 1
                            while not lock and c < 8:
                                if horse_dict2.get(u) != None:
                                    pos.append(horse_dict2.get(u) + str(int(i) + z))
                                    if self.is_pawn_here(horse_dict2.get(u) + str(int(i) + z), board) != False:
                                        lock = True
                                c += 1
                                u = horse_dict2.get(u)
                                z += 1
                            lock = False
                            u = x
                            z = 1
                            c = 0
                            while not lock and c < 8:
                                if horse_dict2.get(u) != None:
                                    pos.append(horse_dict2.get(u) + str(int(i) - z))
                                    if self.is_pawn_here(horse_dict2.get(u) + str(int(i) - z), board) != False:
                                        lock = True
                                c += 1
                                u = horse_dict2.get(u)
                                z += 1
                        if pawn.move_type == 'hetman':
                            lock_up = False
                            lock_row = False
                            for a in range(1, 7):
                                    if not lock_up:
                                        pos.append(x + str(int(i) + a))
                                        if self.is_pawn_here(x + str(int(i) + a), board) != False and self.is_pawn_here(x + str(int(i) + a), board) != pawn.texture:
                                            lock_up = True
                            for m in self.data.numbers_vector:
                                if not lock_row:
                                    pos.append(m + i)
                                    if self.is_pawn_here(m + i, board) != False and self.is_pawn_here(m + i, board) != pawn.texture:
                                            lock_row = True
                            u = x
                            lock = False
                            z = 1
                            c = 0
                            while not lock and c < 8:
                                if horse_dict1.get(u) != None:
                                    pos.append(horse_dict1.get(u) + str(int(i) + z))
                                    if self.is_pawn_here(horse_dict1.get(u) + str(int(i) + z), board) != False:
                                        lock = True
                                c += 1
                                u = horse_dict1.get(u)
                                z += 1
                            lock = False
                            u = x
                            z = 1
                            c = 0
                            while not lock and c < 8:
                                if horse_dict1.get(u) != None:
                                    pos.append(horse_dict1.get(u) + str(int(i) - z))
                                    if self.is_pawn_here(horse_dict1.get(u) + str(int(i) - z), board) != False:
                                        lock = True
                                c += 1
                                u = horse_dict1.get(u)
                                z += 1
                            lock = False
                            u = x
                            c = 0
                            z = 1
                            while not lock and c < 8:
                                if horse_dict2.get(u) != None:
                                    pos.append(horse_dict2.get(u) + str(int(i) + z))
                                    if self.is_pawn_here(horse_dict2.get(u) + str(int(i) + z), board) != False:
                                        lock = True
                                c += 1
                                u = horse_dict2.get(u)
                                z += 1
                            lock = False
                            u = x
                            z = 1
                            c = 0
                            while not lock and c < 8:
                                if horse_dict2.get(u) != None:
                                    pos.append(horse_dict2.get(u) + str(int(i) - z))
                                    if self.is_pawn_here(horse_dict2.get(u) + str(int(i) - z), board) != False:
                                        lock = True
                                c += 1
                                u = horse_dict2.get(u)
                                z += 1
                        if pawn.move_type == 'king':
                            pos.append(x + str(int(i) + 1))
                            pos.append(x + str(int(i) - 1))
                            if horse_dict1.get(x) != None:
                                pos.append(horse_dict1.get(x) + i)
                                pos.append(horse_dict1.get(x) + str(int(i) + 1))
                                pos.append(horse_dict1.get(x) + str(int(i) - 1))
                            if horse_dict2.get(x) != None:
                                pos.append(horse_dict2.get(x) + str(int(i) - 1))
                                pos.append(horse_dict2.get(x) + str(int(i) + 1))
                                pos.append(horse_dict2.get(x) + i)

                            if (_from == 'E1' and self.is_pawn_here('H1', board) == 't') or (_from == 'E8' and self.is_pawn_here('H8', board) == 'T'):
                                roszade = True

        for n in pos:
            if self.is_pawn_here(n, board) != False:
                    try:
                        if (ord(self.is_pawn_here(n, board)) > 100 and ord(pawn.texture) > 100) or (ord(self.is_pawn_here(n, board)) < 100 and ord(pawn.texture) < 100):
                            pos.remove(n)
                    except TypeError:
                        pass

        for y in pos:
            if '0' in y:
                pos.remove(y)
            elif '-' in y:
                pos.remove(y)
        #print(pos)
        textures = {
            'k':self.king1, 't': self.tower11, 'h':self.horse11, 'q':self.hetman1, 'r':self.runner11, 'p':self.pawn11,
            'K':self.king, 'T': self.tower1, 'H':self.horse1, 'Q':self.hetman, 'R':self.runner1, 'P':self.pawn
        }
        if type == 'move':
            if roszade == True and to == 'G1':
                if pawn.texture == 'k':
                    self.insert(self.king1, 'G1', board)
                    self.insert(self.empty, _from, board)
                    self.insert(self.tower11, 'F1', board)
                    self.insert(self.empty, 'H1', board)
                else:
                    self.insert(self.king, 'G8', board)
                    self.insert(self.empty, _from, board)
                    self.insert(self.tower1, 'F8', board)
                    self.insert(self.empty, 'H8', board)

            if to in pos:
                if '8' in to and pawn.texture == 'p':
                    promotion = input('for what you want to change?: ')
                    if promotion == 'q':
                        self.insert(self.hetman1, to, board)
                    if promotion == 'h':
                       self.insert(self.horse11, to, board)
                    if promotion == 'r':
                       self.insert(self.runner11, to, board)
                    if promotion == 't':
                       self.insert(self.tower11, to, board)
                elif '1' in to and pawn.texture == 'P':
                    promotion = input('for what you want to change?: ')
                    if promotion == 'Q':
                       self.insert(self.hetman, to, board)
                    if promotion == 'H':
                       self.insert(self.horse1, to, board)
                    if promotion == 'R':
                       self.insert(self.runner1, to, board)
                    if promotion == 'T':
                       self.insert(self.tower1, to, board)
                else:
                    if self.is_pawn_here(to, board) != False:
                        destroyed_pawn = self.is_pawn_here(to, board)
                        print('zbito ' + destroyed_pawn)
                        obj = textures.get(destroyed_pawn)
                        obj.status = False
                    self.insert(pawn, to, board)
                    self.insert(self.empty, _from, board)
            else:
                    print("wrong move")
            return board
        elif type == 'check':
            if pawn.texture == 'k' and roszade == True:
                pos.append('G1')
            elif pawn.texture == 'K' and roszade == True:
                pos.append('')
            return pos

    def print_board(self, board):
        index = 0
        num = self.data.numbers_row[::-1]
        for x in board:
            print(num[index] + '[', end=" ")
            for y in x:
                if ord(y) > 100:
                    print('\033[94m' + y + '\033[0m', end=" ")
                else:
                    print(y, end=" ")
            print(']')
            index += 1
        print('   A B C D E F G H')

    def boardcopy(self, board):
        new = [[] for _ in range(8)]
        for q in range(len(board)):
            m = board[q]
            for x in m:
                new[q].append(x)

        return new

    def output(self):
        board1 = [['_' for _ in range(8)] for _ in range(8)]
        board1 = self.insert(self.horse1, self.horse1.location, board1)
        board1 = self.insert(self.horse1, 'G1', board1)
        board1 = self.insert(self.tower1, self.tower1.location, board1)
        board1 = self.insert(self.tower1, 'H1', board1)
        board1 = self.insert(self.runner1, self.runner1.location, board1)
        board1 = self.insert(self.runner1, 'F1', board1)
        board1 = self.insert(self.hetman, self.hetman.location, board1)
        board1 = self.insert(self.king, self.king.location, board1)
        pawns_loc = ['A2', 'B2', 'C2', 'D2', 'E2', 'F2', 'G2', 'H2']
        for z in pawns_loc:
            board1 = self.insert(self.pawn1, z, board1)
        board1 = board1[::-1]
        board1 = self.insert(self.horse11, self.horse1.location, board1)
        board1 = self.insert(self.horse11, 'B1', board1)
        board1 = self.insert(self.tower11, self.tower1.location, board1)
        board1 = self.insert(self.tower11, 'A1', board1)
        board1 = self.insert(self.runner11, self.runner1.location, board1)
        board1 = self.insert(self.runner11, 'C1', board1)
        board1 = self.insert(self.hetman1, self.hetman.location, board1)
        board1 = self.insert(self.king1, self.king.location, board1)
        pawns_loc = ['A2', 'B2', 'C2', 'D2', 'E2', 'F2', 'G2', 'H2']
        for z in pawns_loc:
            board1 = self.insert(self.pawn11, z, board1)
        self.print_board(board1)
        whith = 0
        is_check_blue = False
        is_check = False
        checks = []
        checks_blue = []
        need_refresh_white = False
        need_refresh_blue = False
        while True:
            old_board = self.boardcopy(board1)
            pawn_select = input('Select pawn(eg. A2): ')
            selected_pawn = self.is_pawn_here(pawn_select, board1)
            if selected_pawn != False:
                movements = {
                    'p': self.move(self.pawn11, pawn_select, 'A1', board1, 'check'),
                    't': self.move(self.tower11, pawn_select, 'A1', board1, 'check'),
                    'q': self.move(self.hetman1, pawn_select, 'A1', board1, 'check'),
                    'k': self.move(self.king1, pawn_select,'A1', board1, 'check'),
                    'h': self.move(self.horse11, pawn_select, 'A1', board1, 'check'),
                    'r': self.move(self.runner11, pawn_select, 'A1', board1, 'check'),
                    'P': self.move(self.pawn1, pawn_select, 'A1', board1, 'check'),
                    'T': self.move(self.tower1, pawn_select, 'A1', board1, 'check'),
                    'Q': self.move(self.hetman, pawn_select, 'A1', board1, 'check'),
                    'K': self.move(self.king, pawn_select, 'A1', board1, 'check'),
                    'H': self.move(self.horse1, pawn_select, 'A1', board1, 'check'),
                    'R': self.move(self.runner1, pawn_select, 'A1', board1, 'check')
                }
                print('You want to move ' + selected_pawn)
                print('Possible moves are: ')
                for q in movements.get(selected_pawn):
                    print(q)
                pawn_where = input('Where you want to move?(eg. A3): ')
                if selected_pawn == 'P':
                    board1 = self.move(self.pawn1, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'T':
                    board1 = self.move(self.tower1, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'H':
                    board1 = self.move(self.horse1, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'R':
                    board1 = self.move(self.runner1, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'Q':
                    board1 = self.move(self.hetman, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'K':
                    board1 = self.move(self.king, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'p':
                    board1 = self.move(self.pawn11, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 't':
                    board1 = self.move(self.tower11, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'h':
                    board1 = self.move(self.horse11, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'r':
                    board1 = self.move(self.runner11, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'q':
                    board1 = self.move(self.hetman1, pawn_select, pawn_where, board1, 'move')
                if selected_pawn == 'k':
                    board1 = self.move(self.king1, pawn_select, pawn_where, board1, 'move')
                if board1 != None:
                    if self.pawn11.status:
                        self.pawn11.checks = self.move(self.pawn11, pawn_where, 'A1', board1, 'check')
                    else:
                        self.pawn11.checks = ''
                    if self.pawn11.status:
                        self.tower11.checks = self.move(self.tower11, pawn_where, 'A1', board1, 'check')
                    else:
                        self.tower11.checks = ''
                    if self.horse11.status:
                        self.horse11.checks = self.move(self.horse11, pawn_where, 'A1', board1, 'check')
                    else:
                        self.horse11.checks = ''
                    if self.runner11.status:
                        self.runner11.checks = self.move(self.runner11, pawn_where, 'A1', board1, 'check')
                    else:
                        self.runner11.checks = ''
                    if self.hetman1.status:
                        self.hetman1.checks = self.move(self.hetman1, pawn_where, 'A1', board1, 'check')
                    else:
                        self.hetman1.checks = ''
                    if self.king1.status:
                        self.king1.checks = self.move(self.king1, pawn_where, 'A1', board1, 'check')
                    else:
                        self.king1.checks = ''
                    if self.pawn1.status:
                        self.pawn1.checks = self.move(self.pawn1, pawn_where, 'A1', board1, 'check')
                    else:
                        self.pawn1.checks = ''
                    if self.tower1.status:
                        self.tower1.checks = self.move(self.tower1, pawn_where, 'A1', board1, 'check')
                    else:
                        self.tower1.checks = ''
                    if self.horse1.status:
                        self.horse1.checks = self.move(self.horse1, pawn_where, 'A1', board1, 'check')
                    else:
                        self.horse1.checks = ''
                    if self.runner1.status:
                        self.runner1.checks = self.move(self.runner1, pawn_where, 'A1', board1, 'check')
                    else:
                        self.runner1.checks = ''
                    if self.hetman.status:
                        self.hetman.checks = self.move(self.hetman, pawn_where, 'A1', board1, 'check')
                    else:
                        self.hetman.checks = ''
                    if self.king.status:
                        self.king.checks = self.move(self.king, pawn_where, 'A1', board1, 'check')
                    else:
                        self.king.checks = ''

                    checks = [
                        self.king.checks,
                        self.horse1.checks,
                        self.hetman.checks,
                        self.tower1.checks,
                        self.runner1.checks,
                        self.pawn1.checks
                        ]
                    checks_blue = [
                        self.king1.checks,
                        self.runner11.checks,
                        self.tower11.checks,
                        self.horse11.checks,
                        self.hetman1.checks,
                        self.pawn11.checks
                        ]
                    print(checks_blue)
                    for z in checks:
                        for u in z:
                            if self.is_pawn_here(u, board1) == 'k':
                                is_check = True
                                need_refresh_white = True
                    for z in checks_blue:
                        for u in z:
                            if self.is_pawn_here(u, board1) == 'K':
                                is_check_blue = True
                                need_refresh_blue = True
                    if is_check and ord(selected_pawn) > 100:
                        print('wrong move, your opponent have check')
                        board1 = self.boardcopy(old_board)
                        self.print_board(board1)
                    elif is_check_blue and ord(selected_pawn) < 100:
                        print('wrong move, your opponent have check')
                        board1 = self.boardcopy(old_board)
                        self.print_board(board1)
                    else:
                        self.print_board(board1)
                else:
                    board1 = []
                    for q in old_board:
                        board1.append(q)
            else:
                print('No pawn in ' + pawn_select)

szachownica = board()

if szachownica.output():
    print('end of the game')


def reduce_s(s,t):
    for i in range(len(s)):
        if s[i]!=t[i]:
            s=s[:i]
            break
    return s

class Solution(object):
    def longestCommonPrefix(self, strs):
        s=""
        if len(strs)==0:
            return s
        s=strs[0]
        for i in range(1,len(strs)):
            if s=="":
                break
            t = strs[i][:len(s)]
            if s != t:
                # sub match
                s=s[:len(t)]
                if s!=t:
                    # iterate from begining to find out commonPart
                    s = reduce_s(s,t)
            else:
                s=s[:len(t)]
        return s


import os, sys
import stat
from qtpy.QtWidgets import *
from pyqode.core import panels, api, modes
from pyqode.python import widgets, panels as pypanels, modes as pymodes
from pyqode.python.backend import server
from functools import partial
from xicam.gui.threads import QThreadFuture
import subprocess
from appdirs import user_config_dir

class scripteditor(QWidget):
    def __init__(self):
        super(scripteditor, self).__init__()
        scripteditoriteminstance = scripteditoritem()
        self.setLayout(QVBoxLayout())
        self.layout().addWidget(scripteditortoolbar(scripteditoriteminstance))
        self.layout().addWidget(scripteditoriteminstance)

class scripteditortoolbar(QToolBar):
    def __init__(self, editor):
        '''

        Parameters
        ----------
        editor  :   scripteditor
        '''
        super(scripteditortoolbar, self).__init__()
        self.editor = editor

        self.addAction('Run', self.Run)
        self.addAction('Create Action', self.CreateAction)

    def Run(self, script=None):
        if not script: script = self.editor.toPlainText()

        self._runthread = QThreadFuture(partial(exec, script))
        self._runthread.start()

        # tmpdir = user_config_dir('xicam/tmp')
        #
        # if not os.path.isdir(tmpdir): os.mkdir(tmpdir)
        #
        # tmppath = os.path.join(tmpdir,'tmp.py')
        #
        # with open(tmppath,'w') as f:
        #     f.write(script)
        #     # f.close()
        #
        # st = os.stat(tmppath)
        # os.chmod(tmppath, st.st_mode | stat.S_IEXEC)
        #
        # subprocess.call([sys.executable, tmppath])

    def CreateAction(self):
        p = partial(self.Run, self.editor.toPlainText())
        self.addAction('Custom Action', p)

class scripteditoritem(widgets.PyCodeEditBase):
    def __init__(self):
        super(scripteditoritem, self).__init__()

        # starts the default pyqode.python server (which enable the jedi code
        # completion worker).
        self.backend.start(server.__file__)

        # some other modes/panels require the analyser mode, the best is to
        # install it first
        # self.modes.append(pymodes.DocumentAnalyserMode())

        # --- core panels
        self.panels.append(panels.FoldingPanel())
        self.panels.append(panels.LineNumberPanel())
        self.panels.append(panels.CheckerPanel())
        self.panels.append(panels.SearchAndReplacePanel(),
                           panels.SearchAndReplacePanel.Position.BOTTOM)
        self.panels.append(panels.EncodingPanel(), api.Panel.Position.TOP)
        # add a context menu separator between editor's
        # builtin action and the python specific actions
        self.add_separator()

        # --- python specific panels
        self.panels.append(pypanels.QuickDocPanel(), api.Panel.Position.BOTTOM)

        # --- core modes
        self.modes.append(modes.CaretLineHighlighterMode())
        self.modes.append(modes.CodeCompletionMode())
        self.modes.append(modes.ExtendedSelectionMode())
        self.modes.append(modes.FileWatcherMode())
        self.modes.append(modes.OccurrencesHighlighterMode())
        self.modes.append(modes.RightMarginMode())
        self.modes.append(modes.SmartBackSpaceMode())
        self.modes.append(modes.SymbolMatcherMode())
        self.modes.append(modes.ZoomMode())
        self.modes.append(modes.PygmentsSyntaxHighlighter(self.document()))

        # ---  python specific modes
        self.modes.append(pymodes.CommentsMode())
        self.modes.append(pymodes.CalltipsMode())
        self.modes.append(pymodes.FrostedCheckerMode())
        self.modes.append(pymodes.PEP8CheckerMode())
        self.modes.append(pymodes.PyAutoCompleteMode())
        self.modes.append(pymodes.PyAutoIndentMode())
        self.modes.append(pymodes.PyIndenterMode())

        self.syntax_highlighter.color_scheme = api.ColorScheme('darcula')

        QApplication.instance().aboutToQuit.connect(self.cleanup)  # TODO: use this approach in Xi-cam

        # self.file.open('test.py')
        self.insertPlainText('''
# Required to allow controls manipulation in background
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

# Setup RunEngine
from bluesky import RunEngine
from bluesky.plans import inner_product_scan
RE = RunEngine({})

# Set up simulated hardware.
from ophyd.sim import det4, motor1, motor2, motor3
# The 'det4' example detector a 2D Gaussian function of motor1, motor2.

# Move motor1 from 1-5 while moving motor2 from 10-50 -- both in 5 steps.
RE(inner_product_scan([det4], 5,
                      motor1, 1, 5,
                      motor2, 10, 50))
''')

    def cleanup(self):
        self.file.close()
        self.backend.stop()


import torchvision
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np

def repeat_func(x):
    return x.repeat(3, 1, 1)

def get_transforms(dataset_name):
    if dataset_name == 'cifar10':
        train_transforms = transforms.Compose([
            transforms.RandomCrop(32, padding=4),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))])

        test_transforms = transforms.Compose([
            transforms.CenterCrop(32),
            transforms.ToTensor(),
            transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))])
    elif dataset_name == 'mnist':
        train_transforms = transforms.Compose([
            transforms.Resize((32, 32)),
            transforms.ToTensor(),
            transforms.Lambda(repeat_func),
            transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
        ])
        test_transforms = train_transforms
    elif dataset_name == 'svhn':
        train_transforms = transforms.Compose([
            transforms.Resize((32, 32)),
            transforms.ToTensor(),
            transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
        ])
        test_transforms = train_transforms
    else:
        train_transforms = None
        test_transforms = None

    return train_transforms, test_transforms

def get_datasets(dataset_name, train_transforms=None, test_transforms=None):
    if dataset_name == 'cifar10':
        train_dataset = torchvision.datasets.CIFAR10('data/', train=True, transform=train_transforms, download=True)
        test_dataset = torchvision.datasets.CIFAR10('data/', train=False, transform=test_transforms, download=True)
        num_outputs = 10
    elif dataset_name == 'mnist':
        train_dataset = torchvision.datasets.MNIST('data/', train=True, transform=train_transforms, download=True)
        test_dataset = torchvision.datasets.MNIST('data/', train=False, transform=test_transforms, download=True)
        num_outputs = 10
    elif dataset_name == 'svhn':
        train_dataset = torchvision.datasets.SVHN('data/', split='train', transform=train_transforms, download=True)
        test_dataset = torchvision.datasets.SVHN('data/', split='test', transform=test_transforms, download=True)
        num_outputs = 10
    else:
        raise NotImplementedError(f'No such data set {dataset_name}')

    return train_dataset, test_dataset, num_outputs

def get_dataloader(dataset_name, batch_size=128, pin_memory=False, shuffle=True, only_test_transforms=False, num_workers=0):
    train_transforms, test_transforms = get_transforms(dataset_name)
    if only_test_transforms:
        train_transforms = test_transforms

    train_dataset, test_dataset, num_outputs = get_datasets(dataset_name, train_transforms, test_transforms)

    train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers,
                                      pin_memory=pin_memory)
    test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers,
                                      pin_memory=pin_memory)

    return train_dataloader, test_dataloader, num_outputs

def get_train_test_val_dataloaders(dataset_name, batch_size=128, pin_memory=False, num_workers=0, valid_size=0.15,
                                   only_test_transforms=False):

    train_transforms, test_transforms = get_transforms(dataset_name)
    if only_test_transforms:
        train_transforms = test_transforms

    train_dataset, test_dataset, num_outputs = get_datasets(dataset_name, train_transforms, test_transforms)

    num_train = len(train_dataset)
    indices = list(range(num_train))
    split = int(np.floor(valid_size * num_train))
    np.random.seed(1)
    np.random.shuffle(indices)
    train_idx, valid_idx = indices[split:], indices[:split]
    train_sampler = SubsetRandomSampler(train_idx)
    valid_sampler = SubsetRandomSampler(valid_idx)

    train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=pin_memory, sampler=train_sampler)
    valid_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=pin_memory, sampler=valid_sampler)
    test_loader = DataLoader(test_dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=pin_memory)

    return train_loader, test_loader, valid_loader


"""Unit tests for pandas_accessor module."""
from typing import Union
from unittest.mock import patch

import pandas as pd
import pytest

import pandera as pa

@pytest.mark.parametrize(
    "schema1, schema2, data, invalid_data",
    [
        [
            pa.DataFrameSchema({"col": pa.Column(int)}, coerce=True),
            pa.DataFrameSchema({"col": pa.Column(float)}, coerce=True),
            pd.DataFrame({"col": [1, 2, 3]}),
            pd.Series([1, 2, 3]),
        ],
        [
            pa.SeriesSchema(int, coerce=True),
            pa.SeriesSchema(float, coerce=True),
            pd.Series([1, 2, 3]),
            pd.DataFrame({"col": [1, 2, 3]}),
        ],
    ],
)
@pytest.mark.parametrize("inplace", [False, True])
def test_dataframe_series_add_schema(
    schema1: Union[pa.DataFrameSchema, pa.SeriesSchema],
    schema2: Union[pa.DataFrameSchema, pa.SeriesSchema],
    data: Union[pd.DataFrame, pd.Series],
    invalid_data: Union[pd.DataFrame, pd.Series],
    inplace: bool,
) -> None:
    """
    Test that pandas object contains schema metadata after pandera validation.
    """
    validated_data_1 = schema1(data, inplace=inplace)
    if inplace:
        assert data.pandera.schema == schema1
    else:
        assert data.pandera.schema is None
    assert validated_data_1.pandera.schema == schema1

    validated_data_2 = schema2(validated_data_1, inplace=inplace)
    if inplace:
        assert validated_data_1.pandera.schema == schema2
    else:
        assert validated_data_1.pandera.schema == schema1
    assert validated_data_2.pandera.schema == schema2

    with pytest.raises(TypeError, match=f"expected pd.{type(data).__name__}"):
        schema1(invalid_data)

    with pytest.raises(TypeError, match=f"expected pd.{type(data).__name__}"):
        schema2(invalid_data)

    with patch.object(pa.schemas.check_utils, "is_table", return_value=True):
        with patch.object(
            pa.schemas.check_utils,
            "is_field",
            return_value=True,
        ):
            with pytest.raises(TypeError, match="schema arg"):
                schema1(invalid_data)

            with pytest.raises(TypeError, match="schema arg"):
                schema2(invalid_data)