import json

import logging

import unittest

import mock

from osm_mon.plugins.OpenStack.Aodh import alarming as alarm_req
from osm_mon.plugins.OpenStack.common import Common

log = logging.getLogger(__name__)

auth_token = mock.ANY
endpoint = mock.ANY

class Response(object):
    """Mock a response message class."""

    def __init__(self, result):
        """Initialise the response text and status code."""
        self.text = json.dumps(result)
        self.status_code = "MOCK_STATUS_CODE"

class TestAlarming(unittest.TestCase):
    """Tests for alarming class functions."""

    maxDiff = None

    def setUp(self):
        """Setup for tests."""
        super(TestAlarming, self).setUp()
        self.alarming = alarm_req.Alarming()
        self.alarming.common = Common()

    @mock.patch.object(alarm_req.Alarming, "check_payload")
    @mock.patch.object(alarm_req.Alarming, "check_for_metric")
    @mock.patch.object(Common, "_perform_request")
    def test_config_invalid_alarm_req(self, perf_req, check_metric, check_pay):
        """Test configure an invalid alarm request."""
        # Configuring with invalid alarm name results in failure
        values = {"alarm_name": "my_alarm",
                  "metric_name": "my_metric",
                  "resource_uuid": "my_r_id"}
        self.alarming.configure_alarm(endpoint, auth_token, values)
        perf_req.assert_not_called
        perf_req.reset_mock()

        # Correct alarm_name will check for metric in Gnocchi
        # If there isn't one an alarm won;t be created
        values = {"alarm_name": "disk_write_ops",
                  "metric_name": "disk_write_ops",
                  "resource_uuid": "my_r_id"}

        check_metric.return_value = None

        self.alarming.configure_alarm(endpoint, auth_token, values)
        perf_req.assert_not_called

    @mock.patch.object(alarm_req.Alarming, "check_payload")
    @mock.patch.object(alarm_req.Alarming, "check_for_metric")
    @mock.patch.object(Common, "_perform_request")
    def test_config_valid_alarm_req(self, perf_req, check_metric, check_pay):
        """Test config a valid alarm."""
        # Correct alarm_name will check for metric in Gnocchi
        # And conform that the payload is configured correctly
        values = {"alarm_name": "disk_write_ops",
                  "metric_name": "disk_write_ops",
                  "resource_uuid": "my_r_id"}

        check_metric.return_value = "my_metric_id"
        check_pay.return_value = "my_payload"

        self.alarming.configure_alarm(endpoint, auth_token, values)
        perf_req.assert_called_with(
            "<ANY>/v2/alarms/", auth_token,
            req_type="post", payload="my_payload")

    @mock.patch.object(Common, "_perform_request")
    def test_delete_alarm_req(self, perf_req):
        """Test delete alarm request."""
        self.alarming.delete_alarm(endpoint, auth_token, "my_alarm_id")

        perf_req.assert_called_with(
            "<ANY>/v2/alarms/my_alarm_id", auth_token, req_type="delete")

    @mock.patch.object(Common, "_perform_request")
    def test_invalid_list_alarm_req(self, perf_req):
        """Test invalid list alarm_req."""
        # Request will not be performed with out a resoure_id
        list_details = {"mock_details": "invalid_details"}
        self.alarming.list_alarms(endpoint, auth_token, list_details)

        perf_req.assert_not_called

    @mock.patch.object(Common, "_perform_request")
    def test_valid_list_alarm_req(self, perf_req):
        """Test valid list alarm request."""
        # Minimum requirement for an alarm list is resource_id
        list_details = {"resource_uuid": "mock_r_id"}
        self.alarming.list_alarms(endpoint, auth_token, list_details)

        perf_req.assert_called_with(
            "<ANY>/v2/alarms/", auth_token, req_type="get")
        perf_req.reset_mock()

        # Check list with alarm_name defined
        list_details = {"resource_uuid": "mock_r_id",
                        "alarm_name": "my_alarm",
                        "severity": "critical"}
        self.alarming.list_alarms(endpoint, auth_token, list_details)

        perf_req.assert_called_with(
            "<ANY>/v2/alarms/", auth_token, req_type="get")

    @mock.patch.object(Common, "_perform_request")
    def test_ack_alarm_req(self, perf_req):
        """Test update alarm state for acknowledge alarm request."""
        self.alarming.update_alarm_state(endpoint, auth_token, "my_alarm_id")

        perf_req.assert_called_with(
            "<ANY>/v2/alarms/my_alarm_id/state", auth_token, req_type="put",
            payload=json.dumps("ok"))

    @mock.patch.object(alarm_req.Alarming, "check_payload")
    @mock.patch.object(Common, "_perform_request")
    def test_update_alarm_invalid(self, perf_req, check_pay):
        """Test update alarm with invalid get response."""
        values = {"alarm_uuid": "my_alarm_id"}

        self.alarming.update_alarm(endpoint, auth_token, values)

        perf_req.assert_called_with(mock.ANY, auth_token, req_type="get")
        check_pay.assert_not_called

    @mock.patch.object(alarm_req.Alarming, "check_payload")
    @mock.patch.object(Common, "_perform_request")
    def test_update_alarm_invalid_payload(self, perf_req, check_pay):
        """Test update alarm with invalid payload."""
        resp = Response({"name": "my_alarm",
                         "state": "alarm",
                         "gnocchi_resources_threshold_rule":
                         {"resource_id": "my_resource_id",
                          "metric": "my_metric"}})
        perf_req.return_value = resp
        check_pay.return_value = None
        values = {"alarm_uuid": "my_alarm_id"}

        self.alarming.update_alarm(endpoint, auth_token, values)

        perf_req.assert_called_with(mock.ANY, auth_token, req_type="get")
        self.assertEqual(perf_req.call_count, 1)

    @mock.patch.object(alarm_req.Alarming, "check_payload")
    @mock.patch.object(Common, "_perform_request")
    def test_update_alarm_valid(self, perf_req, check_pay):
        """Test valid update alarm request."""
        resp = Response({"name": "my_alarm",
                         "state": "alarm",
                         "gnocchi_resources_threshold_rule":
                         {"resource_id": "my_resource_id",
                          "metric": "my_metric"}})
        perf_req.return_value = resp
        values = {"alarm_uuid": "my_alarm_id"}

        self.alarming.update_alarm(endpoint, auth_token, values)

        check_pay.assert_called_with(values, "my_metric", "my_resource_id",
                                     "my_alarm", alarm_state="alarm")

        self.assertEqual(perf_req.call_count, 2)
        # Second call is the update request
        perf_req.assert_called_with(
            '<ANY>/v2/alarms/my_alarm_id', auth_token,
            req_type="put", payload=check_pay.return_value)

    def test_check_valid_payload(self):
        """Test the check payload function for a valid payload."""
        values = {"severity": "warning",
                  "statistic": "COUNT",
                  "threshold_value": 12,
                  "operation": "GT"}
        payload = self.alarming.check_payload(
            values, "my_metric", "r_id", "alarm_name")

        self.assertEqual(
            json.loads(payload), {"name": "alarm_name",
                                  "gnocchi_resources_threshold_rule":
                                  {"resource_id": "r_id",
                                   "metric": "my_metric",
                                   "comparison_operator": "gt",
                                   "aggregation_method": "count",
                                   "threshold": 12,
                                   "resource_type": "generic"},
                                  "severity": "low",
                                  "state": "ok",
                                  "type": "gnocchi_resources_threshold",
                                  "alarm_actions": ["http://localhost:8662"]})

    def test_check_valid_state_payload(self):
        """Test the check payload function for a valid payload with state."""
        values = {"severity": "warning",
                  "statistic": "COUNT",
                  "threshold_value": 12,
                  "operation": "GT"}
        payload = self.alarming.check_payload(
            values, "my_metric", "r_id", "alarm_name", alarm_state="alarm")

        self.assertEqual(
            json.loads(payload), {"name": "alarm_name",
                                  "gnocchi_resources_threshold_rule":
                                  {"resource_id": "r_id",
                                   "metric": "my_metric",
                                   "comparison_operator": "gt",
                                   "aggregation_method": "count",
                                   "threshold": 12,
                                   "resource_type": "generic"},
                                  "severity": "low",
                                  "state": "alarm",
                                  "type": "gnocchi_resources_threshold",
                                  "alarm_actions": ["http://localhost:8662"]})

    def test_check_invalid_payload(self):
        """Test the check payload function for an invalid payload."""
        values = {"alarm_values": "mock_invalid_details"}
        payload = self.alarming.check_payload(
            values, "my_metric", "r_id", "alarm_name")

        self.assertEqual(payload, None)

    @mock.patch.object(Common, "_perform_request")
    def test_get_alarm_state(self, perf_req):
        """Test the get alarm state function."""
        self.alarming.get_alarm_state(endpoint, auth_token, "alarm_id")

        perf_req.assert_called_with(
            "<ANY>/v2/alarms/alarm_id/state", auth_token, req_type="get")

    @mock.patch.object(Common, "get_endpoint")
    @mock.patch.object(Common, "_perform_request")
    def test_check_for_metric(self, perf_req, get_endpoint):
        """Test the check for metric function."""
        get_endpoint.return_value = "gnocchi_endpoint"

        self.alarming.check_for_metric(auth_token, "metric_name", "r_id")

        perf_req.assert_called_with(
            "gnocchi_endpoint/v1/metric/", auth_token, req_type="get")


import re

class Node :
    def __init__(self, value, next = None):
        self.value = value
        self.next = next

class Reverse_LinkedList:
    def __init__(self, head= None):
        self.head = head

    def to_string(self):
        current = self.head
        values = ""
        while current:
            values += f"{ {current.value} } -> "
            list_values = re.sub(r"\'", ' ', values)
            current = current.next
        list_values += "NONE"
        return list_values

    def append(self, new_value):
            new_node = Node(new_value)
            if self.head is None:
                self.head = new_node
            else:
                current = self.head
                while current.next:
                    current = current.next
                current.next = new_node

    def reverse(self):
        prev = None
        curr = self.head
        while curr:
            newNode = curr.next
            curr.next = prev
            prev = curr
            curr = newNode
        self.head = prev
        return self.head

reverse= Reverse_LinkedList()
reverse.append(1)
reverse.append(2)
reverse.append(3)
print(reverse.to_string())
reverse.reverse()
print(reverse.to_string())


from email.policy import HTTP
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.utils.html import escape

from ..business.bcainvdetu import BCaInvDetU
from ..business.bcainvcab import BCaInvCab
from base.business.bproducto import BProducto
from .serializer import ProductoSerializer
from base.models import CaInvCab, CaInvDet
from base.choices import EstadoInventarioChoices
from base.business.bcainvdet import BCaInvDet
from base.config import Sistema
from base.business.blog import BLog

@api_view(['GET'])
def getRoutes(request):
    routes = [
        'GET /api',
        'GET /api/getinvcab/',
        'POST /api/additem/',
        'GET /api/getinvdet/id_invcab/producto_codigo',
        'GET /api/getlistinvdet/id_invcab',
        'GET /api/getlistinvdetu/id_invcab/s_ubicacion/id_conteo',
        'GET /api/getlistinvdetugroup/id_invcab',
    ]
    return Response(routes)

@api_view(['GET'])
def get_productos(request):
    oBProducto = BProducto()
    productos = oBProducto.get_all()
    serializer = ProductoSerializer(productos, many=True)
    return Response(serializer.data)

@api_view(['GET', 'POST'])
def get_producto(request, id=None):
    if request.method == 'GET':
        oBProducto = BProducto()
        producto = oBProducto.get(id)
        serializer = ProductoSerializer(producto, many=False)
        data_response = {
            'status' : status.HTTP_200_OK if producto is not None else status.HTTP_204_NO_CONTENT,
            'data' : serializer.data if producto is not None else {}
        }
        return Response(data_response)

    elif request.method == 'POST':
        print('POST', request.data)
        return Response({})

@api_view(['POST'])
def add_item(request):
    # print('POST api/additem', request.data)
    print(request, request.data)

    #oBLOg = BLog()

    try:
        data = request.data
        ca_inv_cab_id = data['ca_inv_cab_id']
        id_conteo = data['id_conteo']
        producto_codigo = data['producto_codigo']
        s_ubicacion = data['s_ubicacion']
        cantidad = data['cantidad']

        # oBLOg.save(None, 'new', 0, {'modulo':'api', 'accion':'getadditem',
        #     'detalle': f'request: {ca_inv_cab_id} - {producto_codigo} - {s_ubicacion} - {cantidad}'})

        if len(s_ubicacion) == 0:
            s_ubicacion = Sistema.UBICACION_UNICA

        oBCaInvCab = BCaInvCab()
        if not oBCaInvCab.add_item(
            ca_inv_cab_id,
            producto_codigo,
            s_ubicacion,
            cantidad,
            id_conteo):
            status_id = status.HTTP_404_NOT_FOUND
            message = oBCaInvCab.message
        else:
            status_id = status.HTTP_200_OK
            message = 'OK'

        data_response = {
            'status' : status_id,
            'data' : data,
            'message': message
        }

        # oBLOg.save(None, 'new', 0,
        #     {'modulo':'api', 'accion':'getadditem',
        #     'detalle':f'response: OK - {ca_inv_cab_id} - {producto_codigo} - {s_ubicacion} - {cantidad}' if status_id==status.HTTP_200_OK else f'response ERROR {message}'
        #     }
        # )

    except Exception as e:
        data_response = {
            'status' : status.HTTP_400_BAD_REQUEST ,
            'data' : {},
            'message': f'Ocurrió un error except. {e}'
        }
        # oBLOg.save(None, 'new', 0,
        #     {'modulo':'api', 'accion':'getadditem',
        #     'detalle':f'response: OK - {data_response["status"]} - {data_response["message"]}'
        #     }
        # )

    return Response(data_response)

@api_view(['GET'])
def get_invcab(request):
    print(request)

    aTO = CaInvCab.objects.all().filter(estado_inventario=EstadoInventarioChoices.opened)
    if aTO:
        oTO:CaInvCab = aTO[0]
        data_response = {
            'status': status.HTTP_200_OK,
            'data': {
                'id': oTO.id,
                's_descripcion': oTO.s_descripcion,
                'empleado_nombre_copleto': oTO.empleado.s_nombre_completo,
                's_fecha_inicio': oTO.s_fecha_inicio
            }
        }
    else:
        data_response = {
            'status': status.HTTP_204_NO_CONTENT,
            'data': {}
        }

    return Response(data_response)

@api_view(['GET'])
def get_invdet(request, id_invcab:int, producto_codigo:str):
    print(request)

    # print(request.META['SESSION_MANAGER'])
    # print(request.META['REMOTE_ADDR'])
    # print(request.META['REMOTE_HOST'])
    # print(request.META['SERVER_NAME'])
    # print(request.META['QUERY_STRING'])
    # print(request.META['HTTP_USER_AGENT'])
    # print(request.META['HTTP_HOST'])
    # print(request.META['CONTENT_TYPE'])
    # print(request.headers['User-Agent'])

    producto_codigo = escape(producto_codigo)

    oBCaInvDet = BCaInvDet()
    oTO:CaInvDet = oBCaInvDet.get_item(id_invcab, producto_codigo)
    if oTO == None:
        data_response = {
            'status': status.HTTP_204_NO_CONTENT,
            'data' : {}
        }
    else:
        data_response = {
            'status': status.HTTP_200_OK,
            'data' : oBCaInvDet.get_oTO_toDict(oTO)
            # 'data': {
            #     'id': oTO.producto.id,
            #     's_descripcion': oTO.s_descripcion,
            #     's_codigo': oTO.producto.s_codigo,
            #     'unidad_medida_s_codigo': oTO.unidad_medida.s_codigo,
            #     'unidad_medida_s_descripcion': oTO.unidad_medida.s_descripcion,
            #     'n_stk_act': oTO.n_stk_act,
            #     'ns_conteo1': oTO.ns_conteo1,
            #     'ns_conteo2': oTO.ns_conteo2,

            # }
        }
    return Response(data_response)

@api_view(['GET'])
def get_list_invdet(request, id_invcab):
    print(request)

    oBCaInvDet = BCaInvDet()
    oBCaInvDet.get_all_invcab(id_invcab)
    aCaInvDet = oBCaInvDet.get_aTO_toArray()
    if not aCaInvDet:
        data_response = {
            'status': status.HTTP_204_NO_CONTENT,
            'data' : []
        }
    else:
        data_response = {
            'status': status.HTTP_200_OK,
            'data': aCaInvDet
        }
    return Response(data_response)

@api_view(['GET'])
def get_list_invdetu(request, id_invcab, s_ubicacion, id_conteo):
    print(request)

    oBCaInvDetU = BCaInvDetU()
    oBCaInvDetU.get_all_inv_ubi_conteo(id_invcab, s_ubicacion, id_conteo)
    aCaInvDetU = oBCaInvDetU.get_aTO_toArray()
    if not aCaInvDetU:
        data_response = {
            'status': status.HTTP_204_NO_CONTENT,
            'data' : []
        }
    else:
        data_response = {
            'status': status.HTTP_200_OK,
            'data': aCaInvDetU
        }
    return Response(data_response)

@api_view(['GET'])
def get_list_invdetu_group(request, id_invcab):
    print(request)

    oBCaInvDetU = BCaInvDetU()
    aCaInvDetU = oBCaInvDetU.get_all_ubi_group(id_invcab)
    #aCaInvDetU = oBCaInvDetU.get_aTO_toArray()
    if not aCaInvDetU:
        data_response = {
            'status': status.HTTP_204_NO_CONTENT,
            'data' : []
        }
    else:
        data_response = {
            'status': status.HTTP_200_OK,
            'data': aCaInvDetU
        }
    return Response(data_response)


import turtle
x1, y1 = eval(input("Enter the value of x1 and y1 from point 1:  "))
x2, y2 = eval(input("Enter the value of x2 and y2 from point 2:  "))

distance = ((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2))**0.5

#print(f"The difference between given points is {distance}")

turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
turtle.write("Point 1")
turtle.goto(x2, y2)
turtle.write("Point 2")
turtle.penup()

turtle.goto((x1 + x2) / 2, (y1 + y2) / 2)

turtle.write(distance)
turtle.done()


from __future__ import absolute_import

__all__ = ('Device', )

from sentry.interfaces.base import Interface, InterfaceValidationError
from sentry.interfaces.schemas import validate_and_default_interface
from sentry.utils.safe import trim, trim_dict

class Device(Interface):
    """
    An interface which describes the device.

    >>> {
    >>>     "name": "Windows",
    >>>     "version": "95",
    >>>     "build": "95.0.134.1651",
    >>>     "arbitrary": "data"
    >>> }
    """
    path = 'device'

    @classmethod
    def to_python(cls, data):
        is_valid, errors = validate_and_default_interface(data, cls.path)
        if not is_valid:
            raise InterfaceValidationError("Invalid device")

        data = data.copy()

        extra_data = data.pop('data', data)
        name = trim(data.pop('name'), 64)
        version = trim(data.pop('version'), 64)
        build = trim(data.pop('build', None), 64)

        kwargs = {
            'name': name,
            'version': version,
            'build': build,
            'data': trim_dict(extra_data),
        }
        return cls(**kwargs)

    def get_api_context(self, is_public=False):
        return {
            'name': self.name,
            'version': self.version,
            'build': self.build,
            'data': self.data,
        }

    def get_path(self):
        return 'device'

    def get_hash(self):
        return []


'''
完成
验证消息合法性
'''
from message.transaction import Transaction
from message.vote import Vote
from tree.block.block import Block
'''
description: 验证消息合法性,vote,transaction,block....
input: msg-->obj
output: True&False
'''
def messageValidation(msg):
    if isinstance(msg, Transaction):
        return msg.validate()
    elif isinstance(msg, Vote):
        return msg.validate()
    elif isinstance(msg, Block):
        return msg.validate()
    else:
        return False


from typing import TypeAlias

from foundry import data_dir
from foundry.game.Data import Mario3Level
from smb3parse.util import hex_int

LevelAddress: TypeAlias = int
EnemyItemAddress: TypeAlias = int

ObjectData: TypeAlias = tuple[LevelAddress, bytearray]
EnemyItemData: TypeAlias = tuple[EnemyItemAddress, bytearray]
LevelByteData: TypeAlias = tuple[ObjectData, EnemyItemData]

EMPTY_OBJECT_DATA: ObjectData = (-1, bytearray())
EMPTY_ENEMY_DATA: EnemyItemData = (-1, bytearray())

def _load_level_offsets() -> tuple[list[Mario3Level], list[int]]:
    offsets = [Mario3Level(0, 0, 0, 0, 0, "Placeholder")]
    world_indexes = [0]

    with open(data_dir.joinpath("levels.dat"), "r") as level_data:
        for line_no, line in enumerate(level_data.readlines()):
            data = line.rstrip("\n").split(",")

            numbers = map(hex_int, data[0:5])
            level_name = data[5]

            (
                game_world,
                level_in_world,
                rom_level_offset,
                enemy_offset,
                real_obj_set,
            ) = numbers

            level = Mario3Level(
                game_world,
                level_in_world,
                rom_level_offset,
                enemy_offset,
                real_obj_set,
                level_name,
            )

            offsets.append(level)

            if level.game_world > 0 and level.level_in_world == 1:
                world_indexes.append(line_no)

    return offsets, world_indexes


import platform
import json
from flask import Flask
from flask import render_template
from cpuinfo import get_cpu_info
import os
import socket

class Machine:
    # constructor where i get all system information
    def __init__(self):
        cpu_data = get_cpu_info()

        self.type = platform.machine()
        self.name = platform.node()
        self.system = platform.system()
        self.release = platform.release()
        self.cpu_version = cpu_data["cpuinfo_version_string"]
        self.cpu_bits = cpu_data["bits"]
        self.cpu_frequence = cpu_data["hz_advertised_friendly"]
        self.cpu_brand = cpu_data["brand_raw"]

    # return the instance as a dictonary
    def getDico(self):
        return {
            'Systeme': self.system,
            'Release': self.release,
            'Type': self.type,
            'name': self.name,
            'Version du CPU': self.cpu_version,
            'Bits du CPU': self.cpu_bits,
            'Marque du CPU': self.cpu_brand,
            'Frequence du CPU': self.cpu_frequence
        }

    # start flask
    def start(self):
        app = Flask(__name__)

        @app.route("/")
        def MyMachine():
            return render_template("index.html", maMachine = self.getDico())

        app.run()

tmp = Machine()
tmp.start()


class TDelta (object) :
    def __init__(self,numb):
        self.lookup=[(31536000000,"yr"),(86400000,"day"),(3600000,"hr"),(60000,"min"),(1000,"sec") ]
        self. res = {}
        self.time_span(numb,0)

    def time_span(self,d,n) :
        limit = 4
        cnt = 0
        rem = d
        x = self.lookup[n][0]
        if d>x :
            cnt = (d/x)
            rem = (d%x)
        n+=1
        if n<= limit :
            self.time_span(rem,n)

        if cnt :
            self.res[self.lookup[n-1][1]] = int(cnt)
        else :
            self.res[self.lookup[n-1][1]] = 0


#다리를 지나는 트럭
#트럭 여러 대가 강을 가로지리는 일차선 다리를 정해진 순으로 건너려 한다.
#모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지.
#다리에는 트럭이 최대 bridge_length대 올라갈 수 있고,
#다리는 weight 이하까지의 무게를 견딜 수 있다.
#단, 다리에 완전히 오르지 않은 트럭의 무게는 무시.

#트럭 2대가 올라갈 수 있고 무게를 10kg까지 견디는 다리가 있다면.
#무게가 7,4,5,6kg 인 트럭이 순서대로 최단시간안에 다리를 건너려면 다음과 같이 건넘.
# def solution(bridge_length, weight, truck_weights):
#     answer = 0
#     cnt = 0
#     a=[]
#     while True:
#         x = truck_weights.pop(0)
#         if truck_weights ==[]:
#             cnt +=bridge_length
#             break
#         else:
#             if x+truck_weights[0] < weight:
#                 a.append(x)
#             else:
#                 a.append(0)
#             cnt +=1
#     return answer
# print(solution(2,10,[7,4,5,6]))
# print(solution(100,100,[10]))
#다리길이가 정의가 안되어 있다.

# def solution(bridge_length, weight, truck_weights):
#     b = [0 for i in range(bridge_length)] #다리의 길이를 초기화 즉 길이만큼 0을 넣음
#     answer= 0
#     while True:
#         b.pop(0) #7이들어가기 위해서 하나를 pop
#         answer +=1 #카운트.
#         if len(truck_weights)>0 and sum(b)+truck_weights[0]<=weight:
#             #트럭숫자가 없으면 아래로 내려감.
#             #다리에 있는 트럭 + 갈려는 트럭 에 무게가 다리의 무게를 초과하지 않으면.
#             b.append(truck_weights.pop(0))
#             #다리에 트럭추가.
#         else:
#             b.append(0) #그렇지 않으면 0을 추가해줘서 다리길이 유지.
#         if len(truck_weights) ==0 and sum(b) ==0:
#             #무한루프 break 하는 조건문
#             break
#
#     return answer

# print(solution(2,10,[7,4,5,6]))
# print(solution(100,100,[10]))
#92.9 테스트5만 통과 안댐
#질문하기에서 식을 참고했..

def solution(bridge_length, weight, truck_weights):
    bridge = [0]*bridge_length
    answer= 0
    while True:
        bridge.pop()
        answer +=1
        if len(truck_weights)>0 and sum(bridge)+truck_weights[0]<=weight:
            bridge.insert(0,truck_weights.pop(0))
        else:
            bridge.insert(0,0)
        if len(truck_weights) ==0 and sum(bridge) ==0:
            break

    return answer

print(solution(2,10,[7,4,5,6]))
print(solution(100,100,[10]))
#92.9 테스트5만 통과 안댐
#pop(0) 의 문제가 아니다.
#pop 을 통해 뒤에 값을 지우고 insert 를 통해 앞에다가 값을 추가함
#그냥 앞뒤만 바뀐것뿐 pop(0) 쓰는 숫자를 줄여봄. 근데 아님.

def solution(bridge_length, weight, truck_weights):
    answer = 0
    trucks_on_bridge = [0] * bridge_length

    while len(trucks_on_bridge):
        answer += 1
        trucks_on_bridge.pop(0)
        if truck_weights:
            if sum(trucks_on_bridge) + truck_weights[0] <= weight:
                trucks_on_bridge.append(truck_weights.pop(0))
            else:
                trucks_on_bridge.append(0)
    return answer
print(solution(2,10,[7,4,5,6]))
print(solution(100,100,[10]))
#if 문 하나로 조건 두개 지워버림 무한루프도 안썻고.
#근데 웃긴건 이것도 5번 틀림 -> 변수명 길이차이

def solution(bridge_length, weight, truck_weights):
    time = 0
    q = [0] * bridge_length

    while q:
        time += 1
        q.pop(0)
        if truck_weights:
            if sum(q) + truck_weights[0] <= weight:
                q.append(truck_weights.pop(0))
            else:
                q.append(0)

    return time
#찐막.
#while 문 차이?

#0 for i in range(bridge_length)
#[표현식 for 항목 in 반복가능객체 if 조건문]

#b는 배열 안에 배열들을 선언하는 게 아니라 각각 배열들을 선언
#a는 배열 안에 2차원 배열을 선언
#따라서 a 처럼 선언하고 2차원 배열에 값을 넣으면 2차원 좌표가 아니라
#모든 배열이 동시에 같은 값을 넣게됨
#출력 해줄때 같은 것처럼 보이는데 전혀 다르다.
# a = [[0] * 2] * 3
# b = [[0] * 2 for _ in range(3)]

# a[0][0] = 1
# b[0][0] = 1

# print(a)
# print(b)

# # 출력
# [[1, 0], [1, 0], [1, 0]]
# [[1, 0], [0, 0], [0, 0]]


from PIL import Image
from pptx import Presentation
from pptx.util import Inches, Pt
import os
import sys
import math

prs = Presentation()
# adjustable, in inches
prs.slide_width = Inches(16)
prs.slide_height = Inches(9)

blank_slide_layout = prs.slide_layouts[6] # an empty slide

def get_image_size(image_path): # obtain size of image in inches
    img = Image.open(image_path)
    pixelWidth = float(img.size[0])
    pixelHeight = float(img.size[1])
    try:
        dpi = float(img.info['dpi'][0])
    except:
        #print("image "+image_path+" does not contain dpi info. uses dpi=96 for now")
        dpi = 96 # tekitou
    imageWidth = pixelWidth/dpi
    imageHeight = pixelHeight/dpi
    return imageWidth, imageHeight

def align_CTA_style(imageNames, mW, mH, slideWidth, slideHeight):
    columns={}
    # put each of sorted figureName lists to a dictionary
    # the name of order in this dictionaly decides the figure order in pptx.
    for TCA in ["CTL","TST","ANL","CMP","ETC","MAM","JJA","SON","DJF"]:
        if any(iN[:3] == TCA for iN in imageNames): # only if figureName that start with specified header exists
            columns[TCA]=sorted([iN for iN in imageNames if TCA == iN[:3]])

    num_columns=0
    num_rows=0
    for TCA, figNameList in columns.items():
        if len(figNameList) > num_rows:
            num_rows=len(figNameList)
        num_columns+=1

    # transpose if it can make figure bigger
    asis=abs(slideHeight/slideWidth-num_rows*mH/(num_columns*mW))
    transpose=abs(slideHeight/slideWidth-num_columns*mH/(num_rows*mW))
    if asis > transpose:
        tp=True
    else:
        tp=False

    return get_positions(columns,num_columns,num_rows,mW, mH,slideWidth, slideHeight,tp)

def align_tile_style(imageNames, mW, mH, slideWidth, slideHeight):
    columns={}
    num_columns, num_rows = optimize(len(imageNames), mW, mH, slideWidth, slideHeight)
    i = 0
    imageNames=sorted(imageNames)
    for column_name in range(1, num_columns+1):
        columns[column_name]=imageNames[i:i+num_rows]
        i += num_rows
    return get_positions(columns,num_columns,num_rows,mW, mH,slideWidth, slideHeight, False)

def optimize(num_images, mW, mH, sW, sH):
    amari=99999
    if num_images == 1:
        return 1, 1
    for i in range(1,num_images+1):
        num_columns = i
        num_rows = math.ceil(num_images/i)
        if amari > abs(sH/sW-mH*num_rows/mW/num_columns):
          amari = abs(sH/sW-mH*num_rows/mW/num_columns)
          opt_columns = num_columns
          opt_rows = num_rows
    return opt_columns, opt_rows

# obtain the left, top, and height positions for each figures for the specified set of columns, rows
# to maximize the figure sizes while fitting into the slide-size-minus-padding.
def get_positions(columns, num_columns, num_rows, mW, mH, sW, sH, tp):
    if tp== True:
        figList, topList, leftList, ratio = get_positions(columns, num_rows, num_columns, mH, mW, sW, sH, False)
        return figList, leftList, topList, ratio
    else:
        figList=[]
        topList=[]
        leftList=[]
        heightList=[]
        left=0
        ratio_w=sW/(num_columns*mW)
        ratio_h=sH/(num_rows*mH)
        ratio = min(ratio_w,ratio_h)

        for TCA, figNameList in columns.items():
            top=0
            for fig in figNameList:
                figList.append(fig)
                topList.append(top)
                leftList.append(left)
                top+=mH*ratio
            left+=mW*ratio
        return figList, topList, leftList, ratio

def align_images(image_path, mW, mH, slideWidth, slideHeight):
    imageNames=os.listdir(image_path)
    headers= ["CTL","TST","ANL","CMP","ETC","MAM","JJA","SON","DJF"]
    if all(iN[:3] in headers for iN in imageNames): # all imageNames starts from any of headers
        print("uses alignment for test, control comparison")
        figNameList, topList, leftList, ratio = align_CTA_style(imageNames, mW, mH, slideWidth, slideHeight)
    elif all(iN[:1] in [str(i) for i in range(10)] for iN in imageNames): # all imageNames starts from integer numbers
        print("uses tiling alignment")
        figNameList, topList, leftList, ratio = align_tile_style(imageNames, mW, mH, slideWidth, slideHeight)
    else:
        print("figure names are out of order!")
    return figNameList, topList, leftList, ratio

def obtain_max_image_size(image_path): # obtain maximum image size in n-th directory
    maxImageWidth=maxImageHeight=0
    for img in os.listdir(image_path):
        imageWidth, imageHeight = get_image_size(image_path+"/"+img)
        if maxImageWidth < imageWidth:   maxImageWidth=imageWidth
        if maxImageHeight < imageHeight: maxImageHeight=imageHeight
    return maxImageWidth, maxImageHeight

def get_image_height(image_path):
    imageWidth, imageHeight = get_image_size(image_path)
    return imageHeight

def obtain_padding_list(root_path, sd):
    default = 1 #inches
    try:
        with open(root_path+"/padding.txt") as f:
            for line in f:
                if sd in line:
                    paddingList = line.split()
                    # given strings like slideid( 1( 2 3 4))
                    paddingList.pop(0)
                    if len(paddingList) == 0:
                        return default,default,default,default
                    if len(paddingList) == 1:
                        padding=float(paddingList[0])
                        return padding,padding,padding,padding
                    if len(paddingList) == 4:
                        return [float(padding) for padding in paddingList]
                    else:
                        print("too many or too less number(s) for "+sd+" in padding.txt")
        # if padding.txt does not contain slide info
        return default,default,default,default
    except:
        print("Not found: "+root_path+"/padding.txt")
        return default,default,default,default

root_path = sys.argv[1]
for sd in sorted(os.listdir(root_path)):
    if "slide" not in sd:
        continue

    print("processing " +sd+ "...")
    slide = prs.slides.add_slide(blank_slide_layout)
    image_path = root_path+'/'+sd
    maxImageWidth, maxImageHeight = obtain_max_image_size(image_path)
    if max(maxImageWidth,maxImageHeight)==0:
      continue
    # obtain the space in the slide to be left empty. Better alert if bigger than slide itself
    paddingLeft, paddingRight, paddingTop, paddingBottom = obtain_padding_list(root_path, sd)
    figList, topList, leftList, ratio = align_images(image_path, maxImageWidth, maxImageHeight,
                                                     prs.slide_width -Inches(paddingLeft + paddingRight),
                                                     prs.slide_height-Inches(paddingTop + paddingBottom))
    for fig, top, left in zip(figList, topList, leftList):
        pic = slide.shapes.add_picture(image_path+"/"+fig,
                                       left+Inches(paddingLeft), top+Inches(paddingTop),
                                       height=ratio*get_image_height(image_path+"/"+fig))

prs.save(root_path+'/temp.pptx')


"""Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

"""

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        def reverse(head):
            if head:
                cur = head.next
                head.next = None
                while(cur):
                    tmp = cur
                    cur = cur.next
                    tmp.next = head
                    head = tmp
            return head

        s = head
        f = head
        while(f and f.next):
            s = s.next
            f = f.next.next
        leftEnd = s
        if(f): #奇数个，让右边小，遍历比较的时候以小的为标准
            s = s.next
        s = reverse(s)
        rightHead = s
        f = head
        while(s):
            if s.val != f.val:
                if leftEnd:
                    reverse(rightHead)
                return False
            s = s.next
            f = f.next
        reverse(rightHead)
        return True

def print_node(head):
    print(head.val)
    if head.next:
        print_node(head.next)

if __name__ == '__main__':

    head = ListNode(0)
    cur = head
    for i in range(2,10,2):
        cur.next = ListNode(i)
        cur = cur.next
    print_node(head)
    s = Solution()
    print(s.isPalindrome(head))


import sys

sys.stdin = open('nextvector.in', 'r')
sys.stdout = open('nextvector.out', 'w')

s = input()
l = len(s)
i = l - 1
while s[i] != '1':
    i -= 1
    if i == -1:
        break
if i != -1:
    print(s[:i] + '0' + '1' * (l - i - 1))
else:
    print('-')
i = l - 1
while s[i] != '0':
    i -= 1
    if i == -1:
        break
if i != -1:
    print(s[:i] + '1' + '0' * (l - i - 1))
else:
    print('-')


import csv

import cv2
from keras.models import load_model
import numpy as np
from collections import deque
import os

model = load_model('QuickDraw.h5')
names = [
    "apple",
    "bow",
    "candle",
    "door",
    "envelope",
    "fish",
    "guitar",
    "ice-cream",
    "thunder",
    "moon",
    "mountain",
    "star",
    "tent",
    "broom",
    "watch",
    "apple"
]

def main():
    pts = []
    iter = 0
    blackboard = np.zeros((420, 700, 3), dtype=np.uint8)
    with open(f"data.csv") as f:
        lines = [line.rstrip('\n').replace("(", '').replace(")", '') for line in f]
        pts = [(int(cordStr.split(',')[0]), int(cordStr.split(',')[1])) for cordStr in lines]
    for i in range(1, len(pts)):
        if pts[i - 1] is None or pts[i] is None:
            continue
        cv2.line(blackboard, pts[i - 1], pts[i], (255, 255, 255), 7)
    blackboard_gray = cv2.cvtColor(blackboard, cv2.COLOR_BGR2GRAY)
    blur1 = cv2.medianBlur(blackboard_gray, 15)
    blur1 = cv2.GaussianBlur(blur1, (5, 5), 0)
    thresh1 = cv2.threshold(blur1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    blackboard_cnts = cv2.findContours(thresh1.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0]

    if len(blackboard_cnts) >= 1:
        cnt = max(blackboard_cnts, key=cv2.contourArea)
        if cv2.contourArea(cnt) > 2000:
            x, y, w, h = cv2.boundingRect(cnt)
            digit = blackboard_gray[y:y + h, x:x + w]
            pred_probab, pred_class = keras_predict(model, digit)
            #print(pts)
            #print(names[pred_class])
            with open('result.txt', mode='w') as final:
                final.write(names[pred_class])
            # with open(str(names[pred_class]) + str(iter) + '.csv', mode='w') as sample_file:
            #     writer = csv.writer(sample_file, delimiter='\n', quoting=csv.QUOTE_MINIMAL)
            #     writer.writerow(pts)
            #     iter += 1

def keras_predict(model, image):
    processed = keras_process_image(image)
    pred_probab = model.predict(processed)[0]
    pred_class = list(pred_probab).index(max(pred_probab))
    return max(pred_probab), pred_class

def keras_process_image(img):
    image_x = 28
    image_y = 28
    img = cv2.resize(img, (image_x, image_y))
    img = np.array(img, dtype=np.float32)
    img = np.reshape(img, (-1, image_x, image_y, 1))
    return img

if __name__ == '__main__':
    main()


from unittest import TestCase
from common.UserIdentificationLogic import *

def open_db():
    client = MongoClient('mongodb://127.0.0.1:27017')
    return client.UserProfileManagerDB

class Test(TestCase):

    def test_get_all_audios(self):
        db = open_db()
        sounds = get_all_audios(db)
        self.assertIsNotNone(sounds, 'Errore estrazione file wav')

    def test_match_audio(self):
        db = open_db()
        sounds = get_all_audios(db)
        flag = match_audio(sounds[0], sounds[0])
        self.assertTrue(flag, 'Errore match audio')

    def test_identify_user(self):
        db = open_db()
        sounds = get_all_audios(db)
        user = identify_user(sounds[0], 1, db)
        self.assertIsNotNone(user, 'Nessun utente trovato')


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

import requests
from urllib.parse import urlparse, urlunparse
from .message import Message

class Session:
    def __init__(self):
        self.messages = {}  #: my message catalog (message key => Message)
        self.friends = {}  #: my friends, trusted public keys (key => alias)
        self.private_key = None  #: my global private key
        self.public_key = None  #: my global public key
        self.public_key_str = None  #: my global public key (exported)
        self.routes = {}  #: known peers (public key => address)
        self.branches = set()  #: set of known branches
        self.loose_ends = {}  #: messages that reply to unknown keys

        # Networking
        self.external_app = None  #: web app for external api
        self.internal_app = None  #: web app for internal api
        self.client = requests.Session()  #: web client

    def register_message(self, message):
        if message.key is None:
            message.calculate_key()

        if message.in_reply_to is not None:
            replied = self.get_message(message.in_reply_to)
            if replied is not None:
                replied.branch.insert(message)
            else:
                self.loose_ends[message.in_reply_to] = message

        self.messages[message.key] = message

        if message.key in self.loose_ends:
            loose_branch = self.loose_ends.pop(message.key).branch
            message.branch.combine(loose_branch, self)
            self.branches.remove(loose_branch)

        self.branches.add(message.branch)

    def get_message_keys(self):
        return self.messages.keys()

    def get_message(self, key):
        return self.messages.get(key)

    def get_branch(self, key):
        message = self.get_message(key)
        return message.branch

    def get_branches(self):
        return self.branches

    def notify(self, address):
        r = self.client.get(address)
        if r.content_type == 'text/uri-list':
            keys = r.body.split(b'\n')
            urlinfo = list(urlparse(address))
            for key in keys:
                if key not in self.messages.keys():
                    urlinfo[2] = '/m/' + key.decode('utf8')
                    print(urlinfo)
                    self.notify(urlunparse(urlinfo))
        else:
            message = Message.from_http(r.body, r.headers)
            self.register_message(message)


# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import

import os
import glob

import imageio
import scipy.misc as misc
import numpy as np
import copy as cp

import matplotlib.pyplot as plt
import matplotlib.image as img
import pylab

import tensorflow as tf

def get_uninitialized_variables(sess,var_list):
    unitialized=[]
    for var in var_list:
        try:
            sess.run(var)
        except tf.errors.FailedPreconditionError:
            unitialized.append(var)
    return unitialized

def pad_seq(seq, batch_size):
    # pad the sequence to be the multiples of batch_size
    seq_len = len(seq)
    if seq_len % batch_size == 0:
        return seq
    padded = batch_size - (seq_len % batch_size)
    seq.extend(seq[:padded])
    return seq

def normalize_image(img):
    """
    Make image zero centered and in between (-1, 1)
    """
    normalized = (img / 127.5) - 1.
    return normalized

def read_split_image(img):
    mat = misc.imread(img).astype(np.float)
    side = int(mat.shape[1] / 2)
    assert side * 2 == mat.shape[1]
    img_A = mat[:, :side]  # target [0,1,2]
    img_B = mat[:, side:]  # source

    return img_A, img_B

def shift_and_resize_image(img, shift_x, shift_y, nw, nh):
    w=img.shape[0]
    h=img.shape[1]
    enlarged = misc.imresize(img, [nw, nh])
    return enlarged[shift_x:shift_x + w, shift_y:shift_y + h]

# def scale_back(images):
#     return (images + 1.) / 2.

def scale_with_probability(images,channels,probability):

    if np.sum(probability) < 0:
        probability = - probability
    batchsize = images.shape[0]
    h = images.shape[1]
    w = images.shape[2]
    probability = np.reshape(probability, [batchsize, 1])
    if channels==1:
        probability=np.reshape(probability,[batchsize,1,1])
        probability=np.tile(probability,[1,h,w])
        probability=np.reshape(probability,[probability.shape[0],probability.shape[1],probability.shape[2],1])
    elif channels==3:
        probability = np.reshape(probability, [batchsize, 1, 1, 1])
        probability = np.tile(probability, [1, h, w,channels])
    images = np.multiply(probability,images)
    return images

def scale_back_for_img(images):

    if np.min(images) == np.max(images):
        return images
    min_v=np.min(images)
    images=images-min_v
    max_v=np.max(images)
    images=np.float32(images)/np.float32(max_v)
    return images
def scale_back_for_dif(images):
    images = np.abs(images)
    if np.min(images) == np.max(images):
        return images

    min_v=np.min(images)
    images=images-min_v
    max_v=np.max(images)
    images=np.float32(images)/np.float32(max_v)
    return images

def image_show(img):
    img_out = cp.deepcopy(img)
    img_out = np.squeeze(img_out)
    img_shapes=img_out.shape
    if len(img_shapes)==2:
        curt_channel_img = img_out
        min_v = np.min(curt_channel_img)
        curt_channel_img = curt_channel_img - min_v
        max_v = np.max(curt_channel_img)
        curt_channel_img = curt_channel_img/ np.float32(max_v)
        img_out = curt_channel_img*255
    elif img_shapes[2] == 3:
        channel_num = img_shapes[2]
        for ii in range(channel_num):
            curt_channel_img = img[:,:,ii]
            min_v = np.min(curt_channel_img)
            curt_channel_img = curt_channel_img - min_v
            max_v = np.max(curt_channel_img)
            curt_channel_img = curt_channel_img / np.float32(max_v)
            img_out[:,:,ii] = curt_channel_img*255
    else:
        print("Channel Number is INCORRECT:%d" % img_shapes[2])
    plt.imshow(np.float32(img_out)/255)
    pylab.show()

def image_revalue(img,tah_mark):
    img_out = cp.deepcopy(img)
    img_out = np.squeeze(img_out)
    if tah_mark:
        img_out = np.tanh(img_out)
    return img_out

def merge(images, size):
    h, w = images.shape[1], images.shape[2]
    img = np.zeros((h * size[0], w * size[1], 3))
    for idx, image in enumerate(images):
        i = idx % size[1]
        j = idx // size[1]
        img[j * h:j * h + h, i * w:i * w + w, :] = image

    return img

def save_concat_images(imgs, img_path):
    concated = np.concatenate(imgs, axis=1)
    misc.imsave(img_path, concated)

def compile_frames_to_gif(frame_dir, gif_file):
    frames = sorted(glob.glob(os.path.join(frame_dir, "*.png")))
    print(frames)
    images = [misc.imresize(imageio.imread(f), interp='nearest', size=0.33) for f in frames]
    imageio.mimsave(gif_file, images, duration=0.1)
    return gif_file

def calculate_weighted_loss(weight,loss_org,penalty=1):

    loss_org_shape_dim = loss_org.shape.ndims
    weight_matrix_reshape = [int(weight.shape[0])]
    weight_matrix_tile = [1]
    for ii in range(loss_org_shape_dim-1):
        weight_matrix_reshape.append(1)
        weight_matrix_tile.append(int(loss_org.shape[ii+1]))

    weight_matrix = tf.tile(input=tf.reshape(tensor=weight,
                                             shape=weight_matrix_reshape),
                            multiples=weight_matrix_tile)
    loss_matrix = tf.multiply(weight_matrix,loss_org)
    loss_value = tf.reduce_mean(loss_matrix)*penalty
    return loss_value

def correct_ckpt_path(real_dir,maybe_path):
    maybe_path_dir = str(os.path.split(os.path.realpath(maybe_path))[0])
    if not maybe_path_dir == real_dir:
        return os.path.join(real_dir,str(os.path.split(os.path.realpath(maybe_path))[1]))
    else:
        return maybe_path


from typing import Dict, Type, NamedTuple, Any, Callable, TypeVar, Union

T = TypeVar("T")
NamedTuple_T = TypeVar("NamedTuple_T", bound=Type[NamedTuple])
Json_Object = Dict[str, Any]
Simple_Type = Union[int, bool, float, str, Json_Object]

def unseralize_object(cls: Type[T], value: Simple_Type) -> T:
    """Convert a type native to json to a given class"""
    if isinstance(cls, type(NamedTuple)):
        return make_typed(cls, value)
    if isinstance(value, dict):
        return cls(**value)
    return cls(value)

def make_typed(
    named_tuple_cls: Type[NamedTuple_T], simple_dict: Json_Object
) -> Callable[[Json_Object], NamedTuple_T]:
    """Make a typed named tuple from a dictionary"""

    created_object = dict()
    for key, value_cls in named_tuple_cls._field_types.items():
        created_object[key] = unseralize_object(value_cls, simple_dict[key])
    return named_tuple_cls(**created_object)

    return create_object_hook


#!/usr/bin/env python3

import plotly as plt
import plotly.graph_objs as go
from datetime import datetime

data_file = '/home/matt/pi_data/temperature.log'
dates = []
temps = []
dates_to_graph = []
temps_to_graph = []

try:
    with open( data_file, 'r' ) as f:
        for line in f:
            date =   ' '.join( line.split()[1:] )[1:-2] # second and third term, need to combine and join as a list then remove apostrophes and parenthese
            temp = line.split()[0][1:-1]              # first term, need to remove parenthese and comma
            dates.append( date )
            temps.append( temp )
except OSError:
    print( "Error occurred opening and reading ", data_file )

first_day  = datetime.strptime( dates[0], "%Y-%m-%d %H:%M:%S" )
print( first_day )
date_range = max_date_range = (datetime.now() - first_day).days

user_date_range = int( input( "How many days back do you want to see?\n" ) )
if( user_date_range > max_date_range ):
    print( "Sorry, only data from the past {} days is available.".format(date_range) )
else:
    date_range = int(user_date_range)

for n in range(len(dates)-1,-1,-1):
    current_date = datetime.strptime( dates[n], "%Y-%m-%d %H:%M:%S" )
    diff = (datetime.now()-current_date).days
    if( diff > date_range ):
        dates_to_graph = dates[n:]
        temps_to_graph = temps[n:]
        break

trace = go.Scatter(
        x = dates_to_graph,
        y = temps_to_graph,
)
plt.plotly.image.save_as( [trace], "temp_file.png" )


from .Linker import Linker
from utils.CommandUtils import CommandUtils

class GNULinker(Linker):
    # 32bit Linux dependent
    LINKER = "/usr/bin/ld"
    DYNAMIC_LINKER      = "/lib/ld-linux.so.2"
    C_RUNTIME_INIT      = "/usr/lib32/crti.o"
    C_RUNTIME_START     = "/usr/lib32/crt1.o"
    C_RUNTIME_START_PIE = "/usr/lib32/Scrt1.o"
    C_RUNTIME_FINI      = "/usr/lib32/crtn.o"

    def __init__(self,error_handler):
        self.error_handler = error_handler

    def generate_executable(self,args,destpath,opts):
        cmd = []
        cmd.append(GNULinker.LINKER)
        cmd.append("-dynamic-linker")
        cmd.append(GNULinker.DYNAMIC_LINKER)
        if opts.generating_PIE:
            cmd.append("-pie")
        if not opts.no_start_files:
            if opts.generating_PIE:
                cmd.append(GNULinker.C_RUNTIME_START_PIE)
            else:
                cmd.append(GNULinker.C_RUNTIME_START)
            cmd.append(GNULinker.C_RUNTIME_INIT)
        cmd += args
        if not opts.no_default_libs:
            cmd.append("-lc")
            cmd.append("-lcbc")
        if not opts.no_start_files:
            cmd.append(GNULinker.C_RUNTIME_FINI)
        cmd.append("-o")
        cmd.append(destpath)
        CommandUtils.invoke(cmd,self.error_handler,opts.verbose)

    def generate_shared_library(self,args,destpath,opts):
        cmd = []
        cmd.append(GNULinker.LINKER)
        cmd.append("-shared")
        if not opts.no_start_files:
            cmd.append(GNULinker.C_RUNTIME_INIT)
        cmd += args
        if not opts.no_default_libs:
            cmd.append("-lc")
            cmd.append("-lcbc")
        if not opts.no_start_files:
            cmd.append(GNULinker.C_RUNTIME_FINI)
        cmd.append("-o")
        cmd.append(destpath)
        CommandUtils.invoke(cmd,self.error_handler,opts.verbose)


while True:
    denom = [3, 4]
    print("Enter value: ")
    n = int(input())
    while len(denom) > 0 and n > 0:
        curr = denom.pop()
        if n >= curr:
            n = n % curr
    if n == 0:
        print("YES")
    else:
        print("NO")


from collections import deque

def dfs(list_v, v, visited_dfs):
    visited_dfs[v] = True
    print(v, end=' ')
    for i in list_v[v]:
        if not visited_dfs[i]:
            dfs(list_v, i, visited_dfs)

def bfs(list_v, v, visited_bfs):
    queue = deque([v])
    visited_bfs[v] = True
    while queue:
        result = queue.popleft()
        print(result, end=' ')
        for i in list_v[result]:
            if not visited_bfs[i]:
                queue.append(i)
                visited_bfs[i] = True

n, m, v = map(int, input().split())
list_v = [[] for _ in range(n+1)]
visited_dfs = [False]*(n+1)
visited_bfs = [False]*(n+1)
for _ in range(m):
    num_n, connect_n = map(int, input().split())
    list_v[num_n].append(connect_n)
    list_v[connect_n].append(num_n)
for i in range(len(list_v)):
    list_v[i].sort()
dfs(list_v, v, visited_dfs)
print(end="\n")
bfs(list_v, v, visited_bfs)
# print(end="\n")
# print(list_v)


#!/home/claytonblythe/anaconda3/bin/python
from PIL import Image
import glob
from tqdm import tqdm
import os
import argparse
from PIL import ImageFilter

def get_args():
    '''This function parses and return arguments passed in'''
    # Assign description to the help doc
    parser = argparse.ArgumentParser(description='Script to convert movie file to a wallpaper')
    # Add arguments
    parser.add_argument('-f', '--movie_file', type=str, help='movie file name')
    parser.add_argument('-w', '--width', type=int, default=1920, help='width of wallpaper in pixels')
    parser.add_argument('-v', '--height', type=int, default=1080, help='height of wallpaper in pixels (number of pixels in vertical direction)')
    # Array for all arguments passed to script
    args = parser.parse_args()
    # Assign args to variables
    movie_file = args.movie_file
    width = args.width
    height = args.height
    # Return all variable values
    return movie_file, width, height

 # Match return values from get_arguments()
 # and assign to their respective variables
movie_file, width, height  = get_args()

def make_frames(movie_file):
    os.system('ffmpeg -i {} -vf scale=8:8 im_%06d.png > /dev/null 2>&1'.format(movie_file))

print('Converting movie to frames...please be patient. This may take up to a few minutes')
make_frames(movie_file)

new_size=(1,1)
filenames = glob.glob('im*.png')
total_width = len(filenames) * new_size[0]
max_height = new_size[1]
x_offset = 0

new_im = Image.new('RGB', (total_width, max_height))
print('Converting {} frames to wallpaper'.format(movie_file))
for i in tqdm(range(1, len(filenames))):
  new_size=(1,1)
  my_file= Image.open('im_%s.png' % str('%06d' % (i+1)))
  my_val = my_file.quantize(1).convert('RGB').getpixel((0,0))
  total_new_pixels = new_size[0] * new_size[1]
  list_of_rgbs = [my_val] * total_new_pixels
  im2 = Image.new('RGB',new_size)
  im2.putdata(list_of_rgbs)
  new_im.paste(im2,(x_offset,0))
  x_offset += new_size[0]
  im2.close()
  my_file.close()

current_dir = os.path.basename(os.getcwd())
new_im.save('../wallpapers/'+ current_dir + '_base_image.png')

# Create an image based on command line width and height arguments
resize_ratio2 = (width,height)
new_im2 = new_im.resize(resize_ratio2, Image.ANTIALIAS)
new_im2.save('../wallpapers/' + current_dir + '_sized_{}x{}.png'.format(width, height))

my_dict = {'3048':'1080', '3840':'2160', '1334':'750'}
for k, v in my_dict.items():
    tmp_new_img = new_im.resize((int(k), int(v)), Image.ANTIALIAS)
    tmp_new_img.save('../wallpapers/' + current_dir + '_sized_{}x{}.png'.format(k, v))
    tmp_new_img_blurred = tmp_new_img.filter(ImageFilter.BLUR)
    tmp_new_img_blurred.save('../wallpapers/' + current_dir + '_blurred_sized_{}x{}.png'.format(k, v))


from sklearn import metrics
from Evaluation import eval_util
from EvaluateDifficulty import DifficultyEvaluator
from TrackDifficulty import TrackDifficulty
import slopeMap as sm

TEST_TILES_PATH = 'test_tiles\\'

def get_model_predictions(tracks: list, shingle_length=1, neighbors=5) -> list:
    """
    Gets the predictions of the models for the given tracks with the given number of neighbors.
    :param shingle_length: The number of elements in a shingle.
    :param tracks: a list of pandas df of the form (lat, lon, time, elev) representing an hp tracks with known
    heights.
    :param neighbors: the number of neighbors the model is using (in KNN) to evaluate the difficulty of the
    given tracks.
    :return: a list of the predicted difficulty levels of the given tracks.
    """
    predictions = []
    diff_evaluator = DifficultyEvaluator(TEST_TILES_PATH + 'N14E120' + '.hgt',
                                         [14, 120],
                                         shingle_length)
    for track in tracks:
        difficulty = diff_evaluator.pred_difficulty_known_heights(track, neighbors)
        predictions.append(difficulty.value)
    return predictions

def eval_difficulty(shingle_length=2):
    """
    Evaluates the ability of the model to classify the tracks by difficulty.
    """
    exp_data = eval_util.get_exp_dataframe('difficulty')

    tracks = []
    real = []
    for idx, row in exp_data.iterrows():
        track = eval_util.read_track_to_df(row.gpx)
        points = track[['lat', 'lon']]
        pts = points.to_numpy()
        path_length = sm.compute_track_km(pts)[-1]
        if path_length < (shingle_length + 1) * sm.TICK:
            continue
        tracks.append(track)
        real.append(row['real'])

    labels = [TrackDifficulty.EASY.value, TrackDifficulty.INTERMEDIATE.value, TrackDifficulty.DIFFICULT.value]
    results = {'accuracy': [], 'precision': [], 'recall': []}

    for k in range(1, 55):
        print('Evaluating for k = ' + str(k))
        predictions = get_model_predictions(tracks, shingle_length, k)
        results['accuracy'].append(metrics.accuracy_score(real, predictions))
        results['precision'].append(metrics.precision_score(real, predictions, labels=labels, average='weighted'))
        results['recall'].append(metrics.recall_score(real, predictions, labels=labels, average='weighted'))
    return results

if __name__ == '__main__':
    eval_util.plot_results(eval_difficulty(), "Quality of Difficulty Prediction", 'Neighbors')


# et donen un nombre n que és el nombre d'escales que has de pujar, les pots pujar d'un en un o de dos en dos,
# has de retornar totes les maneres d'arribar a n

def countWays(n):
    prev = 1
    prev2 = 1
    # Running for loop to count all possible ways
    for i in range(2, n+1):
        curr = prev + prev2
        prev2 = prev
        prev = curr
    return prev

n = 200
print("Number of Ways : ", countWays(n))


import threading, time

class SepThreadExec:
	def __init__(self, callerGUI,
				 func,
				 endFunc=None,
				 funcArgs=None,
				 endFuncArgs=None):
		self.callerGUI = callerGUI

		if endFuncArgs is None:
			endFuncArgs = ()
		if funcArgs is None:
			funcArgs = {}

		args = (func, endFunc) + endFuncArgs

		def _callback(func, endFunc, *a, **kw):
			func(**kw)

			if endFunc is not None:
				endFunc(*a)

		self.t = threading.Thread(target=_callback, args=args, kwargs=funcArgs)
		self.t.setName('Exec thread ' + self.t.getName())
		self.t.daemon = True

	def start(self):
		self.t.start()

if __name__ == "__main__":
	def myFunc(name='', age=0):
		for i in range(5):
			time.sleep(1)
			print('My name is {}. I am {} years old'.format(name, age))

	def myEndFunc(name='', age=0):
		print('MY SURNAME WAS {}. I was {} years old'.format(name.upper(), age))

	ste = SepThreadExec(callerGUI=None,
				  func=myFunc,
				  endFunc=myEndFunc,
				  funcArgs={'name': 'Jean-Pierre', 'age': 60},
				  endFuncArgs=('paulo le scientifique', 14))

	ste.start()
	time.sleep(6)


#!/usr/bin/env python

# tsv2gaussian.py - given a TSV file of a particular shape and an integer, plot Gaussian clusters after doing PCA

# configure
PCA_COMPONENTS = 3

# require
from sklearn.decomposition import PCA
from sklearn.mixture import GaussianMixture
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns; sns.set()
import sys

# sanity check
if len( sys.argv ) != 3 :
	sys.stderr.write( 'Usage: ' + sys.argv[ 0 ] + " <TSV> <integer>\n" )
	quit()

# get input
file           = sys.argv[ 1 ]
gmm_components = int( sys.argv[ 2 ] )

# create a data frame from the given file
df = pd.read_csv( file, sep='\t' )

# based on the file name, create an author column (labels)
df[ 'author' ] = df[ 'file' ].str.extract( '^.*/(.*?)-', expand=False )
df[ 'book' ]   = df[ 'file' ].str.extract('^.*/\w+-(.*?)-', expand=False)

# create a feature set; "just give me the data"
X = df.drop( [ 'file', 'author', 'book' ], axis=1 )

# instantiate PCA and identify the components
model      = PCA( n_components=PCA_COMPONENTS )
components = model.fit_transform( X )

# for future reference, insert the components back into the data frame
df['component #1'] = components[ :, 0 ]
df['component #2'] = components[ :, 1 ]

# instantiate a Gaussian model, model, and generate a set of clusters
model = GaussianMixture ( n_components=gmm_components, covariance_type='full' )
model.fit( X )
clusters = model.predict( X )

# insert the clusters into the data frame, plot, and done
df['cluster'] = clusters
sns.lmplot( "component #1", "component #2", data=df, col='cluster', hue='author', fit_reg=False )
plt.show()
exit()


# createmasks stage

import argparse
from functools import partial
from pathlib import Path
from typing import Iterable, Union

import psutil
from pygeos.set_operations import union

import geopandas as gpd
import numpy as np
import pandas as pd
import rioxarray
import xarray as xr
from shapely.geometry import Polygon
from tqdm.contrib.concurrent import process_map

def make_poly(coords: pd.Series) -> Polygon:
    """Create Shapely polygon (a tile boundary) from x1,y1 and x2,y2 coordinates"""
    xs = [coords[v] for v in "x1,x1,x2,x2,x1".split(",")]
    ys = [coords[v] for v in "y1,y2,y2,y1,y1".split(",")]
    return Polygon(zip(xs, ys))

def _identify_empty(tile: Union[Path, str]) -> bool:
    """Helper func for exclude_nodata_tiles"""

    with xr.open_rasterio(tile).sel(band=1) as t:
        # original check
        # status = True if t.max().values - t.min().values > 0 else False
        # check 2 (edge tiles with all white/ black are also detected)
        return False if np.isin(t, [0, 255]).all() else True

def exclude_nodata_tiles(
    path: Iterable[Union[Path, str]],
    tiles_df: gpd.GeoDataFrame,
    workers: int,
) -> gpd.GeoDataFrame:
    """Identify tiles that only contain NoData (in parallel)"""

    print(f"WORKERS: {workers}")

    tile_names = sorted([Path(p) if isinstance(p, str) else p for p in path])

    results = process_map(_identify_empty, tile_names, max_workers=workers, chunksize=1)

    valid_d = dict([(t.name, r) for t, r in zip(tile_names, results)])

    tiles_df["status"] = tiles_df.filename.map(valid_d)
    # limit tiles to those with actual data (and delete status column afterwards)
    return tiles_df[tiles_df.status == 1].drop("status", axis=1)

def create_tile_grid_gdf(path: Union[Path, str], crs: str) -> gpd.GeoDataFrame:
    """Convert gdal_tile split info file into geopandas dataframe"""

    tiles_df = pd.read_csv(path, sep=";", header=None)
    tiles_df.columns = ["filename", "x1", "x2", "y1", "y2"]
    tiles_df["geometry"] = tiles_df.apply(make_poly, axis=1)
    tiles_df = tiles_df.drop(["x1", "x2", "y1", "y2"], axis=1)
    tiles_gpd = gpd.GeoDataFrame(tiles_df, crs=crs, geometry=tiles_df.geometry)
    return tiles_gpd

def split_groundtruth_data_by_tiles(
    groundtruth: gpd.GeoDataFrame, tiles_df: gpd.GeoDataFrame
) -> gpd.GeoDataFrame:
    """Split the oberserved dead tree areas into tile segments for faster downstream processing"""

    union_gpd = gpd.overlay(tiles_df, groundtruth, how="intersection")

    train_files = list(sorted(union_gpd.filename.value_counts().keys()))

    tiles_with_groundtruth = tiles_df[tiles_df.filename.isin(train_files)]
    return tiles_with_groundtruth, union_gpd  # union_gpd[union_gpd.id == 2]

def _mask_tile(
    tile_filename: str,
    *,
    groundtruth_df: gpd.GeoDataFrame,
    crs: str,
    inpath: Path,
    outpath: Path,
    simple: bool = False,
) -> float:

    image_tile_path = inpath / tile_filename
    mask_tile_path = outpath / tile_filename

    with rioxarray.open_rasterio(
        image_tile_path, chunks={"band": 4, "x": 256, "y": 256}
    ) as tile:
        mask_orig = xr.ones_like(tile.load().sel(band=1, drop=True), dtype="uint8")
        mask_orig.rio.set_crs(crs)
        selection = groundtruth_df.loc[groundtruth_df.filename == tile_filename]

        if simple:
            # just use the geometry for clipping (single-class)
            mask = mask_orig.rio.clip(
                selection.geometry,
                crs,
                drop=False,
                invert=False,
                all_touched=True,
                from_disk=True,
            )

        else:
            # use type col from shapefile to create (multi-)classification masks

            classes = [0, 1, 2]  # 0: non-class, 1: coniferous, 2: broadleaf

            selection.loc[:, "type"] = pd.to_numeric(selection["type"])
            masks = [mask_orig * 0]
            for c in classes[1:]:
                gdf = selection.loc[selection["type"] == c, :]

                if len(gdf) > 0:
                    mask = mask_orig.rio.clip(
                        gdf.geometry,
                        crs,
                        drop=False,
                        invert=False,
                        all_touched=True,
                        from_disk=True,
                    )
                else:
                    mask = mask_orig * 0
                masks.append(mask)
            mask = xr.concat(masks, pd.Index(classes, name="classes")).argmax(
                dim="classes"
            )

        mask.astype("uint8").rio.to_raster(mask_tile_path, tiled=True)
        mask_sum = np.count_nonzero(mask.values)  # just for checks
    return mask_sum

def create_tile_mask_geotiffs(
    tiles_df_train: gpd.GeoDataFrame, workers: int, **kwargs
) -> None:
    """Create binary mask geotiffs"""
    process_map(
        partial(_mask_tile, **kwargs),
        tiles_df_train.filename.values,
        max_workers=workers,
        chunksize=1,
    )

def create_masks(
    indir: Path,
    outdir: Path,
    shpfile: Path,
    workers: int,
    simple: bool,
) -> None:
    """
    Stage 1: produce masks for training tiles
    """

    # load domain shape files and use its crs for the entire script
    groundtruth = gpd.read_file(shpfile).explode()
    if "Type" in list(groundtruth.columns.values):
        groundtruth = groundtruth.rename(columns={"Type": "type"})

    crs = groundtruth.crs  # reference crs

    tiles_df = create_tile_grid_gdf(indir / "locations.csv", crs)
    tiles_df = exclude_nodata_tiles(
        sorted(indir.glob("*.tif")),
        tiles_df,
        workers,
    )
    print(f"len2: {len(tiles_df)}")
    tiles_df.to_file("locations.shp")

    tiles_df_train, groundtruth_df = split_groundtruth_data_by_tiles(
        groundtruth, tiles_df
    )

    create_tile_mask_geotiffs(
        tiles_df_train,
        workers,
        groundtruth_df=groundtruth_df,
        crs=crs,
        inpath=indir,
        outpath=outdir,
        simple=simple,
    )

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("indir", type=Path)
    parser.add_argument("outdir", type=Path)
    parser.add_argument("shpfile", type=Path)

    num_cores = psutil.cpu_count(logical=False)

    parser.add_argument(
        "--workers",
        dest="workers",
        type=int,
        default=num_cores,
        help="number of workers for parallel execution [def: %(default)s]",
    )

    parser.add_argument(
        "--simple",
        dest="simple",
        default=False,
        action="store_true",
        help="use just the geometry of the shapefile (no classes)",
    )

    args = parser.parse_args()

    Path(args.outdir).mkdir(parents=True, exist_ok=True)

    create_masks(
        args.indir,
        args.outdir,
        args.shpfile,
        args.workers,
        args.simple,
    )

if __name__ == "__main__":
    main()


# both sg and sf use this
def getSumOfDigits(num):
    sumOfDigits = 0
    for i in str(num):
        sumOfDigits += int(i)
    return sumOfDigits
# f
def getSumOfFactorialDigits(num):
    total = 0
    for i in str(num):
        factorialOfDigits = 1
        for k in range(2,int(i) + 1):
            factorialOfDigits *= k
        total += factorialOfDigits
    return total

def getf(num):
    return getSumOfFactorialDigits(num)
def getsf(num):
    return getSumOfDigits(getSumOfFactorialDigits(num))
def getsg(num):
    return getSumOfDigits(getsf(num))
def getAllsg(amount):
    allsg = []
    for i in range(1,amount + 1):
        allsg.append(-1)
    count = 1
    while(True):
        currentsg = getsg(count)
        if(currentsg <= amount):
            if(allsg[currentsg-1] == -1):
                allsg[currentsg - 1] = count

        count += 1
        for i in range(0,amount):
            if(allsg[i] == -1):
                break
            elif(i == (amount - 1)):
                return allsg
def addArr(arr):
    sum = 0
    for i in range(0,len(arr)):
        sum += arr[i]
    return sum
def main():
    print(getAllsg(15))

if(__name__ == "__main__"):
    main()


import sys
sys.path.append('../../')

import numpy as np

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.solvers as S
import nnabla.monitor as M
from nnabla.experimental.trainers import Trainer
from nnabla.experimental.trainers import Updater
from nnabla.experimental.trainers import Evaluator

from nnabla.utils.data_iterator import data_iterator_simple

from common.parametric_functions import lstm
from common.functions import time_distributed
from common.functions import time_distributed_softmax_cross_entropy
from common.functions import get_mask
from common.functions import expand_dims

from common.utils import PTBDataset
from common.utils import with_padding

from utils import to_glove_dataset

import argparse
parser = argparse.ArgumentParser(description='GloVe model training.')
parser.add_argument('--context', '-c', type=str,
                    default='cpu', help='You can choose cpu or cudnn.')
parser.add_argument('--device', '-d', type=int,
                    default=0, help='You can choose the device id when you use cudnn.')
args = parser.parse_args()

if args.context == 'cudnn':
    from nnabla.ext_utils import get_extension_context
    ctx = get_extension_context('cudnn', device_id=args.device)
    nn.set_default_context(ctx)

ptb_dataset = PTBDataset()

vocab_size = len(ptb_dataset.w2i)
embedding_size = 128
batch_size = 128
max_epoch = 100
window_size = 10

central_train, context_train, target_train = to_glove_dataset(ptb_dataset.train_data, vocab_size=vocab_size, window_size=window_size)
central_valid, context_valid, target_valid = to_glove_dataset(ptb_dataset.valid_data, vocab_size=vocab_size, window_size=window_size)

num_train_batch = len(central_train)//batch_size
num_valid_batch = len(central_valid)//batch_size

def load_train_func(index):
    return central_train[index], context_train[index], target_train[index]

def load_valid_func(index):
    return central_valid[index], context_valid[index], target_valid[index]

train_data_iter = data_iterator_simple(load_train_func, len(central_train), batch_size, shuffle=True, with_file_cache=False)
valid_data_iter = data_iterator_simple(load_valid_func, len(central_valid), batch_size, shuffle=True, with_file_cache=False)

x_central = nn.Variable((batch_size, ))
x_context = nn.Variable((batch_size, ))

with nn.parameter_scope('central_embedding'):
    central_embedding = PF.embed(x_central, vocab_size, embedding_size)
with nn.parameter_scope('context_embedding'):
    context_embedding = PF.embed(x_context, vocab_size, embedding_size)

with nn.parameter_scope('central_bias'):
    central_bias = PF.embed(x_central, vocab_size, 1)
with nn.parameter_scope('context_bias'):
    context_bias = PF.embed(x_context, vocab_size, 1)

dot_product = F.reshape(
    F.batch_matmul(
        F.reshape(central_embedding, shape=(batch_size, 1, embedding_size)),
        F.reshape(context_embedding, shape=(batch_size, embedding_size, 1))
    ),
    shape=(batch_size, 1)
)

prediction = dot_product + central_bias + context_bias

t = nn.Variable((batch_size, 1))
zero = F.constant(0, shape=(batch_size, 1))
one = F.constant(1, shape=(batch_size, 1))
weight = F.clip_by_value(t / 100, zero, one) ** 0.75
loss = F.sum(weight * ((prediction - F.log(t)) ** 2))

# Create solver.
solver = S.Adam()
solver.set_parameters(nn.get_parameters())

# Create monitor
monitor = M.Monitor('./log')
monitor_loss = M.MonitorSeries("Training loss", monitor, interval=1000)
monitor_valid_loss = M.MonitorSeries("Validation loss", monitor, interval=1)
monitor_time = M.MonitorTimeElapsed("Training time", monitor, interval=1000)

# Create updater
def train_data_feeder():
    x_central.d, x_context.d, t.d = train_data_iter.next()
def update_callback_on_finish(i):
    monitor_loss.add(i, loss.d)
    monitor_time.add(i)
updater = Updater(solver=solver,
                  loss=loss,
                  data_feeder=train_data_feeder,
                  update_callback_on_finish=update_callback_on_finish)

# Evaluator
def valid_data_feeder():
    x_central.d, x_context.d, t.d = valid_data_iter.next()
def eval_callback_on_finish(i, ve):
    monitor_valid_loss.add(i, ve)
evaluator = Evaluator(loss,
                      data_feeder=valid_data_feeder,
                      val_iter=valid_data_iter.size // batch_size,
                      callback_on_finish=eval_callback_on_finish)

trainer = Trainer(updater=updater, evaluator=evaluator, model_save_path='./log',
                  max_epoch=3, iter_per_epoch=train_data_iter.size//batch_size)
trainer.train()

with open('vectors.txt', 'w') as f:
    f.write('{} {}\n'.format(vocab_size-1, embedding_size))
    with nn.parameter_scope('central_embedding'):
        x = nn.Variable((1, 1))
        y = PF.embed(x, vocab_size, embedding_size)
    for word, i in ptb_dataset.w2i.items():
        x.d = np.array([[i]])
        y.forward()
        str_vec = ' '.join(map(str, list(y.d.copy()[0][0])))
        f.write('{} {}\n'.format(word, str_vec))


# -*- coding: utf-8 -*-
import requests
import json
import random

lista_cat = ["love","science","art","biographies","fantasy","romance","religion","recipes", "mystery","music", "medicine","history", "chilcren","sci-fi"]

print('Dime la categoría')
subject= raw_input() #selecionar por menus la que sea
url = "https://openlibrary.org/subjects/"+subject+".json?limit=50"
response = requests.get(url).json()

headers = {
        'cache-control': "no-cache"
}

#response = requests.get('https://openlibrary.org/subjects/love.json?limit=100').json()

works_diccionary=response['works']

#random.shuffle(works_diccionary)

#print (response.text)
for i in range(0,10):
	x= random.randrange(50)
	if 'authors' in works_diccionary[x]:
		print ("Titulo:" + works_diccionary[x]['title'] )
		print ("Autor:" + works_diccionary[x]['authors'][0]['name']+'\n')

	else:
		print ("Titulo:" + works_diccionary[x]['title'] + "        Autor: Desconocido")
		print ("Autor: Desconocido"+'\n')


# This program calculates the Index of Coincidence in a text

from collections import Counter
import re
import unicodedata

#regex = re.compile(r"[a-zA-ZΆ-ώ]+")

# regular expression: match all latin and greek letters
regex = r"[a-zA-ZΆ-ώ]+"

# this function removes all diacritics from input_str
def remove_accents(input_str):
    """
    Remove accents and other diacritics from text input

    Parameters
    ----------
    input_str : str
        Text input to remove diacritics from

    Returns
    -------
    text : str
        Text without diacritics

    """
    nfkd_form = unicodedata.normalize('NFKD', input_str)
    return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])

def parse_text(text):
    """
    Parse given text input

    Parameters
    ----------
    input_str : str
        Text input to be parsed

    Returns
    -------
    text : str
        Parsed text

    """
    text = text.lower()
    matches = re.finditer(regex, text, re.MULTILINE)
    re_text = ''
    for matchNum, match in enumerate(matches, start=0):
        re_text += match.group()
    return remove_accents(re_text)

#text = "Good morning sweetheart".lower().replace(' ', '')

#text = input().lower().replace(' ', '').replace(',', '').replace('.', '')

# ask for keyboard input or stdin
text_input = input()

text = parse_text(text_input)

# fi is the frequency of i-th letter in the text
f = Counter(text.strip())

# n is the length of the text, without spaces and non-letters
n = len(text)

# ic is the Index of Coincidence of the text
ic = 0

for elem in f:
    ic += (f[elem] * (f[elem] - 1)) / (n * (n - 1))

print(ic)


import paho.mqtt.client as mqtt  # Import the MQTT library

import time  # The time library is useful for delays

# Our "on message" event

def messageFunction(client, userdata, message):

    topic = str(message.topic)

    message = str(message.payload.decode("utf-8"))

    print(topic + message)

ourClient = mqtt.Client("makerio_mqtt")  # Create a MQTT client object

ourClient.connect("MY_IP", 1883)  # Connect to the test MQTT broker

ourClient.subscribe("req")  # Subscribe to the topic AC_unit

# Attach the messageFunction to subscription
ourClient.on_message = messageFunction

ourClient.loop_start()  # Start the MQTT client

# Main program loop

while(1):

    # Publish message to MQTT broker
    ourClient.publish("req", "REQUEST THE TEMP")

    # Sleep for 15 min and then publishes again / asks for temp from all the devices
    time.sleep(300)
    print("10 min left")
    time.sleep(300)
    print("5 min left")
    time.sleep(300)


#!/usr/bin/python

import latticex.rosetta as cb

import tensorflow as tf
import sys, os
import numpy as np
np.set_printoptions(suppress=True)

protocol="Helix"

if "ROSETTA_TEST_PROTOCOL" in os.environ.keys():
    print("***** test_cases use ", os.environ["ROSETTA_TEST_PROTOCOL"])
    protocol = os.environ["ROSETTA_TEST_PROTOCOL"]
else:
    print("***** test_cases use default helix protocol ")
cb.activate(protocol)

sess = None

xaa = np.array([[1.92, 0.2, 3], [-0.43, .0091, 1.3]])
xbb = np.array([[.2, 0.3], [-2, .3], [-1.111, -0.3]])
xa = tf.Variable(cb.private_input(0, xaa))
xb = tf.Variable(cb.private_input(1, xbb))

z1 = cb.SecureMatMul(xa, xb)
z0 = cb.SecureReveal(z1)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(z1))
    print(sess.run(z0))

xaa = np.array([[1.0, 2.0], [3.0, 4.0]])
xbb = np.array([[1.0, 2.0], [3.0, 4.0]])
xa = tf.Variable(cb.private_input(0, xaa))
xb = tf.Variable(cb.private_input(1, xbb))

z1 = cb.SecureMatMul(xa, xb)
z0 = cb.SecureReveal(z1)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(z1))
    print(sess.run(z0))

cb.deactivate()
exit(0)

def test_matmul(xa, xb):
    global sess
    if sess is not None:
        sess.close()

    print("xa:\n", xa)
    print("xb:\n", xb)

    #
    init = tf.compat.v1.global_variables_initializer()
    sess = tf.compat.v1.Session()
    sess.run(init)

    print("=========================== tf op matmul 1")
    xc = tf.matmul(xa, xb)
    xcc = sess.run(xc)
    print("=========================== tf op matmul 2")
    print(xcc)

    ###########

    print("=========================== mpc op matmul 1")
    xc = cb.SecureMatMul(xa, xb)
    xcc = sess.run(xc)
    print("=========================== mpc op matmul 2")
    print(xcc)

# 2-d, (2,2) x (2,2)
xa = tf.Variable([[0, 0], [0, 0]])
xb = tf.Variable([[0, 0], [0, 0]])
test_matmul(xa, xb)

# 2-d, (2,2) x (2,2)
xa = tf.Variable([[1.0, 2.0], [3.0, 4.0]])
xb = tf.Variable([[5.0, 6.0], [7.0, 8.0]])
test_matmul(xa, xb)

# 2-d, (2,3) x (3,2)
xa = tf.Variable([[1.92, 0.2, 3], [-0.43, .0091, 1.3]])
xb = tf.Variable([[.2, 0.3], [-2, .3], [-1.111, -0.3]])
test_matmul(xa, xb)


import math
import sympy as sy

def sy_func_to_lambda(f):
    x = sy.Symbol('x')

    print(f)
    f = lambda y: f.subs(x, y)
    return f

def fitFunc(val, a, b, func_array):
    """

    :param val: значение функции или х_0
    :param a: левый конец отрезка
    :param b: правый конец отрезка
    :param func_array: функции (библиотеки sympy)
    :return: функцию библиотеки (sympy)
    """

    x = sy.Symbol('x')
    if val < a:
        return func_array[0]
    elif a <= val <= b:
        return func_array[1]
    else:
        return func_array[2]

def count_included_points(interval, points):
    """
    Count number of points that are in interval.
    :param interval: interval where we check points.
    :param points: array of points.
    :return: number of points that are in interval.
    """
    count = 0
    for i in points:
       if interval[0] <= i and i < interval[1]:
           # print(f"{interval[0]} <= {i} < {interval[1]}; \n{interval[0]} >= {i} and {i} < {interval[1]} = {interval[0] >= i and i < interval[1]}")
           count += 1
    return count

def dot_plus(l1, l2):
    s = ""
    for i in range(len(l1)):
        s += str(l1[i]) + "*" + str(l2[i])
        s += " + "

    s = s[:-1-1]

    return s

def s_mas(l):
    s = ""
    for i in range(len(l)):
        s += str(l[i])
        s += " + "

    s = s[:-1 - 1]

    return s


import numpy as np
from enum import IntEnum
import matplotlib.pyplot as plt

global_variable_counter = 0

class Operation(IntEnum):
    S_ADD = 0
    S_SUB = 1
    S_MUL = 2
    S_DIV = 3
    M_ADD = 4
    M_SUB = 5
    M_MUL = 6
    M_ELM = 7
    M_ELD = 8
    S_SQR = 9
    M_ESQ = 10
    M_RDS = 11
    M_TNP = 12

S_OPS = {Operation.S_ADD, Operation.S_SUB, Operation.S_MUL, Operation.S_DIV}
M_ELE = {Operation.M_ADD, Operation.M_SUB, Operation.M_ELM, Operation.M_ELD}
names = ['add', 'sub', 'mul', 'div', 'matadd', 'matsub', 'matmul', 'matelemul', 'matelediv', 'sqr', 'matlelesqr', 'reduce', 'transpose']
specific_names = ['Scalar Addition', 'Scalar Subtraction', 'Scalar Multiplication', 'Scalar Division', 'Matrix Addition', 'Matrix Subtraction', 'Matrix Multiplication', 'Matrix Element-wise Multiplication', 'Matrix Division', 'Scalar Square', 'Matrix Element-wise Square', 'Matrix Reduce Sum']

counts = {name: 0 for name in names}

names_to_ops = {'add': [Operation.S_ADD, Operation.M_ADD],
                'subtract': [Operation.S_SUB, Operation.M_SUB],
                'multiply': [Operation.S_MUL, Operation.M_ELM],
                'divide': [Operation.S_DIV, Operation.M_ELD],
                'square': [Operation.S_SQR, Operation.M_ESQ]
}

used_names = set()

class Variable:
    def __init__(self, operation: Operation = None, value=None, a=None, b=None, trainable=True):
        self.trainable = trainable

        if value is not None:
            if type(value) == np.ndarray:
                self.value = value
                self.shape = value.shape
            elif type(value) == float:
                self.value = value
                self.shape = ()
            elif type(value) == list:
                self.value = np.array(value)
                self.shape = self.value.shape
            else:
                raise TypeError("Supplied value is not of type np.ndarray, list, or float")

            if len(self.shape) > 2:
                raise ValueError("Cannot create tensors of greater than 2 dimensions")

            self.op = None
            self.a = None
            self.b = None
            global global_variable_counter
            self.name = f"Variable {global_variable_counter}"
            global_variable_counter += 1
            return
        else:
            self.value = value

        self.op = operation
        self.name = f"{names[int(self.op)]} {counts[names[int(self.op)]]}"
        counts[names[int(self.op)]] += 1

        if self.op in S_OPS:
            if not (a.is_scalar() and b.is_scalar()):
                raise ValueError("One or both operands is not a scalar")
            self.a = a
            self.b = b
            self.shape = ()
        elif self.op in M_ELE:
            if not a.is_matrix() or not b.is_matrix():
                raise ValueError("One or both operands is not a matrix")
            if not a.shape == b.shape:
                raise ValueError("Matrices are not of same shape")
            self.a = a
            self.b = b
            self.shape = a.shape
        elif self.op == Operation.M_MUL:
            if not len(a.shape) > 0 or not len(b.shape) > 0:
                raise ValueError("One or both operands is not a matrix")
            if not b.shape[1] == 1:
                raise ValueError("Only matrix * column vector is supported for differentiation")
            if not a.shape[1] == b.shape[0]:
                raise ValueError("Incompatible shapes for matrix multiplication")
            self.a = a
            self.b = b
            self.shape = (a.shape[0], b.shape[1])
        elif self.op == Operation.S_SQR:
            if not a.is_scalar():
                raise ValueError("Operand is not a scalar")
            self.a = a
            self.b = None
            self.shape = ()
        elif self.op == Operation.M_ESQ:
            if not a.is_matrix():
                raise ValueError("Operand is not a matrix")
            self.a = a
            self.b = None
            self.shape = self.a.shape
        elif self.op == Operation.M_RDS:
            if not a.is_matrix():
                raise ValueError("Operand is not a matrix")
            self.a = a
            self.b = None
            self.shape = ()
        elif self.op == Operation.M_TNP:
            if not a.is_matrix():
                raise ValueError("Operand is not a matrix")
            self.a = a
            self.b = None
            self.shape = (self.a.shape[1], self.a.shape[0])
        else:
            raise ValueError("Something has gone horribly wrong!")

    def __str__(self):
        if self.a is not None:
            return f"Placeholder(\"{specific_names[int(self.op)]}\" shape={self.shape})"
        else:
            return f"Variable(\"{self.value}\")"

    def is_scalar(self):
        return self.shape == ()

    def is_matrix(self):
        return not self.is_scalar()

    def eval(self):
        if self.op is None:
            return self.value
        elif self.op == Operation.S_ADD:
            self.value = self.a.eval() + self.b.eval()
        elif self.op == Operation.S_SUB:
            self.value = self.a.eval() - self.b.eval()
        elif self.op == Operation.S_MUL:
            self.value = self.a.eval() * self.b.eval()
        elif self.op == Operation.S_DIV:
            self.value = self.a.eval() / self.b.eval()
        elif self.op == Operation.S_SQR:
            self.value = self.a.eval() * self.a.eval()
        elif self.op == Operation.M_ADD:
            self.value = self.a.eval() * self.b.eval()
        elif self.op == Operation.M_SUB:
            self.value = self.a.eval() - self.b.eval()
        elif self.op == Operation.M_ELM:
            self.value = self.a.eval() * self.b.eval()
        elif self.op == Operation.M_ELD:
            self.value = self.a.eval() / self.b.eval()
        elif self.op == Operation.M_ESQ:
            self.value = np.square(self.a.eval())
        elif self.op == Operation.M_MUL:
            self.value = np.matmul(self.a.eval(), self.b.eval())
        elif self.op == Operation.M_RDS:
            self.value = np.sum(self.a.eval())
        elif self.op == Operation.M_TNP:
            self.value = self.a.eval().T
        else:
            print("something has gone horribly wrong")
        return self.value

    def differentiate(self):
        if self.op is None:
            return None
        elif self.op == Operation.S_ADD:
            self.a.grad = self.grad * np.float32(1.)
            self.b.grad = self.grad * np.float32(1.)
        elif self.op == Operation.S_SUB:
            self.a.grad = self.grad * np.float32(1.)
            self.b.grad = self.grad * np.float32(-1.)
        elif self.op == Operation.S_MUL:
            self.a.grad = self.grad * self.b.value
            self.b.grad = self.grad * self.a.value
        elif self.op == Operation.S_DIV:
            self.a.grad = self.grad / self.b.value
            self.b.grad = -self.grad * self.a.value / (self.b.value * self.b.value)
        elif self.op == Operation.S_SQR:
            self.a.grad = 2 * self.grad * self.a.value
        elif self.op == Operation.M_ADD:
            self.a.grad = self.grad * np.ones_like(self.a.value)
            self.b.grad = self.grad * np.ones_like(self.a.value)
        elif self.op == Operation.M_SUB:
            self.a.grad = self.grad * np.ones_like(self.a.value)
            self.b.grad = - self.grad * np.ones_like(self.a.value)
        elif self.op == Operation.M_ELM:
            self.a.grad = self.grad * self.b.value
            self.b.grad = self.grad * self.a.value
        elif self.op == Operation.M_ELD:
            self.a.grad = self.grad / self.b.value
            self.b.grad = -self.grad * self.a.value / (self.b.value * self.b.value)
        elif self.op == Operation.M_ESQ:
            self.a.grad = 2 * self.grad * self.a.value
        elif self.op == Operation.M_MUL:
            diag_d_du = np.diag(self.grad)
            # print(self.grad)
            # print(diag_d_du, np.tile(self.b.value, (self.a.value.shape[0], 1)))
            # self.a.grad = np.matmul(diag_d_du, np.tile(self.b.value, (self.a.value.shape[0], 1)))
            self.a.grad = np.matmul(np.tile(self.b.value, (self.a.value.shape[0], 1)), diag_d_du)
            self.b.grad = np.matmul(self.a.value.T, self.grad)
        elif self.op == Operation.M_RDS:
            # print(self.a)
            self.a.grad = self.grad * np.ones_like(self.a.value)
        elif self.op == Operation.M_TNP:
            self.a.grad = self.grad.T
        else:
            print("something has gone horribly wrong")

    def s_or_ele_ops(self, other, op):
        if not type(other) == Variable:
            raise TypeError(f"Cannot {names[int(op)]} Variable to something else")
        if self.is_scalar():
            if not other.is_scalar():
                raise ValueError(f"Cannot {names[int(op)]} matrix to scalar")
            return Variable(names_to_ops[op][0], a=self, b=other, trainable=False)
        else:
            if other.is_scalar():
                raise ValueError(f"Cannot {names[int(op)]} scalar to matrix")
            if not self.shape == other.shape:
                raise ValueError(f"Cannot {names[int(op)]} matrices of different shapes")
            return Variable(names_to_ops[op][1], a=self, b=other, trainable=False)

    def __add__(self, other):
        return self.s_or_ele_ops(other, 'add')

    def __sub__(self, other):
        return self.s_or_ele_ops(other, 'subtract')

    def __mul__(self, other):
        return self.s_or_ele_ops(other, 'multiply')

    def __truediv__(self, other):
        return self.s_or_ele_ops(other, 'divide')

    def __matmul__(self, other):
        return Variable(Operation.M_MUL, a=self, b=other, trainable=False)

def square(x: Variable):
    if x.is_scalar():
        return Variable(Operation.S_SQR, a=x, trainable=False)
    else:
        return Variable(Operation.M_ESQ, a=x, trainable=False)

def reduce_sum(x: Variable):
    if x.is_scalar():
        return x
    else:
        return Variable(Operation.M_RDS, a=x, trainable=False)

def matmul(x1: Variable, x2: Variable):
    return x1 @ x2

def transpose(x: Variable):
    return Variable(Operation.M_TNP, a=x, trainable=False)

def MSE(y: Variable, y_: Variable):
    if not (y.shape == y_.shape):
        raise ValueError("Arguments must have same shape")

    return reduce_sum(square(y - y_))

def backprop(loss, learning_rate):
    queue = [loss]
    loss.grad = 1.
    while queue:
        cur = queue.pop()
        if cur.trainable:
            cur.value -= learning_rate * cur.grad
        cur.differentiate()
        if cur.a is not None:
            queue.append(cur.a)
        if cur.b is not None:
            queue.append(cur.b)

def training_loop():
    X = np.ones((100, 5), dtype=np.float32)
    Y = np.zeros((100, 1), dtype=np.float32)

    W = Variable(value=np.random.rand(Y.shape[1], X.shape[1]))
    b = Variable(value=np.random.rand(1, 1))

    epochs = 10

    loss_history = np.empty(epochs * 100)
    pred_history = np.empty(epochs * 100)
    c = 0

    for epoch in range(epochs):
        for example, output in zip(X, Y):
            out = matmul(W, transpose(Variable(value=example[np.newaxis], trainable=False))) + b
            loss = MSE(out, Variable(value=output[np.newaxis], trainable=False))
            loss_history[c] = loss.eval()
            pred_history[c] = out.value[0][0]
            c += 1
            backprop(loss, 0.01)

    plt.plot(np.arange(loss_history.shape[0]), loss_history)#title='loss history')
    plt.figure()
    plt.plot(np.arange(loss_history.shape[0]), pred_history)# title='prediction history (ground truth=0')
    plt.show()

def main():
    training_loop()

if __name__ == "__main__":
    main()


import socketserver as SocketServer, threading, time

#####
ZERO = 0
ONE = 1
ACK = "ACK"
TIME_OUT = 0.2
####

class ThreadedUDPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        socket = self.request[1]
        current_thread = threading.current_thread()
        if self.server.mechanism=="STREAM":
               while True:
                    # Receive response
                #print('\nWaiting to receive..')
                try:
                    data, _ = socket.recvfrom(self.server.prefix_size)
                except Exception as err:
                    print(err)
                    continue
                if not data:
                    break
                else:
                    self.server.total_messages += 1
                    self.server.total_bytes += len(data)

        elif self.server.mechanism=="STOP":
            while True:
                # Receive response
                #print('\nWaiting to receive..')
                try:
                    data, _ = socket.recvfrom(self.server.prefix_size)
                except Exception as err:
                    print(err)
                    continue
                if not data:
                    break
                else:
                    self.server.total_messages += 1
                    self.server.total_bytes += len(data)
                    socket.sendto(bytes("ACK","utf-8"), self.client_address)

class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
      pass

def start(host,port,mechanism, prefix_size):

            server = ThreadedUDPServer((host, port), ThreadedUDPRequestHandler)
            server.mechanism = mechanism
            server.total_bytes = ZERO
            server.total_messages = ZERO
            server.prefix_size = prefix_size
            server_thread = threading.Thread(target=server.serve_forever)
            server_thread.daemon = True
            try:
                server_thread.start()
                print("Server started at {} port {}".format(host, port))
                while True: time.sleep(100)
            except (KeyboardInterrupt, SystemExit):
                print("Protocol used: UDP, total messages received : %d, total bytes received: %d"%(server.total_messages, server.total_bytes))
                server.shutdown()
                server.server_close()
            exit()


# pip install --upgrade python-gitlab

import gitlab
import os

gl = gitlab.Gitlab(private_token="<token-gitlab-com>")
glnew = gitlab.Gitlab('<URL-selfhosted-gitlab>', private_token="<token-selfhosted-gitlab>")

gl.auth()
glnew.auth()
groups = gl.groups.list()

for x in groups:
    print(x.id)
    newgrp = x.name.replace('m_','').replace('m-','').replace('mmaks_','')
    glnew.groups.create({'name': newgrp, 'path': f"{newgrp}"})
    group = glnew.namespaces.get(newgrp)

    for project in x.projects.list(iterator=True):
        try:
            print(project.name)
            newproj = glnew.projects.create({'name': f"{project.name}", 'path': f"{project.name}", 'namespace_id':f"{group.id}"})
            os.system(f"git clone {project.ssh_url_to_repo}")
            os.system(f" cd {project.name}  && git remote  set-url origin  {newproj.ssh_url_to_repo} && git push -u origin --all && cd ../")
        finally:
            print(f"что то пошло не так с {project.name}")