fst = list(map(int, list(input())))
snd = list(map(int, list(input())))

fst.reverse()
snd.reverse()

while len(fst) < len(snd):
    fst.append(-1)
while len(snd) < len(fst):
    snd.append(-1)

new_fst = []
new_snd = []

for i in range(len(fst)):
    if fst[i] == snd[i]:
        new_fst.append(fst[i])
        new_snd.append(snd[i])
    elif fst[i] > snd[i]:
        new_fst.append(fst[i])
    else:
        new_snd.append(snd[i])

new_fst.reverse()
new_snd.reverse()

if new_fst == []:
    print("YODA")
else:
    print(int(''.join(list(map(str, new_fst)))))

if new_snd == []:
    print("YODA")
else:
    print(int(''.join(list(map(str, new_snd)))))


from pyspark.sql import SparkSession
from pyspark.sql.functions import col,column,expr
from pyspark.sql.types import StructType,StructField,StringType,LongType,DoubleType,IntegerType

spark=SparkSession.builder.master("local[*]").appName("Hello Spark").getOrCreate()

employees_schema = StructType([
    StructField("NAME", StringType(), True),
    StructField("JOB_TITLE", StringType(), True),
    StructField("DEPARTEMENT", StringType(), True),
    StructField("FULL_PART_TIME", StringType(), True),
    StructField("MONTHLY_HOURLY", StringType(), True),
    StructField("TYPICAL_HOURS", IntegerType(), True),
    StructField("ANNUAL_SALARY", DoubleType(), True),
    StructField("HOURLY_RATE", DoubleType(), True)
])

employees_data = spark.read.format("csv").option("Header", "True").schema(employees_schema).\
    load("D:\\Source-Data\\Employee_Data.csv");

# Add new column #
employees_data.withColumn("MANAGEMENT_FLAG", expr("DEPARTEMENT like '%MGMNT%' ")).select("DEPARTEMENT","MANAGEMENT_FLAG").show(100)
hourly_paid_employee = employees_data.filter(col("HOURLY_RATE") > 0.0).withColumn("HOURLY_PAYMENT",col("HOURLY_RATE") * col("TYPICAL_HOURS")).\
    select("NAME", "JOB_TITLE", "DEPARTEMENT", "TYPICAL_HOURS", "HOURLY_RATE", "HOURLY_PAYMENT").show()

# Rename column #
employees_data.withColumnRenamed("NAME","EMPLOYEE_NAME").withColumnRenamed("JOB_TITLE","TITLE").show(truncate=False)

# Drop column #
employees_data.drop("MONTHLY_HOURLY").show(50)

# case column datatype #
employees_data.select(expr("ANNUAL_SALARY/30"), expr("ANNUAL_SALARY/30 as MONTHLY_SALARY").cast("Integer")).printSchema()


"""
High-level revenue management functions for calculating booking limits.

Currently includes EMSRb, EMSRb + fare transformation (EMSRb-MR), and a
custom heuristic (EMSRb_MR_step).

"""

import numpy as np

from revpy.helpers import check_fares_decreasing, \
    cumulative_booking_limits, incremental_booking_limits
from revpy.optimizers import calc_EMSRb
from revpy.meta_optimizers import calc_EMSRb_MR

def booking_limits(fares, demands, cap, sigmas=None, method='EMSRb'):

    if method == 'EMSRb_MR_step':
        book_lim = iterative_booking_limits(fares, demands, cap, sigmas,
                                            'EMSRb_MR')
    else:
        prot_levels = protection_levels(fares, demands, sigmas, cap, method)
        cum_book_lim = cumulative_booking_limits(prot_levels, cap)
        book_lim = incremental_booking_limits(cum_book_lim)

    return book_lim

def protection_levels(fares, demands, sigmas=None, cap=None, method='EMSRb'):

    check_fares_decreasing(fares)

    if method == 'EMSRb':
        return calc_EMSRb(fares, demands, sigmas)

    elif method == 'EMSRb_MR':
        prot_levels = calc_EMSRb_MR(fares, demands, sigmas, cap)
        return prot_levels

    else:
        raise ValueError('method "{}" not supported'.format(method))

def iterative_booking_limits(fares, demands, cap, sigmas=None,
                             method='EMSRb_MR'):

    # iterate through all possible capacities (remaining seats) and
    # calculate cheapest open fare class (fc)
    cheapest_open_fc_list = []
    for remaining_cap in range(1, int(cap) + 1):
        temp_book_lims = \
            booking_limits(fares, demands, remaining_cap, sigmas, method)
        cheapest_open_fc = max(np.where(temp_book_lims > 0)[0])
        cheapest_open_fc_list.append(cheapest_open_fc)
    fcs = np.array(range(0, len(fares)))
    book_lims = np.zeros(len(fcs))

    # count the number of times a particular fare class was the cheapest
    # open
    for fc in fcs:
        book_lims[fc] = cheapest_open_fc_list.count(fc)

    return book_lims


# -*- coding: utf8 -*-
__author__ = 'Viktor Winkelmann'

from PacketStream import *
import dpkt

class UDPStream(PacketStream):
    def __init__(self, ipSrc, portSrc, ipDst, portDst, firstPacketNumber, pcapFile):
        PacketStream.__init__(self, ipSrc, portSrc, ipDst, portDst, firstPacketNumber, pcapFile)

        self.packets = []
        self.tsLastPacket = None

    def addPacket(self, packet, ts):
        if type(packet) != dpkt.udp.UDP:
            raise TypeError('Packet is no UDP packet!')

        if len(packet.data) == 0:
            return

        if len(self.packets) == 0:
            self.tsFirstpacket = ts

        self.packets.append(packet)
        self.tsLastPacket = ts

    def __iter__(self):
        return iter(self.packets)

    def getFirstBytes(self, count):
        bytes = b''
        index = 0
        while len(bytes) < count and index < len(self.packets):
            bytes += self.packets[index].data
            index += 1
        return bytes[:count]

    def getAllBytes(self):
        bytes = b''
        for packet in self.packets:
            bytes += packet.data
        return bytes


import sys

input = sys.stdin.readline

er = [0] * 250000
er[0], er[1] = 1, 1

for i in range(2, 250000):
    if er[i]: continue
    for j in range(i * i, 250000):
        if j % i == 0:
            er[j] = 1

while True:
    n = int(input())
    if n == 0: break

    result = 0
    for i in range(n + 1, n * 2 + 1):
        if not er[i]: result += 1

    print(result)


import tkinter as tk
from tkinter import messagebox
from PIL import ImageTk, Image
from pypet import Pypet

class TelinhaPypet:
  def __init__(self,janelinha):
    #################################################################
    # PRINCIPAL PROBLEMA: tentei usar o .pack_forget para esconder  #
    # a caixa de entrada (Entry) e os botões OK após os botões      #
    # principais serem pressionados mas dá erro, tornando           #
    # insustentável a existência de uma nova caixa e botão OK       #
    # a cada vez que os botões principais forem pressionados e      #
    # que por extensão, também não seja possível alterar os valores #
    # desejados como fome, saúde e etc...                           #
    #################################################################
    self.pypet = Pypet()
    janelinha.title('Pypet Game!')
    self.frame = tk.Frame(janelinha)
    self.frame.pack()

    self.name = tk.Label(self.frame, text = '')
    self.name.pack()

    self.__level = tk.Label(text='Level:' + str(self.pypet.lvlUP))
    self.__level.pack(side = 'top',anchor = "nw")
    # melhor que apertar um botão para ver o level é
    # vê-lo a todo momento, a intenção é colocar na posição
    # máxima do topo e máxima a esquerda, logo abaixo do
    # título, pypet game, mas não estou acertando a posição

    self.up = tk.Button
    self.up.bind('<Up>',self.showinfo)
    # Up Arrow Key não funciona e dá erro no programa,
    # impedindo que a função para mostrar as informações
    # aconteça

    self.n = tk.Button(self.frame, text = 'Nome')
    self.n['bg'] = 'black'
    self.n['fg'] = 'white'
    self.n.bind('<Button-1>',self.altnome)
    self.n.pack()

    self.hunger = tk.Button(self.frame, text= 'Alimentar')
    self.hunger['bg'] = 'green'
    self.hunger['fg'] = 'white'
    self.hunger.bind('<Button-1>', self.killHunger)
    self.hunger.pack()

    self.heal = tk.Button(self.frame, text= 'Curar +')
    self.heal['bg'] = 'red'
    self.heal['fg'] = 'white'
    self.heal.bind('<Button-1>', self.healing)
    self.heal.pack()

    self.play = tk.Button(self.frame, text= 'Brincar')
    self.play['bg'] = 'yellow'
    self.play.bind('<Button-1>', self.playtime)
    self.play.pack()

  def showinfo(self,event):
     messagebox.showinfo("Informações sobre seu Pypet", self.pypet.mostrar)

  def altnome (self, event):
    self.txt0 = 'Deseja adicionar ou mudar o nome de seu PyPet?'
    messagebox.askokcancel("Novo nome?", self.txt0)
    self.EnterName = tk.Entry(self.frame,border=2)
    self.EnterName['width'] = 10
    self.EnterName.pack(padx=10,pady=10)

    self.btn = tk.Button(self.frame,text='OK')
    self.btn.bind('<Button-1>',self.showname,self.namebtnHide_button,self.nameHide_button)
    self.btn.pack(padx=10,pady=10)
    # A intenção é fazer o ok realizar a ação de dar nome ao
    # pypet e apagar o botão ok e o entry até que o botão nome
    # seja pressionado novamente. Lógica não funciona
  def showname (self,event):
    self.pypet.nome = self.EnterName.get()
    self.name['text'] = self.pypet.nome
  def nameHide_button(self,event):
    self.EnterName.pack_forget()
  def namebtnHide_button(self,event):
    self.btn.pack_forget()

  def killHunger(self,event):
    self.txt1 = 'Informe o quanto deseja alimentar seu Pypet:'
    messagebox.showinfo("Matar a fome", self.txt1)
    self.informHunger = tk.Entry(self.frame,border=2)
    self.informHunger['width'] = 10
    self.informHunger.pack(padx=10,pady=10)
    self.pypet.fome = self.informHunger.get()
    if self.informHunger > 100:
      self.txthunger0 = 'Você quer matar o coitado com tanta comida usuário!!?? (ง︡'-'︠)ง'
      messagebox.showinfo("-_-", self.txthunger0)
      self.pypet.fome = 100
    if self.informHunger < 0:
      self.txthunger1 = 'Isso não deveria ser possível usuário, além de ser muita maldade. Como você fez isso??'
      messagebox.showinfo("-_-", self.txthunger1)
      self.pypet.fome = 0

  def healing(self,event):
    self.txt2 = 'Informe o quanto deseja curar seu Pypet:'
    messagebox.showinfo("Aumentar Saúde", self.txt2)
    self.informHealing = tk.Entry(self.frame,border=2)
    self.informHealing['width'] = 10
    self.informHealing.pack(padx=10,pady=10)
    self.pypet.saude += self.informHealing.get()
    if self.informHealing > 100:
      self.txtheal0 = 'Você vai causar uma overdose de remédios  no pobre Pypet usuário, você deveria cuidar dele!! (ง︡'-'︠)ง'
      messagebox.showinfo("-_-", self.txtheal0,icon='warning')
      self.pypet.saude = 100
    if self.informHealing < 0:
      self.txtheal1 = 'Isso não deveria ser possível usuário, além de ser muita maldade. Como você fez isso??'
      messagebox.showinfo("-_-", self.txtheal1,icon='warning')
      self.pypet.saude = 0

  def playtime(self,event):
    self.txt3 = 'Como pretende brincar? [1] - Ver TV (melhora baixa) [2] - Jogar bola (melhora mediana) [3] - Jogar Video-Game (Melhora muito)'
    messagebox.showinfo("Brincar", self.txt3)
    self.informPlaying = tk.Entry(self.frame,border=2)
    self.informPlaying['width'] = 10
    self.informPlaying.pack(padx=10,pady=10)
    self.y = self.informPlaying.get()
    while self.y < 0 or self.y > 3 or self.y != int:
      if self.y < 0:
        self.txtplay1 = 'Favor, escolher opção entre 1 e 3!'
        messagebox.showinfo("-_-", self.txtplay1)
        self.txt3 = 'Como pretende brincar? [1] - Ver TV (melhora baixa) [2] - Jogar bola (melhora mediana) [3] - Jogar Video-Game (Melhora muito)'
        messagebox.showinfo("Brincar", self.txt3)
        self.informPlaying = tk.Entry(self.frame,border=2)
        self.informPlaying['width'] = 10
        self.informPlaying.pack(padx=10,pady=10)
        self.y = self.informPlaying.get()
      if self.y > 3:
        self.txtplay2 = 'Favor, escolher opção entre 1 e 3!'
        messagebox.showinfo("-_-", self.txtplay2)
        self.txt3 = 'Como pretende brincar? [1] - Ver TV (melhora baixa) [2] - Jogar bola (melhora mediana) [3] - Jogar Video-Game (Melhora muito)'
        messagebox.showinfo("Brincar", self.txt3)
        self.informPlaying = tk.Entry(self.frame,border=2)
        self.informPlaying['width'] = 10
        self.informPlaying.pack(padx=10,pady=10)
        self.y = self.informPlaying.get()
      if self.y != int:
        self.txtplay3 = 'Escolha números e não letras usuário! Favor, respeitar as opções...'
        messagebox.showinfo("-_-", self.txtplay3)
        self.txtplay2 = 'Favor, escolher opção entre 1 e 3!'
        messagebox.showinfo("-_-", self.txtplay2)
        self.txt3 = 'Como pretende brincar? [1] - Ver TV (melhora baixa) [2] - Jogar bola (melhora mediana) [3] - Jogar Video-Game (Melhora muito)'
        messagebox.showinfo("Brincar", self.txt3)
        self.informPlaying = tk.Entry(self.frame,border=2)
        self.informPlaying['width'] = 10
        self.informPlaying.pack(padx=10,pady=10)
        self.y = self.informPlaying.get()
    if self.y == 1:
      self.pypet.x += -1
    if self.y == 2:
      self.pypet.x += -2
    if self.y == 3:
      self.pypet.x += -3

  #############fotinhas#######################################
  # criar a função faz com que a lógica das fotas não aconteça
  # fazendo com que não apareça nenhuma foto do Pypet ou talvex
  # só seja coisa do PIL do meu VS Code mesmo
  def fotinhas (self):
    i= 0
    while i == 0:
      if self.pypet.idade <= 10:
        self.frame1 = tk.Frame(width = 40, height = 40)
        self.frame1.pack()
        self.imgpypet = ImageTk.PhotoImage(Image.open("NewBorn Pypet.jpg"))
        self.label_imagem = tk.Label(self.frame,image=  self.imgpypet)
        self.label_imagem['width'] = 140
        self.label_imagem.pack()
      if self.pypet.idade >= 10 and self.pypet.humor == 'Feliz' or  self.pypet.humor == 'Super Alegre!' or self.pypet.fome > 70 and  self.pypet.saude > 70  :
        self.frame1 = tk.Frame(width = 40, height = 40)
        self.frame1.pack()
        self.imgpypet = ImageTk.PhotoImage(Image.open("HappyPypet.jpg"))
        self.label_imagem = tk.Label(self.frame,image= self.imgpypet)
        self.label_imagem['width'] = 140
        self.label_imagem.pack()
    if self.pypet.idade >= 10 and self.pypet.fome < 50 and self.pypet.saude  < 50:
        self.frame1 = tk.Frame(width = 40, height = 20)
        self.frame1.pack()
        self.imgpypet = ImageTk.PhotoImage(Image.open("NeedyPypet.jpg"))
        self.label_imagem = tk.Label(self.frame,image= self.imgpypet)
        self.label_imagem['width'] = 140
        self.label_imagem.pack()
    if self.pypet.idade >= 10 and self.pypet.humor == 'Triste' or self.pypet.humor == 'Com depressão':
        self.frame1 = tk.Frame(width = 40, height = 20)
        self.frame1.pack()
        self.imgpypet = ImageTk.PhotoImage(Image.open("BoredorStandbyPypet.jpg"))
        self.label_imagem = tk.Label(self.frame,image= self.imgpypet)
        self.label_imagem['width'] = 140
        self.label_imagem.pack()
    if self.pypet.idade >= 10 and self.pypet.humor == 'Contente' or self.pypet.fome > 45 and self.pypet.fome < 60 or self.pypet.saude > 45 and self.pypet.saude < 60 :
        self.frame1 = tk.Frame(width = 40, height = 20)
        self.frame1.pack()
        self.imgpypet = ImageTk.PhotoImage(Image.open("defaultPypet.jpeg"))
        self.label_imagem = tk.Label(self.frame,image= self.imgpypet)
        self.label_imagem['width'] = 140
        self.label_imagem.pack()
#############fotinhas#####################################


from ElectronicSystems import ElectronicSystem
#from Crystal import ConductionBand, ValenceBand
from LaserProfiles import PumpBeam, StedBeam
from Utility import EvolutionRecorder

import numpy as np
import sys

from multiprocessing import Process

class SolidStateStedSimulator(Process):
	#--------------------------------------------------------------------------
	def __init__(self, nSimSteps, resultContainer):
		"""
		Creates a simulator object for STED microscopy in solids.

		Parameters
		----------
		nSimSteps : int or float
			Number of iteration steps for the simulation
		resultContainer : multiprocessing.Queue
			Container to save simulation results
		"""
		super(SolidStateStedSimulator, self).__init__()

		self.numberOfSimulationSteps = int(nSimSteps + 1)
		self.resultContainer = resultContainer

	#--------------------------------------------------------------------------
	def setupSimulation(self, REx, REy, ETx, ETy, pumpAmpl=0.05, stedAmpl=0.5, laserXpos=0.0, laserYpos=0.0, cs=[1,1,1,1,1], eTR=25E-9):
		"""
		Configures all necessary parameters and creates the objects needed for the simulator.

		Parameters
		----------
		REx : array-like
			Represents the x-coordinates of the rare earths
		REy : array-like
			Represents the y-coordinates of the rare earths
		ETx : array-like
			Represents the x-coordinates of the electron traps
		ETy : array-like
			Represents the y-coordinates of the electron traps
		pumpAmpl : float
			Amplitude for the excitation laser beam
		stedAmpl : float
			Amplitude for the STED laser beam
		cs : array-like
			Cross-section for the rare earth in the order
			[gammaRE, sigPumpRE, sigIonizeRE, sigRepumpRE, sigStedRE]
		eTR : float
			Electron travel range
		"""
		self.rareEarthXCoordinates = np.array(REx)
		self.rareEarthYCoordinates = np.array(REy)
		self.electronTrapXCoordinates = np.array(ETx)
		self.electronTrapYCoordinates = np.array(ETy)
		self.pumpAmplitude = pumpAmpl
		self.stedAmplitude = stedAmpl
		self.laserXpos = laserXpos
		self.laserYpos = laserYpos
		self.crossSections = cs
		self.electronTravelRange = eTR

		self.electronicSystemsPopulationDistribution = np.zeros(REx.size + ETx.size)

		# set up valence band
		#self.vb = ValenceBand()

		# set up pump and sted beam
		self.pumpBeam = PumpBeam(x=self.laserXpos, y=self.laserYpos, amplitude=self.pumpAmplitude, wavelength=470E-9, numAperture=1.3)
		self.stedBeam = StedBeam(x=self.laserXpos, y=self.laserYpos, amplitude=self.stedAmplitude, wavelength=600E-9, numAperture=1.3)

		# set up electronic systems
		self.electronSystems = ElectronicSystem(RExPos   = self.rareEarthXCoordinates,
												REyPos   = self.rareEarthYCoordinates,
			                                    ETxPos   = self.electronTrapXCoordinates,
			                                    ETyPos   = self.electronTrapYCoordinates,
			                                    pumpBeam = self.pumpBeam,
			                                    stedBeam = self.stedBeam)

		self.electronSystems.setupTransitionProbabilities(gammaRE     = self.crossSections[0],
														  sigPumpRE   = self.crossSections[1],
														  sigIonizeRE = self.crossSections[2],
														  sigRepumpRE = self.crossSections[3],
														  sigStedRE   = self.crossSections[4])

		# set up evolution recorder for every rare earth in the system
		self.evolutionRecoders = list()
		self.evolutionRecorderIdx = dict()
		for reCnt, reIdx in zip(range(self.electronSystems.rareEarthIndices.size), self.electronSystems.rareEarthIndices):
			self.evolutionRecorderIdx[reIdx] = reCnt
			rePos = self.electronSystems.getPosition(reIdx)
			evRec = EvolutionRecorder('REpos=[%.2g, %.2g, %.2g]'%(rePos[0], rePos[1], rePos[2]), 'sim step', 'N')
			self.evolutionRecoders.append(evRec)

		np.random.seed()

	#--------------------------------------------------------------------------
	def run(self):
		self.electronSystems.createNeighbours(self.electronTravelRange)

		rareEarthIndices = self.electronSystems.rareEarthIndices
		electronTrapIndices = self.electronSystems.electronTrapIndices

		# randomly choose ~1% of the available electron traps
		# to be handeled in a single simulation step
		numRandElectronicSystems = int(0.01 * electronTrapIndices.size + 1)

		# prepare array for random indices to loop over
		self.randIndices = np.zeros(numRandElectronicSystems + rareEarthIndices.size, dtype=np.int32)

		# some constants to check during simulation
		progressUpdate = int(0.01*self.numberOfSimulationSteps)
		progressEvolutionRecord = int(0.05*self.numberOfSimulationSteps)

		for simStep in xrange(self.numberOfSimulationSteps):
			#if not simStep % progressUpdate:
			#	sys.stdout.write("\r%.0f %% "%(float(simStep)/float(self.numberOfSimulationSteps)*100.0))
			#	if int(float(simStep)/float(self.numberOfSimulationSteps)*100.0) == 99:
			#		print ""

			# build up list of random indices for electronic systems
			# to act on and always include all rare earths.
			self.randIndices[:numRandElectronicSystems] = np.random.choice(electronTrapIndices, numRandElectronicSystems, replace=False)
			self.randIndices[numRandElectronicSystems:] = rareEarthIndices
			np.random.shuffle(self.randIndices)

			for index in self.randIndices:
				randomNumber = np.random.rand()

				if index in rareEarthIndices:
					result = self.electronSystems.actOnRareEarth(index, randomNumber)

					if result == 1:
						# RE got ionized, electron is absorbed by CB, now recombine to somewhere
						#self.handleRecombination(self.electronSystems.getPosition(index))
						self.handleRecombination(index)

					elif result == 2:
						# RE got repumped, catch electron from VB
						#self.vb.donateElectron()
						#self.vb.evolutionDonatedElectrons.record(simStep, self.vb.donatedElectronCount)
						pass

				else:
					result = self.electronSystems.actOnElectronTrap(index, randomNumber)

					if result == 1:
						# ET got ionized, add electron to CB and recombine to somewhere
						#self.handleRecombination(self.electronSystems.getPosition(index))
						self.handleRecombination(index)

			# record ground/excited state evolution (internal)
			self.electronSystems.recordREstates()

			# record ground/excited state evolution (binned for result)
			if not simStep % progressEvolutionRecord:
				for REidx in self.electronSystems.rareEarthIndices:
					self.evolutionRecoders[self.evolutionRecorderIdx[REidx]].record(simStep,
																					self.electronSystems.rareEarthGroundStateCounter(REidx),
																					self.electronSystems.rareEarthExcitedStateCounter(REidx))

				self.electronSystems.resetRareEarthEvolutionCounters()

			if not simStep % 2:
				self.recordElectronTrapPopulationDistribution(self.electronSystems.population)

		# after last simulation step
		self.finalize()

	#--------------------------------------------------------------------------
	def handleRecombination(self, index):
		# now go through the conduction band's collected electrons and
		# find the ones which can recombine to either an electron trap
		# or to a rare earth.
		self.possibleRecombinationSlots = np.intersect1d(self.electronSystems.potentialRecombinationIndices,
														 self.electronSystems.getNeighbours(index))

		if not self.electronSystems.isRareEarth(index):
			probDecayToValenceBand = 1.0/(self.possibleRecombinationSlots.size + 1) # + 1 for the VB, to which the electron can decay.
			randomNumber = np.random.rand()
			if randomNumber <= probDecayToValenceBand:
				return

		self.electronSystems.recombine(np.random.choice(self.possibleRecombinationSlots))

	#--------------------------------------------------------------------------
	def recordElectronTrapPopulationDistribution(self, distribution):
		self.electronicSystemsPopulationDistribution += distribution

	#--------------------------------------------------------------------------
	def finalize(self):
		# generate the values which are needed for further processing
		self.groundStateAverage = np.average(np.array_split(self.evolutionRecoders[0]._g, 2)[1])
		self.excitedStateAverage = np.average(np.array_split(self.evolutionRecoders[0]._e, 2)[1])

		# collect single results in a dictionary
		result = dict()
		result["reXpos"] = self.rareEarthXCoordinates
		result["reYpos"] = self.rareEarthYCoordinates
		result["laserXpos"] = self.laserXpos
		result["laserYpos"] = self.laserYpos
		result["groundStateAverage"] = self.groundStateAverage
		result["excitedStateAverage"] = self.excitedStateAverage
		result["rePopulationEvolution_time"] = self.evolutionRecoders[0]._t
		result["rePopulationEvolution_groundState"] = self.evolutionRecoders[0]._g
		result["rePopulationEvolution_excitedState"] = self.evolutionRecoders[0]._e
		result["pumpAmplitude"] = self.pumpAmplitude
		result["stedAmplitude"] = self.stedAmplitude
		result["crossSections"] = self.crossSections
		result["electronTravelRange"] = self.electronTravelRange
		result["electronTrapXCoordinates"] = self.electronTrapXCoordinates
		result["electronTrapYCoordinates"] = self.electronTrapYCoordinates
		result["populationDistribution"] = self.electronicSystemsPopulationDistribution

		self.resultContainer.put(result)


"""
    Valid Palindrome

    Q. Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

        Note: For the purpose of this problem, we define empty string as valid palindrome.

        Example 1:

        Input: "A man, a plan, a canal: Panama"
        Output: true

        Example 2:

        Input: "race a car"
        Output: false

        Constraints:

        s consists only of printable ASCII characters.

"""

class Solution:
    def isPalindrome(self, s: str) -> bool:
        n=len(s)
        i,j=0,n-1
        while i<j:
            # print(s[i],s[j], type(s[i]), type(s[j]))
            if not s[i].isalpha() and not s[i].isdigit():
                i+=1
            elif not s[j].isalpha() and not s[j].isdigit():
                j-=1
            elif s[i].lower() == s[j].lower():
                i+=1
                j-=1
            else:
                return False
        # print(i,j)
        return True


import time
import re
import pandas as pd
from urllib.request import urlopen
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from modules.constants import UrlPaths
from modules.constants import ResultsCols as Cols
from modules.constants import Master
from tqdm.auto import tqdm
from ._prepare_chrome_driver import prepare_chrome_driver

def scrape_shutuba_table(race_id: str, date: str, file_path: str):
    """
    当日の出馬表をスクレイピング。
    dateはyyyy/mm/ddの形式。
    """
    driver = prepare_chrome_driver()
    # 取得し終わらないうちに先に進んでしまうのを防ぐため、暗黙的な待機（デフォルト10秒）
    driver.implicitly_wait(10)
    query = '?race_id=' + race_id
    url = UrlPaths.SHUTUBA_TABLE + query
    df = pd.DataFrame()
    try:
        driver.get(url)

        # メインのテーブルの取得
        for tr in driver.find_elements(By.CLASS_NAME, 'HorseList'):
            row = []
            for td in tr.find_elements(By.TAG_NAME, 'td'):
                if td.get_attribute('class') in ['HorseInfo']:
                    href = td.find_element(By.TAG_NAME, 'a').get_attribute('href')
                    row.append(re.findall(r'horse/(\d*)', href)[0])
                elif td.get_attribute('class') in ['Jockey']:
                    href = td.find_element(By.TAG_NAME, 'a').get_attribute('href')
                    row.append(re.findall(r'jockey/result/recent/(\w*)', href)[0])
                elif td.get_attribute('class') in ['Trainer']:
                    href = td.find_element(By.TAG_NAME, 'a').get_attribute('href')
                    row.append(re.findall(r'trainer/result/recent/(\w*)', href)[0])
                row.append(td.text)
            df = pd.concat([df, pd.DataFrame([row])], ignore_index=True)

        # レース結果テーブルと列を揃える
        df = df[[0, 1, 5, 6, 12, 13, 11, 3, 7, 9]]
        df.columns = [Cols.WAKUBAN, Cols.UMABAN, Cols.SEX_AGE, Cols.KINRYO, Cols.TANSHO_ODDS, Cols.POPULARITY, Cols.WEIGHT_AND_DIFF, 'horse_id', 'jockey_id', 'trainer_id']
        df.index = [race_id] * len(df)

        # レース情報の取得
        texts = driver.find_element(By.CLASS_NAME, 'RaceList_Item02').text
        texts = re.findall(r'\w+', texts)
        # 障害レースフラグを初期化
        hurdle_race_flg = False
        for text in texts:
            if 'm' in text:
                # 20211212：[0]→[-1]に修正
                df['course_len'] = [int(re.findall(r'\d+', text)[-1])] * len(df)
            if text in Master.WEATHER_LIST:
                df["weather"] = [text] * len(df)
            if text in Master.GROUND_STATE_LIST:
                df["ground_state"] = [text] * len(df)
            if '稍' in text:
                df["ground_state"] = [Master.GROUND_STATE_LIST[1]] * len(df)
            if '不' in text:
                df["ground_state"] = [Master.GROUND_STATE_LIST[3]] * len(df)
            if '芝' in text:
                df['race_type'] = [list(Master.RACE_TYPE_DICT.values())[0]] * len(df)
            if 'ダ' in text:
                df['race_type'] = [list(Master.RACE_TYPE_DICT.values())[1]] * len(df)
            if '障' in text:
                df['race_type'] = [list(Master.RACE_TYPE_DICT.values())[2]] * len(df)
                hurdle_race_flg = True
            if "右" in text:
                df["around"] = [Master.AROUND_LIST[0]] * len(df)
            if "左" in text:
                df["around"] = [Master.AROUND_LIST[1]] * len(df)
            if "直線" in text:
                df["around"] = [Master.AROUND_LIST[2]] * len(df)
            if "新馬" in text:
                df["race_class"] = [Master.RACE_CLASS_LIST[0]] * len(df)
            if "未勝利" in text:
                df["race_class"] = [Master.RACE_CLASS_LIST[1]] * len(df)
            if "１勝クラス" in text:
                df["race_class"] = [Master.RACE_CLASS_LIST[2]] * len(df)
            if "２勝クラス" in text:
                df["race_class"] = [Master.RACE_CLASS_LIST[3]] * len(df)
            if "３勝クラス" in text:
                df["race_class"] = [Master.RACE_CLASS_LIST[4]] * len(df)
            if "オープン" in text:
                df["race_class"] = [Master.RACE_CLASS_LIST[5]] * len(df)

        # グレードレース情報の取得
        if len(driver.find_elements(By.CLASS_NAME, 'Icon_GradeType3')) > 0:
            df["race_class"] = [Master.RACE_CLASS_LIST[6]] * len(df)
        elif len(driver.find_elements(By.CLASS_NAME, 'Icon_GradeType2')) > 0:
            df["race_class"] = [Master.RACE_CLASS_LIST[7]] * len(df)
        elif len(driver.find_elements(By.CLASS_NAME, 'Icon_GradeType1')) > 0:
            df["race_class"] = [Master.RACE_CLASS_LIST[8]] * len(df)

        # 障害レースの場合
        if hurdle_race_flg:
            df["around"] = [Master.AROUND_LIST[3]] * len(df)
            df["race_class"] = [Master.RACE_CLASS_LIST[9]] * len(df)

        df['date'] = [date] * len(df)
    except Exception as e:
        print(e)
    finally:
        driver.close()
        driver.quit()

    # 取消された出走馬を削除
    df = df[df[Cols.WEIGHT_AND_DIFF] != '--']
    df.to_pickle(file_path)

def scrape_horse_id_list(race_id_list: list) -> list:
    """
    当日出走するhorse_id一覧を取得
    """
    print('sraping horse_id_list')
    horse_id_list = []
    for race_id in tqdm(race_id_list):
        query = '?race_id=' + race_id
        url = UrlPaths.SHUTUBA_TABLE + query
        html = urlopen(url)
        soup = BeautifulSoup(html, 'lxml', from_encoding='utf-8')
        horse_td_list = soup.find_all("td", attrs={'class': 'HorseInfo'})
        for td in horse_td_list:
            horse_id = re.findall(r'\d+', td.find('a')['href'])[0]
            horse_id_list.append(horse_id)
    return horse_id_list


import numpy as np
from abc import ABC, abstractmethod
from packages.utils.utils import sampleDiscrete
import time

class CountingSimulator(ABC):
    """
    Base class for number of customers leaving the parallel queues
    """

    @abstractmethod
    def __init__(self, nServers):
        self.nServers = nServers

    @abstractmethod
    def draw(self):
        pass

class Generic(CountingSimulator):
    """
    Counting Simulator with pmfs as input for the number of customers leaving each queue
    """

    def __init__(self, pmfs):
        """

        :param pmfs: list of np.arrays: each np.array contains probability values for number of customers leaving, e.g. [.1,.2,.7], starting with p(k=0)
        """
        self.pmfs = pmfs
        nServers = self.pmfs.__len__()
        super().__init__(nServers)

    def draw(self):
        """

        :return:  array of ints - number of customers leaving each queue
        """
        sample = np.zeros(self.nServers, int)
        for i in range(self.nServers):
            sample[i] = sampleDiscrete(self.pmfs[i])
        return sample

class GammaArrivalExpService(CountingSimulator):
    """
    Counting simulator for renewal arrival process with gamma increments and iid Exponential service times
    """

    def __init__(self, alpha, beta, mu):
        """

        :param alpha: scalar >0: shape parameter for the gamma process
        :param beta: scalar >0: rate parameter for the gamma process
        :param mu: array of size nServers >0: rate parameter for the exponential service times
        """
        self.alpha = alpha
        self.beta = beta
        # Vector
        self.mu = np.array(mu)
        nServers = self.mu.__len__()
        super().__init__(nServers)

    def draw(self):
        """

        :return: array of ints - number of customers leaving each queue
        """
        # sample = np.random.geometric(self.beta / (self.mu + self.beta))
        sample = np.random.negative_binomial(self.alpha * np.ones_like(self.mu), 1 - self.mu / (self.mu + self.beta))
        return sample

class DetArrivalExpService(CountingSimulator):
    """
    Counting simulator for deterministic arrival process and renewal process iid Exponential service times
    """

    def __init__(self, inter_arrival_time, mu):
        """

        :param inter_arrival_time: deterministicinter-arrival time
        :param mu:  mu: array of size nServers >0: rate parameter for the exponential service times
        """
        self.inter_arrival_time = inter_arrival_time
        # Vector
        self.mu = np.array(mu)
        nServers = self.mu.__len__()
        super().__init__(nServers)

    def draw(self):
        """

        :return: array of ints - number of customers leaving each queue
        """
        sample = np.random.poisson(self.mu * self.inter_arrival_time)
        return sample

# TODO Document
class GammaArrivalParetoService(CountingSimulator):
    def __init__(self, alpha, beta, a, m):
        self.alpha = alpha
        self.beta = beta
        # Vector
        self.a = np.array(a)
        self.m = np.array(m)
        nServers = self.m.__len__()
        super().__init__(nServers)

    def draw(self):
        # begin = time.time()
        interarrival_time = np.random.gamma(self.alpha, 1 / self.beta)
        sample = np.zeros(self.nServers)
        cum_time = np.zeros(self.nServers)
        not_enough_samples = np.array([True] * self.nServers)
        while not_enough_samples.any():
            service_time_all = np.random.pareto(self.a) * self.m
            cum_time += service_time_all
            sample[np.where(cum_time <= interarrival_time)[0]] += 1
            enough_samples_idx = np.where(cum_time > interarrival_time)[0]
            if len(enough_samples_idx) > 0:
                not_enough_samples[enough_samples_idx] = False
        # print('draw', time.time() - begin)
        return sample

    # def draw(self):
    #     begin = time.time()
    #     interarrival_time = np.random.gamma(self.alpha, 1 / self.beta)
    #     sample = np.zeros(self.nServers)
    #     for server in range(self.nServers):
    #         cum_time = 0
    #         not_enough_samples = True
    #         while not_enough_samples:
    #             service_time = np.random.pareto(self.a[server]) * self.m[server]
    #             cum_time += service_time
    #             if cum_time <= interarrival_time:
    #                 sample[server] += 1
    #             else:
    #                 not_enough_samples = False
    #     print('draw', time.time() - begin)
    #     return sample


import PySimpleGUI as sg
import cv2
import numpy as np

def main():
    sg.theme("LightGreen")

    # Define the window layout
    layout_left = [
        [sg.Text("Text right", size=(50,1), font='Courier 20', background_color='white', key='-textr-')],
        [sg.Button("Exit", size=(10, 1))],
    ]

    layout_right = [
        [sg.Image(size=(10,20), filename="", key="-IMAGE-")],
    ]

    layout = [
        [sg.Column(layout_left),
        sg.VSeparator(),
        sg.Column(layout_right)]
    ]

    w, h = sg.Window.get_screen_size()

    # Create the window and show it without the plot
    window = sg.Window("OpenCV Integration", layout, location=(800, 400), size=(w,h))

    cap = cv2.VideoCapture(0)

    while True:
        event, values = window.read(timeout=20)
        if event == "Exit" or event == sg.WIN_CLOSED:
            break

        ret, frame = cap.read()

        imgbytes = cv2.imencode(".png", frame)[1].tobytes()
        window["-IMAGE-"].update(data=imgbytes)

    window.close()

main()


# '-' 나오고 그 다음 '-' 나올때까지 다 더해서 한번에 빼주기
import sys
input = sys.stdin.readline

string = input().split('-')

for i in range(len(string)):
    ans = 0
    temp = ''
    for j in range(len(string[i])):
        if string[i][j].isdigit() :
            temp += string[i][j]
        else :
            ans += int(temp)
            temp = ''
    if temp :
        ans+=int(temp)

    string[i] = ans

ans = string[0]
for i in range(1,len(string)):
    ans -= string[i]

print(ans)

백준/Silver/1541. 잃어버린 괄호/잃어버린 괄호.py


import pandas as pd
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.operators.python_operator import PythonOperator
from airflow.providers.postgres.operators.postgres import PostgresOperator
from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.providers.amazon.aws.sensors.s3 import S3KeySensor
import requests
import os
import logging

def load_sales_file(url, tmp_file, **context):
    req = requests.get(url)
    url_content = req.content
    with open(tmp_file, 'wb') as f:
        f.write(url_content)
        context['ti'].xcom_push(key='sales_file', value='{}'.format(tmp_file))

# def extract_data(url, tmp_file, **context) -> pd.DataFrame:
#     pd.read_csv(url).to_csv(tmp_file, header=True, index=False) # Изменение to_csv

def db_load_data(schema, table_name, **context):
    pg_hook = PostgresHook(postgres_conn_id='postgres_db', supports_autocommit=True)
    logging.info(f"Clearing Postgres table {schema}.{table_name}")
    pg_hook.run(f"truncate {schema}.{table_name}")
    tmp_file = context['ti'].xcom_pull(task_ids='extract_data', key='sales_file')

    logging.info(f"Loading CSV {tmp_file} into Postgres table {schema}.{table_name}")

    query = "COPY {}.{} FROM STDIN WITH CSV HEADER DELIMITER ',' ".format(schema, table_name)

    conn = pg_hook.get_conn()
    pg_cursor = conn.cursor()
    pg_cursor.copy_expert(sql=query, file=open(tmp_file, 'r'))
    conn.commit()

def sales_data_analisys_to_csv(**context):
    sales_file = context['ti'].xcom_pull(task_ids='extract_data', key='sales_file')
    pg_hook = PostgresHook(postgres_conn_id='postgres_db')
    query = """
                COPY (
                    select payment, date_trunc('month', date)::date "month", round(sum(total), 2) revenue
                    from my_schema.sales
                    group by 1,2
                    order by 1,2
                    )
                TO STDOUT WITH CSV HEADER
                """

    pg_hook.copy_expert(query, sales_file)

def remove_temp_file(**context):
    tmp_file = context['ti'].xcom_pull(task_ids='extract_data', key='sales_file')
    if os.path.exists(tmp_file):
        os.remove(tmp_file)
        logging.info(f"The following was removed: {tmp_file}")
    else:
        logging.info("The file does not exist")

with DAG(dag_id='dag_sales',
         default_args={'owner': 'airflow'},
         schedule_interval='@daily',
         start_date=days_ago(1)
    ) as dag:

    extract_data_op = PythonOperator(
        task_id='extract_data',
        python_callable=load_sales_file,
        op_kwargs={
            'url': 'https://github.com/plotly/datasets/raw/master/supermarket_Sales.csv',
            'tmp_file': '/opt/airflow/tmp/Sales.csv'}
    )

    # truncate_sales_table = PostgresOperator(task_id='truncate_table'
    #                                       , postgres_conn_id='postgres_db'
    #                                       , sql="""
    #                                       truncate table sales
    #                                       """)

    load_sales_data_to_dwh_op = PythonOperator(
        task_id='file_to_db',
        # provide_context=True,
        python_callable=db_load_data,
        op_kwargs={'database': 'my_db',
                   'schema': 'my_schema',
                   'table_name': 'sales'},
                   )

    remove_temp_file_op = PythonOperator(
        task_id='removing_temp_file',
        python_callable=remove_temp_file,
    )

    prepare_csv_sales_data_op = PythonOperator(
        task_id='sales_data_analisys_to_csv',
        python_callable=sales_data_analisys_to_csv
    )

    # transform_data = PythonOperator(
    #     task_id='transform_data',
    #     python_callable=transform_data,
    #     dag=dag,
    #     op_kwargs={
    #         'tmp_file': '/tmp/file.csv',
    #         'tmp_agg_file': '/tmp/file_agg.csv',
    #         'group': ['A', 'B', 'C'],
    #         'agreg': {"D": sum}}
    # )

    # load_data = PythonOperator(
    #     task_id='load_data',
    #     python_callable=load_data,
    #     dag=dag,
    #     op_kwargs={
    #         'tmp_file': '/tmp/file.csv',
    #         'table_name': 'table'
    #     }
    # )

    # email_op = EmailOperator(
    #     task_id='send_email',
    #     to="rustam.trainings@yandex.ru",
    #     #to="stepikairflowcourse@yandex.ru",
    #     subject="Test Email Please Ignore",
    #     html_content=None,
    #     files=['/tmp/file.csv']
    # )

    extract_data_op >> load_sales_data_to_dwh_op >> remove_temp_file_op >> prepare_csv_sales_data_op


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [("ssme_activities", "0001_initial")]

    operations = [
        migrations.AddField(
            model_name="campaignbeneficiary",
            name="pourcentage_attendu",
            field=models.FloatField(default=0.0, null=True),
        ),
        migrations.AddField(
            model_name="campaignbeneficiaryproduct",
            name="pourcentage_attendu",
            field=models.FloatField(default=0.0, null=True),
        ),
    ]


import re
import numpy as np

# Gensim
import gensim
import gensim.corpora as corpora
from gensim.models import CoherenceModel

# Enable logging for gensim
import logging

logging.basicConfig(
    format="%(asctime)s : %(levelname)s : %(message)s", level=logging.ERROR
)

# Download File: http://mallet.cs.umass.edu/dist/mallet-2.0.8.zip

def compute_coherence_values(
    dictionary, corpus, texts, limit, start=2, step=3
):
    """
    Compute c_v coherence for various number of topics

    Parameters:
    ----------
    dictionary : Gensim dictionary
    corpus : Gensim corpus
    texts : List of input texts
    limit : Max num of topics

    Returns:
    -------
    model_list : List of LDA topic models
    coherence_values : Coherence values corresponding to the LDA model with respective number of topics
    """
    mallet_path = "model/mallet-2.0.8/bin/mallet"
    coherence_values = []
    model_list = []
    for num_topics in range(start, limit + 1, step):
        model = gensim.models.wrappers.LdaMallet(
            mallet_path,
            corpus=corpus,
            num_topics=num_topics,
            id2word=dictionary,
        )
        model_list.append(model)
        coherencemodel = CoherenceModel(
            model=model, texts=texts, dictionary=dictionary, coherence="c_v"
        )
        coherence_values.append(coherencemodel.get_coherence())

    return model_list, coherence_values

def topic_modeling(preprocessed_data, start, limit, step, num_words_per_topic):
    """
    Perform topic modeling using Gensim, find the optimal number of topics
    and the associated keywords.

    Parameters:
    ----------
    preprocessed_data : Reviews dataframe after preprocessing step
    start : Minimum number of topics considered
    limit : Maximum number of topics considered
    step : Increment during the search of the optimal number of topics
    num_words_per_topic : Number of words to display per topic

    Returns:
    -------
    topic_keywords : Dictionary with the topics and the associated keywords
    """
    # Create Dictionary
    id2word = corpora.Dictionary(preprocessed_data)
    # Create Corpus
    texts = preprocessed_data
    # Term Document Frequency ("doc2bow" converts document into the bag-of-words
    # (BoW) format = list of (token_id, token_count) tuples.)
    corpus = [id2word.doc2bow(text) for text in texts]

    # Find optimal number of topics and associated LDA model
    model_list, coherence_values = compute_coherence_values(
        dictionary=id2word,
        corpus=corpus,
        texts=preprocessed_data,
        start=start,
        limit=limit,
        step=step,
    )

    optimal_model = model_list[np.argmax(coherence_values)]
    model_topics = optimal_model.show_topics(
        formatted=False, num_words=num_words_per_topic
    )

    topic_keywords = {}
    for topic_number in range(len(model_topics)):
        topic = model_topics[topic_number][0]
        keywords = [element[0] for element in model_topics[topic_number][1]]
        topic_keywords[topic] = keywords

    return topic_keywords


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('api', '0135_auto_20160706_1829'),
    ]

    operations = [
        migrations.AddField(
            model_name='song',
            name='main_unit',
            field=models.CharField(default=b"\xce\xbc's", max_length=20),
            preserve_default=True,
        ),
    ]


import logging
from fn_ldap_utilities.util.helper import LDAPUtilitiesHelper, get_domains_list
from fn_ldap_utilities.util.ldap_utils import LDAPDomains

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
log.addHandler(logging.StreamHandler())

def selftest_function(opts):
    """
    Selftest function will try to connect to the LDAP instance.
    Fail if any exceptions are raised.
    """

    domains_list = get_domains_list(opts)
    ldap = LDAPDomains(opts)

    state = "success"
    reason = "N/A"
    domain = "N/A"
    conn = ""

    for domain_name in domains_list:
        try:
            """
            If labels are given to the servers in the app.config `domain_name` will start with 'fn_ldap_utilities:' else if
            labels are not given then `domain_name` will equal 'fn_ldap_utilites'.
            If `domain_name` contains ':' then a labels have been given to the servers and `domain` will be set to the label given to the server else
            if `domain_name` does not contain ':' then servers have not been labled and `domain` will be set to `domain_name` which will equal 'fn_ldap_utilities'.
            """
            domain = domain_name[domain_name.index(":")+1:] if ":" in domain_name else domain_name

            # Instansiate helper (which gets appconfigs from file)
            helper = LDAPUtilitiesHelper(ldap.ldap_domain_name_test(domain, domains_list))

            options = opts.get(domain_name, {})

            log.info(f"Verifying app.config values for {str(options.get('ldap_server'))} config section")

            # Instansiate LDAP Server and Connection
            conn = helper.get_ldap_connection()

            # Bind to the connection
            log.info("Verifying LDAP connection...")
            conn.bind()

            log.info("Test was successful\n")
        except Exception as err:
            state = "failure"
            reason = err
            break

        finally:
            # Unbind connection
            if conn:
                conn.unbind()

    if state == "success":
        return {"state": state}

    return {
        "state": state,
        "reason": reason,
        "domain": domain
    }


"""empty message

Revision ID: c31a1db2ac29
Revises: 2585dd9e59fe
Create Date: 2023-01-09 08:59:43.171913

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = 'c31a1db2ac29'
down_revision = '2585dd9e59fe'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('animal_alerts', 'date_recorded')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('animal_alerts', sa.Column('date_recorded', postgresql.TIMESTAMP(), autoincrement=False, nullable=True))
    # ### end Alembic commands ###


from codepack.plugins.storable_job import StorableJob
from apscheduler.jobstores.base import BaseJobStore, JobLookupError, ConflictingIdError
from apscheduler.util import datetime_to_utc_timestamp, utc_timestamp_to_datetime
from datetime import datetime
from typing import Optional, TypeVar
try:
    import cPickle as pickle
except ImportError:  # pragma: nocover
    import pickle

Job = TypeVar('Job', bound='apscheduler.job.Job')  # noqa: F821
Storage = TypeVar('Storage', bound='codepack.storages.storage.Storage')  # noqa: F821

class JobStore(BaseJobStore):
    def __init__(self, storage: Storage, pickle_protocol: int = pickle.HIGHEST_PROTOCOL) -> None:
        super().__init__()
        self.storage = storage
        self.pickle_protocol = pickle_protocol

    def lookup_job(self, job_id: str) -> Optional[Job]:
        item = self.storage.load(key=job_id)
        if item:
            item.bind_job(scheduler=self._scheduler, alias=self._alias)
            return item.job
        else:
            return None

    def _get_sorted_items(self) -> list:
        all_item_keys = self.storage.list_all()
        all_items = self.storage.load(key=all_item_keys)
        return sorted(all_items, key=lambda x: x.job.next_run_time)

    def get_due_jobs(self, now: datetime) -> list:
        now_timestamp = datetime_to_utc_timestamp(now)
        pending = list()
        sorted_items = self._get_sorted_items()
        for item in sorted_items:
            _next_run_time = datetime_to_utc_timestamp(item.job.next_run_time)
            if _next_run_time is None or _next_run_time > now_timestamp:
                break
            item.bind_job(scheduler=self._scheduler, alias=self._alias)
            pending.append(item.job)
        return pending

    def get_next_run_time(self) -> Optional[datetime]:
        sorted_items = self._get_sorted_items()
        for item in sorted_items:
            _next_run_time = datetime_to_utc_timestamp(item.job.next_run_time)
            if _next_run_time is not None:
                return utc_timestamp_to_datetime(_next_run_time)
        return None

    def get_all_jobs(self) -> list:
        all_item_keys = self.storage.list_all()
        all_items = self.storage.load(key=all_item_keys)
        for item in all_items:
            item.bind_job(scheduler=self._scheduler, alias=self._alias)
        return [item.job for item in all_items]

    def add_job(self, job: Job) -> None:
        if self.storage.exist(key=job.id):
            raise ConflictingIdError(job.id)
        item = StorableJob(job=job)
        self.storage.save(item=item, update=True)

    def update_job(self, job: Job) -> None:
        item = StorableJob(job=job)
        self.storage.save(item=item, update=True)

    def remove_job(self, job_id: str) -> None:
        if not self.storage.exist(key=job_id):
            raise JobLookupError(job_id)
        self.storage.remove(key=job_id)

    def remove_all_jobs(self) -> None:
        all_item_keys = self.storage.list_all()
        self.storage.remove(key=all_item_keys)


from fastapi import APIRouter, Depends, File, Form, HTTPException
from schema.openai_completion_schema import UpdateCompletionResponse
from service import openai_file_service
from sqlalchemy.orm import Session
from typing import Annotated
from util.db_util import get_db

router = APIRouter(
    prefix="/file/openai",
    tags=["file openai"],
    responses={404: {"description": "Not found"}},
)

@router.post("/pdf")
def create_upload_pdf(
    pdf_file: Annotated[bytes, File()],
    username: Annotated[str, Form()],
    template_id: Annotated[int, Form()],
    db: Session = Depends(get_db),
) -> UpdateCompletionResponse:
    if not pdf_file:
        raise HTTPException(
            status_code=422,
            detail=f"Cannot upload empty PDF file",
        )
    return openai_file_service.upload_pdf_in_completion(
        pdf_file, username, template_id, db
    )


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

def text_encrypt(msg):
    """数据加密"""
    msg = msg.encode('utf-8')
    length = len(msg)
    default_length = 245
    # 长度不用分段
    if length < default_length:
        return base64.b64encode(encrypt(msg))
    # 需要分段
    offset = 0
    res = []
    while length - offset > 0:
        if length - offset > default_length:
            res.append(encrypt(msg[offset:offset + default_length]))
        else:
            res.append(encrypt(msg[offset:]))
        offset += default_length
    byte_data = b''.join(res)
    return base64.b64encode(byte_data)

def text_decrypt(msg):
    """数据解密"""
    msg = base64.b64decode(msg)
    length = len(msg)
    default_length = 256
    # 长度不用分段
    if length < default_length:
        return b''.join(decrypt(msg))
    # 需要分段
    offset = 0
    res = []
    while length - offset > 0:
        if length - offset > default_length:
            res.append(decrypt(msg[offset:offset + default_length]))
        else:
            res.append(decrypt(msg[offset:]))
        offset += default_length

    return b''.join(res).decode('utf8')

def decrypt(crypt_text):  # 用私钥解密
    with open('private.pem', 'rb') as privatefile:
        p = privatefile.read()
    privkey = rsa.PrivateKey.load_pkcs1(p)
    lase_text = rsa.decrypt(crypt_text, privkey)

    return lase_text

def encrypt(text):  # 用公钥加密
    with open('public.pem', 'rb') as publickfile:
        p = publickfile.read()
    # print(p)
    pubkey = rsa.PublicKey.load_pkcs1(p)
    crypt_text = rsa.encrypt(text, pubkey)
    # print(type(crypt_text))
    return crypt_text  # 加密后的密文

def create_keys():  # 生成公钥和私钥
    (pubkey, privkey) = rsa.newkeys(2048)
    pub = pubkey.save_pkcs1()
    print(pub)
    with open('public.pem', 'wb+') as f:
        f.write(pub)

    pri = privkey.save_pkcs1()
    print(pri)
    with open('private.pem', 'wb+') as f:
        f.write(pri)


#!/usr/bin/env python

# Author: Lasitha Wijayarathne
# This node simulates the pulsating behaviour of the table

import numpy as np
import scipy
import rospy
from geometry_msgs.msg import Pose, Twist
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from std_msgs.msg import Float64

# starting time
time_start = 0.0

# build a simple trajectory from the start to end position
#   - for the FS100, we can get by with a simple 2-point trajectory
#   - the controller handles the necessary accel/decel to make smooth motion
def build_traj(start, end, duration):
	# if sorted(start.name) <> sorted(end.name):
	# 	rospy.logerr('Start and End position joint_names mismatch')
	# 	raise

	# assume the start-position joint-ordering
	joint_names = start.name

	start_pt = JointTrajectoryPoint()
	start_pt.positions = start.position
	start_pt.velocities = [0]*len(start.position)
	start_pt.time_from_start = rospy.Duration(1.0)

	end_pt = JointTrajectoryPoint()
	for j in joint_names:
		idx = end.name.index(j)
		end_pt.positions.append(end.position[idx])  # reorder to match start-pos joint ordering
		end_pt.velocities.append(0)
		end_pt.time_from_start = rospy.Duration(duration)

	return JointTrajectory(joint_names=joint_names, points=[start_pt, end_pt])

def move_table(pos_1, pos_1_x, pos_1_y, pos_2, pos_2_y):
	_pub_pos_pr.publish(pos_1)
	_pub_pos_pr_x.publish(pos_1_x)
	_pub_pos_pr_y.publish(pos_1_y)
	_pub_pos_tilt.publish(pos_2)
	_pub_pos_tilt_y.publish(pos_2_y)

if __name__ == '__main__':

	rospy.init_node("table_pulsate")

	_pub_pos_pr = rospy.Publisher('/iiwa/EffortJointInterface_table_joint_controller/command', Float64,
	                             queue_size=1)
	_pub_pos_pr_x = rospy.Publisher('/iiwa/EffortJointInterface_table_joint_x_controller/command', Float64,
	                             queue_size=1)
	_pub_pos_pr_y = rospy.Publisher('/iiwa/EffortJointInterface_table_joint_y_controller/command', Float64,
	                             queue_size=1)
	_pub_pos_tilt = rospy.Publisher('/iiwa/EffortJointInterface_table_joint_tilt_x_controller/command',Float64,
                             queue_size=1)
	_pub_pos_tilt_y = rospy.Publisher('/iiwa/EffortJointInterface_table_joint_tilt_y_controller/command',Float64,
                             queue_size=1)

	r = rospy.Rate(100) # 100hz

	# create a sript to run sinusoidal signals forever
	t = time_start
	while not rospy.is_shutdown():
		j1_pos   = 0.02 * np.sin(2*np.pi*t) + 0.00
		j1_pos_x = 0.02 * np.cos(2*np.pi*t) + 0.00
		j1_pos_y = 0.02 * np.cos(2*np.pi*t) + 0.00
		j2_pos   = 0.02 * np.cos(1*np.pi*1*t)
		j2_pos_y = 0.0 * np.cos(1*np.pi*1*t)
		move_table(j1_pos, j1_pos_x, j1_pos_y, j2_pos, j2_pos_y)
		t += 0.01
		r.sleep()

	# rospy.spin()


import os
import subprocess
from unittest import mock

import fixtures
from testtools.matchers import Equals

from snapcraft_legacy.internal import sources
from tests.legacy import unit

# LP: #1733584
class TestMercurial(unit.sources.SourceTestCase):  # type: ignore
    def setUp(self):
        super().setUp()
        patcher = mock.patch("snapcraft_legacy.sources.Mercurial._get_source_details")
        self.mock_get_source_details = patcher.start()
        self.mock_get_source_details.return_value = ""
        self.addCleanup(patcher.stop)

    def test_pull(self):
        hg = sources.Mercurial("hg://my-source", "source_dir")
        hg.pull()

        self.mock_run.assert_called_once_with(
            ["hg", "clone", "hg://my-source", "source_dir"]
        )

    def test_pull_branch(self):
        hg = sources.Mercurial(
            "hg://my-source", "source_dir", source_branch="my-branch"
        )
        hg.pull()

        self.mock_run.assert_called_once_with(
            ["hg", "clone", "-u", "my-branch", "hg://my-source", "source_dir"]
        )

    def test_pull_tag(self):
        hg = sources.Mercurial("hg://my-source", "source_dir", source_tag="tag")
        hg.pull()

        self.mock_run.assert_called_once_with(
            ["hg", "clone", "-u", "tag", "hg://my-source", "source_dir"]
        )

    def test_pull_commit(self):
        hg = sources.Mercurial("hg://my-source", "source_dir", source_commit="2")
        hg.pull()

        self.mock_run.assert_called_once_with(
            ["hg", "clone", "-u", "2", "hg://my-source", "source_dir"]
        )

    def test_pull_existing(self):
        self.mock_path_exists.return_value = True

        hg = sources.Mercurial("hg://my-source", "source_dir")
        hg.pull()

        self.mock_run.assert_called_once_with(["hg", "pull", "hg://my-source"])

    def test_pull_existing_with_tag(self):
        self.mock_path_exists.return_value = True

        hg = sources.Mercurial("hg://my-source", "source_dir", source_tag="tag")
        hg.pull()

        self.mock_run.assert_called_once_with(
            ["hg", "pull", "-r", "tag", "hg://my-source"]
        )

    def test_pull_existing_with_commit(self):
        self.mock_path_exists.return_value = True

        hg = sources.Mercurial("hg://my-source", "source_dir", source_commit="2")
        hg.pull()

        self.mock_run.assert_called_once_with(
            ["hg", "pull", "-r", "2", "hg://my-source"]
        )

    def test_pull_existing_with_branch(self):
        self.mock_path_exists.return_value = True

        hg = sources.Mercurial(
            "hg://my-source", "source_dir", source_branch="my-branch"
        )
        hg.pull()

        self.mock_run.assert_called_once_with(
            ["hg", "pull", "-b", "my-branch", "hg://my-source"]
        )

    def test_init_with_source_branch_and_tag_raises_exception(self):
        raised = self.assertRaises(
            sources.errors.SnapcraftSourceIncompatibleOptionsError,
            sources.Mercurial,
            "hg://mysource",
            "source_dir",
            source_tag="tag",
            source_branch="branch",
        )

        self.assertThat(raised.source_type, Equals("mercurial"))
        self.assertThat(raised.options, Equals(["source-tag", "source-branch"]))

    def test_init_with_source_commit_and_tag_raises_exception(self):
        raised = self.assertRaises(
            sources.errors.SnapcraftSourceIncompatibleOptionsError,
            sources.Mercurial,
            "hg://mysource",
            "source_dir",
            source_commit="2",
            source_tag="tag",
        )

        self.assertThat(raised.source_type, Equals("mercurial"))
        self.assertThat(raised.options, Equals(["source-tag", "source-commit"]))

    def test_init_with_source_commit_and_branch_raises_exception(self):
        raised = self.assertRaises(
            sources.errors.SnapcraftSourceIncompatibleOptionsError,
            sources.Mercurial,
            "hg://mysource",
            "source_dir",
            source_commit="2",
            source_branch="branch",
        )

        self.assertThat(raised.source_type, Equals("mercurial"))
        self.assertThat(raised.options, Equals(["source-branch", "source-commit"]))

    def test_init_with_source_depth_raises_exception(self):
        raised = self.assertRaises(
            sources.errors.SnapcraftSourceInvalidOptionError,
            sources.Mercurial,
            "hg://mysource",
            "source_dir",
            source_depth=2,
        )

        self.assertThat(raised.source_type, Equals("mercurial"))
        self.assertThat(raised.option, Equals("source-depth"))

    def test_source_checksum_raises_exception(self):
        raised = self.assertRaises(
            sources.errors.SnapcraftSourceInvalidOptionError,
            sources.Mercurial,
            "hg://mysource",
            "source_dir",
            source_checksum="md5/d9210476aac5f367b14e513bdefdee08",
        )

        self.assertThat(raised.source_type, Equals("mercurial"))
        self.assertThat(raised.option, Equals("source-checksum"))

    def test_has_source_handler_entry(self):
        self.assertTrue(sources._source_handler["mercurial"] is sources.Mercurial)

    def test_pull_failure(self):
        self.mock_run.side_effect = subprocess.CalledProcessError(1, [])

        hg = sources.Mercurial("hg://my-source", "source_dir")
        raised = self.assertRaises(sources.errors.SnapcraftPullError, hg.pull)
        self.assertThat(raised.command, Equals("hg clone hg://my-source source_dir"))
        self.assertThat(raised.exit_code, Equals(1))

def get_side_effect(original_call):
    def side_effect(cmd, *args, **kwargs):
        if len(cmd) > 1 and cmd[1] == "id":
            return "mock-commit".encode()
        elif cmd[0] == "hg":
            return
        return original_call(cmd, *args, **kwargs)

    return side_effect

class MercurialDetailsTestCase(unit.TestCase):
    def setUp(self):
        super().setUp()
        self.working_tree = "hg-test"
        self.source_dir = "hg-checkout"

        os.mkdir(self.source_dir)
        # Simulate that we have already cloned the code.
        os.mkdir(os.path.join(self.source_dir, ".hg"))

        self.fake_check_output = self.useFixture(
            fixtures.MockPatch(
                "subprocess.check_output",
                side_effect=get_side_effect(subprocess.check_output),
            )
        )
        self.fake_check_call = self.useFixture(
            fixtures.MockPatch(
                "subprocess.check_call",
                side_effect=get_side_effect(subprocess.check_call),
            )
        )

    def test_hg_details_commit(self):
        hg = sources.Mercurial(self.working_tree, self.source_dir, silent=True)
        hg.pull()

        source_details = hg._get_source_details()
        self.assertThat(source_details["source-commit"], Equals("mock-commit"))

        self.fake_check_output.mock.assert_has_calls(
            [
                mock.call(["hg", "id", self.source_dir]),
                mock.call(["hg", "id", self.source_dir]),
            ]
        )
        self.fake_check_call.mock.assert_called_once_with(
            ["hg", "pull", self.working_tree], stderr=-3, stdout=-3
        )

    def test_hg_details_branch(self):
        hg = sources.Mercurial(
            self.working_tree, self.source_dir, silent=True, source_branch="test-branch"
        )
        hg.pull()

        source_details = hg._get_source_details()
        self.assertThat(source_details["source-branch"], Equals("test-branch"))

        self.fake_check_output.mock.assert_not_called()
        self.fake_check_call.mock.assert_called_once_with(
            ["hg", "pull", "-b", "test-branch", self.working_tree], stderr=-3, stdout=-3
        )

    def test_hg_details_tag(self):
        hg = sources.Mercurial(
            self.working_tree, self.source_dir, silent=True, source_tag="test-tag"
        )
        hg.pull()

        source_details = hg._get_source_details()
        self.assertThat(source_details["source-tag"], Equals("test-tag"))

        self.fake_check_output.mock.assert_not_called()
        self.fake_check_call.mock.assert_called_once_with(
            ["hg", "pull", "-r", "test-tag", self.working_tree], stderr=-3, stdout=-3
        )


from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
import pandas as pd
import time
import json
from pandas.io.json import json_normalize
#We will have to use selenium

def fis():
	ids = []
	sex = []
	count = 0
	#start with the men
	startlist_list = ['https://www.biathlonworld.com/competitions/world-cup/events/bmw-ibu-world-cup-biathlon-oberhof-2021/bt2021swrlcp05/race/women-75km-sprint/bt2021swrlcp05swsp/',
'https://www.biathlonworld.com/competitions/world-cup/events/bmw-ibu-world-cup-biathlon-oberhof-2021/bt2021swrlcp05/race/men-10km-sprint/bt2021swrlcp05smsp/']
	for a in startlist_list:
		startlist = BeautifulSoup(urlopen(a), 'html.parser')
	#print(startlist)
		body = startlist.find_all('div', {'class':'pr-1 g-lg-2 g-md-2 g-sm-2 hidden-xs justify-right gray'})
		print(a)

		for b in range(len(body)):
			#print(body[a].text.strip())
			ids.append(int(body[b].text.strip()))
			#if(count==0):
			#	sex.append('M')
			#else:
			#	sex.append('L')
		count+=1

	#now for the ladies

	return ids
	#return {'id':ids, 'sex':sex}

def fantasy(startlist):
	name = []
	ski_id = []
	price =[]
	sex = []
	#sex = startlist['sex']
	#startlist = startlist['id']
	#print(sex)
	#print(startlist)
	fantasy = 'https://www.fantasyxc.se/api/athletes'
	#soup = BeautifulSoup(urlopen(fantasy), 'html5lib')
	#print(soup)
	with requests.Session() as s:
		r=s.get(fantasy)
		soup = BeautifulSoup(r.content, 'html5lib')
	API_json = json.loads(soup.get_text())
	API_df = pd.DataFrame.from_dict(pd.json_normalize(API_json), orient='columns')

	##Change to locate for increased speed
	for a in range(len(startlist)):
		athlete = API_df.loc[API_df['athlete_id']==startlist[a]]

		first_name = []
		last_name = []
		try:
			test_name = (athlete['name'].iloc[0])
		except:
			print(startlist[a])
			continue
		test_name = test_name.split(" ")
		for word in test_name:
			if word.isupper():
				last_name.append(word)
			else:
				first_name.append(word)
		first_name = ' '.join(first_name)
		last_name = ' '.join(last_name)
		test_name = first_name + " " + last_name

		name.append(test_name)
		try:
			ski_id.append(athlete['athlete_id'].iloc[0])
			price.append(athlete['price'].iloc[0])
			sex.append(athlete['gender'].iloc[0])
		except:
			print(test_name)

	d = {'name':name, 'id':ski_id, 'price':price, 'sex':sex}
	fantasy_df = pd.DataFrame(data=d)
	return fantasy_df

def pursuit(fantasydf):
	stage = [50, 46, 43, 40, 37, 34, 32, 30, 28, 26, 24, 22, 20, 18, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
	wc = [100, 80, 60, 50, 45, 40, 36, 32, 29, 26, 24, 2, 20, 18, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
	mendf = fantasydf.loc[fantasydf['sex']=='m']
	mendf = mendf.sort_values(by='elo', ascending=False)
	mendf['pursuit'] = np.arange(1, len(mendf['name'])+1, 1)
	mendf['pursuit'] = .3*mendf['pursuit'] + .7*mendf['place']
	mendf = mendf.sort_values(by='pursuit', ascending=True)
	mendf['pursuit'] = np.arange(1, len(mendf['name'])+1, 1)
	mendf = mendf[:30]
	mendf['points'] = stage

	ladiesdf = fantasydf.loc[fantasydf['sex']=='f']
	ladiesdf = ladiesdf.sort_values(by='elo', ascending=False)
	ladiesdf['pursuit'] = np.arange(1,len(ladiesdf['name'])+1,1)
	ladiesdf['pursuit'] = .3*ladiesdf['pursuit'] + .7*ladiesdf['place']
	ladiesdf = ladiesdf.sort_values(by='pursuit', ascending=True)
	ladiesdf['pursuit'] = np.arange(1,len(ladiesdf['name'])+1,1)
	ladiesdf = ladiesdf[:30]
	ladiesdf['points'] = stage

	fantasydf = mendf
	fantasydf = fantasydf.append(ladiesdf)
	return fantasydf

def elo(fantasydf):
	stage = [50, 46, 43, 40, 37, 34, 32, 30, 28, 26, 24, 22, 20, 18, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
	wc = [100, 80, 60, 50, 45, 40, 36, 32, 29, 26, 24, 2, 20, 18, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
	skier_elo = []
	df = pd.read_pickle("~/ski/elo/python/ski/men/varmen.pkl")
	ladiesdf = pd.read_pickle("~/ski/elo/python/ski/ladies/varladies.pkl")
	df = df.append(ladiesdf, ignore_index = True)
	df['name'] = df['name'].str.replace('ø', 'oe')

	df['name'] = df['name'].str.replace('ä', 'ae')
	df['name'] = df['name'].str.replace('æ', 'ae')
	df['name']= df['name'].str.replace('ö', 'oe')
	df['name']= df['name'].str.replace('ü', 'ue')
	df['name'] = df['name'].str.replace('Aleksandr Terentev', 'alexander terentev')
	df['name'] = df['name'].str.replace('Irineu Esteve Altimiras', 'ireneu esteve altimiras')
	df['name'] = df['name'].str.replace('Thomas Hjalmar Westgård', 'thomas maloney westgaard')
	df['name'] = df['name'].str.replace('Aleksandr Terentev', 'alexander terentev')
	df['name'] = df['name'].str.replace('Lauri Lepistoe', 'lauri lepisto')
	df['name'] = df['name'].str.replace('Philip Bellingham', 'phillip bellingham')
	df['name'] = df['name'].str.replace('Snorri Einarsson', 'snorri eythor einarsson')
	df['name'] = df['name'].str.replace('Krista Paermaekoski', 'krista parmakoski')
	df['name'] = df['name'].str.replace('Jessica Diggins', 'jessie diggins')
	df['name'] = df['name'].str.replace('Patricijia Eiduka', 'patricija eiduka')
	df['name'] = df['name'].str.replace('Katri Lylynperae', 'katri lylynpera')
	df['name'] = df['name'].str.replace('Julia Belger', 'julia preussger')

	fantasy_names = fantasydf['name']
	fantasy_names = fantasy_names.str.lower()
	fantasy_names  = fantasy_names.tolist()
	#print(fantasy_names)
	for a in range(len(fantasy_names)):
		skier = df.loc[df['name'].str.lower() == fantasy_names[a]]
		if(len(skier['name'])==0):
			print(fantasy_names[a])
		#print(skier)
		try:
			elo = skier['elo'].iloc[-1]
			skier_elo.append(elo)
		#elo = (skier.loc[skier['date']==20210500]['elo'])
		except:
			print(fantasy_names[a])
			skier_elo.append(1300)

	fantasydf['elo'] = skier_elo
	mendf = fantasydf.loc[fantasydf['sex']=='m']
	#Edit out these next three and the ladies three for pursuit.  One for actual

	mendf = mendf.sort_values(by='elo', ascending=False)
	mendf = mendf[:30]
	mendf['points'] = stage
	ladiesdf = fantasydf.loc[fantasydf['sex']=='f']
	ladiesdf = ladiesdf.sort_values(by='elo', ascending=False)
	ladiesdf = ladiesdf[:30]
	ladiesdf['points'] = stage
	mendf['place'] = np.arange(1, len(mendf['name'])+1, 1)
	ladiesdf['place'] = np.arange(1,len(ladiesdf['name'])+1,1)
	fantasydf = mendf
	fantasydf = fantasydf.append(ladiesdf)

	return fantasydf

	#WebDriverWait(driver, 30).until(EC.invisibility_of_element_located((By.XPATH,
	#	"//div[@class='js-off-canvas-overlay is-overlay-fixed']")))

startlist = fis()
#print(startlist)
#print(startlist)
fantasydf = (fantasy(startlist))
fantasydf = elo(fantasydf)
#fantasydf = pursuit(fantasydf)

fantasydf.to_pickle("~/ski/elo/knapsack/fantasydf.pkl")
fantasydf.to_excel("~/ski/elo/knapsack/fantasydf.xlsx")


#
# @lc app=leetcode id=403 lang=python3
#
# [403] Frog Jump
#

# @lc code=start
class Solution:
    def canCross(self, stones: List[int]) -> bool:
        # Solution 1: DP
        # steps = {stone: set() for stone in stones}
        # steps[stones[0]].add(1)
        # for stone in stones[:-1]:
        #     step = steps[stone]
        #     for k in step:
        #         if stone + k in steps:
        #             for n in [k - 1, k , k + 1]:
        #                 if n > 0 and n not in steps[stone + k]:
        #                     steps[stone + k].add(n)
        # return len(steps[stones[-1]]) > 0

        # Solution 2: DFS(TLE)
        # def dfs(stones, curStone, prev, target):
        #     if curStone == target:
        #         return True
        #     for k in [prev - 1, prev, prev + 1]:
        #         if k >= 1 and curStone + k in stones and dfs(stones, curStone + k, k, target):
        #             return True
        #     return False
        # return dfs(set(stones), stones[0], 0, stones[-1])

        # Solution 3: DFS with memorization
        global steps
        steps = {}
        steps[(stones[0], 0)] = True
        def dfs(stones, curStone, prev, target):
            if curStone == target:
                return True
            for k in [prev - 1, prev, prev + 1]:
                if k >= 1 and curStone + k in stones:
                    if (curStone + k, k) not in steps:
                        steps[(curStone + k, k)] = dfs(stones, curStone + k, k, target)
                    if steps[(curStone + k, k)]:
                        return True
            return False

        return dfs(set(stones), stones[0], 0, stones[-1])

# @lc code=end


def numbers_searching(*args):
    sequence = []
    duplicate = []
    missing = []
    for num in args:
        if num not in sequence:
            sequence.append(num)
        else:
            duplicate.append(num)
    min_num = min(sequence)
    max_num = max(sequence)
    for n in range(min_num, max_num):
        if n not in sequence:
            missing.append(n)
    result = sorted(missing)
    duplicate = list(set(duplicate))
    result.append(sorted([num for num in duplicate]))
    return result

print(numbers_searching(1, 2, 4, 2, 5, 4))
print(numbers_searching(5, 5, 9, 10, 7, 8, 7, 9))
print(numbers_searching(50, 50, 47, 47, 48, 45, 49, 44, 47, 45, 44, 44, 48, 44, 48))


'''
前几天看别人的面试题，看到好几次对一个特别大的文件进行处理 比如排序 还有一些别的操作
仔细思考了一下 思路就是 以下几个方面
1. 将一个大文件进行分割成为大小合适的子文本
2. 对每一个子文本进行排序操作
3. 使用归并排序对将子文件进行排序合并成为一个排序好的文件
如果想使用这个类需要重写 deal_input_line 和 deal_output_line 这两个方法以满足自己的需求
具体的使用例子看 同文件夹里面的test.py 这是一个简单的例子可以按照里面的进行写出符合自己需求的代码
'''

class big_file_sort:
    def __init__(self):
        # 分割的子文件的数量
        self._ch_file_cont = None
        # 输入文件的路径
        self.big_file_name = None
        # 最大的子类
        self.max_class = None
        # 每个文件最大的行数
        self.max_line_cont = None
        # 结果文件的文件名 默认为 result.txt
        self.result_file_name = 'result.txt'

    def split_file(self):
        with open(self.big_file_name, 'r') as file:
            cont = 0
            j = 0
            tmp_file = open(f"tmp_file_{cont}.txt", 'w')
            for line in file:
                if j == self.max_line_cont:
                    cont += 1
                    j = 0
                    tmp_file.close()
                    tmp_file = open(f"tmp_file_{cont}.txt", 'w')
                tmp_file.write(line)
                j += 1
            self._ch_file_cont = cont

    def one_file_sort(self):
        for i in range(self._ch_file_cont + 1):
            print(f"正在处理第{i}个文件")
            with open(f"tmp_file_{i}.txt", 'r') as tmp_file:
                t = [self.deal_input_line(line) for line in tmp_file]
                t.sort()
            with open(f"sort_{i}.txt", 'w') as tmp_file:
                x = (self.deal_output_line(one_line)
                     for one_line in t)
                tmp_file.writelines(x)

    def sort(self):
        result = open('result.txt', 'w')
        sort_files = [open(f'sort_{i}.txt', 'r')
                      for i in range(self._ch_file_cont + 1)]
        tmpl = list(map(next, sort_files))
        i = 0
        while True:
            if i == self._ch_file_cont + 1:
                print("结束了")
                for tmp in tmpl:
                    if tmp != self.deal_output_line(self.max_class):
                        result.write(tmp)
                break
            min_num = self.max_class
            min_index = -1
            for index, ip in enumerate(tmpl):
                tmp = self.deal_input_line(ip)
                if tmp < min_num:
                    min_num = tmp
                    min_index = index
            try:
                result.write(tmpl[min_index])
                tmpl[min_index] = next(sort_files[min_index])
            except StopIteration:
                # 到达了一个文件的结尾
                i += 1
                # 记录结束的文件数 加一
                tmpl[min_index] = self.deal_output_line(self.max_class)

    def deal_input_line(self, line):
        return line

    def deal_output_line(self, line):
        return line


from linear_prediction import LP
import numpy as np
from matplotlib import pyplot as plt
import pdb

K = np.linspace(1, 29, 29, dtype=int)
alp = np.linspace(2, 6, 5, dtype = int)
p = np.zeros((5, 29))

for i in range(len(alp)):
    for j in range(len(K)):
        p[i,j] = LP(K[j], alp[i])

# Graphs

fig, ax = plt.subplots()
ax.set_title("Percentage of Blob Positions Correctly Predicted")
ax.set_xlabel("Number of Previous Frames Taken into Account")
ax.set_ylabel("Percent Correctly Predicted")

a = np.linspace(1, 29, 29)
for i in range(len(alp)):
    ax.plot(a, p[i,:], label="Predicted " +str(i+1) + " Frames into the Future")
plt.legend()

plt.show()


class Solution:
    def splitArray(self, nums: List[int], m: int) -> int:
        # Top down DP + Prefix Sum, Time O(mn^2), Space O(n)
        n = len(nums)
        prefix = [0] * (n + 1)
        for i in range(n):
            prefix[i + 1] = prefix[i] + nums[i]

        @lru_cache(None)
        def dfs(i, m):
            if i == n:
                return 0
            if m == 1:
                return prefix[-1] - prefix[i]
            res = float('inf') #if not enough elements for m subarrays, inf is returned
            for j in range(i + 1, len(nums)):
                left = prefix[j] - prefix[i]
                right = dfs(j, m - 1)
                res = min(res, max(left, right))
                if left > right: # this judgement speed it up !!! without it TLE
                    break
            return res

        return dfs(0, m)


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 17:36:51 2016

Draw integrated energy plot

@author: bottero
"""
from __future__ import (absolute_import, division, print_function)
import numpy as np # NumPy (multidimensional arrays, linear algebra, ...)
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import os,sys,glob,shutil
import argparse # To deal with arguments :
# https://docs.python.org/2/library/argparse.html
import scipy.ndimage

def representsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False
def representsFloat(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

class ParFile:
    """ This class is used to store the data contained on a specfem2d
    par_file"""

    def __init__(self,pathToParFile):
        """ Constructor (what happen when we do aParFile=ParFile(path)) """
        self.path=pathToParFile
        self.nt=''
        self.dt=''
        if os.path.exists(self.path):
            self.readParFile()
        else:
            raise IOError('Impossible to read '+pathToParFile)

    def readParFile(self):
        """ Open a the par_file and read some values """
        with open(self.path) as parFile:
            for line in parFile:
                if 'NSTEP=' in line.replace(" ", ""):
                    self.nt=line.split(" = ")[1].split("#")[0].strip()
                    if representsInt(self.nt): # Verify that the string extracted is a int
                        self.nt = int(self.nt)
                    else:
                        raise ValueError('Incorrect value of NSTEP read')
                if 'DT=' in line.replace(" ", ""):
                    self.dt=line.split(" = ")[1].split("#")[0].strip()
                    self.dt=self.dt.replace("d","e").replace("D","E") # Convert to real scientific fomat
                    if representsFloat(self.dt): # Verify that the string extracted is a int
                        self.dt = float(self.dt)
                    else:
                        raise ValueError('Incorrect value of DT read')

def find_index(x,z,xil,zil):
    """Return the indices of the closest point in 2D array"""
    idxX=np.searchsorted(xil,x)
    idxZ=np.searchsorted(zil,z)
    return idxX,idxZ

def interpolateValue(array,xil,zil,x,z):
    """Return the value of the 2D field described by array,xil and zil at (x,z)"""
    idxX,idxZ = find_index(x,z,xil,zil)
    xLine, zLine = np.array([idxX]), np.array([idxZ])
    # Extract the values along the line, using cubic interpolation
    if type(intEnergyi) == np.ndarray:
        zi = scipy.ndimage.map_coordinates(array, np.vstack((zLine,xLine)),order=1)
    else:
        zi = scipy.ndimage.map_coordinates(array.filled(), np.vstack((zLine,xLine)),order=1)

    return zi[0]

####################### PARSE ARGUMENTS #######################
# Here we read the argument given and we check them

parser = argparse.ArgumentParser(
    description="This script plot the files total_integrated_energy_fieldXXXXX representing the energy that have crossed each point")
parser.add_argument("--input_directory","-d",type=str,default="./",
    help="input_directory: directory where we can find the files total_integrated_energy_fieldXXXXX")
parser.add_argument("--par_file_directory",type=str,default="../../",
    help="par_file_directory: directory where we can find the Par_file of the run. Default: input_directory/../../")
parser.add_argument("--name_of_files","-n",type=str,default="total_integrated_energy_field",
    help="name_of_files: to plot something different than total_integrated_energy_fieldXXXXX")
parser.add_argument('-p','--profiles', action='store_true',
    help='profiles: calculate energy profiles')
parser.add_argument('-nc','--no_concatenate_files', action='store_true',
    help='no_concatenate_files: don t concatenate files at the beginning of the script')
parser.add_argument('-nl','--nolog', action='store_true',
    help='nolog: no apply log at the beginning of the script')
parser.add_argument("--title","-t",type=str,default="",
    help="title : title of the figures")
parser.add_argument("-nx",type=int,default=100,
    help="nx: number of x points for interpolated field")
parser.add_argument("-nz",type=int,default=100,
    help="nz: number of z points for interpolated field")
parser.add_argument('-w','--writeInterpolatedField', action='store_true',
    help='writeInterpolatedField: write Interpolated field on file')
parser.add_argument('-sp','--saveOneProfile', action='store_true',
    help='saveOneProfile: Save one profile to file (set it in source code)')
parser.add_argument('-q','--quickDisplay', action='store_true',
    help='quickDisplay: display after a simple linear interpolation')
parser.add_argument('--displayPoints', action='store_true',
    help='displayPoints: plot the data points')
parser.add_argument('--clim',nargs=2,default=[],
    help='clim: set limits of the color bar')
parser.add_argument('--ref',nargs=2,default=[300,-2500],
    help='ref: Point that we set to 1')
parser.add_argument('--nxnzProfiles',nargs=2,default=[10,10],
    help='nxnz: set the number of x and z profiles to plot')
parser.add_argument('--noplot', action='store_true',
    help='noplot: do not plot anything')
parser.add_argument('-v','--verbose', action='store_true',
    help='verbose: display more information')

args = parser.parse_args()
directory=args.input_directory

fontsize = 14
zminProfiles = -5000
zmaxProfiles = -200 # TODO (-650m for 0.5Hz, -300m for 2Hz...)
xsp = 50000

# Check
if not os.path.isdir(directory):
    print("Wrong directory! "+directory)
    sys.exit(0)

if directory[-1] != '/': #If the path given don't finish by slash...
    directory=directory+'/' #... we add one

if args.par_file_directory:
    if args.par_file_directory[-1] != '/': #If the path given don't finish by slash...
        par_file_directory=args.par_file_directory+'/' #... we add one
    else:
        par_file_directory = args.par_file_directory
else:
    par_file_directory = directory+"../../"

if not glob.glob(directory+args.name_of_files+"*"): # If we don't find any matching energy file...
    print("No files "+directory+args.name_of_files+"* were found!")
    sys.exit(0)

# Concatenate all the files (if specfem has been run on parallel each proc has created its own files)

if not os.path.isfile(directory+args.name_of_files+"All"): # If the concatenation has not already been done
    if args.verbose:
        print("Concatenate files...")
    if not args.no_concatenate_files:
        with open(directory+args.name_of_files+"All", 'w') as outfile:
            for infile in glob.glob(directory+args.name_of_files+"0*"):
                shutil.copyfileobj(open(infile), outfile)
else:
    print(directory+args.name_of_files+"All has been found!")

if args.verbose:
    print("Done")
plt.close('all')

# Load data
if args.verbose:
    print("Load data in "+directory+args.name_of_files+"All")
x,z,intEnergy=np.loadtxt(directory+args.name_of_files+"All").T

#if args.verbose:
#    print("Load seismograms "+directory+"AA.S0001.BXX.semv AA.S0001.BXZ.semv at 300m from the source")
#t,vx0=np.loadtxt(directory+"AA.S0001.BXX.semv").T
#t,vz0=np.loadtxt(directory+"AA.S0001.BXZ.semv").T
if args.verbose:
    print("Done")

if "integrated" in args.name_of_files: # We have to multiply by dt
    #scalingFactor = (vx0**2+vz0**2).sum()
    if args.verbose:
        print("Opening Par_file in ",par_file_directory,"...")
    par_file=ParFile(par_file_directory+'Par_file') # Open and read the Par_file
    intEnergy = intEnergy * par_file.dt * x
    #intEnergy = intEnergy/scalingFactor

if "max" in args.name_of_files:
    #scalingFactor = (vx0**2+vz0**2).max()
    intEnergy = intEnergy * x
    #intEnergy = intEnergy/scalingFactor

if not args.nolog:
    intEnergy=10*np.log10(intEnergy)

mask0=~np.isinf(intEnergy)
intEnergy[~mask0]=min(intEnergy[mask0])

nxProfiles = float(args.nxnzProfiles[0])
nzProfiles = float(args.nxnzProfiles[1])

# Color map to use:
cmap = cm.BuPu #cm.Greys #cm.BuPu

if args.clim:
    climMin = float(args.clim[0])
    climMax = float(args.clim[1])

# Display limits:
xmin=x.min()
xmax=0.95*x.max()
zmin=0.95*z.min()
zmax=z.max()

if args.displayPoints:
    if not args.noplot:
        plt.plot(x,z,'o')
        plt.show()

if args.quickDisplay: # Quick ways to plot the energy using the non homogeneous grid:
    if not args.noplot:
        #plt.tricontourf(x,z,intEnergy,20,shading='gouraud',extend="both",cmap=cmap)
        plt.figure(figsize=(8,6))
        plt.tripcolor(x,z,intEnergy,shading='gouraud',cmap=cmap)
        plt.axis([xmin, xmax, zmin, zmax])
        plt.colorbar()
        if args.clim:
            plt.clim(climMin,climMax)
        plt.show()
    sys.exit()
    #cmap.set_bad('w',1.)

#%%
# Interpolation on a regular grid

# Size of regular grid
nx, nz = args.nx,args.nz

# Generate a regular grid to interpolate the data.
xil = np.linspace(xmin-1000, xmax+1000, nx)
zil = np.linspace(zmin-1000, zmax+1000, nz)
xi, zi = np.meshgrid(xil, zil)

if os.path.isfile(args.input_directory+args.name_of_files+"AllInterpolatedx"+str(nx)+"z"+str(nz)): # If the interpolation has already been done and written
    if args.verbose:
        print("Interpolated field file has been found. Loading...")
    intEnergyi = np.load(args.input_directory+args.name_of_files+"AllInterpolatedx"+str(nx)+"z"+str(nz))
    if args.verbose:
        print("Done")
else:
    # Interpolate using delaunay triangularization:
    if args.verbose:
        print("Interpolation...")
    intEnergyi = mlab.griddata(x,z,intEnergy,xi,zi,interp="linear")
    if args.verbose:
        print("Done")
    if args.writeInterpolatedField:
        if args.verbose:
            print("Writing the interpolated field to file..."+args.input_directory+args.name_of_files+"AllInterpolatedx"+str(nx)+"z"+str(nz))
        intEnergyi.dump(args.input_directory+args.name_of_files+"AllInterpolatedx"+str(nx)+"z"+str(nz))
        if args.verbose:
            print("Done")

# Normalize
if "max" in args.name_of_files or "integrated" in args.name_of_files:
    if args.verbose:
        print("Normalizing...")
    valueAtRef = interpolateValue(intEnergyi,xil,zil,float(args.ref[0]),float(args.ref[1]))
    if args.verbose:
        print("Value at reference point (",args.ref[0],",",args.ref[1],") is ",valueAtRef)
    intEnergyi = intEnergyi - valueAtRef
    valueAtRef = interpolateValue(intEnergyi,xil,zil,float(args.ref[0]),float(args.ref[1]))
    if args.verbose:
        print("Value at reference point (",args.ref[0],",",args.ref[1],") is ",valueAtRef)
    if args.verbose:
        print("Done")

#Plot:
if not args.noplot:
    if args.verbose:
        print("Plots...")
    plt.figure(1,figsize=(10,4))
    plt.pcolormesh(xi,zi,intEnergyi,shading='gouraud',cmap=cmap)
    plt.colorbar()
    plt.axis([xmin, xmax, zmin, zmax])
    if args.clim:
        plt.clim(climMin,climMax)
    plt.title(args.title)
    font = {'family' : 'serif','size':fontsize}
    plt.rc('font', **font)
    plt.xlabel("Range (m)",fontsize=fontsize+3)
    plt.ylabel("Depth (m)",fontsize=fontsize+3)
    #plt.rc('text', usetex=True)
    if args.verbose:
        print("Done")

if args.profiles:
    # Plot energy profiles:
    if args.verbose:
        print("Print profiles...")

    num=500
    cmap2 = plt.get_cmap('prism')
    if not args.noplot:
        plt.figure(2)
    zVector=np.arange(zmin/(nzProfiles + 1),zmin,zmin/(nzProfiles + 1))
    colors = [cmap2(i) for i in np.linspace(0, 1, len(zVector))]
    xvect=np.linspace(xmin,xmax,num)

    for i,zz in enumerate(zVector):
        x0,z0=xmin,zz
        x1,z1=xmax,zz

        idxX0,idxZ0 = find_index(x0,z0,xil,zil)
        idxX1,idxZ1 = find_index(x1,z1,xil,zil)
        if not args.noplot:
            plt.figure(1)
            plt.hold(True)
        xLine, zLine = np.linspace(idxX0,idxX1, num), np.linspace(idxZ0, idxZ1, num)

        zi = intEnergyi[zLine.astype(np.int),xLine.astype(np.int)] # If you have got an error here try to choose a lower z1 or a bigger z0!

        # Extract the values along the line, using cubic interpolation
        if type(intEnergyi) == np.ndarray:
            zi = scipy.ndimage.map_coordinates(intEnergyi, np.vstack((zLine,xLine)),order=1)
        else:
            zi = scipy.ndimage.map_coordinates(intEnergyi.filled(), np.vstack((zLine,xLine)),order=1)
        if not args.noplot:
            plt.plot([x0, x1], [z0, z1], 'o-',color=colors[i])
            plt.figure(2)
            plt.plot(xvect,zi,color=colors[i])
            plt.xlabel("Range (m)",fontsize=fontsize+3)
            if not args.nolog:
                plt.ylabel("Log of integrated energy",fontsize=fontsize+3)
            else:
                plt.ylabel("Integrated energy",fontsize=fontsize+3)
            plt.title(args.title)
    if not args.noplot:
        plt.xlim([xmin,xmax])
        plt.figure(3)

    xVector=np.arange(xmax/(nxProfiles + 1),xmax,xmax/(nxProfiles + 1))
    colors = [cmap2(i) for i in np.linspace(0, 1, len(xVector))]
    z0=zminProfiles
    z1=zmaxProfiles # Be careful! This point can't be too close to zmax!
    zvect=np.linspace(z0,z1,num)
    depthIntegratedEnergy=np.zeros(len(xVector))
    #depthIntegratedEnergy2=np.zeros(len(xVector))

    for i,xx in enumerate(xVector):
        x0=xx
        x1=xx

        idxX0,idxZ0 = find_index(x0,z0,xil,zil)
        idxX1,idxZ1 = find_index(x1,z1,xil,zil)
        if not args.noplot:
            plt.figure(1)
            plt.hold(True)
        #if args.verbose:
        #    print("Profile to be saved: (x0,z0) = (",x0,",",z0,")   (x1,z1) = (",x1,",",z1,")")
        xLine, zLine = np.linspace(idxX0,idxX1, num), np.linspace(idxZ0, idxZ1, num)

        zi = intEnergyi[zLine.astype(np.int),xLine.astype(np.int)] # If you have got an error here try to choose a lower z1 or a bigger z0!

        # Extract the values along the line, using cubic interpolation
        if type(intEnergyi) == np.ndarray:
            zi = scipy.ndimage.interpolation.map_coordinates(intEnergyi, np.vstack((zLine,xLine)),order=1)
        else:
             zi = scipy.ndimage.interpolation.map_coordinates(intEnergyi.filled(), np.vstack((zLine,xLine)),order=1)
        #depthIntegratedEnergy[i]=zi2.sum()

        #depthIntegratedEnergy2[i]=zi.sum()
        if not args.nolog:
            depthIntegratedEnergy[i]=10*np.log10(np.power(10,zi/10.0).sum())
        else:
            depthIntegratedEnergy[i]=np.power(10,zi/10.0).sum()
        if not args.noplot:
            plt.plot([x0, x1], [z0, z1], 'o-',color=colors[i])

            plt.figure(3)
            plt.plot(zi,zvect,color=colors[i]) # Without filtering
            plt.xlabel("Depth (m)",fontsize=fontsize+3)
            if not args.nolog:
                plt.ylabel("Log of integrated energy",fontsize=fontsize+3)
            else:
                plt.ylabel("Integrated energy",fontsize=fontsize+3)
            #plt.plot(zi2,zvect,color=colors[i])
            plt.ylim([z0,z1])
            plt.title(args.title)
    if not args.noplot:
        plt.figure(4)
        plt.plot(xVector,depthIntegratedEnergy,'o-')
        #plt.plot(xVector,depthIntegratedEnergy2,'o-')
        plt.xlabel("Range (m)",fontsize=fontsize+3)
        if not args.nolog:
            plt.ylabel("10 Log of total energy in water",fontsize=fontsize+3)
        else:
            plt.ylabel("Total energy in water",fontsize=fontsize+3)

        plt.title(args.title)
        if args.verbose:
            print("Done")

    ### SAVE ONE PROFILE ###
    if args.saveOneProfile:
        if args.verbose:
            print("Saving one profile...")

        np.savetxt(args.input_directory+args.name_of_files+"_energy_vs_range",np.dstack((xVector,depthIntegratedEnergy))[0])
        print("File ",args.input_directory+args.name_of_files+"_energy_vs_range has been written")

        x0,z0=xsp,zminProfiles
        x1,z1=xsp,zmaxProfiles
        zvect2=np.linspace(z0,z1,num)
        if args.verbose:
            print("Profile to be saved: (x0,z0) = (",x0,",",z0,")   (x1,z1) = (",x1,",",z1,")")
        idxX0,idxZ0 = find_index(x0,z0,xil,zil)
        idxX1,idxZ1 = find_index(x1,z1,xil,zil)
        if not args.noplot:
            plt.figure(1)
            plt.hold(True)
        xLine, zLine = np.linspace(idxX0,idxX1, num), np.linspace(idxZ0, idxZ1, num)
        # Extract the values along the line, using cubic interpolation

        zi = intEnergyi[zLine.astype(np.int),xLine.astype(np.int)] # If you have got an error here try to choose a lower z1 or a bigger z0!

        if type(intEnergyi) == np.ndarray:
            zi = scipy.ndimage.map_coordinates(intEnergyi, np.vstack((zLine,xLine)),order=1)
        else:
            zi = scipy.ndimage.map_coordinates(intEnergyi.filled(), np.vstack((zLine,xLine)),order=1)

        #depthIntegratedEnergy2[i]=zi.sum()
        if not args.nolog:
            depthIntegratedEnergy[i]=np.power(10,zi/10.0).sum()
        else:
            depthIntegratedEnergy[i]=zi.sum()
        if not args.noplot:
            plt.plot([x0, x1], [z0, z1], 'o-',color="black",linewidth=3)

            plt.figure(3)
            plt.plot(zi,zvect2,color="black",linewidth=3)
            plt.xlabel("Depth (m)",fontsize=fontsize+3)
            if not args.nolog:
                plt.ylabel("Log of integrated energy",fontsize=fontsize+3)
            else:
                plt.ylabel("Integrated energy",fontsize=fontsize+3)
            plt.title(args.title)
        i=0
        #while os.path.isfile(args.input_directory+args.name_of_files+"_profile_"+str(i)): # If the a profile of this name has already been written
        #    i = i+1
        np.savetxt(args.input_directory+args.name_of_files+"_profile_"+str(i),np.dstack((zvect2,zi))[0])
        print("File ",args.input_directory+args.name_of_files+"_profile_"+str(i)," has been written")
        if args.verbose:
            print("Done")
if not args.noplot:
    plt.show()