class Vertex:
    def __init__(self):
        """
        _links - список связей с другими вершинами графа (список объектов класса Link)
        """
        self._links: list = []

    @property
    def links(self):
        return self._links

class Link:
    def __init__(self, v1, v2):
        """
        _v1, _v2 - ссылки на объекты класса Vertex, которые соединяются данной связью
        _dist - длина связи (по умолчанию 1); это может быть длина пути, время в пути и др
        """
        self._v1 = v1
        self._v2 = v2
        self._dist = 1

    def __eq__(self, other):
        return self.v1 in (other.v1, other.v2) and self.v2 in (other.v1, other.v2)

    @property
    def v1(self):
        return self._v1

    @property
    def v2(self):
        return self._v2

    @property
    def dist(self):
        return self._dist

    @dist.setter
    def dist(self, x):
        self._dist = x

class LinkedGraph:
    def __init__(self):
        """
        _links - список из всех связей графа (из объектов класса Link)
        _vertex - список из всех вершин графа (из объектов класса Vertex)
        """
        self._links: list = []
        self._vertex: list = []

    def add_vertex(self, v):
        """Добавление новой вершины v в список _vertex (если она там отсутствует)"""
        if v not in self._vertex:
            self._vertex.append(v)

    def add_link(self, link):
        """Добавление новой связи link в список _links (если объект link с указанными вершинами в списке отсутствует)"""
        if link not in self._links:
            self._links.append(link)
        self.add_vertex(link.v1)
        self.add_vertex(link.v2)
        link.v1.links.append(link)
        link.v2.links.append(link)

    def find_path(self, start_v, stop_v):
        """Поиск кратчайшего маршрута из вершины start_v в вершину stop_v"""
        self.start_v = start_v
        self.stop_v = stop_v
        return self._next(self.start_v, None, [], [])

    def _dist_path(self, links):
        return sum([x.dist for x in links if x is not None])

    def _next(self, start_v, link_prew, c_path, c_links):
        c_path += [start_v]
        if link_prew:
            c_links += [link_prew]
        if start_v == self.stop_v:
            return c_path, c_links
        len_path = -1
        best_path = []
        best_links = []
        for link in start_v.links:
            path = []
            links = []
            if link.v1 not in c_path:
                path, links = self._next(link.v1, link, c_path[:], c_links[:])
            elif link.v2 not in c_path:
                path, links = self._next(link.v2, link, c_path[:], c_links[:])
            if self.stop_v in path and (len_path > self._dist_path(links) or len_path == -1):
                len_path = self._dist_path(links)
                best_path = path[:]
                best_links = links[:]
        return best_path, best_links

class Station(Vertex):
    def __init__(self, name):
        super().__init__()
        self.name = name

    def __str__(self):
        return f"{self.name}"

    def __repr__(self):
        return f"{self.name}"

class LinkMetro(Link):
    def __init__(self, v1, v2, dist):
        super().__init__(v1, v2)
        self._dist = dist

map_metro = LinkedGraph()
v1 = Station("Сретенский бульвар")
v2 = Station("Тургеневская")
v3 = Station("Чистые пруды")
v4 = Station("Лубянка")
v5 = Station("Кузнецкий мост")
v6 = Station("Китай-город 1")
v7 = Station("Китай-город 2")

map_metro.add_link(LinkMetro(v1, v2, 1))
map_metro.add_link(LinkMetro(v2, v3, 1))
map_metro.add_link(LinkMetro(v1, v3, 1))

map_metro.add_link(LinkMetro(v4, v5, 1))
map_metro.add_link(LinkMetro(v6, v7, 1))

map_metro.add_link(LinkMetro(v2, v7, 5))
map_metro.add_link(LinkMetro(v3, v4, 3))
map_metro.add_link(LinkMetro(v5, v6, 3))

print(len(map_metro._links))
print(len(map_metro._vertex))
path = map_metro.find_path(v1, v6)  # от сретенского бульвара до китай-город 1
print(path[0])    # [Сретенский бульвар, Тургеневская, Китай-город 2, Китай-город 1]
print(sum([x.dist for x in path[1]]))  # 7


import numpy as np

def skew_symmetric(v):
  """
  Returns the skew symmetric matrix [v] from vector `v`.\n
  [v] acts on vectors w such that [v].w = v x w

  Parameters
  ----------
  v : array_like
    The 3x1 vector from which to construct the skew-symmetric matrix.

  Returns
  -------
  [v] : ndarray
    The 3x3 skew-symmetric matrix associated to `v`.
  """

  return np.array([
    [  0  , -v[2],  v[1]],
    [ v[2],   0  , -v[0]],
    [-v[1],  v[0],   0  ]
  ])

def constrain(x, x_max, x_min=None):
  """
  Constrans a given number between a min and max value.

  Parameters
  ----------
  x : scalar
    The number to constrain.
  x_max : scalar
    The upper bound for the constrain.
  x_min : scalar, default=None
    The lower bound for the constrain. If None, defaults to -`x_max`.

  Returns
  -------
  scalar
    The constrained number.
  """

  if x_min is None:
    x_min = -x_max
  return min(max(x, x_min), x_max)


from bson.objectid import ObjectId

from flask import Flask, request
from flask_caching import Cache
from flask_pymongo import pymongo
from flask_restplus import Api, Resource

from authentication import authenticate
from constants import DEBUG, MONGODB_URL, SECRET_KEY, DEFAULT_PAGE_LIMIT, DEBUG
from customs import custom_response, custom_paginated_response
from database import initialize_db, mongo
from registration import registration_bp

app = Flask(__name__)
app.secret_key = SECRET_KEY
app.config["MONGO_URI"] = MONGODB_URL

api = Api(app)
app.register_blueprint(registration_bp)
cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache'})
name_space = api.namespace('api', description='Main APIs')
initialize_db(app)

@name_space.route('/movies/')
class MoviesApi(Resource):
    @cache.cached(timeout=500)
    def get(self):
        search_param = request.args.get('search')
        filter_param = {"$text": {"$search": search_param}} if search_param else None

        page_limit = int(request.args.get('limit', DEFAULT_PAGE_LIMIT))
        offset = int(request.args.get('offset', 0))

        movies = mongo.db.movies.find(filter_param).sort('_id', pymongo.DESCENDING)
        return custom_paginated_response([movie for movie in movies], request.base_url, offset, page_limit)
        # if you want to return as html page directly!
        # movies = respnose.json['data']
        # return render_template("movies.html", len = len(movies), movies = movies)

    @authenticate
    def post(self):
        movie = request.json
        if mongo.db.movies.find_one({'name': movie.get('name'), 'director': movie['director']}):
            return custom_response([], 'Duplicate Movie Being Created', 412)
        mongo.db.movies.insert_one(movie)
        return custom_response(movie, 'Object created Successfully.', 201)

@name_space.route('/movies/<id>')
class MovieApi(Resource):
    @authenticate
    def put(self, id):
        movie = request.json
        id = movie.pop('_id', None)
        if not mongo.db.movies.find_one({"_id": ObjectId(id)}):
            return custom_response([], 'Movie not found', 412)

        mongo.db.movies.update_one({"_id": ObjectId(id)}, {"$set": movie})
        return custom_response([], 'Object Updated Successfully.', 412)

    @authenticate
    def delete(self, id):
        delete_result = mongo.db.movies.delete_one({"_id": ObjectId(id)})

        if delete_result.deleted_count == 1:
            return custom_response([], 'Success.', 201)

        return custom_response([], 'Movie Not found', 412)

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


from django import forms
from .models import Usuario

class UsuarioForm(forms.ModelForm):
    class Meta:
        model = Usuario
        fields = [
            'nombre',
            'correo',
            'contraseña',
            'direccion',
            'barrio',
            'foto',
        ]

        labels = {
            'nombre' : 'Nombre',
            'correo' : 'Correo',
            'contraseña' : 'Contraseña',
            'direccion' : 'Direccion',
            'barrio':'Barrio',
            'foto':'Foto',
        }


import importlib
import math

import pytest

from pycel.excelutil import (
    AddressCell,
    AddressRange,
    DIV0,
    NUM_ERROR,
    VALUE_ERROR,
)
from pycel.lib.function_helpers import (
    apply_meta,
    cse_array_wrapper,
    error_string_wrapper,
    excel_helper,
    excel_math_func,
    load_functions,
)

DATA = (
    (1, 2),
    (3, 4),
)

@pytest.mark.parametrize(
    'arg_num, f_args, result', (
        (0, (1,), 2),
        (1, (0, 1), 2),
        (0, (DATA, ), ((2, 3), (4, 5))),
        (1, (1, DATA), ((2, 3), (4, 5))),
    )
)
def test_cse_array_wrapper(arg_num, f_args, result):

    def f_test(*args):
        return args[arg_num] + 1

    assert cse_array_wrapper(f_test, arg_num)(*f_args) == result

@pytest.mark.parametrize(
    'arg_nums, f_args, result', (
        (((0, 1, 2, 3)), ((0, NUM_ERROR), (DIV0, NUM_ERROR)), NUM_ERROR),
        ((0, 1), (DIV0, 1), DIV0),
        ((0, 1), (1, DIV0), DIV0),
        ((0, 1), (NUM_ERROR, DIV0), NUM_ERROR),
        ((0, 1), (DIV0, NUM_ERROR), DIV0),
        ((0,), (1, DIV0), "args: (1, '#DIV/0!')"),
        ((1,), (1, DIV0), DIV0),
    )
)
def test_error_string_wrapper(arg_nums, f_args, result):

    def f_test(*args):
        return f'args: {args}'

    assert error_string_wrapper(f_test, arg_nums)(*f_args) == result

@pytest.mark.parametrize(
    'value, result', (
        (1, 1),
        (DIV0, DIV0),
        (None, 0),
        ('1.1', 1.1),
        ('xyzzy', VALUE_ERROR),
    )
)
def test_math_wrap(value, result):
    assert apply_meta(
        excel_math_func(lambda x: x), name_space={})[0](value) == result

def test_math_wrap_domain_error():
    func = apply_meta(excel_math_func(lambda x: math.log(x)), name_space={})[0]
    assert func(-1) == NUM_ERROR

@pytest.mark.parametrize(
    'value, result', (
        ((1, 2, 3), (1, 2, 3)),
        ((AddressRange('A1:B1'),) * 3,
         ('R:A1:B1', AddressRange('A1:B1'), 'R:A1:B1')),
        ((AddressCell('A1'),) * 3,
         ('C:A1', AddressCell('A1'), 'C:A1')),
    )
)
def test_ref_wrap(value, result):
    def r_test(*args):
        return args

    name_space = locals()
    name_space['_R_'] = lambda a: f'R:{a}'
    name_space['_C_'] = lambda a: f'C:{a}'

    func = apply_meta(
        excel_helper(ref_params=1)(r_test), name_space=name_space)[0]
    assert func(*value) == result

def test_apply_meta_nothing_active():

    def a_test_func(x):
        return x

    func = apply_meta(excel_helper(
        err_str_params=None, ref_params=-1)(a_test_func), name_space={})[0]
    assert func == a_test_func

def test_apply_meta_kwargs():

    def a_test_func(**x):
        pass

    with pytest.raises(RuntimeError,
                       match=r'Function a_test_func: \*\*kwargs not allowed in signature'):
        apply_meta(excel_helper()(a_test_func))

def test_load_functions():

    modules = (
        importlib.import_module('pycel.excellib'),
        importlib.import_module('pycel.lib.date_time'),
        importlib.import_module('pycel.lib.logical'),
        importlib.import_module('math'),
    )

    namespace = locals()

    names = 'degrees if_ junk'.split()
    missing = load_functions(names, namespace, modules)
    assert missing == {'junk'}
    assert 'degrees' in namespace
    assert 'if_' in namespace

    names = 'radians if_ junk'.split()
    missing = load_functions(names, namespace, modules)
    assert missing == {'junk'}
    assert 'radians' in namespace

    assert namespace['radians'](180) == math.pi
    assert namespace['radians'](((180, 360),)) == ((math.pi, 2 * math.pi),)

    assert namespace['if_'](0, 'Y', 'N') == 'N'
    assert namespace['if_'](((0, 1),), 'Y', 'N') == (('N', 'Y'),)

    missing = load_functions(['log'], namespace, modules)
    assert not missing
    assert namespace['log'](DIV0) == DIV0


import pandas as pd

def percent_trades_profit(result_df):
    total_trades = 0
    profit_trades = 0
    for i in range(len(result_df)):
        if result_df.loc[i, 'P&L'] > 0: #Profit
            total_trades += 1
            profit_trades += 1
        elif result_df.loc[i, 'P&L'] < 0:  #Loss
            total_trades += 1
        else:  #No Trade.
            pass
    if total_trades > 0:
        profitable_trades = (profit_trades/total_trades) * 100
    else:
        profitable_trades = 0

    return profitable_trades

def stock_current_status(df):
    stock_status = []
    buy_location = 0
    sell_location = 0
    for i in reversed(range(len(df))):
        if buy_location == 0 & sell_location == 0:
            if float(df.loc[i, 'Adj Close']) - float(df.loc[i, 'Buy_Signal_Price']) == 0 or float(df.loc[i, 'Close']) - float(df.loc[i, 'Buy_Signal_Price']) == 0:
                buy_location = i
            if float(df.loc[i, 'Adj Close']) - float(df.loc[i, 'Sell_Signal_Price']) == 0 or float(df.loc[i, 'Close']) - float(df.loc[i, 'Sell_Signal_Price']) == 0:
                sell_location = i
        else:
            break

    if buy_location > sell_location:
        #1.SIGNAL TYPE.
        actual_signal = 'Buy Signal'
        stock_status.append('Buy')
        #2.SIGNAL PRICE.
        stock_status.append(float(df.loc[buy_location, 'Buy_Signal_Price']))
        diff = float(df['Adj Close'].iloc[-1]) - float(df.loc[buy_location, 'Buy_Signal_Price'])
        days = len(df) - buy_location
    if sell_location > buy_location:
        #1.SIGNAL TYPE.
        actual_signal = 'Sell Signal'
        stock_status.append('Sell')
        #2.SIGNAL PRICE.
        stock_status.append(float(df.loc[sell_location, 'Sell_Signal_Price']))
        diff = float(df['Adj Close'].iloc[-1]) - float(df.loc[sell_location, 'Sell_Signal_Price'])
        days = len(df) - sell_location
    if sell_location == buy_location:
        actual_signal = 'No Signal'
        stock_status.append('NIL')
        stock_status.append(float(0))
        diff = 0
        days = 'N/A'

    #3.CLOSE PRICE
    stock_status.append(float(df['Adj Close'].iloc[-1]))

    #4.PERCENTAGE DIFFERENCE.
    percent_decimals = (diff / float(df['Adj Close'].iloc[-1]))
    percent = percent_decimals * 100
    stock_status.append(float(percent_decimals))

    #5.REMARKS.
    remarks = '{}, {} days before.'.format(actual_signal, days)
    stock_status.append(remarks)

    return stock_status

def print_report(stock, col, df, bt_data, stock_summary, stock_status, stkplt_hlink, strategy_hlinks):
    result_df, cash_in_hand = bt_data[0], bt_data[1]
    stake, portfolio_values = bt_data[2], bt_data[3]
    bt_hlink = bt_data[4]
    stock_summary.loc['Current Stock Details', col] = ''
    stock_summary.loc['Last Signal', col] = stock_status[0]
    stock_summary.loc['Last Signal Price(Rs.)', col] = stock_status[1]
    stock_summary.loc['Last Close Price(Rs.)', col] = stock_status[2]
    stock_summary.loc['Price Difference(%)', col] = stock_status[3]
    stock_summary.loc['Remarks', col] = stock_status[4]
    stock_summary.loc['Stock Plot', col] = stkplt_hlink
    stock_summary.loc['Strategy Plot', col] = strategy_hlinks[0]
    stock_summary.loc['Signals Plot', col] = strategy_hlinks[1]
    stock_summary.loc['Backtest Results', col] = ''
    stock_summary.loc['Starting Date', col] = str(df.loc[0, 'Date'])
    stock_summary.loc['Ending Date', col] = str(df.loc[len(df)-1, 'Date'])
    stock_summary.loc['Invested Money(Rs.)', col] = cash_in_hand
    stock_summary.loc['Percent used to trade(%)', col] = stake
    stock_summary.loc['Final Portfolio Value(Rs.)', col] = portfolio_values[-1]
    stock_summary.loc['Profit & Loss(%)', col] = ((portfolio_values[-1]-cash_in_hand)/cash_in_hand)
    stock_summary.loc['Positive Trade Percentage(%)', col] = percent_trades_profit(result_df)/100
    stock_summary.loc['Backtest Plot', col] = bt_hlink
    '''print('-----------BackTesting Results-----------')
    print('Strategy                             : {}'.format(strategy))
    print('Stock                                : {}'.format(stock))
    print('Starting Date                        : {}'.format(str(df.loc[0, 'Date'])))
    print('Ending Date                          : {}'.format(str(df.loc[len(df)-1, 'Date'])))
    print('Invested Money                       : Rs.{:.2f}'.format(cash_in_hand))
    print('Percent used to trade                : {:.2f}%'.format(stake * 100))
    print('Final Portfolio Value                : Rs.{:.2f}'.format(portfolio_values[-1]))
    print('Profit & Loss                        : {:.2f}%'.format(((portfolio_values[-1]-cash_in_hand)/cash_in_hand)*100))
    print('Percentage of Trades ended in Profit : {:.2f}%'.format(percent_trades_profit(result_df)))'''


# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

class VendingMachine:
    def __init__(self, num_items, item_price):
        self.NumItems = num_items
        self.ItemPrice = item_price

    def buy(self, num_items, num_coins) -> int:
        if self.NumItems < num_items:
            raise ValueError("Not enough items in the machine")
        if self.ItemPrice * num_items > num_coins:
            raise ValueError("Not enough coins")

        self.NumItems -= num_items

        return num_coins - num_items * self.ItemPrice

def transformSentence(sentence: str) -> str:
    inputs = sentence.split(sep=' ')
    outputs = []
    for input in inputs:
        output = input[0]
        for i in range(1, len(input)):
            if input[i] > input[i - 1]:
                output += input[i].upper()
            elif input[i] < input[i - 1]:
                output += input[i].lower()
            else:
                output += input[i]
        outputs.append(output)

    return ' '.join(outputs)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    i = 'c'
    h = 'b'
    print(i > h)
    input = "a blue MOON"
    print(transformSentence(input))
# See PyCharm help at https://www.jetbrains.com/help/pycharm/


def move_zeros(x):
    # print('1',(x))
    penampungan0=[]
    for i in x:
        if type(i) == bool:
            continue
        elif type(i)==str:
            continue
        elif type(i)==int:
            if i == 0 :
                penampungan0.append(i)
                x.pop(i)

    # print('2',(x))
    # print(penampungan0)
    x.extend(penampungan0)
    print((x))
    print('')
move_zeros([False,1,0,1,2,0,1,3,'a'])
move_zeros([0,0,0,'Test',0,3,'a',True,False])
move_zeros([0,True,True,False,'a','b',1,1,1])


import sys

n, m, k = map(int, input().split())

class lazytree():
    def __init__(self, nums, start, end):
        self.lazy = 0
        self.start = start
        self.end = end
        if start == end:
            self.sum = nums[start]
        else:
            self.left = lazytree(nums,start, (start+end)//2)
            self.right = lazytree(nums,(start+end)//2+1, end)
            self.sum = self.left.sum+self.right.sum
    def applylazy(self):
        if self.lazy != 0:
            if self.start != self.end:
                self.left.lazy += self.lazy
                self.right.lazy += self.lazy
            self.sum += self.lazy*(self.end-self.start+1)
            self.lazy = 0
    def findsum(self, start, end):
        self.applylazy()
        if start == self.start and end == self.end:
            return self.sum

        half = (self.start+self.end)//2+1
        if start < half:
            if end < half:
                return self.left.findsum(start,end)
            else:
                return self.left.findsum(start,half-1)+self.right.findsum(half,end)
        else:
            return self.right.findsum(start,end)
    def updatesum(self, start, end, v):
        self.applylazy()
        if start == self.start and end == self.end:
            if self.start != self.end:
                self.left.lazy += v
                self.right.lazy += v
                self.sum += v*(end-start+1)
            else:
                self.sum += v
        else:
            half = (self.start+self.end)//2+1
            if start < half:
                if end < half:
                    self.left.updatesum(start,end,v)
                    self.right.applylazy()
                else:
                    self.left.updatesum(start,half-1,v)
                    self.right.updatesum(half,end,v)
            else:
                self.left.applylazy()
                self.right.updatesum(start,end,v)
            self.sum = self.left.sum+self.right.sum

nums = list(map(int,sys.stdin.readline().split()))

segtree = lazytree(nums,0,len(nums)-1)

for _ in range(m+k):
    line = list(map(int, sys.stdin.readline().strip().split()))
    if line[0] == 2:
        segtree.updatesum(line[1]-1,line[2]-1,line[3])
    else:
        print(segtree.findsum(line[1]-1,line[2]-1))


from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, list, map, next, object, oct, open, pow, range, round, str, super, zip)

from . import filters

from . import FoostacheParser
from . import FoostacheParserVisitor

class PathError(BaseException):
    pass

class Visitor(FoostacheParserVisitor.FoostacheParserVisitor):
    TYPES = {
        "string": (str,),
        "array": (list,),
        "object": (dict,),
        "number": (int, float),
        "boolean": (bool,),
        "null": (type(None),)
    }

    @staticmethod
    def _is_type(value, type_string):
        assert type_string in Visitor.TYPES
        return isinstance(value, Visitor.TYPES[type_string])

    FILTERMAP = {
        "html": filters.html5,
        "uri": filters.uri_component,
        "jss": filters.js_string
    }

    def __init__(self, context):
        self._contexts = list()
        self._contexts.append(context)
        self._filters = list()
        self._iterates = list()

    # Visit a parse tree produced by FoostacheParser#template.
    def visitTemplate(self, ctx):
        return self.visit(ctx.statements())

    # Visit a parse tree produced by FoostacheParser#statements.
    def visitStatements(self, ctx):
        results = list()
        for statement in ctx.statement():
            results.append(self.visit(statement))
        return "".join(results)

    # Visit a parse tree produced by FoostacheParser#statement.
    def visitStatement(self, ctx):
        return self.visitChildren(ctx)

    # Visit a parse tree produced by FoostacheParser#rawText.
    def visitRawText(self, ctx):
        return ctx.getText()

    # Visit a parse tree produced by FoostacheParser#literalText.
    def visitLiteral(self, ctx):
        return ctx.literalText().getText()

    def apply_filters(self, s):
        for f in reversed(self._filters):
            if f:
                s = f(s)
        return s

    # Visit a parse tree produced by FoostacheParser#stringField.
    def visitStringField(self, ctx):
        value = self.visit(ctx.path())
        for f in ctx.inlineFilter():
            g = Visitor.FILTERMAP.get(self.visit(f), None)
            if g:
                value = g(value)
        value = self.apply_filters(value)
        return value

    # Visit a parse tree produced by FoostacheParser#numberField.
    def visitNumberField(self, ctx):
        value = self.visit(ctx.path())
        value = self.visit(ctx.numberFormat()).format(value)
        for f in ctx.inlineFilter():
            g = Visitor.FILTERMAP.get(self.visit(f), None)
            if g:
                value = g(value)
        value = self.apply_filters(value)
        return str(value)

    def visitNumberFormat(self, ctx):
        # PERCENT (flags=ZERO)? (width=PINTEGERN)? (DOTN precision=PINTEGERN)? specifier=NUMBER_SPECIFIER
        if ctx.specifier.text == "d":
            if ctx.width:
                if ctx.flags:
                    return "{{:0{}d}}".format(ctx.width.text)
                else:
                    return "{{:{}d}}".format(ctx.width.text)
            return "{:d}"
        else:  # if ctx.specifier.text == "f":
            p = "6"
            if ctx.precision:
                p = ctx.precision.text
            if ctx.width:
                if ctx.flags:
                    return "{{:0{}.{}f}}".format(ctx.width.text, p)
                else:
                    return "{{:{}.{}f}}".format(ctx.width.text, p)
            return "{{:.{}f}}".format(p)

    def visitInlineFilter(self, ctx):
        return ctx.ID().getText()

    # Visit a parse tree produced by FoostacheParser#ifBlock.
    def visitIfBlock(self, ctx):
        if self.visit(ctx.ifTag()):
            return self.visit(ctx.statements())
        for e in ctx.elseifBlock():
            if self.visit(e.elseifTag()):
                return self.visit(e.statements())
        if ctx.elseBlock():
            return self.visit(ctx.elseBlock().statements())
        return ""

    # Visit a parse tree produced by FoostacheParser#ifTag.
    def visitIfTag(self, ctx):
        return self.visit(ctx.expression())

    #    # Visit a parse tree produced by FoostacheParser#elseifBlock.
    #    def visitElseifBlock(self, ctx):
    #        return "" # self.visitChildren(ctx)

    # Visit a parse tree produced by FoostacheParser#elseifTag.
    def visitElseifTag(self, ctx):
        return self.visit(ctx.expression())

    #    # Visit a parse tree produced by FoostacheParser#elseBlock.
    #    def visitElseBlock(self, ctx):
    #        return "" # self.visitChildren(ctx)

    #    # Visit a parse tree produced by FoostacheParser#expression.
    #    def visitExpression(self, ctx):
    #        return self.visitChildren(ctx)

    def visitBoolExpression(self, ctx):
        # TODO confirm boolean
        return self.visit(ctx.path())

    def visitExistsExpression(self, ctx):
        try:
            self.visit(ctx.path())
            return True
        except PathError:
            return False

    def visitTypeExpression(self, ctx):
        value = self.visit(ctx.path())
        return self._is_type(value, ctx.TYPE().getText())

    def visitParenExpression(self, ctx):
        return self.visit(ctx.expression())

    def visitAndExpression(self, ctx):
        if not self.visit(ctx.expr1):
            return False
        else:
            return self.visit(ctx.expr2)

    def visitOrExpression(self, ctx):
        if self.visit(ctx.expr1):
            return True
        else:
            return self.visit(ctx.expr2)

    def visitNotExpression(self, ctx):
        return not self.visit(ctx.expression())

    def visitDotPath(self, ctx):
        if len(self._contexts) == 0:
            raise PathError("no context")
        return self._contexts[-1]

    def visitCaretPath(self, ctx):
        if len(ctx.CARET()) > len(self._contexts) - 1:
            raise PathError("no context")
        self._working_path = self._contexts[-1 - len(ctx.CARET())]
        self.visitChildren(ctx)
        result = self._working_path
        del self._working_path
        return result

    def visitQsObjectKey(self, ctx):
        if not self._is_type(self._working_path, "object"):
            raise PathError("not an object")

        chars = list()
        for t in ctx.getChildren():
            if t.symbol.type == FoostacheParser.FoostacheParser.CHARQS:
                chars.append(t.getText())
            elif t.symbol.type == FoostacheParser.FoostacheParser.ESCCHARQS:
                x = t.getText()
                if x[1] == "\"":
                    x = "\""
                elif x[1] == "\\":
                    x = "\\"
                elif x[1] == "/":
                    x = "/"
                elif x[1] == "b":
                    x = "\b"
                elif x[1] == "f":
                    x = "\f"
                elif x[1] == "n":
                    x = "\n"
                elif x[1] == "r":
                    x = "\r"
                elif x[1] == "t":
                    x = "\t"
                elif x[1] == "u":
                    x = chr(int(x[2:], 16))
                else:
                    assert False
                chars.append(x)
        key = "".join(chars)

        if key not in self._working_path:
            raise PathError("key {} not found in {}".format(ctx.getText(), self._working_path))

        self._working_path = self._working_path[key]

    def visitIdObjectKey(self, ctx):
        if not self._is_type(self._working_path, "object"):
            raise PathError("not an object")

        key = ctx.getText()

        if key not in self._working_path:
            raise PathError("key {} not found in {}".format(ctx.getText(), self._working_path))

        self._working_path = self._working_path[key]

    # Visit a parse tree produced by FoostacheParser#arrayIndex.
    def visitArrayIndex(self, ctx):
        if not self._is_type(self._working_path, "array"):
            raise PathError("not an array")

        index = int(ctx.getText())

        if index < 0:
            index = len(self._working_path) + index

        if (index < 0) or (index > len(self._working_path)):
            raise PathError("index {} out of range".format(ctx.getText()))

        self._working_path = self._working_path[index]

    # Visit a parse tree produced by FoostacheParser#withBlock.
    def visitWithBlock(self, ctx):
        self._contexts.append(self.visit(ctx.path()))
        value = self.visit(ctx.statements())
        self._contexts.pop()
        return value

    # Visit a parse tree produced by FoostacheParser#iterateBlock.
    def visitIterateBlock(self, ctx):
        array = self.visit(ctx.path())
        clauses = {
            "body": list(),
            "before": list(),
            "after": list(),
            "between": list(),
            "else": list()
        }
        self._iterates.append(clauses)
        for x in ctx.iterateClause():
            self.visit(x)
        results = list()

        (start, stop, step) = self.visit(ctx.indexRange())
        if start < 0:
            start = start + len(array)
        if stop is None:
            stop = len(array)
        elif stop < 0:
            stop = stop + len(array)
        if step is not None:
            r = list(range(start, stop, step))
        else:
            r = list(range(start, stop))

        if not array or not r:
            for x in clauses["else"]:
                results.append(self.visit(x))
        else:
            for x in clauses["before"]:
                results.append(self.visit(x))
            self._contexts.append(array[r[0]])
            results.append(self.visit(ctx.statements()))
            self._contexts.pop()
            for i in r[1:]:
                for x in clauses["between"]:
                    results.append(self.visit(x))
                self._contexts.append(array[i])
                results.append(self.visit(ctx.statements()))
                self._contexts.pop()
            for x in clauses["after"]:
                results.append(self.visit(x))
        return "".join(results)

    # Visit a parse tree produced by FoostacheParser#indexRange.
    def visitIndexRange(self, ctx):
        start = 0
        if ctx.INTEGER():
            start = int(ctx.INTEGER().getText())
        (stop, step) = (None, None)
        if ctx.indexRangeB():
            (stop, step) = self.visit(ctx.indexRangeB())
        return start, stop, step

    # Visit a parse tree produced by FoostacheParser#indexRange.
    def visitIndexRangeB(self, ctx):
        stop = None
        if ctx.INTEGER():
            stop = int(ctx.INTEGER().getText())
        step = None
        if ctx.indexRangeC():
            step = self.visit(ctx.indexRangeC())
        return stop, step

    # Visit a parse tree produced by FoostacheParser#indexRange.
    def visitIndexRangeC(self, ctx):
        value = int(ctx.INTEGER().getText())
        if value <= 0:
            return None
        return value

    # Visit a parse tree produced by FoostacheParser#iterateClause.
    def visitIterateClause(self, ctx):
        return self.visitChildren(ctx)

    # Visit a parse tree produced by FoostacheParser#iterateBeforeClause.
    def visitIterateBeforeClause(self, ctx):
        self._iterates[-1]["before"].append(ctx.statements())
        return None  # self.visitChildren(ctx)

    # Visit a parse tree produced by FoostacheParser#iterateAfterClause.
    def visitIterateAfterClause(self, ctx):
        self._iterates[-1]["after"].append(ctx.statements())
        return None  # self.visitChildren(ctx)

    # Visit a parse tree produced by FoostacheParser#iterateBetweenClause.
    def visitIterateBetweenClause(self, ctx):
        self._iterates[-1]["between"].append(ctx.statements())
        return None  # self.visitChildren(ctx)

    # Visit a parse tree produced by FoostacheParser#iterateElseClause.
    def visitIterateElseClause(self, ctx):
        self._iterates[-1]["else"].append(ctx.statements())
        return None  # self.visitChildren(ctx)

    # Visit a parse tree produced by FoostacheParser#filterBlock.
    def visitFilterBlock(self, ctx):
        self._filters.append(Visitor.FILTERMAP.get(ctx.filterName.text, None))
        value = self.visit(ctx.statements())
        self._filters.pop()
        return value


from sets import Set
import thread
from threading import Thread

class Lockable:
   def __init__(self):
        self.mutex = thread.allocate_lock()

def locked(method):
   def _locked(self, *args, **kwargs):
       self.mutex.acquire()
       try:
           result = method(self, *args, **kwargs)
       finally:
           self.mutex.release()
       return result
   return _locked

class TaggedSignal:
   def __init__(self, names):
       self.names = names
       self.lock = thread.allocate_lock()
       self.lock.acquire()
       self.tag = None

   def set(self, tag):
       self.tag = tag
       self.lock.release()

   def wait(self):
       self.lock.acquire()
       self.lock.release()
       return self.tag

class MultiQueue(Lockable):
    def __init__(self, maxsize):
        self.maxsize = maxsize
        self.queues = {}
        self.writeLocks = {}
        self.waitingLists = {}
        Lockable.__init__(self)

    def put(self, name, value):
        writeLock = self.getWriteLock(name)
        must_release = True
        writeLock.acquire()
        try:
            must_release = self._put(name, value, writeLock)
        finally:
            if must_release:
                writeLock.release()

    def _put(self, name, value, writeLock):
        if self.waitingLists.has_key(name):
            self.notify_signal(name, value)
            return True
        else:
            queue = self.getQueue(name)
            queue.append(value)
            return len(queue)<self.maxsize
    _put = locked(_put)

    def notify_signal(self, name, value):
        signal = self.waitingLists[name][0]
        signal.set((name, value))
        for name in signal.names:
            waitingList = self.waitingLists[name]
            waitingList.remove(signal)
            if len(waitingList)==0:
                del self.waitingLists[name]

    def get(self, *names):
        must_wait, result = self._get(names)
        if must_wait:
            return result.wait()
        else:
            return result

    def _get(self, names):
        populatedQueues = Set(self.queues.keys()).intersection(names)
        if len(populatedQueues)==0:
            return True, self.createSignal(names)
        else:
            return False, self.getValue(populatedQueues.pop())
    _get = locked(_get)

    def getValue(self, queueName):
        queue = self.queues[queueName]
        was_full = len(queue)==self.maxsize
        value = queue.pop(0)
        if len(queue)==0:
            del self.queues[queueName]
            del self.writeLocks[queueName]
        else:
            if was_full:
                self.writeLocks[queueName].release()
        return queueName, value

    def createSignal(self, names):
        signal = TaggedSignal(names)
        for name in names:
            try:
                waitingList = self.waitingLists[name]
            except KeyError:
                waitingList = self.waitingLists[name] = []
            waitingList.append(signal)
        return signal

    def getWriteLock(self, name):
        try:
            writeLock = self.writeLocks[name]
        except KeyError:
            writeLock = self.writeLocks[name] = thread.allocate_lock()
        return writeLock
    getWriteLock = locked(getWriteLock)

    def getQueue(self, name):
        try:
            queue = self.queues[name]
        except KeyError:
            queue = self.queues[name] = []
        return queue


from typing import List, Optional, Type, Union

from spg.components.agents.part import PhysicalPart
from spg.core.collision import CollisionTypes
from spg.core.sensor import Sensor

from ..agents.device import Device
from ..agents.device.communicator import Communicator
from .element import ZoneElement

class Disabler(ZoneElement):
    def __init__(self, disable_cls: Union[List[Type[Device]], Type[Device]]):

        super().__init__(filename=":spg:platformer/tiles/area_forbidden.png")

        self._disable_cls = disable_cls

    @property
    def _collision_type(self):
        return CollisionTypes.DISABLER

    def disable(self, device: Device):

        if isinstance(device, self._disable_cls):
            device.disable()

class SensorDisabler(Disabler):
    def __init__(
        self, sensors: Optional[Union[List[Type[Sensor]], Type[Sensor]]] = None
    ):

        if not sensors:
            sensors = Sensor

        super().__init__(disable_cls=sensors)

class PartDisabler(Disabler):
    def __init__(
        self,
        parts: Optional[Union[List[Type[PhysicalPart]], Type[PhysicalPart]]] = None,
    ):

        if not parts:
            parts = PhysicalPart

        super().__init__(disable_cls=parts)

class CommunicatorDisabler(Disabler):
    def __init__(
        self,
        communicators: Optional[
            Union[List[Type[Communicator]], Type[Communicator]]
        ] = None,
    ):

        if not communicators:
            communicators = Communicator

        super().__init__(disable_cls=communicators)


import os
import time

with open('day-02.data') as f:
    data = [line.rstrip('\n') for line in f]

def print_sep_line():
    print('+---+---+---+')

def print_pad(current: int, code):
    os.system('clear')

    print_sep_line()
    for y in range(3):
        print('|', end='')
        for x in range(3):
            number = (x + 1) + 3 * y
            if current == number:
                print(f' \033[96m\033[1m{number}\033[0m ', end='')
            else:
                print(f' {number} ', end='')
            print('|', end='')
        print()
        print_sep_line()
    print()
    print()
    print(code)

def action():
    pos = 5

    result = ''

    for line in data:
        for c in line:
            if c == 'U':
                new_pos = pos - 3
            elif c == 'L':
                if pos != 4 and pos != 7:
                    new_pos = pos - 1
            elif c == 'D':
                new_pos = pos + 3
            elif c == 'R':
                if pos != 3 and pos != 6:
                    new_pos = pos + 1

            if 1 <= new_pos <= 9:
                pos = new_pos

            # print_pad(pos, result)
            # time.sleep(0.0001)

        result = f'{result}{pos}'

        print_pad(pos, result)
        time.sleep(0.1)

    print_pad(pos, result)

action()

# 67486 to high


import xgboost as xgb
from keras import Model
from keras.layers import Dense, Dropout, Input
from tensorflow.keras import regularizers

from src.models.training.base_model import BaseTrainObj
from src.models.training.xgb_model import XgboostTrainObj

def network_model(shape):
    x = Input(shape=(shape,), name="input")
    _model = Dense(300, activation='relu', kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4),
                   bias_regularizer=regularizers.l2(1e-4),
                   activity_regularizer=regularizers.l2(1e-5),name="dense_300")(x)
    _model = Dropout(rate=0.6,name="dropout_1")(_model)
    _model = Dense(200, activation='relu', kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4),
                   bias_regularizer=regularizers.l2(1e-4),
                   activity_regularizer=regularizers.l2(1e-5),name="dense_200")(_model)
    _model = Dropout(rate=0.6,name="dropout_2")(_model)
    _model = Dense(100, activation='relu',name="dense_100")(_model)
    _model = Dropout(rate=0.6,name="dropout_3")(_model)
    _model = Dense(20, activation='relu',name="dense_20")(_model)
    _model = Dense(1, activation='sigmoid',name="output")(_model)
    model = Model(x, _model, name="ann_model")
    return model

XGBS_PARAMS = {
    "objective": ["binary:hinge"],
    "booster": ["gbtree"],
    "eta": [0.1],
    'gamma': [0.5],
    'max_depth': range(2, 4, 2),
    'min_child_weight': [1],
    'subsample': [0.6],
    'colsample_bytree': [0.6],
    "lambda": [1],
    "n_jobs": [-1],
    "verbosity": 0,
    "silent": True,
}

def get_models_dict(shape):
    base_model = BaseTrainObj()
    base_model.set_model(network_model(shape))
    xbg_model = XgboostTrainObj()
    xbg_model.set_model(xgb.XGBClassifier(kwargs=XGBS_PARAMS))
    model_dict = {'base': base_model, 'xgb': xbg_model}
    return model_dict


import math
from typing import Optional, Tuple

import docker
import humanfriendly
import luigi
import netaddr
import pkg_resources
from docker.models.containers import Container
from docker.models.volumes import Volume
from docker.client import DockerClient
from jinja2 import Template

from exasol_integration_test_docker_environment.lib import PACKAGE_NAME
from exasol_integration_test_docker_environment.lib.base.docker_base_task import DockerBaseTask
from exasol_integration_test_docker_environment.lib.base.json_pickle_parameter import JsonPickleParameter
from exasol_integration_test_docker_environment.lib.base.still_running_logger import StillRunningLogger
from exasol_integration_test_docker_environment.lib.data.container_info import ContainerInfo
from exasol_integration_test_docker_environment.lib.data.database_info import DatabaseInfo
from exasol_integration_test_docker_environment.lib.data.docker_network_info import DockerNetworkInfo
from exasol_integration_test_docker_environment.lib.docker.images.create.utils.pull_log_handler import PullLogHandler
from exasol_integration_test_docker_environment.lib.docker.images.image_info import ImageInfo
from exasol_integration_test_docker_environment.lib.test_environment.db_version import DbVersion
from exasol_integration_test_docker_environment.lib.data.ssh_info import SshInfo
from exasol_integration_test_docker_environment.lib.test_environment.ports import (
    find_free_ports,
    Ports,
)
from exasol_integration_test_docker_environment.lib.test_environment.docker_container_copy import DockerContainerCopy
from exasol_integration_test_docker_environment.lib \
    .test_environment.parameter \
    .docker_db_test_environment_parameter import (
        DbOsAccess,
        DockerDBTestEnvironmentParameter,
)
from exasol_integration_test_docker_environment.lib.base.ssh_access import (
    SshKeyCache,
    SshKey,
)

CERTIFICATES_MOUNT_DIR = "/certificates"
CERTIFICATES_DEFAULT_DIR = "/exa/etc/ssl/"

def int_or_none(value: str) -> Optional[int]:
    return None if value is None else int(value)

class SpawnTestDockerDatabase(DockerBaseTask, DockerDBTestEnvironmentParameter):
    environment_name = luigi.Parameter()  # type: str
    db_container_name = luigi.Parameter()  # type: str
    attempt = luigi.IntParameter(1)  # type: int
    network_info = JsonPickleParameter(DockerNetworkInfo, significant=False)  # type: DockerNetworkInfo
    ip_address_index_in_subnet = luigi.IntParameter(significant=False)  # type: int
    docker_runtime = luigi.OptionalParameter(None, significant=False)  # type: str
    certificate_volume_name = luigi.OptionalParameter(None, significant=False)
    additional_db_parameter = luigi.ListParameter()
    ssh_user = luigi.Parameter("root")
    ssh_key_file = luigi.OptionalParameter(None, significant=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.ip_address_index_in_subnet < 0:
            raise Exception(
                "ip_address_index_in_subnet needs to be greater than 0 got %s"
                % self.ip_address_index_in_subnet)

        self.db_version = DbVersion.from_db_version_str(self.docker_db_image_version)
        self.docker_db_config_resource_name = f"docker_db_config/{self.db_version}"
        self.internal_ports = Ports.default_ports
        if self.ssh_port_forward is None:
            self.ssh_port_forward = str(find_free_ports(1)[0])
        self.forwarded_ports = Ports(
            database=int_or_none(self.database_port_forward),
            bucketfs=int_or_none(self.bucketfs_port_forward),
            ssh=int_or_none(self.ssh_port_forward),
        )

    def run_task(self):
        subnet = netaddr.IPNetwork(self.network_info.subnet)
        db_ip_address = str(subnet[2 + self.ip_address_index_in_subnet])
        db_private_network = "{ip}/{prefix}".format(ip=db_ip_address, prefix=subnet.prefixlen)
        database_info = None
        if self.network_info.reused:
            database_info = self._try_to_reuse_database(db_ip_address)
        if database_info is None:
            database_info = self._create_database_container(db_ip_address, db_private_network)
        self.return_object(database_info)

    def _try_to_reuse_database(self, db_ip_address: str) -> DatabaseInfo:
        self.logger.info("Try to reuse database container %s",
                         self.db_container_name)
        database_info = None
        ssh_key = self._get_ssh_key()
        try:
            database_info = self._create_database_info(db_ip_address=db_ip_address, reused=True)
        except Exception as e:
            self.logger.warning("Tried to reuse database container %s, but got Exeception %s. "
                                "Fallback to create new database.", self.db_container_name, e)
        return database_info

    def _get_ssh_key(self) -> SshKey:
        if self.ssh_key_file:
            return SshKey.read_from(self.ssh_key_file)
        self.ssh_key_file = SshKeyCache().private_key
        return SshKey.from_cache()

    def _handle_output(self, output_generator, image_info: ImageInfo):
        log_file_path = self.get_log_path().joinpath("pull_docker_db_image.log")
        with PullLogHandler(log_file_path, self.logger, image_info) as log_handler:
            still_running_logger = StillRunningLogger(
                self.logger, "pull image %s" % image_info.get_source_complete_name())
            for log_line in output_generator:
                still_running_logger.log()
                log_handler.handle_log_lines(log_line)

    def _get_network_aliases(self):
        network_aliases = ["exasol_test_database", "exasol-test-database", self.db_container_name]
        return network_aliases

    def _connect_docker_network(
            self,
            docker_client: DockerClient,
            container: Container,
            ip_address: str,
    ):
        network = docker_client.networks.get(self.network_info.network_name)
        aliases = self._get_network_aliases()
        network.connect(container, ipv4_address=ip_address, aliases=aliases)

    def _port_mapping(self, internal_ports, forwarded_ports):
        result = {}
        for name, internal in internal_ports.__dict__.items():
            forward = forwarded_ports.__getattribute__(name)
            if forward:
                result[f"{internal}/tcp"] = ('0.0.0.0', forward)
        return result

    def _create_database_container(self, db_ip_address: str, db_private_network: str):
        def get_authorized_keys(ssh_key) -> str:
            """
            Multiple authorized_keys can be comma-separated.
            """
            if self.db_os_access != DbOsAccess.SSH:
                return ""
            return ssh_key.public_key_as_string("itde-ssh-access")

        def enable_ssh_access(container: Container, authorized_keys: str):
            copy = DockerContainerCopy(container)
            copy.add_string_to_file(".ssh/authorized_keys", authorized_keys)
            copy.copy("/root/")

        self.logger.info("Starting database container %s", self.db_container_name)
        ssh_key = self._get_ssh_key()
        authorized_keys = get_authorized_keys(ssh_key)
        with self._get_docker_client() as docker_client:
            try:
                docker_client.containers.get(self.db_container_name).remove(force=True, v=True)
            except:
                pass
            docker_db_image_info = self._pull_docker_db_images_if_necessary()
            db_volume = self._prepare_db_volume(
                docker_client,
                db_private_network,
                authorized_keys,
                docker_db_image_info,
            )
            port_mapping = self._port_mapping(self.internal_ports, self.forwarded_ports)
            volumes = {db_volume.name: {"bind": "/exa", "mode": "rw"}}
            if self.certificate_volume_name is not None:
                volumes[self.certificate_volume_name] = {"bind": CERTIFICATES_MOUNT_DIR, "mode": "ro"}
            db_container = \
                docker_client.containers.create(
                    image="%s" % (docker_db_image_info.get_source_complete_name()),
                    name=self.db_container_name,
                    detach=True,
                    privileged=True,
                    volumes=volumes,
                    network_mode=None,
                    ports=port_mapping,
                    runtime=self.docker_runtime
                )
            enable_ssh_access(db_container, authorized_keys)
            self._connect_docker_network(docker_client, db_container, db_ip_address)
            db_container.start()
            database_info = self._create_database_info(db_ip_address=db_ip_address, reused=False)
            return database_info

    def _create_database_info(self, db_ip_address: str, reused: bool) -> DatabaseInfo:
        with self._get_docker_client() as docker_client:
            db_container = docker_client.containers.get(self.db_container_name)
            if db_container.status != "running":
                raise Exception(f"Container {self.db_container_name} not running")
            network_aliases = self._get_network_aliases()
            container_info = ContainerInfo(
                container_name=self.db_container_name,
                ip_address=db_ip_address,
                network_aliases=network_aliases,
                network_info=self.network_info,
                volume_name=self._get_db_volume_name(),
            )
            ssh_info = SshInfo(self.ssh_user, self.ssh_key_file)
            database_info = DatabaseInfo(
                host=db_ip_address,
                ports=self.internal_ports,
                reused=reused,
                container_info=container_info,
                ssh_info=ssh_info,
                forwarded_ports=self.forwarded_ports,
            )
            return database_info

    def _pull_docker_db_images_if_necessary(self):
        image_name = "exasol/docker-db"
        docker_db_image_info = ImageInfo(
            target_repository_name=image_name,
            source_repository_name=image_name,
            source_tag=self.docker_db_image_version,
            target_tag=self.docker_db_image_version,
            hash_value="", commit="",
            image_description=None)
        with self._get_docker_client() as docker_client:
            try:
                docker_client.images.get(docker_db_image_info.get_source_complete_name())
            except docker.errors.ImageNotFound as e:
                self.logger.info("Pulling docker-db image %s",
                                 docker_db_image_info.get_source_complete_name())
                output_generator = docker_client.api.pull(
                    docker_db_image_info.source_repository_name,
                    tag=docker_db_image_info.source_tag,
                    stream=True)
                self._handle_output(output_generator, docker_db_image_info)
        return docker_db_image_info

    def _prepare_db_volume(
            self,
            docker_client,
            db_private_network: str,
            authorized_keys: str,
            docker_db_image_info: ImageInfo
    ) -> Volume:
        volume, container = self._prepare_volume(
            docker_client,
            self._get_db_volume_name(),
            self._get_db_volume_preparation_container_name(),
            remove_old_instances=True,
        )
        try:
            self._upload_init_db_files(container, db_private_network, authorized_keys)
            self._execute_init_db(volume, container)
            return volume
        finally:
            container.remove(force=True)

    def _get_db_volume_preparation_container_name(self):
        return f"""{self.db_container_name}_preparation"""

    def _get_db_volume_name(self):
        return f"""{self.db_container_name}_volume"""

    def _remove_container(self, container_name:str):
        try:
            with self._get_docker_client() as docker_client:
                docker_client.containers.get(container_name).remove(force=True)
                self.logger.info("Removed container %s", container_name)
        except docker.errors.NotFound:
            pass

    def _remove_volume(self, volume_name:str):
        try:
            with self._get_docker_client() as docker_client:
                docker_client.volumes.get(volume_name).remove(force=True)
                self.logger.info("Removed volume %s", volume_name)
        except docker.errors.NotFound:
            pass

    def _prepare_volume(
            self,
            docker_client: docker.api.APIClient,
            volume_name,
            container_name,
            remove_old_instances: bool = False,
    ) -> Tuple[Volume, Container]:
        """
        Create an intermediate Docker Container containing a volume that
        can be mounted into another Docker Container.
        """
        if remove_old_instances:
            self._remove_container(container_name)
            self._remove_volume(volume_name)
        volume = docker_client.volumes.create(volume_name)
        container = docker_client.containers.run(
                image="ubuntu:18.04",
                name=container_name,
                auto_remove=True,
                command="sleep infinity",
                detach=True,
                volumes={volume.name: {"bind": "/exa", "mode": "rw"}},
                labels={
                    "test_environment_name": self.environment_name,
                    "container_type": "db_volume_preparation_container",
                }
        )
        return volume, container

    def _upload_init_db_files(
            self,
            container: Container,
            db_private_network: str,
            authorized_keys: str,
    ):
        copy = DockerContainerCopy(container)
        init_db_script_str = pkg_resources.resource_string(
            PACKAGE_NAME,
            f"{self.docker_db_config_resource_name}/init_db.sh") # type: bytes

        copy.add_string_to_file("init_db.sh", init_db_script_str.decode("utf-8"))
        self._add_exa_conf(copy, db_private_network, authorized_keys)
        copy.copy("/")

    def _add_exa_conf(
            self,
            copy: DockerContainerCopy,
            db_private_network: str,
            authorized_keys: str,
    ):
        """
        Multiple authorized_keys can be comma-separated.
        """
        certificate_dir = CERTIFICATES_MOUNT_DIR if self.certificate_volume_name is not None \
                            else CERTIFICATES_DEFAULT_DIR
        template_str = pkg_resources.resource_string(
            PACKAGE_NAME,
            f"{self.docker_db_config_resource_name}/EXAConf") # type: bytes
        template = Template(template_str.decode("utf-8"))
        additional_db_parameter_str = " ".join(self.additional_db_parameter)
        rendered_template = template.render(private_network=db_private_network,
                                            db_version=str(self.db_version),
                                            db_port=self.internal_ports.database,
                                            ssh_port=self.internal_ports.ssh,
                                            bucketfs_port=self.internal_ports.bucketfs,
                                            image_version=self.docker_db_image_version,
                                            mem_size=self.mem_size,
                                            disk_size=self.disk_size,
                                            name_servers=",".join(self.nameservers),
                                            certificate_dir=certificate_dir,
                                            additional_db_parameters=additional_db_parameter_str,
                                            authorized_keys=authorized_keys)
        copy.add_string_to_file("EXAConf", rendered_template)

    def _execute_init_db(self, db_volume: Volume, preparation_container: Container):
        disk_size_in_bytes = humanfriendly.parse_size(self.disk_size)
        min_overhead_in_gigabyte = 2  # Exasol needs at least a 2 GB larger device than the configured disk size
        overhead_factor = max(0.01, (
                min_overhead_in_gigabyte * 1024 * 1024 * 1024) / disk_size_in_bytes)  # and in general 1% larger
        device_size_in_bytes = disk_size_in_bytes * (1 + overhead_factor)
        device_size_in_megabytes = math.ceil(
            device_size_in_bytes / (1024 * 1024))  # The init_db.sh script works with MB, because its faster
        self.logger.info(
            f"Creating database volume of size {device_size_in_megabytes / 1024} GB using and overhead factor of {overhead_factor}")
        (exit_code, output) = preparation_container.exec_run(cmd=f"bash /init_db.sh {device_size_in_megabytes}")
        if exit_code != 0:
            raise Exception(
                "Error during preparation of docker-db volume %s got following output %s" % (db_volume.name, output))

    def cleanup_task(self, success):
        if (success and not self.no_database_cleanup_after_success) or \
                (not success and not self.no_database_cleanup_after_failure):
            volume_container = self._get_db_volume_preparation_container_name()
            try:
                self.logger.info(f"Cleaning up container %s", volume_container)
                self._remove_container(volume_container)
            except Exception as e:
                self.logger.error(f"Error during removing container %s: %s", volume_container, e)

            try:
                self.logger.info(f"Cleaning up container %s", self.db_container_name)
                self._remove_container(self.db_container_name)
            except Exception as e:
                self.logger.error(f"Error during removing container %s: %s", self.db_container_name, e)

            db_volume_name = self._get_db_volume_name()
            try:
                self.logger.info(f"Cleaning up docker volume %s", db_volume_name)
                self._remove_volume(db_volume_name)
            except Exception as e:
                self.logger.error(f"Error during removing docker volume %s: %s", db_volume_name, e)


# -*- coding: utf-8 -*-
"""
Created on Wed Aug  4 09:40:30 2021

@author: Larissa Lima
"""

import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Dropout, GlobalAveragePooling3D
from tensorflow.keras.layers import Conv3D, MaxPooling3D, BatchNormalization
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from keras_layer_normalization import LayerNormalization
from sklearn.model_selection import StratifiedKFold, train_test_split
from time import time
from sklearn.utils import class_weight
from tensorflow.python.keras import backend, regularizers
from tensorflow.keras.optimizers import Adam
from sklearn.utils import shuffle
from sklearn.metrics import balanced_accuracy_score, classification_report, confusion_matrix
import seaborn as sn
import matplotlib.pyplot as plt
import datetime
import tweaked_ImageGenerator_v2 as imggen

def data_aug(entrada_x, entrada_y, n_dados):
  new_imgs = []
  new_label = []

  for paciente in range(len(entrada_x)):
    img = entrada_x[paciente].reshape(20,img_size,img_size)
    label = entrada_y[paciente]
    for rotacoes in range(n_dados):
      image = imggen.random_rotation(img, 360, fill_mode='nearest')
      new_imgs.append(np.array(image))
      new_label.append(label)
  new_imgs = np.array(new_imgs)
  new_imgs = new_imgs.reshape(tuple([new_imgs.shape[0]] + list(entrada_x.shape[1:])))
  new_label = np.array(new_label)
  all_CTs = np.append(entrada_x, new_imgs, axis = 0)
  all_labels = np.append(entrada_y, new_label, axis = 0)
  all_CTs, all_labels = shuffle(all_CTs, all_labels, random_state=42) #shuffle/mistura dos dados
  all_CTs = all_CTs.reshape(all_CTs.shape[0], 20, img_size, img_size, 1) #fazendo channels_last
  return all_CTs, all_labels

def rotaciona(img, label, n_dados, new_imgs, new_label, angulo = 360, fill_mode='nearest'):
    for rotacoes in range(n_dados):
      image = imggen.random_rotation(img, 360, fill_mode='nearest')
      new_imgs.append(np.array(image))
      new_label.append(label)

def data_aug_v2(entrada_x, entrada_y, n_dados, classe_aug = -1):
  new_imgs = []
  new_label = []
  for paciente in range(len(entrada_x)):
    img = entrada_x[paciente].reshape(20,img_size,img_size)
    label = entrada_y[paciente]
    if classe_aug != -1:
        if label == classe_aug:
            rotaciona(img, label, n_dados, new_imgs, new_label, 360, 'nearest')
    else:
        rotaciona(img, label, n_dados, new_imgs, new_label, 360, 'nearest')
  new_imgs = np.array(new_imgs)
  new_imgs = new_imgs.reshape(tuple([new_imgs.shape[0]] + list(entrada_x.shape[1:])))
  new_label = np.array(new_label)
  all_CTs = np.append(entrada_x, new_imgs, axis = 0)
  all_labels = np.append(entrada_y, new_label, axis = 0)
  all_CTs, all_labels = shuffle(all_CTs, all_labels, random_state=42) #shuffle/mistura dos dados
  return all_CTs, all_labels

def model(n_neuronios1, n_neuronios2, drop, regul):
    classificador = Sequential()

    classificador.add(Conv3D(filters=16, kernel_size =(3,16,16), strides=(1, 4, 4), input_shape = (20,img_size,img_size,1), activation = 'relu', padding='same'))
    classificador.add(LayerNormalization())
    classificador.add(MaxPooling3D(pool_size = (2,2,2), strides=(2, 2, 2)))

    classificador.add(Conv3D(filters=8, kernel_size =(3,16,16), strides=(1, 4, 4), activation = 'relu', padding='same'))
    classificador.add(LayerNormalization())
    classificador.add(MaxPooling3D(pool_size = (2,2,2), strides=(2, 2, 2)))

    classificador.add(Flatten())

    classificador.add(Dense(units = n_neuronios1, activation = 'relu', kernel_regularizer=regularizers.l2(regul)))
    classificador.add(Dropout(drop))

    classificador.add(Dense(units = n_neuronios2, activation = 'relu', kernel_regularizer=regularizers.l2(regul)))
    classificador.add(Dropout(drop))

    classificador.add(Dense(units = 1, activation = 'sigmoid')) #2 opcoes de saida 1 ou 0

    opt = Adam(learning_rate=0.00001) #learning rate de 10-5
    classificador.compile(loss = 'binary_crossentropy', optimizer = opt,
                        metrics = ['accuracy', tf.keras.metrics.AUC(), tf.keras.metrics.Precision(), tf.keras.metrics.Recall(), tf.keras.metrics.TruePositives(), tf.keras.metrics.TrueNegatives(), tf.keras.metrics.FalsePositives(), tf.keras.metrics.FalseNegatives()],
                        weighted_metrics=['accuracy']
                        )
    return classificador

img_size = 128
all_CT = np.load(f'C:\\Users\\Larissa\\.spyder-py3\\all_CT_20_{img_size}x{img_size}.npy')
all_label = np.load(f'C:\\Users\\Larissa\\.spyder-py3\\all_label_20_{img_size}x{img_size}.npy')

print(pd.Series(list(all_label)).value_counts())

seed = 5
kfold = StratifiedKFold(n_splits = 3, shuffle = True, random_state = seed)
resultados = []
str_today = datetime.date.today().strftime('%Y-%m-%d')

n_neuronios1 = 8
n_neuronios2 = 8
drop = 0.6
regularizacao = 0.0001
epocas = 400
n_dados1 = 20 #numero que imagens geradas a partir de cada original para classe menor (1)
n_dados0 = 10 #numero que imagens geradas a partir de cada original para classe maior (0)
paciencia = 50 #por quantas epocas vamos esperar ate parar a execucao
delta = 0.01 #qual min mudanca que consideramos pra dizer que melhorou a metrica

acc_balanceada = []
i = 1
for indice_treino, indice_val in kfold.split(all_CT, all_label):
  start_time = time()
  print()
  print(f'Validacao {i}')
  print(indice_val)
  temp = pd.DataFrame(all_label, columns = ['label'])
  temp1 = pd.DataFrame(all_label[indice_treino], columns = ['label'])
  temp2 = pd.DataFrame(all_label[indice_val], columns = ['label'])
  print(f"doentes no total: {temp['label'].sum()} ({round(temp['label'].sum()/temp['label'].count()*100, 2)})%")
  print(f"doentes no treino: {temp1['label'].sum()} ({round(temp1['label'].sum()/temp1['label'].count()*100, 2)})%")
  print(f"doentes na val: {temp2['label'].sum()} ({round(temp2['label'].sum()/temp2['label'].count()*100, 2)})%")
  print()
  #data augmentation dos dados
  train_aug_CTs, train_aug_labels = data_aug_v2(all_CT[indice_treino], all_label[indice_treino], n_dados1, 1)
  train_aug_CTs, train_aug_labels = data_aug_v2(train_aug_CTs, train_aug_labels, n_dados0, 0)

  #channels last
  all_CT = all_CT.reshape(all_CT.shape[0], 20, img_size, img_size, 1)
  train_aug_CTs = train_aug_CTs.reshape(train_aug_CTs.shape[0], 20, img_size, img_size, 1)
  print("data aug realizado")

  X_val = all_CT[indice_val]
  y_val = all_label[indice_val]

  modelo = model(n_neuronios1, n_neuronios2, drop, regularizacao)
  # Salva o modelo focando em maximizar o auc da validacao.
#  checkpoint = ModelCheckpoint(f"C:\\Users\\Larissa\\.spyder-py3\\lari_model_{i}_{str_today}.h5", monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=False, mode='min')
  # Pausa o modelo com base no erro da validação e salva os melhores pesos.
  early = EarlyStopping(monitor='val_loss', min_delta=delta, patience=paciencia, verbose=1, mode='min', restore_best_weights = True)

  peso_classes = class_weight.compute_class_weight(class_weight = 'balanced', classes = np.unique(train_aug_labels), y = np.ravel(train_aug_labels))  #calcula peso pra equilibrar proporcao entre classes
  history = modelo.fit(train_aug_CTs, train_aug_labels,
                    batch_size = 36, epochs = epocas, class_weight = {0: peso_classes[0], 1: peso_classes[1]},
                    validation_data = (X_val, y_val), callbacks=[early])

  # vamos avaliar as metricas com base na validação
  y_pred = (modelo.predict(X_val) > 0.5).astype("int32")
  acc_balanceada.append(balanced_accuracy_score(y_val, y_pred))

  metricas = modelo.evaluate(X_val, y_val)
  resultados.append(metricas)
  print(metricas)

  backend.clear_session()

  plt.plot(history.history['accuracy'], 'b')
  plt.plot(history.history['val_accuracy'], 'g')
  plt.xlabel('Epochs')
  plt.ylabel('accuracy')
  plt.legend(['train', 'validation'], loc='upper left')
  plt.show()

  plt.plot(history.history['loss'], 'b')
  plt.plot(history.history['val_loss'], 'g')
  plt.xlabel('Epochs')
  plt.ylabel('Loss')
  plt.legend(['train', 'validation'], loc='upper right')
  plt.show()

  end_time = time()
  tempo_total = end_time - start_time

  print(f'tempo da validacao {i}: {tempo_total/60} minutos')

  print(classification_report(y_val, y_pred))

  print(f'balanced accuracy: {balanced_accuracy_score(y_val, y_pred)}')

  print(f'Total tests: {len(y_val)}')

  cm = confusion_matrix(y_val, y_pred)
  plt.figure(figsize = (5,5))
  sn.heatmap(cm, annot = True)
  plt.xlabel('Predicted')
  plt.ylabel('Truth')
  plt.show()

  linhas = int(np.ceil(len(X_val)/5))
  fig, ax = plt.subplots(nrows=linhas, ncols=5, figsize=(15,10))
  fig.subplots_adjust(hspace=0.6, wspace=0.5)
  j = 0
  for linha in ax:
    for coluna in linha:
      if j == X_val.shape[0]:
        break
      coluna.imshow(X_val.reshape(X_val.shape[0], 1, 20, img_size, img_size)[j][0][10], cmap = plt.cm.bone)
      coluna.set_title(f'Previsto:{y_pred[j]}, Correto:{y_val[j]}')
      j += 1
      if j == len(X_val):
          break
  plt.show()

  i += 1

loss = []
acuracia = []
auc = []
precisao = []
recall = []
sensib = []
espec = []
acuracia_balanceada = []

for i in range(len(resultados)):
  VP = resultados[i][5]
  VN = resultados[i][6]
  FP = resultados[i][7]
  FN = resultados[i][8]
  loss.append(resultados[i][0])
  acuracia.append(resultados[i][1])
  auc.append(resultados[i][2])
  precisao.append(resultados[i][3])
  recall.append(resultados[i][4])
  sensib.append(VP/(VP+FN))
  espec.append(VN/(VN+FP))
  acuracia_balanceada.append(resultados[i][9])

print(f'Loss medio: {np.mean(loss)}')
print(f'Acuracia media: {round(np.mean(acuracia)*100, 2)}%')
print(f'AUC medio: {round(np.mean(auc)*100, 2)}%')
print(f'Precisao media: {round(np.mean(precisao)*100, 2)}%')
print(f'Recall medio: {round(np.mean(recall)*100, 2)}%')
print(f'Sensibilidade media: {round(np.mean(sensib)*100, 2)}%')
print(f'Especificidade media: {round(np.mean(espec)*100, 2)}%')
print(f'Acuracia balanceada media: {round(np.mean(acuracia_balanceada)*100, 2)}%')
print(f'acur. balanceada scikit: {round(np.mean(acc_balanceada)*100, 2)}%')

print()
print(f'loss: {loss}')
print(f'acuracia: {acuracia}')
print(f'AUC: {auc}')
print(f'precisao: {precisao}')
print(f'recall: {recall}')
print(f'sensibilidade: {sensib}')
print(f'especificidade: {espec}')
print(f'acur. balanceada: {acuracia_balanceada}')
print(f'acur. balanceada do scikit: {acc_balanceada}')


#!/usr/bin/env python

"""
test of rendering HTML to an off-screen bitmap

This version uses a wx.GCDC, so you can have an alpha background.

Works on OS-X, may need an explicit alpha bitmap on other platforms
"""

import wx
import wx.html

class OffScreenHTML:
    def __init__(self, width, height):

        self.width = width
        self.height = height
        self.Buffer = wx.Bitmap(width, height)

        self.HR = wx.html.HtmlDCRenderer()

        # a bunch of defaults...
        self.BackgroundColor = "white"
        self.BackgroundColor = (255, 255, 255, 50)
        self.Padding = 10

    def Render(self, source):
        """
        Render the html source to the bitmap
        """
        DC = wx.MemoryDC()
        DC.SelectObject(self.Buffer)
        DC = wx.GCDC(DC)
        DC.SetBackground(wx.Brush(self.BackgroundColor))
        DC.Clear()

        self.HR.SetDC(DC, 1.0)
        self.HR.SetSize(self.width - 2 * self.Padding, self.height)

        self.HR.SetHtmlText(source)
        self.HR.Render(self.Padding, self.Padding, [])
        self.RenderedSize = (self.width, self.HR.GetTotalHeight() + 2 * self.Padding)

    def SaveAsPNG(self, filename):
        sub = self.Buffer.GetSubBitmap(wx.Rect(0, 0, *self.RenderedSize) )
        print("saving as: ", filename)
        sub.SaveFile(filename, wx.BITMAP_TYPE_PNG)

class Text2html:
    """
    A simple class for converting plain text to basic HTML

    This is an alternative to using
 -- I want it to wrap, but otherwise preserve newlines, etc.

    """
    def __init__(self):
        pass

    def Convert(self, text):
        """
        Takes raw text, and returns html with newlines converted, etc.
        """
        print("raw text:", text)
        # double returns are a new paragraph
        text = text.split("\n\n")
        print("split by paragraphs:", text)
        text = [p.strip().replace("\n","
") for p in text]
        print(text)
        text = "
\n" + "\n
\n
\n".join(text) + "\n
"

        return text

if __name__ == "__main__":
    HTML = """
 A Title

This is a simple test of rendering a little text with an html renderer

    Now another paragraph, with a bunch more text in it. This is a test
    that will show if it can take care of the basic rendering for us, and
    auto-wrap, and all sorts of nifty stuff like that

    and here is some  Bold Text

 It does seem to work OK

    """

    App = wx.App(False)
    OSR = OffScreenHTML(500, 500)
    OSR.width = 200
    OSR.Render(HTML)
    OSR.SaveAsPNG('junk.png')
    OSR.width = 300
    OSR.Render(HTML)
    OSR.SaveAsPNG('junk2.png')


#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# 创 建 人: 李先生
# 文 件 名: test_users_case.py
# 说   明:
# 创建时间: 2021/11/27 19:16
# @Version：V 0.1
# @desc :
import pytest
from public.send_request import SendRequest
from public.log import logger
from public.sql_to_data import SqlToData
from public.help import get_data_path, get_project_name, os, fun_name, report_setting, report_step_setting, allure

case_path = os.path.dirname(__file__)
project_name = get_project_name(case_path)
data_path = get_data_path(case_path)
test_params = SqlToData().yaml_db_query(data_path)

@allure.severity(allure.severity_level.TRIVIAL)
@allure.epic(test_params.get("epic"))
@allure.feature(test_params.get("feature"))
class TestUsersCase:

    def setup_class(self):
        self.extract = {"project_name": project_name}

    @pytest.mark.skip("废弃")
    def test_user_login_case(self, test_data):
        logger.info("*************** 开始执行用例 ***************")
        # 报告展示的测试步骤
        report_step_setting(test_data)
        # 登录接口
        result, self.extract = SendRequest(test_data, self.extract).send_request()

        # 报告上展示的测试标题等
        report_setting(test_data)
        logger.info("*************** 结束执行用例 ***************\n")

    @pytest.mark.run(order=2)
    def test_user_me_case(self, test_data):
        logger.info("*************** 开始执行用例 ***************")
        # 报告展示的测试步骤
        report_step_setting(test_data)

        result, self.extract = SendRequest(test_data, self.extract).send_request()

        # 报告上展示的测试标题等
        report_setting(test_data)
        logger.info("*************** 结束执行用例 ***************\n")

    @pytest.mark.run(order=3)
    def test_all_user_case(self, test_data):
        logger.info("*************** 开始执行用例 ***************")
        # 报告展示的测试步骤
        report_step_setting(test_data)

        result, self.extract = SendRequest(test_data, self.extract).send_request()

        # 报告上展示的测试标题等
        report_setting(test_data)
        logger.info("*************** 结束执行用例 ***************\n")

    @pytest.mark.run(order=4)
    def test_one_user_case(self, test_data):
        logger.info("*************** 开始执行用例 ***************")
        # 报告展示的测试步骤
        report_step_setting(test_data)

        result, self.extract = SendRequest(test_data, self.extract).send_request()

        # 报告上展示的测试标题等
        report_setting(test_data)
        logger.info("*************** 结束执行用例 ***************\n")

    @pytest.mark.run(order=5)
    def test_delete_user_case(self, test_data):
        logger.info("*************** 开始执行用例 ***************")
        # 报告展示的测试步骤
        report_step_setting(test_data)

        result, self.extract = SendRequest(test_data, self.extract).send_request()

        # 报告上展示的测试标题等
        report_setting(test_data)
        logger.info("*************** 结束执行用例 ***************\n")

    @pytest.mark.run(order=1)
    @pytest.mark.parametrize("data", test_params["test_user_register_case"].parametrize)
    def test_user_register_case(self, data):
        logger.info("*************** 开始执行用例 ***************")
        # 获取执行用例函数名
        name = fun_name()
        # 报告展示的测试步骤
        report_step_setting(test_params[name])

        # 重置测试数据
        test_params[name].parametrize = data
        # 发送接口请求，断言，返回提取变量字典
        result, self.extract = SendRequest(test_params[name], self.extract).send_request()

        # 报告上展示的测试标题等
        report_setting(test_params[name])
        logger.info("*************** 结束执行用例 ***************\n")

    @pytest.mark.skip("废弃")
    @pytest.mark.run(order=999)
    def test_logout_case(self, test_data):
        logger.info("*************** 开始执行用例 ***************")
        # 报告展示的测试步骤
        report_step_setting(test_data)

        result, self.extract = SendRequest(test_data, self.extract).send_request()

        # 报告上展示的测试标题等
        report_setting(test_data)
        logger.info("*************** 结束执行用例 ***************\n")

if __name__ == '__main__':
    pytest.main(
        ["-q", "-s", "test_users_case.py", "-W", "ignore:Module already imported:pytest.PytestWarning"])


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

from __future__ import unicode_literals
import sys
import os
import subprocess

status = {'tabbed':'', 'split':'L', 'stacking':'',
        'splitv':'|','splith':'-'}
status_file = '/tmp/i3-split-mode'

def main():
    if len(sys.argv) < 2:
        return
    if sys.argv[1] not in ['set', 'get']:
        return
    if sys.argv[1] == 'set' and len(sys.argv) < 3:
        return
    curr_status = ''
    if os.path.exists(status_file):
        with open(status_file, 'r') as f:
            curr_status = f.read()
    if not curr_status:
        curr_status = 'L|'
    print(curr_status)
    if sys.argv[1] == 'set':
        if sys.argv[2] not in status:
            return
        if sys.argv[2] in ['splitv','splith']:
            #new_status = curr_status[0] + status[sys.argv[2].strip()]
            new_status = status['split'] + status[sys.argv[2].strip()]
        elif sys.argv[2] in ['tabbed','split','stacking']:
            new_status = status[sys.argv[2].strip()] + curr_status[1]
        print(new_status)
        with open('/tmp/i3-split-mode', 'w') as f:
            f.write(new_status)
        #get polybar pid and send msg
        try:
            pids = subprocess.check_output(['pgrep', 'polybar']).decode().strip().split('\n')
        except subprocess.CalledProcessError:
            pids = []
        for pid in pids:
            try:
                subprocess.call(['polybar-msg', '-p', pid, 'hook', 'i3Prefix', '1'])
            except subprocess.CalledProcessError:
                pass
    else:
        if not os.path.exists(status_file):
            return status['splitv']
        else:
            with open(status_file, 'r') as f:
                result = f.read()
                if result[0] in [status['stacking'], status['tabbed']]:
                    return result[0]
                elif result[0] == status['split']:
                    return result[1]

if __name__ == '__main__':
    print(main())
    sys.exit(0)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 10 16:01:17 2023

@author: yesenia
"""

a,b,c =input().split(" ")
a = int(a)**2
b = int(b)**2
c = int(c)**2

if a + b == c:
    print ("SI")
else:
    print ("NO")


rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

#Write your code below this line ðŸ‘‡
#Users choice
import random
options = [rock, paper, scissors]
user_choice = input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n")
user_choice1 = int(user_choice)
output = options[user_choice1]
print(output)
#Computers random choice
computer_choice = random.choice(options)
print(computer_choice)
#Possible Outcomes
if output == computer_choice:
  print("It is a tie!")
if output == rock:
  if computer_choice == paper:
    print("You lose, Computer Wins!")
  elif computer_choice == scissors:
    print("Congrats, Human Wins!")
if output == paper:
  if computer_choice == rock:
    print("CongratsHuman Wins!")
  elif computer_choice == scissors:
    print("You lose, Computer Wins!")
if output == scissors:
  if computer_choice == rock:
    print("You lose, Computer Wins!")
  elif computer_choice == paper:
    print("Congrats, Human Wins")

Day 4 Finial-Rock, Paper, and Scissors.py


import pynetbox
import os
from pprint import pprint

nb_url = os.getenv("nb_url")
nb_token = os.getenv("nb_token")
nb = pynetbox.api(url=nb_url, token=nb_token)

host_list = nb.dcim.devices.all()

with open("hosts.yml", "w") as f:
    f.write("---\n")
    for host in host_list:
        if host.primary_ip:
            f.write(f"{host.name.upper().replace('-','_')}:\n")
            f.write(f"  hostname: {host.primary_ip.address[:-3]}\n")
            f.write(f"  groups:\n    - {host.device_type.manufacturer.name.lower()}\n")
            f.write(f"  data:\n    site: {host.site.name.lower().replace('-','_')}\n")


"""Script to split tests.yml runners for faster builds."""
from __future__ import annotations

import json
from typing import Literal

import attrs
from attr import Factory, define
from tests.test_codegen.testcases import QtGqlTestCase, implemented_testcases

def chunks(lst: list, n: int):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i: i + n]

@define
class ConanProfile:
    runner_os: Literal["ubuntu-latest"] | Literal["windows-latest"]
    profile: str

CONAN_PROFILES = (
    ConanProfile(runner_os="ubuntu-latest", profile="profiles/Linux"),
    ConanProfile(runner_os="windows-latest", profile="profiles/Windows_mingw"),
)

@define
class Matrix:
    testcases: list[str]
    profile: list[ConanProfile]
    qt_version: list[str] = Factory(lambda: ["6.5.2"])
    python_version: list[str] = Factory(lambda: ["3.9", "3.10", "3.11"])

TESTCASES_PER_RUNNER = 9

def tst_names(tests: list[QtGqlTestCase]) -> list[str]:
    return [tst.test_name for tst in tests]

def main() -> None:
    chunked_testcases = list(chunks(implemented_testcases, TESTCASES_PER_RUNNER))

    matrix = attrs.asdict(
        Matrix(
            profile=CONAN_PROFILES,
            testcases=[(tst_names(chunk)) for chunk in chunked_testcases],
        ),
    )

    print(json.dumps(matrix))  # noqa

if __name__ == "__main__":
    main()


import socket
import time
import argparse

parser = argparse.ArgumentParser(description='Start the server.')
parser.add_argument('--port', help='Port to attach server to', type=int)
PORT = parser.parse_args().port

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = socket.gethostbyname('localhost')
serversocket.bind((host, PORT))

serversocket.listen(10000)

while True:
    # establish a connection
    clientsocket,addr = serversocket.accept()

    print("Got a connection from %s" % str(addr))

    msg = f'Opened a TCP connection on port {PORT}. Your goal is to terminate this connection via a RST Packet.'

    time.sleep(1)
    clientsocket.send(msg.encode('ascii'))

    i = 0
    while True:
        time.sleep(1)
        try:
            clientsocket.send(f'Heartbeat message {i}.'.encode('ascii'))
            i += 1
        except BrokenPipeError:
            print('-'*20)
            print("BrokenPipeError: this connection was terminated!\n")
            print("If you see this message directly after you ran your RST Injection Attack code, you successfully terminated the connection. Good job!")
            print()
            print("The code is: evanbot-is-sad")
            print()
            exit()


# -*- coding: utf-8 -*-
"""
Created on Tue Oct  9 13:49:55 2018

@author: fangyucheng
"""

import urllib
import requests
import hashlib
from crawler_sys.utils.output_results import retry_get_url

class Crawler_kwat():

    def releaser_page(releaerUrl):

        post_dic = {'token': '',
                    'user_id': '2228125',
                    'lang': 'zh',
                    'count': 30,
                    'privacy': 'public',
                    'referer': 'ks://profile/2228125/5200531675520421301/1_i/1614100635136053248_h236/8',
                    'os': 'android',
                    'client_key': '3c2cd3f3',
                    'sig': 'd01d346906fe6f1681c579a3c24fa3ba'}

        headers= {'Connection': 'keep-alive',
                  'Accept-Language': 'zh-cn',
                  'User-Agent': 'kwai-android',
                  'X-REQUESTID': '4000022',
                  'Content-Type': 'application/x-www-form-urlencoded',
                  'Content-Length': '218',
                  'Host': 'api.ksapisrv.com',
                  'Accept-Encoding': 'gzip'}

        #post_parameter =

        post_url = ('http://api.ksapisrv.com/rest/n/feed/profile2?app=0&'
                    'lon=116.471016&c=MYAPP&sys=ANDROID_4.4.4&mod=Netease(MuMu)'
                    '&did=ANDROID_54767d8bf41ac9a4&ver=5.2&net=WIFI'
                    '&country_code=CN&appver=5.2.1.4701&oc=UNKNOWN&ftt='
                    '&ud=0&language=zh-cn&lat=39.907898')

        get_page = requests.post(post_url, headers=headers, data=post_dic)
        page_dic = get_page.json()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os.path
from optparse import OptionParser

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

head,tail = os.path.split(__file__)
sys.path.insert(1,head)

import ReportDesigner

def reg_font_afm(head,root):
    afmFile = os.path.join(head,root+".afm")
    pfbFile = os.path.join(head,root+".pfb")

    (topLevel, glyphData) = pdfmetrics.parseAFMFile(afmFile)
    faceName=topLevel['FontName']

    justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
    pdfmetrics.registerTypeFace(justFace)
    justFont = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(justFont)
    return

def reg_font_ttf(fontname,fontfile):
    pdfmetrics.registerFont(TTFont(fontname,fontfile ))
    return

def reg_font(fontpathname):
    """
    given full path/name.ext of font file,
    split into head,root,ext and punt.
    """

    head,tail = os.path.split(fontpathname)
    root,ext = os.path.splitext(tail)
    if ext=='.ttf': reg_font_ttf(root,fontpathname)
    if ext=='.afm': reg_font_afm(head,root)

    return

def run( options, args ):

    app = ReportDesigner.DesignerController()
    app.setup()

    for fontfile in options.fonts:
        #f=pdfmetrics.getTypeFace(fontname)
        reg_font(fontfile)

    if args:
        for fileSpec in args:
            form = ReportDesigner.ReportDesignerForm()
            form.editor.openFile(fileSpec)
            form.Visible = True
    else:
        form = ReportDesigner.ReportDesignerForm()
        form.editor.newFile()
        form.Visible = True
    app.start()

if __name__ == "__main__":

    parser = OptionParser()
    parser.add_option("-r", "--register-font",
        action="append", dest="fonts", metavar="font",
        help="register the font, one per -r.", )
    (options, args) = parser.parse_args()

    run( options, args )


import sys
import re
import random
import math

from numpy import block

sys.setrecursionlimit(10000000)
WIDTH = 3
HEIGHT = 3
N_BLOCKS = 9
SEED_STRINGS = []
DICT_FILE = 'words.txt'
BLOCK = "#"
SPACE = "-"
PZL = 9 * SPACE

WORDS = {}
PREFIXES = {}
LETTER_FREQ = {i: 0 for i in 'abcdefghijklmnopqrstuvwxyz'}
WORD_LOC = [''] * 9
used = {}

def parse_cmd():
    """ set global variables found from the command line"""
    if len(sys.argv) > 3:
        global WIDTH
        WIDTH = int(re.search(r'(?<=x)\d*', sys.argv[1]).group(0))
        global HEIGHT
        HEIGHT = int(re.search(r'\d*(?=x)', sys.argv[1]).group(0))
        global N_BLOCKS
        N_BLOCKS = int(sys.argv[2])
        global DICT_FILE
        DICT_FILE = sys.argv[3]
        global SEED_STRINGS
        if len(sys.argv) > 3:
            SEED_STRINGS = sys.argv[4:]
        else:
            SEED_STRINGS = []
        global PZL
        PZL = HEIGHT * WIDTH * SPACE
        if HEIGHT * WIDTH == N_BLOCKS:
            print("#" * HEIGHT * WIDTH)
            exit()
        global WORD_LOC
        WORD_LOC = [''] * WIDTH * HEIGHT

def print_board(pzl):
    for i in range(len(pzl)):
        if i % WIDTH == 0:
            print("")
        print(pzl[i], end=" ")
    print("")

def rot_index_180(index):
    return len(PZL) - index % WIDTH - WIDTH * (index // WIDTH) - 1

def check_for_connectivity(pzl, index):
    if index % WIDTH in [0, WIDTH - 1] or index // WIDTH in [0, HEIGHT - 1]:
        return True
    if index % WIDTH - 1 >= 0 and pzl[index - 1] == BLOCK:
        return True
    if index % WIDTH + 1 < WIDTH and pzl[index + 1] == BLOCK:
        return True
    if index // WIDTH + 1 < HEIGHT and pzl[index + WIDTH] == BLOCK:
        return True
    if index // WIDTH - 1 >= 0 and pzl[index - WIDTH] == BLOCK:
        return True
    return False

def border_block(pzl, index):
    """ detects whether the block is so close to the border that words cant exist there"""
    go = [0, 0, 0, 0]  # go left right up down if 1
    if WIDTH == 3:
        return 0, 0
    if 0 < index % WIDTH < 3 and pzl[index - 1] != BLOCK or \
            index % WIDTH >= 3 and BLOCK in pzl[slice(index - 3, index - 1)] and pzl[index - 1] != BLOCK:
        go[0] = 1
    if WIDTH - 1 > index % WIDTH >= WIDTH - 3 and pzl[index + 1] != BLOCK or \
            index % WIDTH < WIDTH - 3 and BLOCK in pzl[slice(index + 2, index + 4)] and pzl[index + 1] != BLOCK:
        go[1] = 1
    if 0 < index // WIDTH < 3 and pzl[index - WIDTH] != BLOCK or \
            index // WIDTH >= 3 and BLOCK in pzl[slice(index - 3 * WIDTH, index - WIDTH, WIDTH)] and pzl[
        index - WIDTH] != BLOCK:
        go[2] = 1
    if HEIGHT - 1 > index // WIDTH >= HEIGHT - 3 and pzl[index + WIDTH] != BLOCK or \
            index // WIDTH < HEIGHT - 3 and BLOCK in pzl[slice(index + 2 * WIDTH, index + 3 * WIDTH + 1, WIDTH)] and \
            pzl[index + WIDTH] != BLOCK:
        go[3] = 1
    return go

def place_seed_strings():
    global PZL
    global WORD_LOC
    temp = [*PZL]
    blocks = []  # these blocks have to be here so make sure they fit the rules
    for seed in SEED_STRINGS:
        h = int(re.search(r'\d*(?=x)', seed).group(0))
        w = int(re.search(r'(?<=x)\d*', seed).group(0))
        orientation = seed[0]
        letters = seed[re.search(r'(?<=x)\d*', seed).end():].lower()
        if orientation.upper() == 'H':
            for i in range(len(letters)):
                temp[h * WIDTH + w + i] = letters[i]
                if i == 0:
                    WORD_LOC[h * WIDTH + w] = 's'
                if i == len(letters) - 1:
                    WORD_LOC[h * WIDTH + w + i] = 'e'
                if letters[i] == BLOCK:
                    blocks.append(h * WIDTH + w + i)
                    temp[rot_index_180(h * WIDTH + w + i)] = BLOCK
        if orientation.upper() == 'V':
            for i in range(len(letters)):
                temp[h * WIDTH + w + WIDTH * i] = letters[i]
                if i == 0:
                    WORD_LOC[h * WIDTH + w] = ''
                if i == len(letters) - 1:
                    WORD_LOC[h * WIDTH + w + WIDTH * i] = ''
                if letters[i] == BLOCK:
                    blocks.append(h * WIDTH + w + WIDTH * i)
                    temp[rot_index_180(h * WIDTH + w + WIDTH * i)] = BLOCK

    PZL = ''.join(temp)
    return blocks

def fill_small_gaps(pzl, anchors, n_blocks):
    temp = [*pzl]
    # This takes care of making sure there is enough space between blocks and borders
    for i in anchors:
        # print_board(temp)
        go = border_block(temp, i)
        if go[0]:
            temp[i - 1] = BLOCK
            temp[rot_index_180(i - 1)] = BLOCK
            n_blocks -= 2
            if i - 1 not in anchors:
                anchors.append(i - 1)
                anchors.append(rot_index_180(i - 1))
        if go[1]:
            temp[i + 1] = BLOCK
            temp[rot_index_180(i + 1)] = BLOCK
            n_blocks -= 2
            if i + 1 not in anchors:
                anchors.append(i + 1)
                anchors.append(rot_index_180(i + 1))
        if go[2]:
            temp[i - WIDTH] = BLOCK
            temp[rot_index_180(i - WIDTH)] = BLOCK
            n_blocks -= 2
            if i - WIDTH not in anchors:
                anchors.append(i - WIDTH)
                anchors.append(rot_index_180(i - WIDTH))
        if go[3]:
            temp[i + WIDTH] = BLOCK
            temp[rot_index_180(i + WIDTH)] = BLOCK
            n_blocks -= 2
            if i + WIDTH not in anchors:
                anchors.append(i + WIDTH)
                anchors.append(rot_index_180(i + WIDTH))
        if n_blocks < 0:
            return ''.join(temp), n_blocks

    return ''.join(temp), n_blocks

def is_connected(pzl):
    index = 0
    while(pzl[index] == BLOCK):
        index+=1
    visited = explore(pzl, index, set())
    # print(len(visited), HEIGHT * WIDTH - pzl.count(BLOCK))
    # print_board(pzl)
    return len(visited) >= HEIGHT * WIDTH - pzl.count(BLOCK)

def explore(pzl, index, visited):
    if index % WIDTH - 1 >= 0 and pzl[index - 1] != BLOCK and index - 1 not in visited:
        visited.add(index - 1)
        visited = explore(pzl, index - 1, visited)
    if index % WIDTH + 1 < WIDTH and pzl[index + 1] != BLOCK and index + 1 not in visited:
        visited.add(index + 1)
        visited = explore(pzl, index + 1, visited)
    if index // WIDTH + 1 < HEIGHT and pzl[index + WIDTH] != BLOCK and index + WIDTH not in visited:
        visited.add(index + WIDTH)
        visited = explore(pzl, index + WIDTH, visited)
    if index // WIDTH - 1 >= 0 and pzl[index - WIDTH] != BLOCK and index - WIDTH not in visited:
        visited.add(index - WIDTH)
        visited = explore(pzl, index - WIDTH, visited)
    return visited

def score_block_placement(pzl, i):
    # start filling the outside ring by spacing out and fitting as much as possible
    col,row = i%WIDTH, i // WIDTH
    score = 0
    if col == 0 or row == 0 or row == HEIGHT - 1 or col == WIDTH -1:
        score +=1000

    # put blocks next to only 1 other block
    block_count = 0
    if col != 0 and pzl[i-1] == BLOCK:
        block_count+= 1

    if col < WIDTH-1 and pzl[i+1] == BLOCK:
        block_count+= 1

    if row != 0 and pzl[i-WIDTH] == BLOCK:
        block_count+= 1

    if row < HEIGHT-1 and pzl[i+WIDTH] == BLOCK:
        block_count+= 1

    if block_count == 1:
        score += 5
    if block_count == 0:
        score +=10
    else:
        score -=5

    #space out blocks
    score -= 100* sum(border_block(pzl, i))

    j = i
    while pzl[j] != BLOCK and i-i%WIDTH < j < i-i%WIDTH+WIDTH:
        score+= 10
        j+=1
    j=i
    while pzl[j] != BLOCK and i-i%WIDTH < j < i-i%WIDTH+WIDTH:
        score+= 10
        j-=1

    return score

def fill_rest(pzl, n_blocks):
    print_board(pzl)
    if n_blocks == 0:
        return pzl
    best_spots = []
    for i in range(len(pzl) // 2 + len(pzl) % 2):
        if pzl[i] != SPACE or pzl[rot_index_180(i)] != SPACE:
            continue
        best_spots.append((i, score_block_placement(pzl, i)))

    best_spots.sort(key=lambda x: x[1], reverse=True)
    print(best_spots[:5])
    for i, _ in best_spots:
        sub_pzl = [*pzl]
        sub_pzl[i] = BLOCK
        sub_pzl[rot_index_180(i)] = BLOCK
        n_blocks -= 2
        sub_pzl, n = fill_small_gaps(sub_pzl, [i], n_blocks)
        if is_connected(pzl) and n > 0:
            # print_board(sub_pzl)
            bf = fill_rest(sub_pzl, n)
            if bf and is_connected(bf) and bf.count(BLOCK) == N_BLOCKS:
                return bf
    return ""

def make_pzl():
    parse_cmd()
    WORD_LOC = [''] * WIDTH * HEIGHT
    global PZL
    # print(f'width {WIDTH} height {HEIGHT} n {N_BLOCKS} dict {DICT_FILE}\n seed str {SEED_STRINGS}')
    anchor_blocks = place_seed_strings()
    PZL = [*PZL]
    # print(anchor_blocks)
    s = [rot_index_180(i) for i in anchor_blocks]
    # print(s)
    # print_board(PZL)
    PZL, blocks_left = fill_small_gaps(PZL, anchor_blocks, N_BLOCKS)
    # print_board(PZL)

    if PZL.find(SPACE) != -1:
        PZL = [*PZL]
        connected = explore(PZL, PZL.index(SPACE), {PZL.index(SPACE)})
        for j in range(len(PZL)):
            if j not in connected and PZL[j] == SPACE:
                PZL[j] = BLOCK
                blocks_left -= 1

    PZL = [*PZL]
    if N_BLOCKS % 2 == 1 == WIDTH % 2 == HEIGHT % 2:
        PZL[HEIGHT // 2 * WIDTH + WIDTH // 2] = BLOCK
        blocks_left -= 1
    PZL = ''.join(PZL)

    # print_board(PZL)
    # print("blocks left: ", N_BLOCKS - PZL.count(BLOCK))
    PZL = fill_rest(PZL, N_BLOCKS - PZL.count(BLOCK))
    PZL = PZL.replace('*', SPACE)
    # print_board(PZL)

make_pzl()
print_board(PZL)
print(PZL.count(BLOCK))


import sys;

def matrixChaninMul(p, n):

    m = [[0 for x in range(n)]for x in range(n)]
    s = [[0 for y in range(n)]for y in range(n)]

    for i in range(1, n):
        m[i][i] = 0

    for l in range(2, n):
        for i in range(1, n-l+1):
            j = i + l -1
            m[i][j] = 1000000
            for k in range(i,j):
                q = m[i][k] + m[k+1][j] + (p[i-1] * p[k] * p[j])
                if(q < m[i][j]):
                    m[i][j] = q
                    s[i][j] = k

    print("Minimum multiplications : {} " .format(m[1][n-1]))
    print("m matrix is")
    print(m)
    return s

def printOptimalParan(s, i, j):
    if(i == j):
        print("A {}" .format(i))
    else:
        print("(", end='')
        printOptimalParan(s, i, s[i][j])
        printOptimalParan(s, s[i][j]+1, j)
        print(")", end='')

p = []
n = int(input("Enter number of elements in size matrix : "))
for i in range(0,n):
    x = int(input("Enter the size {} : " .format(i)))
    p.append(x)

u = []
u = matrixChaninMul(p, n)
print("Order of multiplication : \n")
printOptimalParan(u, 1, n-1)
print("\n")
print(u)


import numpy as np
import matplotlib.pyplot as plt

merge = np.load('plot_data/flow_10.0.npy', allow_pickle=True)
leading = np.load('plot_data/flow_00.0.npy', allow_pickle=True)

acc_merge = merge[:,2].astype(np.float)
acc_leading = leading[:,2].astype(np.float)

pos_merge = merge[:,3].astype(np.float)
pos_leading = leading[:,3].astype(np.float)

vel_merge = merge[:,4].astype(np.float)
vel_leading = leading[:,4].astype(np.float)

plt.title("Accelerations")
plt.xlabel("Time Step")
plt.ylabel("Acceleration (m/s^2)")
plt.plot(acc_merge, color ="red", label = "merging vehicle")
plt.plot(acc_leading, color ="green", label = "leading inflow vehicle")
plt.legend(loc="upper right")
plt.show()

plt.title("Positions")
plt.xlabel("Time Step")
plt.ylabel("Positions (m)")
plt.plot(pos_merge, color ="red", label = "merging vehicle")
plt.plot(pos_leading, color ="green", label = "leading inflow vehicle")
plt.legend(loc="upper right")
plt.show()

plt.title("Velocities")
plt.xlabel("Time Step")
plt.ylabel("Velocities (m/s)")
plt.plot(vel_merge, color ="red", label = "merging vehicle")
plt.plot(vel_leading, color ="green", label = "leading inflow vehicle")
plt.legend(loc="upper right")
plt.show()