flag = True

def div(a, b):
       try:
            print("Finally the division of %d/%d is %f" % (a, b,a/b))
            global flag
            flag=False
       except ZeroDivisionError:
            print("Zero Division Error detected")
       else:
            print("Division is successful")
       finally:
            if flag is True:
               print("Try again")
            else:
               print("Thank you")

#global flag

while flag is True:
    div(int(input("Enter numerator")),int(input("Enter denominator")))


import numpy as np
import scipy.io
from tensorflow.keras.utils import to_categorical ,Sequence
from unwrap import unwrap
def normalize_real(x_source):
    a_oo = x_source - x_source.real.min() - 1j * x_source.imag.min()  # origin offsetted
    return a_oo / np.abs(a_oo).max()

def normalize_angle(audio):
    xaudio = (audio - np.min(audio)) / (np.max(audio) - np.min(audio))
    # def normalize_angle (audio):
    # audio= [item.flatten() for item in audio]
    # audio = min_max_scaler.fit_transform(audio)
    # audio= [item.reshape(256,256) for item in audio]
    return xaudio

class DataGenerator(Sequence):
    'Generates data for Keras'

    def __init__(self, pair, class_map, batch_size=16, dim=(256, 256, 1), shuffle=True):
        'Initialization'
        self.dim = dim
        self.pair = pair
        self.class_map = class_map
        self.batch_size = batch_size
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.pair) / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]

        # Find list of IDs
        list_IDs_temp = [k for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.pair))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples'  # X : (n_samples, *dim, n_channels)
        # Initialization
        batch_imgs = list()
        batch_labels = list()

        # Generate data
        for i in list_IDs_temp:
            # Store sample
            # print (self.pair[i][0])
            img = scipy.io.loadmat(self.pair[i][0])['wrap']
            img_normalized = normalize_angle(img)
            batch_imgs.append(img_normalized)

            label = unwrap(img, wrap_around_axis_0=False, wrap_around_axis_1=False, wrap_around_axis_2=False)
            label_normalized = normalize_angle(label)
            batch_labels.append(label_normalized)

        return np.array(np.expand_dims(batch_imgs, axis=-1)), np.array(np.expand_dims(batch_labels, axis=-1))


# 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: build/bdist.macosx-10.14-x86_64/egg/wsiprocess/arguments.py
# Compiled at: 2019-11-28 08:31:06
# Size of source mod 2**32: 2558 bytes
import argparse
from pathlib import Path

class Args:

    def __init__(self):
        self.get_args()

    def get_args(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('wsi', type=Path, help='Path to the target wsi.')
        parser.add_argument('method', type=str, choices={
         'none', 'classification', 'detection', 'segmentation'},
          help='Method to use.')
        parser.add_argument('-st', '--save_to', type=Path, help='Where to save the data.')
        parser.add_argument('-an', '--annotation', type=Path, help='Path to the annotation xml file.')
        parser.add_argument('-of', '--on_foreground', type=float, default=1.0, help='The ratio of overlapped area of a patch and the foreground area.')
        parser.add_argument('-pa', '--on_annotation', type=float, default=1.0, help='The ratio of overlapped area of a patch and the annotated area.')
        parser.add_argument('-pw', '--patch_width', type=int, default=256, help='Width of patches.')
        parser.add_argument('-ph', '--patch_height', type=int, default=256, help='Height of patches.')
        parser.add_argument('-ow', '--overlap_width', type=int, default=1, help='Width of the overlapped area of patches.')
        parser.add_argument('-oh', '--overlap_height', type=int, default=1, help='Height of the overlapped area of patches')
        parser.add_argument('-ss', '--start_sample', action='store_true', help='Generate samples at the start of the process.')
        parser.add_argument('-fs', '--finished_sample', action='store_true', help='Generate samples at the end of the process.')
        parser.add_argument('-ep', '--extract_patches', action='store_true', help='Extract the patches and save them as images.')
        parser.add_argument('-ma', '--magnification', choices={40, 20, 10}, default=40,
          type=int,
          help='Magnification to process.')
        parser.add_argument('-ie', '--inclusion', type=Path, help='File to define the inclusion relationship.')
        args = parser.parse_args()
        for arg in vars(args):
            setattr(self, arg, getattr(args, arg))


#!/usr/bin/env python
##  Copyright (c) 2012 The WebM project authors. All Rights Reserved.
##
##  Use of this source code is governed by a BSD-style license
##  that can be found in the LICENSE file in the root of the source
##  tree. An additional intellectual property rights grant can be found
##  in the file PATENTS.  All contributing project authors may
##  be found in the AUTHORS file in the root of the source tree.
##

# Setup django to silence deprecation warning for 0.96
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util as webapp_util
from google.appengine.api import users

from drilldown import drilldown
from cache import cache_result, CachedDataView
import model
import util
import main
import drilldown
import logging
import urllib

# A global variable to determine how important a test run is (percent improvement)
THRESHOLD_HIGH = 1.0
THRESHOLD_LOW = 0.1

# ------------------------------------------------------------------------------
# Helpers for both handlers

@cache_result()
def get_adhoc_improvement(metrics, config, filenames, commit):
    # Mostly copied from main.py with some notable changes
    response = []

    # Find the baseline based on the raw URL variables
    parent = main.find_baseline(",".join(metrics), config,
                                ",".join(filenames), commit)
    result = []

    for m in metrics:
        if model.metrics()[m].distortion:
            improvement = main.rd_improvement
        else:
            improvement = main.mean_improvement

        if parent:
            baseline_data = main.fetch_metric_for_fileset(
                m, config, filenames, parent)
            average, results = main.calculate_improvement(
                m, config, filenames, commit, baseline_data, improvement)
        else:
            results = dict([f, 0.0] for f in filenames)

        for f, composite in results.iteritems():
            response.append({'metric': m, 'config': config, 'baseline': parent,
                             'filename': f, 'value': composite})
    return response

def run_formatter(commit, resps):
    '''A helper function to format the run data of a commit'''
    formatted_resps = []
    for row in resps:
        if row['metric'] == 'Time(us)' or row['metric'] == 'Bitrate' or row['metric'] == 'target_bitrate':
            continue
        if row['filename'][0] == '~':
            continue

        if not row['baseline']:
            row['class'] = 'unknown'
        elif abs(row['value']) > THRESHOLD_HIGH:
            if row['value'] > 0:
                row['class'] = 'good major'
            else:
                row['class'] = 'bad major'

        elif abs(row['value']) > THRESHOLD_LOW:
            if row['value'] > 0:
                row['class'] = 'good minor'
            else:
                row['class'] = 'bad minor'

        else: # We are right in the middle
            row['class'] = "unchanged"

        # This is a bit messy, but it works (mixing django and
        # javascript doesn't work like you would hope)
        if row['baseline']:
            row['clickcommand'] = str("javascript: ChartFillerCaller(" + "\'" +
                                  row['metric'].encode('ascii', 'ignore') + "," +
                                  row['config'].encode('ascii', 'ignore') + "," +
                                  row['filename'].encode('ascii', 'ignore') + ',' +
                                  commit['commitid'].encode('ascii', 'ignore') + "," +
                                  row['baseline'].encode('ascii', 'ignore') + "\'"+ ')')
        formatted_resps.append(row)

    resp_rows = {}
    for resp in formatted_resps:
        key = (resp['metric'], resp['config'])
        row = resp_rows.setdefault(key, [])
        row.append(resp)
    formatted_resps=[]
    for key in sorted(resp_rows.keys()):
        formatted_resps.append({
            'metric': key[0],
            'config': key[1],
            'runs': sorted(resp_rows[key], key=lambda x: x['filename']),
            })

    return formatted_resps

# ------------------------------------------------------------------------------

class CommitQueryHandler(webapp.RequestHandler):
    def get(self):
        # We get the 5 most recent commits
        query = model.Commit.all()

        # We use this if we just want the newest 5, regardless of run data
        #current_commits = query.order("-commit_time").fetch(limit=5)

        # test data
        current_commits = ['0030303b6949ba2d3391f3ae400213acc0e80db7',
                           '062864f4cc2179b6f222ae337538c18bfd08037a',
                           '05bde9d4a4b575aaadd9b6f5d0f82826b1cb4900',
                           '0c483d6b683fa4313cf7dadf448a707fe32714a4']

        formatted_commits = [] # These are commit_dict, formatted_resps pairs

        for commit in current_commits:
            # We get all the data about the commit we need
            #commit_data = commit

            # only for test data
            commit_data = model.commits()[commit]

            message = commit_data.message.split("\n")
            commit = {'commit': commit_data.key().name()[:9],
                     'commitid': commit_data.key().name(),
                     'author': commit_data.author,
                     'subject': message[0],
                     'body': message[1:],
                     'date': commit_data.author_time,
                     'branches': commit_data.branches}
            commitid = commit_data.key().name()

            # We need (metric, config, fileset) tuples
            resps = []
            query = model.CodecMetricIndex.all()
            query = query.filter('commit =', commitid)
            for item in query:
                resps.extend(get_adhoc_improvement(item.metrics, item.config_name,
                                                   item.files, commitid))

            # Now that we have our responses, we can format them by seeing if
            # the value crosses our threshold
            formatted_resps = run_formatter(commit, resps)

            formatted_commits.append((commit, formatted_resps))

        values = {
            "user": users.get_current_user(),
            "login_url": users.create_login_url("/"),
            "logout_url": users.create_logout_url("/"),
            "formatted_commits" : formatted_commits,
        }
        self.response.out.write(template.render("commit_viewer.html", values))

class CommitDisplayHandler(webapp.RequestHandler):
    def get(self, commit):
        commit = urllib.unquote(commit)

        # We start by seeing if its a valid commit (or email address)
        indexes = model.CodecMetricIndex.all(keys_only = True)
        indexes = indexes.filter('commit =', commit)
        keys = [k.parent() for k in indexes]
        if len(keys) == 0:

            values = {
                "user": users.get_current_user(),
                "login_url": users.create_login_url("/"),
                "logout_url": users.create_logout_url("/"),
                'commit': commit,
                'error': True,
                'errormessage': "There are no matching results for this search.",
            }

            html = template.render("commit_view.html", values)
            self.response.out.write(html)

            return

        # We get all the data about the commit we need
        commit_data = model.commits()[commit]
        message = commit_data.message.split("\n")
        commit = {'commit': commit_data.key().name()[:9],
                 'commitid': commit_data.key().name(),
                 'author': commit_data.author,
                 'subject': message[0],
                 'body': message[1:],
                 'date': commit_data.author_time,
                 'branches': commit_data.branches}
        commitid = commit_data.key().name()

        # We need (metric, config, fileset) tuples
        resps = []
        query = model.CodecMetricIndex.all()
        query = query.filter('commit =', commitid)
        for item in query:
            resps.extend(get_adhoc_improvement(item.metrics, item.config_name,
                                               item.files, commitid))

        # Now that we have our responses, we can format them by seeing if
        # the value crosses our threshold
        formatted_resps = run_formatter(commit, resps)

        values = {
            "user": users.get_current_user(),
            "login_url": users.create_login_url("/"),
            "logout_url": users.create_logout_url("/"),
            'commit': commit,
            'runs': formatted_resps
        }

        html = template.render("commit_view.html", values)
        self.response.out.write(html)

def main_func():
    application = webapp.WSGIApplication([
        ('/commit_viewer/', CommitQueryHandler),
        ('/commit_viewer/(.*)', CommitDisplayHandler),
    ], debug=True)
    webapp_util.run_wsgi_app(application)

if __name__ == '__main__':
    main_func()


# -*- coding: utf-8 -*-
"""
Created on Fri Apr  1 13:32:06 2016

@author: jmwilson
@co-author: mark yoder
#
# comments (yoder): we'll need to code this for Python3 compatibility.
#    ... and i'd rewrite some of this to separate code from data.
#
######           Obsolete, use etas_to_gmp.py instead             ######
"""

import numpy as np
import math
import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
import time
import multiprocessing as mpp
import os
import sys
#
import rtree
from rtree import index
#from geographiclib.geodesic import Geodesic
#
# define the color-cycle for fancy plotting:
_colors =  mpl.rcParams['axes.color_cycle']
#
#==============================================================================
# Extended Magnitude range attenuation relationships for S-wave horizontal acceleration
#               a       b           c 1     c 2     d       e           sig
# PGA   rock    0.73    -7.2x10-4   1.16    0.96    -1.48   -0.42       0.31
#       soil    0.71    -2.38x10-3  1.72    0.96    -1.44   -2.45x10-2  0.33
# PGV   rock    0.86    -5.58x10-4  0.84    0.98    -1.37   -2.58       0.28
#       soil    0.89    -8.4x10-4   1.39    0.95    -1.47   -2.24       0.32
#==============================================================================
#R1 = np.sqrt(R**2+9)
#C = c1*exp(c2*(M-5))*(np.arctan(M-5)+np.pi/2.0)
#Y = 10**(a*M + b*(R1 + C) + d*np.log10(R1 + C) + e)
#
#motion_type_prams = {'PGA-rock':{'a':0.73, 'b':-7.2e-4, 'c1':1.16, 'c2':0.96, 'd':-1.48, 'e':-0.42}, ...}
# but i'm lazier than that too, and i want to minimize mistakes made by mistyping a variable, so let's code it...
motion_type_prams_lst_vars = ['a', 'b', 'c1', 'c2', 'd', 'e']
motion_type_prams_lst = {'PGA-rock':[0.73, -7.2e-4, 1.16, 0.96, -1.48, -0.42],
                     'PGA-soil':[0.71, -2.38e-3, 1.72, 0.96, -1.44, -2.45e-2],
                     'PGV-rock':[0.86, -5.58e-4, 0.84, 0.98, -1.37, -2.58],
                     'PGV-soil':[0.89, -8.4e-4, 1.39, 0.95, -1.47, -2.24]}
motion_type_prams = {key:{ky:vl for ky,vl in zip(motion_type_prams_lst_vars, vals)} for key,vals in motion_type_prams_lst.items()}
#print('mtp: ', motion_type_prams)

def f_Y(R,M, a=None, b=None, c1=None, c2=None, d=None, e=None, motion_type='PGA-soil'):
	# experimenting a bit with this quasi-recursive call structure. this approach might be slow, and maybe we should just separate this into
	# two separate functions.
	# from original implementation; Y() should (nominally) look like this:
	# return 10**(a*M + b*(np.sqrt(R**2+9) + C(M, c1, c2)) + d*np.log10(np.sqrt(R**2+9) + C(M, c1, c2)) + e)
	if motion_type!=None:
		return f_Y(R,M, motion_type=None, **motion_type_prams[motion_type])
	else:
		return 10**(a*M + b*(np.sqrt(R**2+9) + C(M, c1, c2)) + d*np.log10(np.sqrt(R**2+9) + C(M, c1, c2)) + e)
		# it might be a little bit faster to calculate it this way:
		#return (10**(a*M + b*(np.sqrt(R**2+9) + C(M, c1, c2)) + e)) * (np.sqrt(R**2+9) + C(M, c1, c2))**d

def C(M, c1, c2):
    return c1*np.exp(c2*(M-5))*(np.arctan(M-5)+np.pi/2.0)
#
# ... but let's do this a different way as well. let's separate data from code, so put this into a dictionary (which is then a global
# variable, but that's ok... we can use a couple of trick, then, to pull the variables out into function calls. we can use,
# __dict__.update(motion_type_prams[mt]) to set local variables, or we can calla funciton like f(**motion_type_prams[mt]).

def Y(R, M, motiontype):
    if motiontype == "PGA-rock":
        a = 0.73
        b = -7.2e-4
        c1 = 1.16
        c2 = 0.96
        d = -1.48
        e = -0.42
    elif motiontype == "PGA-soil":
        a = 0.71
        b = -2.38e-3
        c1 = 1.72
        c2 = 0.96
        d = -1.44
        e = -2.45e-2
    elif motiontype == "PGV-rock":
        a = 0.86
        b = -5.58e-4
        c1 = 0.84
        c2 = 0.98
        d = -1.37
        e = -2.58
    elif motiontype == "PGV-soil":
        a = 0.89
        b = -8.4e-4
        c1 = 1.39
        c2 = 0.95
        d = -1.47
        e = -2.24
    else:
        print("Motion Type not recognized\n")
        return 0

    return 10**(a*M + b*(np.sqrt(R**2+9) + C(M, c1, c2)) + d*np.log10(np.sqrt(R**2+9) + C(M, c1, c2)) + e)
#
def etas_to_GM(etas_src='../globalETAS/etas_outputs/etas_xyz.xyz', fname_out='GMPE_rec.p', motion_type='PGA-soil', n_procs=None):
	# "ETAS to Ground-Motion:
	#xyz = open('../globalETAS/etas_outputs/etas_xyz.xyz', 'r')
	n_procs=(n_procs or mpp.cpu_count())
	#
	#
	print('open etas_src file: ', etas_src)
	#
	with open(etas_src, 'r') as xyz:
		# i don't know why, except maybe because it does handle exceptions/crashes before the file is closed, but this
		# "open()" syntax seems to be recommended over open(), close() implicit blocks.
		#
		ETAS_array = []
		GMPE_array = []
		#
		#ETAS_array = [[float(x), float(y), float(z)] for x,y,z in xyz]
		ETAS_array = [[float(x) for x in rw.split()] for rw in xyz if not rw[0] in ('#', chr(32), chr(10), chr(13), chr(9))]
		#
	#
	GMPE_array = [[x,y,0.] for x,y,z in ETAS_array]
	lons = sorted(list(set([x for x,y,z in ETAS_array])))
	lats = sorted(list(set([y for x,y,z in ETAS_array])))
	#
		#xyz.close()
	#
	print('etas_src loaded. load data into arrays and process.')
	#
	# this syntax burns memory and time, which will become important later. instead of x.transopse(), we can use zip(*x)... unless
	# it is otherwise known that zip(*x) is slow.
	#ETAS_array = np.array(ETAS_array)
	#ETAS_rec = np.core.records.fromarrays(ETAS_array.transpose(), dtype = [('x', '>f8'), ('y', '>f8'), ('z', '>f8')])
	ETAS_rec = np.core.records.fromarrays(zip(*ETAS_array), dtype = [('x', '>f8'), ('y', '>f8'), ('z', '>f8')])
	#
	# so what are the parameters? for now, assume we have a rectangular grid;
	# define parameters from which to construct a GMPE array.
	d_lon = lons[1]-lons[0]
	d_lat = lats[1]-lats[0]		# maybe need something more robust than this, but it should do...
	lon_range = (min(lons), max(lons)+d_lon, d_lon)
	lat_range = (min(lats), max(lats)+d_lat, d_lat)
	#GMPE_array = np.array(GMPE_array)
	#GMPE_rec = np.core.records.fromarrays(GMPE_array.transpose(), dtype = [('x', '>f8'), ('y', '>f8'), ('z', '>f8')])
	#GMPE_rec = np.core.records.fromarrays(zip(*GMPE_array), dtype = [('x', '>f8'), ('y', '>f8'), ('z', '>f8')])
	#
	l_etas = len(ETAS_rec)
	#
	t0 = time.time()
	# how do we parallelize this? i think first, we want to use iterools(), so we can break up the whole nested loop into one list.
	# we can avoid doing extra arithmetic by doing the round() operations first -- loop over [[round(x), round(y), z], ...]
	# and calc the source magnitude, again, in the first loop  over the ETAS array. at that point, all the rows are independent and
	# we can parse them out to processes.
	#
	m_reff=0.
	#
	if n_procs>1:
		#
		# multi-process.
		P = mpp.Pool(n_procs)
		#
		#we want to construct the GMP_{sub}_arrays at the process level, so we don't have to pipe the whole array to the process.
		# note: the [[x,y], ...] part of the array is like:
		# [[x,y] for x,y in itertools.product(np.arange(*lon_range), np.arange(*lat_range))]
		#
		#
		# so we'll need to write calc_gmps() (aka, copy the single process bit).
		chunk_size = int(np.ceil(l_etas/n_procs))		# "chunk" size, or length of sub-arrays for parallel processing.

		resultses = [P.apply_async(calc_GMPEs, (), {'ETAS_rec':ETAS_rec[j_p*chunk_size:(j_p+1)*chunk_size], 'lon_range':lon_range, 'lat_range':lat_range, 'm_reff':5.0, 'just_z':True}) for j_p in range(n_procs)]

		P.close()
		#
		# not sure of this syntax just yet. it is admittedly a little bit convoluted. it might be better to just suck it up and
		# do an extra loop through the array: set up the zero-value initial array, then add all the returns. here, we're trying to
		# squeeze out a little bit of performance by setting up the array and the first results simultaneously.
		GMP_rec = np.core.records.fromarrays(zip(*[[x,y,z] for (x,y),z in zip(itertools.product(np.arange(*lon_range), np.arange(*lat_range)), resultses[0].get())]), dtype = [('x', '>f8'), ('y', '>f8'), ('z', '>f8')])
		for j,res in enumerate(resultses[1:]):
			GMPE_rec['z']+=np.array(res.get()['z'])
			pass
		#
		# look in vc_parser for proper syntax using Pool() objects with close() and join().
		#P.join()
	#
	if n_procs==1:
		GMPE_rec = calc_GMPEs(ETAS_rec=ETAS_rec, lat_range=None, lon_range=None)
		'''
		j_prev=0
		for (j, (lon1, lat1, z_e)), (k, (lon2, lat2, z_g)) in itertools.product(enumerate(ETAS_rec), enumerate(GMPE_rec)):
			# M=rate_to_m(z_e)
			if j!=j_prev:
				print('new row: ', j)
				j_prev=j
			#
			M = m_from_rate(z_e, m_reff)
			#M = 2.0
			#
			distance = spherical_dist(lon_lat_from=[lon1, lat1], lon_lat_to=[lon2, lat2])
			#g = Geodesic.WGS84.Inverse(lat1, lon1, lat2, lon2)
			#distance = g['s12']
			#
			#S_Horiz_Soil_Acc = Y(distance, M, "PGA-soil")
			S_Horiz_Soil_Acc = f_Y(distance, M, motion_type)
			GMPE_rec['z'][k] = max(GMPE_rec['z'][k], S_Horiz_Soil_Acc)
		#
		'''
		#
		'''
		for j,line1 in enumerate(ETAS_rec):
			lon1 = round(line1['x'],1)
			lat1 = round(line1['y'],1)
			M = #TODO: Mapping from ETAS rate to source magnitude, we might need data for each region's background seismicity
			M=2.0
			print('line: %d/%d' % (j,l_etas))
			#
			for i, line2 in enumerate(GMPE_rec):
				lon2 = round(line2['x'],1)
				lat2 = round(line2['y'],1)
				#
				# geographic_lib distances can be expensive, so let's try this spherical formula for starters...
				#spherical_dist(lon_lat_from=[0., 0.], lon_lat_to=[0.,0.], Rearth = 6378.1):
				distance = spherical_dist(lon_lat_from=[lon1, lat1], lon_lat_to=[lon2, lat2])
				#g = Geodesic.WGS84.Inverse(lat1, lon1, lat2, lon2)
				#distance = g['s12']
				#
				#S_Horiz_Soil_Acc = Y(distance, M, "PGA-soil")
				S_Horiz_Soil_Acc = f_Y(distance, M, motion_type)
				#
				GMPE_rec[i]['z'] = max(GMPE_rec[i]['z'], S_Horiz_Soil_Acc)
			'''
	#
	t1 = time.time()
	print(t1 - t0)
	#
	GMPE_rec.dump(fname_out)
#

def calc_GMPEs(ETAS_rec=None, lat_range=None, lon_range=None, m_reff=5.0, motion_type="PGA-soil", just_z=False):
	# what is the correct syntax to return a subset of columns of a recarray? (the fastest way, of course)?
	#
	# construct GMP array and calculate GM from ETAS. this function to be used as an mpp.Pool() worker.
	#GMPE_rec =[[x,y,0.] for x,y in itertools.product(np.arange(*lon_range), np.arange(*lat_range))]	# check these for proper
	#
	# create an empty GMPE array.																		# sequenceing and grouping.
	GMPE_rec = np.core.records.fromarrays(zip(*[[x,y,0.] for x,y in itertools.product(np.arange(*lon_range), np.arange(*lat_range))]), dtype = [('x', '>f8'), ('y', '>f8'), ('z', '>f8')])
	#GMPE_rec = np.core.records.fromarrays(zip(*GMPE_array), dtype = [('x', '>f8'), ('y', '>f8'), ('z', '>f8')])
	#
	j_prev=0
	for (j, (lon1, lat1, z_e)), (k, (lon2, lat2, z_g)) in itertools.product(enumerate(ETAS_rec), enumerate(GMPE_rec)):
		# M=rate_to_m(z_e)
		if j!=j_prev:
			print('new row[{}]: {}'.format(os.getpid(), j))
			j_prev=j
		#
		M = m_from_rate(z_e, m_reff)
		#M = 2.0
		#
		#distance = spherical_dist(lon_lat_from=[lon1, lat1], lon_lat_to=[lon2, lat2])

		distance = spherical_dist(lon_lat_from=[ETAS_rec['lon'][0], ETAS_rec['lat'][0]], lon_lat_to=[lon2, lat2])

		#g = Geodesic.WGS84.Inverse(lat1, lon1, lat2, lon2)
		#distance = g['s12']
		#
		#S_Horiz_Soil_Acc = Y(distance, M, "PGA-soil")
		S_Horiz_Soil_Acc = f_Y(distance, M, motion_type)
		#S_Horiz_Siol_Acc = 1.0/(10.+distance)
		#
		#GMPE_rec['z'][k] = max(GMPE_rec['z'][k], S_Horiz_Soil_Acc)
		GMPE_rec['z'][k] = max(z_g, S_Horiz_Soil_Acc)
		#GMPE_rec['z'][k] += S_Horiz_Soil_Acc
	#
	if just_z:
		return GMP_rec['z']
	else:
		return GMPE_rec

#
def calc_GMPE(lon1, lat1, lon2, lat2, z_etas, m_reff):
	m_reff=0.
	M = m_from_rate(z_e, m_reff)
	#M = 2.0
	#
	distance = spherical_dist(lon_lat_from=[lon1, lat1], lon_lat_to=[lon2, lat2])
	#g = Geodesic.WGS84.Inverse(lat1, lon1, lat2, lon2)
	#distance = g['s12']
	#
	S_Horiz_Soil_Acc = f_Y(distance, M, motion_type)
	GMPE_rec['z'][k] = max(GMPE_rec['z'][k], S_Horiz_Soil_Acc)

def m_from_rate(rate=None, m_reff=0.):
	# compute a source magnitude based on ETAS rate and a reference magnitude (or something).
	#
	# but for now, just a constant
	return 2.0
#
def spherical_dist(lon_lat_from=[0., 0.], lon_lat_to=[0.,0.], Rearth = 6378.1):
	# Geometric spherical distance formula...
	# displacement from inloc...
	# inloc is a vector [lon, lat]
	# return a vector [dLon, dLat] or [r, theta]
	# return distances in km.
	#
	# also, we need to get the proper spherical angular displacement (from the parallel)
	#
	#Rearth = 6378.1	# km
	deg2rad=2.0*math.pi/360.
	#
	# note: i usually use phi-> longitude, lambda -> latitude, but at some point i copied a source where this is
	# reversed. oops. so just switch them here.
	# phi: latitude
	# lon: longitude
	#
	#phif  = inloc[0]*deg2rad
	#lambf = inloc[1]*deg2rad
	#phis  = self.loc[0]*deg2rad
	#lambs = self.loc[1]*deg2rad

	phif  = lon_lat_to[1]*deg2rad
	lambf = lon_lat_to[0]*deg2rad
	phis  = lon_lat_from[1]*deg2rad
	lambs = lon_lat_from[0]*deg2rad
	#
	#print ('phif: ', phif)
	#print('lambf: ', lambf)
	#
	dphi = (phif - phis)
	dlambda = (lambf - lambs)
	#this one is supposed to be bulletproof:
	sighat3 = math.atan( math.sqrt((math.cos(phif)*math.sin(dlambda))**2.0 + (math.cos(phis)*math.sin(phif) - math.sin(phis)*math.cos(phif)*math.cos(dlambda))**2.0 ) / (math.sin(phis)*math.sin(phif) + math.cos(phis)*math.cos(phif)*math.cos(dlambda))  )
	R3 = Rearth * sighat3
	#
	return R3

# yoder: let's code this up for both command line and interactive use:
if __name__=='__main__':
	#
	kwds={}
	pargs=[]		# poositional arguments.
	for arg in sys.argv[1:]:
		# assume some mistakes might be made. fix them here.
		arg.replace(',', '')
		#
		# note: module name is the first argument.
		if '=' in arg:
			kwds.update(dict([arg.split('=')]))
		else:
			pargs+=[arg]
		#
	#
	# enforce float types:
	#kwds = {key:float(val) for key,val in kwds.items()}
	#pargs = [float(x) for x in pargs]
	#
	X=etas_to_GM(*pargs, **kwds)
else:
	plt.ion()
	pass
#


if __name__ == '__main__':
    n = input()
    arr = n.split(' ')
    arr = [int(num) for num in arr]     #convert list elements to int

    sorted(arr)
    for num in arr:         #check for duplicates
        if arr[num] == arr[num-1]:
            arr.pop(num)

    print(arr)


class Page(object):
    def __init__(self, chinese, answer, hint='', error_count_before_hint=2, show_survey=0):
        self.chinese = chinese
        self.answer = answer
        self.error_count_before_hint = error_count_before_hint
        self.hint = hint
        self.show_survey = show_survey
        self.is_test = is_test
        self.marker_data = marker_data

PAGES = [
    Page('红', 'red', hint='红 = red'),
    Page('黄', 'yellow', hint='黄 = yellow'),
    Page('红', 'red'),
    Page('黄', 'yellow'),
    Page('红', 'red'),
    Page('黄', 'yellow'),
    Page('红', 'red'),
    Page('黄', 'yellow'),
    Page('红', 'red'),
    Page('黄', 'yellow', show_survey=1),

    Page('黑', 'black', hint='黑 = black'),
    Page('橙', 'orange', hint='橙 = orange'),
    Page('棕', 'brown', hint='棕 = brown'),
    Page('粉', 'pink', hint='粉 = pink'),
    Page('白', 'white', hint='白 = white'),
    Page('白 棕 粉', 'white brown pink'),
    Page('橙 绿 蓝', 'orange green blue'),
    Page('黑 红 粉', 'black red pink'),
    Page('紫 棕 蓝', 'purple brown blue'),
    Page('绿 黄 白', 'green yellow white', show_survey=3),
]

'''Page('绿', 'green', hint='绿 = green'),
    Page('绿', 'green'),
    Page('紫', 'purple', hint='紫 = purple'),
    Page('紫', 'purple'),
    Page('绿 紫', 'green purple'),
    Page('紫 绿', 'purple green'),
    Page('蓝', 'blue', hint='蓝 = blue'),
    Page('蓝', 'blue'),
    Page('蓝 绿', 'blue green'),
    Page('紫 蓝', 'purple blue', show_survey=2),'''


"""
This file contains the Support Vector Machine Classification functionality
"""
# region imports
from globals import console
from dataset import DatasetHandler

import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC

# endregion imports

# region SupportVectorClassification
class SupportVectorClassification(DatasetHandler):
    def __init__(self):
        super().__init__()
        self._classifier = None
        self._predicted_output = None
        self._selected_prediction_method = None

    def use_linear_kernel(self,
                          penalty_of_error=1,
                          probability=True,
                          maximum_number_of_iterations=20000):
        """
        This method uses the linear classification method of the Support Vector Machine

        :param penalty_of_error: (Number) The penalty parameter C of the error term. (Default: 1)
        :param probability: (Boolean) Whether to enable probability estimates. This must be enabled prior to calling
        fit, and will slow down that method. (Default: True)
        :param maximum_number_of_iterations: (Integer) Hard limit on iterations within solver, or -1 for no limit.
        (Default: 20000)
        :return: Boolean (True or False)
        """
        try:
            self._classifier = SVC(C=penalty_of_error,
                                   kernel='linear',
                                   probability=probability,
                                   max_iter=maximum_number_of_iterations)

            self._selected_prediction_method = 'linear'
            return True
        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False

    def use_polynomial_kernel(self, penalty_of_error=1, degree=3, gamma='auto'):
        """
        This method uses the polynomial classification method of the Support Vector Machine

        :param penalty_of_error: (Number) The penalty parameter C of the error term. (Default: 1)
        :param degree: (Integer) The degree of the polynomial (Default: 3)
        :param gamma: (Number) Kernel coefficient (Default: 'auto')
        :return: Boolean (True or False)
        """
        try:
            self._classifier = SVC(C=penalty_of_error,
                                   kernel='poly',
                                   degree=degree,
                                   gamma=gamma)

            self._selected_prediction_method = 'polynomial'
            return True
        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False

    def use_radial_basis_function_kernel(self, penalty_of_error=1, gamma='auto'):
        """
        This method uses the radial basic function classification method of the Support Vector Machine

        :param penalty_of_error: (Number) The penalty parameter C of the error term. (Default: 1)
        :param gamma: (Number) Kernel coefficient (Default: 'auto')
        :return: Boolean (True or False)
        """
        try:
            self._classifier = SVC(C=penalty_of_error,
                                   kernel='rbf',
                                   gamma=gamma)

            self._selected_prediction_method = 'radial_basis_function'
            return True
        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False

    def fit_svc_on_training_set(self):
        """
        This method is used on order to fit the "self._classifier" in the training set

        :return: Boolean (True or False)
        """
        try:
            self._classifier.fit(X=self.get_training_set()['X'],
                                 y=self.get_training_set()['y'])

            return True
        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False

    def fit_svc_on_whole_set(self):
        """
        This method is used on order to fit the "self._classifier" in the training set

        :return: Boolean (True or False)
        """
        try:
            self._classifier.fit(X=self.get_whole_set()['X'],
                                 y=self.get_whole_set()['y'])

            return True
        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False

    def get_classification_prediction(self, test_set=None):
        """
        This method predicts the classification of a set of data based on previous training

        :param test_set: (Array) The input variables state space (Default: The input variables from the test set)
        :return: (Array) The SVC predicted output
        """
        try:
            if test_set is not None:
                self._predicted_output = self._classifier.predict(X=test_set)
            else:
                self._predicted_output = self._classifier.predict(X=self.get_whole_set()['X'])

            return self._predicted_output
        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False

    def get_classification_prediction_probability(self, test_set=None):
        """
        This method compute probabilities of possible outcomes for samples in the test set

        :param test_set: (Array) The input variables state space (Default: The input variables from the test set)
        :return: (Array) The probabilities of possible outcomes from samples in the test set
        """
        try:
            if test_set is not None:
                return self._classifier.predict_proba(X=test_set)
            else:
                return self._classifier.predict_proba(X=self.get_test_set()['y'])

        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False

    def get_decision_function(self, test_set=None):
        """
        This method evaluates the decision function for the samples in the test set

        :param test_set: (Array) The input variables state space (Default: The input variables from the test set)
        :return: (Array) The SVC decision function
        """
        try:
            if test_set is not None:
                return self._classifier.decision_function(X=test_set)
            else:
                return self._classifier.decision_function(X=self.get_test_set()['X'])

        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False

    def plot_results(self, regressor='all', title=None, x_label=None, y_label=None):
        """
        This method plots the predicted data of the selected "self._classifier"

        :param regressor: (String) The regressor selected
        :param title: (String) The plot title (Default: No Title)
        :param x_label: (String) The X-Axis label (Default: No Label)
        :param y_label: (String) The Y-Axis label (Default: No Label)
        :return: Boolean (True or False)
        """
        try:
            plt.figure(1)
            plt.scatter(x=np.arange(self._whole_set['y'].size),
                        y=self._whole_set['y'],
                        color='red',
                        label='Real Data')

            plt.plot(self._predicted_output,
                     linestyle='-',
                     color='blue',
                     label=('Predicted Trend Using the \"%s\" classification method' %
                            str(self._selected_prediction_method))
                     )

            plt.grid(color='silver',
                     linestyle='--',
                     linewidth=1)

            plt.legend(loc='best')
            if title is not None and \
                    isinstance(title, str):
                plt.title(title)

            if x_label is not None and \
                    isinstance(x_label, str):
                plt.xlabel(x_label)

            if y_label is not None and \
                    isinstance(y_label, str):
                plt.ylabel(y_label)

            plt.show()
        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False

    def return_error(self, regressor='both'):
        """
        This method returns the error between the real output and the predicted output throwout the whole set

        :param regressor: (String) The regressor selected
        :return: (List) The error between the real output and the predicted output
        """
        try:
            error_value = np.square(
                self.get_whole_set()['y'] - self._predicted_output
            )

            if np.mean(error_value) != 0:
                error_value = np.interp(
                    np.mean(error_value),
                    (error_value.min(), error_value.max()),
                    (0, 100)
                )
            else:
                error_value = 0

            return {
                    'label': self._selected_prediction_method,
                    'value': error_value
            }

        except Exception as error_message:
            console.log(error_message, console.LOG_ERROR)
            return False
# endregion SupportVectorClassification

# region exports
support_vector_classification = SupportVectorClassification()
# endregion exports


# Dragon Realm
# A game by Amanda Huynh
# October 7, 2017

# import stuff
import random
import time

# Global Variables
score = 0

# Show Introduction
def show_intro():
    print('''You've lost your map and there seems to be
no trace of the merchant's caravan you stowed away on.
In one cave, the dragon is friendly
and will share his treasure with you. The other dragon is
greedy and hungry, and will eat you on site.''')
    print()

def choose_cave():
    cave = ""
    while cave != "1" and cave != "2":
        print("Which cave will you go into? (1 or 2)")
        cave = input()
    return cave

def check_cave(cave_chosen):
    global score
    print("You approach the mouth of the cave slowly...")
    time.sleep(2)
    print("You catch a whif of strong-smelling dung and rotten flesh ...")
    time.sleep(4)
    print("You walk deeper into the cave and see MAGNIFICENT piles of TREASUREEEE!!")
    time.sleep(4)
    print('''You jump around and scream for joy!
You grab handfuls of stolen treasure and stuff them into your pockets and bag.''')
    time.sleep(6)
    print()
    print("Suddenly, you hear loud thumps at the back of the cave. and freeze.")
    time.sleep(4)
    print('''You squint into the darkness and
simultaneously, the head of a dragon appears...''')
    time.sleep(4)
    print("You try to run away but trip over some metal objects.")
    time.sleep(4)
    print('''You scramble as quickly as possible away from the dragon
as it makes its way towards you.''')
    time.sleep(4)
    print("But...you are much too slow.")
    print('''The scaly dragon looms over you and stands up tall.
You watch in dread as the dragon opens its mouth, reveals its pointy teeth,
and...''')
    time.sleep(6)
    print()
    time.sleep(3)
    friendly_dragon = random.randint(1, 2)
    if cave_chosen == str(friendly_dragon):
        print("GIVES YOU A RIDE ON HIS BACK AND OFFERS ALL HIS TREASURES!")
        score += 1
        print()
        accept_treasure = random.randint(1, 2)
        print("You are offered all his treasures. Do you accept? (y or n)")
        while accept_treasure != "y" and accept_treasure != "n":
            accept_treasure = input()
        if accept_treasure == "y" and accept_treasure == y:
            print("So greedy!!")
        else:
            print("So generous!!")
    else:
        print("HE CHASES YOU AROUND, TRYING TO FART FIRE ON YOU!")
        dodge_fart = random.randint(1, 2)
        print("You try to escape his fiery fart. You jump...(l or r)")
        dodge_fart = input()
        if dodge_fart == "r" and dodge_fart == "r":
            print("You successfully escaped the fart!")
            print('''On the contrary, some of the shiny treasures in your pocket falls,
but at least you are alive.''')
        else:
            print("You got hit with the stinkest fart ever! You faint and never wake up!")
        dodge = input()
        if score >= 1:
            score -= 1

def play():
    stillPlaying = True
    while stillPlaying:
        show_intro()
        cave = choose_cave()
        check_cave(cave)
        print("Would you like to play again? (y to continue, q to quit)")
        choice = input()
        if choice == "q":
            stillPlaying = False
    print("Your score: " + str(score))
    print("Goodbye! Thanks for playin', naaamean?")

# Play the game!
play()


import bpy

from bl_ui.properties_material import MaterialButtonsPanel

class MATERIAL_PT_pr_context_material(MaterialButtonsPanel, bpy.types.Panel):
    bl_label = ""
    bl_options = {'HIDE_HEADER'}
    COMPAT_ENGINES = {'PEARRAY_RENDER'}

    @classmethod
    def poll(cls, context):
        # An exception, don't call the parent poll func because
        # this manages materials for all engine types

        engine = context.scene.render.engine
        return (context.material or context.object) and (engine in cls.COMPAT_ENGINES)

    def draw(self, context):
        layout = self.layout

        mat = context.material
        ob = context.object
        slot = context.material_slot
        space = context.space_data
        is_sortable = (len(ob.material_slots) > 1)

        if ob:
            rows = 1
            if is_sortable:
                rows = 4

            row = layout.row()

            row.template_list("MATERIAL_UL_matslots", "", ob, "material_slots", ob, "active_material_index", rows=rows)

            col = row.column(align=True)
            col.operator("object.material_slot_add", icon='ZOOMIN', text="")
            col.operator("object.material_slot_remove", icon='ZOOMOUT', text="")

            col.menu("MATERIAL_MT_specials", icon='DOWNARROW_HLT', text="")

            if is_sortable:
                col.separator()

                col.operator("object.material_slot_move", icon='TRIA_UP', text="").direction = 'UP'
                col.operator("object.material_slot_move", icon='TRIA_DOWN', text="").direction = 'DOWN'

            if ob.mode == 'EDIT':
                row = layout.row(align=True)
                row.operator("object.material_slot_assign", text="Assign")
                row.operator("object.material_slot_select", text="Select")
                row.operator("object.material_slot_deselect", text="Deselect")

        split = layout.split(percentage=0.65)

        if ob:
            split.template_ID(ob, "active_material", new="material.new")
            row = split.row()

            if slot:
                row.prop(slot, "link", text="")
            else:
                row.label()
        elif mat:
            split.template_ID(space, "pin_id")
            split.separator()

class MATERIAL_PT_pr_preview(MaterialButtonsPanel, bpy.types.Panel):
    bl_label = "Preview"
    COMPAT_ENGINES = {'PEARRAY_RENDER'}

    def draw(self, context):
        self.layout.template_preview(context.material)

class MATERIAL_PT_pr_bsdf(MaterialButtonsPanel, bpy.types.Panel):
    bl_label = "BSDF"
    COMPAT_ENGINES = {'PEARRAY_RENDER'}

    @classmethod
    def poll(cls, context):
        engine = context.scene.render.engine
        return context.material and (engine in cls.COMPAT_ENGINES)

    def draw(self, context):
        layout = self.layout

        mat = context.material
        type = mat.pearray.bsdf

        split = layout.split()

        col = split.column()
        col.prop(mat.pearray, "bsdf")

        split = col.split()
        col = split.column()
        col.prop(mat.pearray, "cast_shadows")
        col.prop(mat.pearray, "cast_self_shadows")

        col = split.column()
        col.prop(mat.pearray, "is_camera_visible")
        col.prop(mat.pearray, "is_shadeable")

        if type == 'COOK_TORRANCE':
            layout.separator()
            split = layout.split()
            col = split.column(align=True)
            col.prop(mat.pearray, "ct_fresnel_mode")
            col.prop(mat.pearray, "ct_distribution_mode")
            col.prop(mat.pearray, "ct_geometry_mode")

class MATERIAL_PT_pr_diffuse(MaterialButtonsPanel, bpy.types.Panel):
    bl_label = "Diffuse"
    COMPAT_ENGINES = {'PEARRAY_RENDER'}

    @classmethod
    def poll(cls, context):
        engine = context.scene.render.engine
        return context.material and (context.material.pearray.bsdf in {'DIFFUSE', 'ORENNAYAR', 'WARD', 'COOK_TORRANCE'}) and (engine in cls.COMPAT_ENGINES)

    def draw(self, context):
        layout = self.layout

        mat = context.material
        type = mat.pearray.bsdf

        split = layout.split()

        col = split.column()
        color_template(mat, col, "diffuse_color")
        if type == 'ORENNAYAR' or type == 'COOK_TORRANCE':
            col.prop(mat, 'roughness')

class MATERIAL_PT_pr_grid(MaterialButtonsPanel, bpy.types.Panel):
    bl_label = "Grid"
    COMPAT_ENGINES = {'PEARRAY_RENDER'}

    @classmethod
    def poll(cls, context):
        engine = context.scene.render.engine
        return context.material and (context.material.pearray.bsdf == 'GRID') and (engine in cls.COMPAT_ENGINES)

    def draw(self, context):
        layout = self.layout

        mat = context.material
        type = mat.pearray.bsdf

        split = layout.split()

        col = split.column()

class MATERIAL_PT_pr_specular(MaterialButtonsPanel, bpy.types.Panel):
    bl_label = "Specular"
    COMPAT_ENGINES = {'PEARRAY_RENDER'}

    @classmethod
    def poll(cls, context):
        engine = context.scene.render.engine
        return context.material and (context.material.pearray.bsdf in {'GLASS', 'MIRROR', 'WARD', 'COOK_TORRANCE'}) and (engine in cls.COMPAT_ENGINES)

    def draw(self, context):
        layout = self.layout

        mat = context.material
        type = mat.pearray.bsdf

        split = layout.split()

        col = split.column()
        color_template(mat, col, "specular_color")
        if type == 'MIRROR' or type == 'GLASS' or type == 'COOK_TORRANCE':
            ior_template(mat, col, "specular_ior")
        if type == 'WARD' or type == 'COOK_TORRANCE':
            col2 = col.column(align=True)
            col2.prop(mat.pearray, 'spec_roughness_x')
            col2.prop(mat.pearray, 'spec_roughness_y')
            col.prop(mat.pearray, 'reflectivity')
        if type == 'GLASS':
            col.prop(mat.pearray, 'glass_is_thin')

class MATERIAL_PT_pr_emission(MaterialButtonsPanel, bpy.types.Panel):
    bl_label = "Emission"
    COMPAT_ENGINES = {'PEARRAY_RENDER'}

    @classmethod
    def poll(cls, context):
        engine = context.scene.render.engine
        return context.material and (not context.material.pearray.bsdf == 'GRID') and (engine in cls.COMPAT_ENGINES)

    def draw(self, context):
        layout = self.layout

        mat = context.material
        type = mat.pearray.bsdf

        split = layout.split()

        col = split.column()
        color_template(mat, col, "emission_color")

def color_template(obj, layout, name):
    sub_obj = obj
    if not hasattr(obj, name):
        sub_obj = obj.pearray

    type = getattr(obj.pearray, '%s_type' % name)

    col = layout.column(align=True)
    col.row(align=True).prop(obj.pearray, '%s_type' % name, expand=True)
    if type == 'TEMP':
        r = col.row(align=True)
        r.prop(obj.pearray, '%s_temp_type' % name, text="")
        r.prop(obj.pearray, '%s_temp_factor' % name, text='Factor')
        col.prop(obj.pearray, '%s_temp' % name, text="")
    elif type == 'TEX' and hasattr(obj.pearray, '%s_tex_slot' % name):
        col.prop(obj.pearray, '%s_tex_slot' % name)
    else:
        col.prop(sub_obj, name, text="")

def ior_template(obj, layout, name):
    sub_obj = obj
    if not hasattr(obj, name):
        sub_obj = obj.pearray

    type = getattr(obj.pearray, '%s_type' % name)

    col = layout.column(align=True)
    col.row(align=True).prop(obj.pearray, '%s_type' % name, expand=True)
    if type == 'VALUE':
        col.prop(obj.pearray, '%s_value' % name, text="Ior")
    else:
        col.prop(obj.pearray, '%s_color' % name, text="Ior")


"""OpenAPI specific loader behavior."""
import json

import pytest

from schemathesis.specs.openapi import loaders
from schemathesis.specs.openapi.schemas import OpenApi30, SwaggerV20

def test_openapi_asgi_loader(fastapi_app, run_asgi_test):
    # When an ASGI app is loaded via `from_asgi`
    schema = loaders.from_asgi("/openapi.json", fastapi_app)
    strategy = schema["/users"]["GET"].as_strategy()
    # Then it should successfully make calls via `call_asgi`
    run_asgi_test(strategy)

def test_openapi_wsgi_loader(flask_app, run_wsgi_test):
    # When a WSGI app is loaded via `from_wsgi`
    schema = loaders.from_wsgi("/schema.yaml", flask_app)
    strategy = schema["/success"]["GET"].as_strategy()
    # Then it should successfully make calls via `call_wsgi`
    run_wsgi_test(strategy)

@pytest.mark.parametrize(
    "version, expected",
    (
        ("20", SwaggerV20),
        ("30", OpenApi30),
    ),
)
def test_force_open_api_version(version, expected):
    schema = {
        # Invalid schema, but it happens in real applications
        "swagger": "2.0",
        "openapi": "3.0.0",
    }
    loaded = loaders.from_dict(schema, force_schema_version=version, validate_schema=False)
    assert isinstance(loaded, expected)

def test_number_deserializing(testdir):
    # When numbers in a schema are written in scientific notation but without a dot
    # (achieved by dumping the schema with json.dumps)
    schema = {
        "openapi": "3.0.2",
        "info": {"title": "Test", "description": "Test", "version": "0.1.0"},
        "paths": {
            "/teapot": {
                "get": {
                    "summary": "Test",
                    "parameters": [
                        {
                            "name": "key",
                            "in": "query",
                            "required": True,
                            "schema": {"type": "number", "multipleOf": 0.00001},
                        }
                    ],
                    "responses": {"200": {"description": "OK"}},
                }
            }
        },
    }

    schema_path = testdir.makefile(".yaml", schema=json.dumps(schema))
    # Then yaml loader should parse them without schema validation errors
    parsed = loaders.from_path(str(schema_path))
    # and the value should be a number
    value = parsed.raw_schema["paths"]["/teapot"]["get"]["parameters"][0]["schema"]["multipleOf"]
    assert isinstance(value, float)

def test_unsupported_type():
    # When Schemathesis can't detect the Open API spec version
    with pytest.raises(ValueError, match="^Unsupported schema type$"):
        # Then it raises an error
        loaders.from_dict({})


from flask import Flask, render_template, request
from sense_hat import SenseHat
import firebase_admin
from firebase_admin import credentials, firestore

COLLECTION = 'raspberry'

DOCUMENT = 'lector-pi'

cred = credentials.Certificate("../config/labo-i-firebase-adminsdk-nr652-7d2e873b71.json")

firebase_admin.initialize_app(cred)

# sensehat
sense = SenseHat()
sense.set_imu_config(False, False, False)
sense.clear()

def update_sensehat(doc_snapshot, changes, read_time):
    for doc in doc_snapshot:
        doc_readable = doc.to_dict()
        print(doc_readable)

# connect firestore
db = firestore.client()
pi_ref = db.collection(COLLECTION).document(DOCUMENT)
pi_watch = pi_ref.on_snapshot(update_sensehat)

# app
while True:
    pass


import tensorflow_addons as tfa

class CRF:
    def __init__(self,
                 units,
                 sparse_target=True,
                 input_dim=None,
                 **kwargs):
        self.units = units
        self.sparse_target = sparse_target
        self.input_dim = input_dim
        self.kwargs = kwargs

    def build_layers(self):
        layers = []
        layer = tfa.layers.CRF(units=self.units, sparse_target=self.sparse_target, input_dim=self.input_dim, **self.kwargs)
        layers.append(layer)

        return layers

if __name__ == "__main__":
    agent = CRF(10)
    crf = agent.build_layers()


import random
import sys

def RPS():
    while True:
        play = input("Choose your play: Rock, Paper or Scissors ? ")
        a=['Rock','Paper','Scissors']
        if play != 'Rock' and play != 'Paper' and play != 'Scissors':
            print("Invalid choice. Please write your choice again.")
            continue
        b=random.choice(a)
        print(b)
        if play == b:
            print ("Draw!")
        else:
            for i in a:
                if i == play and b == a[(a.index(i)-1) % len(a)]:
                    print ("Congratulations! You won! ")
                    break
                elif i==play and b == a[(a.index(i)+1) % len(a)]:
                    print ("Sorry! You lost.")
                    break
        while True:
            next = input("Do you want to play again? Y/N ")
            if next == 'Y':
                RPS()
            elif next == 'N':
                sys.exit()
            else:
                print("Invalid choice. Please write your choice again.")
                continue
RPS()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def _odd_iter(max_num):
    n = 1
    while n + 2 < max_num:
        n = n + 2
        yield n

def _not_divisible(n):
    return lambda x: x % n > 0

def primes(max_num):
    yield 2
    it = _odd_iter(max_num)  # 初始序列
    while True:
        num = next(it)  # 返回序列的第一个数
        yield num
        it = iter(filter(_not_divisible(num), it))  # 构造新序列

# 打印1000以内的素数:
for n in primes(1000):
    print(n)


# coding: utf-8

# # Lyrics Indexing

# ## Imports

import pymongo
import time
import queue
import threading
import sys

# ## DB Connection

DB_IPHOST = sys.argv[1]
DB_NAME = sys.argv[2]

# Create a MongoDB connection to a specific database
ir_db = pymongo.MongoClient(host=DB_IPHOST)[DB_NAME]

# Connect to collections
songs_tokenized_cleaned = ir_db['songs_tokenized_cleaned']

# Create a new collection
songs_tf = ir_db['songs_tf']

# ## Indexing

# Use mulithreading to accelerate the work of indexing of every lyrics in the collection

def worker():
    while True:
        item = q.get()
        if item is None:
            break
        do_work(item)
        q.task_done()

def do_work(item):
    s_doc = indexing_song(item)
    if s_doc != None:
        songs_docs.append(s_doc)

def indexing_song(song):
    """
    :param song: single song document, taken from a previously filled queue
    :return s_doc: document of a single song, containing also tf for every token
    """

    # single song document
    s_doc = song
    tokens_dicts = song["tokens"]
    td_new = []

    id = s_doc['_id']

    doc_len = len(tokens_dicts)
    if doc_len == 0:
        return None

    # for every token, retrieve the idf, and calculate the tf*idf
    for td in tokens_dicts:
        n_occ = td['count']
        tf_value = n_occ / doc_len
        tok = td['token']

        td_new.append({
            'pos': td['position'],
            'token': td['token'],
            'tf': tf_value})

    # Replacing tokens to the original document
    s_doc.update({"tokens": td_new})
    return s_doc

# ## Quering the DB to retrieve the songs

# create a shared queue for all songs
q = queue.Queue()

songs_docs = []

cursor = songs_tokenized_cleaned.find()
for song in cursor:
    # adding the song to the queue
    q.put(song)

number_of_songs = q.qsize()

print('Number of songs in db: ' + str(number_of_songs))

# create a fixed number of threads
threads = []
num_worker_threads = 60

for i in range(num_worker_threads):
    t = threading.Thread(target=worker)
    # every thread reads from the queue and appends documents
    t1 = time.time()
    t.start()
    threads.append(t)

# stop workers
for i in range(num_worker_threads):
    q.put(None)
for t in threads:
    t.join()

t2 = time.time()
print('Total time: ' + str(t2 - t1) + ' seconds')

# ## Creating a new collection in DB

# Write on the new collection in mongoDB
songs_tf.insert_many(songs_docs)

# One example from this new collection:
#
# ```json
# {
# 	"_id" : ObjectId("582c44314efcb1d1af6f7ace"),
# 	"title" : "On A Little Street In Singapore",
# 	"language" : "English",
# 	"tokens" : [
# 		{
# 			"pos" : 0,
# 			"token" : "on",
#  			"tf" : 0.045454545454545456
# 		},
# 		{
# 			"pos" : 1,
# 			"token" : "little",
# 			"tf" : 0.045454545454545456
# 		},
#       ...
# 	],
# 	"url" : "http://lyrics.wikia.com/wiki/Glenn_Miller:On_A_Little_Street_In_Singapore\n",
# 	"lyrics" : "On a little street in Singapore\nWe'd meet beside a lotus-covered door\nA veil of moonlight on a lonely face\nHow pale the hands that held me in embrace\n\nMy sails tonight are filled with perfume of Shalimar\nAnd temple bells will guide me to the shore\nAnd then I'll hold her in my arms\nAnd love the way I loved before\nOn a little street in Singapore...\n",
# 	"album" : "",
# 	"artist" : "Glenn Miller"
# }
# ```


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

import sys
import os
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QPushButton, QHBoxLayout, QVBoxLayout, QWidget, QTabWidget, QMenuBar, QLineEdit, QSlider, QLabel, QCheckBox, QComboBox
from simulation import *
from buffer import *
from random_pattern import *
import multiprocessing
import signal

from PyQt5.QtGui import QIcon

class Form(QMainWindow):
    def __init__(self):
        super(Form, self).__init__()
        self.initialize()
        self.t = None

    def start_simulation(self):

        if self.enable_random_cb.isChecked():
            dist_text = self.distribution.currentText()
            dist = "u"
            if dist_text == "Geometric":
                dist = "g"
            if self.number_of_balls.text() == '' or self.max_throw.text() == '' or self.min_throw == '':
                print("invalid input!")
                return
            random_pattern = RandomPattern(int(self.number_of_balls.text()), int(self.min_throw.text()), int(self.max_throw.text()), dist_type=dist)
            buffer = Buffer(random_pattern)
            simulation = Simulation(buffer)
            self.t = multiprocessing.Process(target=simulation.run)
            self.t.daemon = True
            self.t.start()
        else:
            text = str(self.pattern.text())
            if not len(text) > 0:
                return
            p = [int(e) for e in text.split(" ")]
            if p != None:
                s = Pattern(p)
                buffer = Buffer(s)
                simulation = Simulation(buffer)
                self.t = multiprocessing.Process(target=simulation.run)
                self.t.daemon = True
                self.t.start()

    def restart_simulation(self):
        if self.t.is_alive():
            os.kill(self.t.pid, signal.SIGINT)
        #the simulation should be restarted here
        #self.start_simulation()

    def initialize(self):
        self.tab_widget = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()

        self.juggle_button = QPushButton("Juggle")
        #restart_button = QPushButton("Restart")
        self.juggle_button.clicked.connect(self.start_simulation)
        #restart_button.clicked.connect(self.restart_simulation)

        self.hbox = QHBoxLayout()
        self.hbox3 = QVBoxLayout()
        self.min_throw = QLineEdit(self)
        self.max_throw = QLineEdit(self)
        self.pattern = QLineEdit(self)
        self.number_of_balls = QLineEdit(self)
        self.min_label = QLabel(self)
        self.max_label = QLabel(self)
        self.pattern_label = QLabel(self)
        self.number_of_balls_label = QLabel(self)
        self.enable_random_cb = QCheckBox("Enable random pattern", self)
        self.distribution = QComboBox(self)
        self.distribution_label = QLabel(self)
        self.distribution.addItem("Uniform")
        self.distribution.addItem("Geometric")

        self.min_label.setText("min throw")
        self.max_label.setText("max throw")
        self.number_of_balls_label.setText("number of balls")
        self.pattern_label.setText("Pattern (only used if random pattern is not enabled)")
        self.distribution_label.setText("Distribution for the random pattern")

        self.hbox3.addWidget(self.min_label)
        self.hbox3.addWidget(self.min_throw)
        self.hbox3.addStretch(1)
        self.hbox3.addWidget(self.max_label)
        self.hbox3.addWidget(self.max_throw)
        self.hbox3.addWidget(self.number_of_balls_label)
        self.hbox3.addWidget(self.number_of_balls)
        self.hbox3.addWidget(self.pattern_label)
        self.hbox3.addWidget(self.pattern)
        self.hbox3.addWidget(self.enable_random_cb)
        self.hbox3.addWidget(self.distribution_label)
        self.hbox3.addWidget(self.distribution)
        self.hbox.addStretch(1)
        #hbox.addWidget(restart_button)
        self.hbox.addWidget(self.juggle_button)

        self.vbox = QVBoxLayout(self.tab1)

        self.vbox.addLayout(self.hbox3)
        self.vbox.addStretch(1)
        self.vbox.addLayout(self.hbox)

        self.hbox2 = QHBoxLayout(self.tab2)

        self.tab_widget.addTab(self.tab1, "Main")
        #self.tab_widget.addTab(self.tab2, "Other")

        self.setCentralWidget(self.tab_widget)

        self.menubar = self.menuBar()
        self.file_menu = self.menubar.addMenu('&File')
        self.help_menu = self.menubar.addMenu('&Help')
        self.about = self.help_menu.addMenu('&About')
        self.exit_action = QAction(QIcon('exit.png'), '&Exit', self)
        self.exit_action.triggered.connect(qApp.quit)
        self.file_menu.addAction(self.exit_action)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Juggling Simulator')
        self.show()

def main():

    juggling_app = QApplication(sys.argv)

    win = Form()
    sys.exit(juggling_app.exec_())

main()


#!/usr/bin/python3
""" """
from models.place import Place
from models.city import City
from models.amenity import Amenity
from os import getenv
from models.base_model import BaseModel
import unittest
import datetime
from uuid import UUID
import json
import os

class test_basemodel(unittest.TestCase):
    """ """

    def __init__(self, *args, **kwargs):
        """ """
        super().__init__(*args, **kwargs)
        self.name = 'BaseModel'
        self.value = BaseModel

    def setUp(self):
        """ """
        pass

    def tearDown(self):
        try:
            os.remove('file.json')
        except:
            pass

    def test_default(self):
        """ """
        i = self.value()
        self.assertEqual(type(i), self.value)

    def test_kwargs(self):
        """ """
        i = self.value()
        copy = i.to_dict()
        new = BaseModel(**copy)
        self.assertFalse(new is i)

    def test_kwargs_int(self):
        """ """
        i = self.value()
        copy = i.to_dict()
        copy.update({1: 2})
        with self.assertRaises(TypeError):
            new = BaseModel(**copy)

    @unittest.skipIf(getenv('HBNB_TYPE_STORAGE') == 'db', "Not a database")
    def test_save(self):
        """ Testing save """
        i = self.value()
        i.save()
        key = self.name + "." + i.id
        with open('file.json', 'r') as f:
            j = json.load(f)
            self.assertEqual(j[key], i.to_dict())

    def test_str(self):
        """ """
        i = self.value()
        self.assertEqual(str(i), '[{}] ({}) {}'.format(self.name, i.id,
                                                       i.__dict__))

    def test_todict(self):
        """ """
        i = self.value()
        n = i.to_dict()
        self.assertEqual(i.to_dict(), n)

    def test_kwargs_none(self):
        """ """
        n = {None: None}
        with self.assertRaises(TypeError):
            new = self.value(**n)

    def test_kwargs_one(self):
        """ """
        n = {'Name': 'test'}
        new = self.value(**n)
        self.assertIn('Name', new.__dict__)

    def test_id(self):
        """ """
        new = self.value()
        self.assertEqual(type(new.id), str)

    def test_created_at(self):
        """ """
        new = self.value()
        self.assertEqual(type(new.created_at), datetime.datetime)

    # @unittest.skipIf(getenv('HBNB_TYPE_STORAGE') == 'db', "Not a database")
    # def test_delete(self):
    #     from models import storage
    #     inst_dict = {}
    #     if self.value != BaseModel:
    #         if self.value == Amenity:
    #             inst_dict = {'name': 'WiFi'}
    #         elif self.value == City:
    #             inst_dict = {'state_id': 1, 'name': 'California', 'id': '2'}
    #         elif self.value == Place:
    #             inst_dict = {'city_id': 2, 'user_id': 42,
    #                          'name': 'Super Rad Place', 'number_rooms': 6,
    #                          'number_bathrooms': 4, 'max_guest': 20,
    #                          'price_by_night': 500}
    #         new = self.value(**inst_dict)
    #         new = self.value()
    #         new.save()
    #         self.assertIn(new, storage.all().values())
    #         new.delete()
    #         self.assertNotIn(new, storage.all().values())

    @unittest.skipIf(getenv('HBNB_TYPE_STORAGE') == 'db', "Not a database")
    def test_updated_at(self):
        """ """
        new = self.value()
        self.assertEqual(type(new.updated_at), datetime.datetime)
        new.id = "new_id"
        new.save()
        new.id = "newer_id"
        new.save()
        new.id = "newest_id"
        new.save()
        n = new.to_dict()
        new = BaseModel(**n)
        self.assertNotEqual(new.created_at, new.updated_at)


#! /usr/bin/env python
from __future__ import print_function
import sys,os,subprocess
class Bash2Py(object):
  __slots__ = ["val"]
  def __init__(self, value=''):
    self.val = value

class Expand(object):
  @staticmethod
  def hash():
    return  len(sys.argv)-1

# --- input file in $out_dir/$out_name.scf.fasta ---
#SCRIPTS=/srv/gs1/projects/cherry/giltae/AGAPE # AGAPE main directory path
#SCRIPT=`echo $0 | sed -e 's;.*/;;'` # script name from command line; path removed for msgs
#fastq_dir=/srv/gs1/projects/cherry/giltae/AGAPE/output/fastq
if (Expand.hash() != 4 ):
    print("Usage: agape_annot.sh output_directory output_name sequence_fasta_file AGAPE_main_path")
    exit(1)
out_dir=Bash2Py(sys.argv[1])
out_name=Bash2Py(sys.argv[2])
seq=Bash2Py(sys.argv[3])
SCRIPTS=Bash2Py(sys.argv[4])
_rc0 = subprocess.call([".",str(SCRIPTS.val)+"/configs.cf"],shell=True)
if (not os.path.exists(str(REF_FASTA.val)) ):
    print("No reference sequence data: annotation based on homology skipped")
else:
    if (not os.path.exists(str(out_dir.val)+"/"+str(out_name.val)+".scf.fasta") ):
        subprocess.call(["ln","-s",str(seq.val),str(out_dir.val)+"/"+str(out_name.val)+".scf.fasta"],shell=True)
    subprocess.call([str(SCRIPTS.val)+"/homology_annot.sh",str(out_dir.val),str(out_name.val),str(SCRIPTS.val)],shell=True)
# results place in $out_dir/annot/$out_name.codex
snap_dir=Bash2Py(str(out_dir.val)+"/snap_files")
_rc0 = subprocess.call(["mkdir","-p",str(snap_dir.val)],shell=True)
_rc0 = subprocess.call(["ln","-s",str(REF_FASTA.val),str(snap_dir.val)+"/"+str(REF_NAME.val)+".dna"],shell=True)
_rc0 = subprocess.call([str(SCRIPTS.val)+"/prep_maker.sh",str(snap_dir.val),str(SCRIPTS.val)],shell=True)
maker_dir=Bash2Py(str(out_dir.val)+"/maker")
_rc0 = subprocess.call(["rm","-rf",str(out_dir.val)+"/maker"],shell=True)
_rc0 = subprocess.call(["mkdir","-p",str(maker_dir.val)],shell=True)
_rc0 = subprocess.call([str(SCRIPTS.val)+"/run_maker.sh",str(out_dir.val),str(out_name.val),str(maker_dir.val),str(snap_dir.val),str(SCRIPTS.val)],shell=True)
# results in $maker_dir/genes.gff
comb_annot=Bash2Py(str(out_dir.val)+"/comb_annot")
_rc0 = subprocess.call(["rm","-rf",str(comb_annot.val)],shell=True)
_rc0 = subprocess.call(["mkdir","-p",str(comb_annot.val)],shell=True)
os.chdir(str(comb_annot.val))
_rc0 = subprocess.call([str(SCRIPTS.val)+"/run_comb_annot.sh",str(comb_annot.val),str(BLAST.val),str(out_name.val),str(maker_dir.val),str(out_dir.val),str(snap_dir.val),str(SCRIPTS.val)],shell=True)
_rc0 = subprocess.call([str(SCRIPTS.val)+"/final_annot.sh",str(out_dir.val)+"/maker/seq.fasta",str(comb_annot.val)+"/gff/"+str(out_name.val)+".genes.gff",str(comb_annot.val),str(out_name.val),str(SCRIPTS.val)],shell=True)
# The results are $comb_annot/$out_name.gff
# BLASTX output file is $comb_annot/blast_out/$out_name.blastx.out


import FWCore.ParameterSet.Config as cms

generator = cms.EDProducer("Pythia6HSCPGun",
    readFromFile = cms.untracked.bool(False),
    stoppedData = cms.string(''),
    PGunParameters = cms.PSet(
        MinPhi = cms.double(-3.14159265359),
        ParticleID = cms.vint32(11),
        neutralinoMass = cms.double(100.0),
        MinEta = cms.double(-10),
        sparticleMass = cms.double(300.0),
        MaxEta = cms.double(10),
        MaxPhi = cms.double(3.14159265359),
        diJetGluino = cms.bool(False),
	decayTable = cms.string('src/stage2ParticlesTable.txt')
    ),
    pythiaPylistVerbosity = cms.untracked.int32(2),
    gluinoHadrons = cms.bool(True),
    stopHadrons = cms.bool(False),
    pythiaHepMCVerbosity = cms.untracked.bool(False),
    maxEventsToPrint = cms.untracked.int32(1),
    PythiaParameters = cms.PSet(
        processParameters = cms.vstring('IMSS(1)=11          ! User defined processes',
            'IMSS(21) = 33       ! LUN number for SLHA File (must be 33) ',
            'IMSS(22) = 33       ! Read-in SLHA decay table '),
        parameterSets = cms.vstring('processParameters',
            'SLHAParameters'),
        SLHAParameters = cms.vstring('SLHAFILE=stage2ParticlesTable.txt')
    )
)


# Jonathan Betancourt, Victoria Arnold, Joon Hong
# jbetancourt3@gatech.edu, varnold@gatech.edu, jhong70@gatech.edu
# A03
# We worked alone on this project and only used the resources given to use by the CS 1301 Course.

from myro import *

# Don't worry about this function.
def Sifter(Pic1, Pic2):
    a = loadPicture(Pic1)
    a = copyPicture(a)
    b = loadPicture(Pic2)
    b = copyPicture(b)
    f = 11
    savePicture(a,"pic12.gif")
    while f > 0:
        for c in getPixels(a):
            d = getX(c)
            h = getY(c)
            e = d%f
            if e == 0:
                j = getPixel(b,d,h)
                g = getRed(j)
                i = getBlue(j)
                k = getGreen(j)
                setRed(c, g)
                setBlue(c, i)
                setGreen(c, k)
            else:
                pass
        savePicture(a,"pic"+str(f)+".gif")
        f = f - 1
    a = loadPicture("pic12.gif")
    b = loadPicture("pic11.gif")
    c = loadPicture("pic10.gif")
    d = loadPicture("pic9.gif")
    e = loadPicture("pic8.gif")
    f = loadPicture("pic7.gif")
    g = loadPicture("pic6.gif")
    h = loadPicture("pic5.gif")
    i = loadPicture("pic4.gif")
    j = loadPicture("pic3.gif")
    k = loadPicture("pic2.gif")
    l = loadPicture("pic1.gif")
    savePicture([a,b,c,d,e,f,g,h,i,j,k,l],"Sifter.gif")

# this function is the create-your-own one. 50 points
def DoTrans(Pic1, Pic2):
    a = loadPicture(Pic1)
    a = copyPicture(a)
    b = loadPicture(Pic2)
    b = copyPicture(b)
    f = 19
    savePicture(a,"pic20.gif")
    while f > 0:
        for c in getPixels(a):
            d = getX(c)
            h = getY(c)
            e = d%f
            q = h%f
            if e == 0 and q == 0:
                j = getPixel(b,d,h)
                g = getRed(j)
                i = getBlue(j)
                k = getGreen(j)
                setRed(c, g)
                setBlue(c, i)
                setGreen(c, k)
            else:
                pass
        savePicture(a,"pic"+str(f)+".gif")
        f = f - 1
    c = loadPicture("pic20.gif")
    d = loadPicture("pic19.gif")
    e = loadPicture("pic18.gif")
    f = loadPicture("pic17.gif")
    g = loadPicture("pic16.gif")
    h = loadPicture("pic15.gif")
    i = loadPicture("pic14.gif")
    j = loadPicture("pic13.gif")
    k = loadPicture("pic12.gif")
    l = loadPicture("pic11.gif")
    m = loadPicture("pic10.gif")
    n = loadPicture("pic9.gif")
    o = loadPicture("pic8.gif")
    p = loadPicture("pic7.gif")
    q = loadPicture("pic6.gif")
    r = loadPicture("pic5.gif")
    s = loadPicture("pic4.gif")
    t = loadPicture("pic3.gif")
    u = loadPicture("pic2.gif")
    v = loadPicture("pic1.gif")
    savePicture([c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v],"DoTrans.gif")

def CrossFade(Pic1, Pic2):
    a = loadPicture(Pic1)
    a = copyPicture(a)
    b = loadPicture(Pic2)
    b = copyPicture(b)
    f = 0
    u = 20
    while u >= 0:
        a = loadPicture(Pic1)
        for c in getPixels(a):
            f = 1 - f
            d = getX(c)
            h = getY(c)
            z = getRed(c)
            z = z*f
            i = getBlue(c)
            i = i*f
            o = getGreen(c)
            o = o*f
            j = getPixel(b,d,h)
            f = 1 - f
            g = getRed(j)
            g = g*f
            p = getBlue(j)
            p = p*f
            k = getGreen(j)
            k = k*f
            setRed(c, z+g)
            setBlue(c, i+p)
            setGreen(c, o+k)
        savePicture(a,"pic"+str(u)+".gif")
        f = f + .05
        u = u - 1
    c = loadPicture("pic20.gif")
    d = loadPicture("pic19.gif")
    e = loadPicture("pic18.gif")
    f = loadPicture("pic17.gif")
    g = loadPicture("pic16.gif")
    h = loadPicture("pic15.gif")
    i = loadPicture("pic14.gif")
    j = loadPicture("pic13.gif")
    k = loadPicture("pic12.gif")
    l = loadPicture("pic11.gif")
    m = loadPicture("pic10.gif")
    n = loadPicture("pic9.gif")
    o = loadPicture("pic8.gif")
    p = loadPicture("pic7.gif")
    q = loadPicture("pic6.gif")
    r = loadPicture("pic5.gif")
    s = loadPicture("pic4.gif")
    t = loadPicture("pic3.gif")
    u = loadPicture("pic2.gif")
    v = loadPicture("pic1.gif")
    x = loadPicture("pic0.gif")
    savePicture([c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,x],"CrossFade.gif")

def RobotZoom():
    zoomList = []
    for i in range (7):
        p = takePicture()
        savePicture(p, "zoomPic" + str(i) + ".gif")
        zoomList.append(p)
        forward(1,1)
    savePicture(zoomList, "zoom.gif")

def dollyShot():
    dollyList = []
    for i in range (5):
        turnRight()
        forward(1,.2)
        turnLeft()
        p = takePicture()
        savePicture(p, "dollyPic" + str(i) + ".gif")
        dollyList.append(p)
    savePicture(dollyList, "dolly.gif")

def threeSixty():
    threeSixtyList = []
    for i in range (8):
        rotate(-.5)
        p = takePicture()
        savePicture(p, "360pic" + str(i) + ".gif")
        threeSixtyList.append(p)
    savePicture(threeSixtyList, "360.gif")

def SeeingRed(pic1):
    piclist = []
    picoriginal = loadPicture(pic1)
    pic = copyPicture(picoriginal)
    for x in range(getWidth(pic)):
        for y in range(getHeight(pic)):
            if x%2 == 0 and y%2==0:
                pixel = getPixel(pic,x,y)
                setRed(pixel,255)
    show(pic)
    savePicture(pic,"SeeingRedAfter.gif")

def Fade(Pic1):
    a = loadPicture(Pic1)
    a = copyPicture(a)
    f = 1
    u = 20
    while u >= 0:
        a = loadPicture(Pic1)
        for c in getPixels(a):

            z = getRed(c)
            z = z*f
            i = getBlue(c)
            i = i*f
            o = getGreen(c)
            o = o*f
            setRed(c, z)
            setBlue(c, i)
            setGreen(c, o)
        savePicture(a,"pic"+str(u)+".gif")
        f = f - .05
        u = u - 1
    c = loadPicture("pic20.gif")
    d = loadPicture("pic19.gif")
    e = loadPicture("pic18.gif")
    f = loadPicture("pic17.gif")
    g = loadPicture("pic16.gif")
    h = loadPicture("pic15.gif")
    i = loadPicture("pic14.gif")
    j = loadPicture("pic13.gif")
    k = loadPicture("pic12.gif")
    l = loadPicture("pic11.gif")
    m = loadPicture("pic10.gif")
    n = loadPicture("pic9.gif")
    o = loadPicture("pic8.gif")
    p = loadPicture("pic7.gif")
    q = loadPicture("pic6.gif")
    r = loadPicture("pic5.gif")
    s = loadPicture("pic4.gif")
    t = loadPicture("pic3.gif")
    u = loadPicture("pic2.gif")
    v = loadPicture("pic1.gif")
    x = loadPicture("pic0.gif")
    savePicture([c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,x],"Fade.gif")


"""
    lstm 模型训练。
    随机 shuffle + mutil-sample-dropout。
    收敛速度显著提升。
"""
import math
import random
import logging

from tqdm import tqdm

import pandas as pd
import numpy as np

import torch
from torch import nn
from torch.nn import utils, init
from torch.utils import data
import torch.optim as optim
import torch.nn.utils.rnn as rnn
import torch.nn.functional as F
from torch.optim.lr_scheduler import CosineAnnealingLR, StepLR
from torch.optim.optimizer import Optimizer, required

from sklearn.model_selection import StratifiedKFold

from utils import *

import os
import warnings
warnings.filterwarnings('ignore')
os.environ['CUDA_VISIBLE_DEVICES'] = '2'

# 自定义训练集
class SeqDataSet(data.Dataset):
    def __init__(self, multi_seqs, feas, labels, num_seqs, max_len, tag):
        self.multi_seqs = multi_seqs
        self.feas = feas
        self.labels = labels
        self.tag = tag

        self.num_seqs = num_seqs
        self.max_len = max_len

    def __getitem__(self, index):
        multi_seq = self.multi_seqs[index]
        fea = self.feas[index]
        label = self.labels[index]
        return multi_seq, fea, label

    def __len__(self):
        return len(self.labels)

    def collate_fn(self, batch_data):
        batch_data.sort(key=lambda data: data[0][0].shape[0], reverse=True)
        multi_seqs = [[] for i in range(self.num_seqs)]
        feas = []
        labels = []
        lens = []

        for data in batch_data:
            multi_seq = data[0]
            lens.append(min(multi_seq[0].shape[0], self.max_len))
            index = np.arange(multi_seq[0].shape[0])
            random.shuffle(index)
            index = index[:self.max_len]
            for i in range(self.num_seqs):
                multi_seqs[i].append(torch.LongTensor(multi_seq[i][index]))
            feas.append(data[1])
            labels.append(data[2])

        # multi_seqs [num_seqs, (batch_size, len)]
        # feas [batch_size, fea_size]
        # lens [batch_size]
        # labels [batch_size]
        multi_seqs = torch.stack([rnn.pad_sequence(seqs, batch_first=True, padding_value=0) for seqs in multi_seqs])
        # multi_seqs [num_seqs, batch_size, max_len]
        multi_seqs = multi_seqs.permute(1, 0, 2)
        # multi_seqs [batch_size, num_seqs, max_len]

        feas = torch.FloatTensor(feas)
        labels = torch.LongTensor(labels)
        lens = torch.IntTensor(lens)

        return multi_seqs, feas, lens, labels

# embedding 层，w2v向量转换和拼接
class embedNet(nn.Module):
    def __init__(self, embeddings):
        super(embedNet, self).__init__()
        embed_layers = [nn.Embedding.from_pretrained(embedding, padding_idx=0) for embedding in embeddings]
        self.num_seqs = len(embed_layers)
        self.embed_layers = nn.ModuleList(embed_layers)

    def forward(self, users_seqs):
        #users_seqs  [batch_size, num_seqs, max_len]
        users_seqs = users_seqs.permute(1, 0, 2)
        embeddings = [self.embed_layers[i](users_seqs[i]) for i in range(self.num_seqs)]
        embeddings = torch.cat(embeddings, dim=2)
        #embeddings [batch_size, max_len, embed_size]
        return embeddings

# lstm 层
class lstmNet(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, drop_out):
        super(lstmNet, self).__init__()
        self.LSTMLayer = nn.LSTM(input_size=input_size,
                                 hidden_size=hidden_size,
                                 num_layers=num_layers,
                                 dropout=drop_out,
                                 bidirectional=True,
                                 batch_first=True)
        self.init_params()

    def forward(self, embeddings, lens):
        # embeddings [batch_size, max_len, embed_size]
        x = rnn.pack_padded_sequence(embeddings, lens, batch_first=True)
        x, (h, c) = self.LSTMLayer(x)
        x, _ = rnn.pad_packed_sequence(x, batch_first=True, padding_value=0.0)
        # x [batch_size, max_len, 2 * hidden_size]
        x = torch.transpose(x, 1, 2)
        # x [batch_size, 2 * hidden_sizen, max_len]
        h = F.max_pool1d(x, x.shape[-1]).squeeze()
        # h [batch_size, 2 * hidden_size]
        return h

    def init_params(self):
        for layer in range(len(self.LSTMLayer.all_weights)):
            init.orthogonal_(self.LSTMLayer.all_weights[layer][0])
            init.orthogonal_(self.LSTMLayer.all_weights[layer][1])
            init.zeros_(self.LSTMLayer.all_weights[layer][2])
            init.zeros_(self.LSTMLayer.all_weights[layer][3])

# 分类全连接层
class classfiyNet(nn.Module):
    def __init__(self, input_size, num_labels, drop_out, num_drop):
        super(classfiyNet, self).__init__()
        self.fc1 = nn.Linear(input_size, input_size // 2)
        self.mutil_dropout1 = nn.ModuleList([
            nn.Dropout(drop_out) for _ in range(num_drop)
        ])
        self.fc2 = nn.Linear(input_size // 2, input_size // 4)
        self.mutil_dropout2 = nn.ModuleList([
            nn.Dropout(drop_out) for _ in range(num_drop)
        ])
        self.fc3 = nn.Linear(input_size // 4, num_labels)

    def forward(self, x):
        h = self.fc1(x)
        h = F.leaky_relu(h, inplace=True)
        if self.training:
            hs = []
            # hs num_drop
            for dropout in self.mutil_dropout1:
                hs.append(F.leaky_relu(self.fc2(dropout(h)), inplace=True))

            ys = []
            # ys num_drop^2
            for dropout in self.mutil_dropout2:
                for h in hs:
                    ys.append(self.fc3(dropout(h)))

            return ys
        else:
            h = self.fc2(h)
            h = F.leaky_relu(h, inplace=True)
            y = self.fc3(h)

            return y

    def init_params(self):
        for name, w in self.fc1.named_parameters():
            if 'weight' in name and w.dim() > 1:
                init.xavier_normal_(w)
            else:
                init.zeros_(w)
        for name, w in self.fc2.named_parameters():
            if 'weight' in name and w.dim() > 1:
                init.xavier_normal_(w)
            else:
                init.zeros_(w)
        for name, w in self.fc3.named_parameters():
            if 'weight' in name and w.dim() > 1:
                init.xavier_normal_(w)
            else:
                init.zeros_(w)

# 完整的网路结构
class Net(nn.Module):
    def __init__(self, embed_size, fea_size, hidden_size, num_layers, drop_out, num_drop):
        super(Net, self).__init__()
        self.lstm_layer = lstmNet(embed_size, hidden_size, num_layers, drop_out)
        self.fc_feas = nn.Sequential(
            nn.Linear(fea_size, hidden_size),
            nn.LeakyReLU(inplace=True),
        )
        self.fc_embed = nn.Sequential(
            nn.Linear(embed_size, hidden_size),
            nn.LeakyReLU(inplace=True),
        )
        self.init_params()
        self.fc_output = classfiyNet(4 * hidden_size, 20, drop_out, num_drop)

    def forward(self, embeddings, feas, lens):
        # lens [batch_size]
        # feas [batch_size, fea_size]
        # embeddings [batch_size, max_len, embed_size]
        lstm_output = self.lstm_layer(embeddings, lens)
        # lstm_output [batch_size, 2 * hidden_size]
        embeddings = embeddings.permute(0, 2, 1)
        embed_output = F.max_pool1d(embeddings, embeddings.shape[-1]).squeeze()
        embed_output = self.fc_embed(embed_output)
        # embed_output [batch_size, hidden_size]
        feas_output = self.fc_feas(feas)
        # feas_output [batch_size, hidden_size]
        h = torch.cat([embed_output, lstm_output, feas_output], dim=1)
        # h [batch_size, 4 * hidden_size]
        y = self.fc_output(h)
        # y  num_drop * [batch_size, 20]
        return y

    def init_params(self):
        for name, w in self.fc_feas.named_parameters():
            if 'weight' in name and w.dim() > 1:
                init.xavier_normal_(w)
            else:
                init.zeros_(w)
        for name, w in self.fc_embed.named_parameters():
            if 'weight' in name and w.dim() > 1:
                init.xavier_normal_(w)
            else:
                init.zeros_(w)

def train(params):
    logger = get_logger('{}.log'.format(params['task']), '{}_logger'.format(params['task']))
    logger.info('start {}'.format(params['task']))

    set_all_seed(params['seed'])

    for key, value in params.items():
        logger.info('{} : {}'.format(key, value))

    logger.info('loading seqs, feas and w2v embeddings ...')
    train_val_data, sub_data, embeddings, embed_size, fea_size = load_data(params['cols'], params['embed_dir'], params['seqs_file'], params['feas_file'])

    logger.info('embed_size : {} | fea_size : {}'.format(embed_size, fea_size))
    batch_size = params['batch_size']
    sub_dataset = SeqDataSet(sub_data['seqs'],
                             sub_data['feas'],
                             sub_data['users'], len(params['cols']), params['max_len'], 'sub')
    sub_loader = data.DataLoader(sub_dataset, batch_size * 10, shuffle=False, collate_fn=sub_dataset.collate_fn, pin_memory=True)

    sub = np.zeros(shape=(sub_data['num'], 20))
    sub = pd.DataFrame(sub, index=sub_data['users'])

    skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=params['seed'])

    for i, (train_idx, val_idx) in enumerate(skf.split(train_val_data['feas'], train_val_data['labels'])):
        logger.info('------------------------------------------{} fold------------------------------------------'.format(i))
        train_dataset = SeqDataSet(train_val_data['seqs'][train_idx],
                                   train_val_data['feas'][train_idx],
                                   train_val_data['labels'][train_idx], len(params['cols']), params['max_len'], 'train')
        train_loader = data.DataLoader(train_dataset, batch_size, shuffle=True, collate_fn=train_dataset.collate_fn, pin_memory=True)

        val_dataset = SeqDataSet(train_val_data['seqs'][val_idx],
                                 train_val_data['feas'][val_idx],
                                 train_val_data['labels'][val_idx], len(params['cols']), params['max_len'], 'val')
        val_loader = data.DataLoader(val_dataset, batch_size * 10, shuffle=False, collate_fn=val_dataset.collate_fn, pin_memory=True)

        logger.info('train samples : {} | val samples : {} | sub samples : {}'.format(len(train_idx), len(val_idx), sub_data['num']))
        logger.info('loading net ...')

        embed_net = embedNet(embeddings).cuda()
        net = Net(embed_size, fea_size, params['hidden_size'], params['num_layers'], params['drop_out'], params['num_drop']).cuda()

        #optimizer = Ranger(params=net.parameters(), lr=params['lr'])
        optimizer = optim.AdamW(params=net.parameters(), lr=params['lr'])
        scheduler = StepLR(optimizer, step_size=2, gamma=params['gamma'])
        #scheduler = CosineAnnealingLR(optimizer, T_max=params['num_epochs'])
        loss_func = CrossEntropyLabelSmooth(20, params['label_smooth'])
        #loss_func = nn.CrossEntropyLoss()

        earlystop = EarlyStopping(params['early_stop_round'], logger, params['task'] + str(i))

        for epoch in range(params['num_epochs']):
            train_loss, val_loss = 0.0, 0.0
            train_age_acc, val_age_acc = 0.0, 0.0
            train_gender_acc, val_gender_acc = 0.0, 0.0
            train_acc, val_acc = 0.0, 0.0

            n, m = 0, 0
            lr_now = scheduler.get_last_lr()[0]
            logger.info('--> [Epoch {:02d}/{:02d}] lr = {:.7f}'.format(epoch, params['num_epochs'], lr_now))

            # 训练模型
            net.train()
            for seqs, feas, lens, labels in tqdm(train_loader, desc='[Epoch {:02d}/{:02d}] Train'.format(epoch, params['num_epochs'])):
                seqs = seqs.cuda()
                feas = feas.cuda()
                lens = lens.cuda()
                labels = labels.cuda()

                logits = net(embed_net(seqs), feas, lens)
                loss = sum([loss_func(logit, labels) for logit in logits]) / len(logits)
                loss.backward()
                optimizer.step()
                optimizer.zero_grad()
                logits = sum(logits) / len(logits)

                train_loss += loss.detach() * labels.shape[0]
                train_age_acc += (logits.argmax(dim=1).detach() % 10 == labels % 10).sum()
                train_gender_acc += (logits.argmax(dim=1).detach() // 10 == labels // 10).sum()

                n += lens.shape[0]

            scheduler.step()

            train_loss = (train_loss / n).item()
            train_age_acc = (train_age_acc / n).item()
            train_gender_acc = (train_gender_acc / n).item()
            train_acc = train_age_acc + train_gender_acc

            # 预测验证集
            net.eval()
            with torch.no_grad():
                for seqs, feas, lens, labels in tqdm(val_loader, desc='[Epoch {:02d}/{:02d}]  Val '.format(epoch, params['num_epochs'])):
                    seqs = seqs.cuda()
                    feas = feas.cuda()
                    lens = lens.cuda()
                    labels = labels.cuda()

                    logits = net(embed_net(seqs), feas, lens)
                    loss = loss_func(logits, labels)

                    val_loss += loss.detach() * labels.shape[0]
                    val_age_acc += (logits.argmax(dim=1) % 10 == labels % 10).sum()
                    val_gender_acc += (logits.argmax(dim=1).detach() // 10 == labels // 10).sum()

                    m += lens.shape[0]

                val_loss = (val_loss / m).item()
                val_age_acc = (val_age_acc / m).item()
                val_gender_acc = (val_gender_acc / m).item()
                val_acc = val_age_acc + val_gender_acc

            logger.info('train_loss {:.5f} | train_gender_acc {:.5f} | train_age_acc {:.5f} | train_acc {:.5f} | val_loss {:.5f} | val_gender_acc {:.5f} | val_age_acc {:.5f} | val_acc {:.5f}'
                        .format(train_loss, train_gender_acc, train_age_acc, train_acc, val_loss, val_gender_acc, val_age_acc, val_acc))

            # 早停
            earlystop(val_loss, val_acc, net)
            if earlystop.early_stop:
                break

        break
        net.load_state_dict(torch.load('{}_checkpoint.pt'.format(params['task']+str(i))))
        logger.info('predicting sub ...')
        net.eval()
        with torch.no_grad():
            for it in range(10):
                probs = []
                users = []
                for seqs, feas, lens, ids in tqdm(sub_loader, desc='predict_{}'.format(it)):
                    seqs = seqs.cuda()
                    feas = feas.cuda()
                    lens = lens.cuda()

                    logits = net(embed_net(seqs), feas, lens)
                    logits = F.softmax(logits, dim=1)

                    probs.append(logits)
                    users.append(ids)

                probs = torch.cat(probs).cpu().numpy()
                users = torch.cat(users).numpy()
                sub += pd.DataFrame(probs, users)
            sub = sub / 10

    return sub

if __name__ == '__main__':

    params = {
        'seed' : 2020,
        'task' : 'lstm1',
        'embed_dir' : './data/w2v',
        'seqs_file' : './data/seqs.pkl',
        'feas_file' : './data/feas.pkl',
        'cols' : ['time', 'click', 'creative', 'ad', 'product', 'ader', 'industry', 'category'],
        'batch_size' : 256,
        'max_len' : 256,
        'hidden_size' : 256,
        'num_layers' : 2,
        'drop_out' : 0.2,
        'num_drop' : 2,
        'label_smooth' : 0.1,
        'num_epochs' : 50,
        'early_stop_round' : 3,
        'lr' : 1e-3,
        'gamma' : 0.75,
    }

    sub = train(params)
    sub_split = pd.DataFrame(np.zeros((sub.shape[0], 12)), index=sub.index)
    sub_split.loc[:,0] = sub.loc[:,:9].sum(axis=1)
    sub_split.loc[:,1] = sub.loc[:,10:].sum(axis=1)
    for i in range(10):
        sub_split.loc[:,i+2] = sub.loc[:,[i,i+10]].sum(axis=1)
    sub_split.to_pickle('./torch_{}_sub.pkl'.format(params['task']))