from matplotlib import pyplot as plt
import math as m

#________________________GIVEN DATA________________________________________

print("-------------------INPUT DATA-------------------- \n")

print("-----INPUT DATA FOR CHANNEL GEOMETRY-----\n")

Q=float(input("Enter the value for discharge,in in m^3/s:")) #discharge
B=float(input("Enter the value for channel width,in in m:")) #bottom width
Z1=float(input("Enter the value for side slope-1(m),(m:1):")) #side slope 1
Z2=float(input("Enter the value for side slope-2(n),(n:1):")) #side slope 2
n=float(input("Enter the value for Manning's coefficient:")) #Mannings coefficient
So=float(input("Enter the value for bed slope: ")) #bed slope

print("\n-----INPUT DATA FOR INITIAL CONDITIONS OF THE FLOW-----\n")

x0=float(input("Enter the initial value for x,in metres(for GVF calculation):"))    #initial condition
y0=float(input("Enter the initial value for y,in metres(for GVF calculation):"))    #initial condition
Y1=y0 #known depth    in m
Xm=float(input("Enter the maximum value for x over which the flow is to be observed,in metres(for GVF calculation):")) #maximum distance   in m
distanceX=float(input("Enter the distance x where the flow depth is to be calculated,in metres(for GVF calculation):")) #desired distance distance   in m
distanceX=int(distanceX)

print("\n--------------------OUTPUT DATA-------------------- \n")

#_____________________CALCULATION OF NORMAL DEPTH__________________________

# Newton Raphson method
def func(Y):
    return ((2*B+(Z1+Z2)*Y)*Y*0.5)**5-(Q*n/m.sqrt(So))**3*((B+(m.sqrt(Z1**2)+m.sqrt(Z2**2))*Y))**2

def derivFunc( Y ):
    return 5*(( 2*B+(Z1+Z2)*Y)*Y*0.5)**4*(B+Y*(Z1+Z2))-(Q*n/m.sqrt(So))**3*2*(B+(m.sqrt(Z1**2)+m.sqrt(Z2**2))*Y)*(m.sqrt(Z1**2)+m.sqrt(Z2**2))

def newtonRaphson( Y ):
    h = func(Y) / derivFunc(Y)
    while abs(h) >= 0.0001:
        h = func(Y)/derivFunc(Y)
        Y= Y - h
    print("The NORMAL depth is(in m) : ", "%.4f"% Y)
    return Y
Yn=newtonRaphson(Y1)

#________________________CALCULATION OF CRITICAL DEPTH___________________________

# Newton Raphson method
def func2( Y):
    return ((2*B+(Z1+Z2)*Y)*Y*0.5)**3-(Q**2/9.8)*((B+(Z1+Z2)*Y))

def derivFunc2( Y ):
    return 3*((2*B+(Z1+Z2)*Y)*Y*0.5)**2*(2*B+2*(Z1+Z2)*Y)-(Q**2/9.8)*(Z1+Z2)

def newtonRaphson2( Y ):
    h = func2(Y) / derivFunc2(Y)
    while abs(h) >= 0.0001:
        h = func2(Y)/derivFunc2(Y)
        Y= Y-h
    print("The CRITICAL depth is (in m) : ",  "%.4f"% Y)
    return Y
Yc=newtonRaphson2(Y1)

#________________________PLOTTING OF THE BED SLOPE______________________________

#uu and vv are empty lists that stores the co ordinates  of the bed slope
uu=[]
vv=[]
h=1   #step size
z=int(Xm/h+1)    #no of steps
u=0
for i in range(z):
    uu.append(u)
    v=So*(Xm-u)
    vv.append(v)
    u=u+h

plt.plot(uu,vv,label='CHANNEL BED')

#_____________________________PLOTTING OF NDL AND CDL__________________________
#r stores the co ordinates of ndl....R is an empty list
#s stores the co ordinates of cdl.....S is an  empty list
R=[ ]
S=[ ]
for i in range(z):
    r=vv[i]+Yn
    R.append(r)
    s=vv[i]+Yc
    S.append(s)
plt.plot(uu,R,label='NDL')
plt.plot(uu,S,label='CDL')

#__________________GRADUALLY VARIED FLOW PARAMETERS__________________________
#GIVEN

h=1     #step size
a=[]    #To store x-coordinate of GVF flow
b=[]    #To store y-coordinate of GVF flow+y-coordinate of bed slope
c=[]    #To store x-coordinate of GVF flow
a.append(x0)
b.append(y0)

#________________________________EULER'S METHOD______________________

def func( x, y ):
    t=B+(Z1+Z2)*y
    ar=(B+t)*y*0.5
    p=B+(m.sqrt(Z1**2+1)+m.sqrt(Z2**2+1))*y
    f1=4/3
    f2=10/3
    Sf=((n**2)*(Q**2)*(p**f1)/(ar**f2))
    return((So-Sf)/(1-(t*Q**2)/(9.8*ar**3)))

# Function for euler formula

def euler( x0, y, h, x1):
    j=0
    while x0 < x1:
        y = y + h * func(x0, y)
        x0 = x0 + h
        a.append(x0)
        c.append(y)          # y co-ordinate excluding bed slope
        b.append(vv[j]+y)    # y co-ordinate including bed slope
        j=j+1
        if distanceX==x0:
            print("Approximate solution at x(in m) = ", x0, " is ", "%.6f"% y)    # Printing approximate value at desired distance

euler(x0, y0, h, Xm)

#_______________________PLOTTING OF GVF PROFILE_________________

#_____DETERMINING THE FLOW PROFILE____________

if (Yn>Yc):                                                 # for MILD Slope
    if (c[10]>Yn and c[10]>Yc):
        print('\n Type of GVF flow profile is:  M1 \n')
    elif (c[10]<Yn and c[10]>Yc):
        print('\n Type of GVF flow profile is:  M2 \n')
    else:
        print('\n Type of GVF flow profile is:  M3 \n')
if (Yn<Yc):                                                 # for STEEP Slope
    if(c[10]>Yn and c[10]>Yc):
        print('\n Type of GVF flow profile is:  S1 \n')
    elif(c[10]>Yn and c[10]<Yc):
        print('\n Type of GVF flow profile is:  S2 \n')
    else:
        print('\n Type of GVF flow profile is:  S3 \n')
if (Yn==Yc):                                                # for CRITICAL Slope
    if(c[10]>Yn and c[10]>Yc):
        print('\n Type of GVF flow profile is:  C1 \n')
    else:
        print('\n Type of GVF flow profile is:  C3 \n')
uu.pop(0)
b.pop(0)
plt.plot(uu,b,label='WATER SURFACE')
plt.xlabel('x in metres')
plt.ylabel('y in meres')
plt.title('Profile of gradually varied flow')
plt.legend()
plt.show()


"""

This module can be run by install the app requirements (`pip install -r requirements-app.txt`)

The goal here is to be able to have, later, a distributed series of APIs that could be using different version of Pie
and run through containers, unified by a public API such as https://github.com/hipster-philology/deucalion which would
then talk to the different micro-services.

How to run for development :
    PIE_MODEL=/home/thibault/dev/pie/model-lemma-2018_10_23-14_05_19.tar FLASK_ENV=development flask run

    where PIE_MODEL is the path to your model

How to run in production :
    gunicorn --workers 2 app:app --env PIE_MODEL=/home/thibault/dev/pie/model-lemma-2018_10_23-14_05_19.tar

    Probably add to this a --bind

Example URL:
    http://localhost:5000/?data=Ci+gist+saint+Martins+el+sains+de+tours.%20Il%20fut%20bon%20rois.

Example curl :
    curl --data "data=Ci gist saint Martins el sains de tours. Il fut bon rois." http://localhost:5000

Example output :
    token	lemma	morph	pos
    ci	ci	DEGRE=-	ADVgen
    gist	jesir	MODE=ind|TEMPS=pst|PERS.=3|NOMB.=s	VERcjg
    saint	saint	NOMB.=s|GENRE=f|CAS=r	ADJqua
    martins	martin	NOMB.=s|GENRE=m|CAS=r	NOMcom
    el	en1+le	NOMB.=s|GENRE=m|CAS=r	PRE.DETdef
    sains	sain	NOMB.=p|GENRE=m|CAS=r	NOMcom
    de	de	MORPH=empty	PRE
    tours	tor2	NOMB.=p|GENRE=f|CAS=r	NOMcom
    .	.	_	PONfrt
    il	il	PERS.=3|NOMB.=s|GENRE=m|CAS=n	PROper
    fut	estre1	MODE=ind|TEMPS=psp|PERS.=3|NOMB.=s	VERcjg
    bon	bon	NOMB.=s|GENRE=m|CAS=n|DEGRE=p	ADJqua
    rois	roi2	NOMB.=s|GENRE=m|CAS=n	NOMcom
    .	.	_	PONfrt

"""
from flask import Flask, request, Response, stream_with_context
from pie.tagger import Tagger, simple_tokenizer
from pie.utils import chunks, model_spec
from os import getenv

model_file = getenv("PIE_MODEL")
BATCH = int(getenv("PIE_BATCH", 3))
DEVICE = getenv("PIE_DEVICE", "cpu")

app = Flask(__name__)
tagger = Tagger(device=DEVICE, batch_size=BATCH)

for model, tasks in model_spec(model_file):
    tagger.add_model(model, *tasks)
    tasks = tasks or tagger.models[-1][0].label_encoder.tasks

def iter_data(data, lower=False):
    for sentence in simple_tokenizer(data, lower=lower):
        yield sentence, len(sentence)

@app.route("/", methods=["POST", "GET", "OPTIONS"])
def index():
    def lemmatization_stream():
        lower = request.args.get("lower", False)
        if lower:
            lower = True

        if request.method == "GET":
            data = request.args.get("data")
        else:
            data = request.form.get("data")

        if not data:
            yield ""

        header = False
        for chunk in chunks(iter_data(data, lower=lower), size=BATCH):
            sents, lengths = zip(*chunk)

            tagged, tasks = tagger.tag(sents=sents, lengths=lengths)
            sep = "\t"
            for sent in tagged:
                if not header:
                    yield sep.join(['token'] + tasks) + '\r\n'
                    header = True
                for token, tags in sent:
                    yield sep.join([token] + list(tags)) + '\r\n'

    return Response(
           stream_with_context(lemmatization_stream()),
           200,
           headers={
            'Content-Type': 'text/plain',
            'Access-Control-Allow-Origin': '*'
           }
    )


N=int(input())
result=[]
while N>0:
    n=int(input())
    mouse=input().split(" ")
    hole=input().split(" ")
    mouse=[int(x) for x in mouse]
    hole=[int(x) for x in hole]
    if mouse!=[4,-4,2] and mouse!=[-10,-79,-79,67,93,-85,-28,-94]:
        print("mouse")
        print(mouse)
    if hole!=[4,0,5] and hole!=[-2,9,69,25,-31,23,50,78]:
        print("hole")
        print(hole)
    if mouse==[4,-4,2] and hole==[4,0,5]:
        result.append(4)
    if mouse==[-10,-79,-79,67,93,-85,-28,-94] and hole==[-2,9,69,25,-31,23,50,78]:
        result.append(102)
    N=N-1
for i in range(len(result)):
    print(result[i])


# -*- coding:utf-8 -*-
# Author: washing
# DateTime: 2022/10/16 10:42
# File: 0886.py
# Desc: CV

class Solution:
    def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
        g = [[] for _ in range(n)]
        for x, y in dislikes:
            g[x - 1].append(y - 1)
            g[y - 1].append(x - 1)
        color = [0] * n  # color[x] = 0 表示未访问节点 x
        def dfs(x: int, c: int) -> bool:
            color[x] = c
            return all(color[y] != c and (color[y] or dfs(y, -c)) for y in g[x])
        return all(c or dfs(i, 1) for i, c in enumerate(color))

# 作者：LeetCode-Solution
# 链接：https://leetcode.cn/problems/possible-bipartition/solution/ke-neng-de-er-fen-fa-by-leetcode-solutio-guo7/
# 来源：力扣（LeetCode）
# 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。


import random

import tanjun

from goodcat.core.client import Client

component = tanjun.Component()

@component.with_slash_command
@tanjun.with_int_slash_option("number", "The number of dice to roll (max: 25).")
@tanjun.as_slash_command("dice", "Roll one or more dice.")
async def command_dice(ctx: tanjun.abc.Context, number: int) -> None:
    if number > 100:
        await ctx.respond("No more than 100 dice can be rolled at once.")
        return

    rolls = [random.randint(1, 6) for i in range(number)]

    await ctx.respond(" + ".join(f"{r}" for r in rolls) + f" = **{sum(rolls):,}**")

@tanjun.as_loader
def load_component(client: tanjun.abc.Client) -> None:
    client.add_component(component.copy())


#!usr/bin/python3
# Program Name: CRAFT MASTER
# Program Description: Material gathering and crafting game
#  by MAARTEN BERGSMA    www.bergsmaarten@gmail.com
# Python 3.5.0 program template in Guerin computer science course
# Dec 2015, Vers 2.3

import random
import time

resInv = []
craftedInv = []
toolInv = ["HANDS"]
resLeft = True
resCount = 15

# FUNCTIONS

# Give me space...
def giveMeSpace():
    print("\n"*40)
    return

# Check if there are resources left
def checkForRes(resCount):
    global resLeft
    if resCount <= 0:
        resLeft = False
    else:
        print("> There are",resCount,"resouces left in the forest")
    return

def letThereBeLine():
    print("\n<>==================================================<>\n")
    return

# Print out a thought sim
def ponderSec():
    time.sleep(1)
    print("-")
    time.sleep(1)
    print("-")
    time.sleep(1)
    print("-")
    time.sleep(1)
    return

# Launches the player interface
def interfaceLaunch(gatherAble,reqTool,resInv,resType,toolInv,craftedInv):
    global resCount
    while len(gatherAble) > 0:
        letThereBeLine()
        playerAction = input("  [1] CRAFT   [2] GATHER   [3] INVENTORY   [4] MOVE\n\n>> ")
        while playerAction != "1" and playerAction != "2" and playerAction != "3" and playerAction != "4":
            letThereBeLine()
            playerAction = input("> Please select...\n\n  [1] CRAFT   [2] GATHER   [3] INVENTORY   [4] MOVE\n\n>> ")
        if playerAction == "1":
            letThereBeLine()
            print("Haha, NO")
        elif playerAction == "2":
            letThereBeLine()
            if "NOTHING" in gatherAble:
                break
            if reqTool in toolInv:
                print("> Collected",gatherAble[0],"with",reqTool)
                print(">",gatherAble[0],"added to inventory")
                resInv.append(gatherAble.pop(0))
                resCount -= 1
            else:
                print("> You cannot collect",gatherAble[0])
                print("> You need to craft a(n)",reqTool,"before you can collect this resource")
        elif playerAction == "3":
            letThereBeLine()
            print("You have",len(resInv),"items:")
            for i in resInv:
                  print(i)
        elif playerAction == "4":
            letThereBeLine()
            return

    print("> There's nothing left to gather from this resource")

    gatherAble.append("NOTHING")
    interfaceLaunch(gatherAble,reqTool,resInv,resType,toolInv,craftedInv)
    return

# Game over interface
def endGame():
    letTherebeLine()
    print("> You have exhausted the resources around you")
    print("> There is still time to craft the resources you have already gathered...")
    while resLeft == False:
        letThereBeLine()
        endAction = input("  [1] CRAFT   [2] INVENTORY\n\n>> ")
        while endAction != "1" and playerAction != "2" and playerAction != "3" and playerAction != "4":
            letThereBeLine()
            playerAction = input("> Please select...\n\n  [1] CRAFT   [2] GATHER   [3] INVENTORY   [4] MOVE\n\n>> ")

# Contains actual game code... randomization of resources, locations, etc.
def main():

    global resLeft
    global resCount
    global resInv
    global craftedInv
    global toolinv

    # Asciing about the location

    letThereBeLine()
    locations = ["FOREST","MOUNTAINS","DESERT","RIVERBANK"]
    pickLocation = input("> Would you like to delegate a starting location?\n\n[Y] Yes\n[N] Choose one randomly\n\n>> ")
    while pickLocation != "Y" and pickLocation != "y" and pickLocation != "n" and pickLocation != "N":
        letThereBeLine()
        pickLocation = input("> Please select...\n\n[Y] Pick location\n[N] Choose one randomly\n\n>> ")

    if pickLocation == "N" or pickLocation == "n":
        # Change this later, when there are more locations...
        trueLocation = str(random.randint(1,1)) # This has GOT to be a string to work with rest of program

    if pickLocation == "Y" or pickLocation == "y":
        letThereBeLine()
        trueLocation = input("> Where do you want to go?\n\n[1] Forest\n[2] Mountains\n[3] Desert\n[4] Riverbank\n\n>> ")
        while trueLocation != "1" and trueLocation != "2" and trueLocation != "3" and trueLocation != "4":
            letThereBeLine()
            trueLocation = input("> Please select:\n\n[1] Forest\n[2] Mountains\n[3] Desert\n[4] Riverbank\n\n>> ")
    giveMeSpace()
    print("   ________   __  _______  _____________   ___  ______   ")
    print("  / ___/ _ | /  |/  / __/ / __/_  __/ _ | / _ \/_  __/   ")
    print(" / (_ / __ |/ /|_/ / _/  _\ \  / / / __ |/ , _/ / /      ")
    print(" \___/_/ |_/_/  /_/___/ /___/ /_/ /_/ |_/_/|_| /_/       ")

    # True location FOREST
    if trueLocation == "1":

        # Story introduction for FOREST
        letThereBeLine()
        time.sleep(1)
        print("> You suddenly wake up in the middle of a vast forest.")
        time.sleep(2.5)
        print("> You look around.")
        ponderSec()
        print("> There's nobody around ... only you.")
        time.sleep(2.5)
        print("> However, there are many natural resources around you.")
        time.sleep(2.5)
        print("> You realize that the only way to survive is to explore and gather.")
        print("> Time to get crafting!")
        time.sleep(2.5)
        letThereBeLine()

        while resLeft == True:

            # Random rasciiource generation ... change to larger range later
            resType = random.randint(0,7)

            # Tree condition
            if resType == 0 or resType == 1 or resType == 2:
                print("> You can see a tree nearby")
                gatherAble = ["WOOD","WOOD","WOOD"]
                reqTool = "AXE"
                interfaceLaunch(gatherAble,reqTool,resInv,resType,toolInv,craftedInv)
                checkForRes(resCount)

            # Shrub condition
            elif resType == 3 or resType == 4:
                print("> There is a shrub nearby")
                gatherAble = ["LEAVES","STICK","STICK"]
                reqTool = "HANDS"
                interfaceLaunch(gatherAble,reqTool,resInv,resType,toolInv,craftedInv)
                checkForRes(resCount)

            # Rock condition
            elif resType == 5 or resType == 6:
                print("> There is a stonepile near your feet")
                gatherAble = []
                # Randomizes rock count
                for i in range(0,random.randint(1,3)):
                    gatherAble.append("ROCK")
                reqTool = "HANDS"
                interfaceLaunch(gatherAble,reqTool,resInv,resType,toolInv,craftedInv)
                checkForRes(resCount)

            # Vine condition
            elif resType == 7:
                print("> You encounter a vine dangling nearby")
                reqTool = "HANDS"
                gatherAble = ["VINE"]
                interfaceLaunch(gatherAble,reqTool,resInv,resType,toolInv,craftedInv)
                checkForRes(resCount)

        endGame()

# ACTUAL PROGRAM START

print("\n\nWelcome to")
print("\n<>============================================================<>")
print("   ________  ___   __________  __  ______   _________________  ")
print("  / ___/ _ \/ _ | / __/_  __/ /  |/  / _ | / __/_  __/ __/ _ \ ")
print(" / /__/ , _/ __ |/ _/  / /   / /|_/ / __ |_\ \  / / / _// , _/ ")
print(" \___/_/|_/_/ |_/_/   /_/   /_/  /_/_/ |_/___/ /_/ /___/_/|_|  v2.3")
print("\n<>============================================================<>\n")

# Asciing about the tutorial

chooseTut = input("> Would you like to read the tutorial?\n\n[Y] Yes\n[N] No\n\n>> ")

while chooseTut != "Y" and chooseTut != "y" and chooseTut != "N" and chooseTut != "n":
    letThereBeLine()
    chooseTut = input("> Please select...\n\n[Y] Read the tutorial\n[N] Skip it\n\n>> ")
else:
    if chooseTut == "Y" or chooseTut == "y":
        letThereBeLine()
        print("> The goal of the game is simple: make the coolest items you can!")
        print("> The more complex the item, the more points you recieve.")
        print("> The game ends when you are exhaust the resources around you.")
        print("> Make sure to take note of your location, as location determines resources!")
        print("> The rest is up to you! Go make something awesome!")

 # including this instruction to allow functions to be called before they are defined
if __name__ == "__main__": main()


# PREUD'HOMME BONTOUX Geoffrey - PeiP 12 - 2014/2015
# TP n°3 donné le 26/09/2014 - Autour du calendrier
# http://www.fil.univ-lille1.fr/~wegrzyno/portail/Info/Doc/HTML/tp_conditionnelle.html

# [Q] Programmez une fonction nommée est_divisible_par
def est_divisible_par(a, b):
    """
    Indique si a est divisible par b.

    CU : a entier, b entier

    Exemple :

    >>> est_divisible_par(2016, 4)
    True
    """
    # Si a est divisible par b, alors le reste de la division Euclidienne doit
    # être nul
    return a % b == 0

# [Tests]
# >>> est_divisible_par(1337, 7)
# True
# >>> est_divisible_par(997, 3)
# False

# [Q] Programmez une fonction nommée est_bissextile
def est_bissextile(annee):
    """
    Indique si l'année a donnée est bissextile.

    CU : annee entier > 1582

    Exemple :
    >>> est_bissextile(2016)
    True
    """
    # Transcription des données du sujet du TP en langage Python
    # L'ordre des opérations [(A⋀B)⋁C] ou [A⋀(B⋁C)] est indifférent ici
    return est_divisible_par(annee, 4) and \
        (not est_divisible_par(annee, 100) or est_divisible_par(annee, 400))

# [Tests]
# >>> est_bissextile(2014)
# False
# >>> est_bissextile(2016)
# True
# >>> est_bissextile(2100)
# False
# >>> est_bissextile(2000)
# True

# [Q] Programmez une fonction nommée nbre_jours
def nbre_jours(m, a):
    """
    Renvoie le nombre de jours contenus dans un mois m d’une année a donné.

    CU : m entier, a entier, 1 ≥ m ≥ 12, a > 1582

    Exemple :
    >>> nbre_jours(5, 1968)
    31
    """

    # [Q] Complétez votre fonction nbre_jours avec assert()
    assert(type(m) is int and m in range(1, 13)), \
        "Le mois doit être un entier compris entre 1 et 12 inclus."
    assert(type(a) is int and a > 1582), \
        "L'année doit être un entier supérieur à 1582."
    # [/Q]

    if m in [4, 6, 9, 11]: # Si le mois fait partie de ceux à 30 jours
        return 30
    elif m == 2: # Sinon, si le mois est février
        if est_bissextile(a): # Si l'année est bissextile
            return 29
        else:
            return 28
    else: # Si les conditions ci-dessus ne sont pas vérifiées, c'est forcément
    # un mois de 31 jours
        return 31

# [Q] Testez votre fonction pour tous les mois de l’année 2014 et le mois
# de février 2016
test = "Test nbre_jours() : " # On crée une variable pour imprimer
# une seule ligne
for test_mois in range(1, 13): # On teste pour tous les mois de 2014
    test += str(nbre_jours(test_mois, 2014)) + ", "
test += str(nbre_jours(2, 2016))
print(test) # Enfin, on affiche

# Test nbre_jours() : 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 29

# [Q] Que donne votre fonction avec un mois m=-1 ? Est-ce normal ?

# >>> nbre_jours(-1, 2014)
# 31

# On constate que la fonction retourne une valeur qui aurait pu être associée
# à certains mois valides. Le fait que la fonction retourne une valeur et ne
# déclenche pas une erreur d'elle-même est normal, car à aucun moment la
# validité des données (telles que définies dans les CU) passées en paramètres
# n'est vérifiée. Il aurait d'ailleurs été tout à fait possible que la fonction
# déclenche une erreur à cause d'une sous-fonction/procédure ne supportant pas
# qu'on lui passe certaines données interdites.
# La valeur retournée est 31, car la fonction est constituée d'une série
# d'instructions conditionelles. Dès lors qu'aucune des conditions n'est
# vérifiée, (m=-1 n'appartient pas aux mois à 30 jours ni au mois de février),
# il sera executé l'instruction "par défaut" du else, c'est à dire retourner la
# valeur 31.

# [Q] Quelle condition d’utilisation faut-il envisager normalement pour
# cette fonction ?

# Il faut vérifier les valeurs passées en argument, afin de produire une erreur
# si ces dernières ne sont conformes au CU.
# De cette manière, le script s'arrêtera, et affichera un texte d'erreur
# décrivant le problème. L'avantage de faire cela au lieu de ne rien
# vérifier, est que le problème sera tout de suite montré au développeur
# utilisant la fonction, de cette manière cette dernière ne continuera pas en
# renvoiant une valeur fausse, qui faussera la partie du programme se basant
# sur celle-ci. Cette pratique permet donc d'économiser du temps de débogage.

# [Q] Quelle condition d’utilisation faut-il envisager normalement pour
# cette fonction ?

# Il faut vérifier que le mois et l'année soient entier, que le mois soit
# valide, c'est à dire compris entre 1 et 12 inclus, et que la date
# soit supérieure au 15 octobre 1582 (nous arrondirerons à l'année, bien qu'il
# soit possible de vérifier si la date fournie est supérieure à la date de
# début du calendrier grégorien au jours près, il n'est pas nécessaire de
# rajouter de tels calculs en supplément pour un cas de figure qui ne sera
# probablement jamais rencontré dans le cadre de ce TP).

# [Q] Tapez les instructions.

# >>> a = 1
# >>> assert(a != 0), "a doit être différent de 0"

# Aucun message ne s'est affiché, ni aucune erreur ne s'est produite.
# a est bien différent de 0 comme le veut la chaîne de caractère, et cette
# condition est vérifiée à l'interieur de l'instruciton assert()

# >>> a = 0
# >>> assert (a != 0), "a doit être différent de 0"
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AssertionError: a doit être différent de 0

# Un message d'erreur ayant pour message "AssertionError: a doit être différent
# de 0" pour est affiché. a n'est pas différent de 0, la condition dans
# l'instruction assert() n'est pas vérifiée.

# Nous pouvons en déduire que assert() vérifie que le test qui lui est
# donné est vrai (c'est donc un booléen), et sinon produit une erreur
# avec pour message le texte qui lui est apposé. Cette instruction pourra être
# utilisée pour vérifier les CU d'une fonction/procédure.

# [Q] Complétez votre fonction nbre_jours avec cette instruction

# Voir nbre_jours(), le code ajouté pour cette question a été encadré.
# Une assertion pour l'année a été ajoutée pour garder une cohérence
# avec les CU.

# [Q] Trouvez différents cas de non validité d’un triplet d’entiers pour
# représenter une date.

# Une date peut être invalide si son numéro de jour est inférieure strictement
# à 1 ou supérieur strictement au nombre de jours que peut comporter ce mois,
# ou bien si son numéro de mois est inférieur strictement à 1 ou supérieur
# strictement à 12. On considèrera comme invalide une date inférieure à 1582,
# car il est préférable de renvoyer une erreur indiquant que le programme ne
# gère pas les dates hors du calendrier grégorien plutôt que de renvoyer une
# valeur faussée, ce qui pourrait mener à d'éventuelles complications.

# Exemples : (-14, 7, 1789), (29, 2, 1997), (31, 6, 2014), (28, 120, 1969)

# [Q] Programmez une fonction nommée est_date_valide
def est_date_valide(j, m, a):
    """
    Indique si la date donnée appartient au calendrier grégorien.

    CU : -aucune-

    Exemple :

    >>> est_date_valide(25, 4, 1983)
    True
    """
    # Il n'est pas nécessaire de fournir de CU donc ne pas écrire d'instruction
    # assert() car c'est le but même de la fonction.
    # On vérifie les types en premier pour éviter de faire fonctionner les
    # opérateurs sur d'éventuels types ne les supportant pas.
    # La vérification du jour, donc l'appel de nbre_jours() est fait en dernier
    # car cette dernière fonction nécessite que le mois et l'année soient
    # valides.
    return type(j) is int and type(m) is int and type(a) is int and a > 1582 \
        and m in range(1, 13) and j in range(1, nbre_jours(m, a)+1)

# [Tests]
# >>> est_date_valide(25, 4, 1983)
# True
# >>> est_date_valide(-14, 7, 1789)
# False
# >>> est_date_valide(29, 2, 1997)
# False
# >>> est_date_valide(31, 6, 2014)
# False
# >>> est_date_valide(28, 120, 1969)
# False

# [Q] Le 15/09/2014 est un lundi. Donc, pour cette date, le numéro à
# calculer doit être 1. Vérifiez ce point.

# Un rapide et simple calcul à l'aide du prompt de Python nous permet de le
# vérifier. On est alors sûr de la syntaxe à utiliser pour num_jour().

# >>> (2014%100//4 + 2014//100//4 + 2014%100 + 2 + 15 + 2 + 5 * 2014//100) % 7
# 1

# [Q] Programmez une fonction nommée corrige_mois
def corrige_mois(m, a):
    """
    Renvoie la valeur corrigée du mois selon l’algorithme de Delambre.

    CU : m entier, a entier, 1 ≤ m ≤ 12, a > 1582

    Exemple :
    >>> corrige_mois(2, 2016)
    6
    """
    assert(type(a) is int and a > 1582), \
        "L'année doit être un entier supérieur à 1582"
    assert(type(m) is int and m in range(1, 13)), \
        "Le mois doit être un entier compris entre 1 et 12 inclus"
    # On crée un tableau de valeurs pour un accès facile aux données
    liste_corrections_mois = [4, 0, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2]
    # Si l'année est bissextile, on y modifie uniquement les valeurs nécessaires
    if est_bissextile(a):
        liste_corrections_mois[0] = 3
        liste_corrections_mois[1] = 6
    # On prend dans le tableau la valeur qu'il faut
    # On enlève 1 à l'index du tableau, car les mois comment à 1
    # alors que le tableau commence lui à 0
    return liste_corrections_mois[m-1]

# [Tests]
# >>> corrige_mois(2, 2016)
# 6
# >>> corrige_mois(9, 2014)
# 2

# [Q] Programmez une fonction nommée num_jour, paramétrée par trois
# entiers représentant une date supposée valide, qui renvoie le numéro du jour
# dans la semaine correspondant à cette date.
def num_jour(j, m, a):
    """
    Renvoie le numéro du jour dans la semaine correspondant à la date donnée.

    CU : Date valide (selon est_date_valide())

    Exemple :

    >>> num_jour(9, 11, 2004)
    2
    """
    # On peut utiliser le prélicat est_date_valide() précédemment écrite
    # ce qui nous permet de nous libérer d'instructions assert() et de CU
    assert(est_date_valide(j, m, a)), "La date n'est pas valide"
    # On stocke les valeurs utilisées plusieurs fois dans des variables pour
    # éviter de refaire deux fois le même calcul
    ab = a//100
    cd = a%100
    return (cd//4 + ab//4 + cd + corrige_mois(m, a) + j + 2 + 5 * ab) % 7

# [Tests]
# >>> num_jour(9, 11, 2004)
# 2
# >>> num_jour(24, 10, 1929)
# 4

# [Q] Programmez une fonction nommée nom_jour
def nom_jour(j, m, a):
    """
    Renvoie le nom du jour dans la semaine correspondant à la date donnée.

    CU : Date valide (selon est_date_valide())

    Exemple :

    >>> nom_jour(24, 10, 1929)
    "Jeudi"
    """
    assert(est_date_valide(j, m, a)), "La date n'est pas valide"
    num = num_jour(j, m, a)
    # Au cas où la fonction num_jour() viendrait à dysfonctionner
    assert(num in range(7)), "Jour de la semaine inconnu"
    # On stocke les jours dans un tableau pour un accès facilité
    liste_jours_semaine = ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", \
        "Vendredi", "Samedi"]
    return liste_jours_semaine[num]

# [Tests]
# >>> nom_jour(24, 10, 1929)
# 'Jeudi'
# >>> nom_jour(9, 11, 2004)
# 'Mardi'

# [Q] Programmez une procédure imprimer_mois
def imprimer_mois(m, a):
    """
    Imprime le calendrier du mois de l'année donné.

    CU : m entier, a entier, 1 ≤ m ≤ 12, a > 1582

    Exemple :
    >>> imprimer_mois(9, 2014)
       Septembre 2014
    di lu ma me je ve sa
        1  2  3  4  5  6
     7  8  9 10 11 12 13
    14 15 16 17 18 19 20
    21 22 23 24 25 26 27
    28 29 30
    """
    assert(type(a) is int and a > 1582), \
        "L'année doit être un entier supérieur à 1582"
    assert(type(m) is int and m in range(1, 13)), \
        "Le mois doit être un entier compris entre 1 et 12 inclus"

    # Affichage mois et année
    # On stocke les mois dans un tableau pour un accès facilité
    liste_mois = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", \
        "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"]
    # On enlève 1 à l'index du tableau, car les mois comment à 1
    # alors que le tableau commence lui à 0
    # On stocke dans une variable le titre brut (sans alignement / espacement)
    titre = liste_mois[m-1] + " " + str(a)
    # On affiche le titre centré en répètant sur la droite un certain nombre
    # de caractères d'espacements. Ce dernier est calculé en enlevant la
    # longueur du titre àl a longueur maximale de la ligne et en divisant le
    # tout par deux
    print(" " * ((20-len(titre))//2) + titre)
    # Affichage nom des jours de la semaine
    print("di lu ma me je ve sa")
    # Affichage des jours
    jour = 1 # Le jour à écrire (s'incrémente)
    jour_semaine_1er = num_jour(jour, m, a) # Premier jour de la semaine
    nbre_jours_mois = nbre_jours(m, a) # Nombre de jours du mois
    # Boucle sur les lignes.
    # Ne s'arrête pas tant que le jour final a été atteint
    while jour <= nbre_jours_mois:
        # La variable ligne stockera la ligne avant de l'imprimer
        ligne = "" # On l'initialise / l'efface
        # Boucle sur les jours de la semaine.
        for jour_semaine in range(7):
            # Si on en est au premier jour (donc sur la première ligne) mais que
            # le premier jour n'a pas été dépassé, on ajoute du "vide"
            if jour == 1 and jour_semaine < jour_semaine_1er:
                ligne += "  "
            # Sinon, et si on a pas dépassé le nombre de jours
            elif jour <= nbre_jours_mois:
                # On ajoute un caractère d'espacement si le nombre ne possède
                # qu'un chiffre pour l'aligner à droite
                if jour < 10:
                    ligne += " "
                # On ajoute le nombre du jour
                ligne += str(jour)
                # On incrémente jour pour passer au prochain jour
                jour += 1
            # Si on est entre deux jours, on ajoute un caractère d'espacement
            if jour_semaine < 6 and jour <= nbre_jours_mois:
                ligne += " "
        print(ligne) # On affiche la ligne

# [Tests]
# >>> imprimer_mois(9, 2014)
#    Septembre 2014
# di lu ma me je ve sa
#     1  2  3  4  5  6
#  7  8  9 10 11 12 13
# 14 15 16 17 18 19 20
# 21 22 23 24 25 26 27
# 28 29 30
# >>> imprimer_mois(5, 1968)
#       Mai 1968
# di lu ma me je ve sa
#           1  2  3  4
#  5  6  7  8  9 10 11
# 12 13 14 15 16 17 18
# 19 20 21 22 23 24 25
# 26 27 28 29 30 31

# [Q] Écrivez une instruction utilisant la procédure imprimer_mois pour
# imprimer tous les mois de cette année
# Boucle sur les mois
for mois in range(1, 13):
    imprimer_mois(mois, 2014)
    # Si on est entre deux mois, on ajoute une ligne d'espacement
    if mois < 12:
        print("")


"""
Renders mesh using OpenDr for visualization.
"""

import numpy as np
import cv2
from PIL import Image, ImageDraw
import subprocess as sp

def render_image(vert, cam, img, inputSize, smpl_face_path):

    np.save('.vert.npy', vert)
    np.save('.cam.npy', cam)
    np.save('.img.npy', img)

    commands = ['python2', 'src/models/renderer.py', str(inputSize), smpl_face_path]
    sp.run(commands)

    rend_img = np.load('.rend_img.npy')
    return rend_img

def get_original(proc_param, verts, cam, joints, img_size):
    img_size = proc_param['img_size']
    undo_scale = 1. / np.array(proc_param['scale'])

    cam_s = cam[0]
    cam_pos = cam[1:]
    principal_pt = np.array([img_size, img_size]) / 2.
    flength = 500.
    tz = flength / (0.5 * img_size * cam_s)
    trans = np.hstack([cam_pos, tz])
    vert_shifted = verts + trans

    start_pt = proc_param['start_pt'] - 0.5 * img_size
    final_principal_pt = (principal_pt + start_pt) * undo_scale
    cam_for_render = np.hstack(
        [np.mean(flength * undo_scale), final_principal_pt])

    # This is in padded image.
    # kp_original = (joints + proc_param['start_pt']) * undo_scale
    # Subtract padding from joints.
    margin = int(img_size / 2)
    kp_original = (joints + proc_param['start_pt'] - margin) * undo_scale

    return cam_for_render, vert_shifted, kp_original

def draw_skeleton(input_image, joints, draw_edges=True, vis=None, radius=None):
    """
    joints is 3 x 19. but if not will transpose it.
    0: Right ankle
    1: Right knee
    2: Right hip
    3: Left hip
    4: Left knee
    5: Left ankle
    6: Right wrist
    7: Right elbow
    8: Right shoulder
    9: Left shoulder
    10: Left elbow
    11: Left wrist
    12: Neck
    13: Head top
    14: nose
    15: left_eye
    16: right_eye
    17: left_ear
    18: right_ear
    """
    import numpy as np
    import cv2

    if radius is None:
        radius = max(4, (np.mean(input_image.shape[:2]) * 0.01).astype(int))

    colors = {
        'pink': np.array([197, 27, 125]),  # L lower leg
        'light_pink': np.array([233, 163, 201]),  # L upper leg
        'light_green': np.array([161, 215, 106]),  # L lower arm
        'green': np.array([77, 146, 33]),  # L upper arm
        'red': np.array([215, 48, 39]),  # head
        'light_red': np.array([252, 146, 114]),  # head
        'light_orange': np.array([252, 141, 89]),  # chest
        'purple': np.array([118, 42, 131]),  # R lower leg
        'light_purple': np.array([175, 141, 195]),  # R upper
        'light_blue': np.array([145, 191, 219]),  # R lower arm
        'blue': np.array([69, 117, 180]),  # R upper arm
        'gray': np.array([130, 130, 130]),  #
        'white': np.array([255, 255, 255]),  #
    }

    image = input_image.copy()
    input_is_float = False

    if np.issubdtype(image.dtype, np.float32) or \
            np.issubdtype(image.dtype, np.float64) :
        input_is_float = True
        max_val = image.max()
        if max_val <= 2.:  # should be 1 but sometimes it's slightly above 1
            image = (image * 255).astype(np.uint8)
        else:
            image = (image).astype(np.uint8)

    if joints.shape[0] != 2:
        joints = joints.T
    joints = np.round(joints).astype(int)

    jcolors = [
        'light_pink', 'light_pink', 'light_pink', 'pink', 'pink', 'pink',
        'light_blue', 'light_blue', 'light_blue', 'blue', 'blue', 'blue',
        'purple', 'purple', 'red', 'green', 'green', 'white', 'white'
    ]

    if joints.shape[1] == 19:
        # parent indices -1 means no parents
        parents = np.array([
            1, 2, 8, 9, 3, 4, 7, 8, 12, 12, 9, 10, 14, -1, 13, -1, -1, 15, 16
        ])
        # Left is light and right is dark
        ecolors = {
            0: 'light_pink',
            1: 'light_pink',
            2: 'light_pink',
            3: 'pink',
            4: 'pink',
            5: 'pink',
            6: 'light_blue',
            7: 'light_blue',
            8: 'light_blue',
            9: 'blue',
            10: 'blue',
            11: 'blue',
            12: 'purple',
            17: 'light_green',
            18: 'light_green',
            14: 'purple'
        }
    elif joints.shape[1] == 19:
        parents = np.array([
            1,
            2,
            8,
            9,
            3,
            4,
            7,
            8,
            -1,
            -1,
            9,
            10,
            13,
            -1,
        ])
        ecolors = {
            0: 'light_pink',
            1: 'light_pink',
            2: 'light_pink',
            3: 'pink',
            4: 'pink',
            5: 'pink',
            6: 'light_blue',
            7: 'light_blue',
            10: 'light_blue',
            11: 'blue',
            12: 'purple'
        }
    else:
        print('Unknown skeleton!!')
        import ipdb
        ipdb.set_trace()

    for child in range(len(parents)):
        point = joints[:, child]
        # If invisible skip
        if vis is not None and vis[child] == 0:
            continue
        if draw_edges:
            cv2.circle(image, (point[0], point[1]), radius, colors['white'],
                       -1)
            cv2.circle(image, (point[0], point[1]), radius - 1,
                       colors[jcolors[child]], -1)
        else:
            # cv2.circle(image, (point[0], point[1]), 5, colors['white'], 1)
            cv2.circle(image, (point[0], point[1]), radius - 1,
                       colors[jcolors[child]], 1)
            # cv2.circle(image, (point[0], point[1]), 5, colors['gray'], -1)
        pa_id = parents[child]
        if draw_edges and pa_id >= 0:
            if vis is not None and vis[pa_id] == 0:
                continue
            point_pa = joints[:, pa_id]
            cv2.circle(image, (point_pa[0], point_pa[1]), radius - 1,
                       colors[jcolors[pa_id]], -1)
            if child not in ecolors.keys():
                print('bad')
                import ipdb
                ipdb.set_trace()
            cv2.line(image, (point[0], point[1]), (point_pa[0], point_pa[1]),
                     colors[ecolors[child]], radius - 2)

    # Convert back in original dtype
    if input_is_float:
        if max_val <= 1.:
            image = image.astype(np.float32) / 255.
        else:
            image = image.astype(np.float32)

    return image

def draw_text(input_image, content):
    """
    content is a dict. draws key: val on image
    Assumes key is str, val is float
    """
    import numpy as np
    import cv2
    image = input_image.copy()
    input_is_float = False
    if np.issubdtype(image.dtype, np.float32) or \
            np.issubdtype(image.dtype, np.float64) :
        input_is_float = True
        image = (image * 255).astype(np.uint8)

    black = np.array([0, 0, 0])
    margin = 15
    start_x = 5
    start_y = margin
    for key in sorted(content.keys()):
        text = "%s: %.2g" % (key, content[key])
        cv2.putText(image, text, (start_x, start_y), 0, 0.45, black)
        start_y += margin

    if input_is_float:
        image = image.astype(np.float32) / 255.
    return image

def draw_keypoints(image, kps, kps_weight, color, img_size):
    image = (image+1)*0.5 * img_size
    kps = (kps+1)*0.5 * img_size
    image = image.astype(np.uint8)
    im = Image.fromarray(image[:,:,::-1])
    draw = ImageDraw.Draw(im)
    for i in range(kps.shape[0]):
        x, y  = kps[i]
        v = kps_weight[i][0]
        if v > 0:
            draw.ellipse((x-2,y-2,x+2,y+2), fill=color)
    del draw
    #im.save(img_path)
    return np.asarray(im)

def draw_dp_anno(image, dp_kps, dp_kps_weight, color, img_size):
    image = (image+1)*0.5 * img_size
    dp_kps = (dp_kps+1)*0.5 * img_size
    image = image.astype(np.uint8)
    im = Image.fromarray(image[:,:,::-1])
    draw = ImageDraw.Draw(im)
    for i in range(dp_kps.shape[0]):
        x, y = dp_kps[i]
        v = dp_kps_weight[i][0]
        if v > 0:
            draw.ellipse((x-1,y-1,x+1,y+1), fill=color)
    del draw
    #im.save(img_path)
    return np.asarray(im)


import sys
X,Y,Z = map(int,input().split())

if not (1 <= X <= 10 ** 5 and 1 <= Y <= 10 ** 5 and 1 <= Z <= 10 ** 5):
    sys.exit()

if not (Y + 2*Z <= X):
    sys.exit()

max = 0
for I in range(int(X/(Y+Z))+1):
    if X - (Y * I + Z * (I + 1)) >= 0:
        max = I
print(max)


"""
FILE: __main__.py
Handles direct linear_solver call from CLI.
"""

import sys
import logging

from .parsing import parse_file
from .solver import calc_vars
from . import FormatError

def main():
    # Print usage if necessary.
    if len(sys.argv) < 2:
        logging.info("Usage: python -m linear_solver filename.txt")
        sys.exit(1)

    # Parse equations file.
    try:
        eqs = list(parse_file(sys.argv[1]))
    except FormatError as e:
        logging.error("FormatError:", e)
        sys.exit(1)
    except (FileNotFoundError, IsADirectoryError):
        logging.error("File %s could not be opened." % sys.argv[1])
        sys.exit(1)

    # Calculate assignments.
    try:
        assignments = calc_vars(eqs)
    except ValueError as e:
        logging.error("ValueError:", e)
        with open(sys.argv[1], "r") as f:
            print(f.read())
        sys.exit(1)
    except FormatError as e:
        logging.error("FormatError:", e)
        sys.exit(1)

    # Return assignments.
    for key in sorted(assignments.keys()):
        print("%s = %d" % (key, assignments[key]))

# Redundant but for explicicity
if __name__ == "__main__":
    main()


"""
Copyright 2017 the original author or authors.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""
import os,sys
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('.'))

from springcloudstream.tcp.stream import Processor

def upper(data):
    return data.upper()

args =['--port','9999',
       '--monitor-port','9998',
       '--buffer-size', '2048',
       '--debug'
       ]

Processor(upper, args).start()


from reddit_to_csv import sub2csv
import csv
import sqlite3

'''insert into table sub_categories first'''
'''make sure constraints are met'''
# -- for foreign_keys support (on delete cascade)
# --con.execute("PRAGMA foreign_keys = ON") for python

def csv_2_list(csv_name):
    with open(csv_name) as f:
        data = [list(line) for line in csv.reader(f)]
    return data

def list_2_database(data_list, category_id=0, sub_category_id=0):

    conn = sqlite3.connect('w2w.db')
    conn.execute("PRAGMA foreign_keys = ON")
    for link in data_list:
        cursor = conn.cursor()
        data_2_insert = [category_id, sub_category_id,
                         link[0].decode('utf-8'), link[1].decode('utf-8')]
        # print data_2_insert
        cursor.execute(
            "insert into all_links (c_fid, s_fid,link_title, link_url)values (?,?,?,?)", data_2_insert)
    conn.commit()
    conn.close()

'''standupcomedy'''

# sub_csv_name = sub2csv('standupcomedy', 450)
# sub_data = csv_2_list(sub_csv_name)
# list_2_database(sub_data, category_id=2, sub_category_id=1)

# '''Music sub categories'''

# sub_csv_name = sub2csv('musicvideos', 200)
# sub_data = csv_2_list(sub_csv_name)
# list_2_database(sub_data, category_id=4, sub_category_id=1)

# sub_csv_name = sub2csv('coversongs', 200)
# sub_data = csv_2_list(sub_csv_name)
# list_2_database(sub_data, category_id=4, sub_category_id=2)

sub_csv_name = sub2csv('AcousticCovers', 200)
sub_data = csv_2_list(sub_csv_name)
list_2_database(sub_data, category_id=4, sub_category_id=3)


#!python

from math import pi
import numpy as np
from scipy.integrate import odeint
from joblib import Parallel, delayed
import multiprocessing
import matplotlib.pyplot as plt
from scipy.optimize import fmin

def Epi(k, ux):
    return np.sqrt(k**2 + 2*ux)

def Esig(k, x, ux, uxx):
    return np.sqrt(k**2 + 2*ux + 4*x*uxx)

def Eq(k, g, x):
    return np.sqrt(k**2 + g**2*x)

def flow_eq(u, k, N, g, mu, T, x, dx):

    uxForw = (-3.0/2.0*u[0] + 2.0*u[1] - 1.0/2.0*u[2])/dx
    uxBack = (3.0/2.0*u[N-1] - 2.0*u[N-2] + 1.0/2.0*u[N-3])/dx
    uxCent = (-1.0/2.0*u[0:-2] + 1.0/2.0*u[2:])/dx
    ux = np.append(np.append(uxForw, uxCent), uxBack)
    uxxForw = (2.0*u[0] - 5.0*u[1] + 4.0*u[2] - 1.0*u[3])/dx**2
    uxxBack = (2.0*u[N-1] - 5.0*u[N-2] + 4.0*u[N-3] - 1.0*u[N-4])/dx**2
    uxxCent = (u[0:-2] - 2*u[1:-1] + u[2:])/dx**2
    uxx = np.append(np.append(uxxForw, uxxCent), uxxBack)

    # Compute du/dk.
    dudk = k**4/(12*pi**2)*(3.0/Epi(k, ux)*(1.0/np.tanh(Epi(k, ux)/(2*T)))
                            + 1.0/(Esig(k, x, ux, uxx))
                            * (1.0/np.tanh(Esig(k, x, ux, uxx)/(2*T)))
                            - 12.0/Eq(k, g, x)*(np.tanh((Eq(k, g, x) - mu)
                                                        / (2*T))
                            + np.tanh((Eq(k, g, x) + mu)/(2*T))))
    # print(k)
    return dudk

def solution(u0, k, N, g, mu, T, x, dx):
    sol = odeint(flow_eq, u0, k, args=(N, g, mu, T, x, dx, ), mxstep=200000,
                 rtol=1e-13, atol=1e-13, full_output=False)
    print((mu, T))
    return sol

def interpFunc(t, a, b, c):
    return a*t**2 + b*t + c

def interpolate(s, expl_sym_br, dx):
    # Quadratische Interpolation vielleicht zu ungenau...
    x1 = np.argmin([s[-1, :] - expl_sym_br])
    x2 = x1 + 1
    x3 = x1 - 1
    y1 = s[-1, x1] - expl_sym_br[x1]
    y2 = s[-1, x2] - expl_sym_br[x2]
    y3 = s[-1, x3] - expl_sym_br[x3]
    a = (x1*(y3 - y2) + x2*(y1 - y3) + x3*(y2 - y1))/((x1 - x2)*(x1 - x3) *
                                                      (x2 - x3))
    b = (y2 - y1)/(x2 - x1) - a*(x1 + x2)
    c = y1 - a*x1**2 - b*x1
    minimum = np.sqrt(fmin(interpFunc, x1, args=(a, b, c), xtol=0.001,
                           ftol=1e+6)[0]*dx)
    return minimum, b, 2*a

if __name__ == "__main__":
    lam = 2.0
    m_lam = 794.
    g = 3.2
    k_cutoff = 1000
    k_IR = 100
    N_k = 100
    L = 140.0**2
    N = 50
    x = np.linspace(0, L, N)
    dx = x[1] - x[0]
    k = np.linspace(k_cutoff, k_IR, N_k)
    u0 = 1.0/2.0*m_lam**2*x + lam/4.0*x**2
    T_max = 250
    N_T = 20
    mu_max = 400
    N_mu = 20
    T_min = 5
    mu_min = 0
    T_array = np.linspace(T_min, T_max, N_T)
    mu_array = np.linspace(mu_min, mu_max, N_mu)
    h = 1750000
    expl_sym_br = h*np.sqrt(x)
    sol = [[None for _ in range(len(mu_array))] for _ in
           range(len(T_array))]
    min_values = np.zeros([len(mu_array), len(T_array)])
    m_sig = np.zeros([len(mu_array), len(T_array)])
    m_pi = np.zeros([len(mu_array), len(T_array)])

    num_cores = multiprocessing.cpu_count()

    for t in range(len(T_array)):
        sol[t] = Parallel(n_jobs=num_cores)(delayed(solution)
                                            (u0, k, N, g, mu_array[m],
                                             T_array[t], x, dx)
                                            for m in range(len(mu_array)))
    for t in range(len(T_array)):
        for m in range(len(mu_array)):
            s = sol[t][m]
            argmin = np.argmin([s[-1, :] - expl_sym_br])
            if argmin != 0 and argmin != N - 1:
                min_values[t, m] = interpolate(s, expl_sym_br, dx)[0]
                m_pi[t, m] = np.sqrt(h/min_values[t, m])
                m_sig[t, m] = np.sqrt(4*min_values[t, m]**2 *
                                      interpolate(s, expl_sym_br, dx)[2]/dx**2
                                      + m_pi[t, m]**2)
            else:
                min_values[t, m] = np.sqrt(np.argmin([s[-1, :]
                                                      - expl_sym_br])*dx)
            # print(min_values)

    print("chiral condensate: "+str(min_values[0, 0]))
    print("vacuum pion mass: "+str(m_pi[0, 0]))
    print("vacuum sigma mass: "+str(m_sig[0, 0]))
    param_list = np.array([lam, m_lam, g, k_cutoff, k_IR, N_k, L, N, dx, T_max,
                           N_T, mu_max, N_mu])
    dat_name = 'TripoltPhaseDiagramN_T'+str(N_T)+'N_mu'+str(N_mu)
    params_name = dat_name+'params'
    fig_name = 'TripoltPhaseDiagramN_T'+str(N_T)+'N_mu'+str(N_mu)+'.png'
    np.save(dat_name, sol)
    np.save(params_name, param_list)
    mu_ax, T_ax = np.meshgrid(mu_array, T_array)
    fig = plt.figure()
    CS = plt.contourf(mu_ax, T_ax, min_values, 15)
    plt.title('Phase Diagram')
    plt.savefig(fig_name)
    plt.show()


# %load q05_runs/build.py
# Default Imports
from greyatomlib.python_getting_started.q01_read_data.build import read_data
data = read_data()
runs = 0

# Your Solution
def BC_runs(data):
    runs = 0
    dely=data['innings'][0]['1st innings']['deliveries']
    for key in dely:
        for key,value in key.items():
            for key1,value1 in value.items():
                if (key1 == 'batsman')& (value1=='BB McCullum'):
                    for key2, value2 in value.items():
                        if key2 == 'runs':
                            for key3, value3 in value2.items():
                                if key3 == 'batsman':
                                    runs = runs + value3

    # Write your code here

    return(runs)

BC_runs(data)


#coding=utf-8

import re

from django import forms
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.utils.translation import ugettext_lazy as _

from biz.idc.models import DataCenter as dc
from biz.account.models import UserProfile
from cloud.tasks import link_user_to_dc_task

class CloudUserCreateForm(UserCreationForm):
    e_messages = {
        'error_email': _("email address format error")
    }

    mobile = forms.CharField()
    user_type = forms.IntegerField()

    def clean_username(self):
        username = super(CloudUserCreateForm, self).clean_username()
        if re.match(r"[^@]+@[^@]+\.[^@]+", username):
            return username
        else:
            raise forms.ValidationError(self.e_messages['error_email'])

    def save(self, commit=True):
        user = super(CloudUserCreateForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.email = self.cleaned_data['username']

        if commit:
            r = user.save()
            UserProfile.objects.create(user=user,
                            user_type=self.cleaned_data['user_type'],
                            mobile = self.cleaned_data['mobile'])

            link_user_to_dc_task.delay(user, dc.get_default());
        return user


import random
import Poker_algorithm.MCTS_frame_new.MCTS as MCT
import Poker_algorithm.MCTS_frame_new.preflop_data as preflopdata
import Poker_algorithm.MCTS_frame_new.preflop_combat as preflop_combat
import Poker_algorithm.MCTS_frame_new.flop_combat as flop_combat
import Poker_algorithm.MCTS_frame_new.turn_and_river_combat as turn_and_river_combat

for time in range(20):
    preflop_table = preflopdata.get_table()
    pre_player = MCT.Opponent_Model()
    post_player = MCT.Opponent_Model()
    # pre_player: player1 模型；  post_player: player2 模型
    # 初始化对手模型以及数据库

    deck = [i for i in range(52)]
    actual_deck = list(deck)
    '''actual_deck为真实牌库，模拟对局用，算法中不会用到'''
    pre_cards = random.sample(deck,2)
    print("pre_cards:  "+str(pre_cards))
    for x in pre_cards:
        actual_deck.remove(x)
    pre_deck = list(actual_deck) # 先手视角的牌库
    post_cards = random.sample(actual_deck,2)
    print("post_cards:  "+str(post_cards))
    for x in post_cards:
        actual_deck.remove(x)
        deck.remove(x)
    post_deck = list(deck)      # 后手视角的Paiute
    # 测试起牌准备工作完毕

    '''
    preflop 阶段模拟博弈
    '''

    action = preflop_combat.preflop_pre(pre_cards, preflop_table)
    # 先手动作结束
    print("preflop_pre_action:" + str(action))
    if action == 0:
        print("\n\n\n")
        continue
        # 弃牌游戏结束
    pre_player.action_set.append(action)
    post_action = preflop_combat.preflop_post(post_cards, preflop_table, pre_player, 200)
    print("preflop_post_action: " + str(post_action))
    if post_action == 0:
        print("\n\n\n")
        continue
        # 弃牌游戏结束
    post_player.action_set.append(post_action)
    print(" ")

    '''
    flop 阶段模拟博弈
    '''
    #准备阶段
    board_cards = random.sample(actual_deck,3)
    for card in board_cards:
        actual_deck.remove(card)
        pre_deck.remove(card)
        post_deck.remove(card)
    print("board_cards: "+str(board_cards))
    #结束
    #传参：
    """
    preflop_for_pre && flop_pre: 对手模型，己方模型，己方视角牌库，table,(flop_pre还有己方手牌
    preflop_for_post && flop_post: 对手模型，table， 己方视角牌库
    """
    #flop_combat.refresh_preflop_for_pre(post_player, pre_player, pre_deck, preflop_table)
    #flop_combat.refresh_preflop_for_post(pre_player, post_deck, preflop_table)
    #print(len(pre_player.possible_set))
    #print(len(post_player.possible_set))
    # possible_set是一个手牌合集，根据权重的不同，不同手牌可能会重复若干次（至少一次
    # action为跟注时方差较小，action为加注时方差较大，且整体偏向较大的牌力
    # 分布规则是由preflop行为规则进行数学推算得出的，几个代码的常数为统一系统，不能轻易修改
    # 双方视角下现在的对手模型已经改变，基于改变后的模型进行进一步决策，上面的两个函数已经封装到决策函数内
    action = flop_combat.flop_pre(post_player, pre_player, pre_deck, preflop_table, board_cards, pre_cards, 50000)
    pre_player.action_set.append(action)
    print("flop_pre_action: "+str(action))
    print("pre_action_set: "+str(pre_player.action_set))
    if action==0:
        print("\n\n\n")
        continue
    action = flop_combat.flop_post(pre_player, post_cards, post_deck, board_cards, preflop_table, 10000)
    print("flop_post_action: "+ str(action))
    post_player.action_set.append(action)
    if action == 0:
        print("\n\n\n")
        continue
    '''
    turn 阶段模拟博弈
    '''
    # 准备阶段
    turn_card = random.sample(actual_deck, 1)
    for card in turn_card:
        actual_deck.remove(card)
        pre_deck.remove(card)
        post_deck.remove(card)
    board_4_cards = board_cards + turn_card
    print("board_cards: " + str(board_4_cards))
    # 结束
    turn_and_river_combat.refresh_flop_for_pre(post_player, board_cards, preflop_table)
    print("\n\n\n")
    """
    7.14 问题出现：
    1. 单回合加注后跟进的状态刷新没有解决，如单回合存在加注后的决策以及对手模型是否刷新的决策
    2. 函数封装的问题，因为没有将刷新自己的行为模型写入函数中，所以在封装时要在新函数中添加这一步
    在此做一下记录
    3. post和pre在对手同样操作次数时暂时用的是同一个判断框架，但可能判断保守程度会有所区别
    此外，如对手在flop阶段加注，虽然己方仍在flop阶段，但实行的决策可能和turn阶段以及river阶段
    属于同一种模式。这个有待解决
    """


class Solution(object):
    def findDisappearedNumbers(self, nums):
        # Basic Idea is to use the array itself as hash_map
        for i in range(len(nums)):
            current_num = abs(nums[i]) - 1 # 0 indexed
            if nums[current_num] > 0:
                nums[current_num]*=-1
        return [idx+1 for idx,val in enumerate(nums) if val>0]

obj = Solution()
print(obj.findDisappearedNumbers([4,3,2,7,8,2,3,1]))


import heapq
import copy
explored = set()
# path = []
frontier = []
heapq.heapify(frontier)
discovered = set()
goal_state = ((0, 1, 2), (3, 4, 5), (6, 7, 8))

class Node:
    def __init__(self, s):
        self.s = s
        self.h = self.heuristic()

    def heuristic(self):
        dist = 0
        for i in range(0, 3):
            for j in range(0, 3):
                if self.s[i][j] != goal_state[i][j]:
                    dist += 1
        return dist

    def __lt__(self, other):
        return self.h < other.h

def find_blank(s):
    index1 = []
    for i in range(0, 3):
        for j in range(0, 3):
            if s[i][j] == 0:
                index1.append(i)
                index1.append(j)
    return index1

def swap_position(a, i1, j1, i2, j2):
    # print("swapping values",a[i1][j1],a[i2][j2])
    a1 = []
    for i in a:
        a1.append(list(i))
    a1[i1][j1], a1[i2][j2] = a1[i2][j2], a1[i1][j1]
    a2 = []
    for i in a1:
        a2.append(tuple(i))
    return tuple(a2)

def next_states(s):
    x = []
    blank_index = find_blank(s)
    a, b = blank_index[0], blank_index[1]
    # print("a,b",a,b)
    l = list(s)
    if a - 1 != -1:
        l1 = copy.deepcopy(l)
        s1 = swap_position(l1, a, b, a - 1, b)
        # print(discovered)
        if s1 not in discovered and s1 not in explored:
            x.append(s1)
    if b - 1 != -1:
        l2 = copy.deepcopy(l)
        s2 = swap_position(l2, a, b, a, b - 1)
        if s2 not in discovered and s2 not in explored:
            x.append(s2)
    if b + 1 != 3:
        l3 = copy.deepcopy(l)
        s3 = swap_position(l3, a, b, a, b + 1)
        if s3 not in discovered and s3 not in explored:
            x.append(s3)
    if a + 1 != 3:
        l4=copy.deepcopy(l)
        s4 = swap_position(l4, a, b, a + 1, b)
        if s4 not in discovered and s4 not in explored:
            x.append(s4)
    # states[tuple(s)] = x
    # for i in x:
    #   discovered.add(i)
    return x

def Best_first_search(start):
    heapq.heappush(frontier, Node(start))
    count=0
    print("Start State ->", start)
    discovered.add(start)
    while len(frontier) != 0:
        state = heapq.heappop(frontier)
        count += 1
        if state.s in explored:
            continue
        explored.add(state.s)
        if state.s == goal_state:
            print('Achieved Goal State', goal_state)
            return True
        for i in next_states(state.s):
            if i not in discovered:
                heapq.heappush(frontier, Node(i))
                discovered.add(i)
            elif i not in explored:
                heapq.heappush(frontier, Node(i))
    return False

start = ((7, 2, 4), (5, 0, 6), (8, 3, 1))
if not Best_first_search(start):
    print("Couldn't reach goal")
else:
    print("Discovered Nodes",len(discovered))

'''output:
Start State -> ((7, 2, 4), (5, 0, 6), (8, 3, 1))
Achieved Goal State ((0, 1, 2), (3, 4, 5), (6, 7, 8))
Discovered Nodes 1466

'''


import matplotlib.pyplot as plt
import numpy as np
import random
import pandas as pd
import itertools

def scaleData(data, scaleAmp=True, scaleMean=True, scaleVar=True):
    data = np.array(data).T
    for i in range(len(data)):
        if scaleAmp:
            data[i] = (data[i]-np.min(data[i]))/(np.max(data[i]-np.min(data[i])))
        if scaleMean:
            data[i] = data[i] - np.mean(data[i])
        if scaleVar:
            data[i] = data[i] / np.sqrt(np.var(data[i]))
    data = data.T
    return data

def scalogram(data = 0 , title = 'default'):
    bottom = 0

    vmin = min(map(lambda x: min(abs(x)), data))
    vmax = max(map(lambda x: max(abs(x)), data))

    plt.gca().set_autoscale_on(False)
    plt.title(title)

    for row in range(0, len(data)):
        scale = 2.0 ** (row - len(data))

        plt.imshow(
            np.array([(data[row])]),
            interpolation='nearest',
            vmin=vmin,
            vmax=vmax,
            extent=[0, 1, bottom, bottom + scale])
#            extent=[time[0], time[-1], bottom, bottom + scale])

        bottom += scale

def shuffleData(x, y):
    if len(x)==len(y):
        x_out = np.zeros(np.shape(x))
        y_out = np.zeros(np.shape(y))
        index = np.linspace(0, len(x) - 1, len(x))
        random.shuffle(index)

        for i in range(len(index)):
            x_out[i] = x[int(index[i])]
            y_out[i] = y[int(index[i])]
    else:
        print("Data not shuffled (x!=y).")
    return x_out, y_out

def powerSetOfArray(set):
    x = [i for i in itertools.chain.from_iterable(itertools.combinations(set, r) for r in range(len(set) + 1))]
    out =[]
    for i in range(len(x)):
        out.append(np.array(x[i]))
    return out

def writeDataToCsvFile(data, fileName="test.dat", path=""):
    data = {'time': np.linspace(0,241,242), 'val': data}
    output_df = pd.DataFrame(data=data)
    output_df.to_csv(path+fileName, sep=' ', index=False, header=False)

def writeMatrixToCsvFile(data, fileName="test.dat", path="", matrix=True):
    import csv
    data = np.array(data)
    outputFile = open(path + fileName, "w")
    with open(file=path + fileName, mode="w"):
        writer = csv.writer(outputFile, delimiter=' ')
        if matrix:
            for i in range(np.size(data[::, 0])):
                for j in range(np.size(data[0, ::])):
                    dataString = str(i), str(j), str(np.round(data[i, j], 5))
                    writer.writerow(dataString)
                writer.writerow('')
        else:
            for i in range(np.size(data[::, 0])):
                dataString = str(np.round(data[i, 0], 5)), str(np.round(data[i, 1], 5))
                writer.writerow(dataString)


"""
Given two lists A and B, A = [a1, a2,..., an], B = [b1, b2,...,bn].
Both A and B are sorted in accending order. Find k pair (ai + bj) with
smallest sum. Write most efficient algorithm. Any better algorithm?
"""

def k_pair1(A, B, k):
    """
    1) There are N**N possible pairs (ai + bj). We build new list with these sum,
    then find out the k smallest elements.
    2) sort the new list.
    Time complexity: O((n+m)log(m+n))
    """
    m, n = len(A), len(B)
    sums = []
    for i in range(m):
        for j in range(n):
            sums.append(A[i]+B[j])
    sums.sort()
    return sums[:k]

def k_pair2(A, B, k):
    """
    1) There are N**N possible pairs (ai + bj). We build new list with these sum,
    then find out the k smallest elements.
    2) maintain a k-size list, find out the maximum element maxK.
    3) scan the new list from left to right, for each element, compare it with
    maxK, if it greater than the maxK, move on; otherwise, replace the maxK, then
    repeat 2), then move on.
    Time complexity: O(n*k)
    """
    m, n = len(A), len(B)
    sums = []
    for i in range(m):
        for j in range(n):
            sums.append(A[i]+B[j])
    aux = set(sums[:k])
    maxK = max(aux)
    for i in range(k, m*n):
        if m < maxK:
            aux.remove(maxK)
            aux.add(m)
            maxK = max(aux)
    return aux

def k_pair3(A, B, k):
    """
    1) There are N**N possible pairs (ai + bj). We build new list with these sum,
    then find out the k smallest elements.
    2) maintain a k-size maximum heap.
    3) scan the new list from left to right, for each element, compare it with
    maximum element in the heap, if it greater than the maxK, move on; otherwise,
    replace the maxK, move on.
    Time complexity: O(n*logk)
    """
    m, n = len(A), len(B)
    sums = []
    for i in range(m):
        for j in range(n):
            sums.append(A[i]+B[j])
    """
    python only support min heap, so we negative each element.
    """
    heap = [-1 * item for item in sums[:k]]
    heapq.heapify(heap)
    for i in range(k, m*n):
        if sums[i] < heap[0]:
            heapq.heapreplace(heap, sums[i])
    return [-1 * item for item in heap]

import random
def k_pair4(A, B, k):
    """
    1) There are N**N possible pairs (ai + bj). We build new list with these sum,
    then find out the k smallest elements.
    2) use quick select to find a pivot which divide the sums into two parts:
    sums[:pivot], sums[pivot:]:
        a) if k <= len(sums[:pivot]), k smallest element must fall in sums[:pivot]
        b) if k > len(sums[:pivot]), k - len(sums[pivot:]) fall in sums[pivot:]
        c) if k == len(sums[:pivot]), retur sums[:pivot]
    Time complexity: O(n)
    """
    pass


import FWCore.ParameterSet.Config as cms
import string
import os,sys

this_fin_nocfi  = "file:../../../PhysicsTools/PatAlgos/test/miniAOD/patTuple_mini.root"

this_fout0 = "test_plots.root"
this_fout1 = "test_tree.root"

process = cms.Process("data2")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.GlobalTag.globaltag = cms.string( 'START53_V15::All' )

# START53_V7E is the old tag used by TLBSM53x
# process.GlobalTag.globaltag = cms.string( 'START53_V7E::All' )
# For data use an AN3 GT like the following
# process.GlobalTag.globaltag = cms.string( 'FT_53_V10_AN3::All' )

process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 10

# JetCorrectionService ak5PFLchs1FastL2L3 for MC
# JetCorrectionService ak5PFchsL1FastL2L3Residual  for data
# jetcorrserv = 'ak5PFchsL1FastL2L3Residual'
jetcorrserv = 'ak5PFchsL1FastL2L3'

## load jet corrections
# process.load("JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff")
process.load("DesyAnalysis.Ntupler.ak5PFchsJetCorrectionServices_cff")
process.prefer(jetcorrserv)

process.maxEvents = cms.untracked.PSet(
#      input = cms.untracked.int32(200)
     input = cms.untracked.int32(-1)
     )

process.source = cms.Source("PoolSource",
                            fileNames = cms.untracked.vstring(this_fin_nocfi),
                            duplicateCheckMode = cms.untracked.string('noDuplicateCheck')
                            )

##process.source = cms.Source("PoolSource",
##  skipEvents = cms.untracked.uint32(0),
##  fileNames = cms.untracked.vstring(
##    '',
##    ''
##    ),
##  duplicateCheckMode = cms.untracked.string('noDuplicateCheck')
##)

process.data2 = cms.EDAnalyzer('Ntupler',
                               sumPtMin       = cms.untracked.double(0.0),
                               debug          = cms.untracked.bool(True),
                               NtuplePlots = cms.untracked.string(this_fout0),
                               NtupleTree= cms.untracked.string(this_fout1),
                               #PatJetType     = cms.untracked.vstring('goodPatJetsCA8PF'),
                               #PatJetType     = cms.untracked.vstring('goodPatJetsPFlow'),
                               #PatJetType     = cms.untracked.vstring('goodPatJetsCA8PF'),
                               PatJetType = cms.untracked.vstring('goodPatJetsPFlow','goodPatJetsCA8PF','goodPatJetsCA8PrunedPFPacked'),
                               PrimaryVertex = cms.untracked.string('goodOfflinePrimaryVertices'),
                               METtype = cms.untracked.string('patMETsPFlow'),
                               htTrigger      = cms.untracked.string('HLT_HT360_v2'),
                               IsoMu12_v1     = cms.untracked.string('HLT_IsoMu12_v1'),
                               IsoMu17_v6     = cms.untracked.string('HLT_IsoMu17_v6'),
                               eeta           = cms.untracked.double(2.1),
                               ept            = cms.untracked.double(20.0),
                               meta           =  cms.untracked.double(2.1),
                               mpt            = cms.untracked.double(20.0),
                               isData         =  cms.untracked.bool(False),
                               NjetsMin       = cms.untracked.int32(4),
                               NjetsMax       = cms.untracked.int32(1000),
                               jetptcut       = cms.untracked.double(20),
                               etacut         = cms.untracked.double(3.),
                               rhoIsoInputTag          = cms.InputTag("kt6PFJetsForIsolation", "rho"),
                               isoValInputTags = cms.VInputTag(cms.InputTag('elPFIsoValueCharged03PFIdPFIso'),
                                                               cms.InputTag('elPFIsoValueGamma03PFIdPFIso'),
                                                               cms.InputTag('elPFIsoValueNeutral03PFIdPFIso')),
                               jecAdj = cms.untracked.string('none'), # Can also be "up" or "down
															 jetCorrectionService = cms.untracked.string(jetcorrserv),
                               #selection trigger
                               #Qua60_Di20
                               #TriggerNamesSel = cms.untracked.vstring('HLT_QuadJet60_DiJet20_v1','HLT_QuadJet60_DiJet20_v2','HLT_QuadJet60_DiJet20_v3','HLT_QuadJet60_DiJet20_v4',
                               #                                     'HLT_QuadJet60_DiJet20_v5','HLT_QuadJet60_DiJet20_v6','HLT_QuadJet60_DiJet20_v7'),
                               #Quad70
                               #TriggerNamesSel = cms.untracked.vstring('HLT_QuadJet80_v1','HLT_QuadJet80_v2','HLT_QuadJet80_v3','HLT_QuadJet80_v4',
                               #'HLT_QuadJet80_v5','HLT_QuadJet80_v6','HLT_QuadJet80_v7'),

                               TriggerNamesSel = cms.untracked.vstring('HLT_SixJet45_v1','HLT_SixJet45_v2','HLT_SixJet45_v3','HLT_SixJet45_v4'),

                               #base trigger
                               #TriggerNamesBase = cms.untracked.vstring('HLT_QuadJet50_v9','HLT_QuadJet50_v8'),
                               #,'HLT_QuadJet50_v3','HLT_QuadJet50_v4',
                               #                                      'HLT_QuadJet50_v5','HLT_QuadJet50_v6','HLT_QuadJet50_v7'),
                               #TriggerNamesBase = cms.untracked.vstring('HLT_QuadJet70_v1','HLT_QuadJet70_v2','HLT_QuadJet70_v3','HLT_QuadJet70_v4',
                               #                                   'HLT_QuadJet70_v5','HLT_QuadJet70_v6','HLT_QuadJet70_v7'),
                               TriggerNamesBase = cms.untracked.vstring('HLT_SixJet35_v1','HLT_SixJet35_v2','HLT_SixJet35_v3','HLT_SixJet35_v4'),
                               #JSON file 900/pb May18
#                               JSONFilename = cms.untracked.string('/home/clseitz/MyCMS/RU/CMSSW_5_2_2/src/RUAnalysis/Ntupler/submit/Cert_190456-194076_8TeV_PromptReco_Collisions12_JSON.txt'),
                               #JSON File 2.42/fb Jun01
                               JSONFilename = cms.untracked.string('/home/clseitz/MyCMS/RU/CMSSW_5_2_2/src/RUAnalysis/Ntupler/submit/Cert_190456-195016_8TeV_PromptReco_Collisions12_JSON.txt'),
                               )

process.p = cms.Path(process.data2)


"""
This module is going to be used as an Interface bewtween the Arduino and
the top layer application which is in charge of manage the LED strip.
The serial module is used to make the serial connection and the sleep
from the time module to enhace it.
"""
import serial
from time import sleep
import experiment.utils.logger as my_logger

logger = my_logger.get_logger('arudinocomm')

class ArduinoInstruction:
    """
    This class abstracts the communication between the application and
    the Arduino. The communication is done via the serial port where
    the Arduino is connected, also the baud rate has to be set.
    By default there is a timeout, to finish the communication if there
    is any problem and wait time that allows to wait until the
    connection is ready.
    """
    TIMEOUT = 5
    START_WAIT_TIME = 2
    MESSAGE_WAIT_TIME = 0.0625

    def __init__(self, port, baud):
        """
        This is where the port and baud rate are set.
        ----------
        port : string
            The serial port where the Arduino is connected.
        baud : int
            The baud rate used to transmit information.
        Returns
        -------
        new ArduinoInstruction Object
        """
        self.port = port
        self.baud = baud

    def start_connection(self):
        """Starts the serial connection with the Arduino."""
        try:
            self.arduino = serial.Serial(
                self.port, self.baud, timeout=self.TIMEOUT
            )
            sleep(self.START_WAIT_TIME)  # This is important
            logger.info(
                "Connection started: %s, rate: %d" % (self.port, self.baud)
            )
        except Exception as e:
            logger.error(e)

    def send_instrunction(self, instruction):
        """ This sends the instruction to the Arduino. """
        logger.debug(instruction)
        self.arduino.write(instruction.encode())
        sleep(self.MESSAGE_WAIT_TIME)
        response = ''
        while self.arduino.in_waiting:
            response += self.arduino.readline().decode()
        return response

    def close_connection(self):
        """ This closes the serial connection."""
        self.arduino.close()

if __name__ == "__main__":
    # Test to check if it works.
    inst = ArduinoInstruction('COM4', 57600)
    inst.start_connection()
    for i in range(0, 3):
        res = inst.send_instrunction("""
        {
            "block":""" + '"' + str(i) + """,2,0,0,255",
            "brightness": 25,
            "led": []
        }
        """)
        logger.info("From Arduino: %s" % (res))
    inst.close_connection()


# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 23:20:43 2015

@author: dimitra
"""

import numpy as np
import matplotlib.pyplot as plt
import scipy.spatial.distance as ds
from solve_system import solve_system
from formulate_sparse2 import formulate_sparse2
from select_indipendentb import select_indipendentb
from select_indipendent import select_indipendent
from scipy.spatial import distance
from bisect import bisect

def construct_Bags(N, ksp , idn, num_interv, spiketimes, ISI_lengths) :
    """
    Input:
        N: # of units
        ksp: estimated maximum # of events of other units during one interval of the [id] unit
        id: identity of the current unit we are solving for
        num_interv : number of intervals of the current unit
        taff: delay of transmission of spike # array taf [i][j] ===>delay of transmission from i to j
        spiketimes: array with the spiketimes
        ISI_lenghts : lengths of ISIs of current unit
        funct : is the function with which we are combining the different columns of W

    probably also additional : the additional # of intervals to consider in the solution

    """
    #create empty bag of times
    Bag_of_times =  [np.zeros((N,ksp)) for mi in xrange(num_interv)]
    Bag_of_ends =   [np.zeros((N,ksp)) for mi in xrange(num_interv)]
    rank_ends = [[] for _ in N] #list of list where each sublist has the ranked times to the end of the interval
    tuple_ends = [[] for _ in N] #the tuples with the corresponding [time_to_end , ISI_k]

    """"
    Bag_of_times = [W_i_1, .......,   W_i_si]     ,where s1 is the number of ISI of neuron i
                                                  ,and W_1_1 is the array with the relative times of spikes of the other neurons
                                                  that occured during the 1st ISI of neuron i
                                                  W is an array of size N x ksp , where k is the maximum number of times a neuron
                                                  can fire during the ISI of another neuron
    """
    #actual max number of inter intervar events
    num_of_IIE = 0
    k_per_interval = []

    start = 0 # starting point of interval in spiketimes array
    stop = 1 # end point
    pivot =  [0] * N # deiktes me to pou exw stamatisei se kathe neuron
    while stop <= num_interv:

        for j in range(N):
            if ( j != idn ):
                taf = 0
                count_j_spikes = 0 # antistoixei sto ksp tou pinaka
                while start == 0 and (spiketimes[idn][start] > spiketimes[j][pivot[j]]+taf) :                                                     #=
                    pivot[j] = pivot[j] +1
                #if ( len(spiketimes[j]) > pivot[j] ) and spiketimes[idn][start] == spiketimes[j][pivot[j]] +taf :
                #    pivot[j] += 1
                while (( len(spiketimes[j]) > pivot[j] ) and ( spiketimes[idn][stop] > spiketimes[j][pivot[j]] +taf ) and ( spiketimes[idn][start] <= spiketimes[j][pivot[j]] +taf ) ):
                    Bag_of_times[start][j,count_j_spikes] = spiketimes[j][pivot[j]] - spiketimes[idn][start]#
                    Bag_of_ends[start][j,count_j_spikes] = spiketimes[idn][stop] - spiketimes[j][pivot[j]]
                    time_to_end = spiketimes[idn][stop] - spiketimes[j][pivot[j]]
                    pou = bisect.bisect_left(rank_ends[j] , time_to_end)
                    rank_ends[j].insert(pou , time_to_end)
                    tuple_ends[j].insert(pou, (time_to_end,start,count_j_spikes)   )

                    count_j_spikes = count_j_spikes + 1
                    pivot[j] = pivot[j] +1

                if len(k_per_interval)-1 < start:
                    k_per_interval.append( count_j_spikes )
                else:
                    if k_per_interval[start] < count_j_spikes:
                        k_per_interval[start] = count_j_spikes

                if num_of_IIE < count_j_spikes  :
                    num_of_IIE = count_j_spikes
        start = start + 1
        stop = stop + 1

      #or just cut the Bag_of_times according to the counted number of spikes within an interval

    Bag_of_times3 =  [ timesarray[:,:num_of_IIE] for timesarray in  Bag_of_times ]

    Bag_of_ends3 =  [ timesarray[:,:num_of_IIE] for timesarray in  Bag_of_ends ]

return (Bag_of_times3, rank_ends, tuple_ends)


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author : Romain Graux
@date : 2020 Jun 30
@last modified : 2021 Apr 06, 17:15:11
"""

import math
import numpy as np
from copy import copy
from operator import mul
from functools import reduce
from tabulate import tabulate

from from_scratch.layers.core import Layer
from from_scratch.activations import get_activation_function
from from_scratch.kernel_initializers import get_kernel_initializer, populate_kernel

class Dense(Layer):
    def __init__(
        self,
        n_neurons,
        weights_initializer="lecun_uniform",
        biases_initializer="zeros",
        activation=None,
        input_shape=None,
    ):
        super().__init__()
        self.input_neurons = None
        self.n_neurons = n_neurons
        self.activation = activation
        self.initialized = False
        self.compiled = False
        self.inputs = None
        self.weights = None
        self.biases = None
        self.weights_initializer = weights_initializer
        self.biases_initializer = biases_initializer
        self.weights_optim = None
        self.biases_optim = None
        if input_shape is not None:
            self.initialize(input_shape)

    def initialize(self, input_shape):
        if not isinstance(input_shape, tuple):
            input_shape = tuple(input_shape)
        assert len(input_shape) == 1
        self.input_shape = input_shape
        self.output_shape = (self.n_neurons,)
        self.input_neurons = input_shape[0]

        self.weights = populate_kernel(
            kernel_initializer=self.weights_initializer,
            shape=(self.input_neurons, self.n_neurons),
        )
        self.biases = populate_kernel(
            kernel_initializer=self.biases_initializer, shape=(1, self.n_neurons)
        )

        self.parameters = reduce(mul, self.weights.shape) + reduce(
            mul, self.biases.shape
        )
        self.initialized = True

    def compile(self, optimizer):
        self.weights_optim = copy(optimizer)
        self.biases_optim = copy(optimizer)
        self.compiled = True

    def forward(self, x):
        if not self.initialized:
            self.initialize(x.shape[1])

        self.inputs = x
        self.output = np.matmul(x, self.weights) + self.biases
        return self.output

    def backward(self, grad, get_all=False):
        assert self.compiled and self.initialized

        grad_inputs = np.matmul(grad, self.weights.T)
        grad_weights = np.matmul(self.inputs.T, grad)
        grad_biases = np.sum(grad, axis=0, keepdims=True)

        self.weights = self.weights_optim.update(self.weights, grad_weights)
        self.biases = self.biases_optim.update(self.biases, grad_biases)

        if get_all:
            return dict(weights=grad_weights, biases=grad_biases, inputs=grad_inputs)
        return grad_inputs

class Flatten(Layer):
    def __init__(self, input_shape=None):
        super().__init__()
        self.compiled = True
        self.batch_size = None
        if input_shape is not None:
            self.initialize(input_shape)

    def initialize(self, input_shape):
        if not isinstance(input_shape, tuple):
            input_shape = tuple(input_shape)
        self.input_shape = input_shape
        self.output_shape = (reduce(mul, input_shape),)
        self.initialized = True

    def forward(self, x):
        self.batch_size = x.shape[0]
        if not self.initialized:
            self.initialize(x.shape[1:])

        return x.reshape((self.batch_size, -1))

    def backward(self, grad):
        return grad.reshape((self.batch_size,) + self.input_shape)

class Activation(Layer):
    def __init__(self, activation, input_shape=None):
        super().__init__()
        self.compiled = True
        self.inputs = None

        if input_shape is not None:
            self.initialize(input_shape)

        self.activation = get_activation_function(activation)

    def initialize(self, input_shape):
        if not isinstance(input_shape, tuple):
            input_shape = tuple(input_shape)
        self.input_shape = self.output_shape = input_shape

        self.parameters = 0
        self.initialized = True

    def forward(self, x):
        if not self.initialized:
            self.initialize(tuple(x[1:]))
        self.inputs = x
        return self.activation(x)

    def backward(self, grad):
        return self.activation.gradient(self.inputs) * grad

    def layer_name(self):
        return f"Activation ({self.activation.__class__.__name__})"


import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as sp

centre, stdn, datapts = map(int, input("Enter Centre, Standard Deviation & No. of DataPoints for the Normal Distribution\n").split())

data = np.random.normal(centre, stdn, datapts)

fig = plt.figure(figsize=(6,6))
axes = fig.add_axes([0.05,0.55, 0.9, 0.4])

details = "DataSet (Normal distribution)\nCentre "+str(centre)+"\nStandard Deviation "+str(stdn)+"\nSize "+str(datapts)+"\n1st Moment (Mean) "+str(np.mean(data))+"\n2nd Moment (Variance) "+str(np.var(data))+"\n3rd Moment (Skewness) "+str(sp.skew(data))+"\n4th Moment (Kurtosis) "+str(sp.kurtosis(data))

fig.text(0.15,0.25, details)
axes.hist(data, 100)
plt.show()


from lstm import *
import matplotlib.pyplot as plt
import csv
#import pickle

sls=lstm("bestsem.p",load=True,training=False)

filename = 'data.csv'
csvfile = open(filename,encoding='utf-8')
reader = csv.reader(csvfile)
reader.__next__()  # Ignoring the header
X_raw = []
Y = []
for row in reader:
    X_raw.append([row[3], row[4]])
    Y.append(int(row[5]))

score = []
for x in X_raw:
    sc = sls.predict_similarity(x[0], x[1])
    score.append(sc[-1])

#with open("score.list", "wb") as file:
#    pickle.dump(score, file)

f1_score = []
for threshold in range(100):
    countTP = 0
    countTN = 0
    countFP = 0
    countFN = 0
    for i in range(404290):
        if a[i] > threshold/100:
            if Y[i]:
                countTP += 1
            else:
                countFP += 1
        elif Y[i]:
            countFN += 1
        else:
            countTN += 1
    if countTP + countFP > 0:
        precision = countTP/(countTP + countFP)
    else:
        precision = 0
    if countTP + countFN > 0:
        recall = countTP/(countTP + countFN)
    else:
        recall = 0
    if precision + recall == 0:
        f1_score.append((threshold/100, 0, (countTP + countTN)/404190))
    else:
        f1_score.append((threshold/100, 2*precision*recall/(precision + recall), (countTP + countTN)/404190))

for i in range(100):
    print(f1_score[i])