import ast
import collections
import json
import re
import time

import colorlabels as cl

from util import (csv_reader, data_source_file, file_read_contents,
                  file_read_lines, file_write_contents, open_html_in_browser,
                  re_sub_literal, report_file, twlda_result_file,
                  twlda_source_file, visual_file)

def parse_user_topic(desc, encoding='utf-8'):
    logfilename = twlda_result_file('%s/TopicsDistributionOnUsers.txt' % desc)
    user_topic = []

    for line in file_read_lines(logfilename, encoding=encoding):
        data_line = line.strip().split('\t')

        if not data_line:
            continue

        data_line[0] = data_line[0][:-4]  # Remove '.txt'
        data_line[1:] = list(map(float, data_line[1:]))
        user_topic.append(data_line)

    return user_topic

def parse_topic_words(desc, encoding='utf-8'):
    topic_words = collections.defaultdict(list)
    logfilename = twlda_result_file('%s/WordsInTopics.txt' % desc)
    content = file_read_contents(logfilename, encoding=encoding)

    for topic in content.split('Topic ')[1:]:
        topic_id, words = topic.split(':')
        topic_id = int(topic_id)
        for word in words.strip().split('\n'):
            w, p = word.strip().split('\t')
            topic_words[topic_id].append((w, float(p)))

    return topic_words

def load_user_info(userinfofile):
    user_info = {}

    for row in csv_reader(userinfofile):
        row['favourites_count'] = int(row['favourites_count'])
        row['followers_count'] = int(row['followers_count'])
        row['friends_count'] = int(row['friends_count'])
        row['listed_count'] = int(row['listed_count'])
        row['statuses_count'] = int(row['statuses_count'])
        row['verified'] = ast.literal_eval(row['verified'])
        user_info[row['screen_name']] = row

    return user_info

def show_topic_words(topic_words, topic_id):
    sum_prob = sum(p for w, p in topic_words[topic_id])
    return [{
        'word': w,
        'prob': p / sum_prob,
        'text': []
    } for w, p in topic_words[topic_id]]

def organize_data(desc, user_topic, topic_words, user_info, topusers):
    num_topics = len(topic_words)

    topics = [{
        'id': i,
        'words': show_topic_words(topic_words, i),
        'users': [],
        'showAllWords': False,
        'showAllUsers': False,
    } for i in range(num_topics)]

    for i, topic in enumerate(topics):
        user_topic = sorted(user_topic, key=lambda x: x[i + 1], reverse=True)

        for item in user_topic[:topusers]:
            sourcefilename = twlda_source_file('%s/%s.txt' % (desc, item[0]))
            text = file_read_contents(sourcefilename)
            topic['users'].append({
                            'username': item[0],
                            'weight': item[i + 1],
                            'info': user_info.get(item[0]) or {},
                            'text': [t for t in text.split('\n') if t]
                        })

            for line in text.split('\n'):
                for word in topic['words']:
                    if word['word'].lower() in line.lower():
                        word['text'].append(line)

        topic['weight'] = sum(item[i + 1] for item in user_topic)

    topics = sorted(topics, key=lambda x: x['weight'], reverse=True)

    for i, topic in enumerate(topics):
        topic['rank'] = i + 1

    return topics

def export_html(keyword, desc, data, portable, open_browser):
    data = json.dumps({
        'keyword': keyword,
        'description': desc,
        'topics': data,
        'currentWord': {'text': []},
        'currentUser': {'info': {}, 'text': []}
    }, separators=(',', ':'))

    if portable:
        template = file_read_contents(visual_file('template.html'))
        html = re.sub(r'<script src="data.js">(.*)', '', template)
        html = re_sub_literal(r'var data =(.*)', 'var data = ' + data, html)

        reportfilename = 'ldavisual-%s-%s.html' \
            % (desc, time.strftime('%Y%m%d%H%M%S'))
        reportfile = report_file(reportfilename)
        file_write_contents(reportfile, html)
        cl.success('Visualization saved as: %s' % reportfilename)

        if open_browser:
            open_html_in_browser(reportfile)

        return reportfilename
    else:
        file_write_contents(visual_file('data.js'), 'var data = ' + data)
        cl.success('Visualization data saved as: data.js')
        return None

def visualization_twlda(keyword, desc, desc_show, userinfofile, topusers=20,
                        encoding='utf-8', portable=True, open_browser=True):
    cl.section('Twitter-LDA Visualization')

    user_topic = parse_user_topic(desc, encoding=encoding)
    topic_words = parse_topic_words(desc, encoding=encoding)
    user_info = load_user_info(data_source_file(userinfofile))
    result = organize_data('test', user_topic, topic_words, user_info,
                           topusers)
    return export_html(keyword, desc_show, result, portable, open_browser)


"""Handels the game setup"""

import os
from classes.playerc import playerclass as pc
from testing import input_testing as inp
from logger import printf
import classes.race as cr
import classes.alignment as ca

def start_setup():
    """Plays intro and calls the player set up
    returns a list with the player objects"""

    intro()

    players = setup_player()

    quest = quest_line()

    return players, quest

def intro():
    printf("""You're about to enter the world of Jan and Piwo.
These are the gods of this world. Whatever you do, do not anger them!""")

def setup_player():
    """sets up the players in the playerclass
    returns a list with player objects"""

    player_quantity = input("How many players are you? ")
    player_quantity = inp.test_quantaty(player_quantity)

    players = {}
    for i in range(1, player_quantity + 1):
        name = input(f"Player {i} whats your name? ")
        name = name.capitalize()

        race_list = cr.__all__
        race = input(f"""Hello {name}, what race do you want to be?
{race_list} """)
        race = race.capitalize()
        race = inp.test_races(race)

        alignment_list = ca.__all__
        alignment = input(f"""And what will be your alignment?
{ca.__all__} """)
        alignment = alignment.capitalize()
        alignment = inp.test_alignment(alignment)

        p = pc.Player(name, race, alignment)
        players[name] = p

    return players

def quest_line():

    subfolders = [f.name for f in os.scandir('classes/world/story') if f.is_dir()]
    counter = []
    for i, folder in enumerate(subfolders):
        printf(f"[{i}] : ", folder)
        counter.append(f'{i}')

    quest = input('What questline do you wanna choose? ')
    quest = inp.test_quest(quest, counter)

    return subfolders[quest]


# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud import datastore
import logging

def hello_gcs(event, context):
    """Triggered by a change to a Cloud Storage bucket.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    #print(event)

    if event['contentType'] not in ['image/png', 'image/jpeg', 'image/gif', 'image/bmp', 'image/webp', 'image/vnd.microsoft.icon', 'application/pdf', 'image/tiff']:
        logging.debug("Non image type " + event['contentType'] + " file detected")
        return
    else:
        logging.info(event['contentType'] + " file detected")

    # Instantiates a client
    client = vision.ImageAnnotatorClient()
    image = vision.types.Image()
    image.source.image_uri = 'gs://{}/{}'.format(event['bucket'], event['name'])

    objects = client.object_localization(image=image).localized_object_annotations
    ds_client = datastore.Client()
    list1 = []
    print('Number of objects found: {}'.format(len(objects)))
    for object_ in objects:
        entity = datastore.Entity(ds_client.key('Object_Detection', event['name'] + "/" + object_.name))
        list1.append(event['name'])
        list1.append(object_.name)
        list1.append(object_.score)
        print('\n{} (confidence: {})'.format(object_.name, object_.score))
        print('Normalized bounding polygon vertices: ')
        for vertex in object_.bounding_poly.normalized_vertices:
            print(' - ({}, {})'.format(vertex.x, vertex.y))
            list1.append(str((vertex.x,vertex.y)))
        entity.update({
            'FileName' : list1[0] ,
            'ObjectName' : list1[1] ,
            'confidence' : list1[2] ,
            'vertex1' : list1[3] ,
            'vertex2' : list1[4] ,
            'vertex3' : list1[5] ,
            'vertex4': list1[6]
            })
        list1 = []


import math
import statistics
import numpy as np

i_matrix = None
fx = None
mut = None
et = None
rx = [[0.1, 0, 0], [0, 0.1, 0], [0, 0, 0.01]]
length = 0

def initialize(n):
    global et, length, mut, i_matrix, fx
    length = 2 * n + 3
    mut = [[0] for j in range(length)]
    fx = [[0 for i in range(length)] for j in range(3)]
    i_matrix = np.identity(length)
    for j in range(3):
        fx[j][j] = 1
    return mut

def calculate_odo(input_matrix, emat, observations, data_list):
    global et, mut
    et = emat
    mut = input_matrix
    mutu_matrix = get_mutu(input_matrix, observations[0])
    etu_matrix = get_etu(input_matrix, observations[0])
    result = get_result_matrix(input_matrix, observations[0])
    return calculate_observation(mutu_matrix, etu_matrix, result, observations, data_list)

def get_result_matrix(input_matrix, sensor_data):
    result_matrix = [[0] for j in range(3)]
    result_matrix[0][0] = input_matrix[0][0] + sensor_data.data2 * math.cos(input_matrix[2][0] + sensor_data.data1)
    result_matrix[1][0] = input_matrix[1][0] + sensor_data.data2 * math.sin(input_matrix[2][0] + sensor_data.data1)
    result_matrix[2][0] = input_matrix[2][0] + sensor_data.data1 + sensor_data.data3
    return result_matrix

def get_gjac(input_matrix, sensor_data):
    return [[1, 0, -1 * sensor_data.data2 * math.sin(input_matrix[2][0] + sensor_data.data1)],
            [0, 1, sensor_data.data2 * math.cos(input_matrix[2][0] + sensor_data.data1)],
            [0, 0, 1]]

def get_mutu(input_matrix, sensor_data):
    global fx
    return np.transpose(fx).dot(get_result_matrix(input_matrix, sensor_data))

def get_gt(input_matrix, sensor_data):
    global fx, i_matrix
    return np.add(i_matrix, multiply_multi(np.transpose(fx), get_gjac(input_matrix, sensor_data), fx))

def get_etu(input_matrix, sensor_data):
    global et, rx
    gt = get_gt(input_matrix, sensor_data)
    return np.add(multiply_multi(gt, et, np.transpose(gt)), multiply_multi(np.transpose(fx), rx, fx))

def multiply_multi(*args):
    first = np.array(args[0])
    second = np.array(args[1])
    third = np.array(args[2])
    total = first.dot(second)
    return np.array(total).dot(third)

def get_sensor_result(result, readed):
    result_matrix = [[0] for j in range(2)]
    mx = readed.x
    my = readed.y
    result_matrix[0][0] = math.sqrt(math.pow(mx - result[0][0], 2) + math.pow(my - result[1][0], 2))
    result_matrix[1][0] = math.atan((my - result[1][0]) / (mx - result[0][0])) - result[2][0]
    return result_matrix

def get_muj_matrix(mutu, read_data):
    result_matrix = [[0] for j in range(2)]
    rti = read_data[0][0]
    bti = read_data[1][0]
    result_matrix[0][0] = mutu[0][0] + (rti * math.cos(bti + mutu[2][0]))
    result_matrix[1][0] = mutu[1][0] + (rti * math.sin(bti + mutu[2][0]))
    return result_matrix

def get_fxj_matrix(j):
    global length
    fxj = [[0 for i in range(length)] for j in range(5)]
    for i in range(3):
        fxj[i][i] = 1
    for i in range(2):
        fxj[i + 3][int(3 + (2 * j - 2) + i)] = 1
    return fxj

def get_q_matrix(observations):
    q1 = list()
    q2 = list()
    for k in range(len(observations) - 1):
        read_data = observations[k + 1]
        q1.append(read_data.data2)
        q2.append(read_data.data3)
    q_matrix = [[0.01, 0], [0, 0.01]]
    q_matrix[0][0] = statistics.stdev(q1)
    q_matrix[1][1] = statistics.stdev(q2)
    return q_matrix

def calculate_observation(mutu, etu, result, observations, data_list):
    global i_matrix
    added_landmarks = dict()
    q_matrix = get_q_matrix(observations)
    for k in range(len(observations) - 1):
        read_data = observations[k + 1]
        fxj = get_fxj_matrix(read_data.data1)
        zt = get_sensor_result(result, data_list[int(read_data.data1 - 1)])
        if read_data.data1 not in added_landmarks:
            added_landmarks[read_data.data1] = get_muj_matrix(mutu, zt)
        j_matrix = added_landmarks[read_data.data1]
        delta_matrix = [[j_matrix[0][0] - result[0][0]], [j_matrix[1][0] - result[1][0]]]
        q = np.array(delta_matrix).transpose().dot(np.array(delta_matrix))
        q = q[0][0]
        ztu = [[math.sqrt(q)], [math.atan2(delta_matrix[1][0], delta_matrix[0][0]) - result[2][0]]]
        ht_matrix = [[-1 * math.sqrt(q) * delta_matrix[0][0], -1 * math.sqrt(q) * delta_matrix[1][0], 0,
                      math.sqrt(q) * delta_matrix[0][0], math.sqrt(q) * delta_matrix[1][0]],
                     [delta_matrix[1][0], -1 * delta_matrix[0][0], -1 * q, -1 * delta_matrix[1][0], delta_matrix[0][0]]]
        ht = np.array((1 / q) * np.array(ht_matrix).dot(fxj))
        ktr = np.add(multiply_multi(ht, etu, ht.transpose()), q_matrix)
        ktr = np.linalg.inv(ktr)
        kt = multiply_multi(etu.tolist(), ht.transpose().tolist(), ktr.tolist())
        mutul = kt.dot(np.subtract(zt, ztu))
        mutu = np.add(mutu, mutul).tolist()
        etu = np.array(np.subtract(i_matrix, np.array(kt).dot(ht))).dot(etu)
    return mutu, etu


# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json
import os

class ZarascraperPipeline(object):
    def process_item(self, item, spider):
        return item

class JsonWriterPipeline(object):

    shop = 'zara'
    gender = 'mujer'
    dirToSave = '../../../dataset/'+gender+'/'

    def open_spider(self, spider):
        self.current_products_abrigos_chaquetas = []
        self.current_products_vestidos = []
        self.current_products_monos = []
        self.current_products_camisetas = []
        self.current_products_tops_bodies = []
        self.current_products_camisas_blusas = []
        self.current_products_faldas = []
        self.current_products_pantalones_largos = []
        self.current_products_pantalones_cortos = []
        self.current_products_sudaderas_jerseis = []

        self.new_products_abrigos_chaquetas = []
        self.new_products_vestidos = []
        self.new_products_monos = []
        self.new_products_camisetas = []
        self.new_products_tops_bodies = []
        self.new_products_camisas_blusas = []
        self.new_products_faldas = []
        self.new_products_pantalones_largos = []
        self.new_products_pantalones_cortos = []
        self.new_products_sudaderas_jerseis = []

        self.update_products_abrigos_chaquetas = []
        self.update_products_vestidos = []
        self.update_products_monos = []
        self.update_products_camisetas = []
        self.update_products_tops_bodies = []
        self.update_products_camisas_blusas = []
        self.update_products_faldas = []
        self.update_products_pantalones_largos = []
        self.update_products_pantalones_cortos = []
        self.update_products_sudaderas_jerseis = []

    def close_spider(self, spider):

        categoryList = ['abrigos_chaquetas'
        ,'camisas_blusas','camisetas',
        'faldas','monos','pantalones_cortos','pantalones_largos','sudaderas_jerseis',
        'tops_bodies', 'vestidos'
        ]

        for category in categoryList:
            dirToSave = self.dirToSave+category+'/'+self.shop+'/products/'

            if category == 'abrigos_chaquetas':
                current_products = self.current_products_abrigos_chaquetas
                new_products = self.new_products_abrigos_chaquetas
                update_products = self.update_products_abrigos_chaquetas
            elif category == 'vestidos':
                current_products =self.current_products_vestidos
                new_products = self.new_products_vestidos
                update_products = self.update_products_vestidos
            elif category == 'monos':
                current_products =self.current_products_monos
                new_products = self.new_products_monos
                update_products = self.update_products_monos
            elif category == 'camisetas':
                current_products =self.current_products_camisetas
                new_products = self.new_products_camisetas
                update_products = self.update_products_camisetas
            elif category == 'tops_bodies':
                current_products =self.current_products_tops_bodies
                new_products = self.new_products_tops_bodies
                update_products = self.update_products_tops_bodies
            elif category == 'camisas_blusas':
                current_products =self.current_products_camisas_blusas
                new_products = self.new_products_camisas_blusas
                update_products = self.update_products_camisas_blusas
            elif category == 'faldas':
                current_products =self.current_products_faldas
                new_products = self.new_products_faldas
                update_products = self.update_products_faldas
            elif category == 'pantalones_largos':
                current_products =self.current_products_pantalones_largos
                new_products = self.new_products_pantalones_largos
                update_products = self.update_products_pantalones_largos
            elif category == 'pantalones_cortos':
                current_products =self.current_products_pantalones_cortos
                new_products = self.new_products_pantalones_cortos
                update_products = self.update_products_pantalones_cortos
            elif category == 'sudaderas_jerseis':
                current_products =self.current_products_sudaderas_jerseis
                new_products = self.new_products_sudaderas_jerseis
                update_products = self.update_products_sudaderas_jerseis

            if len(current_products) > 0:
                try:
                    with open(dirToSave+'previous_products.json') as f:
                        previous_products = json.load(f)

                except FileNotFoundError as exc:
                        previous_products = []

                aux_previous_products = []
                for product in previous_products:

                    if product not in current_products:
                        aux_previous_products.append(product)

                with open(dirToSave+'current_products.json', 'w') as f:
                    json.dump(list(set(current_products)), f, indent = 2, separators = (',',': '))

                with open(dirToSave+'new_products.json', 'w') as f:
                    json.dump(list(set(new_products)), f, indent = 2, separators = (',',': '))

                with open(dirToSave+'update_products.json', 'w') as f:
                    json.dump(list(set(update_products)), f, indent = 2, separators = (',',': '))

                with open(dirToSave+'previous_products.json', 'w') as f:
                    json.dump(aux_previous_products, f, indent = 2, separators = (',',': '))

    def process_item(self, item, spider):
        if item['category'] == 'abrigos_chaquetas':
            self.current_products_abrigos_chaquetas.append(item['productId'])
            if item['new']:
                self.new_products_abrigos_chaquetas.append(item['productId'])
            elif item['update']:
                self.update_products_abrigos_chaquetas.append(item['productId'])
        elif item['category'] == 'vestidos':
            self.current_products_vestidos.append(item['productId'])
            if item['new']:
                self.new_products_vestidos.append(item['productId'])
            elif item['update']:
                self.update_products_vestidos.append(item['productId'])
        elif item['category'] == 'monos':
            self.current_products_monos.append(item['productId'])
            if item['new']:
                self.new_products_monos.append(item['productId'])
            elif item['update']:
                self.update_products_monos.append(item['productId'])
        elif item['category'] == 'camisetas':
            self.current_products_camisetas.append(item['productId'])
            if item['new']:
                self.new_products_camisetas.append(item['productId'])
            elif item['update']:
                self.update_products_camisetas.append(item['productId'])
        elif item['category'] == 'tops_bodies':
            self.current_products_tops_bodies.append(item['productId'])
            if item['new']:
                self.new_products_tops_bodies.append(item['productId'])
            elif item['update']:
                self.update_products_tops_bodies.append(item['productId'])
        elif item['category'] == 'camisas_blusas':
            self.current_products_camisas_blusas.append(item['productId'])
            if item['new']:
                self.new_products_camisas_blusas.append(item['productId'])
            elif item['update']:
                self.update_products_camisas_blusas.append(item['productId'])
        elif item['category'] == 'faldas':
            self.current_products_faldas.append(item['productId'])
            if item['new']:
                self.new_products_faldas.append(item['productId'])
            elif item['update']:
                self.update_products_faldas.append(item['productId'])
        elif item['category'] == 'pantalones_largos':
            self.current_products_pantalones_largos.append(item['productId'])
            if item['new']:
                self.new_products_pantalones_largos.append(item['productId'])
            elif item['update']:
                self.update_products_pantalones_largos.append(item['productId'])
        elif item['category'] == 'pantalones_cortos':
            self.current_products_pantalones_cortos.append(item['productId'])
            if item['new']:
                self.new_products_pantalones_cortos.append(item['productId'])
            elif item['update']:
                self.update_products_pantalones_cortos.append(item['productId'])
        elif item['category'] == 'sudaderas_jerseis':
            self.current_products_sudaderas_jerseis.append(item['productId'])
            if item['new']:
                self.new_products_sudaderas_jerseis.append(item['productId'])
            elif item['update']:
                self.update_products_sudaderas_jerseis.append(item['productId'])

        return item


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
amvmod

Module containing functions for predict_amv
Working on updating documentation...

@author: gliu
"""

from scipy.signal import butter,filtfilt

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.util import add_cyclic_point
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter

## Processing/Analysis ----
def find_nan(data,dim):
    """
    For a 2D array, remove any point if there is a nan in dimension [dim]

    Inputs:
        1) data: 2d array, which will be summed along last dimension
        2) dim: dimension to sum along. 0 or 1
    Outputs:
        1) okdata: data with nan points removed
        2) knan: boolean array with indices of nan points

    """

    # Sum along select dimension
    if len(data.shape) > 1:
        datasum = np.sum(data,axis=dim)
    else:
        datasum = data.copy()

    # Find non nan pts
    knan  = np.isnan(datasum)
    okpts = np.invert(knan)

    if len(data.shape) > 1:
        if dim == 0:
            okdata = data[:,okpts]
        elif dim == 1:
            okdata = data[okpts,:]
    else:
        okdata = data[okpts]

    return okdata,knan,okpts

def eof_simple(pattern,N_mode,remove_timemean):
    """
    Simple EOF function based on script by Yu-Chiao

    Inputs:
        1) pattern: Array of Space x Time [MxN], no NaNs
        2) N_mode:  Number of Modes to output
        3) remove_timemean: Set 1 to remove mean along N

    Outputs:
        1) eof: EOF patterns   [M x N_mode]
        2) pcs: PC time series [N x N_mode]
        3) varexp: % Variance explained [N_mode]

    Dependencies:
        import numpy as np

    """
    pattern1 = pattern.copy()
    nt = pattern1.shape[1] # Get time dimension size
    ns = pattern1.shape[0] # Get space dimension size

    # Preallocate
    eofs = np.zeros((ns,N_mode))
    pcs  = np.zeros((nt,N_mode))
    varexp = np.zeros((N_mode))

    # Remove time mean if option is set
    if remove_timemean == 1:
        pattern1 = pattern1 - pattern1.mean(axis=1)[:,None] # Note, the None adds another dimension and helps with broadcasting

    # Compute SVD
    [U, sigma, V] = np.linalg.svd(pattern1, full_matrices=False)

    # Compute variance (total?)
    norm_sq_S = (sigma**2).sum()

    for II in range(N_mode):

        # Calculate explained variance
        varexp[II] = sigma[II]**2/norm_sq_S

        # Calculate PCs
        pcs[:,II] = np.squeeze(V[II,:]*np.sqrt(nt-1))

        # Calculate EOFs and normalize
        eofs[:,II] = np.squeeze(U[:,II]*sigma[II]/np.sqrt(nt-1))
    return eofs, pcs, varexp

def coarsen_byavg(invar,lat,lon,deg,tol,bboxnew=False,latweight=True,verbose=True):
    """
    Coarsen an input variable to specified resolution [deg]
    by averaging values within a search tolerance for each new grid box.
    To take the area-weighted average, set latweight=True

    Dependencies: numpy as np

    Parameters
    ----------
    invar : ARRAY [TIME x LAT x LON]
        Input variable to regrid
    lat : ARRAY [LAT]
        Latitude values of input
    lon : ARRAY [LON]
        Longitude values of input
    deg : INT
        Resolution of the new grid (in degrees)
    tol : TYPE
        Search tolerance (pulls all lat/lon +/- tol)

    OPTIONAL ---
    bboxnew : ARRAY or False
        New bounds to regrid in order - [lonW, lonE, latS, latN]
        Set to False to pull directly from first and last coordinates
    latweight : BOOL
        Set to true to apply latitude weighted-average
    verbose : BOOL
        Set to true to print status

    Returns
    -------
    outvar : ARRAY [TIME x LAT x LON]
        Regridded variable
    lat5 : ARRAY [LAT]
        New Latitude values of input
    lon5 : ARRAY [LON]
        New Longitude values of input

    """

    # Make new Arrays
    if not bboxnew:
        lon5 = np.arange(lon[0],lon[-1]+deg,deg)
        lat5 = np.arange(lat[0],lat[-1]+deg,deg)
    else:
        lon5 = np.arange(bboxnew[0],bboxnew[1]+deg,deg)
        lat5 = np.arange(bboxnew[2],bboxnew[3]+deg,deg)

    # Check to see if any longitude values are degrees Easy
    if any(lon>180):
        lonflag = True

    # Set up latitude weights
    if latweight:
        _,Y = np.meshgrid(lon,lat)
        wgt = np.cos(np.radians(Y)) # [lat x lon]
        invar *= wgt[None,:,:] # Multiply by latitude weight

    # Get time dimension and preallocate
    nt = invar.shape[0]
    outvar = np.zeros((nt,len(lat5),len(lon5)))

    # Loop and regrid
    i=0
    for o in range(len(lon5)):
        for a in range(len(lat5)):
            lonf = lon5[o]
            latf = lat5[a]

            # check longitude
            if lonflag:
                if lonf < 0:
                    lonf+=360

            lons = np.where((lon >= lonf-tol) & (lon <= lonf+tol))[0]
            lats = np.where((lat >= latf-tol) & (lat <= latf+tol))[0]

            varf = invar[:,lats[:,None],lons[None,:]]

            if latweight:
                wgtbox = wgt[lats[:,None],lons[None,:]]
                varf = np.sum(varf/np.sum(wgtbox,(0,1)),(1,2)) # Divide by the total weight for the box
            else:
                varf = varf.mean((1,2))
            outvar[:,a,o] = varf.copy()
            i+= 1
            msg="\rCompleted %i of %i"% (i,len(lon5)*len(lat5))
            print(msg,end="\r",flush=True)
    return outvar,lat5,lon5

def regress_2d(A,B,nanwarn=1):
    """
    Regresses A (independent variable) onto B (dependent variable), where
    either A or B can be a timeseries [N-dimensions] or a space x time matrix
    [N x M]. Script automatically detects this and permutes to allow for matrix
    multiplication.

    Returns the slope (beta) for each point, array of size [M]

    """
    # Determine if A or B is 2D and find anomalies

    # Compute using nan functions (slower)
    if np.any(np.isnan(A)) or np.any(np.isnan(B)):
        if nanwarn == 1:
            print("NaN Values Detected...")

        # 2D Matrix is in A [MxN]
        if len(A.shape) > len(B.shape):

            # Tranpose A so that A = [MxN]
            if A.shape[1] != B.shape[0]:
                A = A.T

            # Set axis for summing/averaging
            a_axis = 1
            b_axis = 0

            # Compute anomalies along appropriate axis
            Aanom = A - np.nanmean(A,axis=a_axis)[:,None]
            Banom = B - np.nanmean(B,axis=b_axis)

        # 2D matrix is B [N x M]
        elif len(A.shape) < len(B.shape):

            # Tranpose B so that it is [N x M]
            if B.shape[0] != A.shape[0]:
                B = B.T

            # Set axis for summing/averaging
            a_axis = 0
            b_axis = 0

            # Compute anomalies along appropriate axis
            Aanom = A - np.nanmean(A,axis=a_axis)
            Banom = B - np.nanmean(B,axis=b_axis)[None,:]

        # Calculate denominator, summing over N
        Aanom2 = np.power(Aanom,2)
        denom = np.nansum(Aanom2,axis=a_axis)

        # Calculate Beta
        beta = Aanom @ Banom / denom

        b = (np.nansum(B,axis=b_axis) - beta * np.nansum(A,axis=a_axis))/A.shape[a_axis]
    else:
        # 2D Matrix is in A [MxN]
        if len(A.shape) > len(B.shape):

            # Tranpose A so that A = [MxN]
            if A.shape[1] != B.shape[0]:
                A = A.T

            # Set axis for summing/averaging
            a_axis = 1
            b_axis = 0

            # Compute anomalies along appropriate axis
            Aanom = A - np.mean(A,axis=a_axis)[:,None]
            Banom = B - np.mean(B,axis=b_axis)

        # 2D matrix is B [N x M]
        elif len(A.shape) < len(B.shape):

            # Tranpose B so that it is [N x M]
            if B.shape[0] != A.shape[0]:
                B = B.T

            # Set axis for summing/averaging
            a_axis = 0
            b_axis = 0

            # Compute anomalies along appropriate axis
            Aanom = A - np.mean(A,axis=a_axis)
            Banom = B - np.mean(B,axis=b_axis)[None,:]

        # Calculate denominator, summing over N
        Aanom2 = np.power(Aanom,2)
        denom = np.sum(Aanom2,axis=a_axis)

        # Calculate Beta
        beta = Aanom @ Banom / denom

        b = (np.sum(B,axis=b_axis) - beta * np.sum(A,axis=a_axis))/A.shape[a_axis]

    return beta,b

def sel_region(var,lon,lat,bbox,reg_avg=0,reg_sum=0,warn=1):
    """

    Select Region

    Inputs
        1) var: ARRAY, variable with dimensions [lon x lat x otherdims]
        2) lon: ARRAY, Longitude values
        3) lat: ARRAY, Latitude values
        4) bbox: ARRAY, bounding coordinates [lonW lonE latS latN]
        5) reg_avg: BOOL, set to 1 to return regional average
        6) reg_sum: BOOL, set to 1 to return regional sum
        7) warn: BOOL, set to 1 to print warning text for region selection
    Outputs:
        1) varr: ARRAY: Output variable, cut to region
        2+3), lonr, latr: ARRAYs, new cut lat/lon

    """

    # Find indices
    klat = np.where((lat >= bbox[2]) & (lat <= bbox[3]))[0]
    if bbox[0] < bbox[1]:
        klon = np.where((lon >= bbox[0]) & (lon <= bbox[1]))[0]
    elif bbox[0] > bbox[1]:
        if warn == 1:
            print("Warning, crossing the prime meridian!")
        klon = np.where((lon <= bbox[1]) | (lon >= bbox[0]))[0]

    lonr = lon[klon]
    latr = lat[klat]

    #print("Bounds from %.2f to %.2f Latitude and %.2f to %.2f Longitude" % (latr[0],latr[-1],lonr[0],lonr[-1]))

    # Index variable
    varr = var[klon[:,None],klat[None,:],...]

    if reg_avg==1:
        varr = np.nanmean(varr,(0,1))
        return varr
    elif reg_sum == 1:
        varr = np.nansum(varr,(0,1))
        return varr
    return varr,lonr,latr

def calc_AMV(lon,lat,sst,bbox,order,cutofftime,awgt,lpf=1):
    """
    Calculate AMV Index for detrended/anomalized SST data [LON x LAT x Time]
    given bounding box [bbox]. Applies area weight based on awgt

    Parameters
    ----------
    lon : ARRAY [LON]
        Longitude values
    lat : ARRAY [LAT]
        Latitude Values
    sst : ARRAY [LON x LAT x TIME]
        Sea Surface Temperature
    bbox : ARRAY [LonW,LonE,LonS,LonN]
        Bounding Box for Area Average
    order : INT
        Butterworth Filter Order
    cutofftime : INT
        Filter Cutoff, expressed in same timesteps as input data
    awgt : INT
        0 = No weight, 1 = cos(lat), 2 = sqrt(cos(lat))

    Returns
    -------
    amv: ARRAY [TIME]
        AMV Index (Not Standardized)

    aa_sst: ARRAY [TIME]
        Area Averaged SST

    # Dependencies
    functions
        area_avg
    modules
        numpy as np
        from scipy.signal import butter,filtfilt
    """

    # Take the weighted area average
    aa_sst = area_avg(sst,bbox,lon,lat,awgt)

    # Design Butterworth Lowpass Filter
    filtfreq = len(aa_sst)/cutofftime
    nyquist  = len(aa_sst)/2
    cutoff = filtfreq/nyquist
    b,a    = butter(order,cutoff,btype="lowpass")

    # Compute AMV Index
    amv = filtfilt(b,a,aa_sst)

    return amv,aa_sst

def detrend_poly(x,y,deg):
    """
    Matrix for of polynomial detrend
    # Based on :https://stackoverflow.com/questions/27746297/detrend-flux-time-series-with-non-linear-trend

    Inputs:
        1) x --> independent variable
        2) y --> 2D Array of dependent variables
        3) deg --> degree of polynomial to fit

    """
    # Transpose to align dimensions for polyfit
    if len(y) != len(x):
        y = y.T

    # Get the fit
    fit = np.polyfit(x,y,deg=deg)

    # Prepare matrix (x^n, x^n-1 , ... , x^0)
    #inputs = np.array([np.power(x,d) for d in range(len(fit))])
    inputs = np.array([np.power(x,d) for d in reversed(range(len(fit)))])
    # Calculate model
    model = fit.T.dot(inputs)
    # Remove trend
    ydetrend = y - model.T
    return ydetrend,model

def lon360to180(lon360,var):
    """
    Convert Longitude from Degrees East to Degrees West
    Inputs:
        1. lon360 - array with longitude in degrees east
        2. var    - corresponding variable [lon x lat x time]
    """
    kw = np.where(lon360 >= 180)[0]
    ke = np.where(lon360 < 180)[0]
    lon180 = np.concatenate((lon360[kw]-360,lon360[ke]),0)
    var = np.concatenate((var[kw,...],var[ke,...]),0)

    return lon180,var

def area_avg(data,bbox,lon,lat,wgt):

    """
    Function to find the area average of [data] within bounding box [bbox],
    based on wgt type (see inputs)

    Inputs:
        1) data: target array [lat x lon x otherdims]
        2) bbox: bounding box [lonW, lonE, latS, latN]
        3) lon:  longitude coordinate
        4) lat:  latitude coodinate
        5) wgt:  number to indicate weight type
                    0 = no weighting
                    1 = cos(lat)
                    2 = sqrt(cos(lat))

    Output:
        1) data_aa: Area-weighted array of size [otherdims]

    Dependencies:
        numpy as np

    """

    # Find lat/lon indices
    kw = np.abs(lon - bbox[0]).argmin()
    ke = np.abs(lon - bbox[1]).argmin()
    ks = np.abs(lat - bbox[2]).argmin()
    kn = np.abs(lat - bbox[3]).argmin()

    # Select the region
    sel_data = data[kw:ke+1,ks:kn+1,:]

    # If wgt == 1, apply area-weighting
    if wgt != 0:

        # Make Meshgrid
        _,yy = np.meshgrid(lon[kw:ke+1],lat[ks:kn+1])

        # Calculate Area Weights (cosine of latitude)
        if wgt == 1:
            wgta = np.cos(np.radians(yy)).T
        elif wgt == 2:
            wgta = np.sqrt(np.cos(np.radians(yy))).T

        # Remove nanpts from weight, ignoring any pt with nan in otherdims
        nansearch = np.sum(sel_data,2) # Sum along otherdims
        wgta[np.isnan(nansearch)] = 0

        # Apply area weights
        #data = data * wgtm[None,:,None]
        sel_data  = sel_data * wgta[:,:,None]

    # Take average over lon and lat
    if wgt != 0:

        # Sum weights to get total area
        sel_lat  = np.sum(wgta,(0,1))

        # Sum weighted values
        data_aa = np.nansum(sel_data/sel_lat,axis=(0,1))
    else:
        # Take explicit average
        data_aa = np.nanmean(sel_data,(0,1))

    return data_aa

def regress2ts(var,ts,normalizeall=0,method=1,nanwarn=1):
    """
    regress variable var [lon x lat x time] to timeseries ts [time]

    Parameters
    ----------
    var : TYPE
        DESCRIPTION.
    ts : TYPE
        DESCRIPTION.
    normalizeall : TYPE, optional
        DESCRIPTION. The default is 0.
    method : TYPE, optional
        DESCRIPTION. The default is 1.
    nanwarn : TYPE, optional
        DESCRIPTION. The default is 1.

    Returns
    -------
    var_reg : TYPE
        DESCRIPTION.

    """

    # Anomalize and normalize the data (time series is assumed to have been normalized)
    if normalizeall == 1:
        varmean = np.nanmean(var,2)
        varstd  = np.nanstd(var,2)
        var = (var - varmean[:,:,None]) /varstd[:,:,None]

    # Get variable shapes
    londim = var.shape[0]
    latdim = var.shape[1]

    # 1st method is matrix multiplication
    if method == 1:

        # Combine the spatial dimensions

        var = np.reshape(var,(londim*latdim,var.shape[2]))

        # Find Nan Points
        # sumvar = np.sum(var,1)

        # # Find indices of nan pts and non-nan (ok) pts
        # nanpts = np.isnan(sumvar)
        # okpts  = np.invert(nanpts)

        # # Drop nan pts and reshape again to separate space and time dimensions
        # var_ok = var[okpts,:]
        #var[np.isnan(var)] = 0

        # Perform regression
        #var_reg = np.matmul(np.ma.anomalies(var,axis=1),np.ma.anomalies(ts,axis=0))/len(ts)
        var_reg,_ = regress_2d(ts,var,nanwarn=nanwarn)

        # Reshape to match lon x lat dim
        var_reg = np.reshape(var_reg,(londim,latdim))

    # 2nd method is looping point by point
    elif method == 2:

        # Preallocate
        var_reg = np.zeros((londim,latdim))

        # Loop lat and long
        for o in range(londim):
            for a in range(latdim):

                # Get time series for that period
                vartime = np.squeeze(var[o,a,:])

                # Skip nan points
                if any(np.isnan(vartime)):
                    var_reg[o,a]=np.nan
                    continue

                # Perform regression
                r = np.polyfit(ts,vartime,1)
                #r=stats.linregress(vartime,ts)
                var_reg[o,a] = r[0]
                #var_reg[o,a]=stats.pearsonr(vartime,ts)[0]

    return var_reg

## Plotting ----
def plot_AMV(amv,ax=None):

    """
    Plot amv time series

    Dependencies:

    matplotlib.pyplot as plt
    numpy as np
    """
    if ax is None:
        ax = plt.gca()

    htimefull = np.arange(len(amv))

    ax.plot(htimefull,amv,color='k')
    ax.fill_between(htimefull,0,amv,where=amv>0,facecolor='red',interpolate=True,alpha=0.5)
    ax.fill_between(htimefull,0,amv,where=amv<0,facecolor='blue',interpolate=True,alpha=0.5)

    return ax

def plot_AMV_spatial(var,lon,lat,bbox,cmap,cint=[0,],clab=[0,],ax=None,pcolor=0,labels=True,fmt="%.1f",clabelBG=False,fontsize=10):
    fig = plt.gcf()

    if ax is None:
        ax = plt.gca()
        ax = plt.axes(projection=ccrs.PlateCarree())

    # Add cyclic point to avoid the gap
    var,lon1 = add_cyclic_point(var,coord=lon)

    # Set  extent
    ax.set_extent(bbox)

    # Add filled coastline
    ax.add_feature(cfeature.LAND,color=[0.4,0.4,0.4])

    if len(cint) == 1:
        # Automaticall set contours to max values
        cmax = np.nanmax(np.abs(var))
        cmax = np.round(cmax,decimals=2)
        cint = np.linspace(cmax*-1,cmax,9)

    if pcolor == 0:

        # Draw contours
        cs = ax.contourf(lon1,lat,var,cint,cmap=cmap)

        # Negative contours
        cln = ax.contour(lon1,lat,var,
                    cint[cint<0],
                    linestyles='dashed',
                    colors='k',
                    linewidths=0.5,
                    transform=ccrs.PlateCarree())

        # Positive Contours
        clp = ax.contour(lon1,lat,var,
                    cint[cint>=0],
                    colors='k',
                    linewidths=0.5,
                    transform=ccrs.PlateCarree())

        if labels is True:
            clabelsn= ax.clabel(cln,colors=None,fmt=fmt,fontsize=fontsize)
            clabelsp= ax.clabel(clp,colors=None,fmt=fmt,fontsize=fontsize)

            # if clabelBG is True:
            #     [txt.set_backgroundcolor('white') for txt in clabelsn]
            #     [txt.set_backgroundcolor('white') for txt in clabelsp]
    else:

        cs = ax.pcolormesh(lon1,lat,var,vmin = cint[0],vmax=cint[-1],cmap=cmap)

    # Add Gridlines
    gl = ax.gridlines(draw_labels=True,linewidth=0.75,color='gray',linestyle=':')

    gl.top_labels = gl.right_labels = False
    gl.xformatter = LongitudeFormatter(degree_symbol='')
    gl.yformatter = LatitudeFormatter(degree_symbol='')
    gl.xlabel_style={'size':8}
    gl.ylabel_style={'size':8}
    if len(clab) == 1:
        cbar= fig.colorbar(cs,ax=ax,fraction=0.046, pad=0.04,format=fmt)
        cbar.ax.tick_params(labelsize=8)
    else:
        cbar = fig.colorbar(cs,ax=ax,ticks=clab,fraction=0.046, pad=0.04,format=fmt)
        cbar.ax.tick_params(labelsize=8)
    #cbar.ax.set_yticklabels(['{:.0f}'.format(x) for x in cint], fontsize=10, weight='bold')

    return ax

def deseason_lazy(ds,return_scycle=False):
    """
    Deseason function without reading out the values. Remove the seasonal cycle by subtracting the monthly anomalies
    Input:
        ds : DataArray
            Data to be deseasoned
        return_scycle : BOOL (Optional)
            Set to true to return the seasonal cycle that was removed
    Output:
        data_deseason : DataArray
            Deseasoned data
    """
    data_deseason = ds.groupby('time.month') - ds.groupby('time.month').mean('time')

    if return_scycle:
        return data_deseason,ds.groupby('time.month').mean('time')
    return data_deseason

def init_map(bbox,crs=ccrs.PlateCarree(),ax=None):
    """
    Quickly initialize a map for plotting
    """
    # Create Figure/axes
    #fig = plt.gcf()

    #ax = fig.add_subplot(1,1,1,projection=ccrs.PlateCarree())
    if ax is None:
        ax = plt.gca()
    #ax = plt.axes(projection=ccrs.PlateCarree())

    ax.set_extent(bbox,crs)

    # Add Filled Coastline
    ax.add_feature(cfeature.COASTLINE)
    #ax.add_feature(cfeature.LAND,facecolor='k',zorder=-1)

    # Add Gridlines
    gl = ax.gridlines(draw_labels=True,linewidth=0.5,color='gray',linestyle=':')
    gl.top_labels = gl.right_labels = False

    gl.xformatter = LongitudeFormatter(degree_symbol='')
    gl.yformatter = LatitudeFormatter(degree_symbol='')

    return ax


# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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
#
#     https://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.

"""Setup script."""

import os

from setuptools import find_packages
from setuptools import setup

version = '0.0.1'

def _get_requirements():
  """Parses requirements.txt file."""
  install_requires_tmp = []
  dependency_links_tmp = []
  with open(
      os.path.join(os.path.dirname(__file__), './requirements.txt'), 'r') as f:
    for line in f:
      package_name = line.strip()
      # Skip empty line or comments starting with "#".
      if not package_name or package_name[0] == '#':
        continue
      if package_name.startswith('-e '):
        dependency_links_tmp.append(package_name[3:].strip())
      else:
        install_requires_tmp.append(package_name)
  return install_requires_tmp, dependency_links_tmp

install_requires, dependency_links = _get_requirements()

install_requires.append('tf-nightly')

setup(
    name='keras-nlp',
    version=version,
    description='Keras Natural Language Processing Library',
    url='https://github.com/keras-team/keras-nlp',
    author='The Keras authors',
    author_email='keras-team@google.com',
    license='Apache License 2.0',
    install_requires=install_requires,
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.6',
        'Operating System :: Unix',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: MacOS',
        'Intended Audience :: Science/Research',
        'Topic :: Scientific/Engineering',
        'Topic :: Software Development'
    ],
    packages=find_packages(exclude=('tests',)),
    exclude_package_data={'': ['*_test.py',],},
    dependency_links=dependency_links,
    python_requires='>=3.6',
)


import unittest

# 定义测试类
from time import sleep

from base.get_driver import GetDriver
from page.page_cart import PageCart
from page.page_login import PageLogin

class TestCart(unittest.TestCase):
    # 定义 setup
    def setUp(self):
        # 获取driver
        self.driver = GetDriver().get_driver()
        # 实例化 PageCart页面
        self.cart = PageCart(self.driver)
        # 调用成功登录 依赖
        PageLogin(self.driver).page_login_success()
        # 跳转到首页
        sleep(2)
        self.cart.page_open_index()

    # 定义 teardown
    def tearDown(self):
        # 关闭driver
        GetDriver().quit_driver()

    # 定义测试购物车方法
    def test_add_cart(self):
        # 调用 组合添加购物车业务方法
        self.cart.page_add_cart()
        # 断言是否添加成功
        msg = self.cart.page_get_text()
        self.assertEqual(msg, "添加成功")
        # 关闭窗口
        self.cart.page_close_window()


import sys

from PyQt5 import Qt, QtCore, QtGui
from PyQt5.QtWidgets import(
    QApplication,
    QWidget,
    QStyle,
    QPushButton
)

class MainWindow(QWidget):
    """Main Window"""
    def __init__(self):
        super().__init__()
        button = QPushButton("push")
        button.setParent(self)
        style = button.style()
        icon = style.standardIcon(QStyle.SP_MessageBoxCritical)
        button.setIcon(icon)

app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()


from Inner_Functions import *

def main():

    # Creating variables and lists to be used throughout the program
    mins_without_break = 0
    task_list = []
    time_block_list = []

    start = input("Press enter when you would like to begin creating your schedule for today")
    time.sleep(1)

    # Allowing user to input how long they would like to work before taking a break
    break_time_input = False
    while break_time_input == False:
        break_time = input("First, enter after how many minutes of work you would like to take breaks. "
                           "Please input a positive integer value.")
        time.sleep(1)
        try:
            break_time_int = int(break_time)
            if break_time_int > 0:
                print("I will suggest that you take breaks after " + break_time + " minutes of working.")
                break_time_input = True
            else:
                print("Please enter a number greater than 0")
                time.sleep(1)
        except ValueError:
            print("I do not understand that input")

    time.sleep(1)

    # Starting a loop to allow the user to continually add tasks to their schedule
    new_task = True
    while new_task == True:
        task, time_block_number, break_task, work_task, mins_without_break = getNewTask(mins_without_break)

        task_list.append(task)
        # print(task_list)
        time_block_list.append(time_block_number)
        # print(time_block_list)
        time.sleep(1)

        # Suggesting the user takes a break if they create a schedule that makes them work for a long time
        if mins_without_break >= break_time_int:
            need_break = needBreak(mins_without_break)
            if need_break == True:
                task, time_block_number, mins_without_break = getBreak()
                task_list.append(task)
                # print(task_list)
                time_block_list.append(time_block_number)
                # print(time_block_list)
                time.sleep(1)

        # Asking the user if they would like to continue the loop of adding tasks to their schedule
        valid_task_input = False
        while valid_task_input == False:
            new_task_input = input("Would you like to add another task to your schedule? Enter 'y' or 'n'").lower()
            if new_task_input == "y":
                valid_task_input = True
            elif new_task_input == "n":
                valid_task_input = True
                new_task = False
            else:
                print("I do not understand that input")
                time.sleep(1)
        time.sleep(1)

    # Checking if the user likes the final list they created
    # And giving them the opportunity to edit it if they do not
    task_list, time_block_list, schedule_is_okay = isScheduleOkay(task_list, time_block_list)

    time.sleep(1)

    # If the user made any changes to the schedule through the previous function,
    # Checking once again to see if the schedule has any spots where the user may want a break
    # And recommending to the user that they add a break
    if schedule_is_okay == False:
        task_list, time_block_list, break_added = checkForBreaks(task_list, time_block_list, break_time_int)
        time.sleep(1)

    # If the user added a break, they get asked once again to confirm their final schedule
    # And are given the option to edit it if they so wish
        if break_added == True:
            task_list, time_block_list, schedule_is_okay = isFinalScheduleOkay(task_list, time_block_list)
            if schedule_is_okay == False:
                task_list, time_block_list, schedule_is_okay = isScheduleOkay(task_list, time_block_list)

    # Calls a function that creates a timer for each of the tasks for the user to do
    timeTasks(task_list, time_block_list)

if __name__ == '__main__':
    main()


#! /usr/bin/env python
# -*- coding: Latin-1 -*-

from Tkinter import *

class MenuBar(Frame):
    """Barre de menus déroulants"""
    def __init__(self, boss =None):
        Frame.__init__(self, borderwidth =2)

        ##### Menu <Fichier> #####
        fileMenu = Menubutton(self, text ='Fichier')
        fileMenu.pack(side =LEFT)
        # Partie "déroulante" :
        me1 = Menu(fileMenu)
        me1.add_command(label ='Effacer', underline =0,
                        command = boss.effacer)
        me1.add_command(label ='Terminer', underline =0,
                        command = boss.quit)
        # Intégration du menu :
        fileMenu.configure(menu = me1)

        ##### Menu <Musiciens> #####
        self.musi = Menubutton(self, text ='Musiciens')
        self.musi.pack(side =LEFT, padx='3')
        # Partie "déroulante" du menu <Musiciens> :
        me1 = Menu(self.musi)
        me1.add_command(label ='17e siècle', underline =1,
                        foreground ='red', background = 'yellow',
                        font =('Comic Sans MS',11),
                        command = boss.showMusi17)
        me1.add_command(label ='18e siècle', underline =1,
                        foreground='royal blue', background ='white',
                        font =('Comic Sans MS',11,'bold'),
                        command = boss.showMusi18)
        # Intégration du menu :
        self.musi.configure(menu = me1)

        ##### Menu <Peintres> #####
        self.pein = Menubutton(self, text ='Peintres')
        self.pein.pack(side =LEFT, padx='3')
        # Partie "déroulante" :
        me1 = Menu(self.pein)
        me1.add_command(label ='classiques', state=DISABLED)
        me1.add_command(label ='romantiques', underline =0,
                        command = boss.showRomanti)
        # Sous-menu pour les peintres impressionistes :
        me2 = Menu(me1)
        me2.add_command(label ='Claude Monet', underline =7,
                        command = boss.tabMonet)
        me2.add_command(label ='Auguste Renoir', underline =8,
                        command = boss.tabRenoir)
        me2.add_command(label ='Edgar Degas', underline =6,
                        command = boss.tabDegas)
        # Intégration du sous-menu :
        me1.add_cascade(label ='impressionistes ', underline =0,
                        menu = me2)
        # Intégration du menu :
        self.pein.configure(menu = me1)

        ##### Menu <Options> #####
        optMenu = Menubutton(self, text ='Options')
        optMenu.pack(side =LEFT, padx ='3')
        # Variables Tkinter :
        self.relief = IntVar()
        self.actPein = IntVar()
        self.actMusi = IntVar()
        # Partie "déroulante" du menu :
        self.mo = Menu(optMenu)
        self.mo.add_command(label = 'Activer :', foreground ='blue')
        self.mo.add_checkbutton(label ='musiciens', command = self.choixActifs,
                            variable =self.actMusi)
        self.mo.add_checkbutton(label ='peintres', command = self.choixActifs,
                            variable =self.actPein)
        self.mo.add_separator()
        self.mo.add_command(label = 'Relief :', foreground ='blue')
        for (v, lab) in [(0,'aucun'), (1,'sorti'), (2,'rentré'),
                         (3,'sillon'), (4,'crête'), (5,'bordure')]:
            self.mo.add_radiobutton(label =lab, variable = self.relief,
                                value =v, command = self.reliefBarre)
        # Intégration du menu :
        optMenu.configure(menu = self.mo)

    def reliefBarre(self):
        choix = self.relief.get()
        self.configure(relief =[FLAT,RAISED,SUNKEN,GROOVE,RIDGE,SOLID][choix])

    def choixActifs(self):
        p = self.actPein.get()
        m = self.actMusi.get()
        self.pein.configure(state =[DISABLED, NORMAL][p])
        self.musi.configure(state =[DISABLED, NORMAL][m])

class Application(Frame):
    """Application principale"""
    def __init__(self, boss =None):
        Frame.__init__(self)
        self.master.title('Fenêtre avec menus')
        mBar = MenuBar(self)
        mBar.pack()
        self.can = Canvas(self, bg='light grey', height=190,
                          width=250, borderwidth =2)
        self.can.pack()
        mBar.mo.invoke(2)
        self.pack()

    def showMusi17(self):
        self.can.create_text(10, 10, anchor=NW, text='H. Purcell',
                    font=('Times', 20, 'bold'), fill='yellow')

    def showMusi18(self):
        self.can.create_text(245, 40, anchor =NE, text = "W. A. Mozart",
                    font =('Times', 20, 'italic'), fill ='dark green')

    def showRomanti(self):
        self.can.create_text(245, 70, anchor =NE, text = "E. Delacroix",
                    font =('Times', 20, 'bold italic'), fill ='blue')

    def tabMonet(self):
        self.can.create_text(10, 100, anchor =NW, text = 'Nymphéas à Giverny',
                    font =('Technical', 20), fill ='red')

    def tabRenoir(self):
        self.can.create_text(10, 130, anchor =NW, text = 'Le moulin de la galette',
                    font =('Dom Casual BT', 20), fill ='maroon')

    def tabDegas(self):
        self.can.create_text(10, 160, anchor =NW, text = 'Danseuses au repos',
                    font =('President', 20), fill ='purple')

    def effacer(self):
        self.can.delete(ALL)

if __name__ == '__main__':
    app = Application()
    app.mainloop()
    app.destroy()


import requests
import urllib.parse
import json

class TvMaze:
    """
    Gets all important information about a show
    """
    def __init__(self, show):
        self.api_root_url = 'http://api.tvmaze.com'
        self.show = show

    def get_show_info(self):
        proxies = {
            'http': 'one.proxy.att.com:8080'
        }
        q = '/singlesearch/shows?q={}&embed=episodes'.format(urllib.parse.quote_plus(self.show))
        r = requests.get('{}{}'.format(self.api_root_url, q))
        return json.loads(r.text)

if __name__ == '__main__':
    tvmaze = TvMaze('hate thy neighbor')
    info = tvmaze.get_show_info()
    episodes = info['_embedded']['episodes']


import multiprocessing
import logging as log
import serial
from serial.tools import list_ports
from time import time

class SerialProcess(multiprocessing.Process):
    def __init__(self, result_queue):
        self.queue = result_queue
        multiprocessing.Process.__init__(self)
        self.exit = multiprocessing.Event()
        self.s = serial.Serial()
        log.info("SerialProcess ready")

    @staticmethod
    def list_ports():
        return list_ports.comports()

    def get_ports(self):
        ports = []
        for port in self.list_ports():
            ports.append(port[0])
        return ports

    def get_ports_full(self):
        ports = []
        for port in self.list_ports():
            ports.append(port)
        return ports

    def is_port_available(self, port):
        for ports in self.list_ports():
            if ports[0] == port:
                return True
        return False

    def open_port(self, port, bd=115200, timeout=0.5):
        self.s.port = port
        self.s.baudrate = bd
        self.s.stopbits = serial.STOPBITS_ONE
        self.s.bytesize = serial.EIGHTBITS
        self.s.timeout = timeout
        return self.is_port_available(self.s.port)

    def run(self):
        if self.is_port_available(self.s.port):
            if not self.s.isOpen():
                self.s.open()
                log.info("Port opened")
                timestamp = time()
                while not self.exit.is_set():
                    """
                    http://eli.thegreenplace.net/2009/08/07/a-live-data-monitor-with-python-pyqt-and-pyserial/
                    """
                    data = self.s.read(1)
                    data += self.s.read(self.s.inWaiting())
                    if len(data) > 0:
                        self.queue.put((data, (time() - timestamp)))
                    log.debug(data)
                log.info("SerialProcess finished")
                self.s.close()
            else:
                log.warning("Port is not opened")
        else:
            log.warning("Port is not available")

    def stop(self):
        log.info("SerialProcess finishing...")
        self.exit.set()


import os
import re
import json
import helpers

# False when setup has not been performed.
_is_setup = False

def lambda_handler(event, context):
    """
    Extract log data from CloudWatch Logs events and
    pass the data onto the Humio ingester.

    :param event: Event data from CloudWatch Logs.
    :type event: dict

    :param context: Lambda context object.
    :type context: obj

    :return: None
    """
    # Persist variables across lambda invocations.
    if not _is_setup:
        helpers.setup()

    # Decode and unzip the log data.
    decoded_event = helpers.decode_event(event)

    # Debug output.
    print("Event from CloudWatch Logs: %s" % (json.dumps(decoded_event)))

    # Extract the general attributes from the event batch.
    batch_attrs = {
        "owner": decoded_event.get("owner", "undefined"),
        "logGroup": decoded_event.get("logGroup", "undefined"),
        "logStream": decoded_event.get("logStream", "undefined"),
        "messageType": decoded_event.get("messageType", "undefined"),
        "subscriptionFilters": decoded_event.get("subscriptionFilters", "undefined"),
    }

    # Parse out the service name.
    log_group_parser = re.compile("^/aws/(lambda|apigateway)/(.*)")
    parsed_log_group = log_group_parser.match(decoded_event.get("", ""))
    if parsed_log_group:
        batch_attrs.update(
            {
                "awsServiceName": parsed_log_group.group(1),
                "parsedLogGroupName": parsed_log_group.group(2)
            }
        )

    # Flatten the events from CloudWatch Logs.
    humio_events = []
    for log_event in decoded_event["logEvents"]:
        message = log_event["message"]

        # Create the attributes.
        attributes = {}
        attributes.update(batch_attrs)
        attributes.update(helpers.parse_message(message))

        # Append the flattened event
        humio_events.append({
            "timestamp": log_event["timestamp"],
            "rawstring": message,
            "kvparse": True,
            "attributes": attributes,
        })

    # Make request to Humio.
    request = helpers.ingest_events(humio_events, {"#env": os.environ["humio_env"], "#type": "log"})

    # Debug output.
    print("Got response %s from Humio." % request.text)


from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from sistemaAcademico.Apps.GestionAcademica.Forms.Matriculacion.forms_mov_anio_curso import Mov_Aniolectivo_curso_forms
from django.shortcuts import render, redirect
from sistemaAcademico.Apps.GestionAcademica.Diccionario.Estructuras_tablas_mov import Mov_Aniolectivo_curso
from sistemaAcademico.Apps.GestionAcademica.Diccionario.Estructuras_tablas_genr import GenrGeneral

class Create_Mov_Aniolectivo_curso(CreateView):
    model = Mov_Aniolectivo_curso
    form_class = Mov_Aniolectivo_curso_forms
    template_name = 'sistemaAcademico/Matriculacion/Asignacion_curso/crear_asig_curso.html'
    success_url = reverse_lazy('Academico:asignacion_curso')
class Update_Mov_Aniolectivo_curso(UpdateView):
    model = Mov_Aniolectivo_curso
    form_class = Mov_Aniolectivo_curso_forms
    context_object_name = 'anio'
    template_name = 'sistemaAcademico/Matriculacion/Asignacion_curso/edit_asig_curso.html'
    success_url = reverse_lazy('Academico:asignacion_curso')
class ListaAnioElectivoCurso(ListView):
    model = Mov_Aniolectivo_curso
    context_object_name = 'anio'
    queryset = Mov_Aniolectivo_curso.objects.filter(id_estado_gnral=97)
    template_name = 'sistemaAcademico/Matriculacion/Asignacion_curso/listar_asig_curso.html'
def eliminar_Asignacion_Curso(request, id):
    dic={  }
    anio = Mov_Aniolectivo_curso.objects.get(id_mov_anioelectivo_curso=id)
    lis_anio = Mov_Aniolectivo_curso.objects.filter(id_mov_anioelectivo_curso=id)
    inactivo = GenrGeneral.objects.get(idgenr_general=98)
    dic['anio']=anio
    dic['lis_anio']=lis_anio
    if request.method == 'POST':
        anio.id_estado_gnral = inactivo
        anio.save()
        return redirect('Academico:asignacion_curso')
    return render(request, 'sistemaAcademico/Matriculacion/Asignacion_curso/eliminar_asig_curso.html', dic)


import numpy as np
import matplotlib.pyplot as plt
import warnings

class Beampath:
    """
    Computes the beam radius and angle according to ABCD matrices using paraxial approximation. Units should be consistent (all mm or all m)
    """
    # Define plotting variables
    __col_beam = 'crimson'
    __col_object = 'tab:blue'
    __col_lens_pos = 'tab:green'
    __col_lens_neg = 'tab:orange'
    __col_image = 'purple'
    __col_exit = 'darkslategrey'
    __col_inter = 'xkcd:dull blue'
    __alpha_beam = 0.1
    __scale_vert = 0.8
    __text_offset = 0.05
    __xmin = 0
    __xmax = 1
    __ymin = -1
    __ymax = 1
    __prec = '%.2f'

    def __init__(self, radius=0, angle=1, index=1, position=0):
        """
        Initialise beam path with an object

        Parameters
        ----------
        radius: float, optional
            Radius of the object

        angle: float, optional
            Half divergence angle in radians

        index: float, optional
            Initial index of refraction

        position: float, optional
            Longitudinal position of the object
        """
        self.radius = np.array([radius])
        self.angle = np.array([angle])
        if index < 1:
            warnings.warn('Index lower than 1!')
        self.index = np.array([index])
        self.position = np.array([position])
        self.list_elements = [Object()]
        self.M = np.identity(2)
        self._check_paraxial()

    def add_thinlens(self, focal_length):
        """
        Add a thin lens to the optical path and calculates the new beam parameters

        Parameters
        ----------
        focal_length: float
            Focal length of the thin lens.
            Can be positive or negative but not zero
        """
        self.list_elements.append(Thinlens(focal_length))
        new_rad, new_angle = np.dot(self.list_elements[-1].M, np.array([self.radius[-1], self.angle[-1]]))
        self.radius = np.append(self.radius, new_rad)
        self.angle = np.append(self.angle, new_angle)
        self.index = np.append(self.index, self.index[-1])
        self.position = np.append(self.position, self.position[-1])
        self.M = np.dot(self.list_elements[-1].M, self.M)
        self._check_paraxial()

    def add_freespace(self, distance):
        """
        Add free space propagation to the optical path and calculates the new beam parameters

        Parameters
        ----------
        distance: float
            Distance of propagation in free space.
            Can be negative but be careful of the results.
            Cannot be zero.
        """
        self.list_elements.append(Freespace(distance))
        new_rad, new_angle = np.dot(self.list_elements[-1].M, np.array([self.radius[-1], self.angle[-1]]))
        self.radius = np.append(self.radius, new_rad)
        self.angle = np.append(self.angle, new_angle)
        self.index = np.append(self.index, self.index[-1])
        self.position = np.append(self.position, self.position[-1]+distance)
        self.M = np.dot(self.list_elements[-1].M, self.M)
        self._check_paraxial()

    def add_interface(self, index, curvature = np.inf):
        """
        Add an interface with a different medium to the optical path and calculates the new beam parameters

        Parameters
        ----------
        index: float
            Index of refraction after the interface.

        curvature: float, optional
            Radius of curvature of the interface.
            Positive means convexe surface, negative means concave surface.
            Infinite radius is a flat surface.
        """
        self.list_elements.append(Interface(index, self.index[-1], curvature))
        new_rad, new_angle = np.dot(self.list_elements[-1].M, np.array([self.radius[-1], self.angle[-1]]))
        self.radius = np.append(self.radius, new_rad)
        self.angle = np.append(self.angle, new_angle)
        self.index = np.append(self.index, index)
        self.position = np.append(self.position, self.position[-1])
        self.M = np.dot(self.list_elements[-1].M, self.M)
        self._check_paraxial()

    def add_thicklens(self, index, thickness, radius_in=np.inf, radius_out=np.inf):
        """
        Add a thick lens to the optical path and calculates the new beam parameters

        Parameters
        ----------
        index: float
            Index of refraction of the thick lens.

        thickness: float
            Center thickness of the thick lens.

        radius_in: float, optional
            Radius of curvature of the first surface.
            Positive means convexe surface, negative means concave surface.
            Infinite radius is a flat surface.

        radius_out: float, optional
            Radius of curvature of the second surface.
            Positive means convexe surface, negative means concave surface.
            Infinite radius is a flat surface.
        """
        index_before = self.index[-1]
        self.add_interface(index, radius_in)
        self.add_freespace(thickness)
        self.add_interface(index_before, radius_out)

    def add_image(self):
        """
        Calculate the image position and add it to the beam path
        """
        beam_in = np.array([0,1])
        beam_out = np.dot(self.M, beam_in)
        # Get distance where the beam crosses the optical axis
        with np.errstate(divide='ignore'): # remove divide by zero warning
            distance_image = -beam_out[0]/beam_out[1]
        if isinstance(self.list_elements[-1], Freespace):
            self._add_exit()
        self.add_freespace(distance_image)
        self.list_elements.append(Image())
        self.radius = np.append(self.radius, self.radius[-1])
        self.angle = np.append(self.angle, self.angle[-1])
        self.index = np.append(self.index, self.index[-1])
        self.position = np.append(self.position, self.position[-1])
        self._check_paraxial()

    def _add_exit(self):
        """
        Add an dummy exit plane
        """
        self.list_elements.append(Exit())
        self.radius = np.append(self.radius, self.radius[-1])
        self.angle = np.append(self.angle, self.angle[-1])
        self.index = np.append(self.index, self.index[-1])
        self.position = np.append(self.position, self.position[-1])

    def _check_paraxial(self):
        """
        Check if the paraxial approximation is respected, i.e. theta-sin(theta) is small enough
        """
        par_error = np.max(np.abs(self.angle - np.sin(self.angle)))
        if par_error > 0.01:
            warn_message = 'Paraxial approximation is not valid: |x - sin(x)| = %.3g'%par_error
            warnings.warn(warn_message)

    def plot(self, **kwargs):
        """
        Plot the beam path

        Optionnal keywords arguments
        ----------------------------
        'figsize': int tuple
            Set the figure size

        'plot_digit': int
            Change the maximum number of decimal digits of the annotations
        """
        fig, ax = self._plot_initialise(**kwargs)
        for idx in range(len(self.list_elements)):
            self.list_elements[idx].plot(ax, idx, self, **kwargs)

    def _plot_initialise(self, **kwargs):
        """
        Initialise plot and plot variables
        """
        fig_size = kwargs.get('figsize', (12,6))
        fig, ax = plt.subplots(figsize=fig_size) # Initialise figure
        pos = self.position[np.isfinite(self.position)]
        xrange = np.ptp(pos) # Get x range
        # Compute x and y limits
        if self.list_elements:
            self.__xmin = np.min(pos) - 0.1*xrange
            self.__xmax = np.max(pos) + 0.1*xrange
            self.__ymax = np.max(np.abs(self.radius[np.isfinite(self.radius)]))*1.5
            self.__ymin = - self.__ymax
        # Set x and y limits
        ax.set_xlim(self.__xmin, self.__xmax)
        ax.set_ylim(self.__ymin, self.__ymax)
        # Define the digit precision
        plot_digit = kwargs.get('plot_digit', None)
        if plot_digit is not None:
            self.__prec = '%.' + '%d'%plot_digit + 'f'
        # Plot optical axis
        ax.plot([self.__xmin, self.__xmax],[0, 0], ls='-.', color='grey')
        if np.any(self.index!=self.index[0]):
            ax.text(self.__xmin + 0.01*xrange, self.__ymin*(self.__text_offset+self.__scale_vert),
                    'Index:', color = self.__col_inter, ha='left', va='top')
        return fig, ax

class Element:
    """
    Abstract parent class for optical elements.
    Do not call!
    """
    def __init__(self):
        # Initialise plotting variables
        self.__color = {'beam': 'crimson',
                        'object': 'tab:blue',
                        'lens_pos': 'tab:green',
                        'lens_neg': 'tab:orange',
                        'image': 'purple',
                        'exit': 'darkslategrey',
                        'interface': 'xkcd:dull blue',
                        'axis': 'grey'}
        self.__alpha_beam = 0.1
        self.__scale_vert = 0.8
        self.__text_offset = 0.05
        self.__xmin = 0
        self.__xmax = 1
        self.__ymin = -1
        self.__ymax = 1
        self.__prec = '%.2f'

    def _plot_var(self, ax, **kwargs):
        """
        Initialise the plot variables
        """
        self.__xmin, self.__xmax = ax.get_xlim()
        self.__ymin, self.__ymax = ax.get_ylim()
        plot_digit = kwargs.get('plot_digit', None)
        if plot_digit is not None:
            self.__prec = '%.' + '%d'%plot_digit + 'f'

class Object(Element):
    """
    Object of beam path
    """
    def __init__(self):
        super().__init__()

    def plot(self, ax, elem_pos, beam_path, **kwargs):
        """
        Plot the object in the beam path

        Parameters
        ----------
        ax: matplotlib.pyplot.axis
            Axis in which the object should be drawn

        elem_pos: float
            Longitudinal position where the object should be drawn

        beam_path: Beampath
            Beampath containing the object
        """
        # Get plot variables
        self._plot_var(ax, **kwargs)
        ymin = self._Element__ymin
        ymax = self._Element__ymax
        sc = self._Element__scale_vert
        tx = self._Element__text_offset
        col = self._Element__color['object']
        pos = beam_path.position[elem_pos]
        # Plot object
        ax.plot([pos, pos], [ymin*sc, ymax*sc], ls='--', color = col)
        ax.text(pos, ymax*(sc+tx), 'Object', color = col, ha = 'center', va = 'bottom')

class Thinlens(Element):
    """
    Thin lens optical element
    """
    def __init__(self, focal_length):
        """
        Constructor of the thin lens element

        Parameters
        ----------
        focal_length: float
            Focal length of the thin lens
        """
        super().__init__()
        self.focal_length = focal_length
        self.M = np.array([[1,0],[-1/self.focal_length, 1]])

    def plot(self, ax, elem_pos, beam_path, **kwargs):
        """
        Plot the thin lens in the beam path

        Parameters
        ----------
        ax: matplotlib.pyplot.axis
            Axis in which the thin lens should be drawn

        elem_pos: float
            Longitudinal position where the thin lens should be drawn

        beam_path: Beampath
            Beampath containing the thin lens
        """
        # Get plot variables
        self._plot_var(ax, **kwargs)
        ymin = self._Element__ymin
        ymax = self._Element__ymax
        sc = self._Element__scale_vert
        tx = self._Element__text_offset
        prec = self._Element__prec
        prec = prec[0] + '+' + prec[1:] # display signed focal length
        pos = beam_path.position[elem_pos]
        if self.focal_length < 0:
            col = self._Element__color['lens_neg']
        else:
            col = self._Element__color['lens_pos']
        # Plot lens with text
        ax.plot([pos, pos], [sc*ymin, sc*ymax], color=col)
        ax.text(pos, (sc+tx)*ymax, ('Lens\n'+prec%(self.focal_length)).rstrip('0').rstrip('.'),
                color=col, ha='center', va='bottom')

class Freespace(Element):
    """
    Free space propagation
    """
    def __init__(self, distance):
        """
        Constructor of the thin lens element

        Parameters
        ----------
        distance: float
            Distance of the free space propagation
        """
        super().__init__()
        self.distance = distance
        self.M = np.array([[1,distance],[0, 1]])

    def plot(self, ax, elem_pos, beam_path, **kwargs):
        """
        Plot the propagated beam path

        Parameters
        ----------
        ax: matplotlib.pyplot.axis
            Axis in which the thin lens should be drawn

        elem_pos: float
            Longitudinal position where the free space is placed

        beam_path: Beampath
            Beampath containing the free space
        """
        # Get plot variables
        self._plot_var(ax, **kwargs)
        ymin = self._Element__ymin
        ymax = self._Element__ymax
        sc = self._Element__scale_vert
        tx = self._Element__text_offset
        col = self._Element__color['beam']
        col2 = self._Element__color['interface']
        alp = self._Element__alpha_beam
        pos = beam_path.position[elem_pos-1:elem_pos+1]
        rad = beam_path.radius[elem_pos-1:elem_pos+1]
        n = beam_path.index[elem_pos]
        prec = self._Element__prec
        # Plot beam path
        # If beam going to image, plot the beam in dotted line otherwise, solid line
        if isinstance(beam_path.list_elements[-1], Image) and elem_pos == (len(beam_path.list_elements)-2):
            line_style = ':'
        else:
            line_style = '-'
        # Beam edges
        ax.plot(pos, rad,line_style, color=col)
        ax.plot(pos, -rad,line_style, color=col)
        # Beam inside
        ax.fill_between(pos, rad, -rad, facecolor=col, alpha=alp)
        # If there is a change of index, overlay a shadowed area according to the refractive index
        if np.any(beam_path.index!=beam_path.index[0]):
            ax.fill_between(pos, [ymax, ymax], [ymin, ymin], facecolor = col2, alpha = (1-1/n))
            ax.text(np.mean(pos), (sc+tx)*ymin, (prec%n).rstrip('0').rstrip('.'),
                        color=col2, ha = 'center', va='top')

class Interface(Element):
    """
    Interface between two mediums
    """
    def __init__(self, index_out, index_in = 1, curvature=np.inf):
        """
        Constructor of the interface element

        Parameters
        ----------
        index_out: float
            Index of refraction after the interface.

        index_in: float, optional
            Index of refraction before the interface.

        curvature: float, optional
            Radius of curvature of the interface.
            Positive is convexe, negative is concave.
            Infinity is a flat interface.
        """
        super().__init__()
        if index_in < 1 or index_out < 1:
            warnings.warn('Index lower than 1!')
        self.index_in = index_in
        self.index_out = index_out
        self.curvature = curvature
        self.M = np.array([[1,0],[(self.index_in-self.index_out)/(self.curvature*self.index_out),
                                  self.index_in/self.index_out]])

    def plot(self, ax, elem_pos, beam_path, **kwargs):
        """
        Plot the interface

        Parameters
        ----------
        ax: matplotlib.pyplot.axis
            Axis in which the interface should be drawn

        elem_pos: float
            Longitudinal position where the interface is placed

        beam_path: Beampath
            Beampath containing the interface
        """
        # Retreive plot variables
        self._plot_var(ax, **kwargs)
        ymin = self._Element__ymin
        ymax = self._Element__ymax
        pos = beam_path.position[elem_pos]
        diff_pos = np.ptp(beam_path.position)/20
        col = self._Element__color['interface']
        # If infinite radius, draw a vertical line
        if not np.isfinite(self.curvature):
            x = np.array([pos,pos])
            y = np.array([0, ymax])
        else: # Otherwise, draw a curved interface
            r = self.curvature
            x0 = r + pos
            x = np.linspace(-r, -r + np.sign(r)*diff_pos, num=200) + x0
            y = np.abs(r*np.sin(np.arccos(np.clip((x-x0)/r, -1,1))))
        ax.plot(x, y, color = col)
        ax.plot(x, -y, color = col)

class Exit(Element):
    """
    Exit plane of beam path
    """
    def plot(self, ax, elem_pos, beam_path, **kwargs):
        """
        Plot the exit plane

        Parameters
        ----------
        ax: matplotlib.pyplot.axis
            Axis in which the exit plane should be drawn

        elem_pos: float
            Longitudinal position where the exit plane is placed

        beam_path: Beampath
            Beampath containing the exit plane
        """
        # Get plot variables
        self._plot_var(ax, **kwargs)
        ymin = self._Element__ymin
        ymax = self._Element__ymax
        sc = self._Element__scale_vert
        tx = self._Element__text_offset
        col = self._Element__color['exit']
        prec = self._Element__prec
        pos = beam_path.position[elem_pos]
        # Plot object
        ax.plot([pos, pos], [ymin*sc, ymax*sc], ls='--', color = col)
        #ax.text(pos, ymax*(sc+tx), 'Exit plane at '+prec%pos, color = col, ha = 'center', va = 'bottom')

class Image(Element):
    """
    Image of beam path
    """

    def plot(self, ax, elem_pos, beam_path, **kwargs):
        """
        Plot the image plane

        Parameters
        ----------
        ax: matplotlib.pyplot.axis
            Axis in which the image plane should be drawn

        elem_pos: float
            Longitudinal position where the image plane is placed

        beam_path: Beampath
            Beampath containing the image plane
        """
        # Get plot variables
        self._plot_var(ax, **kwargs)
        xmin = self._Element__xmin
        xmax = self._Element__xmax
        ymin = self._Element__ymin
        ymax = self._Element__ymax
        sc = self._Element__scale_vert
        tx = self._Element__text_offset
        col = self._Element__color['image']
        prec = self._Element__prec
        pos = beam_path.position[elem_pos]
        xrange = xmax-xmin
        yrange = ymax-ymin
        # Plot object
        # If at finite distance, draw the plane
        if np.isfinite(pos):
            ax.plot([pos, pos], [ymin*sc, ymax*sc], ls='--', color=col)
            ax.text(pos, ymax*(sc+tx), ('Image at\n'+prec%pos).rstrip('0').rstrip('.'), color=col, ha='center', va='bottom')
        else: # Othewise, annote the figure that the image is at infinity
            ax.text(xmax - 0.01*xrange, yrange*0.01, 'Image', color=col, ha='right', va='bottom')
            ax.text(xmax - 0.01*xrange, -yrange*0.01, 'at \u221E \u2192', color=col, ha='right', va='top')


'''

'''

import math
import os

# 一个优雅的解决方式

nums = [1, 2, 3, 4, 5]
s = sum(x*x for x in nums)
print(s)

# 一些其他栗子

# 1
files = os.listdir('../<1>数据结构和算法/')
if any(name.endswith('.py') for name in files):
    print('There be python!')
else:
    print('Sorry, no python.')

# 2
s = ('ACME', 50, 123.45)
print(','.join(str(x) for x in s))

# 3
portfolio = [
    {'name': 'GOOG', 'shares': 50},
    {'name': 'YHHO', 'shares': 75},
    {'name': 'AOL', 'shares': 20},
    {'name': 'SCOX', 'shares': 65},
]

min_shares = min(s['shares'] for s in portfolio)
print(min_shares)

PythonCookbook/<1>数据结构和算法/19-同时对数据做转换和换算.py

19-同时对数据做转换和换算.py


#!/usr/bin/env python2
""" The layout class """

# upconvert.py - A universal hardware design file format converter using
# Format:       upverter.com/resources/open-json-format/
# Development:  github.com/upverter/schematic-file-converter
#
# Copyright 2011 Upverter, 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.

from upconvert.core.shape import Arc

class Layout:
    """ Represents the design schematic as a PCB Layout. """

    def __init__(self):
        self.layers = list()

    def generate_netlist(self):
        """ Generate a netlist from the layout. """
        pass

    def json(self):
        """ Return the layout as JSON """
        return {
            "layers": [layer.json() for layer in self.layers]
            }

class Layer:
    """ A layer in the layout (ie, a PCB layer). """

    def __init__(self, name='', type_=''):
        self.name = name
        self.type = type_ # copper/mask/silk/drill
        self.images = list()
        self.apertures = dict()
        self.macros = dict()
        self.vias = list()
        self.components = list()

    def json(self):
        """ Return the layer as JSON """
        return {
            "type": self.type,
            "images": [i.json() for i in self.images],
            "apertures": [self.apertures[k].json() for k in self.apertures],
            "macros": [self.macros[m].json() for m in self.macros],
            "vias": [v.json() for v in self.vias],
            "components": [c.json() for c in self.components]
            }

class Image:
    """
    An image layer (not a PCB layer).

    Image layers can be additive or subtractive. Therefore they
    must be applied successively to build up a final image
    representing a single layer of the PCB (ie, a single gerber
    file).

    Image layers will be applied in the order they appear in the
    layer[n].images list of the Layout. Subtractive image layers
    only subtract from previous image layers - not subsequent
    image layers.

    Example
    =======
    For a ground plane that is partly negated to make room for
    traces, define three image layers in the following order:

        1. the ground plane
        2. the area(s) to be negated (as a subtractive image)
        3. the traces to be laid within the negated area(s)
    """

    def __init__(self, name='Untitled Image', is_additive=True):
        self.name = name
        self.is_additive = is_additive
        self.x_repeats = 1
        self.x_step = None
        self.y_repeats = 1
        self.y_step = None
        self.traces = list()
        self.fills = list()
        self.smears = list()
        self.shape_instances = list()

    def not_empty(self):
        """ True if image contains only metadata. """
        return (self.traces or self.fills or self.smears or
                self.shape_instances) and True or False

    def get_trace(self, width, end_pts):
        """
        Get a trace given a width and pair of points.
        Return None if no Trace is found.

        Params:
            width   - float
            end_pts - tuple of 2 Points (ie, the endpoints of
                      the segment we wish to attach)

        """
        start, end = end_pts
        for trace in self.traces:
            for seg in trace.segments:
                if trace.width == width:
                    if isinstance(seg, Arc):
                        seg_ends = seg.ends()
                    else:
                        seg_ends = (seg.p1, seg.p2)
                    if start in seg_ends or end in seg_ends:
                        return trace
        return None

    def json(self):
        """ Return the image as JSON """
        return {
            "name": self.name,
            "is_additive": self.is_additive and 'true' or 'false',
            "x_repeats": self.x_repeats,
            "x_step": self.x_step,
            "y_repeats": self.y_repeats,
            "y_step": self.y_step,
            "traces": [t.json() for t in self.traces],
            "fills": [f.json() for f in self.fills],
            "smears": [s.json() for s in self.smears],
            "shape_instances": [i.json() for i in self.shape_instances]
            }

class Trace:
    """ A collection of connected segments (lines/arcs). """

    def __init__(self, width, segments=None):
        self.width = width
        self.segments = segments or []

    def json(self):
        """ Return the trace as JSON """
        return {
            "width": self.width,
            "segments": [s.json() for s in self.segments]
            }

class Fill:
    """
    A closed loop of connected segments (lines/arcs).

    The segments define the outline of the fill. They
    must be contiguous, listed in order (ie, each seg
    connects with the previous seg and the next seg)
    and not intersect each other.
    """

    def __init__(self, segments=None):
        self.segments = segments or list()

    def json(self):
        """ Return the trace as JSON """
        return {
            "segments": [s.json() for s in self.segments]
            }

class Smear:
    """ A line drawn by a rectangular aperture. """

    def __init__(self, line, shape):
        self.line = line
        self.shape = shape

    def json(self):
        """ Return the smear as JSON """
        return {
            "line": self.line.json(),
            "shape": self.shape.json()
            }

class ShapeInstance:
    """
    An instance of a shape defined by an aperture.

    Instead of wrapping the aperture itself, we wrap
    its constituent shape and hole defs, because
    gerber does not prohibit an aperture from being
    redefined at some arbitrary point in the file.

    x and y attributes serve as an offset.
    """

    def __init__(self, point, aperture):
        self.x = point.x
        self.y = point.y
        self.shape = aperture.shape
        self.hole = aperture.hole

    def json(self):
        """ Return the shape instance as JSON """
        return {
            "x": self.x,
            "y": self.y,
            "shape": (isinstance(self.shape, str) and
                      self.shape or self.shape.json()),
            "hole": self.hole and self.hole.json()
            }

class Aperture:
    """
    A simple shape, with or without a hole.

    If the shape is not defined by a macro, its class
    must be one of Circle, Rectangle, Obround or
    RegularPolygon.

    If the shape is not defined by a macro, it may have
    a hole. The class of the hole must be either Circle
    or Rectangle. Shape and hole are both centered on
    the origin. Placement is handled by metadata
    connected to the aperture when it used.

    Holes must be fully contained within the shape.

    Holes never rotate, even if the shape is rotatable
    (ie, a RegularPolygon).
    """

    def __init__(self, code, shape, hole):
        self.code = code
        self.shape = shape
        self.hole = hole

    def __eq__(self, other):
        """ Compare 2 apertures. """
        if (isinstance(self.shape, str) or
            isinstance(other.shape, str)):
            equal = self.shape == other.shape
        else:
            equal = (self.shape.__dict__ == other.shape.__dict__ and
                     (self.hole == other.hole or
                      (self.hole and other.hole and
                       self.hole.__dict__ == other.hole.__dict__)))
        return equal

    def json(self):
        """ Return the aperture as JSON """
        return {
            "code": self.code,
            "shape": (isinstance(self.shape, str) and
                      self.shape or self.shape.json()),
            "hole": self.hole and self.hole.json()
            }

class Macro:
    """
    Complex shape built from multiple primitives.

    Primitive shapes are added together in the order they
    appear in the list. Subtractive shapes subtract only
    from prior shapes, not subsequent shapes.

    """
    def __init__(self, name, primitives):
        self.name = name
        self.primitives = primitives

    def json(self):
        """ Return the macro as JSON """
        return {
            "name": self.name,
            "primitives": [prim.json() for prim in self.primitives]
            }

class Primitive:
    """ A shape with rotation and exposure modifiers. """

    def __init__(self, is_additive, rotation, shape):
        self.is_additive = is_additive
        self.rotation = rotation
        self.shape = shape

    def json(self):
        """ Return the primitive as JSON """
        return {
            "is_additive": self.is_additive and 'true' or 'false',
            "rotation": self.rotation,
            "shape": self.shape.json()
            }


from .base import SimIRExpr

import logging
l = logging.getLogger(name=__name__)

class SimIRExpr_Unsupported(SimIRExpr):

    __slots__ = []

    def _execute(self):
        l.error("Unsupported IRExpr %s. Please implement.", type(self._expr).__name__)
        self.expr = self.state.solver.Unconstrained(type(self._expr).__name__, self.size_bits())
        self.state.history.add_event('resilience', resilience_type='irexpr', expr=type(self._expr).__name__, message='unsupported irexpr')


"""
Copyright (C) 2014 The HDF Group
Copyright (C) 2014 John Evans

This example code illustrates how to access and visualize an NSIDC AMSR grid
file in Python.

If you have any questions, suggestions, or comments on this example, please use
the HDF-EOS Forum (http://hdfeos.org/forums).  If you would like to see an
example of any other NASA HDF/HDF-EOS data product that is not listed in the
HDF-EOS Comprehensive Examples page (http://hdfeos.org/zoo), feel free to
contact us at eoshelp@hdfgroup.org or post it at the HDF-EOS Forum
(http://hdfeos.org/forums).

Usage:  save this script and run

    python AMSR_E_L3_SI_25km_NH_06V_ASC.py

The HDF file must either be in your current working directory or in a directory
specified by the environment variable HDFEOS_ZOO_DIR.
"""

import os
import re

import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import mpl_toolkits.basemap.pyproj as pyproj
import numpy as np

USE_GDAL = False

def run(FILE_NAME):

    # Identify the data field.
    DATAFIELD_NAME = 'SI_25km_NH_06V_ASC'

    if USE_GDAL:
        import gdal
        GRID_NAME = 'NpPolarGrid25km'
        gname = 'HDF4_EOS:EOS_GRID:"{0}":{1}:{2}'.format(FILE_NAME,
                                                         GRID_NAME,
                                                         DATAFIELD_NAME)
        gdset = gdal.Open(gname)
        data = gdset.ReadAsArray().astype(np.float64)

        # Read projection parameters from global attribute.
        meta = gdset.GetMetadata()
        x0, xinc, _, y0, _, yinc = gdset.GetGeoTransform()
        nx, ny = (gdset.RasterXSize, gdset.RasterYSize)
        del gdset
    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # Read dataset.
        data2D = hdf.select(DATAFIELD_NAME)
        data = data2D[:,:].astype(np.float64)
        # Read global attribute.
        fattrs = hdf.attributes(full=1)
        ga = fattrs["StructMetadata.0"]
        gridmeta = ga[0]

        # Construct the grid.  The needed information is in a global attribute
        # called 'StructMetadata.0'.  Use regular expressions to tease out the
        # extents of the grid.
        ul_regex = re.compile(r'''UpperLeftPointMtrs=\(
                                  (?P<upper_left_x>[+-]?\d+\.\d+)
                                  ,
                                  (?P<upper_left_y>[+-]?\d+\.\d+)
                                  \)''', re.VERBOSE)
        match = ul_regex.search(gridmeta)
        x0 = np.float(match.group('upper_left_x'))
        y0 = np.float(match.group('upper_left_y'))

        lr_regex = re.compile(r'''LowerRightMtrs=\(
                                  (?P<lower_right_x>[+-]?\d+\.\d+)
                                  ,
                                  (?P<lower_right_y>[+-]?\d+\.\d+)
                                  \)''', re.VERBOSE)
        match = lr_regex.search(gridmeta)
        x1 = np.float(match.group('lower_right_x'))
        y1 = np.float(match.group('lower_right_y'))
        ny, nx = data.shape
        xinc = (x1 - x0) / nx
        yinc = (y1 - y0) / ny

    # Apply the attributes information.
    # Ref:  http://nsidc.org/data/docs/daac/ae_si12_25km_seaice/data.html
    data[data == 0] = np.nan
    data *= 0.1
    data = np.ma.masked_array(data, np.isnan(data))

    # Construct the grid.  Reproject out of the GCTP stereographic into lat/lon.
    x = np.linspace(x0, x0 + xinc*nx, nx)
    y = np.linspace(y0, y0 + yinc*ny, ny)
    xv, yv = np.meshgrid(x, y)
    args = ["+proj=stere",
            "+lat_0=90",
            "+lon_0=-45",
            "+lat_ts=70",
            "+k=1",
            "+es=0.006693883",
            "+a=6378273",
            "+x_0=0",
            "+y_0=0",
            "+ellps=WGS84",
            "+datum=WGS84"]
    pstereo = pyproj.Proj(' '.join(args))
    wgs84 = pyproj.Proj("+init=EPSG:4326")
    lon, lat= pyproj.transform(pstereo, wgs84, xv, yv)

    units = 'K'
    long_name = DATAFIELD_NAME

    m = Basemap(projection='npstere', resolution='l', boundinglat=30, lon_0 = 0)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(0, 91, 20), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180, 181, 45), labels=[0, 0, 0, 1])
    m.pcolormesh(lon, lat, data, latlon=True)

    cb = m.colorbar()
    cb.set_label(units)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, long_name))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)

if __name__ == "__main__":

    # If a certain environment variable is set, look there for the input
    # file, otherwise look in the current directory.
    hdffile = 'AMSR_E_L3_SeaIce25km_V11_20050118.hdf'
    try:
        hdffile = os.path.join(os.environ['HDFEOS_ZOO_DIR'], hdffile)
    except KeyError:
        pass

    run(hdffile)


import os
import random

from twython.exceptions import TwythonError

from core.scripts.twitter_related import base
from core.twitter_related_scripts_runner import EventDispatcherSingleton
from core.utils.logging import log

class NobodyCares(base.BaseTimelineScript):
    def on_timeline_update(self, data):
        do_reply = (random.randint(0, 500) == 0)
        if not do_reply or data.get('in_reply_to_status_id_str', None) or data['entities']['user_mentions'] or len(
                data['text']) == 0:
            return

        log('Ok...sending nobody cares')

        script_dir = os.path.dirname(__file__)
        photo_rel_address = 'assets/nobody_cares.jpg'
        photo_path = os.path.join(script_dir, photo_rel_address)
        photo = open(photo_path, 'rb')

        log('Photo found')

        try:
            self.twitter.update_status_with_media(
                status='@' + data['user']['screen_name'],
                media=photo,
                in_reply_to_status_id=data['id_str']
            )
            EventDispatcherSingleton().terminate_scripts()
        except TwythonError as e:
            print(e)