from flask import render_template,request,url_for,jsonify,redirect,flash
from bikestore import  app,db,bcrypt
from bikestore.models import Bike_order,Bike_inventory
# dictionary defined globally

@app.route("/")
def home():
    return render_template("home.html")

# 1 . add bikes
@app.route("/details/add",methods=['GET','POST'])
def bike_details_add():
    if request.method == 'POST':
        bike_name = request.form['bike_name']
        bike_model = request.form['bike_model']
        bike_chassis_number = request.form['bike_chassis_no']
        bike_price = request.form['bike_price']
        bike_count = request.form['bike_count']

        bike = Bike_inventory(bike_name=bike_name,bike_model=bike_model,bike_chassis_number=bike_chassis_number, \
                          base_price=bike_price,bike_count=bike_count)

        db.session.add(bike)
        db.session.commit()

        return redirect(url_for('bike_details_display'))
    return render_template("bike_details_add.html")

# 2 . Display all bike details
@app.route("/details/display", methods=['GET','POST'])
def bike_details_display():
    bike = Bike_inventory.query.all()

    return render_template('bike_details_display.html', bikedata=bike)

# 3. select bike details to update
@app.route("/details/update/<bikeid>", methods=['PUT', 'GET','POST'])
def bike_details_update(bikeid):
    bike = Bike_inventory.query.filter_by(id=bikeid).first()
    if request.method == 'POST':
        bike.bike_name = request.form['bikename']
        bike.bike_model = request.form['bikemodel']
        bike.bike_chassis_number = request.form['bikechassisno']
        bike.bike_price = request.form['baseprice']
        bike.bike_count = request.form['bikecount']

        db.session.commit()

        return redirect(url_for('bike_details_display'))

    return render_template('bike_details_update.html',bike=bike)

# 4. Delete bike details
@app.route("/details/delete/<bikeid>", methods=['POST'])
def bike_details_delete(bikeid):
    bike = Bike_inventory.query.filter_by(id=bikeid).first()
    db.session.delete(bike)
    db.session.commit()

    return redirect(url_for('bike_details_display'))

# 1. Create order with customer name and phone number
@app.route("/order/create", methods=['GET','POST'])
def order_create():
    if request.method == 'POST':
        order_bike_name = request.form['bikename']
        order_downpayment = request.form['downpayment']
        order_count = request.form['ordercount']

        order = Bike_order(order_bike_name=order_bike_name,order_downpayment=order_downpayment,order_count=order_count)

        db.session.add(order)
        db.session.commit()
        flash('order created successfully')
        return redirect(url_for('order_display'))

    return render_template('order_create.html')

# 2. Display order details
@app.route("/order/display", methods=['GET','POST'])
def order_display():
    order = Bike_order.query.all()

    return render_template('order_display.html', orders=order)

# 3. Update order , cancel, return
@app.route("/order/delete/<id>", methods=['GET','POST'])
def order_delete(id):
    order = Bike_order.query.filter_by(id=id).first()
    db.session.delete(order)
    db.session.commit()

    return redirect(url_for('order_display'))

'''
add home route link in all apps

'''

'''

bike.base_price = 33000
    db.session.commit()

'''

'''
Bike store

Bike inventory
    add bikes
    update bike details
    delete bikes
    fetch all bike details
    fetch a single bike details

Bike order
    create order for customer
    update the status of the order
        based on inventory availability
        order bike to factory
    cancel the order
    return order
    create order with customer name , number.

customer login
    username, password, mobile number

admin login
    username , password

'''


# 547. Friend Circles

# There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature.
# For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C.
# And we defined a friend circle is a group of students who are direct or indirect friends.

# Given a N*N matrix M representing the friend relationship between students in the class.
# If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not.
# And you have to output the total number of friend circles among all the students.

# Example 1:

# Input:
# [[1,1,0],
#  [1,1,0],
#  [0,0,1]]
# Output: 2
# Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
# The 2nd student himself is in a friend circle. So return 2.

# Example 2:
# Input:
# [[1,1,0],
#  [1,1,1],
#  [0,1,1]]
# Output: 1
# Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
# so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
# Note:
# N is in range [1,200].
# M[i][i] = 1 for all students.
# If M[i][j] = 1, then M[j][i] = 1.

class FriendCircles:

    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        def find(node):
            if circles[node] == node:
                return node

            root = find(circles[node])
            circles[node] = root
            return root

        n = len(M)
        circles = {x:x for x in range(n)}
        for i in range(n):
            for j in range(i, n):
                if i != j and M[i][j] == 1 and find(i) != find(j):
                    circles[find(i)] = find(j)

        return sum([1 for k, v in circles.items() if k == v])

    def doit(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        def parent(i):
            if circle[i] != i:
                circle[i] = parent(circle[i])
            return circle[i]

        circle = [x for x in range(len(M))]

        for i in range(len(M)):

            for j in range(i+1, len(M)):

                if M[i][j] == 1 and parent(i) != parent(j):
                    circle[parent(j)] = parent(i)

        return sum(1 for i in range(len(circle)) if i == circle[i])

    def doit1(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        def dfs(i, visited):
            visited.add(i)
            for j in range(len(M)):
                if M[i][j] == 1 and j not in visited:
                    dfs(j, visited)

        count, visited = 0, set()
        for i in range(len(M)):
            if i not in visited:
                dfs(i, visited)
                count += 1

        return count

class UnionFind(object):
    def __init__(self, grid):
        self.n = len(grid)
        self.parent = [-1] * self.n
        for idx in xrange(self.n):
            self.parent[idx] = idx

    def find(self, i):
        if self.parent[i] != i:
            self.parent[i] = self.find(self.parent[i])
        return self.parent[i]

    def union(self, x, y):
        rootx = self.find(x)
        rooty = self.find(y)
        if rootx != rooty:
            self.parent[rooty] = rootx

    def diff_groups(self):
        diff_groups = set()
        for i in xrange(self.n):
            diff_groups.add(self.find(i))
        return len(diff_groups)

class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        n = len(M)
        uf = UnionFind(M)

        for i in xrange(n):
            for j in xrange(n):
                if M[i][j] == 1:
                    uf.union(i, j)

        return uf.diff_groups()

if __name__ == "__main__":

    res = FriendCircles().doit([[1, 1, 0],
                                [1, 1, 0],
                                [0, 0, 1]])

    res = FriendCircles().doit([[1, 1, 0],
                                [1, 1, 1],
                                [0, 1, 1]])

    res = FriendCircles().doit([[1, 0, 0, 1],
                                [0, 1, 1, 0],
                                [0, 1, 1, 1],
                                [1, 0, 1, 1]])

    res = FriendCircles().findCircleNum([[1, 0, 0, 1],
                                         [0, 1, 1, 0],
                                         [0, 1, 1, 1],
                                         [1, 0, 1, 1]])

    pass


inp = input("Please enter a string")
result = ""
orig = ""
s = 4
x = 8
pos = len(inp) - 1
for i in range(len(inp)):
    char = inp[pos]  #starting at end to reverse input
    result += chr((ord(char) + s-97) % 26 + 97) #Shifting the (backwords)og value
    result += chr((ord(char) + x - 97) % 26 + 97) #first salt
    result += chr((ord(char) + 1 - 97) % 26 + 97)   #second salt
    pos -= 1
print(result)

for i in range(0, len(result), 3):
    char = result[i]
    orig += chr((ord(char) - s-97) % 26 + 97)
    i += 1
    i += 1

orig = orig[::-1]
print(orig)


# coding:iso-8859-9 Türkçe

kelime = input ("k basamaklı şifreleme için dizge girin: ")
k = int (eval (input ("Kaçarlı şifreleme oluşturacaksın: ")))
if k > len (kelime)//2: k = len(kelime)//2
elif k < 2: k = 2
şifreli=deşifreli=''
for i in range (k-1, len(kelime), k):
    for j in range (i, i-k, -1): şifreli += kelime[j]
for i in range (len(kelime)%k): şifreli += kelime[-i-1]
print ("\n", k, "'li genel şifreleme: ", şifreli, sep="")

for i in range (k-1, len(şifreli), k):
    for j in range (i, i-k, -1): deşifreli += şifreli[j]
for i in range (len(şifreli)%k): deşifreli += şifreli[-i-1]
print ("\n", k, "'li genel deşifreleme: ", deşifreli, sep="")

Brian Heinold (243) ile Python/p10611f_sınav.py


# File Types in Python
# 1. Text file
# 2. Binary file
# 3. Raw Binary file (typically not used)

# modes:
# r (default): open for reading
# r+: open for reading and writing
# w: open for writing, creates file if not there, if there truncates it
# w+: open for reading and writing, creates file if not there, if there truncates it
# a: open for writing, creates file if not there, if there places the pointer at the end of the file
# a+: open for reading and writing, creates file if not there,
# if there place the pointer at the end of the file

# filetypes: binary: b, text: t (default)

filein = open('test1.txt', mode='a+')
# print(type(filein.read()))
# print(type(filein.readline()))
# print(filein.readlines())
filein.seek(0)
for line in filein:
    print(line)
    print(type(line))
    print(list(line))

text = "Add this text to the file.\n"
filein.write(text)

filein.close()

# Tips
# NEW LINE
# WINDOWS: Carriage Return (CR or \r) and the Line Feed (LF or \n) characters (CR+LF or \r\n)
# LINUX and MAC: Line Feed (LF or \n)
# Character Encodings
# ASCII: 128 characters
# Unicode: 1,114,112 characters


import fitz
import os
from pdf2image import convert_from_path
# PDF转JPG封装

def pdf2jpg(pdfPath, imagePath):
    pdfDoc = fitz.open(pdfPath)
    for pg in range(pdfDoc.pageCount):
        page = pdfDoc[pg]
        rotate = int(0)
        # 每个尺寸的缩放系数为1.3，这将为我们生成分辨率提高2.6的图像。
        # 此处若是不做设置，默认图片大小为：792X612, dpi=96
        zoom_x = 4  # (1.33333333-->1056x816)   (2-->1584x1224)
        zoom_y = 4
        mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
        pix = page.getPixmap(matrix=mat, alpha=False)

        if not os.path.exists(imagePath):  # 判断存放图片的文件夹是否存在
            os.makedirs(imagePath)  # 若图片文件夹不存在就创建

        pix.writePNG(imagePath+'/'+'%s.jpg' % pg)  # 将图片写入指定的文件夹内


import config as cfg
import os
import logging
import config as cfg
from datetime import datetime
from database import db_connect, Logger

logger_name = 'main'
logger = logging.getLogger(logger_name)

class LogDBHandler(logging.Handler):
    def __init__(self):
        logging.Handler.__init__(self)

    def emit(self, record):
        db = db_connect()

        try:
            data = Logger(
                name=record.name,
                level=record.levelname,
                path='%s:%s' % (record.filename, record.lineno),
                content=record.msg,
                createAt=datetime.fromtimestamp(record.created),
            )
            db.add(data)
            db.commit()
            db.close()
        except Exception as e:
            db.rollback()
            db.close()
            raise e

def logger_create(name):
    logger = logging.getLogger(name)

    if cfg.DEV:
        fmt = '-' * 70 + '\n%(asctime)s %(levelname)s %(filename)s:%(lineno)d/%(funcName)s > %(message)s'
        datefmt = '%H:%M:%S'
        formatter = logging.Formatter(fmt, datefmt)

        logger.setLevel(logging.DEBUG)

        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(formatter)
        logger.addHandler(console)

    else:
        fmt = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d/%(funcName)s > %(message)s'
        datefmt = '%m-%d %H:%M:%S'
        formatter = logging.Formatter(fmt, datefmt)

        logger.setLevel(logging.INFO)

        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(formatter)
        logger.addHandler(console)

        log_db = LogDBHandler()
        log_db.setLevel(logging.INFO)
        logger.addHandler(log_db)

        log_info = logging.FileHandler(cfg.LOGGER_INFO_PATH)
        log_info.setLevel(logging.INFO)
        log_info.setFormatter(formatter)
        logger.addHandler(log_info)

        log_error = logging.FileHandler(cfg.LOGGER_ERROR_PATH)
        log_error.setLevel(logging.WARN)
        log_error.setFormatter(formatter)
        logger.addHandler(log_error)

    return logger

logger = logger_create('main')
#logger.debug('debug')
#logger.info('info')
#logger.warning('warning')
#logger.error('error')
#logger.critical('critical')
#logger.exception('exception')


import unittest

def longest_chain(library):
    """you are given a library with n words.
    You choose a word from it, and in each step,
    remove one letter from this word only if doing so yields another word in the library.
    What is the longest possible chain of these removal steps?"""
    library.sort(key=len)

    # lc[word] is the length of the longest chain that ends at this word
    lc = {}

    # for each new word in the library
    #   either it extends a previous chain (of word length-1)
    #   or it creates a new chain of length 1

    for word in library:
        if word not in lc:
            lc[word] = 1
        for oll in one_letter_less(word):
            if oll in lc:
                lc[word] = max(lc[word], lc[oll]+1)

    return max(lc.values())

def one_letter_less(word):
    bag = []
    for i in range(len(word)):
        bag.append(word[:i] + word[i+1:])
    return bag

class TestLongestChain(unittest.TestCase):
    """Boilerplate docs"""
    def testLongestChain(self):
        lib = ['a', 'b', 'ba', 'bca', 'bda', 'bdca']
        self.assertEqual(4, longest_chain(lib))

if __name__ == '__main__':
    unittest.main()


def reverse(root):
	if not root.left and not root.right:
		return root
	nodeLeft = root.left
	nodeRight = root.right
	root.left = None
	root.right = None
	return helper(nodeLeft, root, nodeRight)

def help(node, top, right):
	nodeLeft = node.left
	nodeRight = node.right
	node.right = top
	node.left = right
	if nodeLeft == None:
		return node
	return help(nodeLeft, node, nodeRight)


from turtle import Turtle
FONT = ("Courier", 24, "normal")

class Scoreboard(Turtle):
    def __init__(self):
        super().__init__()
        self.level = 1
        self.penup()
        self.hideturtle()
        self.color("black")
        self.goto(-200,260)
        self.write(f"LEVEL : {self.level}", align= "center", font= FONT)

    def updation(self):
        self.level += 1
        self.clear()
        self.write(f"LEVEL : {self.level}", align= "center", font= FONT)

    def game_over(self):
        self.home()
        self.write("GAME OVER", align= "center", font = ("Arial", "50", "bold"))


"""
Single root scenario: Soil depletion due to sinusoidal transpiration

coupled to cylindrical rhizosphere models using 1d axi-symetric richards equation (DUMUX solver)
"""

import sys; sys.path.append("../../../modules/"); sys.path.append("../../../../../CPlantBox/");  sys.path.append("../../../../../CPlantBox/src/python_modules")
sys.path.append("../../../../build-cmake/cpp/python_binding/"); sys.path.append("../../../modules/fv/");
sys.path.append("../"); sys.path.append("../scenarios/");

import plantbox as pb  # CPlantBox
from rosi_richards import RichardsSP  # C++ part (Dumux binding), macroscopic soil model
from richards import RichardsWrapper  # Python part, macroscopic soil model
from xylem_flux import *  # root system Python hybrid solver
from rhizo_models import *  # Helper class for cylindrical rhizosphere models

import vtk_plot as vp
import van_genuchten as vg
import aggregated_rs as agg

import matplotlib.pyplot as plt
import numpy as np

"""
Parameters
"""

""" soil """
p_top = -1000  # -5000 (_dry), -1000 (_wet)
p_bot = -200  #
sstr = "_wet"  # <---------------------------------------------------------- (dry or wet)

min_b = [-0.5, -0.5, -50]
max_b = [0.5, 0.5, 0.]
cell_number = [1, 1, 100]
periodic = False

alpha = 0.018  # (cm-1) soil
n = 1.8
Ks = 28.46  # (cm d-1)
loam = [0.08, 0.43, alpha, n, Ks]
soil_ = loam
soil = vg.Parameters(soil_)
vg.create_mfp_lookup(soil, -1.e5, 1000)  # creates the matrix flux potential look up table (in case for exact)

""" root system """
trans = 0.5  # cm3/day
radius = 0.05  # cm
wilting_point = -10000

""" rhizosphere models """
mode = "dumux"
NC = 10  # dof+1, i.e. dof = 9
logbase = 0.5  # according to Mai et al. (2019)
split_type = 0  # type 0 == volume, type 1 == surface, type 2 == length

""" simulation time """
sim_time = 7.1  # 0.65  # 0.25  # [day]
dt = 20 / (24 * 3600)  # time step [day], 120 schwankt stark
NT = int(np.ceil(sim_time / dt))  # number of iterations
skip = 3  # for output and results, skip iteration

"""
Initialize macroscopic soil model (Dumux binding)
"""
s = RichardsWrapper(RichardsSP())
s.initialize()
s.createGrid(min_b, max_b, cell_number, periodic)  # [cm]
s.setLinearIC(p_top, p_bot)  # cm pressure head, equilibrium
s.setTopBC("noFlux")
s.setBotBC("noFlux")
s.setVGParameters([soil_])
s.setParameter("Newton.EnableAbsoluteResidualCriterion", "True")
s.initializeProblem()
s.setCriticalPressure(wilting_point)  # new source term regularisation
s.ddt = 1.e-5  # [day] initial Dumux time step

"""
Initialize xylem model
"""
ns = 100  # 50 cm root, 100 segments, 0.5 cm each
r = agg.create_singleroot(ns = ns, l = 50, a = radius)
r.rs.setRectangularGrid(pb.Vector3d(min_b[0], min_b[1], min_b[2]), pb.Vector3d(max_b[0], max_b[1], max_b[2]),
                        pb.Vector3d(cell_number[0], cell_number[1], cell_number[2]), cut = False)
picker = lambda x, y, z: s.pick([x, y, z])  #  function that return the index of a given position in the soil grid (should work for any grid - needs testing)
r.rs.setSoilGrid(picker)  # maps segments, maps root segements and soil grid indices to each other in both directions
rs = RhizoMappedSegments(r.rs, wilting_point, NC, logbase, mode)
rs.setRectangularGrid(pb.Vector3d(min_b[0], min_b[1], min_b[2]), pb.Vector3d(max_b[0], max_b[1], max_b[2]),
                        pb.Vector3d(cell_number[0], cell_number[1], cell_number[2]), cut = False)
picker = lambda x, y, z: s.pick([x, y, z])  #  function that return the index of a given position in the soil grid (should work for any grid - needs testing)
rs.setSoilGrid(picker)  # maps segments, maps root segements and soil grid indices to each other in both directions
rs.set_xylem_flux(r)
agg.init_comp_conductivities_const(r)

""" sanity checks """
r.test()  # sanity checks

"""
Initialize local soil models (around each root segment)
"""
start_time = timeit.default_timer()
x = s.getSolutionHead()  # initial condition of soil [cm]
rs.initialize(soil_, x)
# print("press any key"); input()

"""
Simulation

loop
1. xylem model
2. local soil models
3. macroscopic soil model
"""
print("Starting simulation")
start_time = timeit.default_timer()

# for post processing
psi_x_ = []
psi_s_ = []  # root soil interface
psi_s2_ = []  # soil
sink_ = []
x_, y_ = [], []

water_uptake, water_collar_cell, water_cyl, water_domain = [], [], [], []  # cm3

cci = picker(rs.nodes[0].x, rs.nodes[0].y, rs.nodes[0].z)  # collar cell index
cell_volumes = s.getCellVolumes()  # cm3
cell_volumes = comm.bcast(cell_volumes, root = 0)
net_flux = np.zeros(cell_volumes.shape)

t = 0.
rs_age = 0.

for i in range(0, NT + 1):

    t = i * dt  # current simulation time

    """ 1. xylem model """
    rsx = rs.get_inner_heads()  # matric potential at the root soil interface, i.e. inner values of the cylindric models (not extrapolation to the interface!) [cm]
    if i == 0:
        rx = r.solve(rs_age + t, -trans * sinusoidal(t), 0., rsx, cells = False, wilting_point = wilting_point, soil_k = [])

    # different choices of limitting conductivitiy
    soil_k0 = np.zeros(rsx.shape)  # exact
    for j in range(0, rsx.shape[0]):
        hsoil = rsx[j]
        hint = rx[j + 1]
        soil_k0[j] = (vg.fast_mfp[soil](hsoil) - vg.fast_mfp[soil](hint)) / (hsoil - hint)
    soil_k00 = np.divide(soil_k0, rs.get_dx2())  # only valid for homogenous soil
    soil_k000 = rs.get_soil_k(rx)
    # approx
    soil_k1 = np.divide(vg.hydraulic_conductivity(rsx, soil), rs.get_dx2())  # only valid for homogenous soil
    # approx2 rs.get_dx2()
    soil_k2 = np.divide(vg.hydraulic_conductivity(rx[1:], soil), rs.get_dx2())  # only valid for homogenous soil
    # old
    soil_k = np.divide(vg.hydraulic_conductivity(rsx, soil), rs.radii)  # only valid for homogenous soil
    soil_k = soil_k00
    rx = r.solve(rs_age + t, -trans * sinusoidal(t), 0., rsx, cells = False, wilting_point = wilting_point, soil_k = soil_k)

    # validity check
    proposed_inner_fluxes = r.segFluxes(0., rx.copy(), rsx.copy(), approx = False, cells = False, soil_k = soil_k.copy())  # [cm3/day]
    collar_flux = r.collar_flux(0., rx.copy(), rsx.copy(), k_soil = soil_k.copy(), cells = False)
    err = np.linalg.norm(np.sum(proposed_inner_fluxes) - collar_flux)
    if err > 1.e-10:
        print("error: summed root surface fluxes and root collar flux differ" , err)

    """ 2. local soil models """
    proposed_outer_fluxes = r.splitSoilFluxes(net_flux / dt, split_type)
    rs.solve(dt, proposed_inner_fluxes, proposed_outer_fluxes)  # left and right neumann fluxes
    realized_inner_fluxes = rs.get_inner_fluxes()  # identical for mode = "dumux"

    # validity check
    err = np.linalg.norm(np.array(proposed_inner_fluxes) - np.array(realized_inner_fluxes))
    if err > 1.e-15:
        print("error: summed root surface fluxes and cylindric model fluxes differ" , err)

    """ 3a. macroscopic soil model """
    water_content = np.array(s.getWaterContent())  # theta per cell [1]
    soil_water = np.multiply(water_content, cell_volumes)  # water per cell [cm3]
    soil_fluxes = r.sumSegFluxes(realized_inner_fluxes)  # [cm3/day]  per soil cell
    s.setSource(soil_fluxes.copy())  # [cm3/day], in moduels/richards.py
    s.solve(dt)  # in modules/solverbase.py

    """ 3b. calculate net fluxes """
    water_content = np.array(s.getWaterContent())
    new_soil_water = np.multiply(water_content, cell_volumes)  # calculate net flux
    net_flux = new_soil_water - soil_water  # change in water per cell [cm3]
    for k, root_flux in soil_fluxes.items():
        net_flux[k] -= root_flux * dt
        # net_flux[k] = 0  # same as SRA approach (currently no-flux at boundary)
    soil_water = new_soil_water

    """ remember results ... """
    if i % skip == 0:
        x_.append(t)
        sum_flux = 0.
        for f in soil_fluxes.values():
            sum_flux += f
        y_.append(sum_flux)  # cm3/day
        fluxes = np.array(proposed_inner_fluxes)
        collar_flux = r.collar_flux(0., rx, rsx, k_soil = soil_k, cells = False)
        print(i / skip, collar_flux, np.sum(fluxes), np.min(fluxes), np.max(fluxes))
        psi_x_.append(rx.copy())
        psi_s_.append(np.array(rsx.copy()))
        dd = np.array(s.getSolutionHead())
        psi_s2_.append(dd[:, 0])
        sink_.append(fluxes.copy())

print ("Coupled benchmark solved in ", timeit.default_timer() - start_time, " s")

""" file output """
file1 = 'results/psix_singleroot_cyl_dynamic_constkrkx' + sstr
np.save(file1, np.array(psi_x_))

file2 = 'results/psiinterface_singleroot_cyl_dynamic_constkrkx' + sstr
np.save(file2, np.array(psi_s_))

file3 = 'results/sink_singleroot_cyl_dynamic_constkrkx' + sstr
np.save(file3, -np.array(sink_))

file4 = 'results/transpiration_singleroot_cyl_dynamic_constkrkx' + sstr
np.save(file4, np.vstack((x_, -np.array(y_))))

file5 = 'results/soil_singleroot_cyl_dynamic_constkrkx' + sstr
np.save(file5, np.array(psi_s2_))

print("fin")


#!/usr/bin/env python

from setuptools import *

try:
	readme = open("README").read()
except StandardError:
	readme = "see README file"

setup(
	name='mandy',
	version='0.1.4',
	description='a terse command-line options parser',
	author='Tim Cuthbertson',
	author_email='tim3d.junk+mandy@gmail.com',
	url='http://pypi.python.org/pypi/mandy/',
	packages=find_packages(exclude=["test"]),

	long_description=readme,
	classifiers=[
		"License :: OSI Approved :: BSD License",
		"Programming Language :: Python",
		"Development Status :: 4 - Beta",
		"Intended Audience :: Developers",
		"Topic :: Software Development :: Libraries :: Python Modules",
	],
	keywords='optparse option parsing command commandline simple',
	license='BSD',
	install_requires=[
		'setuptools',
	],
)


import csv
import sys

debug = False
neighborhood_num = 1

# If a file was not provided, prompt the user
if(sys.argv[1] is None):
	csvfile = input("What is the name of the CSV? ")
else:
	csvfile = sys.argv[1]

# Ask what info is in the file
option = input("Which type of file is this?")

# Generate individual text files
for row in csv.DictReader(open(csvfile), delimiter='\t'):
	filename = "neighborhood_" + option + "_%s.txt" % neighborhood_num
	with open(filename, 'w', newline='', encoding='utf8') as f:  # Just use 'w' mode in 3.x

		w = csv.DictWriter(f, row.keys())
		w.writeheader()
		w.writerow(row)

		if debug:
			print(row)
	neighborhood_num += 1

print("Finished writing %d text files", neighborhood_num-1)


import pytest
import datetime
import botocore.session
from botocore.stub import Stubber
import expireKeys

# Warn after 85 days, expire after 90
warning = 85
expiration = 90
sample = 87 # should be greater than warning, less than expiration

# testing against logic involving time, set dates which can be asserted
def setDates(warn, expire):
    today = datetime.datetime.now()
    sampleDays = (datetime.datetime.now() - datetime.timedelta(days=sample))
    warnDays = (datetime.datetime.now() - datetime.timedelta(days=warn))
    expireDays = (datetime.datetime.now() - datetime.timedelta(days=expire))

    dates = {}
    dates['today'] = today
    dates['sampleDate'] = sampleDays
    dates['warnDate'] = warnDays
    dates['expireDate'] = expireDays
    return dates

date = setDates(warning, expiration)
usersResponse = {
  "Users": [
    {
      "Arn": "arn:aws:iam::123456789012:user/test1",
      "CreateDate": datetime.datetime(2018, 4, 28, 16, 38, 14),
      "PasswordLastUsed": date['today'],
      "Path": "/",
      "UserId": "AID2MAB8DPLSRHEXAMPLE",
      "UserName": "test1"
    },
    {
      "Arn": "arn:aws:iam::123456789012:user/test2",
      "CreateDate": datetime.datetime(2018, 4, 28, 16, 38, 14),
      "PasswordLastUsed": date['today'],
      "Path": "/",
      "UserId": "AIDIODR4TAW7CSEXAMPLE",
      "UserName": "test2"
    },
    {
      "Arn": "arn:aws:iam::123456789012:user/test3",
      "CreateDate": datetime.datetime(2018, 4, 28, 16, 38, 14),
      "PasswordLastUsed": date['today'],
      "Path": "/",
      "UserId": "AIDTKWGCODQAEXAMPLE",
      "UserName": "test3"
    },
    {
      "Arn": "arn:aws:iam::123456789012:user/test4",
      "CreateDate": datetime.datetime(2018, 4, 28, 16, 38, 14),
      "PasswordLastUsed": date['today'],
      "Path": "/",
      "UserId": "AIDTKWGCODQAEXAMPLE",
      "UserName": "test4"
    }
  ]
}

test1KeysResponse = {
  "AccessKeyMetadata": [
    {
      "UserName": "test1",
      "AccessKeyId": "11111111111111111111",
      "Status": "Active",
      "CreateDate": date['warnDate']
    },
  ],
  "IsTruncated": False,
  "Marker": "string"
}

test2KeysResponse = {
  "AccessKeyMetadata": [
    {
      "UserName": "test2",
      "AccessKeyId": "22222222222222222222",
      "Status": "Active",
      "CreateDate": date['expireDate']
    },
    {
      "UserName": "test2",
      "AccessKeyId": "33333333333333333333",
      "Status": "Inactive",
      "CreateDate": date['warnDate']
    },
  ],
  "IsTruncated": False,
  "Marker": "string"
}

test3KeysResponse = {
  "AccessKeyMetadata": [
    {
      "UserName": "test3",
      "AccessKeyId": "44444444444444444444",
      "Status": "Active",
      "CreateDate": date['sampleDate']
    },
    {
      "UserName": "test3",
      "AccessKeyId": "55555555555555555555",
      "Status": "Active",
      "CreateDate": date['expireDate']
    },
  ],
  "IsTruncated": False,
  "Marker": "string"
}

test4KeysResponse = {
  "AccessKeyMetadata": [],
  "IsTruncated": False,
  "Marker": "string"
}

updateResponse = {
  'ResponseMetadata': {
    'RetryAttempts': 0,
    'HTTPStatusCode': 200,
    'RequestId': '3e015bc2-6ac8-11e8-b630-1fa11ee69c5c',
    'HTTPHeaders': {
      'x-amzn-requestid': '3e015bc2-6ac8-11e8-b630-1fa11ee69c5c',
      'date': date['today'],
      'content-length': '210',
      'content-type': 'text/xml'
    }
  }
}

stubber = Stubber(expireKeys.client)

def test_issue_users_dict():
  # takes list of IAM users
  # gets all keys for each user
  # determines warn and expired keys
  # set expired keys to Inactive
  # return dict with list of warning keys + days remaining and a list of keys set to Inactive
  stubber.add_response('list_users', usersResponse, {})
  stubber.add_response('list_access_keys', test1KeysResponse, {'UserName': 'test1'})
  stubber.add_response('list_access_keys', test2KeysResponse, {'UserName': 'test2'})
  stubber.add_response('update_access_key', updateResponse, {'AccessKeyId': '22222222222222222222', 'UserName': 'test2', 'Status': 'Inactive'})
  stubber.add_response('list_access_keys', test3KeysResponse, {'UserName': 'test3'})
  stubber.add_response('update_access_key', updateResponse, {'AccessKeyId': '55555555555555555555', 'UserName': 'test3', 'Status': 'Inactive'})
  stubber.add_response('list_access_keys', test4KeysResponse, {'UserName': 'test4'})
  stubber.activate()

  users = expireKeys.getIssueUsers(warning, expiration)

  stubber.assert_no_pending_responses()
  stubber.deactivate()
  # User test1:
  # - should have a key which warns and ttl
  # - should not have any expired keys
  assert users[0]['user'] == usersResponse['Users'][0]['UserName']
  assert users[0]['warn'][0]['ttl'] == (date['warnDate'].date() - date['expireDate'].date()).days
  assert users[0]['warn'][0]['key'] == test1KeysResponse['AccessKeyMetadata'][0]['AccessKeyId']
  assert len(users[0]['expired']) == 0

  # User test2:
  # - should have an expired key
  # - should not have any warn keys
  assert users[1]['user'] == usersResponse['Users'][1]['UserName']
  assert len(users[1]['warn']) == 0
  assert users[1]['expired'][0] == test2KeysResponse['AccessKeyMetadata'][0]['AccessKeyId']

  # User test3:
  # - should have a key which warns; ttl of expire - sample difference
  # - should have a expired key
  assert users[2]['user'] == usersResponse['Users'][2]['UserName']
  assert users[2]['warn'][0]['ttl'] == (date['sampleDate'].date() - date['expireDate'].date()).days
  assert users[2]['warn'][0]['key'] == test3KeysResponse['AccessKeyMetadata'][0]['AccessKeyId']
  assert users[2]['expired'][0] == test3KeysResponse['AccessKeyMetadata'][1]['AccessKeyId']

  # User test4:
  # - should not be returned
  def verifyUser4NotFound(users):
    check = []
    for user in users:
      if user['user'] == usersResponse['Users'][3]['UserName']:
        x = True
        check.append(x)
      else:
        x = False
        check.append(x)
    return check

  checks = verifyUser4NotFound(users)
  assert True not in checks


import os
import time

from game.catan_state import CatanState
from players.expectimax_baseline_player import ExpectimaxBaselinePlayer
from players.random_player import RandomPlayer
from train_and_test.logger import logger, fileLogger
from players.mcts_player import MCTSPlayer

def scores_changed(state, previous_scores, scores):
    for player in state.players:
        if previous_scores[player.get_id()] != scores[player.get_id()]:
            return True
    return False

def execute_game(i, iterations, plot_map=True):
    seed = None
    timeout_seconds = 5
    p0 = MCTSPlayer(0, iterations=iterations)
    p1 = RandomPlayer(1)
    p2 = RandomPlayer(2)
    p3 = RandomPlayer(3)
    players = [p0, p1, p2, p3]

    state = CatanState(players, seed)

    turn_count = 0
    score_by_player = state.get_scores_by_player_indexed()
    # if plot_map:
    #     state.board.plot_map('turn_{}_scores_{}.png'
    #                          .format(turn_count, ''.join('{}_'.format(v) for v in score_by_player.values())))

    while not state.is_final():
        # noinspection PyProtectedMember
        logger.info('----------------------p{}\'s turn----------------------'.format(state._current_player_index))

        turn_count += 1
        robber_placement = state.board.get_robber_land()

        move = state.get_current_player().choose_move(state)
        assert not scores_changed(state, score_by_player, state.get_scores_by_player_indexed())
        state.make_move(move)
        state.make_random_move()

        score_by_player = state.get_scores_by_player_indexed()

        move_data = {k: v for k, v in move.__dict__.items() if (v and k != 'resources_updates') and not
                     (k == 'robber_placement_land' and v == robber_placement) and not
                     (isinstance(v, dict) and sum(v.values()) == 0)}
        logger.info('| {}| turn: {:3} | move:{} |'.format(''.join('{} '.format(v) for v in score_by_player),
                                                          turn_count, move_data))
        # if plot_map:
        #     image_name = 'turn_{}_scores_{}.png'.format(
        #         turn_count, ''.join('{}_'.format(v) for v in score_by_player))
        #     state.board.plot_map(image_name, state.current_dice_number)

    players_scores_by_names = {(k, v.__class__, v.expectimax_alpha_beta.evaluate_heuristic_value.__name__ if (
        isinstance(v, ExpectimaxBaselinePlayer)) else None): score_by_player[v.get_id()]
                               for k, v in locals().items() if v in players
                               }
    fileLogger.info('\n' + '\n'.join(' {:80} : {} '.format(str(name), score)
                                     for name, score in players_scores_by_names.items()) +
                    '\n turns it took: {}\n'.format(turn_count) + 'game num: {}, num iterations: {}'.format(i, iterations) + '\n' + ('-' * 156))

    p0_type = type(p0).__name__
    p_others_type = type(p1).__name__

# def run_single_game_and_plot_map():
#     execute_game(plot_map=False)

def run_multiple_games_with_different_iterations():
    for i in range(20):
        execute_game(i+1, 10, plot_map=False)
    # for j in range(10):
    #     execute_game(j+1, 1000, plot_map=False)
    # execute_game(1, 100, plot_map=False)

if __name__ == '__main__':
    run_multiple_games_with_different_iterations()


def minNumberOfCoinsForChange(n, denoms):
    # Write your code here.
	dp = [float('inf') for _ in range(n + 1)]
	dp[0] = 0
	for i in range(1,n+1):
		for j in range(len(denoms)):
			if denoms[j] <= i:
				dp[i] = min(dp[i], dp[i - denoms[j]] + 1)
	return dp[n] if dp[n] != float('inf') else -1


import rospy
import pygame
from geometry_msgs.msg import Twist
lis = 0
ans = 0

while True:
	pub = rospy.Publisher('/turtle1/cmd/vel',Twist,queue_size = 10)
	rospy.init_node('/turtle1/cmd/vel',anonymous = True)
	rate = rospy.Rate(10)
	pub_twist = Twist()
	pub_twist.linear.x = lis
	pub_twist.angular = ans
	pub.publish( pub_twist )
	rate.sleep()
	if keys_pressed[pygame.K_W]:
		lis = 1


"""
TESTS is a dict with all you tests.
Keys for this will be categories' names.
Each test is dict with
    "input" -- input data for user function
    "answer" -- your right answer
    "explanation" -- not necessary key, it's using for additional info in animation.
"""

TESTS = {
    "Basics": [
        {
            "input": ["w@AABGWA>eehurrag"],
            "answer": "Password1",
            "explanation": ""
        },
        {
            "input": ["aGG*?^gZAihl"],
            "answer": "Monkey",
            "explanation": ""
        }
    ],
    "Extra": [
        {
            "input": ["rfegrjewoigfwaef"],
            "answer": "TCDPTMLX",
            "explanation": ""
        },
        {
            "input": ["jliajgawegireajger"],
            "answer": "XINKKBS^B",
            "explanation": ""
        },
        {
            "input": ["4grwefwfegdr"],
            "answer": "FCURCQ",
            "explanation": ""
        },
        {
            "input": ["wy4eu4ehxfh"],
            "answer": "__LMP;",
            "explanation": ""
        }
    ]
}


import asyncio
import unittest
from typing import Awaitable

import hummingbot.connector.derivative.bitmex_perpetual.bitmex_perpetual_web_utils as web_utils
import hummingbot.connector.derivative.bitmex_perpetual.constants as CONSTANTS
from hummingbot.connector.derivative.bitmex_perpetual.bitmex_perpetual_web_utils import BitmexPerpetualRESTPreProcessor
from hummingbot.core.web_assistant.connections.data_types import RESTMethod, RESTRequest
from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory

class BitmexPerpetualWebUtilsUnitTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        super().setUpClass()
        cls.ev_loop = asyncio.get_event_loop()

        cls.pre_processor = BitmexPerpetualRESTPreProcessor()

    def async_run_with_timeout(self, coroutine: Awaitable, timeout: float = 1):
        ret = self.ev_loop.run_until_complete(asyncio.wait_for(coroutine, timeout))
        return ret

    def test_bitmex_perpetual_rest_pre_processor_non_post_request(self):
        request: RESTRequest = RESTRequest(
            method=RESTMethod.GET,
            url="/TEST_URL",
        )

        result_request: RESTRequest = self.async_run_with_timeout(self.pre_processor.pre_process(request))

        self.assertIn("Content-Type", result_request.headers)
        self.assertEqual(result_request.headers["Content-Type"], "application/x-www-form-urlencoded")

    def test_bitmex_perpetual_rest_pre_processor_post_request(self):
        request: RESTRequest = RESTRequest(
            method=RESTMethod.POST,
            url="/TEST_URL",
        )

        result_request: RESTRequest = self.async_run_with_timeout(self.pre_processor.pre_process(request))

        self.assertIn("Content-Type", result_request.headers)
        self.assertEqual(result_request.headers["Content-Type"], "application/json")

    def test_rest_url_main_domain(self):
        path_url = "/TEST_PATH_URL"

        expected_url = f"{CONSTANTS.PERPETUAL_BASE_URL}{path_url}"
        self.assertEqual(expected_url, web_utils.rest_url(path_url))
        self.assertEqual(expected_url, web_utils.rest_url(path_url))

    def test_rest_url_testnet_domain(self):
        path_url = "/TEST_PATH_URL"

        expected_url = f"{CONSTANTS.TESTNET_BASE_URL}{path_url}"
        self.assertEqual(
            expected_url, web_utils.rest_url(path_url=path_url, domain="testnet")
        )

    def test_wss_url_main_domain(self):
        endpoint = "TEST_SUBSCRIBE"

        expected_url = f"{CONSTANTS.PERPETUAL_WS_URL}{endpoint}"
        self.assertEqual(expected_url, web_utils.wss_url(endpoint=endpoint))

    def test_wss_url_testnet_domain(self):
        endpoint = "TEST_SUBSCRIBE"

        expected_url = f"{CONSTANTS.TESTNET_WS_URL}{endpoint}"
        self.assertEqual(expected_url, web_utils.wss_url(endpoint=endpoint, domain="testnet"))

    def test_build_api_factory(self):
        api_factory = web_utils.build_api_factory()

        self.assertIsInstance(api_factory, WebAssistantsFactory)
        self.assertIsNone(api_factory._auth)

        self.assertTrue(1, len(api_factory._rest_pre_processors))


import os
import argparse

def parseArgs():
	"""
	Parse command line arguments.

	:return:	command line
	:rtype:	argument object
	"""
	parser = argparse.ArgumentParser(description = 'fix the indentation of a file')

	parser.add_argument('-f', '--file', dest = 'file', help = 'input file to treat',	 required = True)
	parser.add_argument('-m', '--marker', dest = 'marker', help = 'marker of the beginning of a method',	required = True)

	args = parser.parse_args()

	return args

def main():
	args = parseArgs()

	file_path = os.path.abspath(args.file)
	marker = args.marker

	if ((os.path.isfile(file_path)) and (marker)):
		buffer = []
		ind = 0

		with open(file_path, 'r') as file:
			for line in file:
				if (line.find(marker) == 0):
					buffer.append('{0}<method>\n'.format('\t'*ind))
					ind += 1
				else:
					ind -= 1
					buffer.append('{0}</method>{1}'.format('\t'*ind, line))

		# Creation of the new cleaned file
		head, tail = os.path.split(file_path)
		tail = os.path.splitext(tail)[0]

		file_path1 = os.path.join(head, tail + '_fixed_indentation')

		with open(file_path1, 'w') as file:
			for line in buffer:
				file.write(line)

	print('::INFO  {0} is now clean and ready for an analyse! \n'.format(tail + '_fixed_indentation'))

if __name__ == '__main__':
	main()


# real main.py page

from flask import Flask, render_template
from datetime import datetime

app = Flask(__name__)

@app.route('/')
def hello():
	utc_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
#	return ("
Hello World
"+utc_time
	return render_template("index.html", utc_time=utc_time)

@app.route('/about')
def about():
	utc_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
	return render_template("about.html", utc_time=utc_time)

if __name__=='__main__':
    app.run(host="0.0.0.0",debug=True)


# Classes for Euler-Bernoulli Codes

class Params:
	def __init__(self,f,M,F,EI,L,N,ELEM,IELEM,NELEM,NDF):
		# Model Parameters
		self.f = f
		self.M = M
		self.F = F
		self.EI = EI
		self.L = L

		# Mesh Parameters
		self.N = N
		self.ELEM = ELEM
		self.IELEM = IELEM
		self.NELEM = NELEM
		self.NDF = NDF

class Domain:
	def __init__(self,start,stop,ELEM,f,M,F,EI):
		self.start = start
		self.stop = stop
		self.ELEM = ELEM
		self.f = f
		self.M = M
		self.F = F
		self.EI = EI

		self.h = (stop - start)/ELEM


class FenwickTree:
    def __init__(self, n):
        self.n = n
        self.tree = [0] * n

    def query(self, l, r):
        def _query(pos):
            res = 0
            while pos >= 0:
                res += self.tree[pos]
                pos = (pos & (pos + 1)) - 1
            return res

        return _query(r) - _query(l - 1)

    def update(self, pos, val):
        while pos < self.n:
            self.tree[pos] += val
            pos = pos | (pos + 1)

t = FenwickTree(16)
for i in range(16):
    t.update(i, i)
print([i for i in range(16)])
print(t.tree)
print(t.query(0, 9))


from scipy.integrate import quadrature
from scipy.integrate import romb
from scipy.integrate import quad
from scipy.special import gamma
from operator import add
import numpy as np
import time
import sys
#checking
start_time = time.time()
procfile = open('proc_results.dat', 'w+')
def read_prod_data(file):

    """Reads the ENDF product yield data file"""

    prod_file = open(file,'r')

    pfile = prod_file.readlines()
    Z = []
    A = []
    isomer = []
    element = []
    prod_yield = []
    for lines in pfile:
        word = lines.split()
        Z.append(float(word[1]))
        element.append(word[2])
        A.append(float(word[3]))
        isomer.append(int(float(word[5])))
        prod_yield.append(float(word[6]))

    return A, Z, element, isomer, prod_yield

def read_decay_data(decay_file, parent, isomer_flag):

    """Reads the extracted decay data from the betadata.dat file."""

    print('------------------------------------------', file=procfile)
    print('Parent: ', parent, file=procfile)
    decay_data = []
    parent_energy = []
    level_decay_data = []

    f = open(decay_file, 'r')
    lines = f.readlines()
    f.close()

    i = 0
    ii = 1
    for line in lines:
        objects = line.split()

        if  objects[0] == parent:
            if objects[1] == isomer_flag:
                print('Isomer Flag: ', isomer_flag, file=procfile)
                i = 1
        elif objects[0] == 'EOF' and (i == 1 or i == 2):
            decay_data = level_decay_data
            return parent_energy, decay_data
        elif i == 1:
            print('Parent E: ', objects[0], file=procfile)
            parent_energy = [float(objects[0]), float(objects[1])]
            i = 2
        elif i == 2:
            level_decay_data.append(objects)
        elif ii > len(lines) - 1:
            decay_data = level_decay_data
            return parent_energy, decay_data

        ii += 1

    return parent_energy, decay_data

def fermi(a, z, e, e0, forbid):

    """Calculates the Fermi function for a beta- decay"""

    if e < 613.2:#Should be e < 1.2*511=613.2
        alpha = - 0.811 + z * 4.46E-2 + np.square(z) * 1.08E-4
        beta = 0.673 - z * 1.82E-2 + np.square(z) * 6.38E-5
        f_initial = np.exp(alpha + beta * np.sqrt(((e + 511.) / 511.) - 1))
    elif e >= 613.2:
        alpha = - 8.46E-2 + z * 2.48E-2 + np.square(z) * 2.37E-4
        beta = 1.15E-2 + z * 3.58E-4 - np.square(z) * 6.17E-5
        f_initial = np.exp(alpha + beta * np.sqrt(((e + 511.) / 511.) - 1))

    c = correction(e, e0, forbid)
    f = f_initial * c

    return f

def correction(e, e0, forbid):

    """Shape factors for allowed (A), first-forbidden (FF), and
    first-forbidden unique (FFU) decays"""

    #Defining the electron and neutrino momentum
    p = np.sqrt(e*e + 2 * 511. * e)
    q = (e0 - e)
    beta = p / e
    #The shape factors, determined by the spin-parity of decay
    #Gamow-Teller decays
    if forbid == 'A':
        c = 1
    elif forbid == 'FF':
        c = p*p + q*q + 2 * beta*beta * q * e
    elif forbid == 'FFU':
        c = p*p + q*q
    #Find an expression for this forbideness
    elif forbid == 'SFU':
        c = 1
    #    #c = p*p - 2 * e * q
    #    c = p*p + q*q
    #Fermi decays
    #elif forbid == '0+':
    #    c = 1
    #elif forbid == '1-':
    #    c = p*p + q*q + (2/3) * beta*beta * q * e

    return c

def probability(a, z, e, e0, forbid):

    """Function to calculate the unormalized probability spectrum
    of beta- decay branch. Includes only the finite size correction... so far."""

    q = (e0 - e)**2
    fermi_func = fermi(a, z, e, e0, forbid)
    prob = (q * np.square(e + 511.) * fermi_func)

    return prob

def normalization(a, z, e0, forbid):

    """Integrates the analytical form of the beta spectrum and returns the
    normalization factor."""

    #Check out Scipy Ctype integration with C via Python, >2x speedup.
    y = lambda e: probability(a, z, e, e0, forbid)
    l_lim = 1.
    norm = quad(y, l_lim, e0)[0]
    print('Branch Integration: ', norm, file=procfile)

    return norm

def total_normalization(spectrum):

    """Integrates the coordinate pairs of the total beta spectrum and
    returns the normalization factor."""

    y1 = []
    for coord in spectrum:
        y1.append(coord[1])
    y = np.array(y1)
    #Check out Scipy Ctype integration with C via Python, >2x speedup.
    #Important!! The romb (romberg) integration must have 2^k + 1 points.
    l_lim = 1.
    dx = 0.5
    norm = romb(y, dx=dx)

    return norm

def branch_spectrum(a, z, e0, forbidden, intensity):

    """Calculate the spectrum for a single decay branch. It includes the intensity factor."""

    branch_spectrum = []
    print('Forbiddeness: ', forbidden, file=procfile)
    I = intensity / 100
    print('Intensity: ', I, file=procfile)
    norm = normalization(a, z, e0, forbidden)
    #Create spectrum, note for the romb integration must have 2^k + 1 points.
    for i in range(0, 4097):
        e = (i * 3.5) + 1.0
        if e <= e0:
            prob = probability(a, z, e, e0, forbidden)
            branch_spectrum.append([e, I * (prob / norm)])
        else:
            branch_spectrum.append([e, 0])

    return branch_spectrum

def decay_spectrum(f, spectra, intensity):

    """Somewhat generic function to sum spectra, write to file,
    and return the spectrum sum.

    f = 0, only sums the spectra
    f = a file name, sums and prints the complete spectrum to file."""

    #Sum spectra
    i = 1
    decay_spectrum = []
    for spectrum in spectra:
        print(len(spectrum), i, file=procfile)
        spec = []
        if i < 2:
            for prob in spectrum:
                decay_spectrum.append(prob[1])
        else:
            for total, prob in zip(decay_spectrum, spectrum):
                spec.append(total + prob[1])
            decay_spectrum = spec
        i += 1

    spectrum = spectra[0]
    isotope_spectrum = []

    #Multiply by intensity only
    if not f:
        for e, y in zip(spectra[0], decay_spectrum):
            isotope_spectrum.append([e[0], y*intensity])
    #Multiply by intensity and write to file
    else:
        for e, y in zip(spectra[0], decay_spectrum):
            print('%2.4f   %1.20f ' % (e[0], y*intensity), file=f)
            isotope_spectrum.append([e[0], y*intensity])

    return isotope_spectrum

#Assign and open files to be read and written.
fission_file = 'cum_py.txt'
decay_file = 'betadata.dat'
h = open('final_spectrum.dat', 'w+')
k = open('e_range.dat', 'w+')

#Gather the fission yield data
A, Z, element, isomer_flags, prod_yield = read_prod_data(fission_file)

ii = 0
isotope_spectrum = []
for a, z, elem, isomer_flag, pyield in zip(A, Z, element, isomer_flags, prod_yield):

    print('Fission Intensity: ', pyield, file=procfile)
    parent = str(int(a)) + elem.upper()
    print(ii, ' ', parent)
    #Gather decay data
    parent_energy, level_decay_data = read_decay_data(decay_file, parent, str(isomer_flag))

    level_spectrum = []
    #Each ground state or isomer
    print('Number of Branches: ', len(level_decay_data), file=procfile)
    if len(level_decay_data) < 1:
        print('No Decay Branches!', file=procfile)
        ii += 1
        continue
    else:
        print(ii, ' ','Spectrum processed', parent)

        #file = 'beta_spec_test' + parent + str(ii) + '.dat'
        #f = open(file, 'w+')
        #Make list containing each branch spectrum.
        spectra = []
        #Calculate the spectrum for each branch
        for branch in level_decay_data:
            e_level = float(branch[0])
            forbidden = branch[1]
            intensity = float(branch[2])
            #Disregard branches with intensity < 0.25%
            if intensity < 0.0001:
                continue
            else:
                e0 = parent_energy[1] + parent_energy[0]
                e_max = (e0 - e_level)  #Max energy of the electron in keV
                if e_max <= 0:
                    continue
                else:
                    print('Daughter Energy: ', e_max, file=procfile)
                    spectra.append(branch_spectrum(a, z, e_max, forbidden, intensity))

        print('Len of spectra', len(spectra), file=procfile)
        if len(spectra) > 0:
            #Sum and normalize the branch spectra into the level spectrum
            spectrum = decay_spectrum(0, spectra, 1.0)
            level_norm = total_normalization(spectrum)
            print('Nucleus or Isomer Integration: ', level_norm, file=procfile)
            level_inten = 1 / level_norm
            level_spectrum.append(decay_spectrum(0, spectra, 1.0))

        #f.close()

    #Multiply the level spectrum by the fission yield factor (pyield).
    level_spectrum2 = []
    if len(level_spectrum) > 0:
        print('Multiplied by Fission Intensity', file=procfile)
        level_spectrum2 = (decay_spectrum(0, level_spectrum, pyield))
        isotope_spectrum.append(level_spectrum2)

    ii += 1

#Sum and normalize all the level spectra into final spectrum and write to final_spectrum.dat
fission_spectrum = []
fission_spectrum.append(decay_spectrum(0, isotope_spectrum, 1.0))
fission_norm = total_normalization(fission_spectrum)
print('Final Spectrum Integration: ', fission_norm, file=procfile)
intensity = 1 / fission_norm
decay_spectrum(h, isotope_spectrum, intensity)

print('Number of files: ', ii)
h.close()
procfile.close()
print('Total run time:  ', time.time() - start_time)


from django.urls import path
from . import views
from .views import Products_List, Product_Subs_List

urlpatterns = [
    path('', views.all_products, name='products'),
    path('<int:product_id>/', views.product_detail, name='product_detail'),
    path('product_mgt/', views.product_mgt, name='product_mgt'),
    path('add/', views.add_product, name='add_product'),
    path('products_list/', Products_List.as_view(), name='products_list'),
    path('edit/<int:product_id>/', views.edit_product, name='edit_product'),
    path('delete/<int:product_id>/',
         views.delete_product,
         name='delete_product'),
    path('addprodsub/', views.add_product_subs, name='add_product_subs'),
    path('prodsubs_list/', Product_Subs_List.as_view(), name='prod_subs_list'),
    path('editprodsub/<int:product_subs_id>/',
         views.edit_product_subs,
         name='edit_product_subs'),
    path('delete_prodsub/<int:product_id>/',
         views.delete_product_subs,
         name='delete_product_subs'),
    path('add_review/<int:product_id>/', views.add_review, name='add_review'),
]


from xai.brain.wordbase.nouns._hillside import _HILLSIDE

#calss header
class _HILLSIDES(_HILLSIDE, ):
	def __init__(self,):
		_HILLSIDE.__init__(self)
		self.name = "HILLSIDES"
		self.specie = 'nouns'
		self.basic = "hillside"
		self.jsondata = {}


#Python 3.6.5
import numpy as np

intr = [1,3]

def f(t):
    k = 0.67
    return np.e**(-(1/2)*t)*np.arccosh(np.e**((1/2)*t))-np.sqrt(k/2)

def bissec(prec):

    a = intr[0]
    b = intr[1]

    if f(a) == 0: return a
    if f(b) == 0: return b

    if (f(a)*f(b)) < 0:

        tam = b - a

        while(tam > prec):

            tam = b - a
            c = (a + b)/2

            if(f(c) == 0): return c
            if(f(a)*f(c) < 0): b = c

            else: a = c

        return c
    else:
        print("Valores do intervalo não são válidos")

print(bissec(0.000001))


def complex_mult(x):
    return (500000.0 - 1000*x) / (1000.0 - b)

b = 1.0
a = complex_mult(b)
c = 1000 - a - b

# run the loop until both a and c are integers
while (a % 1.0 != 0 or c % 1.0 != 0):
    b += 1
    a = complex_mult(b)
    c = 1000 - a - b

b = int(b)
a = int(a)
c = int(c)

print ("a: " + str(a) + ", b: " + str(b) + ", c: " + str(c))

print (a*b*c)


import asyncio
import aiohttp
import aiohttp.web
from aiohttp.web import StreamResponse
import pytest
import requests
import signal
import subprocess as sp
import sys
import time
import socket
import multiprocessing

_proxy_bypass = {
  "http": None,
  "https": None,
}

host = "localhost"

def get_free_tcp_port():
    sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sckt.bind((host, 0))
    addr, port = sckt.getsockname()
    sckt.close()
    return port

# This runs in a subprocess for a variety of reasons
# 1) early versions of python 3.5 did not correctly set one thread per run loop
# 2) aiohttp uses get_event_loop instead of using the passed in run loop
# 3) aiohttp shutdown can be hairy
class AIOServer(multiprocessing.Process):
    """
    This is a mock AWS service which will 5 seconds before returning
    a response to test socket timeouts.
    """
    def __init__(self):
        super().__init__(target=self._run)
        self._loop = None
        self._port = get_free_tcp_port()
        self.endpoint_url = 'http://{}:{}'.format(host, self._port)
        self.daemon = True  # die when parent dies

    def _run(self):
        asyncio.set_event_loop(asyncio.new_event_loop())
        app = aiohttp.web.Application()
        app.router.add_route('*', '/ok', self.ok)
        app.router.add_route('*', '/{anything:.*}', self.stream_handler)

        try:
            aiohttp.web.run_app(app, host=host, port=self._port,
                                handle_signals=False)
        except BaseException:
            pytest.fail('unable to start and connect to aiohttp server')
            raise

    async def __aenter__(self):
        self.start()
        await self._wait_until_up()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        try:
            self.terminate()
        except BaseException:
            pytest.fail("Unable to shut down server")
            raise

    async def ok(self, request):
        return aiohttp.web.Response()

    async def stream_handler(self, request):
        # Without the Content-Type, most (all?) browsers will not render
        # partially downloaded content. Note, the response type is
        # StreamResponse not Response.
        resp = StreamResponse(status=200, reason='OK',
                              headers={'Content-Type': 'text/html'})

        await resp.prepare(request)
        await asyncio.sleep(5, loop=self._loop)
        await resp.drain()
        return resp

    async def _wait_until_up(self):
        async with aiohttp.ClientSession() as session:
            for i in range(0, 30):
                if self.exitcode is not None:
                    pytest.fail('unable to start/connect to aiohttp server')
                    return

                try:
                    # we need to bypass the proxies due to monkey patches
                    await session.get(self.endpoint_url + '/ok', timeout=0.5)
                    return
                except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
                    await asyncio.sleep(0.5)
                except BaseException:
                    pytest.fail('unable to start/connect to aiohttp server')
                    raise

        pytest.fail('unable to start and connect to aiohttp server')

def start_service(service_name, host, port):
    args = [sys.executable, "-m", "moto.server", "-H", host,
            "-p", str(port), service_name]

    # If test fails stdout/stderr will be shown
    process = sp.Popen(args, stdin=sp.PIPE)
    url = "http://{host}:{port}".format(host=host, port=port)

    for i in range(0, 30):
        if process.poll() is not None:
            process.communicate()
            pytest.fail("service failed starting up: {}".format(service_name))
            break

        try:
            # we need to bypass the proxies due to monkeypatches
            requests.get(url, timeout=0.5, proxies=_proxy_bypass)
            break
        except requests.exceptions.ConnectionError:
            time.sleep(0.5)
    else:
        stop_process(process)  # pytest.fail doesn't call stop_process
        pytest.fail("Can not start service: {}".format(service_name))

    return process

def stop_process(process):
    try:
        process.send_signal(signal.SIGTERM)
        process.communicate(timeout=20)
    except sp.TimeoutExpired:
        process.kill()
        outs, errors = process.communicate(timeout=20)
        exit_code = process.returncode
        msg = "Child process finished {} not in clean way: {} {}" \
            .format(exit_code, outs, errors)
        raise RuntimeError(msg)

@pytest.yield_fixture(scope="session")
def s3_server():
    host = "localhost"
    port = 5000
    url = "http://{host}:{port}".format(host=host, port=port)
    process = start_service('s3', host, port)

    try:
        yield url
    finally:
        stop_process(process)

@pytest.yield_fixture(scope="session")
def dynamodb2_server():
    host = "localhost"
    port = 5001
    url = "http://{host}:{port}".format(host=host, port=port)
    process = start_service('dynamodb2', host, port)

    try:
        yield url
    finally:
        stop_process(process)

@pytest.yield_fixture(scope="session")
def cloudformation_server():
    host = "localhost"
    port = 5002
    url = "http://{host}:{port}".format(host=host, port=port)
    process = start_service('cloudformation', host, port)

    try:
        yield url
    finally:
        stop_process(process)

@pytest.yield_fixture(scope="session")
def sns_server():
    host = "localhost"
    port = 5003
    url = "http://{host}:{port}".format(host=host, port=port)
    process = start_service('sns', host, port)

    try:
        yield url
    finally:
        stop_process(process)

@pytest.yield_fixture(scope="session")
def sqs_server():
    host = "localhost"
    port = 5004
    url = "http://{host}:{port}".format(host=host, port=port)
    process = start_service('sqs', host, port)

    try:
        yield url
    finally:
        stop_process(process)


#!/usr/bin/python

from __future__ import absolute_import
from roberta.ev3 import Hal
from ev3dev import ev3 as ev3dev
import math
import os

class BreakOutOfALoop(Exception): pass
class ContinueLoop(Exception): pass

_brickConfiguration = {
    'wheel-diameter': 5.6,
    'track-width': 18.0,
    'actors': {
    },
    'sensors': {
        '1':Hal.makeTouchSensor(ev3dev.INPUT_1),
        '2':Hal.makeGyroSensor(ev3dev.INPUT_2),
        '3':Hal.makeColorSensor(ev3dev.INPUT_3),
        '4':Hal.makeUltrasonicSensor(ev3dev.INPUT_4),
    },
}
hal = Hal(_brickConfiguration)

def run():
    while True:
        if ( 0 == 0 ) and True:
            break
        hal.waitFor(15)
    hal.waitFor(500)
    while True:
        if hal.isPressed('1') == True:
            break
        hal.waitFor(15)
    while True:
        if hal.getGyroSensorValue('2', 'angle') > 90:
            break
        hal.waitFor(15)
    while True:
        if hal.getGyroSensorValue('2', 'rate') > 90:
            break
        hal.waitFor(15)
    while True:
        if hal.getColorSensorColour('3') == 'red':
            break
        hal.waitFor(15)
    while True:
        if hal.getColorSensorRed('3') < 50:
            break
        hal.waitFor(15)
    while True:
        if hal.getColorSensorAmbient('3') < 50:
            break
        hal.waitFor(15)
    while True:
        if hal.getUltraSonicSensorDistance('4') < 30:
            break
        hal.waitFor(15)
    while True:
        if hal.getUltraSonicSensorPresence('4') == True:
            break
        hal.waitFor(15)

def main():
    try:
        run()
    except Exception as e:
        hal.drawText('Fehler im EV3', 0, 0)
        hal.drawText(e.__class__.__name__, 0, 1)
        hal.drawText(str(e), 0, 2)
        hal.drawText('Press any key', 0, 4)
        while not hal.isKeyPressed('any'): hal.waitFor(500)
        raise

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
o = input()
e = input()
ans = ""
for i in range(len(o)+len(e)):
    if i%2 == 0:
        ans += o[i//2]
    else:
        ans += e[i//2]
print (ans)


# -*- coding: utf-8 -*-

"""
!!!!!!!!!!!!!!!!!!!!
only applies gaussian blur effect to the realtime face detection.
!!!!!!!!!!!!!!!!!!!!
"""

import cv2
import face_recognition

camera_stream = cv2.VideoCapture(0)
" captures video from camera with index 0"

face_locations = []

while True:
    brk, current_frame = camera_stream.read()
    current_frame_crop = cv2.resize(current_frame,(0,0), fx=0.25, fy=0.25)

    face_locations = face_recognition.face_locations(current_frame_crop, number_of_times_to_upsample=2, model='hog')

    for index,face_location in enumerate(face_locations):
        top_pos, right_pos, bottom_pos, left_pos = face_location
        top_pos *= 4
        right_pos *= 4
        bottom_pos *= 4
        left_pos *= 4

        print('Found face {}, top:{}, right:{}, bottom: {}, left: {}'.format(index, top_pos, right_pos, bottom_pos, left_pos))
        one_face_image = current_frame[top_pos:bottom_pos, left_pos:right_pos]
        one_face_image = cv2.GaussianBlur(one_face_image, (99,99), 35)
        current_frame[top_pos:bottom_pos, left_pos:right_pos] = one_face_image

        cv2.rectangle(current_frame, (left_pos, top_pos), (right_pos, bottom_pos), (255,0,0), 2)

    cv2.imshow("Face from feed", current_frame)

    if cv2.waitKey(1) & 0xFF == ord('f'):
        "Exit key is F !!!"
        break
camera_stream.release()
cv2.destroyAllWindows


from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()

doc = {
	'author': 'Vivek',
	'text': 'Hello World',
	'datetime': datetime.now(),
}

result = es.index(index='test-index', doc_type='test-doc', id=1, body=doc)
print(result['created'])


from recognize_objects import ObjectRecognition
from PIL import Image
import picar_4wd as fc
import picamera

def main():
    with ObjectRecognition() as recognizer:
        while True:
            recognized_objects = [recognizer.label_from_class_id(recognized_object["class_id"]) for recognized_object in recognizer.detect()]
            print(recognized_objects)
            if "stop sign" in recognized_objects:
                fc.stop()
            else:
                fc.forward(20)

if __name__ == "__main__":
    try:
        main()
    finally:
        fc.stop()


# This script runs a workflow using the Galaxy API

import os
import sys
import argparse
import ConfigParser
import time
import tempfile
import urllib
import shutil
import logging as log
import subprocess
import errno
from urlparse import urlparse
from bioblend.galaxy import GalaxyInstance
from bioblend.galaxy.config import ConfigClient
from bioblend.galaxy.workflows import WorkflowClient
from bioblend.galaxy.tools import ToolClient
from bioblend.galaxy.toolshed import ToolShedClient
from bioblend.galaxy.histories import HistoryClient
from bioblend.galaxy.libraries import LibraryClient
from bioblend.galaxy.datasets import DatasetClient

# Parse the CL arguments
parser = argparse.ArgumentParser(description='Run Galaxy workflow using the Galaxy API.')
parser.add_argument("-c", "--config", type=str, required=True)
parser.add_argument("-l", "--log", type=str, required=False, default="execute_workflow.log")

args = parser.parse_args()
config_file = args.config
log_file = args.log

# Create logger
log.basicConfig(filename=log_file, level=log.DEBUG)
logFormatter = log.Formatter("%(asctime)s [%(levelname)-5.5s]  %(message)s")
logger = log.getLogger()

fileHandler = log.FileHandler(log_file, mode='w')
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)

consoleHandler = log.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)

logger.info("Parsed command line arguments")

# Parse the configuration file
config = ConfigParser.RawConfigParser()
config.read(config_file)

# Parse general configuration
wf_id = config.get('General', 'workflow_id')
galaxy_url_dest = config.get('General', 'galaxy_url_dest')
container_file = config.get('General', 'container_file')

# Parse input/output/tmp directories
input_dir = config.get('Data', 'input_directory')
output_dir = config.get('Data', 'output_directory')
tmp_dir = config.get('Data', 'tmp_directory')

# Parse user information (user of Galaxy in Container for whom the workflow is installed)
user_mail = config.get('User', 'user_mail')
user_api_key = config.get('User', 'user_api_key')

# Is the path to the container file valid?
if not os.path.isfile(container_file):
    logger.error("Container does not exist: %s", container_file)
    exit(1)
if not os.access(container_file, os.R_OK):
    logger.error("Container exists, but is not readable: %s", container_file)

# Is the Destination Galaxy URL well formed?
try:
    logger.info("Check if Galaxy URL is well formed ...")
    result_dest = urlparse(galaxy_url_dest)
    if not [result_dest.scheme, result_dest.netloc, result_dest.path]:
        logger.error("Destination Galaxy URL is not well formed: %s", galaxy_url_dest)
        exit(1)
except:
    logger.error("Error during Source Galaxy URL check")
    exit(1)

# Is the input_directory valid and does it contain all needed input files?
# 1. Check if the input directory exists
if not os.path.isdir(input_dir):
    logger.error("Specified input_directory does not exist: %s", input_dir)
    exit(1)
# 2. Parse workflow input steps from the config file: Results in a diectionary, where a
# key is the name of a Galaxy workflow input step.
# The corresponding value is a dictionary with keys that describe the path to the file and the galaxy data type.
workflow_input = {}
for section in config.sections():
    if section not in ["General", "User", "Data"]:
        workflow_input[section] = {}
        for (key, val) in config.items(section):
            workflow_input[section][key] = val
# 3. Check that every input file is present in the input_directory
for step, input  in workflow_input.iteritems():
    input_file = input['filename']
    if os.path.isabs(input_file):
        input_file_abs = input_file
    else:
        input_file_abs = os.path.join(input_dir, input_file)
    if not os.path.isfile(input_file_abs):
        logger.error("Input file for input step %s does not exist: %s", step, input_file_abs)
        exit(1)

# Is the output_directory valid? If it does not exist, create it!
if not os.path.isdir(output_dir):
    logger.info("Specified output_directory does not exist, try to create it: %s", output_dir)
    try:
        os.makedirs(output_dir)
    except:
        logger.error("Cannot create specified output_directory: %s", output_dir)

# Is the tmp_directory valid? Try to create the temporary directory for this session. If that does not work, the temporary directory specifide is not valid.
try:
    tempfile.tempdir = tmp_dir
    session_tmp_dir = tempfile.mkdtemp(prefix="galaxy2singularity_")
except IOError as e:
    logger.error("Cannot write to the specified tmp_directory: %s", tmp_directory)
    exit(1)

# Copy the integrated tools panel and the universe.sqlite into the tmp directory
tmp_bind = session_tmp_dir + ":/galaxy_tmp"
subprocess.call(["singularity", "exec", "--bind", tmp_bind, container_file, "cp", "/galaxy/integrated_tool_panel.xml", "/galaxy/database/universe.sqlite", "/galaxy_tmp"])

# Start Galaxy in daemon mode with binds to input, output und temporary directories
input_bind = input_dir + ":/input"
output_bind = output_dir +":/output"
bind_dirs = input_bind + "," + output_bind + "," + tmp_bind
FNULL = open(os.devnull, 'w')
subprocess.call(["singularity", "exec", "--bind", bind_dirs, container_file, "sh", "/galaxy/run.sh","--log-file", "/output/paster.log", "--pid-file", " /output/paster.pid", "--daemon"], stdout=FNULL, stderr=subprocess.STDOUT)

# Wait until Galaxy is up and running
response = None
while not response:
    # Wait 5s until Galaxy is up
    logger.info("Galaxy is not up ... wait 5 seconds")
    time.sleep(5)
    try:
        response = urllib.urlopen(galaxy_url_dest).getcode() # returns 200 if galaxy is up
    except:
        # Wait 5s until Galaxy is up
        logger.info("Galaxy is not up ... wait 5 seconds")
        time.sleep(5)
        response = None
        continue
    # Galaxy is up
    logger.info("Galaxy is up ...")

# Check if the provided API key is valid
logger.info("Check if the provided API key is valid ...")
gi = GalaxyInstance(url=galaxy_url_dest, key=user_api_key)
try:
    cc = ConfigClient(gi)
    galaxy_version = cc.get_version()
    galaxy_config = cc.get_config()
    logger.info("Provided API key is valid")
except:
    logger.error("Provided API key is not valid.")
    exit(1)

# Get details of a workflow
wfc = WorkflowClient(gi)
wf_desc = wfc.show_workflow(wf_id)

# Create a new history where the workflow outputs are saved
hc = HistoryClient(gi)
output_history_name = 'Output History'
output_history_dict = hc.create_history(output_history_name)
output_history_id = output_history_dict['id']

# Create a library for the input files
# The library is saved at /galaxy_tmp/library directory with a subdirectory that has the user_mail as name
lc = LibraryClient(gi)
# Get id of the input library
input_library_name = 'Input Library'
input_library = lc.get_libraries(library_id=None, name=input_library_name, deleted=False)[0]
input_folder = lc.create_folder(input_library['id'], user_mail)

# Iterate over the files in the input directory and upload them to the 'Input Library'
for input_step, param in workflow_input.iteritems():
    path = os.path.join(input_dir, param['filename'])
    logger.info("Next upload: " + path)
    workflow_input[input_step]['dataset_id'] = lc.upload_file_from_local_path(input_library['id'], path, file_type=param['galaxy_file_type'], folder_id=input_folder[0]['id'])

# Prepare the inputs
# inputs is a dict that maps workflow inputs to datasets and dataset collections.
# The map must be in the following format:
# {'<input_index>': {'id': <encoded dataset ID>, 'src': '[ldda, ld, hda, hdca]'}} (e.g. {'2': {'id': '29beef4fadeed09f', 'src': 'hda'}})
wf_input={}
for input_step, param in workflow_input.iteritems():
    wf_input[param['uuid']] = {'id':param['dataset_id'][0]['id'] , 'src':'ld'}

logger.info("Invoking workflow ...")
# Invoke the workflow
try:
    wf_invocation = wfc.invoke_workflow(wf_id,
		inputs=wf_input,
		params=None,
		history_id=output_history_id,
		history_name=None,
		import_inputs_to_history=False,
		replacement_params=None,
		allow_tool_state_corrections=None)
except:
    logger.error("Error during workflow execution. Please see paster.log at %s for more details", output_dir)

# TODO add except for MissingToolException
# e.g. MissingToolException: toolshed.g2.bx.psu.edu/repos/iuc/bcftools_filter/bcftools_filter/1.3.0

# TODO incorporate the while loop into the upper try ...

# Check workflow status, e.g. check the status of the history in which the results are saved
# Of not 100 percent of jobs ran or if there are no errors, the workflow runs
while True:
    history_status = hc.get_status(wf_invocation['history_id'])
    logger.info("Percent Complete: %s", str(history_status['percent_complete']))
    if history_status['percent_complete'] != 100 and history_status['state_details']['error'] < 1:
        logger.info("Workflow is running ...")
        time.sleep(10)
    else:
        logger.info("No. Errors: " + str(history_status['state_details']['error']))
        break

# Export the output history to the output directory
# Get a list of all datasets in the output history
output_history_datasets = hc.show_history(output_history_id, contents=True, deleted=None, visible=None, details=None, types=None)
# Iterate over the datasets of the output history and download each dataset that has 'ok' state (e.g. the tool completed)
dc = DatasetClient(gi)
for dataset in output_history_datasets:
    # Check the dataset status, e.g. if the corresponding task completed. Do not download input datasets!
    if dataset['state'] == 'ok':
        logger.info("Download dataset %s, state: %s", dataset['name'], dataset['state'])
        dc.download_dataset(dataset['id'], file_path=output_dir, use_default_filename=True, wait_for_completion=False, maxwait=12000)
    else:
        logger.info("Do not download dataset %s, state: %s", dataset['name'], dataset['state'])

# Stop Galaxy daemon
subprocess.call(["singularity", "exec", "--bind", bind_dirs, container_file, "sh", "/galaxy/run.sh","--log-file", "/output/paster.log", "--pid-file", " /output/paster.pid", "--stop-daemon"], stdout=FNULL, stderr=subprocess.STDOUT)

# Remove the temporary directory
logger.info("Remove temporary directory")
shutil.rmtree(session_tmp_dir, ignore_errors=False, onerror=None)


# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/sch/prj/setup/pytigon/pytigon/prj/_schtools/schsimplescripts/script_tools.py
# Compiled at: 2020-05-02 15:32:44
# Size of source mod 2**32: 650 bytes
from pytigon_lib.schdjangoext.django_ihtml import ihtml_to_html

def _transform_view(name, txt1, txt2):
    fun = ''
    for row in txt2.split('\n'):
        fun = fun + '    ' + row + '\n'

    x2 = 'def scripts_%s(request, argv):\n%s\n' % (name, fun)
    return txt1 + '\n' + x2

def _transform_template(txt):
    return ihtml_to_html(None, txt)

def decode_script(name, code):
    elements = code.split('===')
    if len(elements) >= 4:
        _form = elements[1]
        _view = _transform_view(name, elements[0], elements[2])
        _template = _transform_template(elements[3])
        return [_form, _view, _template]


"""Module of the parameters used in the framework

"""

from __future__ import division
import numpy as np
import os
import math as mt

filePath = os.path.realpath(__file__)
projDir, _ = os.path.split(filePath)

# In general, all units are in the standard format, except for variables of length (mm)

# body length.
# unit: mm
# each row: coxa, femur, tiba, tarsus
# each column:
# front leg
# middle leg
# hind leg
bodyLen = np.array([[0.3, 1.3775, 1.0120, 1.2310],
                    [0.3, 1.3848, 1.1580, 1.3562],
                    [0.3, 2.2705, 1.9163, 2.1075],
                    [0.3, 1.3775, 1.0120, 1.2310],
                    [0.3, 1.3848, 1.1580, 1.3562],
                    [0.3, 2.2705, 1.9163, 2.1075]])

# triangle template
# unit: mm
# each row: x, y, z
# each column: L1/L2/L3/R1/R2/R3
templateTri = np.array([[0.973, 0, 2.625],
                       [2.714, 0, -0.105],
                       [1.746, 0, -2.520],
                       [-0.973, 0, 2.625],
                       [-2.714, 0, -0.105],
                       [-1.746, 0, -2.520]])

# offset array
# unit: mm
# each row: x, y, z
# each column: L1/L2/L3/R1/R2/R3
offsetArray = np.array([[0.5, 0.0, 0.6],
                        [0.0, 0.0, 0.6],
                        [-0.5,0.0,  0.6],
                        [0.5, 0.0, -0.6],
                        [0.0, 0.0, -0.6],
                        [-0.5,0.0,  -0.6]])

# read the CPG parameters
# unit: phase - radian, amp - ratio with no unit, offset - radian
# param_cpg = np.loadtxt('param/operators.txt')

# read the PD parameters
# unit: kp - N m/radian,  kd - N m s/radian
# param_pd = np.loadtxt('param/pd.txt')

# Parameters used in the optimisation
# mass of character. unit: kg
mass = 0.001

# COM height. unit: mm
height = 2

# period for a cycle for median velocity 20mm/s. unit: second
period = 1/4

# torque threshold. unit: Nxm
torqueThreshold = 0.000001
# deviation threshold: unit (y/z): mm. phi - radian
deviationThreshold = {'y':1, 'z':0.5, 'phi':1.04}

####################################################
# constants used in the relationship of triangle-speed
# unit: mm
con_so = 3
# unit: s
con_as = 0.1

# unit: mm/kg
a_com = 0.1

# Triangle-load
loadOffset = np.array([[-0.28, 0.0, 0.33],
                       [-0.30, 0.0, 0.0],
                       [-0.60, 0.0, -0.64],
                       [0.28, 0.0, 0.33],
                       [0.30, 0.0, 0.0],
                       [0.60, 0.0, -0.64]])

####################################################
# total simulation time. unit: second
# When optimizing the clut, set tf to 1/4 seconds (one full stride)
tf = 2
# maximum distance. unit: mm
xmax = 100
# time span for per frame. unit: second
dt = 1/24
# targe velocity of CPG. unit: mm/s
vcpg = 20

####################################################
a_com = a_com*5
loadOffset[:, 0] = -loadOffset[:, 0]

####################################################

legArray = ['frontLeft', 'middleLeft', 'backLeft', 'frontRight', 'middleRight', 'backRight']

legJoints_PEP = []
legJoints_AEP = []

####################################################
# Constants used in the stepEngine module

# spatial probability. unit: mm
con_stride = 5
con_ae = 5

# phase probability. unit: radian
con_phase = mt.pi/4

# neighbour probability. unit: mm
con_dc = 0.5

# load probability. unit: N
con_FL = 0.005

####################################################


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import glob
import logging

logger = logging.getLogger(__name__)

class Processor(object):
    """
    Represents a processor that handles a part of a release.
    """

    def __init__(self, fs):
        """
        Initialise a new processor instance.

        :param fs: A Transferer instance to use to execute filesystem
                     operations.
        """
        self._fs = fs

    @staticmethod
    def _find_entry_by_suffix(directory, suffix):
        """
        Find a file or directory with a suffix within a directory.

        :param directory: The directory to search within.
        :param suffix: The file or directory suffix.
        :return: The entry path if found.
        :raises IOError: If there is not exactly 1 matching entry.
        """
        matches = glob.glob('{0}/*{1}'.format(directory, suffix))
        if len(matches) != 1:
            raise IOError(
                'Failed to identify entry ending with {0} in {1}'.format(
                    suffix, directory))
        return matches[0]

    @staticmethod
    def _find_file_by_extension(directory, extension):
        """
        Find the file with an extension in a directory.

        :param directory: The directory in which to look for the file.
        :param extension: The extension of the file.
        :return: The file path if found.
        :raises IOError: If there is not exactly 1 matching file.
        """
        path = Processor._find_entry_by_suffix(directory, '.' + extension)
        if not os.path.isfile(path):
            raise IOError('Found entry {0} is not a file'.format(path))
        return path


import torch
import os
import numpy as np
import librosa
import random
from torch.utils.data import Dataset,DataLoader
import torchvision.transforms as transforms
from PIL import Image
import pandas as pd
from encoder.audio import preprocess_wav
from encoder import inference as encoder
from pathlib import Path

enc_model_fpath = Path("E:/FR-PSS/encoder/encoder.pt")
encoder.load_model(enc_model_fpath)

class Data_ganerator(Dataset):
    def __init__(self,txt_file):
        with open(txt_file, 'r') as f:
            self.all_triplets = f.readlines()
        self.all_triplets = self.all_triplets[0:]
        print(self.all_triplets)

    def __getitem__(self, item):
        triplet = self.all_triplets[item].split(' ')
        pos_image_dir = triplet[1]
        neg_image_dir = triplet[2]
        voice_dir = triplet[0]
        # print('1',image_dir)
        # print('2',voice_dir)
        pos_image = self.load_image(pos_image_dir)
        neg_image = self.load_image(neg_image_dir)
        voice = self.load_voice(voice_dir)
        return voice,pos_image,neg_image

    def __len__(self):

        return len(self.all_triplets)

    def load_image(self,image_dir):
        image = Image.open(image_dir).convert('RGB')
        if image.size != (224, 224):
            image = image.resize((224, 224), resample=Image.BILINEAR)
        image = np.array(image, dtype=np.float32)
        image = image * 2 / 255 -1
        # # crop & resize
        # image = np.array(image,dtype=np.float32)
        image = image.transpose(2,0,1)
        # image = image * 2 / 255 -1
        image = torch.from_numpy(image)
        return image

    def load_voice(sele,voice_dir):
        original_wav, sampling_rate = librosa.load(voice_dir)
        preprocessed_wav = preprocess_wav(original_wav, sampling_rate)
        voice_embed = encoder.embed_utterance(preprocessed_wav)
        return voice_embed

# def custom_collate_fn(batch):
# #     voice = [torch.from_numpy(item[0]) for item in batch]
# #     face = [item[1] for item in batch]
# #     # face = torch.from_numpy(np.array(face,dtype=np.float64))
# #     # voice = torch.from_numpy(np.array(voice,dtype=np.float64))
# #     # print(face.shape)
# #     # print(voice.shape)
# #     voice = torch.stack(voice, dim=0)
# #     # face = torch.stack(face, dim=0)
# #
# #     return voice,face

# if __name__ == '__main__':
#     dataset = Data_ganerator('D:/BaiduNetdiskDownload/FV_dataset/train.txt')
#     loader = DataLoader(dataset,batch_size=2,shuffle=True,drop_last=True,num_workers=2)
#     for step, (voice,pos_face,neg_face) in enumerate(loader):
#         #print(voice)
#         print(pos_face.shape)
#         print(neg_face.shape)
#         print(voice.shape)


import math

def abcd(x, y):
    global n1, n2
    while n1 > 1 and n2 > 1:
        n1 = int(math.floor(len(str(x))/2.0))
        n2 = int(math.floor(len(str(y))/2.0))
        a = int(str(x)[:n1])
        b = int(str(x)[n1:])
        c = int(str(y)[:n2])
        d = int(str(y)[n2:])
        ac = abcd(a, c)
        ad = abcd(a, d)
        bc = abcd(b, c)
        bd = abcd(b, d)

    else:
        n1 = int(math.ceil(len(str(x)) / 2.0))
        m1 = len(str(x)) - n1
        n2 = int(math.ceil(len(str(y)) / 2.0))
        m2 = len(str(y)) - n2
        try:
            a = int(str(x)[:n1])
        except:
            a = 0
        try:
            b = int(str(x)[n1:])
        except:
            b = 0
        try:
            c = int(str(y)[:n2])
        except:
            c = 0
        try:
            d = int(str(y)[n2:])
        except:
            d = 0
        ac = a * c
        ad = a * d
        bc = b * c
        bd = b * d
        x_times_y = 10 ** (m1 + m2) * ac + 10 ** m1 * ad + 10 ** m2 * bc + bd
        return x_times_y

while True:
    x = input("Input x: ")
    y = input("Input y: ")
    n1 = int(math.floor(len(str(x)) / 2.0))
    n2 = int(math.floor(len(str(y)) / 2.0))
    print(abcd(x, y))
    print("Double check: ")
    print(int(x) * int(y))


"""
Exercise 1: Write a program which repeatedly reads numbers until the user enters “done”.
Once “done” is entered, print out the total, count, and average of the numbers.
If the user enters anything other than a number,
detect their mistake using try and except and print an error message and skip to the next number.
"""

def main():
    """main function to output result"""
    num_list = []
    while True:
        number = input("Enter a number: ")
        if number == 'done':
            print (f"{sum(num_list):.0f}, {len(num_list)}, {sum(num_list)/len(num_list)}")
            break
        try:
            number = float(number)
            num_list.append(number)
        except: # pylint: disable=bare-except
            print ("Invalid input")

if __name__ == '__main__':
    main()


from softqlearning.algorithms.sql import SQL
from softqlearning.misc.kernel import adaptive_isotropic_gaussian_kernel
from softqlearning.replay_buffers.simple_replay_buffer import SimpleReplayBuffer
from softqlearning.value_functions.value_function import NNQFunction
from softqlearning.policies.stochastic_policy import StochasticNNPolicy
from softqlearning.misc.sampler import SimpleSampler
from softqlearning.environment.space_robot_3link import SpaceRobot3link
# from softqlearning.environment.space_robot_7links import SpaceRobot3link
# from softqlearning.environment.space_robot_double_3links import SpaceRobot3link

from experiment.hyper_parameters import SHARED_PARAMS, ENV_PARAMS

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

env = SpaceRobot3link()

pool = SimpleReplayBuffer(
    env_spec=env.spec, max_replay_buffer_size=SHARED_PARAMS['max_pool_size'])

sampler = SimpleSampler(
    max_path_length=ENV_PARAMS['max_path_length'],
    min_pool_size=SHARED_PARAMS['min_pool_size'],
    batch_size=SHARED_PARAMS['batch_size'])

base_kwargs = dict(
    epoch_length=SHARED_PARAMS['epoch_length'],
    n_epochs=ENV_PARAMS['n_epochs'],
    n_train_repeat=SHARED_PARAMS['n_train_repeat'],
    eval_render=False,
    eval_n_episodes=1,
    sampler=sampler)

qf = NNQFunction(env_spec=env.spec, hidden_layer_sizes=SHARED_PARAMS['Q_layer_size'])

policy = StochasticNNPolicy(env_spec=env.spec, hidden_layer_sizes=SHARED_PARAMS['policy_layer_size'],
                            squash=ENV_PARAMS['squash'])

algorithm = SQL(
    base_kwargs=base_kwargs,    env=env,
    pool=pool,
    qf=qf,
    policy=policy,
    kernel_fn=adaptive_isotropic_gaussian_kernel,
    kernel_n_particles=SHARED_PARAMS['kernel_particles'],
    kernel_update_ratio=SHARED_PARAMS['kernel_update_ratio'],
    value_n_particles=SHARED_PARAMS['value_n_particles'],
    td_target_update_interval=SHARED_PARAMS['td_target_update_interval'],
    qf_lr=SHARED_PARAMS['qf_lr'],
    policy_lr=SHARED_PARAMS['policy_lr'],
    discount=SHARED_PARAMS['discount'],
    reward_scale=ENV_PARAMS['reward_scale'],
    save_full_state=False)

load_path = SHARED_PARAMS['model_save_path'] + 'stage1' + '/model-500.ckpt'
algorithm.train(load=load_path)


# Plot a single picture

# imports
import matplotlib.pylab as plt
import numpy as np

# initial size of plot window
plt.rcParams['figure.figsize'] = 20, 12

# input file
#filename = 'MD.data'
#data = np.loadtxt(filename)

t01= np.load('time_tau_T=0.1.data.npy')
T01= np.load('Temp_tau_T=0.1.data.npy')
t001= np.load('time_tau_T=0.01.data.npy')
T001= np.load('Temp_tau_T=0.01.data.npy')
t0001= np.load('time_tau_T=0.001.data.npy')
T0001= np.load('Temp_tau_T=0.001.data.npy')

# plot
plt.plot(t01, T01,'-',label='tau = 0.1 ps')
plt.plot(t001, T001-200,'--',label='tau = 0.01 ps')
plt.plot(t0001, T0001-400,'-.',label='tau = 0.001 ps')

# labels
plt.xlabel('Time [ps]', fontsize=20)
plt.ylabel('Temperature [K]', fontsize=20)

# title
plt.title('Temperature regulation')

# tick fontsize
plt.xticks(fontsize=10)
plt.yticks(fontsize=10)

# legend
plt.legend()
leg = plt.gca().get_legend()
ltext  = leg.get_texts()
plt.setp(ltext, fontsize=30)

# display the plot
plt.show()