import cv2
import cv2.aruco
import numpy as np
import sys
# import pygame
import time
import serial
from threading import Thread
ser1 = serial.Serial('/dev/ttyACM0', 9600)
ser2 = serial.Serial('/dev/ttyACM1', 9600)

# alpha-100  beta-150
def direction(img, top_left, top_right, centre, ids):
    x1 = top_left[0]
    y1 = top_left[1]
    x2 = top_right[0]
    y2 = top_right[1]
    s1 = (x1 + x2) / 2
    s2 = (y1 + y2) / 2
    if abs(x2 - x1) <= 15:
        if y1 > y2:
            orient = "west"
        elif y2 > y1:
            orient = "east"
    elif (x2 - x1) > 0:     # upright
        if abs(y2 - y1) <= 15:
            orient = "north"
        elif (y2 > y1):
            orient = "ne"
        elif (y1 > y2):
            orient = "nw"
    elif (x2 - x1) < 0:
        if abs(y2 - y1) <= 15:
            orient = "south"
        elif (y1 > y2):
            orient = "sw"
        elif (y2 > y1):
            orient = "se"
    return orient

def radio1(data, ids):
    if ids == 100:
        if data == 'for':
            print("forward")
            ser1.write('w'.encode())
        if data == 'lt':
            print("left")
            ser1.write('a'.encode())
        if data == 'rev':
            print("reverse")
            ser1.write('s'.encode())
        if data == 'rt':
            print("right")
            ser1.write('d'.encode())
        if data == 'z':
            sys.exit()
        if data == 'c':
            print("not pressed")
            ser1.write('q'.encode())
        time.sleep(0.1)

def radio2(data, ids):
    if ids == 150:
        if data == 'for':
            print("forward")
            ser2.write('w'.encode())
        if data == 'lt':
            print("left")
            ser2.write('a'.encode())
        if data == 'rev':
            print("reverse")
            ser2.write('s'.encode())
        if data == 'rt':
            print("right")
            ser2.write('d'.encode())
        if data == 'z':
            sys.exit()
        if data == 'c':
            print("not pressed")
            ser2.write('q'.encode())
        time.sleep(0.1)

def send_radio(data, ids):
    t1 = Thread(target=radio1, args=(data, ids))
    t2 = Thread(target=radio2, args=(data, ids))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

def orientation(img, top_left, top_right, centre, ids):
    x1 = top_left[0]
    y1 = top_left[1]
    x2 = top_right[0]
    y2 = top_right[1]
    s1 = (x1 + x2) / 2
    s2 = (y1 + y2) / 2
    data = 'for'
    # centre1 = centre[0]
    # centre2 = centre[1]
    # destination coord
    d1 = 250.0
    d2 = 250.0
    orient = ""

    if abs(s1 - d1) <= 15 and abs(s2 - d2) <= 15:
        data = 'c'
    # north
    # orient = direction(img, top_left, top_right, centre, ids)
    if direction(img, top_left, top_right, centre, ids) == "north":
    	send_radio('c', ids)
    else:
        direc = direction(img, top_left, top_right, centre, ids)
        while direc != 'north':
            print("Stuck in loop")
            send_radio('rt', ids)
            send_radio('c', ids)
            direc = direction(img, top_left, top_right, centre, ids)
            break
        send_radio('c', ids)
    # send_radio(data, ids)

if __name__=='__main__':
    cap = cv2.VideoCapture(2)
    dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_6X6_250)
    while True:
        ret, frame = cap.read()
        # getting all the values in different variables
        corners, ids, rejected = cv2.aruco.detectMarkers(frame, dictionary)
        cv2.aruco.drawDetectedMarkers(frame, corners, ids)
        # createGrid(frame)
        cv2.imshow('out', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        if len(corners) > 0:
            # draw only if aruco detected
            i = 0

            # nested loop only for centre coordinates
            while i < len(corners):
                # corners contains 4 coordinates of the aruco (2d array)
                j = 0
                while j < len(corners[i]):
                    # first taking sum of all x coord, then divide by 4. Then y
                    pos = np.sum(corners[i], axis=1) / 4
                    j = j + 1
                    # call the function for position
                    # checkMarker(frame, ids[i], pos)
                    # orient north and move
                    orientation(frame, corners[0][0][0], corners[0][0][1], pos, ids[i])
                i = i + 1
            print("\n")
        # cv2.imshow('out', frame)
        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break

    cap.release()
    cv2.destroyAllWindows()


import os
import os.path as op
import numpy as np
import re
import csv
import nltk
from collections import defaultdict
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

#nqa_dir = os.environ["NARRATIVEQA_DIR"]
mimir_dir = os.environ["MIMIR_DIR"]
data_dir = op.join(mimir_dir, "data")

def map_words_to_named_entities(obj_dict, classes = ["ORG","LOC","PERSON"]):

	word2entity = {}

	for ne_class in classes:
		for idx, obj in obj_dict[ne_class].items():
			for name in obj.name_variants:
				word2entity[name] = idx

	return(word2entity)

def make_dataset_dict():
	data_dir = op.join(mimir_dir, "data")
	id_name_dict = make_id_name_dict()
	summary_csv = op.join(data_dir, "summaries.csv")
	summary_list = csv_to_list(summary_csv)
	name_dataset_dict = {}
	for row in summary_list[1:]:
		try:
			doc_id, corpus_set, _, _ = row
			book_name = id_name_dict[doc_id]
			name_dataset_dict[book_name] = corpus_set #Test, train, valid#
		except KeyError:
			pass
	return name_dataset_dict

def make_qa_dict_valid(qaps_line_list, id_name_dict):
	qa_dict_valid = {}
	for line in qaps_line_list:
		if line[0] in id_name_dict: #if it's a book
			if line[1] == "valid":
				qa_dict_valid[line[2]] = (id_name_dict[line[0]],[line[3],line[4]])
	return(qa_dict_valid)

def tokenize(sent:str):
	return word_tokenize(sent)

def remove_stopwords(sent:list):
	stop_words = set(stopwords.words("english"))
	return ([word for word in sent if word.lower() not in stop_words and word.isalnum()])

def csv_to_list(csv_file_path):

	line_list = []

	with open(csv_file_path, newline="") as csvfile:
		csvreader = csv.reader(csvfile)
		for row in csvreader:
			line_list.append(row)

	return(line_list)

def list_to_csv(csv_file_path, line_list):

	with open(csv_file_path, "w+") as csvfile:
		csvwriter = csv.writer(csvfile)
		for row in line_list:
			csvwriter.writerow(row)

def load_or_create_object(numpy_filename: str, obj: object):
	if not numpy_filename.endswith(".npy"):
		numpy_filename += ".npy"
	if not op.exists(numpy_filename):
		return obj
	else:
		return np.load(numpy_filename, allow_pickle=True)[0]

def make_id_name_dict():
	id_name_dict = {}
	docs_csv = op.join(data_dir, "documents.csv")
	docs_list = csv_to_list(docs_csv)
	for line in docs_list[1:]:
		try:
			if line[2] == "gutenberg":
				id_name_dict[line[0]] = line[6]
		except:
			pass
	return(id_name_dict)

def make_name_url_dict():
	id_name_dict = make_id_name_dict()
	name_url_dict = {}
	id_url_csv = op.join(data_dir, "id_url.csv")
	id_url_list = csv_to_list(id_url_csv)
	for line in id_url_list[1:]:
		try:
			if line[1] == "gutenberg":
				name_url_dict[id_name_dict[line[0]]] = line[2]
		except:
			pass
	return name_url_dict

def map_words_to_named_entities(obj_dict, classes = ["PERSON"]):

	word2entity = {}

	for ne_class in set(classes)&set(obj_dict.keys()):
		for idx, obj in obj_dict[ne_class].items():
			for name in obj.name_variants:
				word2entity[name] = idx

	return(word2entity)

def levenshtein(input_sentence, target_sentence):
	#Calculates the minimum edit distance (Levenshtein distance) between two strings (or lists)
	if type(input_sentence) != type(target_sentence):
		raise TypeError("Input and target should probably be the same type. \
Input (type {}): {} \
Target (type {}): {}".format(type(input_sentence),input_sentence, type(target_sentence),target_sentence))

	trellis = np.zeros((len(input_sentence) + 1, len(target_sentence) + 1))
	trellis[:,0] = np.arange(len(input_sentence)+1)
	trellis[0,:] = np.arange(len(target_sentence)+1)

	for i in range(1, len(input_sentence) + 1):
		w_in = input_sentence[i-1]
		for j in range(1, len(target_sentence) +1):
			w_t = target_sentence[j-1]
			if w_in == w_t:
				square_score = 0
			else:
				square_score = 1
			trellis[i,j] = min(trellis[i-1,j], trellis[i-1,j-1], trellis[i,j-1]) +square_score

	return(trellis[-1,-1])

def download_models():
	nltk.download('stopwords')
	nltk.download('punkt')
	nltk.download('averaged_perceptron_tagger')
	nltk.download('maxent_ne_chunker')
	nltk.download('words')

def get_line_list_from_file(file):
	with open(file) as f:
		line_list = f.readlines()

	return line_list

def file_path_to_text(file):
    line_list = get_line_list_from_file(file)
    raw_text = " ".join([line.strip("\n") for line in line_list])
    return(raw_text)

def get_tokens_from_text(line):
	tokens = nltk.word_tokenize(line)

	return tokens

def get_named_entities(tokens):
	entities = nltk.chunk.ne_chunk(nltk.pos_tag(tokens))
	return entities

def ne_labels_from_file(file_path):
	line_list = get_line_list_from_file(file_path)
	entity_list = []

	all_lines = " ".join([line.strip("\n") for line in line_list])
	entities = get_named_entities(tokenize(all_lines))
	return(entities)

def context_to_tokens(labelled_string: list, stemmer):
	tokens = []
	for item in labelled_string:
		if isinstance(item, nltk.tree.Tree):
			leaves = item.leaves()
			tokens += [stemmer.stem(leaf[0]) for leaf in leaves]
		else:
			tokens.append(stemmer.stem(item[0]))
	return(tokens)

def ne_BOWs_from_file(file_path, context_length=5, stemmer=None):
	ne_labels = ne_labels_from_file(file_path)

	BOWs_dict = defaultdict(list)

	for i, item in enumerate(ne_labels):
		if isinstance(item, nltk.tree.Tree):
			if item.label() == "PERSON":
				person_name = " ".join([leaf[0] for leaf in item.leaves()])
				before_context = ne_labels[i-context_length:i]
				after_context = ne_labels[i+1:i+1+context_length]
				BOWs_dict[person_name] += context_to_tokens(before_context + after_context, stemmer)

	return(BOWs_dict)

def merge_list(list_list):
	return [l for sub_l in list_list for l in sub_l]

def BOWs_to_TFIDF(BOWs_dict):
	types = list(set(merge_list(list(BOWs_dict.values()))))
	DFs = defaultdict(int)
	for word in types:
		for BOW in BOWs_dict.values():
			if word in BOW:
				DFs[word] += 1

	person_TFs_dict = {}
	for person in BOWs_dict.keys():
		TFs = defaultdict(int)
		BOW = BOWs_dict[person]
		for token in BOW:
			TFs[token] += 1
		token_sum = sum(TFs.values())
		for token in TFs:
			TFs[token] = TFs[token]/token_sum
		person_TFs_dict[person] = TFs

	tf_idf_dict = defaultdict(dict)
	for person, tf_dict in person_TFs_dict.items():
		for word, tf in tf_dict.items():
			tf_idf_dict[person][word] = tf * (1/DFs[word])

#	print(tf_idf_dict)
#	import pdb; pdb.set_trace()
	return(tf_idf_dict)

def ne_tokens_from_file(file_path, pause=False):
	line_list = get_line_list_from_file(file_path)
	entity_list = []

	for line in line_list: #for each sentence in the input file
		line.strip("\n")
		t = get_tokens_from_text(line) #get tokens
		entities = get_named_entities(t) # get entities tree
		if pause == True:
			print(entities)

			stop = input("stop? y/n")
			if stop == "y":
				import pdb; pdb.set_trace()

		for e in entities:
			if isinstance(e, nltk.tree.Tree): #it's an entity
				ent_string = " ".join([leaf[0] for leaf in e.leaves()])
				ent_tuple = (ent_string, e.label())

				entity_list.append(ent_tuple)
	return(entity_list)

def list_to_dict(l:list):
	out_dict = defaultdict(int)

	for thing in l:
		out_dict[thing] += 1
	return(out_dict)

def ne_list_from_file(file_path, pause=False):
	line_list = get_line_list_from_file(file_path)
	entity_list = []

	for line in line_list: #for each sentence in the input file
		line.strip("\n")
		t = get_tokens_from_text(line) #get tokens
		entities = get_named_entities(t) # get entities tree
		if pause == True:
			print(entities)

			stop = input("stop? y/n")
			if stop == "y":
				import pdb; pdb.set_trace()

		for e in entities:
			if isinstance(e, nltk.tree.Tree): #it's an entity
				ent_string = " ".join([leaf[0] for leaf in e.leaves()])
				ent_tuple = (ent_string, e.label())

				if ent_tuple not in entity_list:
					entity_list.append(ent_tuple)
	return(entity_list)

def extract_text_from_gutenberg(text):
	text = re.split(r"\*\*\*.*?START.*?PROJECT GUTENBERG EBOOK.*?\*\*\*", text)[1]
	text = re.split(r"\*\*\*.*?END.*?PROJECT GUTENBERG EBOOK.*?\*\*\*", text)[0]
	return(text)

def ne_sent_dict_from_file(file_path, pause=False):
	full_text = file_path_to_text(file_path)
	full_text = extract_text_from_gutenberg(full_text)
	sentences = full_text.split(".")

	entity_list = []

	entity_sentence_dict = defaultdict(list)

	for sentence in sentences: #for each sentence in the input file
		sentence.strip("\n")
		t = get_tokens_from_text(sentence) #get tokens
		entities = get_named_entities(t) # get entities tree
		if pause == True:
			print(entities)

			stop = input("stop? y/n")
			if stop == "y":
				import pdb; pdb.set_trace()

		for e in entities:
			if isinstance(e, nltk.tree.Tree): #it's an entity
				ent_string = " ".join([leaf[0] for leaf in e.leaves()])
				ent_tuple = (ent_string, e.label())

				if ent_tuple not in entity_list:
					entity_sentence_dict[ent_tuple].append(t)

	return(entity_sentence_dict)

if __name__ == "__main__":

	print(make_dataset_dict())
	exit(1)
	download_models()
	print(ne_list_from_file(op.join(mimir_dir,"data","nqa_summary_text_files","train", "Anna Karenina")))

	print(BOWs_to_TFIDF(ne_BOWs_from_file(op.join(mimir_dir,"data","dune_plot.txt"))))


import pickle
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from sklearn.model_selection import KFold
from sklearn import metrics
import sys
import create_contact_features
import matplotlib.pyplot as plt
import math
from joblib import dump, load
from sklearn.metrics import confusion_matrix
from collections import defaultdict

#from xgboost import XGBClassifier
#import eli5
#from eli5.sklearn import PermutationImportance

alleles = []
allele_indices = []
running_index = 0
print("Reading Data")

data = pickle.load(open("data_ensemble.pkl",'rb'))
X_o = data['X']
y_o = data['y']
peptides = data['peptides']
alleles = data['alleles']

rows_finite = np.isfinite(X_o).all(axis=1)
X_o = X_o[rows_finite]
y_o = y_o[rows_finite]
peptides = peptides[rows_finite]
alleles = alleles[rows_finite]

allele_peptides = defaultdict(lambda: [])
labels = defaultdict(lambda: [])
for i in range(len(peptides)):
    if (i%10000) == 0: print(i)
    ap_name = alleles[i] + "-" + peptides[i]
    allele_peptides[ap_name].append(X_o[i])
    labels[ap_name].append(y_o[i])

X = []
y = []
peptides_n = []
alleles_n = []
for allele_peptide in allele_peptides.keys():
    allele, peptide = allele_peptide.split("-")
    X.append(np.mean(allele_peptides[allele_peptide], axis=0))
    y.append(labels[allele_peptide][0])
    peptides_n.append(peptide)
    alleles_n.append(allele)

X = np.array(X)
y = np.array(y)

print(X.shape, y.shape, len(peptides_n), len(alleles_n))

data = {'X':X, 'y':y, 'peptides':peptides_n, 'alleles':alleles_n}

f = open("data_ensemble_avg.pkl", 'wb')
pickle.dump(data, f)
f.close()


import mailchimp
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_delete, pre_save, post_save
from django.dispatch import receiver

import hq.models
from hq.models import Person

class Subscription(models.Model):
    name = models.CharField(max_length=50, unique=True)
    description = models.TextField()
    subscribers = models.ManyToManyField(hq.models.Person,
        related_name='subscriptions', through='UserSubscription')
    mailchimp_id = models.CharField(max_length=32, blank=True)

    def __unicode__(self):
        return self.name

class UserSubscription(models.Model):
    user = models.ForeignKey(hq.models.Person)
    subscription = models.ForeignKey(Subscription)

    class Meta:
        unique_together = ('user', 'subscription')

    def mailchimp_add(self):
        if hasattr(self, 'no_api'):
            return
        listid = self.subscription.mailchimp_id
        if listid:
            try:
                mc = mailchimp.Mailchimp(settings.MAILCHIMP_APIKEY)
                mc.lists.subscribe(
                    listid,
                    {'email': self.user.email},
                    {'FNAME': self.user.given_name,
                     'LNAME': self.user.family_name,
                     'UID': self.user.id},
                    double_optin=False,
                    send_welcome=False)
            except mailchimp.ListAlreadySubscribedError:
                pass

    def mailchimp_remove(self, old_email=None):
        if hasattr(self, 'no_api'):
            return
        listid = self.subscription.mailchimp_id
        if listid:
            try:
                mc = mailchimp.Mailchimp(settings.MAILCHIMP_APIKEY)
                mc.lists.unsubscribe(
                    listid,
                    {'email': old_email if old_email else self.user.email},
                    send_goodbye=False,
                    send_notify=False)
            except (mailchimp.ListNotSubscribedError,
                    mailchimp.EmailNotExistsError):
                pass

    def mailchimp_update(self, old_email=None):
        if hasattr(self, 'no_api'):
            return
        listid = self.subscription.mailchimp_id
        if listid:
            mc = mailchimp.Mailchimp(settings.MAILCHIMP_APIKEY)
            args = {
                'id': listid,
                'email': {'email': self.user.email},
                'merge_vars': {
                    'FNAME': self.user.given_name,
                    'LNAME': self.user.family_name,
                    'UID': self.user.id,
                },
                'update_existing': True,
            }

            if old_email:
                args['email']['email'] = old_email
                args['merge_vars']['new-email'] = self.user.email
            try:
                mc.lists.subscribe(**args)
            except mailchimp.ListAlreadySubscribedError:
                self.mailchimp_remove(old_email=old_email)

@receiver(pre_save, sender=UserSubscription)
def _add_to_mailchimp(sender, instance, **kwargs):
    instance.mailchimp_add()

@receiver(pre_delete, sender=UserSubscription)
def _remove_from_mailchimp(sender, instance, **kwargs):
    instance.mailchimp_remove()

@receiver(pre_save, sender=Person)
def _update_person_mailchimp(sender, instance, **kwargs):
    try:
        old = Person.objects.get(id=instance.id)
    except (Person.DoesNotExist, Person.MultipleObjectsReturned):
        return

    if not instance.email:
        for usub in old.usersubscription_set.all():
            usub.delete()
    elif old.email != instance.email:
        for usub in instance.usersubscription_set.all():
            usub.mailchimp_update(old_email=old.email)

@receiver(post_save, sender=Person)
def _sync_new_person_to_mailchimp(sender, instance, created, **kwargs):
    if created and instance.email:
        mc = mailchimp.Mailchimp(settings.MAILCHIMP_APIKEY)
        for sub in Subscription.objects.exclude(mailchimp_id=''):
            result = mc.lists.member_info(
                sub.mailchimp_id, [{'email': instance.email}])
            if result['data']:
                usub = UserSubscription(user=instance, subscription=sub)
                usub.no_api = True
                usub.save()
                del usub.no_api
                usub.mailchimp_update()


# how to create variable
x = 5
# in python you don't need write $ like php or you dont need write int string before name ov var
# also you don't need write let var etc
# just write a name of variable

# in name you can use letters (latin only), _ , Numbers
my_var1 = 100

_anotherVar = 200

# not working first symbol can't be a Number
# 12anotherVar = 300

_123test = 400
print(_123test)
print(type(_123test))


from django.conf.urls import url
from . import views

urlpatterns = [
    # Examples:
    # url(r'^$', 'ecommerce.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^$', views.show_menus, name='show_menus'),
    url(r'^spide_menus/$', views.spide_menus, name='spide_menus'),
    url(r'^menu_page/(?P<menu_folder>[a-z_0-9]+)/$', views.menu_page, name='menu_page'),
    url(r'^delete_menu/(?P<menu_folder>[a-z_0-9]+)/$', views.delete_menu, name='delete_menu'),
]


# Import dependencies
import numpy as np

# Collect data and change pos1,pos2
p = list(np.genfromtxt('day2_input.csv', delimiter=',', dtype=int))
solution = 19690720

# Write integer computer function
def intComp(p):
    tp = p[:]

    for i in range(0, len(tp), 4):
        if tp[i] == 99:
            return tp[0]
        elif tp[i] == 1:
            tp[tp[i + 3]] = tp[tp[i + 1]] + tp[tp[i + 2]]
        elif tp[i] == 2:
            tp[tp[i + 3]] = tp[tp[i + 1]] * tp[tp[i + 2]]

    return tp[0]

for noun in range(100):
    for verb in range(100):
        p[1] = noun
        p[2] = verb
        if intComp(p) == 19690720:
            print(100 * noun + verb)
            break


from clientclass import Client
import threading
import time

c1=Client("sharan")
time.sleep(2)
c2=Client("smiron")
time.sleep(2)

def update_messages():
    msgs=[]
    run = True
    while run:
        time.sleep(0.1)
        new_messages=c1.get_messages()
        msgs.extend(new_messages)
        for msg in new_messages:
            print(msg)
            if msg == '!disconnect':
                run = False
                break

threading.Thread(target=update_messages).start()

c1.send("hello")
time.sleep(2)
c2.send("hi")
time.sleep(1)
c1.disconnect()
time.sleep(1)
c2.disconnect()


import os
import pickle

import torch
import numpy as np

from vadam.datasets import Dataset, DEFAULT_DATA_FOLDER
from vadam.models import MLP, BNN, IndividualGradientMLP
import vadam.metrics as metrics

from torch.optim import Adam
from vadam.optimizers import Vadam, VOGN

from vadam.utils import goodfellow_backprop_ggn

###############################################################################
## Define function that specify folder naming convention for storing results ##
###############################################################################

def folder_name(experiment_name, data_set, model_params, train_params, optim_params, results_folder="./results"):
    mp = ''.join('{}:{}|'.format(key, val) for key, val in sorted(model_params.items()))[:-1]
    tp = ''.join('{}:{}|'.format(key, val) for key, val in sorted(train_params.items()))[:-1]
    op = ''.join('{}:{}|'.format(key, val) for key, val in sorted(optim_params.items()))[:-1]
    return os.path.join(results_folder, experiment_name, data_set, mp, tp, op)

###############################################################
## Define function for loading only history from experiments ##
###############################################################

def load_final_metric(experiment_name, data_set, model_params, train_params, optim_params, results_folder="./results", silent_fail=False):

    # Folder to load history from
    folder = folder_name(experiment_name, data_set, model_params, train_params, optim_params, results_folder)
    file = os.path.join(folder, 'final_metric.pkl')
    # Silent fail
    if silent_fail and not os.path.exists(file):
        return None

    # Load history
    pkl_file = open(file, 'rb')
    final_metric = pickle.load(pkl_file)
    pkl_file.close()

    # Return history
    return final_metric

def load_metrics(file_path):
    pkl_file = open(file_path, 'rb')
    metric_history = pickle.load(pkl_file)
    pkl_file.close()
    return metric_history

def load_metric_history(experiment_name, data_set, model_params, train_params, optim_params, results_folder="./results", silent_fail=False):

    # Folder to load history from
    folder = folder_name(experiment_name, data_set, model_params, train_params, optim_params, results_folder)
    file = os.path.join(folder, 'metric_history.pkl')

    # Silent fail
    if silent_fail and not os.path.exists(file):
        return None

    # Load history
    pkl_file = open(file, 'rb')
    metric_history = pickle.load(pkl_file)
    pkl_file.close()

    # Return history
    return metric_history

def load_objective_history(experiment_name, data_set, model_params, train_params, optim_params, results_folder="./results", silent_fail=False):

    # Folder to load history from
    folder = folder_name(results_folder, experiment_name, data_set, model_params, train_params, optim_params)
    file = os.path.join(folder, 'objective_history.pkl')

    # Silent fail
    if silent_fail and not os.path.exists(file):
        return None

    # Load history
    pkl_file = open(file, 'rb')
    objective_history = pickle.load(pkl_file)
    pkl_file.close()

    # Return history
    return objective_history

######################################
## Define abstract experiment class ##
######################################

class Experiment():

    def __init__(self, data_set, model_params, train_params, optim_params, evals_per_epoch=1, normalize_x=False, results_folder="./results", data_folder=DEFAULT_DATA_FOLDER, use_cuda=torch.cuda.is_available()):

        # Store parameters
        self.data_set = data_set
        self.model_params = model_params
        self.train_params = train_params
        self.optim_params = optim_params
        self.evals_per_epoch = evals_per_epoch
        self.normalize_x = normalize_x
        self.data_folder = data_folder
        self.results_folder = results_folder
        self.use_cuda = use_cuda

        # Set random seed
        seed = train_params['seed']
        torch.manual_seed(seed)
        if self.use_cuda:
            torch.cuda.manual_seed_all(seed)

        # Initialize metric history
        self.objective_history = []

        # Initialize data
        self.data = Dataset(data_set = data_set, data_folder = data_folder)

        ## All subclasses should override:

        # Define folder name for results
        self.folder_name = None

        # Define prediction function
        self.prediction = None

        # Define objective
        self.objective = None

        # Initialize model
        self.model = None

        # Initialize optimizer
        self.optimizer = None

        # Initialize metric history
        self.metric_history = None

        # Initialize final metric
        self.final_metric = None

    def run(self, log_metric_history=True):

        # Prepare
        num_epochs = self.train_params['num_epochs']
        batch_size = self.train_params['batch_size']
        seed = self.train_params['seed']

        # Set random seed
        torch.manual_seed(seed)
        if self.use_cuda:
            torch.cuda.manual_seed_all(seed)

        # Prepare data loader for training
        train_loader = self.data.get_train_loader(batch_size = batch_size)

        # Load full data set for evaluation
        x_train, y_train = self.data.load_full_train_set(use_cuda = self.use_cuda)
        x_test, y_test = self.data.load_full_test_set(use_cuda = self.use_cuda)

        # Compute normalization of x
        if self.normalize_x:
            self.x_means = torch.mean(x_train, dim=0)
            self.x_stds = torch.std(x_train, dim=0)
            self.x_stds[self.x_stds == 0] = 1

        # Set iterations for evaluation
        num_batches = np.ceil(self.data.get_train_size() / batch_size)
        if self.evals_per_epoch > num_batches:
            evals_per_epoch = num_batches
        else:
            evals_per_epoch = self.evals_per_epoch
        eval_iters = np.round((1 + np.arange(evals_per_epoch)) * (num_batches / evals_per_epoch)).astype(int)

        # Train model
        for epoch in range(num_epochs):

            # Set model in training mode
            self.model.train(True)

            # Initialize batch objective accumulator
            batch_objective = []

            for i, (x, y) in enumerate(train_loader):

                # Prepare minibatch
                if self.use_cuda:
                    x, y = x.cuda(), y.cuda()

                # Normalize x and y
                if self.normalize_x:
                    x = (x-self.x_means)/self.x_stds

                # Update parameters
                def closure():
                    return self._closure(x, y)
                loss = self.optimizer.step(closure)

                if log_metric_history and (i+1) in eval_iters:

                    # Set model in test mode
                    self.model.train(False)

                    # Evaluate model
                    with torch.no_grad():
                        self._evaluate_model(self.metric_history, x_train, y_train, x_test, y_test)

                # Store batch objective
                batch_objective.append(loss.detach().cpu().item())

            # Compute and store average objective from last epoch
            self.objective_history.append(np.mean(batch_objective))

            if log_metric_history:

                # Print progress
                self._print_progress(epoch)

            else:

                # Print average objective from last epoch
                self._print_objective(epoch)

        # Set model in test mode
        self.model.train(False)

        # Evaluate model
        with torch.no_grad():
            self._evaluate_model(self.final_metric, x_train, y_train, x_test, y_test)

    def _evaluate_model(self, metric_dict, x_train, y_train, x_test, y_test):

        ## All subclasses should override:
        raise NotImplementedError

    def _print_progress(self, epoch):

        ## All subclasses should override:
        raise NotImplementedError

    def _print_objective(self, epoch):

        # Print average objective from last epoch
        print('Epoch [{}/{}], Objective: {:.4f}'.format(
                epoch+1,
                self.train_params['num_epochs'],
                self.objective_history[-1]))

    def save(self, save_final_metric=True, save_metric_history=True, save_objective_history=True, save_model=True, save_optimizer=True, create_folder=True, folder_path=None):

        # Define folder path
        if not folder_path:
            folder_path = self.folder_name

        # Create folder
        if create_folder:
            os.makedirs(folder_path, exist_ok=True)

        # Store state dictionaries for model and optimizer
        if save_model:
            torch.save(self.model.state_dict(), os.path.join(folder_path, 'model.pt'))
        if save_optimizer:
            torch.save(self.optimizer.state_dict(), os.path.join(folder_path, 'optimizer.pt'))

        # Store history
        if save_final_metric:
            output = open(os.path.join(folder_path, 'final_metric.pkl'), 'wb')
            pickle.dump(self.final_metric, output)
            output.close()
        if save_metric_history:
            output = open(os.path.join(folder_path, 'metric_history.pkl'), 'wb')
            pickle.dump(self.metric_history, output)
            output.close()
        if save_objective_history:
            output = open(os.path.join(folder_path, 'objective_history.pkl'), 'wb')
            pickle.dump(self.objective_history, output)
            output.close()

    def load(self, load_final_metric=True, load_metric_history=True, load_objective_history=True, load_model=True, load_optimizer=True, folder_path=None):

        # Define folder path
        if not folder_path:
            folder_path = self.folder_name
        # Load state dictionaries for model and optimizer
        if load_model:
            state_dict = torch.load(os.path.join(folder_path, 'model.pt'))
            self.model.load_state_dict(state_dict)
            self.model.train(False)
        if load_optimizer:
            state_dict = torch.load(os.path.join(folder_path, 'optimizer.pt'))
            self.optimizer.load_state_dict(state_dict)

        # Load history
        if load_final_metric:
            pkl_file = open(os.path.join(folder_path, 'final_metric.pkl'), 'rb')
            self.final_metric = pickle.load(pkl_file)
            pkl_file.close()
        if load_metric_history:
            pkl_file = open(os.path.join(folder_path, 'metric_history.pkl'), 'rb')
            self.metric_history = pickle.load(pkl_file)
            pkl_file.close()
        if load_objective_history:
            pkl_file = open(os.path.join(folder_path, 'objective_history.pkl'), 'rb')
            self.objective_history = pickle.load(pkl_file)
            pkl_file.close()

######################################
## Define experiment class for BBVI ##
######################################

class ExperimentBBBMLPClass(Experiment):

    def __init__(self, data_set, model_params, train_params, optim_params, evals_per_epoch=1, normalize_x=False, results_folder="./results", data_folder=DEFAULT_DATA_FOLDER, use_cuda=torch.cuda.is_available()):
        super(type(self), self).__init__(data_set, model_params, train_params, optim_params, evals_per_epoch, normalize_x, results_folder, data_folder, use_cuda)

        # Define name for experiment class
        experiment_name = "bbb_mlp_class"

        # Define folder name for results
        self.folder_name = folder_name(experiment_name, data_set, model_params, train_params, optim_params, results_folder)

        # Initialize model
        self.model = BNN(input_size = self.data.num_features,
                         hidden_sizes = model_params['hidden_sizes'],
                         output_size = self.data.num_classes,
                         act_func = model_params['act_func'],
                         prior_prec = model_params['prior_prec'],
                         prec_init = optim_params['prec_init'])
        if use_cuda:
            self.model = self.model.cuda()

        # Define prediction function
        def prediction(x):
            logits_list = [self.model(x) for _ in range(self.train_params['train_mc_samples'])]
            return logits_list
        self.prediction = prediction

        # Define objective
        def objective(logits_list, y):
            return metrics.avneg_elbo_categorical(logits_list, y, train_set_size = self.data.get_train_size(), kl = self.model.kl_divergence())
        self.objective = objective

        # Initialize optimizer
        self.optimizer = Adam(self.model.parameters(),
                              lr = optim_params['learning_rate'],
                              betas = optim_params['betas'],
                              eps = 1e-8)

        # Initialize metric history
        self.metric_history = dict(elbo_neg_ave = [],
                                   train_pred_logloss=[], train_pred_accuracy=[],
                                   test_pred_logloss=[], test_pred_accuracy=[])

        # Initialize final metric
        self.final_metric = dict(elbo_neg_ave = [],
                                 train_pred_logloss=[], train_pred_accuracy=[],
                                 test_pred_logloss=[], test_pred_accuracy=[])

    def _evaluate_model(self, metric_dict, x_train, y_train, x_test, y_test):

        # Normalize train x
        if self.normalize_x:
            x_train = (x_train-self.x_means)/self.x_stds

        # Get train predictions
        logits_list = [self.model(x_train) for _ in range(self.train_params['eval_mc_samples'])]

        # Store train metrics
        metric_dict['train_pred_logloss'].append(metrics.predictive_avneg_loglik_categorical(logits_list, y_train).detach().cpu().item())
        metric_dict['train_pred_accuracy'].append(metrics.softmax_predictive_accuracy(logits_list, y_train).detach().cpu().item())
        metric_dict['elbo_neg_ave'].append(metrics.avneg_elbo_categorical(logits_list, y_train, train_set_size = self.data.get_train_size(), kl = self.model.kl_divergence()).detach().cpu().item())

        # Normalize test x
        if self.normalize_x:
            x_test = (x_test-self.x_means)/self.x_stds

        # Get test predictions
        logits_list = [self.model(x_test) for _ in range(self.train_params['eval_mc_samples'])]

        # Store test metrics
        metric_dict['test_pred_logloss'].append(metrics.predictive_avneg_loglik_categorical(logits_list, y_test).detach().cpu().item())
        metric_dict['test_pred_accuracy'].append(metrics.softmax_predictive_accuracy(logits_list, y_test).detach().cpu().item())

    def _print_progress(self, epoch):

        # Print progress
        print('Epoch [{}/{}], Neg. Ave. ELBO: {:.4f}, Logloss: {:.4f}, Test Logloss: {:.4f}'.format(
                epoch+1,
                self.train_params['num_epochs'],
                self.metric_history['elbo_neg_ave'][-1],
                self.metric_history['train_pred_logloss'][-1],
                self.metric_history['test_pred_logloss'][-1]))

    def _closure(self, x, y):
        self.optimizer.zero_grad()
        logits = self.prediction(x)
        loss = self.objective(logits, y)
        loss.backward()
        return loss

#######################################
## Define experiment class for Vadam ##
#######################################

class ExperimentVadamMLPClass(Experiment):

    def __init__(self, data_set, model_params, train_params, optim_params, evals_per_epoch=1, normalize_x=False, results_folder="./results", data_folder=DEFAULT_DATA_FOLDER, use_cuda=torch.cuda.is_available()):
        super(type(self), self).__init__(data_set, model_params, train_params, optim_params, evals_per_epoch, normalize_x, results_folder, data_folder, use_cuda)

        # Define name for experiment class
        experiment_name = "vadam_mlp_class"

        # Define folder name for results
        self.folder_name = folder_name(experiment_name, data_set, model_params, train_params, optim_params, results_folder)

        # Initialize model
        self.model = MLP(input_size = self.data.num_features,
                         hidden_sizes = model_params['hidden_sizes'],
                         output_size = self.data.num_classes,
                         act_func = model_params['act_func'])
        if use_cuda:
            self.model = self.model.cuda()

        # Define prediction function
        def prediction(x):
            logits = self.model(x)
            return logits
        self.prediction = prediction

        # Define objective
        self.objective = metrics.avneg_loglik_categorical

        # Initialize optimizer
        self.optimizer = Vadam(self.model.parameters(),
                               lr = optim_params['learning_rate'],
                               betas = optim_params['betas'],
                               prior_prec = model_params['prior_prec'],
                               prec_init = optim_params['prec_init'],
                               num_samples = train_params['train_mc_samples'],
                               train_set_size = self.data.get_train_size())

        # Initialize metric history
        self.metric_history = dict(elbo_neg_ave = [],
                                   train_pred_logloss=[], train_pred_accuracy=[],
                                   test_pred_logloss=[], test_pred_accuracy=[])

        # Initialize final metric
        self.final_metric = dict(elbo_neg_ave = [],
                                 train_pred_logloss=[], train_pred_accuracy=[],
                                 test_pred_logloss=[], test_pred_accuracy=[])

    def _evaluate_model(self, metric_dict, x_train, y_train, x_test, y_test):

        # Normalize train x
        if self.normalize_x:
            x_train = (x_train-self.x_means)/self.x_stds

        # Get train predictions
        logits_list = self.optimizer.get_mc_predictions(self.model.forward, inputs = x_train, mc_samples = self.train_params['eval_mc_samples'], ret_numpy=False)

        # Store train metrics
        metric_dict['train_pred_logloss'].append(metrics.predictive_avneg_loglik_categorical(logits_list, y_train).detach().cpu().item())
        metric_dict['train_pred_accuracy'].append(metrics.softmax_predictive_accuracy(logits_list, y_train).detach().cpu().item())
        metric_dict['elbo_neg_ave'].append(metrics.avneg_elbo_categorical(logits_list, y_train, train_set_size = self.data.get_train_size(), kl = self.optimizer.kl_divergence()).detach().cpu().item())

        # Normalize test x
        if self.normalize_x:
            x_test = (x_test-self.x_means)/self.x_stds

        # Get test predictions
        logits_list = self.optimizer.get_mc_predictions(self.model.forward, inputs = x_test, mc_samples = self.train_params['eval_mc_samples'], ret_numpy=False)

        # Store test metrics
        metric_dict['test_pred_logloss'].append(metrics.predictive_avneg_loglik_categorical(logits_list, y_test).detach().cpu().item())
        metric_dict['test_pred_accuracy'].append(metrics.softmax_predictive_accuracy(logits_list, y_test).detach().cpu().item())

    def _print_progress(self, epoch):

        # Print progress
        print('Epoch [{}/{}], Neg. Ave. ELBO: {:.4f}, Logloss: {:.4f}, Test Logloss: {:.4f}'.format(
                epoch+1,
                self.train_params['num_epochs'],
                self.metric_history['elbo_neg_ave'][-1],
                self.metric_history['train_pred_logloss'][-1],
                self.metric_history['test_pred_logloss'][-1]))

    def _closure(self, x, y):
        self.optimizer.zero_grad()
        logits = self.prediction(x)
        loss = self.objective(logits, y)
        loss.backward()
        return loss


#!/usr/bin/env python

from argparse import FileType, ArgumentParser
import csv
from operator import itemgetter
import os

parser = ArgumentParser(description='Calculate the total of a column.');
parser.add_argument("input_csv",
                    type=FileType('rU'),
                    help="CSV containing (sum,product) pairs");
parser.add_argument("output_csv",
                    type=FileType('w'),
                    help="CSV containing one (sum,product) pair");
args = parser.parse_args();

reader = csv.DictReader(args.input_csv);
writer = csv.DictWriter(args.output_csv,
                        ['sum', 'product'],
                        lineterminator=os.linesep)
writer.writeheader()

# Copy first row unchanged
for row in reader:
    writer.writerow(row)
    break

sum_total = sum(map(int, map(itemgetter('sum'), reader)))
product_total = 0
writer.writerow(dict(sum=sum_total, product=product_total))


from django.urls import path
from products import views

app_name = 'products'

urlpatterns = [
    path('', views.index, name='index'),
    path('shop/', views.all_products_view, name='all_products'),
    path('shop/<slug>/', views.single_product_view, name='single_product'),
]


def main():
    y={}
    n=number()
    for i in range(n):
        key=input("Enter key :")
        value = input("Enter value :")
        y[key]=value
    print("Before sorting - ",y)

    dict1 = sorted(y.items())
    print("After sorting - ",dict(dict1))

def number():
    n=int(input("Enter the number of elements in the dictionary - "))
    return n

main()


# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright: Red Hat Inc. 2020
# Author: Amador Pahim <apahim@redhat.com>

"""
The GitHub Mirror endpoints
"""

import hashlib
import logging
import requests

import flask

from ghmirror.app.response import MirrorResponse
from ghmirror.data_structures.monostate import RequestsCache
from ghmirror.data_structures.monostate import StatsCache

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)-15s %(message)s')

LOG = logging.getLogger(__name__)
GH_API = 'https://api.github.com'

APP = flask.Flask(__name__)

@APP.route('/healthz', methods=["GET"])
def healthz():
    """
    Health check endpoint for Kubernetes.
    """
    return flask.Response('OK')

@APP.route('/stats', methods=["GET"])
def stats():
    """
    Cache statistics endpoint.
    """
    stats_cache = StatsCache()

    return flask.jsonify(
        {
            'cache_hit': stats_cache.hits,
            'cache_miss': stats_cache.misses,
        }
    )

@APP.route('/', defaults={'path': ''})
@APP.route('/<path:path>', methods=["GET", "POST", "PUT", "PATCH", "DELETE"])
def ghmirror(path):
    """
    Default endpoint, matching any url without a specific endpoint.
    """
    url = f'{GH_API}/{path}'

    if flask.request.args:
        url += '?'
        for key, value in flask.request.args.items():
            url += f'{key}={value}&'
        url = url.rstrip('&')

    headers = {}
    authorization = flask.request.headers.get('Authorization')
    auth_sha = None
    if authorization is not None:
        headers['Authorization'] = authorization
        # The authorization token will be used as cache key,
        # so let's hash it for additional security.
        auth_sha = hashlib.sha1(authorization.encode()).hexdigest()

    if flask.request.method != 'GET':
        LOG.info('[%s] BYPASS %s', flask.request.method, url)

        resp = requests.request(flask.request.method,
                                url=url,
                                headers=headers,
                                data=flask.request.data)

        return flask.Response(resp.content,
                              resp.status_code)

    stats_cache = StatsCache()
    cache = RequestsCache()

    cache_key = (url, auth_sha)
    if cache_key in cache:
        etag = cache[cache_key].headers.get('ETag')
        if etag is not None:
            headers['If-None-Match'] = etag
        last_mod = cache[cache_key].headers.get('Last-Modified')
        if last_mod is not None:
            headers['If-Modified-Since'] = last_mod

    resp = requests.request(flask.request.method,
                            url=url,
                            headers=headers)

    if resp.status_code != 304:
        LOG.info('[GET] CACHE_MISS %s', url)
        stats_cache.miss()
        # Caching only makes sense when at least one
        # of those headers is present
        if any(['ETag' in resp.headers,
                'Last-Modified' in resp.headers]):
            cache[cache_key] = resp
        mirror_response = MirrorResponse(original_response=resp,
                                         gh_api_url=GH_API,
                                         gh_mirror_url=flask.request.host_url)
    else:
        LOG.info('[GET] CACHE_HIT %s', url)
        stats_cache.hit()
        mirror_response = MirrorResponse(original_response=cache[cache_key],
                                         gh_api_url=GH_API,
                                         gh_mirror_url=flask.request.host_url)

    return flask.Response(mirror_response.content,
                          mirror_response.status_code,
                          mirror_response.headers)

if __name__ == '__main__':  # pragma: no cover
    APP.run(host='127.0.0.1', debug=True, port='8080')


import numpy as np
from PIL import Image

def image2array(image):
    image = np.asarray(image)
    if image.ndim==3:
        image = image.transpose(2, 0, 1)
    elif image.ndim==2:
        image = np.expand_dims(image, axis=0)
    return image.astype(np.float32)


from sapol.ui import Actor, Group
from sapol.math import interpolation
from sapol.ui.action import (
    Action, AddAction, RemoveAction, MoveToAction, MoveByAction, SizeToAction,
    SizeByAction, ScaleToAction, ScaleByAction, RotateToAction, RotateByAction,
    ColorAction, AlphaAction, FadeInAction, FadeOutAction, VisibilityAction,
    InteractiveAction, DelayAction, SequenceAction, ParallelAction, NotifyAction,
    AddListenerAction, RemoveListenerAction, AddActionAction, RemoveActionAction,
    RepeatAction)

def addActor(actor: Actor, to: Group=None):
    """See :py:class:`~sapol.ui.AddAction`."""
    return AddAction(actor, to)

def removeActor(actor: Actor, fromGroup: Group=None):
    """See :py:class:`~sapol.ui.RemoveAction`."""
    return RemoveAction(actor, fromGroup)

def addAction(action: Action, to: Actor=None):
    """See :py:class:`~sapol.ui.AddActionAction`."""
    return AddActionAction(action, to)

def removeAction(action: Action, fromActor: Actor=None):
    """See :py:class:`~sapol.ui.RemoveActionAction`."""
    return RemoveActionAction(action, fromActor)

def moveTo(toX, toY, **kwargs):
    """See :py:class:`~sapol.ui.MoveToAction`."""
    return MoveToAction(toX, toY, **kwargs)

def moveBy(byX, byY, **kwargs):
    """See :py:class:`~sapol.ui.MoveByAction`."""
    return MoveByAction(byX, byY, **kwargs)

def sizeTo(toWidth, toHeight, **kwargs):
    """See :py:class:`~sapol.ui.SizeToAction`."""
    return SizeToAction(toWidth, toHeight, **kwargs)

def sizeBy(byWidth, byHeight, **kwargs):
    """See :py:class:`~sapol.ui.SizeByAction`."""
    return SizeByAction(byWidth, byHeight, **kwargs)

def scaleTo(xScale, yScale, **kwargs):
    """See :py:class:`~sapol.ui.ScaleToAction`."""
    return ScaleToAction(xScale, yScale, **kwargs)

def scaleBy(xScaleBy, yScaleBy, **kwargs):
    """See :py:class:`~sapol.ui.ScaleByAction`."""
    return SizeByAction(xScaleBy, yScaleBy, **kwargs)

def rotateTo(zRot, **kwargs):
    """See :py:class:`~sapol.ui.RotateToAction`."""
    return RotateToAction(zRot, **kwargs)

def rotateBy(zRot, **kwargs):
    """See :py:class:`~sapol.ui.RotateByAction`."""
    return RotateByAction(zRot, **kwargs)

def color(r, g, b, a=None, **kwargs):
    """See :py:class:`~sapol.ui.ColorAction`."""
    return ColorAction(r, g, b, a, **kwargs)

def alpha(toAlpha, **kwargs):
    """See :py:class:`~sapol.ui.AlphaAction`."""
    return AlphaAction(toAlpha, **kwargs)

def fadeIn(time, interpolation=interpolation.LINEAR):
    """See :py:class:`~sapol.ui.FadeInAction`."""
    return FadeInAction(time, interpolation)

def fadeOut(time, interpolation=interpolation.LINEAR):
    """See :py:class:`~sapol.ui.FadeOutAction`."""
    return FadeOutAction(time, interpolation)

def visible(visible, actor=None):
    """See :py:class:`~sapol.ui.VisibilityAction`."""
    return VisibilityAction(visible, actor)

def interactive(interactive, actor=None):
    """See :py:class:`~sapol.ui.InteractiveAction`."""
    return InteractiveAction(interactive, actor)

def delay(seconds):
    """See :py:class:`~sapol.ui.DelayAction`."""
    return DelayAction(seconds)

def sequence(*actions, immediate=True, resetActions=True):
    """See :py:class:`~sapol.ui.SequenceAction`."""
    return SequenceAction(*actions, immediate=immediate, resetActions=resetActions)

def parallel(*actions, resetActions=True):
    """See :py:class:`~sapol.ui.ParallelAction`."""
    return ParallelAction(*actions, resetActions)

def repeat(repetitionLimit, *actions):
    """See :py:class:`~sapol.ui.RepeatAction`."""
    return RepeatAction(repetitionLimit, *actions)

def notify(toCall, **callArgs):
    """See :py:class:`~sapol.ui.NotifyAction`."""
    return NotifyAction(toCall, **callArgs)

def addListener(listener, to: Actor=None):
    """See :py:class:`~sapol.ui.AddListenerAction`."""
    return AddListenerAction(listener, to)

def removeListener(listener, fromActor: Actor=None):
    """See :py:class:`~sapol.ui.RemoveListenerAction`."""
    return RemoveListenerAction(listener, fromActor)

def create(*actions):
    if len(actions) == 0:
        raise RuntimeError("actions.create requires at least one action to create.")
    elif len(actions) == 1:
        # We don't want to create a sequence action if there is only one action to create:
        return _createAction(actions[0])
    # Create a sequence action using the list of cactions created:
    return SequenceAction(*_createActions(actions))

def _createActions(actions):
    actionList = []
    for action in actions:
        actionList.append(_createAction(action))
    return actionList

def _createAction(data):
    # Return the raw action:
    if isinstance(data, Action):
        return data
    # If the object has items, assume it is a dict:
    elif hasattr(data, "items"):
        parallelActions = []
        for actionType, trueAction in data.items():
            parallelActions.append(_createActionFromName(actionType, trueAction))
        return ParallelAction(*parallelActions)
    elif isinstance(data[0], str):
        return _createActionFromName(data[0], data[1:])
    else:
        return SequenceAction(*_createActions(data))

def _createActionFromName(typename, data):
    # If data is not a list of some sort, it needs to be converted to one:
    try:
        data[0]
    except TypeError:
        data = (data,)
    # Allow typename to be case-insensitive:
    typename = typename.lower()

    if typename.startswith("addactor"):
        return AddAction(*data)
    elif typename.startswith("removeactor"):
        return RemoveAction(*data)
    elif typename.startswith("addaction"):
        return AddActionAction(create(data[0]), *data[1:])
    elif typename.startswith("removeaction"):
        return RemoveActionAction(*data)
    elif typename.startswith("moveto"):
        return _createActionWithClass(MoveToAction, typename, len("moveto"), data)
    elif typename.startswith("moveby"):
        return _createActionWithClass(MoveByAction, typename, len("moveby"), data)
    elif typename.startswith("sizeto"):
        return _createActionWithClass(SizeToAction, typename, len("sizeto"), data)
    elif typename.startswith("sizeby"):
        return _createActionWithClass(SizeByAction, typename, len("sizeby"), data)
    elif typename.startswith("scaleto"):
        return _createActionWithClass(ScaleToAction, typename, len("scaleto"), data)
    elif typename.startswith("scaleby"):
        return _createActionWithClass(ScaleByAction, typename, len("scaleby"), data)
    elif typename.startswith("rotateto"):
        return _createActionWithClass(RotateToAction, typename, len("rotateto"), data)
    elif typename.startswith("rotateby"):
        return _createActionWithClass(RotateByAction, typename, len("rotateby"), data)
    elif typename.startswith("color"):
        return _createActionWithClass(ColorAction, typename, len("color"), data)
    elif typename.startswith("alpha"):
        return _createActionWithClass(AlphaAction, typename, len("alpha"), data)
    elif typename.startswith("fadein"):
        return FadeInAction(*data)
    elif typename.startswith("fadeout"):
        return FadeOutAction(*data)
    elif typename.startswith("visibility"):
        return VisibilityAction(*data)
    elif typename.startswith("interactive"):
        return InteractiveAction(*data)
    elif typename.startswith("delay"):
        return DelayAction(*data)
    elif typename.startswith("notify"):
        if len(data) == 1:
            return NotifyAction(data[0])
        elif len(data) == 2:
            return NotifyAction(data[0], **data[1])
        else:
            raise RuntimeError("Notify requires any arguments to be in a dict.")
    elif typename.startswith("addlistener"):
        return AddListenerAction(*data)
    elif typename.startswith("removelistener"):
        return RemoveListenerAction(*data)
    elif typename.startswith("sequence"):
        return _createAction(data)
    elif typename.startswith("parallel"):
        return ParallelAction(*_createActions(data))
    elif typename.startswith("repeat"):
        if typename.startswith(".forever", len("repeat")):
            return RepeatAction(None, *_createActions(data))
        else:
            return RepeatAction(data[0], *_createActions(data[1:]))
    elif typename.startswith("action"):
        return data[0]
    else:
        raise RuntimeError("No standard action with the name: {n}".format(n=typename))

def _createActionWithClass(cls, typename, nameEnd, data):
    argsdict = {}
    # Main args represents the arguments that are given in order for the action.
    # For example, MoveToAction takes two arguments: toX, toY while AlphaAction
    # only takes one: toAlpha
    mainArgCount = 2
    # Extra args represent extra arguments that can sometimes be in place, and
    # take place before the time/speed arguments. For example, ColorAction can
    # take an alpha value if '.a' is provided, so it has one extra argument.
    extraArgs = 0
    if typename.startswith("rotate"):
        mainArgCount = 1
        if typename.startswith(".xy", nameEnd):
            nameEnd += 3
            argsdict["xRot"] = data[mainArgCount]
            argsdict["yRot"] = data[mainArgCount + 1]
            extraArgs = 2
        elif typename.startswith(".yx", nameEnd):
            nameEnd += 3
            argsdict["yRot"] = data[mainArgCount]
            argsdict["xRot"] = data[mainArgCount + 1]
            extraArgs = 2
        elif typename.startswith(".x", nameEnd):
            nameEnd += 2
            argsdict["xRot"] = data[mainArgCount]
            extraArgs = 1
        elif typename.startswith(".y", nameEnd):
            nameEnd += 2
            argsdict["yRot"] = data[mainArgCount]
            extraArgs = 1
    elif typename.startswith("color"):
        mainArgCount = 3
        if typename.startswith(".a", nameEnd):
            nameEnd += 2
            mainArgCount = 4
    elif typename.startswith("alpha"):
        mainArgCount = 1

    if typename.startswith(".time", nameEnd):
        argsdict["time"] = data[mainArgCount + extraArgs]
        if len(data) > mainArgCount + extraArgs + 1:
            argsdict["interpolation"] = data[mainArgCount + extraArgs + 1]
    elif typename.startswith(".speed", nameEnd):
        argsdict["speed"] = data[mainArgCount + extraArgs]
        if len(data) > mainArgCount + extraArgs + 1:
            argsdict["interpolation"] = data[mainArgCount + extraArgs + 1]

    return cls(*data[0:mainArgCount], **argsdict)


running = True
is_started = False
while running:
    command = input("> ").upper()
    if (command == "HELP"):
        print("""
start - to start the car
stop - to stop the car
quit - to exit
        """)
    elif command == "START":
        if is_started:
            print("Car has already started")
        else:
            is_started = True
            print("Car started... Ready to go!")
    elif command == "STOP":
        if not is_started:
            print("Car has already stopped")
        else:
            is_started = False
            print("Car stopped.")
    elif command == "QUIT":
        running = False
    else:
        print("I don't understand that...")


import direct.directbase.DirectStart
from direct.showbase.DirectObject import DirectObject

class Game(DirectObject):
    def __init__(self):
        self.accept('escape', __import__('sys').exit)
        self.parent = loader.loadModel('models/longslug.egg')
        self.parent.reparentTo(render)
        self.child = loader.loadModel('models/longslug.egg')
        self.child.reparentTo(self.parent)
        self.parent.setColor(1, 0, 0, 1)
        self.child.setColor(0, 0, 1, 1)
        self.parent.setPos(-0.5, 5, 0)
        self.child.setPos(1, 0, 0)

Game()
run()


import os
import sys
import pickle
meta = {
    'filename_cifar10': 'batches.meta',
    'filename_cifar100': 'meta',
    'key_cifar10': 'label_names',
    'key_cifar100': 'fine_label_names'
}
def cifar_load_meta(root, base_folder, name='cifar10'):
    path = os.path.join(root, base_folder, meta['filename_%s' % name])
    with open(path, 'rb') as infile:
        if sys.version_info[0] == 2:
            data = pickle.load(infile)
        else:
            data = pickle.load(infile, encoding='latin1')

        classes = data[meta['key_%s' % name]]
    return classes


import pandas as pd
import numpy as np
import re

import bokeh.plotting as bk

from bokeh.palettes import Spectral6
from bokeh.plotting import ColumnDataSource

from bokeh.models import (HoverTool,
                          BoxZoomTool,
                          ResetTool,
                          PanTool,
                          WheelZoomTool,
                          Slider,
                          CustomJS,
                          Range1d,
                          Circle,
                          Text,
                          NumeralTickFormatter)

from bokeh.io import vform

gdp_df = pd.read_csv('data/gapminder/'
                     'indicator_gapminder_gdp_per_capita_ppp.csv',
                     thousands=',')

gdp_df.rename(columns={'GDP per capita': 'Entity'},
              inplace=True)

min_gdp = gdp_df.iloc[:,1:].min().min()
max_gdp = gdp_df.iloc[:,1:].max().max()

geographical_regions_df = pd.read_csv('data/gapminder/'
                                      'geographical_regions.csv')

all_df = pd.merge(gdp_df,
                  geographical_regions_df[['Entity', 'Group']],
                  on='Entity')

lex_df = pd.read_csv('data/gapminder/'
                     'indicator_gapminder_life_expectancy_at_birth.csv')

lex_df.rename(columns={'Life expectancy with projections. Yellow is IHME':
                       'Entity'},
              inplace=True)

min_lex = lex_df.iloc[:,1:].min().min()
max_lex = lex_df.iloc[:,1:].max().max()

all_df = pd.merge(all_df,
                  lex_df,
                  on='Entity',
                  suffixes=("_gdp", "_lex"))

pop_df = pd.read_csv('data/gapminder/'
                     'indicator_gapminder_population.csv',
                     thousands=',')

pop_df.rename(columns={'Total population':
                       'Entity'},
             inplace=True)

all_df = pd.merge(all_df,
                  pop_df,
                  on='Entity')

for column in all_df.columns:
    col_match = re.match(r'(\d+)(_(.+))?', column)
    if col_match:
        if col_match.lastindex > 1:
            new_name = col_match.group(3) + '_' + col_match.group(1)
            all_df.rename(columns={column: new_name},
                          inplace=True)
        else:
            new_name = 'pop_' + col_match.group(1)
            all_df.rename(columns={column: new_name},
                          inplace=True)
            sizes = 0.003 * np.sqrt(all_df[new_name] / np.pi)
            all_df['size_' + col_match.group(1)] = sizes

groups = geographical_regions_df['Group'].drop_duplicates()
group_map = {v: k for k, v in enumerate(groups)}
all_df['Group Code'] = all_df['Group'].map(group_map)

all_df['x'] = all_df['gdp_2015']
all_df['y'] = all_df['lex_2015']
all_df['pop'] = all_df['pop_2015']

all_df['size'] = all_df['size_2015']

colors = all_df['Group Code'].map(lambda x: Spectral6[x])

source = ColumnDataSource(all_df)

hover = HoverTool(tooltips=[
        ("Country Name", "@Entity"),
        ("Population", "@pop")
        ]
    )

min_x = 100 * (min_gdp // 100)
max_x = 1000 * (max_gdp // 1000) + 1000

min_y = 10 * (min_lex // 10)
max_y = 100 * (max_lex // 100) + 100

tools = [
    hover,
    WheelZoomTool(),
    PanTool(),
    BoxZoomTool(),
    ResetTool(),
]

p = bk.Figure(tools=tools,
              x_axis_type="log",
              x_axis_label="Income per person "
              "(GDP/capita, PPP$ inflation-adjusted)",
              y_axis_label="Life expectancy (years)",
              x_range=Range1d(min_x, max_x),
              y_range=Range1d(min_y, max_y),
              plot_width=700)

p.xaxis[0].formatter = NumeralTickFormatter(format='0a')

text_x = 15000
text_y = 20

for i, group in enumerate(groups):
    p.add_glyph(Text(x=text_x,
                     y=text_y,
                     text=[group],
                     text_font_size='10pt',
                     text_color='#666666'))
    p.add_glyph(Circle(x=text_x - 2000,
                       y=text_y + 1,
                       fill_color=Spectral6[i],
                       size=10,
                       line_color=None, fill_alpha=0.8))
    text_y = text_y - 3

callback = CustomJS(args=dict(source=source), code="""
        var data = source.get('data');
        var v = cb_obj.get('value')
        x = data['gdp_' + v];
        y = data['lex_' + v];
        data['x'] = x;
        data['y'] = y;
        data['size'] = data['size_' + v];
        data['pop'] = data['pop_' + v];
        source.trigger('change');
    """)

p.scatter('x',
          'y',
          source=source,
          size='size',
          fill_color=colors,
          fill_alpha=0.8)

slider = Slider(start=1800, end=2015, value=2015, step=1, title="Year",
                callback=callback)

layout = vform(p, slider)

bk.output_file("gdp_lex_gapminder.html")

bk.show(layout)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import tagging.fields

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Bookmark',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=100, null=True, blank=True)),
                ('slug', models.SlugField(unique=True, verbose_name='slug')),
                ('url', models.URLField(unique=True, verbose_name='url')),
                ('description', models.TextField(verbose_name='description')),
                ('extended', models.TextField(verbose_name='extended', blank=True)),
                ('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),
                ('modified', models.DateTimeField(auto_now=True, verbose_name='modified')),
                ('tags', tagging.fields.TagField(max_length=255, blank=True)),
            ],
            options={
                'db_table': 'bookmarks',
                'verbose_name': 'bookmark',
                'verbose_name_plural': 'bookmarks',
            },
        ),
    ]


# -*- coding: utf-8 -*-
"""
Created on Fri Sep  4 11:41:26 2020

@author: QuYue
"""

#%%
import record
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

#%%
file_name = ['./result/e4_2-2020-09-04_16-33-41.pkl']
#%%
class PARM:
    def __init__(self):
        self.dataset_ID = 1

def mean_std(vector, dim=None):
    vector = np.array(vector)
    if dim == None:
        m = vector.mean()
        n = vector.std()
    else:
        m = vector.mean(dim)
        n = vector.std(dim)
    return m, n

num = len(file_name)
Parm = []
for name in file_name:
    Parm.append(record.read(name))

#%%
for parm in Parm:
    print(parm.random_seed)

#%%
length = len(Parm[0].result['SoloNet'])
Acc = np.empty([length, num])
Total = np.empty([length, num])
for i in range(num):
    parm = Parm[i]
    for j in range(length):
        Acc[j, i] = parm.result['SoloNet'][j]['Acc']
        Total[j, i] = parm.result['SoloNet'][j]['TotalAcc']

print(f"SoloNetAcc: {mean_std(Acc, 1)}")
print(f"SoloNetTotal: {mean_std(Total, 1)}")

# %%
Aver = np.empty([num])
AverAcc = np.empty([num, length])
for i in range(num):
    parm = Parm[i]
    Aver[i] = parm.result['FusionNet']['AverFusion']['TotalAcc']
    for j in range(length):
        AverAcc[i,j] = parm.result['FusionNet']['AverFusion']['Acc'][j]

print(f"AverAcc: {mean_std(AverAcc, 0)}")
print(f"AverTotal: {mean_std(Aver)}")

# %%
pinv = np.empty([num])
pinvAcc = np.empty([num, length])
for i in range(num):
    parm = Parm[i]
    pinv[i] = parm.result['FusionNet']['PinvFusion']['TotalAcc']
    for j in range(length):
        pinvAcc[i,j] = parm.result['FusionNet']['PinvFusion']['Acc'][j]

print(f"pinvAcc: {mean_std(pinvAcc, 0)}")
print(f"pinvTotal: {mean_std(pinv)}")

# %%
pinv_w = np.empty([num])
pinv_wAcc = np.empty([num, length])
for i in range(num):
    parm = Parm[i]
    pinv_w[i] = parm.result['FusionNet']['PinvFusion_W']['TotalAcc']
    for j in range(length):
        pinv_wAcc[i,j] = parm.result['FusionNet']['PinvFusion_W']['Acc'][j]

print(f"pinvwAcc: {mean_std(pinv_wAcc, 0)}")
print(f"pinvwTotal: {mean_std(pinv_w)}")

# %%
pinv_AF = np.empty([num])
pinv_AFAcc = np.empty([num, length])
for i in range(num):
    parm = Parm[i]
    pinv_AF[i] = parm.result['FusionNet']['PinvFusion+AF']['TotalAcc']
    for j in range(length):
        pinv_AFAcc[i,j] = parm.result['FusionNet']['PinvFusion+AF']['Acc'][j]

print(f"pinvAFAcc: {mean_std(pinv_AFAcc, 0)}")
print(f"pinvAFTotal: {mean_std(pinv_AF)}")

# %%
pinv_MAN = np.empty([num])
pinv_MANAcc = np.empty([num, length])
for i in range(num):
    parm = Parm[i]
    pinv_MAN[i] = parm.result['FusionNet']['PinvFusion+MAN']['TotalAcc']
    for j in range(length):
        pinv_MANAcc[i,j] = parm.result['FusionNet']['PinvFusion+MAN']['Acc'][j]

print(f"pinvMANAcc: {mean_std(pinv_MANAcc, 0)}")
print(f"pinvMANTotal: {mean_std(pinv_MAN)}")

# %%
Origin = np.empty([num])
for i in range(num):
    parm = Parm[i]
    Origin[i] = max(parm.result['Origin']['origin'])

print(f"Origin: {mean_std(Origin)}")

# %%
FineTune = np.empty([num])
for i in range(num):
    parm = Parm[i]
    FineTune[i] = max(parm.result['FusionNet']['FusionFineTune'])

print(f"FineTune: {mean_std(FineTune)}")

#%%
MLKD = np.empty([num])
for i in range(num):
    parm = Parm[i]
    MLKD[i] = max(parm.result['FusionNet']['FusionMLKD'])

print(f"MLKD: {mean_std(MLKD)}")

#%%
plt.figure(1)
plt.plot(Parm[0].time['Origin'], Parm[0].result['Origin']['origin'])
plt.plot(Parm[0].time['FusionFineTune'], Parm[0].result['FusionNet']['FusionFineTune'])
plt.plot(Parm[0].time['FusionMLKD'], Parm[0].result['FusionNet']['FusionMLKD'])
plt.legend(['Normal', 'FineTune', 'MLKD'])
plt.grid('on')
plt.show()

#%%
def counter(acc):
    if int(acc//0.1)==9:
        return 9 + int((acc-0.9)//0.01)
    else:
        return int(acc//0.1)

def speed(acc_list):
    acc = [counter(i) for i in acc_list]
    acc = np.array(acc)
    return acc

d = speed(Parm[0].result['Origin']['origin'])
d = pd.Series(d).value_counts()
d1 = dict(d)
print(d)

d = speed(Parm[0].result['FusionNet']['FusionFineTune'])
d = pd.Series(d).value_counts()
d2 = dict(d)
print(d)

d = speed(Parm[0].result['FusionNet']['FusionMLKD'])
d = pd.Series(d).value_counts()
d3 = dict(d)
print(d)

#%%
h = {}
for i in range(1,19):
    a = []
    if i in d1:
        a.append(d1[i])
    else:
        a.append(0)
    if i in d2:
        a.append(d2[i])
    else:
        a.append(0)
    if i in d3:
        a.append(d3[i])
    else:
        a.append(0)
    h[i] = a

#%%
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2.- 0.2, 1.03*height, '%s' % int(height))
name_list = ['10-20', '20-30', '30-40', '40-50', '50-60', '60-70', '70-80', '80-90', '90-91', '91-92','92-93','93-94','94-95','95-96','96-97','97-98','98-99','99-100']
num_list = [h[i][0] for i in range(1, 19)]
num_list1 = [h[i][1] for i in range(1, 19)]
num_list2 = [h[i][2] for i in range(1, 19)]
plt.figure(2)
plt.grid('on')
x = list(range(len(name_list)))
total_width, n = 0.8, 3
width = total_width / n

plt.bar(x, num_list, width=width, label='Normal', fc='b')

for i in range(len(x)):
    x[i] += 2*width
plt.bar(x, num_list2, width=width, label='MLKD', tick_label=name_list, fc='r')

for i in range(len(x)):
    x[i] -= width
plt.bar(x, num_list2, width=width, label='FineTune', tick_label=name_list, fc='g')
plt.legend()
plt.xlabel('Accuray')
plt.ylabel()
plt.show()


from imports import *
sudo = 186513800
maintenance = True
Chatsuporte = "-1001097459691"
TOKEN = ''
api = telepot.Bot(TOKEN)
bot = api.getMe()
bot_name = bot['first_name']
bot_username = '@{}'.format(bot['username'])
bot_id = str(bot['id'])


from nose.tools import eq_
import libs.aws as aws_lib

def test_get_object_keys():
    """should return all objects in all buckets"""

    # class MockObject(object):
    #     def __init__(self, key, value):
    #         self.key = key
    #         self.value = value

    class MockObjects(object):
        def __init__(self, values):
            self.values = values

        def all(self):
            return self.values

    class MockBucket(object):
        def __init__(self, values):
            self.objects = MockObjects(values)

    _buckets = [
        MockBucket([
            {'key': 'A', 'value': 1},
            {'key': 'B', 'value': 2},
        ]),
        MockBucket([
            {'key': 'C', 'value': 3},
        ]),
    ]

    def extract_objects(r, buckets):
        return buckets.objects.all()

    r = aws_lib.get_object_keys(extract_objects)(_buckets)

    eq_(r[0], 'A')
    eq_(r[1], 'B')
    eq_(r[2], 'C')


from os.path import join
import xarray as xr
from ninolearn.private import plotdir
from ninolearn.pathes import processeddir
import matplotlib.pyplot as plt
from ninolearn.IO.read_processed import data_reader
from ninolearn.plot.prediction import plot_prediction

plt.close('all')

start = '2003-01'
end = '2017-12'
reader = data_reader(startdate=start, enddate=end)
oni = reader.read_csv('oni')

data = xr.open_dataset(join(processeddir, f'dem_review_supersimple_forecasts_with_std_estimated.nc'))

fig, axs = plt.subplots(3, figsize=(9,7))

lead_arr = [0, 3, 6]

for i in range(len(lead_arr)):
    lead = lead_arr[i]
    lead_DE = lead//3

    UU_DE_mean = data['mean'].loc[start:end][:,lead_DE]
    UU_DE_std = data['std'].loc[start:end][:,lead_DE]

    plot_prediction(UU_DE_mean.target_season.values, UU_DE_mean.values,std=UU_DE_std.values,
                    alpha=0.4, ax=axs[i])

    NASA_GMAO = reader.read_other_forecasts('NASA GMAO', lead)
    NCEP_CFS = reader.read_other_forecasts('NCEP CFS', lead)
    JMA = reader.read_other_forecasts('JMA', lead)
    SCRIPPS =  reader.read_other_forecasts('SCRIPPS', lead)
    ECMWF = reader.read_other_forecasts('ECMWF', lead)
    KMA_SNU = reader.read_other_forecasts('KMA SNU', lead)
    UBC_NNET = reader.read_other_forecasts('UBC NNET', lead)
    UCLA_TCD = reader.read_other_forecasts('UCLA-TCD', lead)
    CPC_MRKOV = reader.read_other_forecasts('CPC MRKOV', lead)
    CPC_CA = reader.read_other_forecasts('CPC CA', lead)
    CPC_CCA = reader.read_other_forecasts('CPC CCA', lead)

    target_season = NASA_GMAO.target_season

    #%%
    alpha = 1
    axs[i].plot(target_season, UBC_NNET, alpha=alpha, label='UBC NNET', ls='--')
    axs[i].plot(target_season, UCLA_TCD, alpha=alpha, label='UCLA-TCD', ls='--')
    axs[i].plot(target_season, CPC_MRKOV, alpha=alpha, label='CPC MRKOV', ls='--')
    axs[i].plot(target_season, CPC_CA, alpha=alpha, label='CPC CA', ls='--')
    axs[i].plot(target_season, CPC_CA, alpha=alpha, label='CPC CCA', ls='--')

    axs[i].plot(target_season, NASA_GMAO, alpha=alpha, label='NASA GMAO')
    axs[i].plot(target_season, NCEP_CFS, alpha=alpha, label='NCEP CFS')
    axs[i].plot(target_season, JMA, alpha=alpha, label='JMA')
    axs[i].plot(target_season, SCRIPPS, alpha=alpha, label='SCRIPPS')
    axs[i].plot(target_season, ECMWF, alpha=alpha, label='ECMWF')
    axs[i].plot(target_season, KMA_SNU, alpha=alpha, label='KMA SNU')

    axs[i].plot(oni.index, oni, c='r', label='ONI', lw=2)

    axs[i].set_xlim(UU_DE_mean.target_season.values[0], UU_DE_mean.target_season.values[-1])
    axs[i].set_ylim(-3,3)

    if i==1:
        axs[i].legend(loc='center left', bbox_to_anchor=(1, 0.5))

    if i==2:
        axs[i].set_xlabel('Time [Year]')

    axs[i].axhspan(-0.5, -6, facecolor='blue',  alpha=0.1,zorder=0)
    axs[i].axhspan(0.5, 6, facecolor='red', alpha=0.1,zorder=0)

    #axs[i].set_title(f"Lead time: {lead} months")
    axs[i].grid()

    axs[i].set_ylabel('ONI [K]')

    axs[i].text(oni.index[4], 2.2, f'{lead}-months', weight='bold', size=10,
        bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 7})
    #plt.tight_layout()
    plt.subplots_adjust(top=0.945,
                        bottom=0.095,
                        left=0.09,
                        right=0.795,
                        hspace=0.2,
                        wspace=0.2)

    #plt.savefig(join(plotdir, f'compare_prediction_lead{lead}.pdf'))


# write a Python program that accept a word from the user and reverse it.

def revers_word(string):
    new_word = ""
    for i in range(len(string) -1, -1, -1):
        new_word = new_word + string[i]
    print(new_word)

# test
string = input("Podaj słowo do odwórócenia: ")

revers_word(string)


import logging

from tornado import web

from .core import RequestHandler, MyApp, Resources

logger = logging.getLogger(__name__)

class Info(RequestHandler):
    def get(self):
        resp = {'ncores': self.server.ncores,
                'nkeys': len(self.server.data),
                'status': self.server.status}
        self.write(resp)

def HTTPWorker(worker):
    application = MyApp(web.Application([
        (r'/info.json', Info, {'server': worker}),
        (r'/resources.json', Resources, {'server': worker}),
        ]))
    return application


from . import SnowComponent
import pandas as pd
import os

def simulation(datafile, vardata, params, init):
    rep = os.path.dirname(datafile)
    out = os.path.join(rep, 'output.csv')
    df = pd.read_csv(datafile, sep = ";")

    # inputs values
    t_jul = df[vardata.loc[vardata["Variables"]=="jul","Data columns"].iloc[0]].to_list()
    t_precip = df[vardata.loc[vardata["Variables"]=="precip","Data columns"].iloc[0]].to_list()
    t_tmax = df[vardata.loc[vardata["Variables"]=="tmax","Data columns"].iloc[0]].to_list()
    t_tmin = df[vardata.loc[vardata["Variables"]=="tmin","Data columns"].iloc[0]].to_list()

    #parameters
    Tmf = params.loc[params["name"]=="Tmf", "value"].iloc[0]
    SWrf = params.loc[params["name"]=="SWrf", "value"].iloc[0]
    tsmax = params.loc[params["name"]=="tsmax", "value"].iloc[0]
    DKmax = params.loc[params["name"]=="DKmax", "value"].iloc[0]
    trmax = params.loc[params["name"]=="trmax", "value"].iloc[0]
    rho = params.loc[params["name"]=="rho", "value"].iloc[0]
    Kmin = params.loc[params["name"]=="Kmin", "value"].iloc[0]
    Pns = params.loc[params["name"]=="Pns", "value"].iloc[0]
    tmaxseuil = params.loc[params["name"]=="tmaxseuil", "value"].iloc[0]
    tminseuil = params.loc[params["name"]=="tminseuil", "value"].iloc[0]
    prof = params.loc[params["name"]=="prof", "value"].iloc[0]
    E = params.loc[params["name"]=="E", "value"].iloc[0]

    #initialization
    ps_t1 = init.loc[init["name"]=="ps_t1", "value"].iloc[0]
    Sdepth_t1 = init.loc[init["name"]=="Sdepth_t1", "value"].iloc[0]
    Sdry_t1 = init.loc[init["name"]=="Sdry_t1", "value"].iloc[0]
    Swet_t1 = init.loc[init["name"]=="Swet_t1", "value"].iloc[0]

    #outputs
    output_names = ["M","tminrec","Sdepth","Sdry","Snowaccu","ps","Swet","tavg","Mrf","tmaxrec","preciprec","Snowmelt","Sdepth_cm"]

    df_out = pd.DataFrame(columns = output_names)
    for i in range(0,len(df.index)-1):
        jul = t_jul[i]
        precip = t_precip[i]
        tmax = t_tmax[i]
        tmin = t_tmin[i]
        M,tminrec,Sdepth,Sdry,Snowaccu,ps,Swet,tavg,Mrf,tmaxrec,preciprec,Snowmelt,Sdepth_cm= SnowComponent.model_snow(jul,Tmf,SWrf,tsmax,precip,DKmax,trmax,tmax,ps_t1,Sdepth_t1,Sdry_t1,Swet_t1,rho,Kmin,Pns,tmaxseuil,tminseuil,tmin,prof,E)

        ps_t1 = ps
        Sdepth_t1 = Sdepth
        Sdry_t1 = Sdry
        Swet_t1 = Swet
        df_out.loc[i] = [M,tminrec,Sdepth,Sdry,Snowaccu,ps,Swet,tavg,Mrf,tmaxrec,preciprec,Snowmelt,Sdepth_cm]
    df_out.insert(0, 'date', pd.to_datetime(df.year*10000 + df.month*100 + df.day, format='%Y%m%d'), True)
    df_out.set_index("date", inplace=True)
    df_out.to_csv(out, sep=";")
    return df_out


'''
Manages the translation system.

Last update: 26/04/19
'''
# Dependancies
import gettext, asyncio, time

from data.queries.select.user_info import User_language

async def Translator(client, ctx):
    '''
    This function returns the right translated strings in function of the user's language

    Return: str
    '''
    caller = ctx.message.author
    caller_lang = await User_language(client, caller)
    if(type(caller_lang) == str):
        caller_lang = caller_lang.upper()
    else:
        error_time = time.strftime('%d/%m/%y - %H:%M', time.gmtime())
        print('{} - Error in cogs.utils.translation.translation.Translator : The \'caller_lang\' type is uncorrect'.format(error_time))
        return

    # Get the translations
    if(caller_lang == 'FR'):
        # French translation
        french_t = gettext.translation('fr', localedir= 'locale', languages= ['fr'])
        french_t.install()

        # The '_' will be the function used to translate different strings
        _ = french_t.gettext

        return(_)

    # If the language is the default language ('EN') we don't translate anything
    else:
        gettext.install('locale/pantheist_translation')

        _ = gettext.gettext

        return(_)


#!python3
#Download reddit links to file

import bs4,requests, os
from bs4 import BeautifulSoup

pagefile= requests.get('https://reddit.com')
pagefile.raise_for_status()
soup = BeautifulSoup(pagefile.text,'html.parser')
sall = soup.select('p  a')

file= open('redditLinks.txt','a')

for href in sall:
    file.write(str(href))

file.close()