import numpy as np

def split_data(data, batch_sizes):

    if type != np.ndarray:
        data = np.array(data)

    total_batches = sum(batch_sizes)

    size_of_batch = data.shape[0] // total_batches
    amount_to_remove = data.shape[0] -  (total_batches * size_of_batch)

    if amount_to_remove > 0:
        data = data[ : -amount_to_remove]

    split_data = np.split(data, total_batches)

    res = []
    splits_indices = np.cumsum([0] + batch_sizes)

    for i in range(len(splits_indices)-1):
        res.append( np.stack(split_data[splits_indices[i] : splits_indices[i+1]]) )

    if len(res) == 1:
        return res[0] # prevents extra dimension from being prepended to return array
    else:
        return res

def encode_mini_batches(X, char_to_ind):
    func = np.vectorize(lambda x: char_to_ind[x])
    return func(X)

def clean_doc(file):

    f = open(file)
    s = f.read()

    s = s.lower()
    s = s.replace('\n','')
    s = s.replace('  ',' ')
    s = s.replace('-',' ')
    s = s.replace('â','a')
    s = s.replace('é','e')
    s = s.replace('/',' ')
    s = s.replace(';',':')
    s = s.replace('—',' ')

    s = s.replace('\t',' ')
    s = s.replace('^',' ')
    s = s.replace('_',' ')

    s = s.replace('•','.')
    s = s.replace('ü','u')
    s = s.replace('}',')')
    s = s.replace('_',' ')

    clean_text = []

    for char in s:
        clean_text.append(char)

    words_to_ind = {}
    ind_to_words = []

    ind = 0

    for word in clean_text:
        if word not in words_to_ind:
            words_to_ind[word] = ind
            ind_to_words.append(word)

            ind += 1

    clean_text = np.array(clean_text)

    return clean_text, words_to_ind, ind_to_words


from sys import stdin

def feliz(n):
    for j in range(8):
        con = 0
        for h in str(n):
            a=int(h)**2
            con+=int(a)
        print(con)
        n=con
        if con == 1: return 1
    if con != 1: return 0

def main():
    n=int(stdin.readline().strip())
    for i in range(n):
        a=int(stdin.readline().strip())
        z=feliz(a)
        if z == 1:
            print("Case #"+str(i+1)+":",a,"is a Happy number.")
        else:
            print("Case #"+str(i+1)+":",a,"is an Unhappy number.")
main()


#!/usr/bin/python
# Copyright (C) 2010 McAfee, Inc.  All rights reserved.
# TestcaseID: 17441
# TestcaseDescription:  AppPro behaviour test when a binary added to appPro rule, gets changed

import sys
import logging
import shutil
import os
import subprocess
import time

# Add common folder into the sys path for module importing
sys.path.append("../Common")
import commonFns
import CommonAppProFns
# Import CommonTest module into current namespace
from CommonTest import *

# Get testcase name
testcaseName = sys.argv[0][:-3]

class TestCase(BaseTest):
    # Files which we will use as our test binaries
    _binary_1=os.getcwd() + "/data/SampleApplications/UDPServer"
    _binary_2=os.getcwd() + "/data/SampleApplications/UDPClient"
    # Copies of Files which we will use as our test binaries
    _binary_1_copy=_binary_1 + "_copy"
    _binary_2_copy=_binary_2 + "_copy"

    def __init__(self):
        logging.info("TestcaseID : 17441")
        logging.info("Description : AppPro behaviour test when a binary added to appPro rule, gets changed")

    def init(self):
        logging.info("Initializing testcase %s" % testcaseName)
        # Call the common initialization check
        _retval = BaseTest.init(self)
        if _retval != 0 :
            return _retval
        try:
            shutil.copy(self._binary_1,self._binary_1_copy)
            shutil.copy(self._binary_2,self._binary_2_copy)
        except:
            logging.error("Unable to copy the binaries")
            return 1

        # Install the test tool
        logging.debug("Installing appProtTestTool")
        if CommonAppProFns.installAppProtTestTool() != True :
            logging.error("Failed to install appProtTestTool")
            return 1
        CommonAppProFns.resetAppProtToDefaults()
        return 0

    def execute(self):
        logging.info("Executing testcase %s" % testcaseName)
        # Set exclusion for aptt
        if CommonAppProFns.setAppProExclusions( [ os.getcwd() + "/data/aptt" ]) != True:
            logging.error("Unable to add aptt exclusion")
            return 1
        logging.debug("Added exclusion for aptt")

        # Set unknown app action to block
        if CommonAppProFns.setUnknownAppAction(2) != True:
            logging.error("Unable to set unknown apps to block. Can't proceed")
            return 1
        logging.debug("set unknown app action to deny")

        # Lets Add a rule for first binary
        _rule1 = dict()
        _rule1["AppPath"]= self._binary_1_copy
        _rule1["ExecAllowed"]="1"
        _rule1["Enabled"]="1"
        _rule1["NwAction"]="1"
        if CommonAppProFns.addAppProtRule(_rule1) != CommonAppProFns.SUCCESS:
            logging.error("Addition of allow rule failed")
            return 1

        logging.debug("Added rule for binary one")

        # Lets Add a rule for second binary
        _rule2 = dict()
        _rule2["AppPath"]= self._binary_2_copy
        _rule2["ExecAllowed"]="0"
        _rule2["Enabled"]="1"
        _rule2["NwAction"]="1"
        if CommonAppProFns.addAppProtRule(_rule2) != CommonAppProFns.SUCCESS:
            logging.error("Addition of deny rule failed")
            return 1
        logging.debug("Added rule for binary two")

        # Mv second binary to first
        try:
            shutil.move(self._binary_2_copy,self._binary_1_copy)
            logging.debug("Moving " + self._binary_2_copy + " to " + self._binary_1_copy + " succeeded")
        except:
            logging.error("Moving " + self._binary_2_copy + " to " + self._binary_1_copy + " failed")
            return 1

        time.sleep(5)
        try:
            retval = subprocess.call( [ self._binary_1_copy,
                                    "172.16.193.1",
                                    "500",
                                    "Message" ])
            logging.info("Invocation of binary succeeded. This is not good")
            return 1
        except:
            logging.info("Invocation of binary failed as expected")
        return 0

    def verify(self):
        logging.info("Verifying testcase %s" % testcaseName)
        if commonFns.searchProductLog("Denied " +
                                      self._binary_1_copy +
                                      " from executing because  it matched with profile rule for") != True:
            logging.error("Expected error message not found in the product log")
            return 1
        logging.info("Expected error message found in the logs")
        return 0

    def cleanup(self):
        logging.info("Performing cleanup for testcase %s" % testcaseName)
        # Copy logs and clean them.
        foundCrash = 0
        foundCrash = commonFns.copyLogs()
        CommonAppProFns.resetAppProtToDefaults()
        try:
            os.remove(self._binary_1_copy)
            os.remove(self._binary_2_copy)
        except:
            pass
        commonFns.cleanLogs()

        if foundCrash != 0:
            logging.error("copylogs returned failure status.  Maybe a product crash")

        return foundCrash

    def __del__(self):
        pass

if __name__ == "__main__":
    # Setup testcase
    setupTestcase(sys.argv)

    testObj = TestCase()

    # Perform testcase operations
    retVal = testObj.init()

    # Perform execute once initialization succeeds...
    if(retVal == 0):
        retVal = testObj.execute()

    # Once execution succeeds, perform verification...
    if(retVal == 0):
        retVal = testObj.verify()

    # Perform testcase cleanup
    retVal += testObj.cleanup()

    if(retVal == 0):
        resultString = "PASS"
    else:
        resultString = "FAIL"

    logging.info("Result of testcase %s: %s" % (testcaseName, resultString) )
    sys.exit(retVal)

McAfee/src/MSM Automation - 1/Testcases/AppProtection/Appprot_Adhoc_18.py


from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('gallery/',views.gallery,name='gallery'),
    path('photos/<id>/',views.photos,name='photos'),
    path('add/',views.add,name='add'),
    path('new_category/',views.new_category,name='new_category'),
    path('search/',views.searchbar,name='search'),
    path('register/',views.registration,name='register'),
    path('login/',views.login,name='login'),
    path('logout/',views.logout,name='logout'),
    path('theme/',views.theme,name='theme'),
    path('Themeform/',views.ThemeForm,name='Themeform')
]

urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns +=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)


""" Written by VMC
    This tool written for train your own dataset
"""
import tensorflow as tf
import numpy as np
import argparse
import facenet
import os
import math
import pickle
from sklearn.svm import SVC
from sklearn.utils import shuffle

reload_data = False
if reload_data:
    print('Mode: reload data.')
else:
    print('Mode: use saved data.')

def write_embedding_data(X, y, file_name):
    with open(file_name, 'w+') as file:
        for i in range(X.shape[0]):
            for item in X[i, :]:
                file.write(str(item) + ' ')
            file.write(y[i] + '\n')

def main():
    with tf.Graph().as_default():
        with tf.Session() as sess:
            dataset = facenet.get_dataset(args.data_dir)
            paths, labels = facenet.get_image_paths_and_labels(dataset)

            print('Number of classes: %d' % len(dataset))
            print('Number of images: %d' % len(paths))
            print('Number of labels: %d' % len(labels))

            # Load the model
            print('Loading feature extraction model')
            model_path = './model_check_point/20170512-110547.pb'
            facenet.load_model(model_path)

            # Get input and output tensors
            images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
            embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
            phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
            embedding_size = embeddings.get_shape()[1]

            # Run forward pass to calculate embeddings
            batch_size = 40
            image_size = 160

            print('Calculating features for images')
            nrof_images = len(paths)
            nrof_batches_per_epoch = int(math.ceil(1.0*nrof_images / batch_size))
            emb_array = np.zeros((nrof_images, embedding_size))

            if reload_data:
                for i in range(nrof_batches_per_epoch):
                    start_index = i*batch_size
                    end_index = min((i+1)*batch_size, nrof_images)
                    paths_batch = paths[start_index:end_index]
                    images = facenet.load_data(paths_batch, False, False, image_size)
                    feed_dict = { images_placeholder:images, phase_train_placeholder:False }
                    emb_array[start_index:end_index,:] = sess.run(embeddings, feed_dict=feed_dict)
                    print("Epoch #{}. Embedded: {}/{}".format(i, end_index, nrof_images))

                # save data on disk
                with open("emb_array.pkl", 'wb') as pickle_file:
                    pickle.dump(emb_array, pickle_file)
            else:
                # load data from disk
                with open("emb_array.pkl", 'rb') as pickle_file:
                    emb_array = pickle.load(pickle_file)

            # Train classifier
            from sklearn.model_selection import train_test_split
            X_train, X_test, y_train, y_test = train_test_split(emb_array, labels, random_state = 10, test_size=0.3)

            print('Training classifier')
            model = SVC(kernel='linear', probability=True, C=12, gamma='auto')
            model.fit(X_train, y_train)

            # # Create a list of class names
            class_names = [ cls.name.replace('_', ' ') for cls in dataset]
            classifier_filename_exp = os.path.expanduser(args.classifier_filename)

            y_train_pred = model.predict(X_train)
            y_test_pred = model.predict(X_test)

            from sklearn.metrics import accuracy_score
            test_score = accuracy_score(y_test, y_test_pred)
            train_score = accuracy_score(y_train, y_train_pred)

            print("Train accuracy: {}".format(train_score))
            print("Test accuracy: {}".format(test_score))

            # Write into file
            y = []
            for i in labels:
                y.append(class_names[i])

            # write_embedding_data(emb_array, y, 'embedding_Data')

            # Saving classifier model
            with open(classifier_filename_exp, 'wb') as outfile:
                pickle.dump((model, class_names), outfile)
            print('Saved classifier model to file "%s"' % classifier_filename_exp)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--data-dir', type=str, action='store', dest='data_dir',
                    help='data directory')
    parser.add_argument('--cls-name', dest='classifier_filename',
        help='Classifier model file name as a pickle (.pkl) file. ' +
        'For training this is the output and for classification this is an input.')
    args = parser.parse_args()
    main()


from django.core.management.base import BaseCommand
from rooms.models                import RoomType

NAME = 'Room Type'

class Command(BaseCommand):

    help = f'this command create {NAME}!'

    def handle(self, *args, **options):
        roomtypes = (
                    'Hotel Room',
                    'Shared Room',
                    'Private Room',
                    'Entire Room',
                    )

        for f in roomtypes:
            RoomType.objects.create(
                name=f
            )
        self.stdout.write(self.style.SUCCESS(f"성공적으로 {NAME} {len(roomtypes)}개가 생성되었습니다."))


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        temp = head
        length = ans = 0
        while temp:
            length += 1
            temp = temp.next
        for i in range(length):
            ans += 2**(length-i-1) * head.val
            head = head.next
        return ans


from itertools import permutations

def nested_lst(text):
    words = text.split()
    vertical = (words[0] == 'V')
    return [words[0], vertical, set(words[2:])]

def txt_to_dict(file, size):
    lst = []
    new_lst = []
    lib = {}
    for i in file:
        lst = lst + [i]
    for j in lst:
        new_lst = new_lst + [nested_lst(j)]
    for i in range(0, size):
        lib[i] = new_lst[i]
    return lib

def interest(tag1, tag2):
    return min([len(tag1.intersection(tag2)), len(tag1.difference(tag2)), len(tag2.difference(tag1))])

def score(values, combination):
    if (len(combination) == 1):
        return 0
    else:
        return (values.get(tuple([combination[0], combination[1]])) + score(values, combination[1:]))

def form(best_combo):
    if (len(best_combo) == 1):
        return [[best_combo[0]]]
    if (len(best_combo) == 0):
        return []
    else:
        return [[best_combo[0], best_combo[1]]] + form(best_combo[2:])

def ver_to_hor(lib):
    compared = []
    values = {}
    combinations = []
    high = 0
    best_combo = []
    index = []
    for i in lib:
        index = index + [i]
    for i in lib:
        for j in lib:
            if (i != j):
                compared = compared + [{i, j}]
                values[(i, j)] = interest(lib.get(i)[2], lib.get(j)[2])
    for k in list(permutations(index)):
        combinations = combinations + [list(k)]
    for l in combinations:
        if (score(values, l) > high):
            high == score(values, l)
            best_combo = l
    best_combo = form(best_combo)
    new_lib = {}
    for i in best_combo:
        new_lib[tuple(i)] = ['V', True, lib[i[0]][2] | lib[i[1]][2]]
    return new_lib

def main(infile):
    file = open(infile, "r")
    size = int(file.readline())
    index = list(range(0, size))
    lib = txt_to_dict(file.readlines(), size)
    ver_lib = {}
    hor_lib = {}
    for i in lib:
        if (lib.get(i)[1]):
            ver_lib[i] = lib.get(i)
        else:
            hor_lib[i] = lib.get(i)
    for i in hor_lib:
        lib[i] = hor_lib.get(i)
    ver_lib = ver_to_hor(ver_lib)
    for i in ver_lib:
        lib[i] = ver_lib.get(i)
    compared = []
    values = {}
    combinations = []
    high = 0
    best_combo = []
    for i in lib:
        for j in lib:
            if (i != j):
                compared = compared + [{i, j}]
                values[(i, j)] = interest(lib.get(i)[2], lib.get(j)[2])
    for k in list(permutations(index)):
        combinations = combinations + [list(k)]
    for l in combinations:
        if (score(values, l) > high):
            high == score(values, l)
            best_combo = l
    outfile = open(infile[:-4] + '_output.txt', 'w+')
    outfile.write(str(len(best_combo)) + '\n')
    for m in range(0, len(best_combo)):
        outfile.write(str(best_combo[m]) + '\n')
    outfile.close()
    file.close()


#Usar
#python 03_ObjectDetection_SSD_MobileNet_COCO_video.py
#OpenCV DNN - TensorFlow SSD - 1 ~ 91
import numpy as np
import cv2

def prediction(imagem, net, CLASSES, COLORS, confidence_lim):
	(h, w) = imagem.shape[:2]
	blob = cv2.dnn.blobFromImage(imagem, size=(300, 300), swapRB=True, crop=False)
	#blob = cv2.dnn.blobFromImage(cv2.resize(imagem, (300, 300)), 0.007843, (300, 300), 127.5, False)
	#blob = cv2.dnn.blobFromImage(imagem, swapRB=True, crop=False)
	net.setInput(blob)
	detections = net.forward()
	for i in range(0, detections.shape[2]):
		confidence = detections[0, 0, i, 2]
		if confidence > confidence_lim:
			idx = int(detections[0, 0, i, 1]) - 1 #Porque inicia em 1
			box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
			(startX, startY, endX, endY) = box.astype("int")
			label = "{}: {:.2f}%".format(CLASSES[idx], confidence * 100)
			print("[INFO] {}".format(label))
			cv2.rectangle(imagem, (startX, startY), (endX, endY),COLORS[idx], 4)
			y = startY - 15 if startY - 15 > 15 else startY + 15
			cv2.putText(imagem, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, COLORS[idx], 2)
	print('-------------------')
	return imagem

CLASSES = ["person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "street sign", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "hat", "backpack", "umbrella", "shoe", "eye glasses", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "plate", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "mirror", "dining table", "window", "desk", "toilet", "door", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "blender", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush", "hair brush" ]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

net1 = cv2.dnn.readNetFromTensorflow('frozen_inference_graph_ssd_mb_v1_coco.pb', 'ssd_mobilenet_v1_coco_2017_11_17.pbtxt')
net1ppn = cv2.dnn.readNetFromTensorflow('frozen_inference_graph_ssd_mb_v1_ppn_coco.pb', 'ssd_mobilenet_v1_ppn_coco.pbtxt')
net2 = cv2.dnn.readNetFromTensorflow('frozen_inference_graph_ssd_mb_v2_coco.pb', 'ssd_mobilenet_v2_coco_2018_03_29.pbtxt')
net3 = cv2.dnn.readNetFromTensorflow('frozen_inference_graph_ssd_mb_v3_coco.pb', 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt')

use_gpu = 1
if (use_gpu == 1):
    net1.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
    net1.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
    net1ppn.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
    net1ppn.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
    net2.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
    net2.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
    net3.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
    net3.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
confidence_lim = 0.4

cap = cv2.VideoCapture('Bangkok-30945.mp4')
#cap = cv2.VideoCapture(0)

stop = 0
ret=True
while (ret==True):
	if(stop == 0):
		ret, frame = cap.read()
		if (ret == True):
			imagem_net1 = prediction(frame.copy(), net1, CLASSES, COLORS, confidence_lim)
			imagem_net1ppn = prediction(frame.copy(), net1ppn, CLASSES, COLORS, confidence_lim)
			imagem_net2 = prediction(frame.copy(), net2, CLASSES, COLORS, confidence_lim)
			imagem_net3 = prediction(frame.copy(), net3, CLASSES, COLORS, confidence_lim)

			cv2.putText(imagem_net1, 'v1', (int(0.90*imagem_net1.shape[1]),int(0.95*imagem_net1.shape[0])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), cv2.LINE_AA)
			cv2.putText(imagem_net1ppn, 'v1ppn', (int(0.8*imagem_net1ppn.shape[1]),int(0.95*imagem_net1ppn.shape[0])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), cv2.LINE_AA)
			cv2.putText(imagem_net2, 'v2', (int(0.90*imagem_net2.shape[1]),int(0.95*imagem_net2.shape[0])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), cv2.LINE_AA)
			cv2.putText(imagem_net3, 'v3', (int(0.90*imagem_net3.shape[1]),int(0.95*imagem_net3.shape[0])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), cv2.LINE_AA)

			imagem = np.concatenate( ( (np.concatenate((imagem_net1, imagem_net1ppn), axis=1)), (np.concatenate((imagem_net2, imagem_net3), axis=1)) ), axis = 0)
		frame = cv2.resize(imagem, dsize=(0, 0), fx=0.75, fy=0.85)
		cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF
	if key == ord('s'):
		stop = not(stop)
	if key == ord('q'):
		break
cv2.waitKey(0)
cv2.destroyAllWindows()


import random;
namesMale = ["George","Joe","Harold","Bob","Luis","Luke","Jackson","Ethan","Jason","Jack","Noah","Jayden"]; #List of male names to be chosen randomly
namesFemale = ["Clarissa","Maria","Olivia","Emma","Ava","Isabella","Riley","Charlotte","Audrey","Lily","Chloe","Evelyn"]; #List of female names to be chosen randomly
objects = ["bottle caps","stamps","dog treats","apples","coins"]; #List of objects to be given or taken
objectp = ""; #INIT
name1 = ""; #INIT
name2 = ""; #INIT
name1Gender = 0; #INIT
name2Gender = 0; #INIT
number1 = 0; #INIT
number2 = 0; #INIT

def newName():  #Create new name for either subject1 or subject2

        gender = random.randrange(0,2); #Choose random gender for subject1, boy if 0, girl if 1

        if gender == 0:  #Choose name for subject1
            name = namesMale[random.randrange(0,len(namesMale))];
        else:
            name = namesFemale[random.randrange(0,len(namesFemale))];

        return name;

while True:  #Main Loop
    name1 = newName(); #Get name of subject1
    name2 = newName(); #Get name of subject2

    objectp = objects[random.randrange(0,len(objects))];

    number1 = str(random.randrange(8,23)); #Pick a random number
    number2 = str(random.randrange(10,22)); #Pick a random number

    if name1 in namesMale:
        name1Gender = "him";
    else:
        name1Gender = "her";

    if name2 in namesMale:
        name2Gender = "him";
    else:
        name2Gender = "her";

    input(name1 + " had " + number1 + " " + objectp + ". Then " + name2 + " gave " +name1Gender + " " + number2 + " more. How many " + objectp + " does " + name1 + " have now?");


##########################################################################
# Let d(n) be defined as the sum of proper divisors of n
# (numbers less than n which divide evenly into n).
# If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable
# pair and each of a and b are called amicable numbers.
#
# For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110;
# therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
#
# Evaluate the sum of all the amicable numbers under 10000.
##########################################################################

def sumDivisors(x):
    divisor_sum = 0
    for j in range(1, int(x / 2) + 2):
        if (x % j) is 0:
            divisor_sum += j

    return divisor_sum

amicable_number = []
for i in range(1, 10000):
    if i in amicable_number:
        continue

    testing_number = sumDivisors(i)
    if (i == sumDivisors(testing_number)) and (testing_number != i):
        amicable_number.append(i)

        if testing_number not in amicable_number:
            amicable_number.append(testing_number)

sum_of_numbers = sum(amicable_number)
print(sum_of_numbers)

# Solution: 31626


#Sam SKolnekovich
#Assignment3

import sys
import math
from sys import argv

script, filename, Heuristic = argv

txt = open(filename)
rows=0
cols=0
i=0
j=-1
print(txt.read())

adj_nodes=[]
nodepaths=[]
allnodes=[]

class node():
	def __init__(self,node,locationx,locationy,distance,heur1,cost,parentnode,value, adj,totalcost,visited, iscalculated):
		self.node=node
		self.locationx=locationx
		self.locationy=locationy
		self.distance=distance    #initialize objects, distance not used
		self.heur1=heur1			#heuristic
		self.cost=cost				#cost from previous node+cost of current adjacency
		self.parentnode=parentnode
		self.value=value			#0,1=mountain,2=wall
		self.adj=adj				#list of adj vertices, tuple not a node list
		self.totalcost=totalcost	#cost+heur1
		self.visited=False
		self.iscalculated=False   #initialized, not used

def addHeur1(current_node,goal_node,heuristic):  #Heuristic, cmdl needs one of two words
	x=current_node.locationx
	y=current_node.locationy
	a=goal_node.locationx
	b=goal_node.locationy
	if(heuristic=='manhattan'):
		heur=10*(math.fabs(a-x)+math.fabs(y-b))
		return heur
	if(heuristic=="pythagorean"):
		return (10 * math.sqrt(((a-x)**2)+((y-b)**2)))
	else:
		return ("Did not enter correct Heuristic")

def addNode(x,y,value):      #addnodes in loop from matrix, matrix from text file
	value=int (value)
	newnode=node(None,x,y,None,None,None,None,value,None,None,False,False)
	allnodes.append(newnode)

	print(allnodes[-1].locationx,allnodes[-1].locationy, allnodes[-1].value)

def findAdjacent():      #associate a list with the adjacent vertices
	for nodes in allnodes:

		nodes.adj=[(nodes.locationx-1,nodes.locationy-1),(nodes.locationx,nodes.locationy-1),(nodes.locationx+1,nodes.locationy-1),
		(nodes.locationx-1,nodes.locationy), (nodes.locationx+1,nodes.locationy),
		(nodes.locationx-1,nodes.locationy+1),(nodes.locationx,nodes.locationy+1),(nodes.locationx+1,nodes.locationy+1)]
		for i in range(0,2):
			for int1,int2 in nodes.adj:
				if(int1>9 or int1<0):
					nodes.adj.remove((int1,int2))
		for i in range(0,2):
			for int1,int2 in nodes.adj:
				if(int2>7 or int2<0):
					nodes.adj.remove((int1,int2))

def AStar(rows,cols, current_node,parent_node):
	goalFound=False
	goalnode=allnodes[cols-1]
	goalnode.locationx=allnodes[cols-1].locationx
	goalnode.locationy=allnodes[cols-1].locationy
	if (len(nodepaths)==0):
		nodepaths.append(current_node)
		nodepaths[0].cost=0
		nodepaths[0].heur1=addHeur1(nodepaths[0],goalnode,Heuristic)
		nodepaths[0].parentnode=parent_node
		nodepaths[0].parentnode.cost=0
	temp_list=[]
	current_node.parentnode=parent_node
	startnode=allnodes[rows*cols-cols]
	j=0
	for item1,item2 in current_node.adj:
		for item in range(len(allnodes)): 				#assign list of adj vertices to actual nodes
			if(item1==allnodes[item].locationx and item2==allnodes[item].locationy and allnodes[item].value!=2 and allnodes[item].iscalculated==False and allnodes[item].visited==False):
				#print(allnodes[item].locationx,allnodes[item].locationy)
				allnodes[item].heur1=addHeur1(allnodes[item],goalnode,Heuristic)
				if(allnodes[item].value==0):
					if((allnodes[item].locationx-current_node.locationx)**2+(allnodes[item].locationy-current_node.locationy)**2==2):
						allnodes[item].cost=14
					if((allnodes[item].locationx-current_node.locationx)**2+(allnodes[item].locationy-current_node.locationy)**2==1):
						allnodes[item].cost=10
				if(allnodes[item].value==1):
					if((allnodes[item].locationx-current_node.locationx)**2+(allnodes[item].locationy-current_node.locationy)**2==2):
						allnodes[item].cost=24
					if((allnodes[item].locationx-current_node.locationx)**2+(allnodes[item].locationy-current_node.locationy)**2==1):
						allnodes[item].cost=20
												#Above just takes adj nodes and assigns them a cost for a given value
				allnodes[item].parentnode=current_node
				a=int(allnodes[item].cost)

				y=int(allnodes[item].parentnode.cost)

				a=a+y

				i=int(allnodes[item].heur1+a)

				allnodes[item].cost=a
				allnodes[item].totalcost=i
				if(len(adj_nodes)==0):
					adj_nodes.append(allnodes[item])

				else:
					if(allnodes[item] not in adj_nodes):
						adj_nodes.append(allnodes[item])

				allnodes[item].iscalculated=True
				adj_nodes[-1].parentnode=current_node

	for item in range(len(adj_nodes)-1):
		if(adj_nodes[item+1].totalcost>adj_nodes[item].totalcost):
			temp_list.append(adj_nodes[item])
			adj_nodes[item]=adj_nodes[item+1]
			adj_nodes[item+1]=temp_list[-1]
			temp_list.pop()

	if(len(adj_nodes)>=1):
		nodepaths.append(adj_nodes[-1])
		adj_nodes[-1].visited=True
		nodepaths[-1].parentnode=adj_nodes[-1].parentnode
		adj_nodes.pop()
	nodepaths[-1].visited=True

	d=0
	isdone=False
	finalcount=0
	if(goalnode in nodepaths):
		goalFound=True
		for items in range(len(nodepaths)):
			finalcount=finalcount+1
		#if(nodepaths[-1].locationx==goalnode.locationx and nodepaths[-1].locationy==goalnode.locationy):
		print(nodepaths[-1].totalcost)
		while (isdone==False):
			if(nodepaths[-1].locationx==0 and nodepaths[-1].locationy==rows-1):
				isdone=True
			print(nodepaths[-1].locationx, nodepaths[-1].locationy)#nodepaths[-1].totalcost,nodepaths[-1].heur1)
			nodepaths[-1]=nodepaths[-1].parentnode
		print(finalcount)
		'''for item in range(len(nodepaths)):
			for item1,item2 in nodepaths[item].adj:
				if(len(nodepaths)>1):
					if(item1==nodepaths[item].locationx and item2==allnodes[item].locationy):
						print(nodepaths[item].locationx,nodepaths[item].locationy)
						nodepaths[-1]=nodepaths[item]
					else:
						nodepaths.pop()
				if (len(nodepaths)>=0):
					break'''

	if(len(adj_nodes)>0 and goalFound==False):							#Recurse with new current_node
		AStar(rows,cols,nodepaths[-1],nodepaths[-1].parentnode)			#keep track of its parent

with open(filename) as txt:
	for line in txt:
		line=line.strip()
		items=line.split(' ')
		#print(line)
		#print(items)
		for value in items:
			cols=cols+1
		rows=rows+1
rows=rows-1
cols=cols-1
cols=round(cols/rows)
print(rows,cols)
matrix=[[0 for x in range(rows)] for y in range(cols)]

with open(filename) as txt:
	for line in txt:
		line=line.strip()
		items=line.split(' ')
		i=0
		j=j+1
		for value in items:
			if(j<=rows-1 and i<=cols-1):
				matrix[i][j]=value
				addNode(i,j,value)
			i=i+1
# so i=cols and j=rows and i comes before j, even though range is opposite,

findAdjacent()
startnode=allnodes[rows*cols-cols]
dummy=node(None,None,None,None,None,None,None,None,None,None,False,False)
AStar(rows,cols,startnode,dummy)


#
# @lc app=leetcode.cn id=218 lang=python
#
# [218] 天际线问题
#
# https://leetcode-cn.com/problems/the-skyline-problem/description/
#
# algorithms
# Hard (37.40%)
# Total Accepted:    985
# Total Submissions: 2.6K
# Testcase Example:  '[[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]'
#
#
# 城市的天际线是从远处观看该城市中所有建筑物形成的轮廓的外部轮廓。现在，假设您获得了城市风光照片（图A）上显示的所有建筑物的位置和高度，请编写一个程序以输出由这些建筑物形成的天际线（图B）。
#
#
#
# 每个建筑物的几何信息用三元组 [Li，Ri，Hi] 表示，其中 Li 和 Ri 分别是第 i 座建筑物左右边缘的 x 坐标，Hi 是其高度。可以保证 0
# ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX 和 Ri - Li > 0。您可以假设所有建筑物都是在绝对平坦且高度为 0
# 的表面上的完美矩形。
#
# 例如，图A中所有建筑物的尺寸记录为：[ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] 。
#
# 输出是以 [ [x1,y1], [x2, y2], [x3, y3], ... ]
# 格式的“关键点”（图B中的红点）的列表，它们唯一地定义了天际线。关键点是水平线段的左端点。请注意，最右侧建筑物的最后一个关键点仅用于标记天际线的终点，并始终为零高度。此外，任何两个相邻建筑物之间的地面都应被视为天际线轮廓的一部分。
#
# 例如，图B中的天际线应该表示为：[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0]
# ]。
#
# 说明:
#
#
# 任何输入列表中的建筑物数量保证在 [0, 10000] 范围内。
# 输入列表已经按左 x 坐标 Li  进行升序排列。
# 输出列表必须按 x 位排序。
# 输出天际线中不得有连续的相同高度的水平线。例如 [...[2 3], [4 5], [7 5], [11 5], [12 7]...]
# 是不正确的答案；三条高度为 5 的线应该在最终输出中合并为一个：[...[2 3], [4 5], [12 7], ...]
#
#
#
import heapq
class Solution(object):
    def getSkyline(self, buildings):
        """
        :type buildings: List[List[int]]
        :rtype: List[List[int]]
        """
        events = [(l, -h, r) for l, r, h in buildings]
        events.extend([(r, 0, 0) for l, r, h in buildings])
        events.sort()
        # print(events)

        res = [[0, 0]]
        live = [(0, float('inf'))]

        for l,neg_h,r in events:

            while live[0][1] <= l:
                heapq.heappop(live)
            if neg_h:
                heapq.heappush(live, (neg_h, r))
            if res[-1][1] != -live[0][0]:
                res.append([l, -live[0][0]])

        return res[1:]

b = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
print(Solution().getSkyline(b))


from News.views import news
from django.conf.urls import url, include
from Projects.views import projects, projectss, newproject, AddCommentProject, ListMyProjects, donate, donateapi, change, changeapi, deleteproject
from NewsProjects.views import AddNWProject

urlpatterns =[
    url(r'addproject/', newproject, name='addproject'),
    url(r'donate/(?P<pk>\d+)/', donate, name='donate'),
    url(r'donateapi/(?P<pk>\d+)/', donateapi, name='donateapi'),
    url(r'delete/(?P<pk>\d+)/', deleteproject, name='delete'),
    url(r'changeapi/(?P<pk>\d+)/', changeapi, name='changeproject'),
    url(r'changeproject/(?P<pk>\d+)/$', change, name='change'),
    url(r'addcomment/(?P<pk>\d+)/$', AddCommentProject, name='AddCommentProject'),
    url(r'addnews/(?P<pk>\d+)/$', AddNWProject, name='AddNewsProject'),
    url(r'list/$', ListMyProjects, name='ListMyProjects'),
    url(r'(?P<pk>\w+)/$', projectss, name='current'),
    url(r'$', projects, name='projects'),
]


import pandas as pd
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import sqlalchemy as sa

engine = sa.create_engine('mssql+pyodbc://sa:INSERT USERNAME@INSERT SERVER ADDRESS?DRIVER={ODBC Driver 13 for SQL Server}',fast_executemany=True)

# parse stranice
page = requests.get('https://oddscheck.meridianbet.com/prices?leagueID=593')
soup = BeautifulSoup(page.content, 'html.parser')

# selekcija html entiteta (igraca) za skrejpovanje
items = soup.select('ul')
broj_igraca = len(items)

players = []
points = []
teams = []
date = []

# formatiranje meseca u datumu, html vraca mesec u vidu "Jan", "Feb"
def mesec(string):
    return "01" if string == "Jan" else "02" if string == "Feb" else "03" if string == "Mar" else "04" if string == "Apr" else "05" if string == "May" else "06" if string == "Jun" else "07" if string == "Jul" else "08" if string == "Aug" else "09" if string == "Sep" else "10" if string == "Oct" else "11" if string == "Nov" else "12" if string == "Dec" else "Error"

# iteracija kroz svaki entitet (igrac)
for player in items:
    pdata = player.previous.strip().partition('-')[2]
    pdate = player.previous.strip().split(" ")
    # name = pdata.partition(' (')[0]
    players.append(pdata.partition(' (')[0])
    # team = pdata.partition(' (')[2].rstrip(")")
    teams.append(pdata.partition(' (')[2].rstrip(")"))
    limit1 = player.select('li')[0].text.partition(', OU : ')[2].replace(']','')
    limit2 = player.select('li')[1].text.partition(', OU : ')[2].replace(']','')
    limit3 = player.select('li')[2].text.partition(', OU : ')[2].replace(']','')
    limit4 = player.select('li')[3].text.partition(', OU : ')[2].replace(']','')
    limit = float(limit1) + float(limit2) + float(limit3) + float(limit4)
    points.append(limit)
    # date = mesec(pdate[2]) + "-" + pdate[3] + "-" + pdate[6].replace(",", "")
    date.append(mesec(pdate[2]) + "-" + pdate[3] + "-" + pdate[6].replace(",", ""))

    # print(f"{name} ({team}) : {date} : {limit}")

ct = datetime.today()

# output tabele
players_stuff = pd.DataFrame(
    {
        'player': players,
        'team': teams,
        'date': date,
        'points': points,
        'datetime' : ct,
    })

c = engine.connect()

# brisanje postojece tabele na serveru
sql_delete = (f"INSER YOUR SQL CODE FOR TABLE DELETION")
deletion = c.execute(sql_delete)

# upis u tabelu na serveru
players_stuff.to_sql('meridian',con=engine)

# output kao csv fajl
# players_stuff.to_csv(r'meridian.csv')


import unittest
import numpy as np
from nose.tools import assert_equal
from numpy.testing import assert_array_equal
from dfo.evalpoint import EvalPoint
from dfo.dfoproblem import DFOProblem
from dfo.model_uobyqa2 import ModelUOBYQA2
from dfo.uobyqa_interset import UOBYQAInterset

class Sum(DFOProblem):
    def eval(self, x):
        output = np.sum(x.input)
        x.output = output
        return True

class TestModelUOBYQA(unittest.TestCase):
    def setUp(self):
        """
        lpoints corresponds to the interpolation set
        found using UOBYQA's method to compute the
        initial interpolation set.
        """
        x = EvalPoint(np.array([1, 2]))
        pb = Sum(2, 0, x)
        pb.eval(x)
        lpoints = [np.array([1, 2]), np.array([2, 2]), np.array([0, 2]), np.array([1, 3]), np.array([1, 1]),
                   np.array([0, 1])]
        interset = UOBYQAInterset(x, 2, lpoints, [])
        sigmas = [-1, -1]
        rhobeg = 1
        self.mod_pow = ModelUOBYQA2(x, interset, pb, sigmas, rhobeg)

    def test_plagrange(self):
        j = 1
        b = 0
        y = EvalPoint(np.array([-1, 3]))
        pl = self.mod_pow.plagrange(j, b, y, self.mod_pow.x)
        assert_equal(pl, 1)
        b = 1
        pl = self.mod_pow.plagrange(j, b, y, self.mod_pow.x)
        assert_equal(pl, 0)

    def test_temp_poly(self):

        res = [0, 1, 3, 1, 0, -2]
        y = EvalPoint(np.array([-1, 3]))
        temp_pols = self.mod_pow.temp_polynoms(y, self.mod_pow.x)
        assert_array_equal(temp_pols, res)

    def test_plagrange_init(self):

        res = [-6,  1,  5,  1,  2, -2]
        y = EvalPoint(np.array([-1, 3]))
        self.mod_pow.powell_lagrange_init(y, self.mod_pow.x)
        assert_array_equal(self.mod_pow.polynoms, res)

    def test_hq(self):

        F = [5, 8, 4, 10, 2, 1]
        self.mod_pow.hQ(F, 5)

        GQr = np.array([[2, 0], [0, 2]])
        assert_array_equal(self.mod_pow.GQ, GQr)

        gQr = np.array([2, 4])
        assert_array_equal(self.mod_pow.gQ, gQr)

    def test_his(self):

        self.mod_pow.his(self.mod_pow.x)
        gis = [[0, 0], [0.5, 0], [-0.5, 0], [0, 0.5], [0, -0.5], [0, 0]]
        assert_array_equal(self.mod_pow.gis, gis)

    def test_update_model(self):

        y = EvalPoint(np.array([-1, 3]))
        fnew = 10
        qnew = 2
        t = 2
        lnew = [-4.5, 1, 5, -0.5, 0, 0]
        for i in xrange(6):
            self.mod_pow.Gis[i] = np.ones((2, 2))

        self.mod_pow.powell_lagrange_init(y, self.mod_pow.x)
        self.mod_pow.his(self.mod_pow.x)
        self.mod_pow.update_model(t, fnew, lnew, qnew)
        res_polynomials = [-1.5, 0, 1, 1.5, 2, -2]
        assert_array_equal(self.mod_pow.polynoms, res_polynomials)
        res_gis = [np.array([-0.45, 0]), np.array([0.6, 0]), np.array([-0.1, 0]),
                   np.array([-0.05, 0.5]), np.array([0, -0.5]), np.array([0., 0.])]
        assert_array_equal(res_gis, self.mod_pow.gis)


from easyquant import StrategyTemplate
from easyquant.main_engine import MainEngine
# from evan_utils import config_io
import easyquotation
import easytrader

# main_engine = MainEngine('ht', "tmp/ht.json")

class Strategy(StrategyTemplate):
    name = 'zcyTest'

    def __init__(self, user, log_handler, main_engine):
        super().__init__(user, log_handler, main_engine)
        self.user = user
        self.main_engine = main_engine
        self.clock_engine = main_engine.clock_engine
        # 优先使用自定义 log 句柄, 否则使用主引擎日志句柄
        self.log = self.log_handler() or log_handler
        self.init()

    def init(self):
        # 进行相关的初始化操作
        pass

    def strategy(self, event):
        print('\n\n')
        self.log.info('--------------------------------')
        self.config = config_io.file2dict()
        for key in self.config.keys():
            zhisun = float(self.config[key]['zs'])
            zhisunbili = float(self.config[key]['zsbl'])

            zhisun2 = float(self.config[key]['zs2'])
            zhisunbili2 = float(self.config[key]['zsbl2'])

            data = event.data[key]
            now = float(data['now'])
            high = float(data['high'])
            close = float(data['close'])

            if high * zhisunbili > zhisun:
                self.config[key]['zs'] = str(high * zhisunbili)
                self.config[key]['zs2'] = str(high * zhisunbili2)
                config_io.dict2file(self.config)

            baifenbi = (1 - zhisun / (now == 0 and 0.01 or now)) * 100.0
            baifenbi2 = (1 - zhisun2 / (now == 0 and 0.01 or now)) * 100.0

            zhangdiefu = (now / close - 1) * 100

            print(' \033[1;31m%s\033[0m now:%.2f  涨跌幅:%.2f ' % (data['name'], now, zhangdiefu), end = '')
            if now > zhisun:
                print('止损价:%.2f 止损百分比:%.2f%% high:%.2f 默认比例:%.2f%%\n' % (zhisun, baifenbi, high, zhisunbili * 100))
            elif now > zhisun2:
                print('止损价:%.2f \033[1;31m止损百分比:%.2f%% 跌破止损 1\033[0m high:%.2f 默认比例:%.2f%%\n' % (zhisun, baifenbi, high, zhisunbili * 100))
            else:
                print('止损价:%.2f \033[1;31m止损百分比:%.2f%% 跌破止损 2 \033[0m high:%.2f 默认比例:%.2f%%\n' % (zhisun2, baifenbi2, high, zhisunbili2 * 100))


from fitparse import FitFile
import numpy as np

from .models import dataframes

def load(fname):
    """
    This method uses the Python fitparse library to load a FIT file into a WorkoutDataFrame.
    It is tested with a Garmin FIT file but will probably work with other FIT files too.
    Columns names are translated to sweat terminology (e.g. "heart_rate" > "heartrate").

    Parameters
    ----------
    fname : str

    Returns
    -------
    wdf : WorkoutDataFrame
    """

    fitfile = FitFile(fname)

    records = []
    for record in fitfile.get_messages('record'):
        records.append(record.get_values())

    wdf = dataframes.WorkoutDataFrame(records)

    wdf = wdf.rename(columns={'heart_rate': 'heartrate'})

    wdf.index = (wdf.timestamp - wdf.timestamp[0]) / np.timedelta64(1, 's')
    wdf.index = wdf.index.astype(int)

    return wdf


import hashlib
import hmac
import json
import random
import string
import urllib

from . import config

class InstagramIdCodec:
    ENCODING_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

    @staticmethod
    def encode(num, alphabet=ENCODING_CHARS):
        """Covert a numeric value to a shortcode."""
        num = int(num)
        if num == 0:
            return alphabet[0]
        arr = []
        base = len(alphabet)
        while num:
            rem = num % base
            num //= base
            arr.append(alphabet[rem])
        arr.reverse()
        return "".join(arr)

    @staticmethod
    def decode(shortcode, alphabet=ENCODING_CHARS):
        """Covert a shortcode to a numeric value."""
        base = len(alphabet)
        strlen = len(shortcode)
        num = 0
        idx = 0
        for char in shortcode:
            power = strlen - (idx + 1)
            num += alphabet.index(char) * (base ** power)
            idx += 1
        return num

def generate_signature_old(data):
    """Generate signature of POST data for Private API

    Returns
    -------
    str
        e.g. "signed_body=57310ea0133ba7683871e87f86f45756ac4d40c5b454e470d71eff728579a7ac.asdasd&ig_sig_key_version=4"
    """
    body = hmac.new(
        config.IG_SIG_KEY.encode("utf-8"), data.encode("utf-8"), hashlib.sha256
    ).hexdigest()
    return "signed_body={body}.{data}&ig_sig_key_version={sig_key}".format(
        body=body,
        data=urllib.parse.quote(data),
        sig_key=config.SIG_KEY_VERSION,
    )

def generate_signature(data):
    """Generate signature of POST data for Private API

    Returns
    -------
    str
        e.g. "signed_body=SIGNATURE.test"
    """
    return "signed_body=SIGNATURE.{data}".format(
        data=urllib.parse.quote_plus(data)
    )

def json_value(data, *args, default=None):
    cur = data
    for a in args:
        try:
            if isinstance(a, int):
                cur = cur[a]
            else:
                cur = cur.get(a)
        except (IndexError, KeyError, TypeError, AttributeError):
            return default
    return cur

def gen_token(size=10, symbols=False):
    """Gen CSRF or something else token
    """
    chars = string.ascii_letters + string.digits
    if symbols:
        chars += string.punctuation
    return "".join(random.choice(chars) for _ in range(size))

def gen_password(size=10):
    """Gen password
    """
    return gen_token(size)

def dumps(data):
    """Json dumps format as required Instagram
    """
    return json.dumps(data, separators=(",", ":"))

def generate_jazoest(symbols: str) -> str:
    amount = sum(ord(s) for s in symbols)
    return f'2{amount}'


import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import const
import numpy as np

class BiLSTM_Attn(nn.Module):
    def __init__(self,vocab_size,emb_size,lstm_hidden_size,output_size,batch_size,bidirectional, dropout, use_cuda, attention_size, sequence_length):
        """

        :param vocab_size:输入输出的词典
        :param emb_size:
        :param lstm_hidden_size:
        :param output_size:
        :param batch_size:
        :param bidirectional: 是否使用双向LSTM
        :param dropout:
        :param use_cuda:
        :param attention_size:
        :param sequence_length:
        """
        super(BiLSTM_Attn, self).__init__()
        self.batch_size = batch_size
        self.output_size = output_size
        self.hidden_size = lstm_hidden_size
        self.vocab_size = vocab_size
        self.embed_dim = emb_size
        self.bidirectional = bidirectional
        self.dropout = dropout
        self.use_cuda = use_cuda
        self.sequence_length = sequence_length

        self.emb = nn.Embedding(self.vocab_size,self.embed_dim)
        self.emb.weight.data.uniform_(-1.0,1.0)

        self.layer_size = 1

        self.LSTM = nn.LSTM(self.embed_dim,self.hidden_size,self.layer_size,dropout=self.dropout,
                            bidirectional=self.bidirectional)

        if self.bidirectional:
            self.layer_size = self.layer_size*2
        else:
            self.layer_size = self.layer_size

        self.attention_size = attention_size

        if self.use_cuda:
            self.w_omega = Variable(torch.zeros(self.hidden_size * self.layer_size, self.attention_size).cuda())
            self.u_omega = Variable(torch.zeros(self.attention_size).cuda())
        else:
            self.w_omega = Variable(torch.zeros(self.hidden_size * self.layer_size, self.attention_size))
            self.u_omega = Variable(torch.zeros(self.attention_size))

        self.output = nn.Linear(lstm_hidden_size * self.layer_size, output_size)

    def attention_net(self,lstm_output):
        # (squence_length, batch_size, hidden_size*layer_size)
        lstm_output_reshape = torch.Tensor.reshape(lstm_output, shape=[-1, self.hidden_size * self.layer_size])
        # (squence_length*batch_size, hidden_size*layer_size)
        # a起一个tanh加线性层的作用
        att_tanh = torch.tanh(torch.mm(lstm_output_reshape,self.w_omega))
        #(seq_len*batch_size,attention_size)
        attn_hidden_layer = torch.mm(att_tanh,torch.Tensor.reshape(self.u_omega, [-1, 1]))
        # print(attn_hidden_layer.size()) = (squence_length * batch_size, 1)
        # 一维的注意力汇聚
        exps = torch.Tensor.reshape(torch.exp(attn_hidden_layer), [-1, self.sequence_length])
        #print(exps.size()) = (batch_size, squence_length)
        alphas = exps / torch.Tensor.reshape(torch.sum(exps, 1), [-1, 1])
        #print(alphas.size()) = (batch_size, squence_length)
        alphas_reshape = torch.Tensor.reshape(alphas, [-1, self.sequence_length, 1])
        #print(alphas_reshape.size()) = (batch_size, squence_length, 1)
        #print(attn_hidden_layer.size()) = (squence_length * batch_size, 1)
        state = lstm_output.permute(1, 0, 2)
        #print(state.size()) = (batch_size, squence_length, hidden_size*layer_size)

        attn_output = torch.sum(state * alphas_reshape, 1)
        #print(attn_output.size()) = (batch_size, hidden_size*layer_size)

        return attn_output

    def forward(self,inputs,batch_size = None):
        inputs = inputs.long()
        inputs = self.emb(inputs)
        # 因为att——net中需要batch_first
        inputs = inputs.permute(1,0,2)
        if self.use_cuda:
            h_0 = Variable(torch.zeros(self.layer_size, self.batch_size, self.hidden_size).cuda())
            c_0 = Variable(torch.zeros(self.layer_size, self.batch_size, self.hidden_size).cuda())
        else:
            h_0 = Variable(torch.zeros(self.layer_size, self.batch_size, self.hidden_size))
            c_0 = Variable(torch.zeros(self.layer_size, self.batch_size, self.hidden_size))

        lstm_output, (final_hidden_state, final_cell_state) = self.LSTM(inputs, (h_0, c_0))
        attn_output = self.attention_net(lstm_output)
        logits = self.output(attn_output)
        return logits

text classify attention and textCNN/model.py


def drawLine(length=0, direction="v"):
    try:
        length = float(input("Indicati lungimea (ex: 10): "))
    except:
        print("Indicati doar numere intregi!")
    direction = input("Indicati orientarea (ex: v - verticala/ h - orizontala): ")

    if length == int(length) and length != str(length) and direction == "h":
        while length >= 0:
            print("-"*int(length))
            length -= 1
            break
    elif length == int(length) and direction == "v":
            while length >= 0:
                print("|\n"*int(length))
                length -= 1
                break
    else:
        print("Indicati doar numere intregi / alegeti directia orizontala sau verticala")

drawLine()


# -*- coding: utf-8 -*-
"""
author: Jessica Bobeck
date: 1.27.16
purpose: Modeling class Assignment 3
"""

import os
import numpy as np
from matplotlib import pyplot as plt
from numpy import tanh,e

'''Functions'''

def delLess(delta18):
    '''
    From Hanson et al (2013)
    Equation that transfers Delta 18O valuse in to averge sea level

    In:
    delta18 = Delta O18 value (int) that is less than 3.25

    Out
    sl = average sea level in meters
    '''

    sl = 60 - 40*(delta18 - 1.75)
    return sl

def delGreater(delta18):
    '''
    From Hanson et al (2013)
    Equation that transfers Delta 18O valuse in to averge sea level

    In:
    delta18 = Delta O18 value (int) that is greater than 3.25

    Out
    sl = average sea level in meters
    '''

    sl = -120*((delta18 - 3.25)/1.65)
    return sl

def growthCoral(z):
    '''
    '''
    Gm = .010 #mm/yr
    k = .08 #/m
    Io=2100 #uE/m^2/s
    Ik = 200 #uE/m^2/s
    G = Gm*tanh((Io*(e**(-k*z)))/Ik)
    return G

'''Delta O18'''
#Initial Files
del18o = 'Pleist_oxy.txt'

#Importing data into numpy 2d array
del18o = np.loadtxt(del18o,usecols=range(0,3))
del18o = np.transpose(del18o) #transposing the array

#Plotting data
plt.plot(del18o[0], del18o[1])
plt.title('$\delta O^{18}$ for past 2.5 Million Years', fontsize=22)
plt.xlabel('Years (Ka)', fontsize=20)
plt.ylabel(r'$\delta O^{18}$', fontsize=20)
plt.gca().invert_yaxis()
plt.tick_params(axis='both', labelsize=16)
plt.xlim(xmax=del18o[0][-2:-1])#setting limit of x axis to -1 of array
plt.ylim(ymin=5.15)
plt.savefig('deltaO18.png')
plt.cla()

'''Sea Level rise'''
ocean = []
for i in del18o[1]:
    if i <= 3.25:
        sl = delLess(i)
    elif i > 3.25:
        sl = delGreater(i)
    ocean.append(sl)

#Plotting

plt.plot(del18o[0], np.transpose(ocean))
plt.title('Sea Level for past 2.5 Million Years', fontsize=22)
plt.xlabel('Years (Ka)', fontsize=20)
plt.ylabel(r'Sea Level (m)', fontsize=20)
plt.gca().invert_yaxis()
plt.tick_params(axis='both', labelsize=16)
plt.xlim(xmax=del18o[0][-2:-1])#setting limit of x axis to -1 of array
plt.ylim(ymax=10)
plt.axhline(y=0,linestyle='--', color = 'k', linewidth=2)
plt.savefig('sealevel.png')
plt.cla()

'''Coral Grow'''
x = np.linspace(0,100,1486)
zb = -200*x +5 #base of ocean floor
#plt.plot(zb)

c =zb[3] #initial starting coral
cz = 3
z = -200+c #initial starting depth
#plt.plot(cz,c,'ro')

for i in range(len(ocean)):
    #changes in ocean level every thousand years
    depth = ocean[i]-z
    if depth > 0: #If the water is above coral, then grow
        cg =growthCoral(depth)*len(ocean)
        c = c + cg
        cz = cz + cg
        plt.plot(x[i],c, 'ko')
        z = -200+c
plt.title('Coral Growth 2.5 Million Years', fontsize=22)
plt.xlabel('Distance from Shore(m)', fontsize=20)
plt.ylabel(r'Sea Level (m)', fontsize=20)
plt.tick_params(axis='both', labelsize=16)
plt.savefig('coral.png')


'''
Brian Orozco
October 21st, 2015
CS 100 - H01

Homework 14
'''

import turtle

#Spring 2015 Midterm Problems
#Question 1
x = 2
for i in range(3):
    print(x, end = ' ')
    x += i
'''
My answer is c. 2 2 3
Correct answer: c.
'''

#Question 2
noise = 'hullaballoo'
idx = 0
while idx < len(noise):
    let = noise[idx]
    print(let, end='')
    letCount = noise.count(let)
    if idx > 2:
        idx += letCount
    else:
        idx += 1

'''
My answer is c. hulll
Correct Answer: c.
'''

#Question 3
s = 'GimmeASlice'
print(2*s[:5] + s[:])

'''
My answer is a. GimmeGimmeGimmeASlice
Correct answer: a.
'''

#Question 4
noise = 'hullaballoo'
changeCount = 0
for i in range(1, len(noise)):
    if noise[i] != noise[i-1]:
        changeCount += 1
print(changeCount)

'''
My answer is d. 7
Correct answer d.
'''

#Question 5
braveOnes = ['Merida', 'Elinor', 'Macintosh', 'Fergus']
vowels = 'aeiou'
for character in braveOnes:
    for vowel in vowels:
         if vowel in character:
             continue
         else:
             print(character[0], end='')
             break

'''
My answer is d. MEMF
Correct answer d.
'''

#Question 6
pandemics = [['HIV'], '', ['Ebola', 'SARS'], ['polio', 'smallpox']]
print(pandemics[1:3])

'''
My answer is e. none of the above
Correct answer: e
'''

#Skip Question 7

#Question 8
boolExprs = [True and False, not True, True or False, True and not False]
fCount = 0
for expr in boolExprs:
     if expr == False:
         fCount += 1
     else:
         break
print(fCount)

'''
My answer is c. 2
Correct answer: 2
'''

#Question 9
abe = 'no man has a good enough memory to be a successful liar'
def wordLens(t, limit):
     rtn = []
     aList = t.split()
     for s in aList:
         if len(s) > limit:
             return rtn
         rtn.append(len(s))
     return rtn
print(wordLens(abe, 5))

#Question 10
def fileCount(fileName, s):
     inF = open(fileName)
     count = 0
     for line in inF:
         count += line.lower().count(s)
     inF.close()
     return count
w = open('seuss.txt', 'w')
w.write('You have brains in your head' + '\n')
w.write('You have feed in your shoes' + '\n')
w.close()
print(fileCount('seuss.txt', 'you'))

'''
My answer is b. 4
Correct answer b.
'''

#Question 11a
t = turtle.Turtle()
s = turtle.Screen()

def halfSquare(t, length):
    for i in range(2):
        t.forward(length)
        t.left(90)

halfSquare(t, 100)
s.bye()

#11b
t = turtle.Turtle()
s = turtle.Screen()

def halfSquares(t, initial, increment, reps):
    for i in range(reps):
        halfSquare(t, initial)
        initial += increment

halfSquares(t, 25, 15, 10)

#Question 12
def wordCount(inFile,outFile):
    fileLines = inFile.readlines()

    newFile = []
    splitFile = []
    for i in range(len(fileLines)):
        splitFile += fileLines[i].split()
        newFile.append(len(splitFile))

    inFile.close()

    for i in newFile:
        outFile.write(str(i)+'\n')
    outFile.close()

inFile = open('humpty.txt','r')
outFile = open('output.txt','w')
wordCount(inFile,outFile)


#!/apollo/sbin/envroot "$ENVROOT/python3.6/bin/python3.6"

import logging
import re
import argparse
import yaml
from dxd_tools_dev.modules import jukebox
#from com.amazon.jukebox.portreservations import portReservations
from dxd_tools_dev.modules.utils import setup_logging, validate_file_exists

def parse_args():
    parser = argparse.ArgumentParser(description='''Upload Yaml file into Jukebox.\n
    wiki:TBD
    Examples:
    /apollo/env/DXDeploymentTools/bin/yaml_to_jukebox.py --yaml ~/DXYamls/nrt7.yaml
    ''', add_help=True, formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-y', '--yaml', required=True, help='Path to yaml file, e.g. ~/DXYamls/nrt7.yaml')
    parser.add_argument('-e', '--execute', action='store_true', help='Uploads yaml data to Jukebox. If not specified, script runs in dryrun mode')
    return parser.parse_args()

def validate_input(args):
    """
    Validate user input
    :param args:
    :return:
    """
    validate_file_exists(args.yaml)
    if args.execute:
        logging.info('Script running in EXECUTE mode')
    else:
        logging.info('Script running in DRYRUN mode')

def get_link_type(z_hostname):
    """
    Returns L3 link type based on z_hostname
    :param z_hostname:
    :return:
    """
    link_type_table = [
        [r'(vc-(bar|edg|xlc|cir))', 'internal'],
        ['svc', 'ec2'],
        ['br-agg', 'border'],
        ]
    for link in link_type_table:
        if re.search(link[0], z_hostname):
            return link[1]

def add_device(device_dict, region):
    """
    Query Jukebox for device, else create coral device
    :param device_dict: dictionary for one device
    :param region:
    :return coral_device: jukebox coral device object
    """
    vendor = 'Juniper'
    global NEW_DEVICE
    try:  # Might need a better way to find if device exists
        logging.info('Querying Jukebox for {}'.format(device_dict['a_hostname']))
        NEW_DEVICE = False
        coral_device = jukebox.get_device_detail(device_dict['a_hostname'])
        return coral_device
    except TypeError:
        logging.info('{} not found in Jukebox, creating {}'.format(device_dict['a_hostname'], device_dict['a_hostname']))
        NEW_DEVICE = True
        return jukebox.create_coral_device(device_dict['a_hostname'],vendor,device_dict['model'],device_dict['serial'], device_dict['ipv4'],'',region)

def parse_cabling(a_device_dict, coral_device):
    """
    Parse cabling info for A-Device
    :param a_device_dict:
    :param coral_device:
    :return amended_cabling: Jukebox DeviceCabling object
    """
    a_hostname = a_device_dict['a_hostname']
    global ADD_CABLING
    ADD_CABLING = False
    amended_cabling = []
    existing_a_intf = []  # used to make sure new interfaces don't already exist in JB
    if NEW_DEVICE:
        existing_cabling = []
    elif not NEW_DEVICE:
        existing_cabling = coral_device.data.cabling
        for cable in existing_cabling:
            if cable.device_a_name == a_hostname:  # this condition is needed because JB returns mirrored cabling as well
                existing_a_intf.append(cable.device_a_interface_name)

    for z_index in a_device_dict['connections'].keys():
        z_hostname = a_device_dict['connections'][z_index]['z_hostname']
        if 'vc-svc' in z_hostname and a_device_dict['edge_rack'] == 'dori-s':  # skips cabling for vc-svc in vegemite racks
            continue
        if a_device_dict['connections'][z_index].get('a_interfaces'):
            logging.info('Parsing cabling: {} <> {}'.format(a_hostname, z_hostname))
            ADD_CABLING = True
            for index, a_intf in enumerate(a_device_dict['connections'][z_index]['a_interfaces']):
                z_intf = a_device_dict['connections'][z_index]['z_interfaces'][index]
                if a_intf in existing_a_intf:
                    logging.warning('{}:{} already exists, ignoring..'.format(a_hostname, a_intf))
                else:
                    amended_cabling = jukebox.device_cabling(a_intf, a_hostname, z_hostname, z_intf, existing_cabling)
        else:
            logging.info('Cabling not found: {} <> {}'.format(a_hostname, z_hostname))
    return amended_cabling

def parse_links(a_device_dict, coral_device):
    """
    Parse link info for A-Device
    :param a_device_dict:
    :param coral_device:
    :return amended_links: Jukebox DeviceLink object:
    """
    a_hostname = a_device_dict['a_hostname']
    global ADD_LINKS
    ADD_LINKS = False
    amended_links = []
    if NEW_DEVICE:
        existing_links = []
    elif not NEW_DEVICE:
        existing_links = coral_device.data.links
        for link in existing_links:
            if link.device_a_name == a_hostname:  # Needed because JB returns mirrored cabling as well
                existing_links.append(link.device_z_name)

    for z_index in a_device_dict['connections'].keys():
        z_hostname = a_device_dict['connections'][z_index]['z_hostname']
        csc_cidr = None  # Default is no csc_cidr, only exists towards br-aggs
        if 'es-svc' in z_hostname:  # skips layer 2 es-svc devices
            continue
        if a_device_dict['connections'][z_index].get('inet_cidr'):
            logging.info('Parsing link CIDRs: {} <> {}'.format(a_hostname, z_hostname))
            ADD_LINKS = True
            inet_cidr = a_device_dict['connections'][z_index]['inet_cidr']
            if z_hostname in existing_links:  # Checking link doesn't already exist
                logging.warning('{} to {} link already exists, ignoring..'.format(a_hostname, z_hostname))
            else:
                amended_links = jukebox.create_new_cidr_info(a_hostname, z_hostname, inet_cidr, csc_cidr, get_link_type(z_hostname), existing_links)
        else:
            logging.info('Link CIDR not found: {} to {}'.format(a_hostname, z_hostname))
    return amended_links

def upload_to_jukebox(coral_device, amended_cabling, amended_links, site, a_hostname):
    """
    Upload coral device to Jukebox
    :param coral_device:
    :param amended_cabling:
    :param amended_links:
    :param site:
    :param a_hostname:
    :return:
    """
    try:
        logging.info('Uploading {} data to Jukebox'.format(a_hostname))
        if NEW_DEVICE:
            jukebox.add_new_device_to_jb(coral_device, amended_cabling, amended_links, site)
        elif not NEW_DEVICE:
            if ADD_CABLING and ADD_LINKS:
                jukebox.edit_full_device(a_hostname, amended_cabling, amended_links)
            elif ADD_CABLING:
                jukebox.edit_jukebox_cabling(a_hostname, amended_cabling)
            elif ADD_LINKS:
                jukebox.edit_link_cidr(a_hostname, amended_links)
    except Exception as error:
        logging.error('Failed to upload {} to Jukebox'.format(a_hostname))
        logging.error(error)

def main():
    setup_logging()
    args = parse_args()
    validate_input(args)
    logging.info('Reading {}'.format(args.yaml))
    with open(args.yaml) as hambone_yaml:
        main_dict = yaml.load(hambone_yaml)

    for layer in main_dict['Devices'].keys():
        for a_index in main_dict['Devices'][layer].keys():
            coral_device = add_device(main_dict['Devices'][layer][a_index], main_dict['Region'])
            amended_cabling = parse_cabling(main_dict['Devices'][layer][a_index], coral_device)
            amended_links = parse_links(main_dict['Devices'][layer][a_index], coral_device)
            if args.execute:
                upload_to_jukebox(coral_device, amended_cabling, amended_links, main_dict['Site'], (main_dict['Devices'][layer][a_index]['a_hostname']))

if __name__ == "__main__":
    main()


from django.shortcuts import render, redirect, get_object_or_404
from .models import Place
from .forms import NewPlaceForm, TripReviewForm
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from django.contrib import messages

@login_required()
def place_list(r):
    if r.method == 'POST':
        form = NewPlaceForm(r.POST)
        place = form.save(commit=False)
        place.user = r.user
        if form.is_valid():
            place.save()
            return redirect('place_list')

    places = Place.objects.filter(user=r.user).filter(visited=False).order_by('name')
    new_place_form = NewPlaceForm()
    return render(r, 'travel_wishlist/wishlist.html', {'places': places, 'new_place_form': new_place_form})

@login_required()
def places_visited(r):
    visited = Place.objects.filter(visited=True)
    return render(r, 'travel_wishlist/visited.html', {'visited': visited})

@login_required()
def place_was_visited(r, place_pk):
    if r.method == 'POST':
        place = get_object_or_404(Place, pk=place_pk)
        if place.user == r.user:
            place.visited = True
            place.save()
        else:
            return HttpResponseForbidden()
    return redirect('place_list')

@login_required()
def about(r):
    author = 'Nate'
    about = 'A website to create a list of places to visit'
    return render(r, 'travel_wishlist/about.html', {'author': author, 'about': about})

@login_required()
def place_details(r, place_pk):
    place = get_object_or_404(Place, pk=place_pk)
    if place.user != r.user:
        return HttpResponseForbidden()
    if r.method == 'POST':
        form = TripReviewForm(r.POST, r.FILES, instance=place)
        if form.is_valid():
            form.save()
            messages.info(r, 'Trip information updated')
        else:
            messages.error(r, form.errors)
        return redirect('place_details', place_pk=place_pk)
    else:
        if place.visited:
            review_form = TripReviewForm(instance=place)
            return render(r, 'travel_wishlist/place_detail.html', {'place': place, 'review_form': review_form})
        else:
            return render(r, 'travel_wishlist/place_detail.html', {'place': place})

@login_required()
def delete_place(r, place_pk):
    place = get_object_or_404(Place, pk=place_pk)
    if place.user == r.user:
        place.delete()
        return redirect('place_list')
    else:
        return HttpResponseForbidden()


from sys import stdin
from typing import TypeVar, Callable

from distance_matrix.DistanceMatrix import DistanceMatrix
from helpers.InputUtils import str_to_list
from phylogeny.Balder import bald_distance_matrix
from phylogeny.FourPointCondition import is_additive

N = TypeVar('N')

def create_distance_matrix(m: list[list[float]]) -> DistanceMatrix:
    d = {}
    for i in range(len(m)):
        for j in range(len(m)):
            i1, i2 = sorted([i, j])
            d[(f'v{i1}', f'v{i2}')] = float(m[i1][i2])
    return DistanceMatrix(d)

# MARKDOWN
def expose_neighbour_parent(
        dm: DistanceMatrix[N],
        l1: N,
        l2: N,
        gen_node_id: Callable[[], N]
) -> N:
    bald_distance_matrix(dm, l1)
    bald_distance_matrix(dm, l2)
    m_id = gen_node_id()
    m_dists = {x: (dm[l1, x] + dm[l2, x]) / 2 for x in dm.leaf_ids_it()}
    m_dists[m_id] = 0
    dm.insert(m_id, m_dists)
    dm.delete(l1)
    dm.delete(l2)
    return m_id
# MARKDOWN

def main():
    print("
", end="\n\n")
    print("`{bm-disable-all}`", end="\n\n")
    try:
        mat = []
        leaf1_id = stdin.readline().strip()
        leaf2_id = stdin.readline().strip()
        for line in stdin:
            row = [float(e) for e in str_to_list(line.strip(), 0)[0]]
            mat.append(row)
        dist_mat = create_distance_matrix(mat)
        assert is_additive(dist_mat), "Must be additive"
        print('Given additive distance matrix...')
        print()
        print('
')
        print('

')
        print('	')
        for l in sorted(dist_mat.leaf_ids_it()):
            print(f'{l}	')
        print('

')
        print('
')
        for l1 in sorted(dist_mat.leaf_ids_it()):
            print('
')
            print(f'{l1}	')
            for l2 in sorted(dist_mat.leaf_ids_it()):
                print(f'{dist_mat[l1, l2]}	')
            print('
')
        print('
')
        print('
')
        print()
        print(f'... and given that {leaf1_id} and {leaf2_id} are neighbours, balding and merging {leaf1_id} and {leaf2_id} results in ...')
        _next_node_id = 0
        def gen_node_id():
            nonlocal _next_node_id
            _next_node_id += 1
            return f'N{_next_node_id}'
        expose_neighbour_parent(dist_mat, leaf1_id, leaf2_id, gen_node_id)
        print()
        print('
')
        print('

')
        print('	')
        for l in sorted(dist_mat.leaf_ids_it()):
            print(f'{l}	')
        print('

')
        print('
')
        for l1 in sorted(dist_mat.leaf_ids_it()):
            print('
')
            print(f'{l1}	')
            for l2 in sorted(dist_mat.leaf_ids_it()):
                print(f'{dist_mat[l1, l2]}	')
            print('
')
        print('
')
        print('
')
        print()
    finally:
        print("
", end="\n\n")
        print("`{bm-enable-all}`", end="\n\n")

if __name__ == '__main__':
    main()


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

import os
import platform
import logging

if platform.platform().startswith("Windows"):
    loggingFile = os.path.join(
        os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"), "test.log")
else:
    loggingFile = os.path.join(os.getenv("HOME"), "test.log")

print("Logging to ", loggingFile)

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s : %(levelname)s : %(message)s",
    filename=loggingFile,
    filemode="w",
)

logging.debug("Start of the program")
logging.info("Do something")
logging.warning("Dying now")


# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.

from pyqrllib.pyqrllib import bin2hstr
from qrl.core import config, logger
import simplejson as json

from qrl.crypto.misc import sha256

class StakeValidator:
    """
    Stake Validator class to represent the each unique Stake Validator.

    Maintains the cache of successfully validated hashes, saves validation
    time by avoiding recalculation of the hash till the hash terminators.
    """
    def __init__(self, stake_txn, entry_blocknumber):
        self.buffer_size = 4  # Move size to dev configuration
        self.stake_validator = stake_txn.txfrom
        self.slave_public_key = stake_txn.slave_public_key
        self.balance = stake_txn.balance
        self.hash = stake_txn.hash
        self.entry_blocknumber = entry_blocknumber  # Blocknumber at which ST txn was added into block

        self.finalized_blocknumber = stake_txn.finalized_blocknumber
        self.finalized_headerhash = stake_txn.finalized_headerhash

        self.nonce = 0
        self.is_banned = False
        self.is_active = True  # Flag that represents if the stakevalidator has been deactivated by destake txn

        if self.hash:
            self.cache_hash = dict()
            self.cache_hash[entry_blocknumber] = self.hash

    def hash_to_terminator(self, hash, times):
        for _ in range(times):
            hash = sha256(bin2hstr(tuple(hash)).encode())

        return hash

    # Saves the last X validated hash into the memory
    def update(self, epoch_blocknum, hash, hash_staker):
        self.cache_hash[epoch_blocknum] = hash
        hash_staker[hash] = self.stake_validator
        if len(self.cache_hash) > self.buffer_size:
            minimum_epoch_blocknum = min(self.cache_hash)
            remove_hash = self.cache_hash[minimum_epoch_blocknum]
            del hash_staker[remove_hash]
            del self.cache_hash[minimum_epoch_blocknum]

    @staticmethod
    def get_epoch_blocknum(blocknum):
        epoch = blocknum // config.dev.blocks_per_epoch
        return blocknum - (epoch * config.dev.blocks_per_epoch)

    def validate_hash(self, hash, blocknum, hash_staker):

        cache_blocknum = max(self.cache_hash)
        times = blocknum - cache_blocknum

        terminator_expected = tuple(self.hash_to_terminator(hash, times))
        terminator_found = tuple(self.cache_hash[cache_blocknum])

        if terminator_found != terminator_expected:
            return False

        self.update(blocknum, hash, hash_staker)

        return True

    def to_json(self):
        return json.dumps(self.__dict__)


#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

from ax.core.objective import MultiObjective
from ax.core.optimization_config import MultiObjectiveOptimizationConfig
from ax.modelbridge.dispatch_utils import (
    DEFAULT_BAYESIAN_PARALLELISM,
    choose_generation_strategy,
)
from ax.utils.common.testutils import TestCase
from ax.utils.testing.core_stubs import (
    get_branin_search_space,
    get_discrete_search_space,
    get_experiment,
    get_factorial_search_space,
    get_large_factorial_search_space,
)

class TestDispatchUtils(TestCase):
    """Tests that dispatching utilities correctly select generation strategies."""

    def test_choose_generation_strategy(self):
        with self.subTest("GPEI"):
            sobol_gpei = choose_generation_strategy(
                search_space=get_branin_search_space()
            )
            self.assertEqual(sobol_gpei._steps[0].model.value, "Sobol")
            self.assertEqual(sobol_gpei._steps[0].num_trials, 5)
            self.assertEqual(sobol_gpei._steps[1].model.value, "GPEI")
        with self.subTest("MOO"):
            sobol_gpei = choose_generation_strategy(
                search_space=get_branin_search_space(),
                optimization_config=MultiObjectiveOptimizationConfig(
                    objective=MultiObjective(objectives=[])
                ),
            )
            self.assertEqual(sobol_gpei._steps[0].model.value, "Sobol")
            self.assertEqual(sobol_gpei._steps[0].num_trials, 5)
            self.assertEqual(sobol_gpei._steps[1].model.value, "MOO")
        with self.subTest("Sobol (we can try every option)"):
            sobol = choose_generation_strategy(
                search_space=get_factorial_search_space(), num_trials=1000
            )
            self.assertEqual(sobol._steps[0].model.value, "Sobol")
            self.assertEqual(len(sobol._steps), 1)
        with self.subTest("Sobol (because of too many categories)"):
            sobol_large = choose_generation_strategy(
                search_space=get_large_factorial_search_space()
            )
            self.assertEqual(sobol_large._steps[0].model.value, "Sobol")
            self.assertEqual(len(sobol_large._steps), 1)
        with self.subTest("GPEI-Batched"):
            sobol_gpei_batched = choose_generation_strategy(
                search_space=get_branin_search_space(), use_batch_trials=3
            )
            self.assertEqual(sobol_gpei_batched._steps[0].num_trials, 1)
        with self.subTest("BO_MIXED (purely categorical)"):
            bo_mixed = choose_generation_strategy(
                search_space=get_factorial_search_space()
            )
            self.assertEqual(bo_mixed._steps[0].model.value, "Sobol")
            self.assertEqual(bo_mixed._steps[0].num_trials, 5)
            self.assertEqual(bo_mixed._steps[1].model.value, "BO_MIXED")
        with self.subTest("BO_MIXED (mixed search space)"):
            bo_mixed_2 = choose_generation_strategy(
                search_space=get_branin_search_space(with_choice_parameter=True)
            )
            self.assertEqual(bo_mixed_2._steps[0].model.value, "Sobol")
            self.assertEqual(bo_mixed_2._steps[0].num_trials, 5)
            self.assertEqual(bo_mixed_2._steps[1].model.value, "BO_MIXED")

    def test_setting_random_seed(self):
        sobol = choose_generation_strategy(
            search_space=get_factorial_search_space(), random_seed=9
        )
        sobol.gen(experiment=get_experiment())
        # First model is actually a bridge, second is the Sobol engine.
        self.assertEqual(sobol.model.model.seed, 9)

    def test_enforce_sequential_optimization(self):
        sobol_gpei = choose_generation_strategy(search_space=get_branin_search_space())
        self.assertEqual(sobol_gpei._steps[0].num_trials, 5)
        self.assertTrue(sobol_gpei._steps[0].enforce_num_trials)
        self.assertIsNotNone(sobol_gpei._steps[1].max_parallelism)
        sobol_gpei = choose_generation_strategy(
            search_space=get_branin_search_space(),
            enforce_sequential_optimization=False,
        )
        self.assertEqual(sobol_gpei._steps[0].num_trials, 5)
        self.assertFalse(sobol_gpei._steps[0].enforce_num_trials)
        self.assertIsNone(sobol_gpei._steps[1].max_parallelism)

    def test_max_parallelism_override(self):
        sobol_gpei = choose_generation_strategy(
            search_space=get_branin_search_space(), max_parallelism_override=10
        )
        self.assertTrue(all(s.max_parallelism == 10 for s in sobol_gpei._steps))

    def test_winsorization(self):
        winsorized = choose_generation_strategy(
            search_space=get_branin_search_space(),
            winsorize_botorch_model=True,
            winsorization_limits=(None, 0, 2),
        )
        self.assertIn(
            "Winsorize", winsorized._steps[1].model_kwargs.get("transform_configs")
        )

    def test_num_trials(self):
        ss = get_discrete_search_space()
        # Check that with budget that is lower than exhaustive, BayesOpt is used.
        sobol_gpei = choose_generation_strategy(search_space=ss, num_trials=11)
        self.assertEqual(sobol_gpei._steps[0].model.value, "Sobol")
        self.assertEqual(sobol_gpei._steps[1].model.value, "BO_MIXED")
        # Check that with budget that is exhaustive, Sobol is used.
        sobol = choose_generation_strategy(search_space=ss, num_trials=12)
        self.assertEqual(sobol._steps[0].model.value, "Sobol")
        self.assertEqual(len(sobol._steps), 1)

    def test_use_batch_trials(self):
        sobol_gpei = choose_generation_strategy(
            search_space=get_branin_search_space(), use_batch_trials=True
        )
        self.assertEqual(sobol_gpei._steps[0].num_trials, 1)

    def test_fixed_num_initialization_trials(self):
        sobol_gpei = choose_generation_strategy(
            search_space=get_branin_search_space(),
            use_batch_trials=True,
            num_initialization_trials=3,
        )
        self.assertEqual(sobol_gpei._steps[0].num_trials, 3)

    def test_max_parallelism_adjustments(self):
        # No adjustment.
        sobol_gpei = choose_generation_strategy(search_space=get_branin_search_space())
        self.assertIsNone(sobol_gpei._steps[0].max_parallelism)
        self.assertEqual(
            sobol_gpei._steps[1].max_parallelism, DEFAULT_BAYESIAN_PARALLELISM
        )
        # Impose a cap of 1 on max parallelism for all steps.
        sobol_gpei = choose_generation_strategy(
            search_space=get_branin_search_space(), max_parallelism_cap=1
        )
        self.assertEqual(
            sobol_gpei._steps[0].max_parallelism,
            sobol_gpei._steps[1].max_parallelism,
            1,
        )
        # Disable enforcing max parallelism for all steps.
        sobol_gpei = choose_generation_strategy(
            search_space=get_branin_search_space(), max_parallelism_override=-1
        )
        self.assertIsNone(sobol_gpei._steps[0].max_parallelism)
        self.assertIsNone(sobol_gpei._steps[1].max_parallelism)
        # Override max parallelism for all steps.
        sobol_gpei = choose_generation_strategy(
            search_space=get_branin_search_space(), max_parallelism_override=10
        )
        self.assertEqual(sobol_gpei._steps[0].max_parallelism, 10)
        self.assertEqual(sobol_gpei._steps[1].max_parallelism, 10)

    def test_set_should_deduplicate(self):
        sobol_gpei = choose_generation_strategy(
            search_space=get_branin_search_space(),
            use_batch_trials=True,
            num_initialization_trials=3,
        )
        self.assertListEqual(
            [s.should_deduplicate for s in sobol_gpei._steps], [False] * 2
        )
        sobol_gpei = choose_generation_strategy(
            search_space=get_branin_search_space(),
            use_batch_trials=True,
            num_initialization_trials=3,
            should_deduplicate=True,
        )
        self.assertListEqual(
            [s.should_deduplicate for s in sobol_gpei._steps], [True] * 2
        )


# Import libraries
import sys
import os

import pandas as pd

from utils import fp_to_manure_data, fp_to_arable_land_data

# Input arguments
wd = sys.argv[1]
predictor = sys.argv[2]

# Change working directory
os.chdir(wd)

# Read manure data
manure = pd.read_csv(fp_to_manure_data(predictor), sep=',', header=1, encoding='utf-8-sig')\
    .pipe(
        lambda df: df.rename(
            columns={df.columns[0]: 'year', df.columns[1]: 'county', df.columns[2]: f'{predictor}_t'}
        )
    )

# Read arable land data
arable_land = pd.read_csv(fp_to_arable_land_data(), sep=',', header=1)

# Melt arable land data
arable_land_melt = pd.melt(arable_land, id_vars=['Maakond'], value_vars=arable_land.columns[-5:])\
    .pipe(lambda df: df.assign(year=df['variable'].str.split().str[0].astype(int)))\
    .drop('variable', axis=1)\
    .rename(columns={'Maakond': 'county', 'value': 'arable_land_ha'})

# Merge counties with manure
manure_arable = manure.merge(arable_land_melt, how='left', on=['county', 'year'])

# Calculate amount of nutrient in kg per ha
manure_arable[f'{predictor}_kg_per_ha'] = (manure_arable[f'{predictor}_t'] * 1000) / manure_arable['arable_land_ha']
fp = os.path.join(os.path.dirname(fp_to_manure_data(predictor)), f'{predictor}_kg_per_ha.csv')
manure_arable.drop([f'{predictor}_t', 'arable_land_ha'], axis=1)\
    .to_csv(fp, sep=',', index=False, encoding='utf-8-sig')


import pandas as pd
import re
import sqlite3
from os import listdir, path, getcwd
from os.path import isfile, isdir, join
from functools import partial
from git import Repo

AWESOMO_REPO = 'https://github.com/lk-geimfari/awesomo.git'

DIR_PATH = path.dirname(path.realpath('__file__'))
CWD = getcwd()

AWESOME_REPO_PATH = join(CWD,'awesomo')

# Always make sure
if isdir(AWESOME_REPO_PATH):
    Repo(AWESOME_REPO_PATH).remotes.origin.pull
else:
    Repo.clone_from(
        AWESOMO_REPO,
        AWESOME_REPO_PATH,
        branch='master'
    )

AWESOMO_PATH = join(CWD,'awesomo','languages')

FILENAMES = listdir(AWESOMO_PATH)

TITLE_PATTERN = r'\*\*.*?\*\*'
URL_PARTTERN = r'\*\s?\]\(.*?\)'

# retrieves project title
_get_title = partial(re.findall, pattern=TITLE_PATTERN, flags=0)

# retrives project url
_get_url = partial(re.findall, pattern=URL_PARTTERN, flags=0)

def _get_languages(files=FILENAMES):
    """Get languages lists for each file name"""
    return [md_file[:-3] for md_file in files
                  if md_file.endswith('.md')]

def _get_file_lines(file_path):
    """Read file and get line iterator"""
    file = open(file_path, "r",encoding='utf-8', newline='\n')
    return file.readlines()

def _clean_url(url_string):
    """Remove invalid characters from url"""
    return url_string.strip(
        ' '
    ).replace(
        '*',''
    ).replace(
        '\u200aa',''
    ).replace(
        '\u200a',''
    ).replace(
        ']', ''
    ).replace(
        '(',''
    ).replace(
        ')',''
    ).replace(
        '[',''
    )

def _split_description(line):
    """Split description from the title line. """
    description =  line.split(
        ')'
    )[1]
    return description

def _fix_description_start(description, project_name):
    """Fix description start in case it doesn't make sens"""
    if description.startswith('a '):
        return project_name + ' is ' + description
    elif description.startswith('is ') or description.startswith('lets '):
        return project_name + ' ' + description
    else:
        return description

def _extend_description(description, line, line_list):
    """Extend the description based on the nex paragraph"""
    line_i = line_list.index(line)
    for next_line in line_list[line_i+1:]:
        s_line = next_line.strip()
        break_condition =  (
            s_line == '' or s_line.startswith('![')
            or s_line.startswith('<') or   s_line.startswith('[')
        )
        if s_line == '' or s_line.startswith('![') or s_line.startswith('<') or   s_line.startswith('['):
            break
        description = description + ' ' + s_line
    return description

def _clean_description(description):
    """Remove invalid characters from description"""
    description = description.replace('\u200a','')
    description = description.replace('—','')
    description = description.strip(' '
    ).strip(
        '— '
    ).strip(
        '- '
    ).replace(
        '\u200aa', ''
    ).replace(
        '\u200a', ''
    ).lstrip(
        '. '
    ).strip(
        ' '
    ).strip(
        '\n'
    ).strip(
        '\t'
    ).rstrip(
        ', which are:'
    )
    return description

def _get_project_description(line, line_list, project_name):
    """Retrieve project description"""
    description = _split_description(line)
    description = _extend_description(description, line, line_list)
    description = _clean_description(description)
    description = _fix_description_start(description, project_name)
    return description

def _get_information(line, line_list):
    """Retrive project information and save it into a dictionary."""
    project_name = _get_title(string=line)[0].strip('*').strip('\u200aa')

    info_dict = {'name': project_name}

    project_url = _clean_url(
        _get_url(string=line)[0]
    )

    description = _get_project_description(line, line_list, project_name)

    info_dict = {'name': project_name}
    info_dict['url'] = project_url
    info_dict['description'] = description

    return info_dict

def _read_title_line(line,line_list, language):
    """Find title line and retrieve basic project information."""
    if line.startswith('[**'):
        info_dict = _get_information(line, line_list)
        info_dict["language"] = language
        return [info_dict]
    else:
        return []

def _read_language(line_list, language, info_list = []):
    """Scan language file and retrieves a list of project infos."""
    for line in line_list:
        infos = _read_title_line(line,line_list, language)
        info_list.extend(infos)
    return info_list

def _read_language_files(language_list):
    """Scan all the language files and retrieve a comple list of projects and their info."""
    info_list = []
    for lang in language_list:
        lang_path = join(AWESOMO_PATH, lang+'.md')
        line_list  = _get_file_lines(lang_path)
        info_list = _read_language(line_list, lang, info_list)
    return info_list

def _retrive_information(language_list = _get_languages()):
    """Retruns a list of dictionaries containing project information.."""
    return _read_language_files(language_list)

def _create_connection(db_name='opensource'):
    """Create a SQLite3 connection."""
    return sqlite3.connect(db_name+".sqlite")

def _get_table_columns(column_names):
    """Transform list of column names in a string tuple.
    This is done so it can be easily injected into the query.
    """
    columns = ','.join(column_names)
    return '(' + columns + ')'

def _create_replace_table(table_name,cursor, column_names):
    """Create or replace a given table with an empty table."""
    drop_query = "DROP TABLE IF EXISTS " + table_name + ";"
    cursor.execute(drop_query)
    create_query = "CREATE TABLE " + table_name + " " + column_names + ";"
    cursor.execute(create_query)
    return cursor

def _fill_table(cursor, connection, column_list, data_list, table_name):
    """Populate table with information conatined in the data list."""
    insert_query = "insert into " + table_name + " values (?,?,?,?)"
    for data in data_list:
        keys = tuple(data[c] for c in column_list)
        cursor.execute(insert_query, keys)
    connection.commit()

def build_project_table(
    db_name='opensource',
    table_name='projects',
    column_list= ['language', 'name', 'url', 'description']):
    """Build opensource projects table."""
    data_list = _retrive_information()
    db_connection = _create_connection(db_name)
    db_cursor = db_connection.cursor()
    column_names = _get_table_columns(column_list)
    db_cursor = _create_replace_table(table_name,db_cursor, column_names)
    _fill_table(db_cursor, db_connection, column_list, data_list,table_name)
    db_connection.close()

if __name__=='__main__':

    build_project_table()

    db = sqlite3.connect("opensource.sqlite")
    c = db.cursor()
    print(c.execute("select count(*) from projects").fetchall())
    print(c.execute("select * from projects order by random() limit 10").fetchall())
    c.close()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

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

import sys
sys.path.append("../")
import calculations as cc
import ListUitpakken as get

colors = ['#b35806', '#e08214', '#fdb863', '#fee0b6', '#ffffbf', '#d8daeb', '#b2abd2', '#8073ac', '#542788']

data1_1 = cc.readfile("20140307_axis1_1_bolo4mm.csv")
data1_2 = cc.readfile("20140307_axis1_5_bolo1.2mm.csv")
data1_3 = cc.readfile("20140311_axis1_1_bolo4mm.csv")
data1_4 = cc.readfile("20140319_axis1_1_globar2.18mm.csv")

def align(data, axis):
	align_index = np.argmax(data[2])
	align_shift = data[axis][align_index]
	return data[axis] - align_shift

plt.figure(1, figsize=(12,8))
cc.plotsimple(align(data1_1, 0), data1_1[2], colors[0], "bolo 4mm", 2)
cc.plotsimple(align(data1_2, 0), data1_2[2], colors[2], "bolo 1.2mm", 2)
cc.plotsimple(align(data1_3, 1), data1_3[2], colors[4], "bolo 4mm", 2)
cc.plotsimple(align(data1_4, 1), data1_4[2], colors[6], "globar 2.18mm", 2)

plt.figure(2, figsize=(12,8))
cc.logplotsimple(align(data1_1, 0), data1_1[2], colors[0], "bolo 4mm", 2)
cc.logplotsimple(align(data1_2, 0), data1_2[2], colors[2], "bolo 1.2mm", 2)
cc.logplotsimple(align(data1_3, 1), data1_3[2], colors[4], "bolo 4mm", 2)
cc.logplotsimple(align(data1_4, 1), data1_4[2], colors[6], "globar 2.18mm", 2)

plt.show()


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

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^question/(?P<question_id>[0-9]+)/$', views.question, name='question'),
    url(r'^login/$', views.login_view, name='login'),
    url(r'^new_question/$', views.new_question, name='new_question'),
    url(r'^register/$', views.register, name='register'),
    url(r'^question/like/(?P<question_id>[0-9]+)/$', views.question_like, name='question_like'),
    url(r'^question/dislike/(?P<question_id>[0-9]+)/$', views.question_dislike, name='question_dislike'),
    url(r'^hot/', views.hot, name='hot'),
    url(r'^tag/(?P<tag_id>[0-9]+)/$', views.tag, name='tag'),
    url(r'^logout/$', views.logout_view, name='logout'),
    url(r'^profile/$', views.profile_view, name='profile'),
]


from unittest import TestCase
from zcfd.solvers.cfl import CFL

class TestCFL(TestCase):

    def setUp(self):
        self.cfl = CFL(1.0)

    def test_updatecfl(self):
        solve_cycle = 0
        real_time_step = 0
        self.cfl.max_cfl = 10.0
        self.cfl.min_cfl = 1.0
        self.cfl.cfl_ramp = 1.1
        self.cfl.update(solve_cycle, real_time_step, None)
        assert self.cfl.cfl == 1.0
        solve_cycle = 500
        self.cfl.update(solve_cycle, real_time_step, None)
        assert self.cfl.cfl == 10.0
        solve_cycle = 100000
        self.cfl.update(solve_cycle, real_time_step, None)
        assert self.cfl.cfl == 10.0

    def test_norampfunc(self):
        self.cfl.update(0, 0, None)

    def test_constfunc(self):
        self.cfl.update(0, 0, lambda solve_cycle, real_time_step, cfl: 1.0)
        assert self.cfl.cfl == 1.0


# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/runner/work/PyTplot/PyTplot/pytplot/QtPlotter/PyTPlot_Exporter.py
# Compiled at: 2020-04-24 00:12:01
# Size of source mod 2**32: 5669 bytes
import pyqtgraph as pg, numpy as np
import pyqtgraph.functions as fn
from pyqtgraph.Qt import QtCore, QtGui
from pyqtgraph.exporters import Exporter
from pyqtgraph.parametertree import Parameter

class PytplotExporter(pg.exporters.ImageExporter):

    def __init__(self, item):
        Exporter.__init__(self, item)
        tr = self.getTargetRect()
        if isinstance(item, QtGui.QGraphicsItem):
            scene = item.scene()
        else:
            scene = item
        bgbrush = scene.backgroundBrush()
        bg = bgbrush.color()
        if bgbrush.style() == QtCore.Qt.NoBrush:
            bg.setAlpha(0)
        self.params = Parameter(name='params', type='group', children=[
         {'name':'width',
          'type':'int',  'value':tr.width(),  'limits':(0, None)},
         {'name':'height',
          'type':'int',  'value':tr.height(),  'limits':(0, None)},
         {'name':'antialias',
          'type':'bool',  'value':True},
         {'name':'background',
          'type':'color',  'value':bg}])
        self.params.param('width').sigValueChanged.connect(self.widthChanged)
        self.params.param('height').sigValueChanged.connect(self.heightChanged)

    def export(self, fileName=None, toBytes=False, copy=False):
        if fileName is None:
            if not toBytes:
                if not copy:
                    if pg.Qt.USE_PYSIDE:
                        filter = ['*.' + str(f) for f in QtGui.QImageWriter.supportedImageFormats()]
                    else:
                        filter = ['*.' + bytes(f).decode('utf-8') for f in QtGui.QImageWriter.supportedImageFormats()]
                    preferred = [
                     '*.png', '*.tif', '*.jpg']
                    for p in preferred[::-1]:
                        if p in filter:
                            filter.remove(p)
                            filter.insert(0, p)

                    self.fileSaveDialog(filter=filter)
                    return
        else:
            targetRect = QtCore.QRect(0, 0, self.params['width'], self.params['height'])
            sourceRect = self.getSourceRect()
            w, h = self.params['width'], self.params['height']
            if not w == 0:
                if h == 0:
                    raise Exception('Cannot export image with size=0 (requested export size is %dx%d)' % (w, h))
                bg = np.empty((int(self.params['width']), int(self.params['height']), 4), dtype=(np.ubyte))
                color = self.params['background']
                bg[:, :, 0] = color.blue()
                bg[:, :, 1] = color.green()
                bg[:, :, 2] = color.red()
                bg[:, :, 3] = color.alpha()
                self.png = fn.makeQImage(bg, alpha=True)
                origTargetRect = self.getTargetRect()
                resolutionScale = targetRect.width() / origTargetRect.width()
                painter = QtGui.QPainter(self.png)
                try:
                    self.setExportMode(True, {'antialias':self.params['antialias'],
                     'background':self.params['background'],  'painter':painter,
                     'resolutionScale':resolutionScale})
                    painter.setRenderHint(QtGui.QPainter.Antialiasing, self.params['antialias'])
                    self.getScene().render(painter, QtCore.QRectF(0, 0, 1, 1), QtCore.QRectF(0, 0, 1, 1))
                    self.getScene().render(painter, QtCore.QRectF(targetRect), QtCore.QRectF(sourceRect))
                finally:
                    self.setExportMode(False)

                painter.end()
                if copy:
                    QtGui.QApplication.clipboard().setImage(self.png)
            else:
                if toBytes:
                    return self.png
                self.png.save(fileName)

    def getPaintItems(self, root=None):
        """Return a list of all items that should be painted in the correct order."""
        if root is None:
            root = self.item
        preItems = []
        postItems = []
        if isinstance(root, QtGui.QGraphicsScene):
            childs = [i for i in root.items() if i.parentItem() is None]
            rootItem = []
        else:
            try:
                childs = root.childItems()
            except:
                childs = root.items()

            rootItem = [
             root]
        childs.sort(key=(lambda a: a.zValue()))
        while len(childs) > 0:
            ch = childs.pop(0)
            tree = self.getPaintItems(ch)
            if not int(ch.flags() & ch.ItemStacksBehindParent) > 0:
                if not ch.zValue() < 0 or int(ch.flags() & ch.ItemNegativeZStacksBehindParent) > 0:
                    preItems.extend(tree)
            else:
                postItems.extend(tree)

        return preItems + rootItem + postItems

    def getTargetRect(self):
        return self.item.rect()

    def getSourceRect(self):
        return self.item.rect()