starting_points = 301
current_points = starting_points
total_success_shots = 0
total_fail_shots = 0
name = input()
command = input()
is_winning = False
is_retired = False

while command != "Retire":
    section = command
    points = int(input())
    if section == "Single":
        points = points
    elif section == "Double":
        points = points * 2
    elif section == "Triple":
        points = points * 3
    total_success_shots += 1
    previous_points = current_points
    current_points -= points
    if current_points == 0:
        is_winning = True
        break
    elif current_points < 0:
        current_points = previous_points
        total_fail_shots += 1
        total_success_shots -= 1
    command = input()
    if command == "Retire":
        is_retired = True
if is_winning:
    print(f"{name} won the leg with {total_success_shots} shots.")
if is_retired:
    print(f"{name} retired after {total_fail_shots} unsuccessful shots.")


from spheres.magic import *
from functools import *

class OperatorExpression:
	def __init__(self, ops):
		self.ops = ops

	def __mul__(self, other):
		if type(other) == OperatorExpression:
			return OperatorExpression(self.ops+other.ops)
		elif type(other) == qObj and other.type == "oper":
			return OperatorExpression(self.ops+[other])
		else:
			return self.reduced()*other

	def __rmul__(self, other):
		if type(other) == OperatorExpression:
			return OperatorExpression(other.ops+self.ops)
		elif type(other) == qObj and other.type == "oper":
			return OperatorExpression([other]+self.ops)
		else:
			return other*self.reduced()

	def reduced(self, qua=False):
		r = reduce(lambda x, y: x*y, [op.qua() for op in self.ops])
		return r if qua else qObj(r.full())

	def __repr__(self):
		return str(self.ops)

class qObj(qt.Qobj):
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.name = ""

	def qua(self):
		return qt.Qobj(self.full())

	def __mul__(self, other):
		if self.type == "bra":
			if type(other) == OperatorExpression:
				return qObj(self.qua()*other.reduced(qua=True))
			elif type(other) == qObj and other.type == "oper":
				return qObj(self.qua()*other.qua())
			else:
				return qObj(super().__mul__(other).full())
		elif self.type == "oper":
			if type(other) == OperatorExpression:
				return OperatorExpression([self]+other.ops)
			elif type(other) == qObj and other.type == "oper":
				return OperatorExpression([self, other])
			else:
				return qObj(super().__mul__(other).full())
		else:
			raise Exception()

	def __rmul__(self, other):
		if self.type == "ket":
			if type(other) == OperatorExpression:
				return qObj(other.reduced(qua=True), self.qua())
			elif type(other) == qObj and other.type == "oper":
				return qObj(other.qua(), self.qua())
			else:
				return qObj(super().__rmul__(other).full())
		elif self.type == "oper":
			if type(other) == OperatorExpression:
				return OperatorExpression(other.ops+[self])
			elif type(other) == qObj and other.type == "oper":
				return OperatorExpression([other, self])
			else:
				return qObj(super().__rmul__(other).full())
		else:
			raise Exception()

	def dag(self):
		return qObj(super().dag().full())

	def __repr__(self):
		if self.name == "":
			return super().__repr__()
		return self.name

v = qObj(qt.rand_ket(2).full())
a, b, DM, c, d = [qObj(qt.rand_herm(2).full()) for i in range(5)]
v.name = "v"
a.name = "a"
b.name = "b"
c.name = "c"
d.name = "d"
DM.name = "DM"
v2 = v.qua()
a2, b2, DM2, c2, d2 = a.qua(), b.qua(), DM.qua(), c.qua(), d.qua()
#DM << (a*b*DM*c*d)


import tensorflow as tf
import numpy as np

# binary logic functions that support per-element operations between numpy
# nd arrays.
xor_fn = np.vectorize(lambda x, y: x != y)
nand_fn = np.vectorize(lambda x, y: not (x and y))
and_fn = np.vectorize(lambda x, y: x and y)
or_fn = np.vectorize(lambda x, y: x or y)

def sample_logic_fn(f, samples=10000):
    """ Takes a vectorized function that takes two binary input values and
    generates labeled data for use in training or evaluating classifiers.
    """
    inputs = np.random.randint(2, size=(samples, 2))
    outputs = f(inputs[:,0], inputs[:,1])
    labels = np.transpose(np.vstack((outputs, outputs==False)))
    return inputs.astype(np.float32), labels.astype(np.float32)

def nn_model(n_input, n_classes, hiddens=[]):
    """ Construct a layer map that consists of a list of TensorFlow variables
    (Tensors) representing the weights and biases from each layer to the next
    layer defined by the input data, the number of output labels (output layer
    corresponds to one-hot vector encodings for classes), and an ordered count
    of neurons in hidden layers.
    """
    layer_map = []
    connections = [n_input] + hiddens + [n_classes]
    for n1, n2 in zip(connections[:-1], connections[1:]):
        weights = tf.Variable(tf.truncated_normal([n1, n2]))
        biases = tf.Variable(tf.zeros([n2]))
        layer_map.append((weights, biases))
    return layer_map

def feed_forward(layer_map, data):
    """ Use a layer_map returned by nn_model and use a reduce-like composition
    model to construct the TensorFlow data flow graph that specifies the matrix
    multiplications that calculates the response for each neuron in each layer
    from the response of all connected neurons in the previous layer plus the
    biases and with the rectified linear activation function.
    """
    accum = data
    for l in layer_map[:-1]:
        accum = tf.nn.relu(tf.matmul(accum, l[0]) + l[1])
    return tf.matmul(accum, layer_map[-1][0]) + layer_map[-1][1]

def accuracy(preds, labels):
    """ Return the mean error of the difference between one hot encoded
    labels and softmax neural network output probabilities.
    """
    return np.mean(np.argmax(preds,1) == np.argmax(labels,1))

def fit_nnet(train_data, train_labels, hiddens=[], n_steps=1000,
             lrate=0.01, valid_data=None, valid_labels=None, test_data=None,
             test_labels=None):
    """ Construct a neural net data flow graph in TensorFlow and use it to learn
    weights that fit the train_data to the train_labels.
    """

    # matrix dimension influencing variables
    n_samples, input_dims = np.shape(train_data)
    n_labels = np.shape(train_labels)[-1]

    # build up TensorFlow data flow graph by initializing variables and
    # placeholders and composing functions.
    graph = tf.Graph()
    with graph.as_default():
        tf_train_data = tf.Variable(train_data)
        tf_train_labels = tf.Variable(train_labels)

        # build layer stack then build tf dataflow graph implied by feed_forward
        model = nn_model(input_dims, n_labels, hiddens=hiddens)
        pred = feed_forward(model, tf_train_data)

        # use log distance of labels from predictions as our cost
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits(pred, tf_train_labels)
        cost_fn = tf.reduce_mean(cross_entropy)

        # use gradient descent as our optimizer
        opt = tf.train.GradientDescentOptimizer(lrate).minimize(cost_fn)

        # determine predictions for training data
        train_pred = tf.nn.softmax(pred)

        # set up variables for and calculate predictions for validation data
        # and test data if provided
        if valid_data is not None:
            tf_valid_data = tf.constant(valid_data)
            tf_test_data = tf.constant(test_data)
        if test_data is not None:
            valid_pred = tf.nn.softmax(feed_forward(model, tf_valid_data))
            test_pred = tf.nn.softmax(feed_forward(model, tf_test_data))

    with tf.Session(graph=graph) as session:
        tf.initialize_all_variables().run()
        for step in range(n_steps):
            _, cost_y, preds = session.run([opt, cost_fn, train_pred])
            if (step % 200) == 0:
                print("Cost function value as of step %d: %f"\
                    % (step, cost_y))
                print("Accuracy for training dataset: %.3f"\
                    % accuracy(preds, train_labels))
                if valid_data is not None:
                    print("Validation accuracy estimate: %.3f"\
                        % accuracy(valid_pred.eval(), valid_labels))
        if test_data is not None:
            print("Test accuracy after training complete: %.3f"\
                % accuracy(test_pred.eval(), test_labels))

if __name__ == "__main__":
    # we can get 100% on any of these with just a bit of training
    for l_fn in [and_fn, or_fn, nand_fn, xor_fn]:
        train_data, train_labels = sample_logic_fn(l_fn)
        valid_data, valid_labels = sample_logic_fn(l_fn, 1000)
        test_data, test_labels = sample_logic_fn(l_fn, 1000)
        fit_nnet(train_data, train_labels, hiddens=[3], n_steps=2000,
                lrate=0.75, valid_data=valid_data, valid_labels=valid_labels,
                test_data=test_data, test_labels=test_labels)


import libpysal as lps
import geopandas as gpd
import csv

state = "ok"
file = ("./ok_boundary.json")
shp = gpd.read_file(file)

rW = lps.weights.Rook.from_dataframe(shp, idVariable="GEOID")

outputName = state + "_neighbors.csv"
header = ['id','NEIGHBORS']

with open(outputName, 'w', newline='') as csv_out:
    writeCSV = csv.writer(csv_out, delimiter=',')
    writeCSV.writerow(header)
    for row in rW:
        id = row[0]
        neighbors = row[1]
        neighborIDs = list(neighbors.keys())
        n = []
        for i in neighborIDs:
                n.append(i)
        neighborString = ",".join(n)
        writeCSV.writerow([row[0], neighborString])
csv_out.close()


import unittest

import mock
import networkx

from kiva.testing import KivaTestAssistant

from graphcanvas.graph_container import GraphContainer
from graphcanvas.graph_node_component import GraphNodeComponent
from graphcanvas.graph_view import graph_from_dict

class TestGraphContainer(KivaTestAssistant, unittest.TestCase):
    def create_graph_container(self):
        """ Utility method to generate a GraphContainer with a simple graph for
            re-use in several tests herein.
        """
        d = {'a': ['b'], 'b': ['c', 'd'], 'c': [], 'd': []}
        g = graph_from_dict(d)
        container = GraphContainer(graph=g)
        for node in g.nodes():
            GraphNodeComponent(container=container, value=node)
        return container

    def assert_in_bounds(self, container):
        """ Utility method for asserting that all components are contained
            within the bounds of the container.
        """
        upper_x, upper_y = container.bounds
        lower_x, lower_y = 0, 0
        for component in container.components:
            self.assertGreaterEqual(upper_x, component.x)
            self.assertGreaterEqual(component.x, lower_x)
            self.assertGreaterEqual(upper_y, component.y)
            self.assertGreaterEqual(component.y, lower_y)

    def test_no_layout_needed(self):
        container = self.create_graph_container()
        container._graph_layout_needed = False
        result = container.do_layout()
        self.assertIsNone(result)

    def test_no_nodes(self):
        container = GraphContainer(graph=graph_from_dict({}))
        self.assertTrue(container.components == [])
        result = container.do_layout()
        self.assertIsNone(result)

    def test_do_layout(self):
        container = self.create_graph_container()
        # test spring layout
        container.style = 'spring'
        self.assertTrue(container._graph_layout_needed)
        container.do_layout()
        self.assert_in_bounds(container)
        self.assertFalse(container._graph_layout_needed)

        # test tree layout
        container = self.create_graph_container()
        container.style = 'tree'
        self.assertTrue(container._graph_layout_needed)
        container.do_layout()
        self.assert_in_bounds(container)
        self.assertFalse(container._graph_layout_needed)

        # test shell layout
        container = self.create_graph_container()
        container.style = 'shell'
        self.assertTrue(container._graph_layout_needed)
        container.do_layout()
        self.assert_in_bounds(container)
        self.assertFalse(container._graph_layout_needed)

        # test spectral layout
        container = self.create_graph_container()
        container.style = 'spectral'
        self.assertTrue(container._graph_layout_needed)
        container.do_layout()
        self.assert_in_bounds(container)
        self.assertFalse(container._graph_layout_needed)

        # test circular layout
        g = networkx.balanced_tree(3, 5)
        container = GraphContainer(graph=g)
        for node in g.nodes():
            GraphNodeComponent(container=container, value=node)
        container.style = 'circular'
        self.assertTrue(container._graph_layout_needed)
        container.do_layout()
        self.assert_in_bounds(container)
        self.assertFalse(container._graph_layout_needed)

    def test_draw(self):
        container = self.create_graph_container()
        self.assertPathsAreCreated(container)

    def test_draw_directed_arrow_direction(self):
        d = {'a': ['b'], 'b': []}
        g = graph_from_dict(d)
        container = GraphContainer(graph=g)
        for node in g.nodes():
            GraphNodeComponent(container=container, value=node)

        # Node a is to the left of node b
        container._layout_needed = False
        container.components[0].x = 0.0
        container.components[1].x = 100.0
        container.components[0].y = 0.0
        container.components[1].y = 0.0
        self.assertPathsAreCreated(container)

        # Node a is to the right of node b
        container._layout_needed = False
        container.components[0].x = 100.0
        container.components[1].x = 0.0
        container.components[0].y = 0.0
        container.components[1].y = 0.0
        self.assertPathsAreCreated(container)

        # Node a is above of node b
        container._layout_needed = False
        container.components[0].x = 0.0
        container.components[1].x = 0.0
        container.components[0].y = 0.0
        container.components[1].y = 100.0
        self.assertPathsAreCreated(container)

        # Node a is below of node b
        container._layout_needed = False
        container.components[0].x = 0.0
        container.components[1].x = 0.0
        container.components[0].y = 100.0
        container.components[1].y = 0.0
        self.assertPathsAreCreated(container)

    def test_draw_no_layout(self):
        container = self.create_graph_container()
        container._layout_needed = False
        self.assertPathsAreCreated(container)

    def test_draw_not_directed(self):
        d = {'a': ['b'], 'b': ['c', 'd'], 'c': [], 'd': []}
        g = graph_from_dict(d)
        g = g.to_undirected()
        container = GraphContainer(graph=g)
        for node in g.nodes():
            GraphNodeComponent(container=container, value=node)
        self.assertPathsAreCreated(container)

    def test_draw_single_node(self):
        g = networkx.DiGraph()
        g.add_node('a')
        container = GraphContainer(graph=g)
        for node in g.nodes():
            GraphNodeComponent(container=container, value=node)
        self.assertPathsAreCreated(container)

    def test_weighted(self):
        g = networkx.Graph()
        g.add_edge('a', 'b', weight=0.6)
        g.add_edge('a', 'c', weight=0.2)
        g.add_edge('c', 'd', weight=0.1)
        g.add_edge('c', 'e', weight=0.7)
        g.add_edge('c', 'f', weight=0.9)
        g.add_edge('a', 'd', weight=0.3)
        container = GraphContainer(graph=g)
        for node in g.nodes():
            GraphNodeComponent(container=container, value=node)
        self.assertPathsAreCreated(container)

    def test_spring_layout_with_non_zero_initial_positions(self):
        container = self.create_graph_container()
        for component in container.components:
            component.position = [1.0, 2.0]
        container.style = 'spring'
        self.assertTrue(container._graph_layout_needed)
        container.do_layout()
        self.assert_in_bounds(container)
        self.assertFalse(container._graph_layout_needed)

    @mock.patch('graphcanvas.graph_container.tree_layout')
    @mock.patch('networkx.drawing.nx_agraph.pygraphviz_layout')
    def test_no_pygraphviz_tree(self,
                                mock_pygraphviz_layout,
                                mock_tree_layout):
        mock_pygraphviz_layout.side_effect = ImportError()
        container = self.create_graph_container()
        mock_tree_layout.return_value = {
            node: (0, 0) for node in container.graph.nodes()
        }
        container.style = 'tree'
        container.do_layout()
        self.assertFalse(container._graph_layout_needed)
        mock_pygraphviz_layout.assert_called_once_with(
            container.graph, prog='dot'
        )
        mock_tree_layout.assert_called_once_with(container.graph)

    @mock.patch('networkx.circular_layout')
    @mock.patch('networkx.drawing.nx_agraph.pygraphviz_layout')
    def test_no_pygraphviz_circular(self,
                                    mock_pygraphviz_layout,
                                    mock_circular_layout):
        mock_pygraphviz_layout.side_effect = ImportError()
        container = self.create_graph_container()
        container.style = 'circular'
        container.do_layout()
        self.assertFalse(container._graph_layout_needed)
        mock_pygraphviz_layout.assert_called_once_with(
            container.graph, prog='twopi'
        )
        mock_circular_layout.assert_called_once_with(
            container.graph,
            center=[bound // 2 for bound in container.bounds],
            scale=min(container.bounds) // 2,
        )

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


# 과목의 수강생 번호 1~ N번
# 제출하지 않은 사람의 번호를 오름차순으로 출력하는 프로그램을 작성하라.
# set?

# 첫 번째 줄에는 수강생의 수를 나타내는 정수와 과제를 제출한 사람의수
# 두 번째는 과제를 제출한 사람의 번호
import sys
sys.stdin = open('input.txt', 'r')

T = int(input())

for t in range(1, T+1):
    student_num, submit  = list(map(int, input().split())) # 5 2
    submit_num = list(map(int, input().split())) # 2 5 3
    # 전체 학생 수
    student = [k for k in range(1, student_num+1)]

    for j in submit_num:
        if j in student:
            student.remove(j)

    students = list(map(str, student)) # int -> str
    ans = ' '.join(students)
    print(f'#{t} {ans}')


from typing import List, Any

from sqlalchemy.orm import Session

from api import schemas, models, crud
from api.votes import schemas as votes_schemas

def get_votes_from_game_id(db: Session, game_id: int) -> List[Any]:
    return db.query(models.Vote).filter(models.Vote.game_id == game_id).all()

def add_vote(db: Session, game_id: int, vote: votes_schemas.VoteCreate) -> models.Vote:
    db_game = crud.games.get_game_by_id(db, game_id)
    db_vote = models.Vote(
        vote_from = vote.vote_from,
        vote_to = vote.vote_to,
        game_id = game_id,
        day = db_game.current_day,
        vote_type = vote.vote_type.value
    )
    db.add(db_vote)
    db.commit()
    db.refresh(db_vote)
    return db_vote


from spack import *
from spack.pkg.builtin.amr_wind import AmrWind

class AmrWind(AmrWind):
    git      = "https://github.com/Alpine-DAV/amr-wind.git"
    version('ascent', branch='ascent', submodules=True)

    # draft of changes needed to build amr-wind+ascent
    variant('ascent', default=False,
            description='Build amr-wind coupled with ascent')
    depends_on('ascent', when='+ascent')

    def cmake_args(self):
        # Grab cmake args from builtin warpx package
        args = super(AmrWind, self).cmake_args()

        if '+ascent' in self.spec:
            args += [
                self.define('AMR_WIND_ENABLE_ASCENT', True),
                self.define('ASCENT_DIR',self.spec['ascent'].prefix)
            ]

        return args


#!/usr/bin/python3
""" Module: 4-print_square
Contain function print_square that print a square with # char

    Testing: use tests/4-print_square.txt with doctest()
"""

def print_square(size):
    """Prints the square with # char
    Arg:
        size (int): size of the square
    """
    if isinstance(size, int):
        if size < 0:
            raise ValueError("size must be >= 0")
    else:
        raise TypeError("size must be an integer")
    if size == 0:
        print("", end="")
    else:
        for row in range(size):
            print("#" * size)


num=input("enter multiple with space number:")
spli=num.split()
'''ans=",".join(spli)
print(ans)
'''
tab=" "
count=0
for word in spli:
    count=count+1
    tab=tab+word
    if(count<len(spli)):
       tab=tab+"-"
print(tab)


from torch.utils import data
from get_data import get_data
import torch

BATCH_SIZE = 4

[items, attributes, df] = get_data()

NUM_ITEMS = len(items)
NUM_ATTRIBUTES = len(attributes)

features = torch.tensor(to_categorical(range(NUM_ITEMS)), dtype=torch.float32)
targets = torch.tensor(df.values, dtype=torch.float32)

class Dataset(data.Dataset):
    "Construct a PyTorch Dataset & Dataloader to automate batching & shuffling"

    def __init__(self, features, targets):
        self.features = features
        self.targets = targets

        if len(targets) != len(features):
            raise ValueError("Length of features and targets vectors are different")

        self.n_samples = len(targets)

    def __len__(self):
        return self.n_samples

    def __getitem__(self, index):
        return (self.features[index], self.targets[index])

dataset = Dataset(features, targets)
dataloader = data.DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)


import tkinter as tk
from tkinter import ttk, messagebox
from constants import BACKGROUND, DATA_BASE, LABEL_FONT, PHOTO_DEFAULT, TITLE_FONT
from global_functions import add_image, run_sql, transform_image

class MaterialView(tk.Frame):
    def __init__(self, window):
        tk.Frame.__init__(self, window, bg=BACKGROUND)
        self.type_values = []   # valors que apareixen al combobox type
        self.mark_values = []   # valors que apareixen al combobox mark
        self.name_database = DATA_BASE
        self.width_photo = 120
        self.height_photo = 120
        self.path_img = PHOTO_DEFAULT
        self.default_img = transform_image(PHOTO_DEFAULT, self.width_photo, self.height_photo)
        self.img_photo = self.default_img
        # Widgets
        self.title = tk.Label(self, text="Material d'escalada", font=TITLE_FONT, bg=self.cget("bg"))
        self.frame_data = tk.Frame(self, bg=self.cget("bg"))
        self.lb_type = tk.Label(self.frame_data, text="Tipus: ", font=LABEL_FONT, bg=self.cget("bg"))
        self.txt_type = ttk.Combobox(self.frame_data, width=25)
        self.lb_mark = tk.Label(self.frame_data, text="Marca: ", font=LABEL_FONT, bg=self.cget("bg"))
        self.txt_mark = ttk.Combobox(self.frame_data, width=25)
        self.lb_model = tk.Label(self.frame_data, text="Model: ", font=LABEL_FONT, bg=self.cget("bg"))
        self.txt_model = tk.Entry(self.frame_data, width=27, relief="flat", bd=0)
        self.lb_photo = tk.Label(self.frame_data, text="Fotografía: ", font=LABEL_FONT, bg=self.cget("bg"))
        self.txt_photo = tk.Label(self.frame_data, image=self.default_img)
        self.txt_photo.bind("<Double Button 1>", self.add_images)
        self.lb_comments = tk.Label(self.frame_data, text="Observacions: ", font=LABEL_FONT, bg=self.cget("bg"))
        self.txt_comments = tk.Text(self.frame_data, relief="flat", bd=0, height=5, width=75)
        self.frame_buttons = tk.Frame(self, bg=self.cget("bg"))
        self.bt_add = tk.Button(self.frame_buttons, text="Afegir registre", cursor="hand2",
            command=self.add_register)
        self.bt_update = tk.Button(self.frame_buttons, text="Actualitzar registre", cursor="hand2",
            state="disabled", command=self.update_register)
        self.bt_delete = tk.Button(self.frame_buttons, text="Eliminar registre", cursor="hand2",
            state="disabled", command=self.delete_register)
        self.bt_erase = tk.Button(self.frame_buttons, text="Esborrar camps", cursor="hand2",
            command=lambda:self.delete_fields(True))
        self.frame_list = tk.Frame(self, bg=self.cget("bg"))
        self.scroll_list = ttk.Scrollbar(self.frame_list, orient="vertical")
        self.material_list = ttk.Treeview(self.frame_list, columns=("type", "mark", "model"),
            yscrollcommand=self.scroll_list.set)
        self.material_list.heading("#0", text="ID")
        self.material_list.heading("type", text="Tipus")
        self.material_list.heading("mark", text="Marca")
        self.material_list.heading("model", text="Model")
        self.material_list.column("#0", width=56, minwidth=50, anchor="w")
        self.material_list.column("type", width=178, minwidth=178, anchor="center")
        self.material_list.column("mark", width=178, minwidth=178, anchor="center")
        self.material_list.column("model", width=178, minwidth=178, anchor="center")
        self.material_list.bind("<Double Button 1>", self.select_material)
        self.scroll_list.config(command=self.material_list.yview)
        self.draw()
        self.create_table()

    def draw(self):
        self.title.pack(fill=tk.X, padx=10)
        # data
        self.frame_data.pack(fill=tk.X)
        self.lb_type.grid(row=0, column=0, padx=(20, 0), pady=(10, 0), sticky="e")
        self.txt_type.grid(row=0, column=1, padx=(0, 10), pady=(10, 0))
        self.lb_mark.grid(row=1, column=0, padx=(20, 0), pady=(10, 0), sticky="e")
        self.txt_mark.grid(row=1, column=1, padx=(0, 10), pady=(10, 0))
        self.lb_model.grid(row=2, column=0, padx=(20, 0), pady=(10, 0), sticky="e")
        self.txt_model.grid(row=2, column=1, padx=(0, 10), pady=(10, 0))
        self.lb_photo.grid(row=0, column=2, padx=(100, 0), pady=(10, 0))
        self.txt_photo.grid(row=0, column=3, rowspan=4, padx=(0, 20), pady=(10, 0))
        self.lb_comments.grid(row=3, column=0, columnspan=2, padx=20, pady=(10, 0), sticky="w")
        self.txt_comments.grid(row=4, column=0, columnspan=4, padx=10, pady=(0, 10))
        # buttons
        self.frame_buttons.pack(fill=tk.X)
        self.bt_add.grid(row=0, column=0, padx=(25, 10), pady=10)
        self.bt_update.grid(row=0, column=1, padx=10, pady=10)
        self.bt_delete.grid(row=0, column=2, padx=10, pady=10)
        self.bt_erase.grid(row=0, column=3, padx=(10, 20), pady=10)
        # material list
        self.frame_list.pack(fill=tk.X)
        self.material_list.pack(side="left", fill="both", padx=(20, 0), pady=10)
        self.scroll_list.pack(side="right", fill=tk.Y, padx=(0, 20), pady=10)

    def create_table(self):
        query = """CREATE TABLE IF NOT EXISTS MATERIAL (ID INTEGER PRIMARY KEY, TIPUS TEXT, MARCA TEXT,
        MODEL TEXT, FOTO TEXT, COMENTARIS TEXT)"""
        run_sql(self.name_database, query)
        self.counter_ids()
        self.delete_material_list()
        self.filling_material_list()
        self.add_values()

    def check_fields(self):
        if self.txt_type.get() != "" and self.txt_mark.get() != "" and self.txt_model.get() != "":
            return True
        else:
            messagebox.showerror("Error", "Has d'incerir el tipus, la marca i el model obligatoriament.")
            return False

    def counter_ids(self):
        count = 1
        query = "SELECT ID FROM MATERIAL ORDER BY ID"
        data = run_sql(name=self.name_database, query=query, read=True)
        for item in data:
            if item[0] != count:
                break
            count += 1
        return count

    def filling_material_list(self):
        query = "SELECT ID, TIPUS, MARCA, MODEL FROM MATERIAL ORDER BY ID"
        data = run_sql(name=self.name_database, query=query, read=True)
        for item in data:
            text = item[0]
            values = (item[1], item[2], item[3])
            self.material_list.insert("", tk.END, text=text, values=values)

    def delete_material_list(self):
        for item in self.material_list.get_children():
            self.material_list.delete(item)

    def add_values(self):
        query = "SELECT TIPUS, MARCA FROM MATERIAL ORDER BY TIPUS, MARCA"
        data = run_sql(name=self.name_database, query=query, read=True)
        for item in data:
            if item[0] not in self.type_values:
                self.type_values.append(item[0])
            if item[1] not in self.mark_values:
                self.mark_values.append(item[1])
        self.txt_type["values"] = self.type_values
        self.txt_mark["values"] = self.mark_values

    def add_images(self, event):
        self.path_img = add_image()
        if self.path_img:
            self.img_photo = transform_image(self.path_img, self.width_photo, self.height_photo)
            self.txt_photo["image"] = self.img_photo

    def select_material(self, event):
        parameter = (self.material_list.item(self.material_list.selection()[0], "text"), )
        query = "SELECT * FROM MATERIAL WHERE ID=?"
        data = run_sql(name=self.name_database, query=query, parameters=parameter, read=True)
        for item in data:
            self.delete_fields()
            self.txt_type.insert(0, item[1])
            self.txt_mark.insert(0, item[2])
            self.txt_model.insert(0, item[3])
            self.path_img = item[4]
            self.img_photo = transform_image(self.path_img, self.width_photo, self.height_photo)
            self.txt_photo["image"] = self.img_photo
            self.txt_comments.insert(1.0, item[5])
            self.bt_update["state"] = "normal"
            self.bt_delete["state"] = "normal"

    # buttons functions
    def delete_fields(self, button=False):
        self.txt_type.delete(0, tk.END)
        self.txt_mark.delete(0, tk.END)
        self.txt_model.delete(0, tk.END)
        self.txt_comments.delete(1.0, tk.END)
        self.txt_photo["image"] = self.default_img
        self.txt_type.focus()
        self.bt_update["state"] = "disabled"
        self.bt_delete["state"] = "disabled"
        if button:
            self.material_list.selection_remove(self.material_list.selection())

    def add_register(self):
        if self.check_fields():
            query = "INSERT INTO MATERIAL VALUES(?, ?, ?, ?, ?, ?)"
            param = (self.counter_ids(), self.txt_type.get().upper(), self.txt_mark.get().upper(),
                self.txt_model.get().upper(), self.path_img, self.txt_comments.get(1.0, tk.END))
            run_sql(self.name_database, query, param)
            messagebox.showinfo("Afegir registre", "Has afegit un registre correctament.")
            self.delete_fields()
            self.counter_ids()
            self.delete_material_list()
            self.filling_material_list()
            self.add_values()

    def update_register(self):  # falta seleccionar un registre
        if self.check_fields():
            query = "UPDATE MATERIAL SET TIPUS=?, MARCA=?, MODEL=?, FOTO=?, COMENTARIS=? WHERE ID=?"
            param = (self.txt_type.get().upper(), self.txt_mark.get().upper(),
                self.txt_model.get().upper(), self.path_img, self.txt_comments.get(1.0, tk.END),
                self.material_list.item(self.material_list.selection()[0], "text"))
            run_sql(self.name_database, query, param)
            print(self.txt_comments.get(1.0, tk.END))
            messagebox.showinfo("Afegir registre", "Has actualitzat un registre correctament.")
            self.delete_fields()
            self.counter_ids()
            self.delete_material_list()
            self.filling_material_list()
            self.add_values()

    def delete_register(self):
        option = messagebox.askokcancel("Eliminar registre", "Estas segur d'eliminar el registre?")
        if option:
            query = "DELETE FROM MATERIAL WHERE ID=?"
            param = (self.material_list.item(self.material_list.selection()[0], "text"), )
            run_sql(self.name_database, query, param)
            messagebox.showinfo("Eliminar registre", "Has eliminat un registre correctament.")
            self.delete_fields()
            self.counter_ids()
            self.delete_material_list()
            self.filling_material_list()
            self.add_values()


def method1():
    a = [1, 2, 3, 4, 5]
    for _ in range(1):
        f = a[0]
        for j in range(0, len(a) - 1):
            a[j] = a[j + 1]
        a[len(a) - 1] = f
    return a

if __name__ == "__main__":
    """
    from timeit import timeit
    print(timeit(lambda: method1(), number=10000)) 0.008410404003370786
    """


import numpy as np
import time

def encode(str, row):
    start = 0
    end = int(len(str) / row)
    arr = []
    while int(len(str) - row*end) != 0:
            str = str + "+"
            end = int(len(str) / row)

    for i in range(row):
        if end > len(str):
            arr.append(list(str[start:len(str) + 1]))
            break
        arr.append(list(str[start:end]))
        start = end
        end = end + int(len(str)/row)
    encode_str = ""

    for k in range(len(arr[0])):
        for i in range(row):
            encode_str = encode_str + "".join(arr[i][k])
    print(f'encode: {encode_str}')

    for i in range(len(arr)):
        print(f'array: {arr[i]}')

    return arr

def decode(arr, row):

    decode_str = ""
    for i in range(row):
        decode_str = decode_str + ''.join(arr[i])
    print(f'decode: {decode_str.replace("+", "")}')

ans = "BAD"
while ans == "BAD":
    print("Input your string: ")
    str1 = str(input())
    print("Input row:")
    row = int(input())
    if "+" in str1:
        print("Please, input your string without +")
        continue
    encode_arr = encode(str1,row)
    decode_str = decode(encode_arr,row)
    ans = "GOOD"


import time
import sys
import math
from dronekit import connect, VehicleMode, LocationGlobalRelative, Command
from vehicle_additional import get_bearing, get_distance_metres, get_location_metres

from pymavlink import mavutil
from pid import PID
from wingman import Wingman

import argparse
parser = argparse.ArgumentParser(description='双机编队')
parser.add_argument('-v1',
                    help="Vehicle1 connection target string.", nargs='?', const="127.0.0.1:12341", type=str)
parser.add_argument('-v2',
                    help="Vehicle2 connection target string.", nargs='?', const="127.0.0.1:12342", type=str)

parser.add_argument('-vu1',
                     help="Vehicle1 connection target string.")
parser.add_argument('-vu2',
                    help="Vehicle2 connection target string.")

args = parser.parse_args()

if args.vu1 and args.vu2:
    v1 = connect(args.vu1)
    v2 = connect(args.vu2, vehicle_class=Wingman)
else:
    v1 = connect(args.v1)
    v2 = connect(args.v2, vehicle_class=Wingman)

C = 100
drift = 0

pid = PID(0.2, 0.01, 0.1)
pid.target = 0

while True:
    pos = get_location_metres(
        v1.location.global_relative_frame, v1.heading, C + drift, is_bearing=True)

    dt_speed = pid(-1 * (get_distance_metres(
        pos, v2.location.global_relative_frame) - C))

    if dt_speed < 0:
        dt_speed *= 1.5
    v2.set_thr_aspd = v1.airspeed+dt_speed

    print("速度差距", v2.airspeed-v1.airspeed, dt_speed)
    time.sleep(0.2)


# -*- coding: utf-8 -*-
"""
Created on Fri Feb 18 13:40:36 2022

maybe needed:
%load_ext autoreload
%autoreload 2

@author: fabian_balzer
"""

# %%

import argparse

import input_scripts.availability_plots as av
import input_scripts.filter_coverage_plot as fc
import input_scripts.separation_plots as sep
import output_scripts.specz_photz_plots as s_p
import output_scripts.template_analysis_plots as ta
import util.my_tools as mt

def read_args():
    """Reads out the arguments given by the user."""
    parser = argparse.ArgumentParser(
        description="Analyse a variety of files related to the LePhare photo-z process.")
    stem_defaults = {"input": "baseline_input", "separation": "baseline_input",
                     "Filter": "baseline_filters", "output": "new_test", "template": "baseline_templates"}
    for argtype in ["input", "separation", "Filter", "output", "template"]:
        # Introduce a boolean call:
        short = f"-{argtype[0]}"  # i, s, F, o and t can be specified now.
        long = f"--produce_{argtype}_plots"
        helpstring = f"Specify wether to save the {argtype} plots"
        parser.add_argument(short, long, action="store_true",
                            help=helpstring, default=True)
        # Allow to specify the stem names:
        argname = f"--{argtype}_stem"
        default = stem_defaults[argtype]
        helpstring = f"Specify the stem name of the {argtype} data."
        parser.add_argument(argname, help=helpstring, default=default)
    parser.add_argument("--context",
                        help="The context for the LePhare run.", type=int, default=-1)
    parser.add_argument("-S", "--Stats", action="store_true",
                        help="Provide statistics on each of the files to the command line.")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="Increase output verbosity.")
    args, _ = parser.parse_known_args()
    mt.LOGGER.info("Starting the analysis script for the following subtypes:")
    args.output_stem = "with_dr10"
    args.input_stem = "with_dr10"
    for argtype in [argtype.split('_')[1] for argtype, val in vars(args).items() if isinstance(val, bool) and val]:
        stemval = vars(args)[f'{argtype}_stem']
        mt.LOGGER.info(f"{argtype}_stem: {stemval}")
    args.output_stem = "with_dr10"
    return args

args = read_args()

mt.LOGGER.info(args.context)  # TODO
# print(args.context)
# %%
# input dataframes:
if args.produce_input_plots:
    input_df = mt.read_plike_and_ext(prefix=f"matches/{args.input_stem}_",
                                     suffix="_processed_table.fits")
    input_df = mt.add_mag_columns(input_df)
    av.plot_r_band_magnitude(input_df, args.input_stem)
    av.plot_input_distribution(input_df, args.input_stem, args.context)
    av.plot_band_number_distribution(input_df, args.input_stem, args.context)

# %% Separation plots:
if args.produce_separation_plots:
    input_df = mt.read_plike_and_ext(prefix=f"matches/{args.input_stem}_",
                                     suffix="_processed_table.fits")
    input_df = mt.add_mag_columns(input_df)
    sep.plot_all_separations(input_df, args.separation_stem, args.context)

# %% Filter analysis:
if args.produce_Filter_plots:
    filter_df = fc.read_filter_info_file(args.Filter_stem)
    fc.produce_filter_plot(filter_df, args.Filter_stem)
    info_df = fc.read_filter_overview_file(args.Filter_stem)
    fc.save_filter_info(info_df, args.Filter_stem)

# %% Output dataframe and analysis:
if args.produce_output_plots:
    output_df = mt.read_plike_and_ext(
        prefix=f"lephare_output/{args.output_stem}_", suffix=".fits")
    output_df = mt.add_filter_columns(output_df)
    output_df = output_df[output_df["mag_i-ls10"] > 0]
    for ttype in ["pointlike", "extended"]:
        # ta.plot_problematic_templates(output_df, ttype)
        s_p.plot_photoz_vs_specz(output_df, ttype, args.output_stem)

# %%
if args.produce_template_plots:
    output_df = mt.read_plike_and_ext(
        prefix=f"lephare_output/{args.output_stem}_", suffix=".fits")
    output_df = mt.add_filter_columns(output_df)
    for ttype in ["pointlike", "extended"]:
        # ta.plot_problematic_templates(output_df, ttype, args.template_stem)
        template_df = mt.read_template_library(
            f"{ttype}_mag_lib.dat")  # TODO: {args.template_stem}_
        ta.plot_multiple_against_redshift(
            output_df, template_df, ttype, args.template_stem, bands=("i-hsc", "i-kids"))


#!/usr/bin/env python3
import socket

socket_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

socket_server.bind(('127.0.0.1', 9876))

print('Bind UDP on 9876...')

while True:
    data, addr = socket_server.recvfrom(1024)
    print(data.decode('utf-8'))
    #print('Received %s from %s:%s.' % (data.decode('utf-8'), addr[0], addr[1]))
    #socket_server.sendto(b'recved:' +data, addr)


import folium
from geopy.geocoders import Nominatim

film_studio_cities = ['Los Angeles', 'Rome', 'Wellington', 'Saint-Denis', 'Mumbai', 'Ouarzazate', 'Berlin']
film_studio = ['Hollywood', 'Cinecitta', 'Weta', 'La Cité du Cinéma', 'Bollywood', ' Atlas', 'Filmpark Babelsberg']
locations = list()
lst = list()
titles = list()
name = str()
city = str()
map = folium.Map()
year = input('Enter the year: ')
films = folium.FeatureGroup(name='Location')
studio = folium.FeatureGroup(name='Famous studio')
with open('C:\\Users\\Home\\Downloads\\locations.list') as text:
    for line in text:
        if (year in line) and ('(' in line):
            lst = line.strip().split()
            if (len(lst) == 5) and (year in lst[1]):
                titles.append(lst[0])
                del (lst[:2])
                name = list(lst[0])
                if name.pop() == ',':
                    for j in range(len(name)):
                        city += name[j]
                    if city not in locations:
                        locations.append(city)
                    city = str()
                    name = str()
                    if len(locations) == 25:
                        break

geolocator = Nominatim(user_agent="Map")
for i in range(len(locations)):
    location = geolocator.geocode(locations[i])
    if location == None:
        continue
    else:
        films.add_child(folium.Marker(location=[location.latitude, location.longitude],
                                      popup=titles[i],
                                      icon=folium.Icon()))

for j in range(len(film_studio)):
    location = location = geolocator.geocode(film_studio_cities[j])
    if location == None:
        continue
    else:
        studio.add_child(folium.CircleMarker(location=[location.latitude, location.longitude],
                                             radius=10,
                                             popup=film_studio[j],
                                             fill_color='green',
                                             color='red',
                                             fill_opacity=0.5))
map.add_child(films)
map.add_child(studio)
map.save('films.html')


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the plusMinus function below.
def plusMinus(arr):
    zeros = 0
    pos = 0
    neg = 0
    for num in arr:
        if num is 0:
            zeros +=1
        elif num > 0:
            pos +=1
        else:
            neg +=1
    print("{:.6f}".format(pos/(pos+neg+zeros)))
    print("{:.6f}".format(neg/(pos+neg+zeros)))
    print("{:.6f}".format(zeros/(pos+neg+zeros)))

if __name__ == '__main__':
    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    plusMinus(arr)


import itertools
import json
import zipfile
from typing import BinaryIO, List, Tuple

import numpy as np
from PIL import Image

from shap_e.rendering.view_data import Camera, ProjectiveCamera, ViewData

class BlenderViewData(ViewData):
    """
    Interact with a dataset zipfile exported by view_data.py.
    """

    def __init__(self, f_obj: BinaryIO):
        self.zipfile = zipfile.ZipFile(f_obj, mode="r")
        self.infos = []
        with self.zipfile.open("info.json", "r") as f:
            self.info = json.load(f)
        self.channels = list(self.info.get("channels", "RGBAD"))
        assert set("RGBA").issubset(
            set(self.channels)
        ), "The blender output should at least have RGBA images."
        names = set(x.filename for x in self.zipfile.infolist())
        for i in itertools.count():
            name = f"{i:05}.json"
            if name not in names:
                break
            with self.zipfile.open(name, "r") as f:
                self.infos.append(json.load(f))

    @property
    def num_views(self) -> int:
        return len(self.infos)

    @property
    def channel_names(self) -> List[str]:
        return list(self.channels)

    def load_view(self, index: int, channels: List[str]) -> Tuple[Camera, np.ndarray]:
        for ch in channels:
            if ch not in self.channel_names:
                raise ValueError(f"unsupported channel: {ch}")

        # Gather (a superset of) the requested channels.
        channel_map = {}
        if any(x in channels for x in "RGBA"):
            with self.zipfile.open(f"{index:05}.png", "r") as f:
                rgba = np.array(Image.open(f)).astype(np.float32) / 255.0
                channel_map.update(zip("RGBA", rgba.transpose([2, 0, 1])))
        if "D" in channels:
            with self.zipfile.open(f"{index:05}_depth.png", "r") as f:
                # Decode a 16-bit fixed-point number.
                fp = np.array(Image.open(f))
                inf_dist = fp == 0xFFFF
                channel_map["D"] = np.where(
                    inf_dist,
                    np.inf,
                    self.infos[index]["max_depth"] * (fp.astype(np.float32) / 65536),
                )
        if "MatAlpha" in channels:
            with self.zipfile.open(f"{index:05}_MatAlpha.png", "r") as f:
                channel_map["MatAlpha"] = np.array(Image.open(f)).astype(np.float32) / 65536

        # The order of channels is user-specified.
        combined = np.stack([channel_map[k] for k in channels], axis=-1)

        h, w, _ = combined.shape
        return self.camera(index, w, h), combined

    def camera(self, index: int, width: int, height: int) -> ProjectiveCamera:
        info = self.infos[index]
        return ProjectiveCamera(
            origin=np.array(info["origin"], dtype=np.float32),
            x=np.array(info["x"], dtype=np.float32),
            y=np.array(info["y"], dtype=np.float32),
            z=np.array(info["z"], dtype=np.float32),
            width=width,
            height=height,
            x_fov=info["x_fov"],
            y_fov=info["y_fov"],
        )


from urllib.request import urlopen
html = urlopen("https://stepik.org/media/attachments/lesson/209717/1.html").read().decode('utf-8')
s = str(html)
a = s.count('Python')
b = s.count('C++')
print(a, b)
if a > b :
    print('Python')
else:
    print('C++')


from django.conf.urls.defaults import *

from contact.views import *
from contact.models import *

urlpatterns = patterns ('django.views.generic.simple',

    url(
        r'^info/$',
        ContactController.info,
        name="info"
    ),

    url(
        r'^$',
        ContactController.default,
        name="default"
    ),

)


from collections import defaultdict
from typing import List, TypeVar, Generic, Dict, Optional

from mapfmclient import Problem

from src.data.agent import Agent
from src.data.vertex import Vertex

A = TypeVar("A", bound=Agent)

class Grid(Generic[A]):
    def __init__(self, problem: Problem):
        self.width: int = problem.width
        self.height: int = problem.height

        self._vertices: Dict[int, Dict[int, Optional[Vertex]]] = defaultdict(
            lambda: defaultdict(lambda: None))
        for x in range(self.width):
            for y in range(self.height):
                if problem.grid[y][x] == 0:
                    self._vertices[y][x] = Vertex(x, y)

        self.agents: List[A] = self.create_agents(problem)

    def get_vertex(self, x: int, y: int) -> Optional[Vertex]:
        return self._vertices[y][x]

    def create_agents(self, problem: Problem) -> List[A]:
        raise NotImplementedError("Override this!")


#!/usr/bin/python2.7

import json
import time
import socket
import glob
from websocket import create_connection
import rippled
import monitoring2_7

apiKey = "APIKEY"
core_dir = "/data/rippled/var/cores"
SLEEP = 20

hostname = socket.gethostname()
host_type = rippled.ServerType.lookup(hostname)

if not host_type:
	print("Could not determine state from hostname: %s") % hostname
	exit(2)

host_type.proposers_needed -= 1

key = "rippled.%s.%s.status" % (host_type.name,hostname)
#target = "http://flrrb.com:8000/api/alert"

#print "Detected host type as: %s" % host_type.name

d = rippled.ServerInfo('localhost').get()
build_version_1 = d.build_version
ledger_s_1 = d.ledgers['min']
ledger_e_1 = d.ledgers['max']
proposers_1 = d.proposers
server_state_1 = d.server_state.name

time.sleep(SLEEP)

d = rippled.ServerInfo('localhost').get()
build_version_2 = d.build_version
ledger_s_2 = d.ledgers['min']
ledger_e_2 = d.ledgers['max']
proposers_2 = d.proposers
server_state_2 = d.server_state.name

ledger_gaps = d.ledgers['gaps']

core_count = len(glob.glob('%s/core.*' % core_dir))

if server_state_2 != host_type.state_needed:
	msg = "Wrong state for host type: %s (needed %s)" % (server_state_2,host_type.state_needed)
	code = 2
elif ledger_e_2 <= ledger_e_1:
	msg = "Ledger sample 2 not greater than 1: %s %s" % (ledger_e_1,ledger_e_2)
	code = 1
elif proposers_2 < host_type.proposers_needed:
	msg = "Do not have enough proposers: %s (needed %s)" % (proposers_2,host_type.proposers_needed)
	code = 1
else:
	ledger_rate = float(int(ledger_e_2)-int(ledger_e_1))*60/10
	msg = "Version: %s Ledgers: %s (%s/min) Proposers: %s Gaps: %i Coredumps: %i State: %s" % (build_version_2,ledger_e_2,ledger_rate,proposers_2,ledger_gaps,core_count,server_state_2)
	code = 0

n = monitoring2_7.Nagios(apiKey)
n.add(key,msg,code)
n.send()

g = monitoring2_7.Graphite()
g.set_prefix("rippled.%s.server_info" % g.get('hostname'))
g.add("ledgers_min",d.ledgers['min'])
g.add("ledgers_max",d.ledgers['max'])
g.add("fetch_pack",d.fetch_pack)
g.add("io_latency_ms",d.io_latency_ms)
g.add("last_close.converge_time_s",d.converge_time_s)
g.add("last_close.proposers",d.proposers)
g.add("peers",d.peers)
g.add("validation_quorum",d.validation_quorum)
g.add("load.threads",d.threads)
g.add("server_state",d.server_state.value)
g.add("state.%s" % server_state_2, 1)
g.add("age",d.age)
g.add("validated_age",d.validated_age)
g.add("load_factor",d.load_factor)
g.add("reserve_base_xrp",d.reserve_base_xrp)
g.add("reserve_inc_xrp",d.reserve_inc_xrp)
g.add("validated_seq",d.validated_seq)
g.add("base_fee_xrp",format(d.base_fee_xrp,'f'))

for job in d.jobs:
        job_name = job['name']
        g.add("jobs.%s.avg_time" % job_name, job['avg_time'])
        g.add("jobs.%s.in_progress" % job_name, job['in_progress'])
        g.add("jobs.%s.peak_time" % job_name, job['peak_time'])
        g.add("jobs.%s.per_second" % job_name, job['per_second'])
        g.add("jobs.%s.waiting" % job_name, job['waiting'])

g.set_prefix("rippled.%s" % g.get('hostname'))
g.add("coredumps.count",core_count)

# fee-related stuff
if host_type.name == 'validator':
	f = rippled.Rippled('localhost').get('min_cluster_fee')
	g.set_prefix("rippled.%s.fee" % g.get('hostname'))
	g.add('cost_of_ref_txn',f['cost_of_ref_txn'])
	g.add('load_base',f['load_base'])
	g.add('effective_min_fee',f['effective_min_fee'])
	g.add('min_load_value',f['min_load_value'])

g.set_prefix("rippled.%s" % g.get('hostname'))
g.add("check_rippled.status_code",code)

# nodestore activity
getCounts = rippled.Rippled('localhost').get('get_counts', ({'min_count': 0}) )
g.set_prefix('rippled.%s.get_counts' % g.get('hostname'))
if 'node_reads_hit' in getCounts:
	g.add('node_reads_hit', getCounts['node_reads_hit'])
if 'node_reads_total' in getCounts:
	g.add('node_reads_total', getCounts['node_reads_total'])
if 'node_writes' in getCounts:
	g.add('node_writes', getCounts['node_writes'])

g.send('0.0.0.0')

print(msg)
exit(code)


"""
Multiple WAD Injector

checks for a settings file and:
-  Clones OOTR repo if not already present
-  Then prints a link to it if gz gui is not already present
-  Then requests a settings string if not present
-  Then Requests the number of seeds to generate, if not present

Then loops and generates the roms, followed by injecting them into wad donors
to generate the alloted number of rando seeds

NOTE for some reason no cosmetics or sound changes can be done with this. The settings
     string doesnt change when you update the cosmetics, and the system doesnt apeear to
     allow for cosmetics/sounds to be update by settings string
"""

import os
import random
import subprocess
import json
import sys
import glob
import shutil
import time
from venv import create

def main():
    # make sure we have all the files we need
    try:
        settings = json.loads(open("./settings.json").read())
    except:
        print("You might have accidentally deleted the default settings.json file, please re-clone!")
        sys.exit()

    if not os.path.exists("./output"):
        os.makedirs("./output")

    ootr_path = os.path.abspath(settings["ootr_path"])
    gz_path = os.path.abspath(settings["gz_path"])
    num_seeds = int(settings["num_seeds"])
    ootr_settings_path = os.path.abspath("./ootr_settings.json")
    ootr_settings = json.loads(open(ootr_settings_path, 'r').read())
    rom_path = os.path.abspath(settings["rom_path"])
    wad_path = os.path.abspath(settings["wad_path"])
    ootr_log = os.path.abspath("./log.log")
    out_dir = os.path.abspath(settings["out_dir"])

    # doner rom, clean oot v1.0
    dummy_path = os.path.abspath(".\OoT-Randomizer\ZOOTDEC.z64")

    if not os.path.exists(dummy_path):
        shutil.copy(rom_path, dummy_path)

    print(f"Generating {num_seeds} seeds with settings from '{ootr_settings_path}'")
    if not os.path.exists(ootr_path):
        print("WARNING: ootr not cloned, run the following to clone it: ")
        print("    git clone https://github.com/TestRunnerSRL/OoT-Randomizer.git")
        print("then run me again :)")
        sys.exit()
    if len(glob.glob("./gz*")) == 0:
        print("WARNING: you dont not have gz (for wad injection)")
        print("download it from here: https://github.com/glankk/gz/releases")
        print("Extract it in this repo's root directory, should be called something like 'gz-0.3.6-windows-i686'")
        print("Then run me again :)")
        sys.exit()

    # handle settings
    new_settings = ootr_settings
    if settings["random_starting_item"]:
        items = json.loads(open("./starting_items.json").read())
        starting_category = list(items.keys())[random.randint(0,1)]  # category is either equipment (swords etc) or gear (bow etc)
        new_settings[starting_category] = [items[starting_category][random.randint(0, len(items[starting_category])-1)]]
    if settings["extra_settings"]:
        print(f"adding extra settings: \n{settings['extra_settings']}")
        for key in settings["extra_settings"]:
            new_settings[key] = settings["extra_settings"][key]

    # make a new settings file and use the path to that instead
    new_settings_path = os.path.abspath(f"./output/OOTR_SETTINGS_{str(time.time()).split('.')[0]}.json")
    with open(new_settings_path, 'w') as f:
        f.write(json.dumps(new_settings, indent=4))
    ootr_settings_path = new_settings_path
    sys.path.extend(".\\OoT-Randomizer")

    # Generate the rando seed roms
    created_roms = []
    for i in range(num_seeds):
        print(f"Creating seed number {str(i+1)}")
        stdout = subprocess.check_output(["python", ".\\OoT-Randomizer\\OoTRandomizer.py", "--output_settings",
                                          "--settings", ootr_settings_path, "1>", ootr_log, "2>&1"],
                                         shell=True, encoding="utf8")
        for line in open(ootr_log, 'r').readlines():
            if "Created compressed rom at" in line:
                filename = line.split("at:")[1].strip()
                created_roms.append(filename)
                print(f"Finished '{filename}'")

    print("Copying result to outdir")
    if not os.path.exists(out_dir):
        os.mkdir(out_dir)

    for rom in created_roms:
        shutil.copy(rom, out_dir)

    # Inject them into wad to make wii vc wads of the rando seeds
    # home = os.getcwd()
    # os.chdir(gz_path)
    # cur = 1
    # patcher = os.path.abspath("./patch-wad.bat")
    # for rom in created_roms:
    #     new_path = os.path.abspath(f"./output/OOTR{str(cur)}.wad")
    #     command = [patcher, '-m', rom, '-o', new_path, wad_path]
    #     print(f"running: '{' '.join(command)}'")
    #     subprocess.check_output(command)
    #     cur += 1
    #     print(f"created '{new_path}'")

if __name__ == "__main__":
    main()


"""
sample hyperparameters
sample maximum values by gumble, random features
all in python

optimization the criterion
    1 hyperparameter
        feed: Xsamples, ysamples, l, sigma, sigma0, initialxs
    multiple hyperparameters
        feed: Xsamples, ysamples, ls, sigmas, sigma0s, initialxs
    return
        train operation
        x to query

    !covmatrix computed once and cached for each optimization

GPflow
    optimize for the correct hyperparameters
    samples of hyperparameters

Implement:
    feed: Xsamples, ysamples
    return
        samples of maximum values
            by gumble
            by random features
                optimize for maximum from Xsamples, and some random initialization
    x to query

    optimize a function with multiple initializations
        list of x variables (initialized with initializations)
        list of optimizers for each x variables
            feed: initial values
                  Xsamples, ysamples
                  l, sigma, sigma0
"""

import tensorflow as tf
import numpy as np
import scipy as sp
import time
import scipy.stats as spst
import sys
import utils

import matplotlib.pyplot as plt

# draw random features, and their weights
def draw_random_init_weights_features(
            xdim, n_funcs, n_features,

            xx, # (nobs, xdim)
            yy, # (nobs, 1)

            l, sigma, sigma0,
            # (1,xdim), (), ()

            dtype=tf.float32,
            name='random_features'):
    """
    sigma, sigma0: scalars
    l: 1 x xdim
    xx: n x xdim
    yy: n x 1
    n_features: a scalar
    different from draw_random_weights_features,
        this function set W, b, noise as Variable that is initialized randomly
        rather than sample W, b, noise from random function
    """

    n = tf.shape(xx)[0]

    xx = tf.tile( tf.expand_dims(xx, axis=0), multiples=(n_funcs,1,1) )
    yy = tf.tile( tf.expand_dims(yy, axis=0), multiples=(n_funcs,1,1) )
    idn = tf.tile(tf.expand_dims(tf.eye(n, dtype=dtype), axis=0), multiples=(n_funcs,1,1))

    # draw weights for the random features.
    W = tf.get_variable(name="{}_W".format(name),
                shape=(n_funcs, n_features,xdim),
                dtype=dtype,
                initializer=tf.random_normal_initializer()) \
        * tf.tile( tf.expand_dims(tf.sqrt(l), axis=0),
                   multiples=(n_funcs,n_features,1) )
    # W = tf.random.normal(shape=(n_funcs, n_features,xdim), dtype=dtype) * tf.tile( tf.expand_dims(tf.sqrt(l), axis=0), multiples=(n_funcs,n_features,1) )
    # n_funcs x n_features x xdim

    b = 2.0 * np.pi \
        * tf.get_variable(
            name="{}_b".format(name),
            shape=(n_funcs,n_features,1),
            dtype=dtype,
            initializer=tf.random_uniform_initializer(minval=0., maxval=1.))
    # b = 2.0 * np.pi * tf.random.uniform(shape=(n_funcs,n_features,1), dtype=dtype)
    # n_funcs x n_features x 1

    # compute the features for xx.
    Z = tf.cast(tf.sqrt(2.0 * sigma / n_features), dtype=dtype)\
        * tf.cos( tf.matmul(W, xx, transpose_b=True)
                + tf.tile(b, multiples=(1,1,n) ))
    # n_funcs x n_features x n

    # draw the coefficient theta.
    noise = tf.get_variable(
                name="{}_noise".format(name),
                shape=(n_funcs,n_features,1),
                dtype=dtype,
                initializer=tf.random_normal_initializer())
    # noise = tf.random.normal(shape=(n_funcs,n_features,1))
    # n_funcs x n_features x 1

    def true_clause():
        Sigma = tf.matmul(Z, Z, transpose_a=True) + sigma0 * idn
        # n_funcs x n x n of rank n or n_features

        mu = tf.matmul(tf.matmul(Z, utils.multichol2inv(Sigma, n_funcs, dtype=dtype)), yy)
        # n_funcs x n_features x 1

        # tf.linalg.eigh returns None sometimes!!!
        e, v = tf.linalg.eigh(Sigma)

        # e = tf.linalg.eigvalsh(Sigma)
        e = tf.expand_dims(e, axis=-1)
        # n_funcs x n x 1

        r = tf.reciprocal(tf.sqrt(e) * (tf.sqrt(e) + tf.sqrt(sigma0)))
        # n_funcs x n x 1

        theta = noise \
            - tf.matmul(Z,
                        tf.matmul(v,
                                r * tf.matmul(v,
                                                tf.matmul(Z, noise, transpose_a=True),
                                                transpose_a=True))) \
            + mu
        # n_funcs x n_features x 1

        return theta

    def false_clause():
        Sigma = utils.multichol2inv( tf.matmul(Z, Z, transpose_b=True) / sigma0
                        + tf.tile(tf.expand_dims(tf.eye(n_features, dtype=dtype), axis=0), multiples=(n_funcs,1,1)),
                        n_funcs, dtype=dtype)

        mu = tf.matmul(tf.matmul(Sigma, Z), yy) / sigma0

        theta = mu + tf.matmul(tf.cholesky(Sigma), noise)
        return theta

    # theta = tf.cond(
    #             pred=tf.less(n, n_features),
    #             true_fn=true_clause,
    #             false_fn=false_clause
    #         )
    print("Need to debug the sampling of theta, W, b in optfunc.py:draw_random_init_weights_features")
    theta = false_clause()

    return theta, W, b

def make_function_sample(x, n_features, sigma, theta, W, b, dtype=tf.float32):
    fval = tf.squeeze( tf.sqrt(2.0 * sigma / n_features) \
                * tf.matmul(theta,
                            tf.cos( tf.matmul(W,
                                              x,
                                              transpose_b=True)
                                    + b ),
                            transpose_a=True) )
    # x must be a 2d tensor
    # return: n_funcs x tf.shape(x)[0]
    #      or (tf.shape(x)[0],) if n_funcs = 1

    return fval

def duplicate_function_with_multiple_inputs(f, n_inits, xmin=-np.infty, xmax=np.infty, dtype=tf.float32):

    xs_list = [None] * n_inits
    fvals = [None] * n_inits

    for i in range(n_inits):
        xs_list[i] = tf.get_variable(shape=(1,xdim), dtype=dtype, name='{}_{}'.format(name, i),
                                constraint=lambda x: tf.clip_by_value(x, xmin, xmax))
        fvals[i] = f(xs_list[i])

    fvals = tf.squeeze(tf.stack(fvals))
    xs = tf.stack(xs_list)
    return xs, xs_list, fvals

# find maximum of a function with multiple initializers
# a function is a tensor, so this function can be used in the above function
def find_maximum_with_multiple_init_tensor(xs_list, fvals, n_inits, xdim, optimizer, dtype=tf.float32):
    """
    # xmin=-np.infty, xmax=np.infty,
    xs: list of size n_inits of (1,xdim)
    fvals: (n_inits,): function value with inputs are xs tensor
    initializers: n_inits x xdim
    """
    # initializers: n x d
    # func: a tensor function
    #     input:  tensor n x d
    #     output: tensor n x 1
    # n_inits: scalar (not a tensor)
    """
    returns:
        vals: shape = (n_inits,)
        invars: shape = (n_inits,xdim)
        maxval: scalar
        maxinvar: shape= (xdim,)
    """

    trains = [None] * n_inits

    for i in range(n_inits):
        trains[i] = optimizer.minimize(-fvals[i], var_list=[xs_list[i]])

    max_idx = tf.argmax(fvals)
    return trains, max_idx

def find_maximum_list_of_funcs(xdim, n_inits, n_funcs, xs, xs_list, fvals, optimizer, dtype=tf.float32):
    """
    xs: shape=(n_funcs, n_inits, xdim)
    xs_list: list of n_funcs lists of size n_inits of tensor (1,xdim)
    fvals: tensor of shape (n_funcs, n_inits)
    #initializers: (n_funcs, n_inits, xdim)
    """
    train_all = []
    max_val_all = [None] * n_funcs
    max_input_all = [None] * n_funcs
    max_idx_all = []

    for i in range(n_funcs):
        trains, max_idx = find_maximum_with_multiple_init_tensor(xs_list[i], fvals[i,...], n_inits, xdim, dtype=dtype, optimizer=optimizer)

        train_all.extend(trains)
        max_idx_all.append(max_idx)

        max_input_all[i] = xs[i,max_idx,...]
        max_val_all[i] = fvals[i,max_idx]

    max_val_arr = tf.reshape(tf.stack(max_val_all), shape=(n_funcs,))
    max_input_arr = tf.reshape(tf.stack(max_input_all), shape=(n_funcs,xdim))
    max_idx_arr = tf.reshape(tf.stack(max_idx_all), shape=(n_funcs,))

    return train_all, max_val_arr, max_input_arr, max_idx_arr

def gen_fval_xs(funcs, n_inits, xdim, xmin, xmax, dtype=tf.float32, name='test'):
    """
    if funcs is a list of functions
        return xs: nfuncs x n_inits x xdim
               xs_list: list of nfuncs lists of n_inits tensors of size (1,xdim)
               fvals: nfuncs x n_inits
    else:
        return xs: n_inits x xdim
               xs_list: list of n_inits tensors of size (1,xdim)
               fvals: n_inits,
    """
    if isinstance(funcs, list):
        print("List of functions")

        n_funcs = len(funcs)
        xs_list = [[tf.get_variable(shape=(1,xdim), dtype=dtype, name='{}_{}_{}'.format(name, i, j),
                                    constraint=lambda x: tf.clip_by_value(x, xmin, xmax)) for i in range(n_inits)] for j in range(n_funcs)]

        xs = []
        for i in range(n_funcs):
            xs.append( tf.stack(xs_list[i]) )
        xs = tf.stack(xs)

        fvals = []
        for i in range(n_funcs):
            fvals_i = []
            for j in range(n_inits):
                fvals_i.append( tf.squeeze(funcs[i](xs_list[i][j])) )

            fvals.append( tf.squeeze(tf.stack(fvals_i)) )

        fvals = tf.stack(fvals)

    else: # funcs is a function
        print("A function")
        xs_list = [tf.get_variable(shape=(1,xdim), dtype=dtype, name='test_func_mul_init_{}'.format(i),
                                    constraint=lambda x: tf.clip_by_value(x, xmin, xmax)) for i in range(n_inits)]

        fvals = [funcs(x) for x in xs_list]

        xs = tf.reshape(tf.concat(xs_list, axis=0), shape=(n_inits, xdim))
        fvals = tf.squeeze(tf.concat(fvals, axis=0))

    return xs, xs_list, fvals

# draw random features, and their weights
def draw_random_init_weights_features_np(
            xdim, n_funcs, n_features,

            xx, # (nobs, xdim)
            yy, # (nobs, 1)

            l, sigma, sigma0):
            # (1,xdim), (), ()
    """
    sigma, sigma0: scalars
    l: 1 x xdim
    xx: n x xdim
    yy: n x 1
    n_features: a scalar
    different from draw_random_weights_features,
        this function set W, b, noise as Variable that is initialized randomly
        rather than sample W, b, noise from random function
    """
    n = xx.shape[0]
    l = l.reshape(1,xdim)

    xx = np.tile( xx.reshape(1,n,xdim), reps=(n_funcs,1,1) )
    yy = np.tile( yy.reshape(1,n,1), reps=(n_funcs,1,1) )
    idn = np.tile( np.eye(n).reshape(1,n,n), reps=(n_funcs,1,1) )

    # draw weights for the random features.
    W = np.random.randn(n_funcs, n_features, xdim) \
        * np.tile(np.sqrt(l).reshape(1,1,xdim),
                  reps=(n_funcs, n_features, 1))
    # n_funcs x n_features x xdim

    b = 2.0 * np.pi * np.random.rand(n_funcs, n_features, 1)
    # n_funcs x n_features x 1

    # compute the features for xx.
    Z = np.sqrt(2.0 * sigma / n_features) \
        * np.cos( np.matmul(W, np.transpose(xx, (0,2,1)))
                  + np.tile(b, reps=(1,1,n)) )
    # n_funcs x n_features x n

    # draw the coefficient theta.
    noise = np.random.randn(n_funcs, n_features, 1)
    # n_funcs x n_features x 1

    if n < n_features:
        Sigma = np.matmul(np.transpose(Z, (0,2,1)), Z) \
                + sigma0 * idn
        # n_funcs x n x n

        mu = np.matmul( np.matmul(Z, np.linalg.inv(Sigma) ), yy)
        # n_funcs x n_features x 1

        e, v = np.linalg.eig(Sigma)
        # n_funcs, n
        # n_funcs, n, n

        e = e.reshape(n_funcs, n, 1)
        # n_funcs x n x 1

        r = 1.0 / (np.sqrt(e) * (np.sqrt(e) + np.sqrt(sigma0)))
        # n_funcs x n x 1

        theta = noise \
                - np.matmul(Z,
                            np.matmul(v,
                                      r * np.matmul(np.transpose(v, (0,2,1)),
                                                    np.matmul(np.transpose(Z,(0,2,1)),
                                                              noise)
                                                    )
                                     )
                            ) \
                + mu
        # n_funcs x n_features x 1
    else:
        Sigma = np.linalg.inv(
            np.matmul(Z, np.transpose(Z,(0,2,1))) / sigma0
            + np.tile( np.eye(n_features).reshape(1,n_features,n_features), reps=(n_funcs,1,1) )
        )
        mu = np.matmul( np.matmul(Sigma,Z), yy ) / sigma0

        theta = mu + np.matmul(np.linalg.cholesky(Sigma), noise)

    return theta, W, b

# for testing draw_random_init_weights_features_np
def make_function_sample_np(x, n_features, sigma, theta, W, b):
    fval = np.squeeze(
        np.sqrt(2.0 * sigma / n_features)
        * np.matmul(theta.T,
                    np.cos(
                        np.matmul(W, x.T)
                        + b
                        )
                    ) )
    # x must be a 2d tensor
    # return: n_funcs x tf.shape(x)[0]
    #      or (tf.shape(x)[0],) if n_funcs = 1

    return fval

########################## TEST FUNCTIONS ##########################

def test_find_maximum_with_multiple_init_tensor(ntrain=10, n_inits=5, dtype = tf.float32):
    """
    Adam with 1000 iterations
    """
    tf.reset_default_graph()

    xdim = 2
    xmin = -10.
    xmax = 10.

    func = lambda x: tf.sin( tf.matmul(x,x,transpose_b=True) )

    initializers = tf.random.uniform(shape=(n_inits,xdim), dtype=dtype) * (xmax - xmin) + xmin

    xs, xs_list, fvals = gen_fval_xs(func, n_inits, xdim, xmin, xmax, dtype=dtype, name='test_max_f_mulinit')

    assign_inits = []
    for i in range(n_inits):
        assign_inits.append( tf.assign(xs_list[i], tf.reshape(initializers[i,:], shape=(1,xdim))) )

    optimizer = tf.train.AdamOptimizer()

    trains, max_idx = find_maximum_with_multiple_init_tensor(xs_list, fvals, n_inits, xdim, dtype=dtype, name='find_maximum_multiple_inputs', optimizer=optimizer)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        sess.run(assign_inits)

        xs_val, xs_list_val, fvals_val = sess.run([xs, xs_list, fvals])
        print('')
        print('input = ', xs_val[0,...])
        print(xs_list_val[0])
        print('output = ', fvals_val[0])

        for i in range(ntrain):
            _, max_idx_val, xs_val, xs_list_val, fvals_val = sess.run([trains, max_idx, xs, xs_list, fvals])

        print('')
        print('input = ', xs_val[0,...])
        print(xs_list_val[0])
        print('output = ', fvals_val[0])

def test_find_maximum_list_of_funcs(ntrain, n_inits=5, dtype = tf.float32):
    """
    Adam with 1000 iterations
    """
    tf.reset_default_graph()

    xdim = 2
    xmin = -10.
    xmax = 10.

    funcs = [lambda x: tf.sin( tf.matmul(x,x,transpose_b=True) ),
             lambda x: tf.cos( tf.matmul(x,x,transpose_b=True)) + 2.0 ]
    n_funcs = len(funcs)

    initializers = tf.random.uniform(shape=(n_funcs, n_inits, xdim), dtype=dtype) * (xmax - xmin) + xmin

    xs, xs_list, fvals = gen_fval_xs(funcs, n_inits, xdim, xmin, xmax, dtype=dtype, name='test_max_listf')

    assign_inits = []
    for i in range(n_funcs):
        for j in range(n_inits):
            assign_inits.append( tf.assign(xs_list[i][j], tf.reshape(initializers[i,j,:], shape=(1,xdim))) )

    optimizer = tf.train.AdamOptimizer()

    trains, max_vals, max_inputs = find_maximum_list_of_funcs(xdim, n_inits, n_funcs, xs, xs_list, fvals, optimizer=optimizer, dtype=dtype, name="opt_list_funcs")

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        sess.run(assign_inits)

        for i in range(ntrain):
            _, max_vals_val, max_inputs_val, xs_val, fvals_val = sess.run([trains, max_vals, max_inputs, xs, fvals])

            if i == ntrain - 1 or i == 1:
                print('')
                print('max input = ', max_inputs_val)
                print('max output = ', max_vals_val)
                print('xs = ', xs_val)
                print('fvals = ', fvals_val)

def test_draw_random_weights_features(n_funcs=10, n_features=500, dtype=tf.float32, randomize_funcs=False, func_param_plc=False, plot=True):
    tf.reset_default_graph()

    xdim = 1

    xx = tf.placeholder(shape=(None, xdim), dtype=dtype, name='xx')
    yy = tf.placeholder(shape=(None, 1), dtype=dtype, name='yy')
    l = tf.get_variable(shape=(1,xdim), dtype=dtype, name='l')
    sigma = tf.get_variable(shape=(), dtype=dtype, name='sigma')
    sigma0 = tf.get_variable(shape=(), dtype=dtype, name='sigma0')

    x = tf.placeholder(shape=(None, xdim), dtype=dtype, name='x')

    thetas, Ws, bs = draw_random_init_weights_features(xdim, n_funcs, n_features, xx, yy, l, sigma, sigma0, dtype=dtype, name='random_features')

    if func_param_plc:
        thetas_plc = tf.placeholder(shape=(n_funcs, n_features, 1), dtype=dtype, name='theta')
        Ws_plc = tf.placeholder(shape=(n_funcs, n_features, xdim), dtype=dtype, name='W')
        bs_plc = tf.placeholder(shape=(n_funcs, n_features, 1), dtype=dtype, name='b')

        fvals = []
        for i in range(n_funcs):
            fvals.append( make_function_sample(x, n_features, sigma, thetas_plc[i,...], Ws_plc[i,...], bs_plc[i,...], dtype=dtype) )
        fvals = tf.stack(fvals)

    else:
        fvals = []
        for i in range(n_funcs):
            fvals.append( make_function_sample(x, n_features, sigma, thetas[i,...], Ws[i,...], bs[i,...], dtype=dtype) )
        fvals = tf.stack(fvals)

    xx_val = np.array([[0.], [1.], [4.], [5.]])
    yy_val = np.array([[-5.], [0.5], [3.0], [0.3]])
    l_val = np.array([[10.0]])
    # xx_val = np.array([[0., 1.], [1.,1.], [4.,1.], [5.,1.1]])
    # yy_val = np.array([[-5.], [0.5], [3.0], [0.3]])
    # l_val = np.array([[10.0, 5.0]])

    sigma_val = 2.0
    sigma0_val = 1e-3

    x_val = np.linspace(0., 5., 100).reshape(-1,1)
    # x_val = np.array(list(zip( np.linspace(0., 5., 50), np.ones(50) )))

    n_plot_funcs = 3
    func_vals = []
    fixed_func_vals = []

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        l.load(l_val, sess)
        sigma.load(sigma_val, sess)
        sigma0.load(sigma0_val, sess)

        start = time.time()

        feed_dict = {xx: xx_val, yy: yy_val, x: x_val}

        if func_param_plc and not randomize_funcs:
            thetas_val, Ws_val, bs_val = sess.run([thetas, Ws, bs], feed_dict=feed_dict)

        for i in range(n_plot_funcs):
            if randomize_funcs:
                sess.run(tf.global_variables_initializer())

                if func_param_plc:
                    thetas_val, Ws_val, bs_val = sess.run([thetas, Ws, bs], feed_dict=feed_dict)

            if func_param_plc:
                func_val = sess.run(fvals, feed_dict=feed_dict)
            else:
                func_val = sess.run(fvals, feed_dict=feed_dict)

            func_vals.append(func_val)
        print("End in {:.4f}s".format(time.time() - start))

    if plot:
        fig, axs = plt.subplots(n_plot_funcs,2)
        for j in range(n_plot_funcs):
            for i in range(n_funcs):
                axs[j,0].plot(np.squeeze(x_val), np.squeeze(func_vals[j][i,...]))

            axs[j,0].scatter(xx_val, yy_val)

        plt.show()

def test_maximize_random_weights_features(n_funcs=10, ntrain=100, n_inits=5, n_features=500, dtype=tf.float32, plot=True):
    # TODO: not working, only optimize for 1 functions...
    tf.reset_default_graph()

    xdim = 1
    xmin = 0.
    xmax = 5.

    xx = tf.placeholder(shape=(None, xdim), dtype=dtype, name='xx')
    yy = tf.placeholder(shape=(None, 1), dtype=dtype, name='yy')
    l = tf.get_variable(shape=(1,xdim), dtype=dtype, name='l')
    sigma = tf.get_variable(shape=(), dtype=dtype, name='sigma')
    sigma0 = tf.get_variable(shape=(), dtype=dtype, name='sigma0')

    x = tf.placeholder(shape=(None, xdim), dtype=dtype, name='x')

    thetas, Ws, bs = draw_random_init_weights_features(xdim, n_funcs, n_features, xx, yy, l, sigma, sigma0, dtype=dtype, name='random_features')

    thetas_plc = tf.get_variable(shape=(n_funcs, n_features, 1), dtype=dtype, name='theta')
    Ws_plc = tf.get_variable(shape=(n_funcs, n_features, xdim), dtype=dtype, name='W')
    bs_plc = tf.get_variable(shape=(n_funcs, n_features, 1), dtype=dtype, name='b')

    # funcs = [lambda x: tf.sin( x ),
    #          lambda x: tf.cos(x) + 2.0 ]
    # funcs_np = [lambda x: np.sin( x ),
    #             lambda x: np.cos(x) + 2.0 ]
    # n_funcs = len(funcs)

    # optimizing function samples
    initializers = tf.random.uniform(shape=(n_funcs, n_inits, xdim), dtype=dtype) * (xmax - xmin) + xmin

    funcs = []
    for i in range(n_funcs):
        funcs.append( (lambda x: make_function_sample(x, n_features, sigma, thetas_plc[i,...], Ws_plc[i,...], bs_plc[i,...], dtype=dtype)) )

    fvals = []
    for i in range(n_funcs):
        fvals.append( funcs[i](x) )
    fvals = tf.stack(fvals)

    print("# of funcs: ", len(funcs))
    sys.stdout.flush()

    # xs, xs_list, opt_fvals = gen_fval_xs(funcs, n_inits, xdim, xmin, xmax, dtype=dtype, name='test_max_listf')
    print("IMPORTANT: cannot use gen_fval_xs, only the last function would be used")
    name = 'test_max_listf'
    xs_list = [[tf.get_variable(shape=(1,xdim), dtype=dtype, name='{}_{}_{}'.format(name, i, j),
                                constraint=lambda x: tf.clip_by_value(x, xmin, xmax)) for i in range(n_inits)] for j in range(n_funcs)]

    xs = []
    for i in range(n_funcs):
        xs.append( tf.stack(xs_list[i]) )
    xs = tf.stack(xs)

    opt_fvals = []
    for i in range(n_funcs):
        fvals_i = []
        for j in range(n_inits):
            fval = tf.squeeze( tf.sqrt(2.0 * sigma / n_features) \
                            * tf.matmul(thetas_plc[i,...],
                                        tf.cos( tf.matmul(Ws_plc[i,...],
                                                          xs_list[i][j],
                                                          transpose_b=True)
                                                + bs_plc[i,...] ),
                                        transpose_a=True) )
            fvals_i.append( fval )

        opt_fvals.append( tf.squeeze(tf.stack(fvals_i)) )

    opt_fvals = tf.stack(opt_fvals)

    assign_inits = []
    for i in range(n_funcs):
        for j in range(n_inits):
            assign_inits.append( tf.assign(xs_list[i][j], tf.reshape(initializers[i,j,:], shape=(1,xdim))) )

    optimizer = tf.train.AdamOptimizer()

    trains, max_vals, max_inputs, max_idx_arr = find_maximum_list_of_funcs(xdim, n_inits, n_funcs, xs, xs_list, opt_fvals, optimizer=optimizer, dtype=dtype, name="opt_list_funcs")

    xx_val = np.array([[0.], [1.], [4.], [5.]])
    yy_val = np.array([[-5.], [0.5], [3.0], [0.3]])
    l_val = np.array([[10.0]])

    sigma_val = 2.0
    sigma0_val = 1e-3

    x_val = np.linspace(xmin, xmax, 100).reshape(-1,1)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        start = time.time()

        l.load(l_val, sess)
        sigma.load(sigma_val, sess)
        sigma0.load(sigma0_val, sess)

        thetas_val, Ws_val, bs_val = sess.run([thetas, Ws, bs], feed_dict={xx: xx_val,
                             yy: yy_val,
                             x: x_val})

        thetas_plc.load(thetas_val, sess)
        Ws_plc.load(Ws_val, sess)
        bs_plc.load(bs_val, sess)

        func_val = sess.run(fvals, feed_dict={x: x_val})

        print("End evaluating functions in {:.4f}s".format(time.time() - start))
        sys.stdout.flush()

        start = time.time()
        sess.run(assign_inits)

        xs_val, opt_fvals_val = sess.run([xs, opt_fvals])

        for i in range(ntrain):
            _, max_vals_val, max_inputs_val, max_idx_arr_val = sess.run([trains, max_vals, max_inputs, max_idx_arr])

            if i == ntrain - 1 or i == 1:
                print('')
                print('max input = ', max_inputs_val)
                print('max output = ', max_vals_val)
                print('max_idx_arr = ', max_idx_arr_val)
                # for j in range(n_funcs):
                #     print('              ', xs_val[j,max_idx_arr_val[j],...])
                #     print('            f:', opt_fvals_val[j,max_idx_arr_val[j],...])

        print("End optimizing in {:.4f}s".format(time.time() - start))
        sys.stdout.flush()

    if plot:
        fig, axs = plt.subplots()

        for i in range(n_funcs):
            axs.plot(np.squeeze(x_val), np.squeeze(func_val[i,...]), zorder=0)

        axs.scatter(xx_val, yy_val, zorder=3)
        axs.scatter(np.squeeze(max_inputs_val), max_vals_val, zorder=5, c='r')

        plt.show()


import os
import tempfile

import requests

from testbot.configs import worker_config, server_url
from testbot.util import md5sum

class APIError(Exception):
    pass

def get_auth_param():
    return worker_config['name'], worker_config['password']

def report_started(submission_id: int, work_id: str, hostname: str, pid: int):
    data = {'hostname': hostname, 'pid': pid}
    resp = requests.put('%sapi/submissions/%d/worker-started/%s' % (server_url, submission_id, work_id),
                        json=data, auth=get_auth_param())
    resp.raise_for_status()

def report_result(submission_id: int, work_id: str, data: dict):
    resp = requests.put('%sapi/submissions/%d/worker-result/%s' % (server_url, submission_id, work_id),
                        json=data, auth=get_auth_param())
    resp.raise_for_status()

def get_submission_and_config(submission_id: int, work_id: str):
    resp = requests.get(
        '%sapi/submissions/%d/worker-get-submission-and-config/%s' % (server_url, submission_id, work_id),
        auth=get_auth_param())
    resp.raise_for_status()
    return resp.json()

def download_material(material: dict, folder: str, chunk_size: int = 65536) -> str:
    resp = requests.get('%sapi/materials/%d/worker-download' % (server_url, material['id']), auth=get_auth_param(),
                        stream=True)
    resp.raise_for_status()

    name = material['name']
    name_parts = name.rsplit('.', 2)
    if len(name_parts) > 1:
        name_parts[0] = ''
        suffix = '.'.join(name_parts)
    else:
        suffix = None

    ffd = None
    try:
        fd, path = tempfile.mkstemp(suffix=suffix, dir=folder)
        ffd = os.fdopen(fd, 'wb')
        for chunk in resp.iter_content(chunk_size=chunk_size):
            if chunk:
                ffd.write(chunk)
    finally:
        if ffd:
            ffd.close()

    if material['md5'] != md5sum(path):
        raise APIError('MD5 check of material "%s" failed' % material['name'])
    return os.path.relpath(path, folder)

def download_submission_file(submission_id: int, work_id: str, file: dict, local_save_path: str,
                             chunk_size: int = 65536):
    resp = requests.get('%sapi/submissions/%d/worker-submission-files/%s/%d' %
                        (server_url, submission_id, work_id, file['id']),
                        auth=get_auth_param(), stream=True)
    resp.raise_for_status()
    with open(local_save_path, 'wb') as f:
        for chunk in resp.iter_content(chunk_size=chunk_size):
            if chunk:
                f.write(chunk)
    if file['md5'] != md5sum(local_save_path):
        raise APIError('MD5 check of submission file "%s" failed' % file['requirement']['name'])

def upload_output_files(submission_id: int, work_id: str, files: dict):
    resp = requests.post('%sapi/submissions/%d/worker-output-files/%s' %
                         (server_url, submission_id, work_id),
                         files=files, auth=get_auth_param())
    resp.raise_for_status()


import cv2
from model import FacialExpressionModel
import numpy as np
import threading, time
import queue
import logging
import sys
from memory_profiler import profile

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-9s) %(message)s',)

BUFFER_SIZE = 700
qbuffer = queue.Queue(BUFFER_SIZE)

class ProducerThread(threading.Thread):
    def __init__(self, name):
        super(ProducerThread,self).__init__()
        self.name = name
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

    @profile
    def run(self):
        while True:
            if self.stopped():
                return
            ret, fr = rgb.read()
            if not qbuffer.full():
                if ret==True:
                    qbuffer.put(fr)
                    logging.debug('ProducerThread ' + str(qbuffer.qsize()) + ' items in queue')
        return

class ConsumerThread(threading.Thread):
    def __init__(self, name):
        super(ConsumerThread,self).__init__()
        self.name = name
        self._stop = threading.Event()
        return

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

    @profile
    def run(self):
        f=0
        while True:
            if self.stopped():
                return
            if not qbuffer.empty():
                f+=1
                fr = qbuffer.get()
                if f%5==1:
                    gray_fr = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY)
                    faces = facec.detectMultiScale(gray_fr, 1.3, 5)
                    for (x, y, w, h) in faces:
                        fc = gray_fr[y:y+h, x:x+w]

                        roi = cv2.resize(fc, (48, 48))
                        norm = np.zeros((48,48))
                        roi = cv2.normalize(roi,  norm, 0, 255, cv2.NORM_MINMAX)
                        pred = cnn.predict_emotion(roi[np.newaxis, :, :, np.newaxis])
                        cv2.putText(fr, pred, (x, y), font, 1, (255, 255, 0), 2)
                        cv2.rectangle(fr,(x,y),(x+w,y+h),(255,0,0),2)

                    cv2.imshow("emotion_win",fr)
                    cv2.waitKey(1)
                    logging.debug('ConsumerThread ' + str(qbuffer.qsize()) + ' items in queue')

                    #out.write(fr)
        return

if __name__ == '__main__':

    rgb = cv2.VideoCapture(0)
    facec = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    font = cv2.FONT_HERSHEY_SIMPLEX
    cnn = FacialExpressionModel("face_model.json", "face_model.h5")
    #fourcc = cv2.VideoWriter_fourcc(*'XVID')
    #out = cv2.VideoWriter('output.avi',fourcc,float(5), (640,480))

    t1 = ProducerThread(name='producer')
    t2 = ConsumerThread(name='consumer')

    t1.start()
    t2.start()

    time.sleep( 30 )
    t1.stop()
    t2.stop()


import requests, os

from flask import Flask, jsonify, render_template, request

app = Flask(__name__)

apikey = os.getenv("API_KEY")

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

@app.route("/convert", methods=["POST"])
def convert():

    # Query for currency exchange rate
    symbol = request.form.get("currency")
    res = requests.get("http://data.fixer.io/api/latest", params={
        "access_key": apikey, "base": "EUR", "symbols": symbol})

    # Make sure request succeeded
    if res.status_code != 200:
        return jsonify({"success": False})

    # Make sure currency is in response
    data = res.json()

    if data['success'] == False:
        return jsonify({"success": False})

    if symbol not in data['rates']:
        return jsonify({"success": False})

    return jsonify({"success": True, "rate": data["rates"][symbol]})


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

import re
from PIL import Image, ImageDraw
import yaml, sys, subprocess

def draw_arc(draw: ImageDraw.ImageDraw, target, offset=(0,0), scale=1.0):
	# check
	# calc
	x0 = (target['center']['x'] - target['radius']) * scale + offset[0]
	x1 = (target['center']['x'] + target['radius']) * scale + offset[0]
	y0 = (target['center']['y'] - target['radius']) * scale + offset[1]
	y1 = (target['center']['y'] + target['radius']) * scale + offset[1]
	start = target['range']['start']
	end = target['range']['end']
	# draw
	draw.arc(
		[(int(x0), int(y0)), (int(x1), int(y1))],
		start, end)

def draw_line(draw: ImageDraw.ImageDraw, target, offset=(0,0), scale=1.0):
	vertexes = []
	for vertex in target['vertexes']:
		x = vertex['x'] * scale + offset[0]
		y = vertex['y'] * scale + offset[1]
		vertexes.append((int(x), int(y)))
	# draw
	draw.line(vertexes)

if __name__ == '__main__':
	width = 72
	height = 72
	background = (0, 0, 0, 0)
	mode = 'RGBA'
	input = 'alpaca.yaml'
	output = 'hoge.png'

	with open('alpaca.yaml') as f:
		yml = yaml.safe_load(f)
	# print(yml)

	img = Image.new(mode, (width, height), background)
	draw = ImageDraw.Draw(img)

	for draw_target in yml['draws']:
		if draw_target['type'] == 'ARC':
			draw_arc(draw, draw_target, (36, 30), 2.5)
		elif draw_target['type'] == 'LINE':
			draw_line(draw, draw_target, (36, 30), 2.5)

	img = img.transpose(Image.ROTATE_180)

	img.save(output)


"""Used to call an external NLP API for a given text input """
# Library imports
import cProfile
import pstats
import logging
import os
import PyPDF2 as pypdf
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer
import src.Internal_API.db_connector as db_connector

# Setup logging for text analysis module
logger = logging.getLogger('text_analysis_logger')
logger.setLevel(logging.DEBUG)

# Logging handler and setting logging level to DEBUG
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# format for log entries
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# adding format to handler
ch.setFormatter(formatter)

# adding handling to logger
logger.addHandler(ch)

# API_error value for testing only, will be removed when NLP API is implemented
def text_analyze(input):
    """Handles text analysis from a given text and uses external API, returns raw data from NLP analysis"""
    # Error Checks:
    if input is None or input.strip() == '':# Checks if input is empty
        logging.error("ERROR 101: Input not found")
        return 101
    if not isinstance(input, str):  # Checks if input text is a string
        logging.error("ERROR 102: Input is not a string")
        return 102
    if len(input) < 3:# Checks if length of input is within bounds, is lower for testing
        logging.error("ERROR 103: Input is too short")
        return 103
    if len(input) > 15:  # Checks if length of input is within bounds, is higher for testing
        logging.error("ERROR 104: Input is too long")
        return 104
    sia = SentimentIntensityAnalyzer()
    scores = sia.polarity_scores(input)
    sentiment_score = scores["compound"]
    db_connector.query_db("INSERT INTO Paragraphs (paragraphID,documentID,sentimentNum) VALUES (1, 1234, 0.7)")
    print("Text Analyzed")
    return sentiment_score

# extracted_text and pdf_page are for testing only, will be removed when pypdf is implemented
def pdf_to_text(file_name, extracted_text, pdf_page):
    """Handles the conversion from PDF to a text string, returns string of text or list of strings"""
    if not os.path.isfile(file_name):
        logger.error("ERROR 201: File not found")
        return 201
    if not file_name.endswith('.pdf'):
        logger.error("ERROR 202: Invalid file format")
        return 202
    try:
        pdf_object = open(file_name, 'rb')
        pdf_reader = pypdf.PdfReader(pdf_object)
    except pypdf.utils.PdfReadError:
        logger.error("ERROR 203: Error reading PDF file")
        return 203
    if len(pdf_reader.pages) == 0:
        logger.error("ERROR 204: Selected PDF has no pages")
        return 204
    db_connector.query_db(f"INSERT INTO Paragraphs (paratext) VALUES ('{extracted_text}') WHERE paragraphID = 1")
    print("Text Extracted!")
    return 0

def text_analysis_profiler():
    """Runs a profile on text analysis Module and prints results to the console"""
    profiler = cProfile.Profile()
    profiler.enable()
    text_analyze("Hello World!", False)
    print('Text Analysis Successful')
    profiler.disable()
    stats = pstats.Stats(profiler).sort_stats('ncalls')
    stats.print_stats()
    return 0


import pandas as pd
from controller.project_controller.projects.base.file_operations import file_methods
from controller.project_controller.projects.base.data_preprocessing import preprocessing
from controller.project_controller.projects.base.data_ingestion import data_loader_prediction
from controller.project_controller.projects.base.Prediction_Raw_Data_Validation.predictionDataValidation import \
    PredictionDataValidation
from logging_layer.logger.logger import AppLogger
from project_library_layer.initializer.initializer import Initializer
from integration_layer.file_management.file_manager import FileManager
from exception_layer.generic_exception.generic_exception import GenericException as PredictFromModelException
import sys

class Prediction:

    def __init__(self, project_id, executed_by, execution_id, cloud_storage,socket_io=None):
        try:
            self.log_writer = AppLogger(project_id=project_id, executed_by=executed_by,
                                        execution_id=execution_id,socket_io=socket_io)
            self.file_object = FileManager(cloud_storage)
            self.initializer = Initializer()
            self.log_writer.log_database = self.initializer.get_prediction_database_name()
            self.log_writer.log_collection_name = self.initializer.get_prediction_main_log_collection_name()
            self.project_id = project_id
            self.socket_io = socket_io
            self.pred_data_val = PredictionDataValidation(project_id=project_id, prediction_file_path=None,
                                                          executed_by=executed_by, execution_id=execution_id,
                                                          cloud_storage=cloud_storage,socket_io=socket_io)
        except Exception as e:
            predict_model_exception = PredictFromModelException(
                "Failed during object instantiation in module [{0}] class [{1}] method [{2}]"
                    .format(self.__module__, Prediction.__name__,
                            self.__init__.__name__))
            raise Exception(predict_model_exception.error_message_detail(str(e), sys)) from e

    def prediction_from_model(self):

        try:
            self.pred_data_val.delete_prediction_file()  # deletes the existing prediction file from last run!
            self.log_writer.log('Start of Prediction')
            data_getter = data_loader_prediction.DataGetterPrediction(project_id=self.project_id,
                                                                      file_object=self.file_object,
                                                                      logger_object=self.log_writer)
            data = data_getter.get_data()

            if not isinstance(data, pd.DataFrame):
                raise Exception("prediction data not loaded successfully into pandas data frame.")
            first_column_name = data.columns[0]

            preprocessor = preprocessing.Preprocessor(file_object=self.file_object, logger_object=self.log_writer,
                                                      project_id=self.project_id)
            data=preprocessor.remove_null_string(data)

            is_null_present, cols_with_missing_values = preprocessor.is_null_present_in_columns(data)
            if is_null_present:
                data = preprocessor.impute_missing_values(data)

            cols_to_drop = preprocessor.get_columns_with_zero_std_deviation(data)
            data = preprocessor.remove_columns(data, cols_to_drop)
            file_loader = file_methods.FileOperation(project_id=self.project_id, file_object=self.file_object,
                                                     logger_object=self.log_writer)
            kmean_folder_name = self.initializer.get_kmean_folder_name()
            kmeans = file_loader.load_model(kmean_folder_name)

            clusters = kmeans.predict(
                data.drop([first_column_name], axis=1))  # drops the first column for cluster prediction

            data['clusters'] = clusters
            clusters = data['clusters'].unique()
            prediction_file_path = self.initializer.get_prediction_output_file_path(self.project_id)
            prediction_file_name = self.initializer.get_prediction_output_file_name()
            result = pd.DataFrame()  # we can remove it but last line we are trying to return hence creating empty result

            for i in clusters:
                cluster_data = data[data['clusters'] == i]
                # wafer_names = list(cluster_data['Wafer'])
                record_identifier = list(cluster_data[first_column_name])
                # cluster_data = data.drop(labels=['Wafer'], axis=1)
                cluster_data = data.drop(labels=[first_column_name], axis=1)
                cluster_data = cluster_data.drop(['clusters'], axis=1)
                model_name = file_loader.find_correct_model_file(str(i))
                model = file_loader.load_model(model_name)

                result = list(model.predict(cluster_data))
                result = pd.DataFrame(list(zip(record_identifier, result)),
                                          columns=[first_column_name, 'Prediction'])
                result.reset_index(drop=True, inplace=True)

                response = self.file_object.read_file_content(prediction_file_path, prediction_file_name)
                if not response['status']:
                    self.file_object.write_file_content(prediction_file_path, prediction_file_name, result)
                else:
                    existing_prediction = response['file_content']
                    if isinstance(existing_prediction, pd.DataFrame):
                        final_result = existing_prediction.append(result)
                        final_result.reset_index(drop=True, inplace=True)
                        self.file_object.write_file_content(prediction_file_path, prediction_file_name, final_result,over_write=True)

            self.log_writer.log('End of Prediction')

            return "{}/{}".format(prediction_file_path, prediction_file_name)

        except Exception as e:
            predict_model_exception = PredictFromModelException(
                "Failed during prediction in module [{0}] class [{1}] method [{2}]"
                    .format(self.__module__, Prediction.__name__,
                            self.prediction_from_model.__name__))
            raise Exception(predict_model_exception.error_message_detail(str(e), sys)) from e


def summations(value: int):
  ''' Calculates how many different ways can number be written
  as a sum of at least two positive integers \n
    Args:
      value: integer to find number of summations for
    Returns:
      number of summations, int '''

  ways = [1] + [0 for _ in range(value)]
  for number in range(1, value):
    for addend in range(number, value + 1):
      ways[addend] += ways[addend - number]
  # the last element is the answer
  return ways[-1]

# print(summations(5))