import os
import sys
os.environ["PYTHONDONTWRITEBYTECODE"] = 'stobbit'

import time
import logging
import datetime
import argparse
import threading

from array import array, typecodes

try:
    import pygame
except ImportError as e:
    print("Can't import `pygame`. Did you remember to activate the virtual environment?")
    sys.exit(5)

def get_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('--solo', action='store_true', help='Launch level with no network capabilities. Overrides server and client.')
    parser.add_argument('--server', action='store_true', help='Launch level with server capabilities. Overrides client.')
    parser.add_argument('--useserver', help='Launch level as client connecting to specified server IP address.')
    parser.add_argument('--debug', action='store_true',help='Display variables from the player')
    parser.add_argument('-u', '--username', required=True, help='Username')
    parser.add_argument('-c', '--color', required=True, help='Username')
    parser.add_argument('-r', '--resolution', help='resolution to run game at')

    return parser.parse_args()

def test(args):
    # Testing basic movement, weapons, environment here.
    os.system("cls")
    logging.error("Beginning the pygame test\n\n")
    logging.info(f"pygame version: {pygame.__version__}")
    global USERNAME

    USERNAME = args.username

    color = args.color.upper()
    if color not in CN.COLOR_DICT:
        raise ValueError("Must be one of BLACK, WHITE, RED, GREEN, BLUE, YELLOW, CYAN, MAGENTA")

    start_game(args)

def make_text(text, color, bgcolor, top, left):
    '''
    Create rough text box to blit onto screen
    '''
    textSurf = CN.BASICFONT.render(text, True, color, bgcolor)
    textRect = textSurf.get_rect()
    textRect.topleft = (top, left)
    return (textSurf, textRect)

def get_screen_size(res):
    '''
    Get screen area from args, and return default value if not parseable
    '''
    try:
        w, h = res.split('x')
        return (int(w), int(h))
    except:
        return CN.SCREEN_REZ

def get_proper_screen_size(w,h):
    '''
    Force screen size to be 16x9
    '''
    # TODO: Python float storage imperfect, rejigger this plz
    while float(w)/float(h) != CN.SCREEN_ASPECTRATIO:
        if float(w)/float(h) > CN.SCREEN_ASPECTRATIO:
            # too wide, base off of height
            w = int(16*(float(h)/9))
        else:
            # too narrow, base off of width
            h = int(9*(float(w)/16))
    return w,h

def start_server():
    '''
    Run the server for the game. Eventually build the game loop here.
    '''
    from MMX_Combat.network.server import MMXServer
    from time import sleep
    server = MMXServer(localaddr=('', 12000))
    logging.debug(server)
    pygame.init()
    server_clock = pygame.time.Clock()
    while True:
        server.CalcAndPump()
        server_clock.tick(CN.FPS)

def start_game(args):
    '''
    The actual game function. Imports necessary modules, builds level (should
    move this to server), makes player, and houses main game loop.
    '''

    # Import game-specific modules
    from MMX_Combat.player import BasePlayerObj, LocalPlayerObj, DummyJoystick
    from MMX_Combat.environment import BaseEnvironmentObj, TestLevel, ServerTestLevel
    from MMX_Combat.camera import Camera, complex_camera
    from MMX_Combat.network.server import MMXServer

    DEBUG = args.debug

    # Initialize key program elements
    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    SCREEN = pygame.display.set_mode(get_screen_size(args.resolution), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE)
    CAMERA_SCREEN = pygame.Surface(CN.SCREEN_REZ)

    pygame.display.set_caption(f'MMX Combat: {args.username}')

    BASICFONT = pygame.font.Font(None, CN.BASICFONTSIZE)

    if not pygame.joystick.get_init():
        pygame.joystick.init()

    attached_joysticks = pygame.joystick.get_count()
    if attached_joysticks:
        # logging.debug(f"Attached joysticks: {attached_joysticks}")
        # logging.debug("Getting first joystick")
        jstick = pygame.joystick.Joystick(0)
        jstick.init()
    else:
        jstick = DummyJoystick()

    if args.solo:
        level = TestLevel(CN.DEFAULT_SERVER_IP, CN.DEFAULT_SERVER_PORT, args.username, network=False)
    elif args.server:
        threading.Thread(target=start_server, daemon=True, name='server_thread').start()
        # time.sleep(3)
        level = ServerTestLevel(CN.DEFAULT_SERVER_IP, CN.DEFAULT_SERVER_PORT, args.username)
    elif args.useserver:
        level = ServerTestLevel(args.useserver, CN.DEFAULT_SERVER_PORT, args.username)

    # logging.debug(f'Level block size: ({level.block_width}x{level.block_height})')
    MINIMAP_SCREEN = pygame.Surface((level.width, level.height))
    show_minimap = False

    all_players = []

    local_player = LocalPlayerObj(USERNAME, level, jstick, args.color)
    # local_player = LocalPlayerObj(USERNAME, level, jstick, player_color, {"MAX_SHOTS":2})
    all_players.append(local_player)

    level.player_names.add(USERNAME)

    # for remote_player in get_all_remote_players(level):
    #     all_players.append(remote_player)

    for player in all_players:
        player.walls = level.wall_list
        level.all_sprite_list.add(player)
        level.players.add(player)

    longest_proc_frame = 0

    frame_history = array('f')

    player_camera = Camera(complex_camera, level.width, level.height)

    in_focus = True

    # main game loop
    while True:
        # os.system("cls")
        pressed_keys = []
        pressed_keys_str = ''
        cur_keys = pygame.key.get_pressed()
        cur_hat = jstick.get_hat(0)
        if cur_keys[pygame.K_LEFT] or cur_keys[pygame.K_RIGHT] or cur_hat[0] != 0:
            if cur_keys[pygame.K_LEFT] or cur_hat[0] == -1:
                local_player.go_left()
            if cur_keys[pygame.K_RIGHT] or cur_hat[0] == 1:
                local_player.go_right()
        else:
            local_player.stop()

        if local_player._check_control_down():
            local_player.duck()
        if local_player._check_control_jump():
            local_player.jump()
        if local_player._check_control_fire():
            local_player.charge()
        if local_player._check_control_dash():
            local_player.dash()
        if (cur_keys[pygame.K_KP_MINUS] or cur_keys[pygame.K_MINUS]) and CN.FPS > 1:
            CN.FPS -= 1
        if (cur_keys[pygame.K_KP_PLUS] or cur_keys[pygame.K_PLUS])and CN.FPS < 30:
            CN.FPS += 1

        show_minimap = True if cur_keys[pygame.K_TAB] else False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                logging.info(f"  Longest frame process: {longest_proc_frame} seconds")
                frame_update = 1.0/CN.FPS
                logging.info(f"  Average frame process: {sum(frame_history)/len(frame_history)} seconds")
                logging.info(f"Single frame update max: {frame_update} seconds")
                print("")
                logging.info("            Code status: {}".format("All good\n" if frame_update > longest_proc_frame else "Too heavy\n"))
                sys.exit()

            # elif event.type == pygame.ACTIVEEVENT:
            #     # logging.debug(event)
            #     # logging.debug(event.state)
            #     logging.debug('state:', event.state, '| gain:', event.gain,)
            #     if event.state == 1:
            #         if event.gain == 0:
            #             logging.debug("| mouse out",)
            #         elif event.gain == 1:
            #             logging.debug("| mouse in",)
            #     elif event.state == 2:
            #         if event.gain == 0:
            #             logging.debug("| titlebar pressed",)
            #         elif event.gain == 1:
            #             logging.debug("| titlebar unpressed",)
            #     elif event.state == 6:
            #         if event.gain == 0:
            #             logging.debug("| window minimized",)
            #     elif event.state == 4:
            #         if event.gain == 1:
            #             logging.debug("| window normal",)

            elif event.type == pygame.VIDEORESIZE:
                # logging.debug(f"Resizing to {event.dict['size']}!")
                SCREEN = pygame.display.set_mode(get_proper_screen_size(*event.dict['size']), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE)

            # Check for keys being released.
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT and local_player.x_velocity < 0 and local_player.dashing < 0:
                    if not pygame.key.get_pressed()[pygame.K_RIGHT]:
                        local_player.stop()
                    else:
                        local_player.go_right()
                if event.key == pygame.K_RIGHT and local_player.x_velocity > 0 and local_player.dashing < 0:
                    if not pygame.key.get_pressed()[pygame.K_LEFT]:
                        local_player.stop()
                    else:
                        local_player.go_left()
                if event.key == pygame.K_DOWN:
                    local_player.standup()
                if event.key == pygame.K_SPACE:
                    local_player.allow_jump()
                if (event.key == pygame.K_LSHIFT and not cur_keys[pygame.K_RSHIFT]) or (event.key == pygame.K_RSHIFT and not cur_keys[pygame.K_LSHIFT]):
                    local_player.allow_dash()
                if event.key == pygame.K_LCTRL and not cur_keys[pygame.K_RCTRL]:
                    if local_player.charge_level > 2:
                        local_player.fire()

            # Check for keys being pressed this frame.
            elif event.type == pygame.KEYDOWN:
                if event.key in (pygame.K_LCTRL, pygame.K_RCTRL):
                    local_player.fire()
                elif event.key == pygame.K_z:
                    local_player.alt_fire()
                elif event.key == pygame.K_i:
                    level.print_data_cache()

            elif event.type == pygame.JOYBUTTONDOWN:
                # logging.debug(f"Joystick button {event.button} pressed.")
                if event.button == 2:
                    local_player.fire()
            elif event.type == pygame.JOYBUTTONUP:
                # logging.debug(f"Joystick button {event.button} released.")
                if event.button == 0:
                    local_player.allow_jump()
                if event.button == 1:
                    local_player.allow_dash()
                if event.button == 2:
                    if local_player.charge_level > 5:
                        local_player.fire()
                    local_player.discharge()

            # Now we check for whether the hat is being pressed/released
            elif event.type == pygame.JOYHATMOTION:
                if event.value[0] == 0:
                    local_player.stop()
                if event.value[1] == 0:
                    local_player.standup()

        CAMERA_SCREEN.fill(CN.BLACK)
        MINIMAP_SCREEN.fill(CN.BLACK)

        # Update info on all players
        proc_start_time = datetime.datetime.now()

        if local_player not in level.all_sprite_list:
            local_player.update()

        level.chat_client.Loop()

        level.update_data()
        # TODO: check for conflicts between local_player local data and server data

        level.all_sprite_list.update()

        player_camera.update(local_player)
        proc_end_time = (datetime.datetime.now() - proc_start_time).total_seconds()
        frame_history.append(proc_end_time)
        if proc_end_time > longest_proc_frame:
            longest_proc_frame = proc_end_time

        # Apply camera
        for s in level.all_sprite_list:
            CAMERA_SCREEN.blit(s.image, player_camera.apply(s))
            MINIMAP_SCREEN.blit(s.image, s.rect)

        SCREEN.blit(pygame.transform.scale(CAMERA_SCREEN, [*SCREEN.get_size()], SCREEN), [0,0])
        if show_minimap:
            MINIMAP_SCREEN.set_alpha(128)
            SCREEN.blit(pygame.transform.scale(MINIMAP_SCREEN, [level.block_width*4, level.block_height*4]),
                        [SCREEN.get_size()[0]-(level.block_width*4), SCREEN.get_size()[1]-(level.block_height*4)])

        # Display debug and/or controls
        if DEBUG:
            text_surf, text_rect = make_text("{}: {}".format('id',str(local_player.__dict__['id'])), CN.WHITE, CN.BLACK, 50, 10)
            SCREEN.blit(text_surf, text_rect)
            i = 1
            text_surf, text_rect = make_text("{}: {}".format('FPS',str(CN.FPS)), CN.WHITE, CN.BLACK, 50, 10+(i*1.1*CN.BASICFONTSIZE))
            SCREEN.blit(text_surf, text_rect)
            i+=1
            for k,v in sorted(local_player.__dict__.items()):
                # logging.debug(k)
                # logging.debug("\t" + str(type(v)))
                if k != 'id' and not callable(v) and not k.startswith("_") and k[0] != k[0].upper() and isinstance(v, (int, bool, list)):
                    text_surf, text_rect = make_text("{}: {} ({})".format(k,str(v), type(v)), CN.WHITE, CN.BLACK, 50, 10+(i*1.1*CN.BASICFONTSIZE))
                    SCREEN.blit(text_surf, text_rect)
                    i += 1
        else:
            text = """Controls:
                    Movement: Arrow Keys or Controller D-Pad
                    Jump: Spacebar or bottom Controller button (X)
                    Dash: Shift or right Controller button (O)
                    Fire: Control or left Controller button ([])"""
            for i, line in enumerate(text.split("\n")):
                text_surf, text_rect = make_text(line.strip(), CN.WHITE, CN.BLACK, 50, 10+(i*1.1*CN.BASICFONTSIZE))
                SCREEN.blit(text_surf, text_rect)

        pygame.display.flip()
        # logging.debug(f'{threading.activeCount()} active threads!')
        FPSCLOCK.tick(CN.FPS)

if __name__ == "__main__":

    mmx_main_path = os.path.normpath(os.path.join(os.path.realpath(__file__), "..", ".."))
    if mmx_main_path not in sys.path:
        sys.path.append(mmx_main_path)
    import MMX_Combat.constants as CN
    logging.basicConfig(level=logging.DEBUG, format=CN.LOG_FMT)
    args = get_args()
    # logging.debug(args)
    test(args)


import math as math
import numpy as np
import utm
import json

from .optimalControl import OptimalControl

class Navigation:

    # Object for vehicle controller
    controller = OptimalControl()

    path = None # Trajectory goals
    endReached = True
    pathCount = 1  # Counter to select which goal to go to

    maxAimLen = 4.0  # Length from the point orthogonal to the route for which to aim
    minAimLen = 2.0  # Minimum length as to not slow down entirely
    deadzone = 4 # Deadzone, when the vehicle is within the radius of the target - change target.

    # Simpel P-controller gains (unitconversion)
    velGain = 0.4   # velGain * maxAimLen = maxSpeed
    rotGain = 1.0

    def __init__(self):
        self.reset()

    def reset(self):
        self.path = None
        self.pathCount = 1
        self.endReached = True

    def retry(self):
        self.endReached = False

    def setPath(self, path):
        self.path = path

        # Show the path on Google Map
        self.logToMap()

    def run(self, actualPos, actualHeading, actualVel, actualRot):

        # Use the pathfollower algorithm to calculate desired speeds for navigating
        velRef, rotRef = self.pathFollow(actualPos, actualHeading)

        # Map distance to linear speed, and map error in radians to rad/s
        velRef = self.velGain * velRef
        rotRef = self.rotGain * rotRef

        # Input to the controller
        return self.controller.run( velRef, rotRef, actualVel, actualRot)

    def pathFollow(self, actualPos, heading):

        # Convert lists to numpy arrays for easy vector calculations
        actualPos = np.array( actualPos )

        targetPos = np.array( self.path[self.pathCount] )
        startPos = np.array( self.path[self.pathCount-1] )

        # Calculate vector between target and actual postion to calculate the length
        target = targetPos - actualPos
        distance = math.sqrt( pow(target[0],2) + pow(target[1], 2))

        # If vehicle is close to targetPos, update the goal counter
        if(  abs(distance) <= self.deadzone ):

            # Check if there still are a new target
            if self.pathCount < (len(self.path) - 1):

                self.pathCount = self.pathCount + 1

            else:
                # Final goal reached, stop moving
                return 0, 0

        ###### Use Helmans method to calculate movement ######
        # Calculate vector between start and the target position (the wanted route)
        route = targetPos - startPos

        # Calculate the point which is orthorgonal to the route from the actualPos
        orthPoint = startPos + ( ((actualPos - startPos) @ route)/(route @ route)) * route

        ###  Calculate the aiming point on the route ###

        # First calculate distance from orthPoint to targetPos
        orthRoute = targetPos - orthPoint
        distance = math.sqrt( pow(orthRoute[0],2) + pow(orthRoute[1], 2))

        # Depending on the distance, calculate the distance to next aim point
        if distance < self.maxAimLen:
            aimDistance = self.minAimLen if (distance < self.minAimLen) else distance
        else:
            aimDistance = self.maxAimLen

        ### Calculate the target heading for the vehicle ###

        # Calculate the lenght of the route
        routeLength = math.sqrt( pow(route[0],2) + pow(route[1], 2))

        # Calculate the aiming point by adding the route vector scaled by the aimDistance
        aimPoint = orthPoint + (aimDistance * route)/routeLength

        # Find the vector between actualPos and aimPoint
        aimRoute = aimPoint - actualPos

        # Calculate the angle of the aimRoute vector
        angle = math.atan2(aimRoute[1], aimRoute[0])

        # Map atan2 angle to two pi
        thetaRef = (angle) % (2 * math.pi)

        # Find shortest route in degress  and map to radians
        thetaError = (thetaRef*180/math.pi - heading*180/math.pi + 540) % 360 - 180
        thetaError = thetaError*(math.pi/180)

        # Log the path-algorithm to Google Map
        # self.logToMap( actualPos, heading, orthPoint, aimPoint )

        return aimDistance, thetaError

    def logToMap(self, actualPos = None, heading = None, orthPoint = None, aimPoint = None):

        route = list()
        actual, orth, aim = None, None, None

        if self.path:
            for i in range(len(self.path)):
                route.append( utm.to_latlon(self.path[i][0], self.path[i][1], 32, 'V') )

        # Only log actual position if it is different than zero
        if actualPos and all(i != 0 for i in actualPos):
            actual = utm.to_latlon(actualPos[0], actualPos[1], 32, 'V')

        # Only add algorithm data if it is available
        if orthPoint and aimPoint:
            orth = utm.to_latlon(orthPoint[0], orthPoint[1], 32, 'V')
            aim = utm.to_latlon(aimPoint[0], aimPoint[1], 32, 'V')

        with open("map/pathlog.json", "w") as file:

            data = json.dumps({'route': route, 'actual':actual, 'orth':orth, 'aim': aim, 'heading': heading})
            file.write(data)


import curses
import sys
import time

if False:

    def pbar(window):
        for i in range(10):
            j = str(i * 10)
            window.addstr(
                0,
                0,
                "Time to download "
                + "["
                + ("#" * i)
                + ("-" * (9 - i))
                + "]"
                + " " * len(j)
                + j
                + "%",
            )
            window.addstr(10, 10, "[" + ("#" * i) + ("-" * (9 - i)) + "]")
            window.refresh()
            time.sleep(0.5)

    curses.wrapper(pbar)

else:
    for i in range(11):
        sys.stdout.write("\r[{0}{1}] {2}%".format("#" * i, "-" * (10 - i), i * 10))
        sys.stdout.flush()
        time.sleep(0.5)
    print


# encoding: utf-8
"""Test keras.layers.core.Layer.__call__"""

from __future__ import print_function

import unittest
import numpy as np

from numpy.testing import assert_allclose

from keras import backend as K
from keras.layers.core import Dense
from keras.models import Sequential

class TestCall(unittest.TestCase):
    """Test __call__ methods"""

    def test_layer_call(self):
        """Test keras.layers.core.Layer.__call__"""
        nb_samples, input_dim, output_dim = 3, 10, 5
        layer = Dense(output_dim, input_dim=input_dim)
        W = np.asarray(K.eval(layer.W)).astype(K.floatx())
        X = K.placeholder(ndim=2)
        Y = layer(X)
        F = K.function([X], [Y])

        x = np.ones((nb_samples, input_dim)).astype(K.floatx())
        y = F([x])[0].astype(K.floatx())
        t = np.dot(x, W).astype(K.floatx())
        assert_allclose(t, y, rtol=.2)

    def test_sequential_call(self):
        """Test keras.models.Sequential.__call__"""
        nb_samples, input_dim, output_dim = 3, 10, 5
        model = Sequential()
        model.add(Dense(output_dim=output_dim, input_dim=input_dim))
        model.compile('sgd', 'mse')

        X = K.placeholder(ndim=2)
        Y = model(X)
        F = K.function([X], [Y])

        x = np.ones((nb_samples, input_dim)).astype(K.floatx())
        y1 = F([x])[0].astype(K.floatx())
        y2 = model.predict(x)
        # results of __call__ should match model.predict
        assert_allclose(y1, y2)

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


#!/usr/bin/python3

# This software is distributed under the GNU Lesser General Public License (https://www.gnu.org/licenses/lgpl-3.0.en.html)
# WARNING: This is not a software to be used in production. I write this software for teaching purposes.
# TO DO: There lots of things to be done. This is experimental software and will never finish. But I will do the followings first:
# 1) Save SQL Query as view - done 2017/04/11
# 2) Modify Table is not implemented. Will implement whenever I find time
# 3) Editing SQLite parameters
# 4) Creating Index
# 5) SQL syntax highlight
# 6) Currently all changes done on database. Write Changes, Revert Changes
# 7) ….
# 8) Those features queried by users

import sys
import os

from PyQt5 import QtWidgets, QtCore, QtGui, Qt, QtSql, uic

from apps.pyqt_sqlite.ui import ModifyTableDialog,TYPE_DICT,addUi

from functools import partial
ui_path = os.path.dirname(os.path.abspath(__file__))
mainwindowUi = uic.loadUiType(os.path.join(ui_path, "mainwindow.ui"))[0]

#mainwindowUi = uic.loadUiType("main_window.ui")[0]

app = QtWidgets.QApplication(sys.argv)

__appname__='PyQt SqLite Database Browser'
class SqliteWindow(QtWidgets.QMainWindow, mainwindowUi):
    selectedTable=None
    work_directory=os.path.dirname(os.path.realpath(__file__))
    current_database_file=''
    current_database=None

    def __init__(self, *args):
        super(SqliteWindow, self).__init__(*args)

        QtCore.QCoreApplication.setOrganizationName("mbaser")
        QtCore.QCoreApplication.setOrganizationDomain("foo.org")
        QtCore.QCoreApplication.setApplicationVersion("0.0.1")
        self.current_database = QtSql.QSqlDatabase.addDatabase('QSQLITE')
        self.setupUi(self)
        self.tree_model=QtGui.QStandardItemModel()

        self.treeView.setModel(self.tree_model)
        self.settings=QtCore.QSettings()

        self.recent_files=self.settings.value('recent_files',[])
        self.update_recent_files()

    def setTitle(self, title=None):
        t_str="PyQt SqLite"
        if title:
            t_str += ' [%s]' % title
        self.setWindowTitle(t_str)

    @QtCore.pyqtSlot()
    def on_actionAbout_triggered(self):
        QtWidgets.QMessageBox.about(self, "About this software","This software is written for teaching purposes. Don't use in production!!! My purpose is to demonstrate how PyQt widgets can be used to develop software.\n\n Main developer: Mustafa Baser <mbaser@mail.com>")

    @QtCore.pyqtSlot()
    def on_commandLinkButton_clicked(self):
        dialog=ModifyTableDialog(self)
        dialog.exec_()

    @QtCore.pyqtSlot()
    def on_commandLinkButton_3_clicked(self):
        if self.selectedTable:
            result=QtWidgets.QMessageBox.question(self, "Warning",
                                                     "You are just deleting %s %s. You will lost all the data in %s. Dou you want to delete?" % (
                                                     self.selectedTable[1],
                                                     self.selectedTable[0],
                                                     self.selectedTable[0]
                                                   ))
        if result==QtWidgets.QMessageBox.Yes:
            self.current_database.exec("DROP %s `%s`" % (self.selectedTable[0], self.selectedTable[1]))
            if not self.error_check(self.current_database):
                self.update_tables_table()

    @QtCore.pyqtSlot('QModelIndex', int)
    def on_treeView_expanded(self, ind):
        pass

    @QtCore.pyqtSlot('QModelIndex')
    def on_treeView_clicked(self, ind):

        item=self.tree_model.itemFromIndex(ind.sibling(0,0))

        if hasattr(item,"tableType"):
            self.selectedTable=(item.tableType,ind.sibling(ind.row(),0).data())
            self.commandLinkButton_2.setEnabled(True)
            self.commandLinkButton_3.setEnabled(True)
        else:
            self.commandLinkButton_2.setEnabled(False)
            self.commandLinkButton_3.setEnabled(False)

    def update_tables_table(self):
        self.tree_model.clear()
        self.tree_model.setHorizontalHeaderLabels(['Name', 'Type','Schema'])
        for typ in ('table','view'):
            q=self.current_database.exec("SELECT name FROM sqlite_master WHERE type = '%s'" % typ)
            self.error_check(self.current_database)
            tables=[]
            while q.next():
                tables.append(q.value(0))

            tab_par = QtGui.QStandardItem('%ss (%d)' % (typ.title(),len(tables)))

            for tb in tables:
                if typ=='table': c_icon="sc_inserttable.png"
                else: c_icon="sc_dbviewtablenames.png"
                self.comboBox.addItem(QtGui.QIcon("icons/"+c_icon), tb)
                tb_name=QtGui.QStandardItem(tb)
                tb_name.tableType=typ
                tb_type=QtGui.QStandardItem(typ.title())
                q=self.current_database.exec("SELECT sql FROM sqlite_master WHERE tbl_name = '%s' AND type = '%s'" % (tb,typ))
                tb_schema_str=''
                if q.next():
                    tb_schema_str=q.value(0)
                    tb_schema_str=tb_schema_str.replace("\n", " ")
                    tb_schema_str=tb_schema_str.replace("\t", " ")

                tb_schema=QtGui.QStandardItem(tb_schema_str)

                driver=self.current_database.driver()
                rec=driver.record(tb)
                for i in range(rec.count()):
                    col_name=QtGui.QStandardItem(rec.field(i).name())
                    type_id=rec.field(i).type()
                    if type_id in TYPE_DICT: type_str=TYPE_DICT[type_id]
                    else: type_str=str(type_id)
                    col_type=QtGui.QStandardItem(type_str)

                    tb_name.appendRow([col_name, col_type])

                tab_par.appendRow([tb_name, tb_type, tb_schema])

            self.tree_model.appendRow(tab_par)

    def error_check(self, model):

        error = model.lastError()
        if error.isValid():
            self.show_warning(error.text())
            return True

    @QtCore.pyqtSlot()
    def on_queryExecButton_pressed(self):
        self.queryTableView.setModel(QtSql.QSqlQueryModel())
        query = self.queryTextEdit.toPlainText()
        model = self.queryTableView.model()
        model.setQuery(query)
        self.error_check(model)

    @QtCore.pyqtSlot(str)
    def on_comboBox_currentIndexChanged(self,tbl_name):
        if tbl_name:
            model = QtSql.QSqlTableModel()
            model.setTable('"'+tbl_name+'"')
            model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)
            model.select()

            self.error_check(model)
            self.tableView.setModel(model)

    def show_warning(self, text):
        QtWidgets.QMessageBox.warning(self, "Info", "Could not execute query. Error message from database engine is:\n"+ text)

    @QtCore.pyqtSlot()
    def on_newRecordButton_pressed(self):
        model = self.tableView.model()
        model.submitAll()
        result=model.insertRows(model.rowCount(), 1)
        if not result:
            self.error_check(model)

    @QtCore.pyqtSlot()
    def on_reloadTableButton_pressed(self):
        self.tableView.model().select()

    @QtCore.pyqtSlot()
    def on_deleteRecordButton_pressed(self):
        model = self.tableView.model()
        model.removeRow(self.tableView.currentIndex().row())
        model.select()

    @QtCore.pyqtSlot()
    def on_actionClose_triggered(self):
        self.closeDatabase()

    @QtCore.pyqtSlot()
    def on_actionExit_triggered(self):
        self.close()

    @QtCore.pyqtSlot()
    def on_actionNew_triggered(self):
        save_file_dialog=QtWidgets.QFileDialog.getSaveFileName(self, "Name of new database", self.work_directory)
        if save_file_dialog[0]:
            self.loadDatabase(save_file_dialog[0])

    @QtCore.pyqtSlot()
    def on_actionOpen_triggered(self):
        self.fileDialog = QtWidgets.QFileDialog(self)
        self.fileDialog.setDirectory(self.work_directory)

        result=self.fileDialog.getOpenFileName()

        if result[0]:
            self.loadDatabase(result[0])

    @QtCore.pyqtSlot()
    def on_saveQueryAsView_pressed(self):

        model = self.queryTableView.model()

        if model:
            if model.rowCount():
                view_name, result = QtWidgets.QInputDialog.getText(self, __appname__, 'Enter vieww name:')
                if result:
                    query = self.queryTextEdit.toPlainText()
                    query = 'CREATE VIEW {0} AS\n{1}'.format(view_name, query)
                    if not self.execute_query(query):
                        self.update_tables_table()

    def closeDatabase(self):
        if self.current_database:
            if self.current_database.isOpen():
                self.tree_model.clear()
                self.comboBox.clear()
                tbm=self.tableView.model()
                tbm.clear()

                self.current_database.close()
                self.setTitle()
                self.commandLinkButton.setEnabled(False)
                self.actionClose.setEnabled(False)
            print('Clearing "Execute SQL Widgets"')
            #clear "Execute SQL Widgets"
            self.queryTextEdit.clear()
            tableModel=self.queryTableView.model()
            if tableModel:
                tableModel.clear()

            self.queryTableView.setModel(None)
            self.queryResultText.clear()

    def loadDatabase(self, db_file, *args):
        self.closeDatabase()
        self.tree_model.removeRows(0, self.tree_model.rowCount())
        self.work_directory=os.path.dirname(db_file)
        self.current_database_file=os.path.basename(db_file)
        self.current_database.setDatabaseName(db_file)
        if self.current_database.open():
            self.commandLinkButton.setEnabled(True)
            self.actionClose.setEnabled(True)
            self.setTitle(db_file)
            self.update_tables_table()

            if db_file in self.recent_files:
                self.recent_files.remove(db_file)

            self.recent_files.insert(0,db_file)
            self.update_recent_files()

    def update_recent_files(self):
        self.menuOpen_Recent.clear()
        for i, rc in enumerate(self.recent_files):
            recent_file_action=QtWidgets.QAction('&%d %s' % (i+1, rc), self, triggered=partial(self.loadDatabase, rc))
            self.menuOpen_Recent.addAction(recent_file_action)

    def execute_query(self, query):
        self.current_database.exec(query)

        return self.error_check(self.current_database)

    def closeEvent(self, event):

        self.settings.setValue('recent_files', self.recent_files)
        self.closeDatabase()

main = SqliteWindow()
main.show()
sys.exit(app.exec_())


#-*- coding:utf-8 -*-
import os, csv
from shutil import copyfile

from variables import APPS
from variables import CORPUS_PATH, RAW_IMG_PATH, DUPLICATES_REPORT_PATH, DUPLICATES_CLUSTER_PATH, DUPLICATES_CLUSTER_IMG_PATH

# ---------------------------------------------------------------------------------------
# Description   : Function to prepare the duplicate report data
# ---------------------------------------------------------------------------------------

def prepare_txt(app):
	with open('/'.join([DUPLICATES_REPORT_PATH, app, 'duplicate_set.csv'])) as csv_file:
		reader = csv.reader(csv_file)
		for row in reader:
			if len(row) == 1: # 只包含一个review的cluster
				continue

			tag = row[0] # tag 是review的id
			#print("row[0] {}".format(row[0])) #135552
			if not os.path.exists('/'.join([DUPLICATES_CLUSTER_PATH, app, str(tag)])):
				os.makedirs('/'.join([DUPLICATES_CLUSTER_PATH, app, str(tag)]))

			for i in range(len(row)):
				report_id = row[i]

				from_name = '/'.join([CORPUS_PATH, app, str(report_id) + '.txt'])
				to_name = '/'.join([DUPLICATES_CLUSTER_PATH, app, str(tag), str(report_id) + '.txt'])
				copyfile(from_name, to_name) # 就是把同一个cluster的review的txt文件都拷贝到了同一个文件夹下

for app in APPS:
	prepare_txt(app)


# -*- coding: utf-8 -*-
"""Config for the Trunk.
"""

__authors__ = "emenager, tnavez"
__contact__ = "etienne.menager@inria.fr, tanguy.navez@inria.fr"
__version__ = "1.0.0"
__copyright__ = "(c) 2020, Inria"
__date__ = "Jun 29 2022"

import sys
import pathlib
sys.path.insert(0, str(pathlib.Path(__file__).parent.absolute())+"/../")
sys.path.insert(0, str(pathlib.Path(__file__).parent.absolute()))

from Libraries.BaseConfig import BaseConfig

import Mesh.Constants as Const

class Config(BaseConfig):
    def __init__(self):
        super(Config,self).__init__("Finger")
        self.scene_name = "2Finger"
        self.n_robot = 2
        self.set_scene_config({"source": [-400.0, -50, 100],
                               "target": [30, -25, 100],
                               "goalPos": [0, Const.Height/2, -3.0*Const.Length]})

    def get_actuators_variables(self):
        return {"cable1": [20, 0, 20],
                "cable2": [10, 0, 20]}

    def get_n_dt(self):
        return 30

    def get_n_eq_dt(self):
        return 2

    def get_trajectory(self):
        import numpy as np
        goals = []
        n_samples, max_x_pos = 5, 30

        init_point = np.array([- max_x_pos, Const.Height/2, -3.0*Const.Length])
        for i in range(2*n_samples):
            goals.append(init_point+ i*np.array([max_x_pos/n_samples, 0, 0]))

        return goals


# SWEA 1983
# 학생의 성적을 구분하고 특정 학생의 성적 출력

T = int(input())
# 여러개의 테스트 케이스가 주어지므로, 각각을 처리합니다.
for test_case in range(1, T + 1):
    # 첫번째로 학생 수와 성적을 알고 싶어하는 학생의 Index
    N, K = map(int, input().split())

    letter_grade = ['A+', 'A0', 'A-', 'B+', 'B0', 'B-', 'C+', 'C0', 'C-', 'D']
    new_letter_grade = []
    for i in range(0, len(letter_grade)):
        for j in range(0, N//10):
            new_letter_grade.append(letter_grade[i])

    grade_list = []

    # 점수 받아서 계산 후 리스트에 넣기
    for i in range(0, N):
        one_student = list(map(int, input().split()))
        student_grade = one_student[0]*0.35 + one_student[1]*0.45 + one_student[2]*0.2
        grade_list.append(student_grade)

    this_student = grade_list[K-1]

    find_student = grade_list.copy()
    find_student.sort(reverse=True)

    for index, value in enumerate(find_student):
        if this_student == value:
            print('#{} {}'.format(test_case, new_letter_grade[index]))


import time

import pytest

from gitlabform.gitlabform import GitLabForm
from gitlabform.gitlabform.test import (
    create_group,
    create_project_in_group,
    create_readme_in_project,
    get_gitlab,
    GROUP_NAME,
)

PROJECT_NAME = "archive_project"
GROUP_AND_PROJECT_NAME = GROUP_NAME + "/" + PROJECT_NAME

@pytest.fixture(scope="function")
def gitlab(request):
    gl = get_gitlab()

    create_group(GROUP_NAME)
    create_project_in_group(GROUP_NAME, PROJECT_NAME)
    create_readme_in_project(GROUP_AND_PROJECT_NAME)  # in main branch

    def fin():
        gl.delete_project(GROUP_AND_PROJECT_NAME)
        # TODO: find some smarter way to avoid 400 when trying to create project while it is still being deleted
        time.sleep(15)

    request.addfinalizer(fin)
    return gl  # provide fixture value

archive_project = """
gitlab:
  api_version: 4

project_settings:
  gitlabform_tests_group/archive_project:
    project:
      archive: true
"""

unarchive_project = """
gitlab:
  api_version: 4

project_settings:
  gitlabform_tests_group/archive_project:
    project:
      archive: false
"""

edit_archived_project = """
gitlab:
  api_version: 4

# the project has to be configured as archived
# for other configs for it to be ignored
project_settings:
  gitlabform_tests_group/archive_project:
    project:
      archive: true

group_settings:
  gitlabform_tests_group:
    files:
      README.md:
        overwrite: true
        branches:
          - main
        content: |
          Some other content that the default one
"""

class TestArchiveProject:
    def test__archive_project(self, gitlab):
        gf = GitLabForm(
            config_string=archive_project,
            project_or_group=GROUP_AND_PROJECT_NAME,
        )
        gf.main()

        project = gitlab.get_project(GROUP_AND_PROJECT_NAME)

        assert project["archived"] is True

    def test__unarchive_project(self, gitlab):
        gf = GitLabForm(
            config_string=archive_project,
            project_or_group=GROUP_AND_PROJECT_NAME,
        )
        gf.main()

        project = gitlab.get_project(GROUP_AND_PROJECT_NAME)

        assert project["archived"] is True

        gf = GitLabForm(
            config_string=unarchive_project,
            project_or_group=GROUP_AND_PROJECT_NAME,
        )
        gf.main()

        project = gitlab.get_project(GROUP_AND_PROJECT_NAME)

        assert project["archived"] is False

    def test__dont_edit_archived_project(self, gitlab):
        gf = GitLabForm(
            config_string=archive_project,
            project_or_group=GROUP_AND_PROJECT_NAME,
        )
        gf.main()

        project = gitlab.get_project(GROUP_AND_PROJECT_NAME)

        assert project["archived"] is True

        gf = GitLabForm(
            config_string=edit_archived_project,
            project_or_group=GROUP_NAME,
        )
        gf.main()

        # if we tried to edit an archived project, then we will get an exception here


from time import sleep
from typing import List

from utils.PageObject import PageObject

PRODUCTS_LINK_SELECTOR = ".product .title > h2 > a"

class WallpapersPage(PageObject):
    page_url = "https://avi-home.co.il/product-category/wallpapers/"

    def scroll_down(self):
        self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")

    def load_all_products(self, time_out=15, max_products=None):
        sleeping_time = 0
        products_len = 0
        while True:
            new_products_len = len(self.getElements(PRODUCTS_LINK_SELECTOR))
            if new_products_len > products_len:
                self.scroll_down()
                products_len = new_products_len
                sleeping_time = 0

            else:
                sleep(0.1)
                sleeping_time += 0.1

            if sleeping_time >= time_out:
                return self.products_list

            if max_products and new_products_len > max_products:
                return self.products_list

    @property
    def products_list(self) -> List[str]:
        links = []
        for product in self.getElements(PRODUCTS_LINK_SELECTOR):
            links.append(product.get_attribute("href"))

        return links


import tkinter as Tkinter
import tkinter.messagebox as tkMessageBox

import picamera
import time
import Adafruit_DHT
import RPi.GPIO as GPIO
from RPLCD.i2c import CharLCD
GPIO.setmode(GPIO.BCM)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(20,GPIO.OUT)
GPIO.setup(21,GPIO.OUT)

lcd=CharLCD("PCF8574",0x27)
camera=picamera.PiCamera()
camera.resolution=(2592,1944)
intrusion_control=0
timer=0
dht_type=11
bcm_pin=23

def bellRing(on):
    if on:
        while True:
            pitch=1000
            duration=0.1
            period=1.0/pitch
            delay=period/2
            cycles=int(duration*pitch)

            for i in range(cycles):
                GPIO.output(25,True)
                time.sleep(delay)
                GPIO.output(25,False)
                time.sleep(delay)

        time.sleep(0.5)
    else:
        GPIO.cleanup()

def showTempAndHum():
    lcd.clear()
    humidity,temperature=Adafruit_DHT.read_retry(dht_type,bcm_pin)
    humid=round(humidity,1)
    temp=round(temperature,1)
    print(humid,temp)
    lcd.write_string('TEMP')
    lcd.write_string(str(temp))
    lcd.write_string('C')
    lcd.crlf()
    lcd.write_string('HUMID')
    lcd.write_string(str(humid))
    lcd.write_string('%')

def emergencyLight(on):
    if on:
        while True:
            GPIO.output(16,True)
            time.sleep(0.1)
            GPIO.output(16,False)
            time.sleep(0.1)
            GPIO.output(20,True)
            time.sleep(0.1)
            GPIO.output(20,False)
            time.sleep(0.1)
            GPIO.output(21,True)
            time.sleep(0.1)
            GPIO.output(21,False)
            time.sleep(0.1)
    else:
        GPIO.cleanup()

def camera():
    camera.capture("photo.jpg")
    tkMessageBox.showinfo( "Camera", "Phote is saved!")

top = Tkinter.Tk()
top.title("Smart Home")

Bell = Tkinter.Button(top, text ="Bell ring", command = bellRing(True))
BellOff = Tkinter.Button(top, text ="Bell off", command = bellRing(False))
Temperature = Tkinter.Button(top, text ="Show Temp", command = showTempAndHum())
LightOn = Tkinter.Button(top, text ="Light Blink", command = emergencyLight(True))
LightOff = Tkinter.Button(top, text ="Light Off", command = emergencyLight(False))
Camera  = Tkinter.Button(top, text ="Take Picture", command = camera())

Bell.pack()
BellOff.pack()
Temperature.pack()
LightOn.pack()
LightOff.pack()
Camera.pack()
top.mainloop()


# needed imports
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import scipy.cluster.hierarchy as sch
import numpy as np

# This determines the clustering method. Check https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html#scipy.cluster.hierarchy.linkage for details
method = 'ward'  # average, ward, single...

class cluster():
    def __init__(self, cluster, projections):
        self.cluster = cluster
        self.bundles = []
        self.n = 0

        self.summation = []
        for factor in range(len(projections)):
            self.summation.append([])
            for projection in range(len(projections[factor])):
                self.summation[factor].append(0)

    def add_bundle(self, bundle):
        self.bundles.append(bundle)
        self.n += 1

        # adds 1 to one projection - specified in bundle - for each factor
        for i in range(len(self.summation)):
            self.summation[i][bundle[i]-1] += 1

    def get_mixture(self):
        mixture = []
        for factor in range(len(self.summation)):
            mixture.append([])
            for projection in range(len(self.summation[factor])):
                mixture[factor].append(
                    self.summation[factor][projection]/self.n)
        return mixture

def create_distance_matrix(bundles):
    # Need to convert the class projection bundle in a list of bundles
    bundles_list = []
    for object in bundles:
        bundles_list.append(object.bundle)

    bundles = np.array(bundles_list)
    # Hamming metric: 0 if same, 1 if different
    d = sch.distance.pdist(bundles, 'hamming')
    # generate the linkage matrix
    return d

def create_linkage_matrix(distances):
    Z = linkage(distances, method)
    return Z

def fancy_dendrogram(*args, **kwargs):
    max_d = kwargs.pop('max_d', None)
    if max_d and 'color_threshold' not in kwargs:
        kwargs['color_threshold'] = max_d
    annotate_above = kwargs.pop('annotate_above', 0)

    ddata = dendrogram(*args, **kwargs)

    if not kwargs.get('no_plot', False):
        plt.title('Hierarchical Clustering Dendrogram (truncated)')
        plt.xlabel('sample index or (cluster size)')
        plt.ylabel('distance')
        for i, d, c in zip(ddata['icoord'], ddata['dcoord'], ddata['color_list']):
            x = 0.5 * sum(i[1:3])
            y = d[1]
            if y > annotate_above:
                plt.plot(x, y, 'o', c=c)
                plt.annotate("%.3g" % y, (x, y), xytext=(0, -5),
                             textcoords='offset points',
                             va='top', ha='center')
        if max_d:
            plt.axhline(y=max_d, c='k')
    return ddata

def show_dendrogram(Z):
    fancy_dendrogram(Z, truncate_mode='lastp',
                     p=12,
                     leaf_rotation=90.,
                     leaf_font_size=12.,
                     show_contracted=True,
                     annotate_above=10,  # useful in small plots so annotations don't overlap
                     )
    plt.show()

def show_elbow(Z):
    # showing the elobow diagram
    last = Z[-10:, 2]
    last_rev = last[::-1]
    idxs = np.arange(1, len(last) + 1)
    plt.plot(idxs, last_rev)

    acceleration = np.diff(last, 2)  # 2nd derivative of the distances
    acceleration_rev = acceleration[::-1]
    plt.plot(idxs[:-2] + 1, acceleration_rev)
    plt.show()
    # if idx 0 is the max of this we want 2 clusters
    k = acceleration_rev.argmax() + 2
    print("Recommend clusters from elbow diagram:", k)
    return k

def get_clusters(Z, k):
    return sch.fcluster(Z, k, criterion='maxclust')


import numpy as np
import cv2

'''include if you want some more information about the needed memory'''
#from memory_profiler import profile

#@profile
def NC():
    '''Put file name here'''
    input_name = "demo.png"

    pic = cv2.imread(input_name,1)
    gray = cv2.imread(input_name,0)
    height, width, _ = pic.shape

    '''for less extreme values set it lower
    value should be between 0 and 1'''
    bmp_percent = 0.5
    nrm_percent = 0.7

    '''blur on or off?'''
    blur_switch = 1

    '''Fast and rough Ambient Occlusion?'''
    thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,31,21)
    cv2.imwrite(input_name[:len(input_name)-4]+"_notfinished_AO.png",thresh)

    '''the next part is for blurring image a bit,
    but leaving the edged sharp. '''
    if blur_switch == 1:
        not_thresh = cv2.bitwise_not(thresh)
        th1 = cv2.GaussianBlur(gray, (11,11), 0)
        th1 = cv2.bitwise_and(th1, th1, mask = thresh)
        th2 = cv2.bitwise_and(gray, gray, mask = not_thresh)
        bump = cv2.add(th1, th2)

    else:
        bump = gray

    '''reduces contrast'''
    bump = (np.ones((height,width),dtype = np.uint16)*200*(1-bmp_percent) + bump*bmp_percent)

    '''bmp pic can be modified for bump or roughness'''
    cv2.imwrite(input_name[:len(input_name)-4]+"_notfinished_bmp.png",bump)

    '''starting edge detection with sobel horizontal and vertical'''
    sobel_x = cv2.Sobel(bump, cv2.CV_16S,1,0, ksize =-1)
    sobel_y = cv2.Sobel(bump, cv2.CV_16S,0,1, ksize =-1)

    '''Using absolute units if there is an (horizental or vertical) edge, and 0 if there is not'''
    abs_x = cv2.convertScaleAbs(sobel_x) - np.ones((height,width),dtype = np.uint8)*255
    abs_y = cv2.convertScaleAbs(sobel_y) - np.ones((height,width),dtype = np.uint8)*255

    '''Converting into a value between -1 and 1 to be ready to convert into normalmap values'''
    pixel_x = (abs_x*(2/255)-1)
    pixel_y = (abs_y*(2/255)-1)

    '''Array of ones (fastens the calculation)'''
    ones = np.ones((height,width),dtype = np.uint8)

    '''1 color for each pixel (3 dimensional array per pixel)
    x/y value is 1 z value is pixel_x/pixel_y
    this leads to a color change only if the is an horizontal/vertical edge'''
    dx = np.zeros((height,width,3),dtype = np.float64)
    dx[:,:,0] = ones
    dx[:,:,2] = pixel_x
    dy = np.zeros((height,width,3),dtype = np.float64)
    dy[:,:,1] = ones
    dy[:,:,2] = pixel_y

    '''norm values are the lenght of each array(treated like vector's)'''
    dx_norm = np.sqrt(dx[:,:,0]**2+dx[:,:,1]**2+dx[:,:,2]**2)**-1
    dy_norm = np.sqrt(dy[:,:,0]**2+dy[:,:,1]**2+dy[:,:,2]**2)**-1

    '''normalizing the arrays (treated like vector's)'''
    dx[:,:,0] = np.multiply(dx[:,:,0],dx_norm)
    dx[:,:,1] = np.multiply(dx[:,:,1],dx_norm)
    dx[:,:,2] = np.multiply(dx[:,:,2],dx_norm)

    dy[:,:,0] = np.multiply(dy[:,:,0],dy_norm)
    dy[:,:,1] = np.multiply(dy[:,:,1],dy_norm)
    dy[:,:,2] = np.multiply(dy[:,:,2],dy_norm)

    '''cross product of x and y is the final normalmap(with extreme values)'''
    dcross = np.zeros((height,width,3),dtype = np.float)

    dcross[:,:,2] = (np.multiply(dx[:,:,1],dy[:,:,2]) - np.multiply(dx[:,:,2],dy[:,:,1]) + ones)*(256/2)
    dcross[:,:,1] = (np.multiply(dx[:,:,2],dy[:,:,0]) - np.multiply(dx[:,:,0],dy[:,:,2]) + ones)*(256/2)
    dcross[:,:,0] = (np.multiply(dx[:,:,0],dy[:,:,1]) - np.multiply(dx[:,:,1],dy[:,:,0]) + ones)*(128/2) + ones * 128

    '''calc normals to Normalmap
     z is blue between 128 and 256
     x is red between 0 and 256
     y is green between 0 and 256'''

    blue = np.array([255,127,127])

    '''flatens normal'''
    dcross = (dcross*nrm_percent + blue*(1-nrm_percent))
    color_matrix = dcross.astype(np.uint8)

    cv2.imwrite(input_name[:len(input_name)-4]+"_nrm.png",color_matrix)
    print ("ready")
    return ("ready")

if __name__ == '__main__':
    NC()
    end = input("end")


# read the dataset
# divide it train test splet  60 to 40
# classfication using svm
# kernel linear and kerneal rbf
# acuuracy and presetion and f1 measure

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

df = pd.read_csv('./classficationData/classifier.csv')  # dataframe
X = df.drop('outcome', 1)
y = df['outcome']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=10)
svc_model = SVC(C=.1, kernel='linear', gamma=1)
svc_model.fit(X_train, y_train)

prediction = svc_model.predict(X_test)

from sklearn.metrics import accuracy_score
acc = accuracy_score(y_test, prediction)
print("accuracy ", acc)

# precision
from sklearn.metrics import precision_score

pre = precision_score(y_test, prediction)
print("precision ", pre)

from sklearn.metrics import f1_score
f1 = f1_score(y_test, prediction)
print("f1-measure  ", f1)

print("--------------------kernel rbf-------------------------------")

svc_model = SVC(kernel='rbf')
svc_model.fit(X_train, y_train)

from sklearn.metrics import accuracy_score
acc = accuracy_score(y_test, prediction)
print("accuracy ", acc)

# precision
from sklearn.metrics import precision_score

pre = precision_score(y_test, prediction)
print("precision ", pre)

from sklearn.metrics import f1_score
f1 = f1_score(y_test, prediction)
print("f1-measure  ", f1)


# -*- coding: utf-8 -*-
import time

from fastapi import FastAPI,Request

from .routers import setu
from .db import on_shutdown, on_start

app = FastAPI()

app.include_router(setu.router)

app.on_event("startup")(on_start)
app.on_event("shutdown")(on_shutdown)

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


from iota.crypto.types import Seed
from iota.crypto.addresses import AddressGenerator
from iota import Iota
from datetime import datetime
import requests, json, zmq

class Node:

    def __init__(self, seed=None):
        if seed != None:
            self.seed = seed
        else:
            self.seed = str(Seed.random())

    def __repr__(self):
        return self.seed

    # Connects to IRI
    def api(self):
        api = Iota(url(), self.seed)
        return api

    @staticmethod
    def url():
        # Grabs available IOTA nodes urls
        r = requests.get('https://api.iota-nodes.net/').json()

        # Filters nodes that are at 100% health and are on the latest version of IRI
        nodes = [r[node]['hostname'] for node in range(len(r))\
            if (r[node]['health'] == 5)\
                and (r[node]['version'] == '1.8.5-RELEASE')\
                    and (r[node]['hasZMQ'] == 1)]

        # Returns first node url in list
        return nodes[0]

    # Gets 1st index address from designated seed
    def address(self):
        addresses = AddressGenerator(seed=self.seed, checksum=False, security_level=3)
        main_address = addresses.get_addresses(0,1)
        main = str(main_address[0])
        return main

    @staticmethod
    def gen_seed():
        return Seed.random()

# Create a RTC to the Tangle and listen for the ricipient address
class Tangle:

    def __init__(self, connect, address=None):
        config = Node()
        self.node = config.url()
        self.connect_status = connect
        self.rec_address = config.address()

    def connect(self):
        if self.connect_status == False:
            pass
        else:
            recipient = bytes(self.rec_address, 'utf-8')
            context = zmq.Context()
            socket = context.socket(zmq.SUB)
            # Prepares socket to istens to 1st indexed address
            # of seed for tx information
            zmq_node = f'tcp://zmq.{self.node}'
            socket.setsockopt(zmq.SUBSCRIBE, recipient)
            # Initates connections
            socket.connect(zmq_node)
            print(socket)
            connected = True
            while connected:
                address, data = socket.recv().decode().split(' ', 1)

                if address:

                    hash_data = dict.fromkeys([
                        tx_hash,
                        address,
                        value,
                        obs_tag,
                        ts,
                        index,
                        last_index,
                        bundle_hash,
                        trunk_hash,
                        branch_hash,
                        received_ts,
                        tag,
                    ])

                    for i, j in data.items():
                        hash_data[i] = j

                    if hash_data:
                        print(hash_data)
                        connected = False
                        return connected

test = Tangle(True, None)
test.connect()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
Music Widget that play music online.
'''

import widget

class Widget(widget.WidgetModel):
    '''
    Play music
    '''

    __title__ = 'Music Player'
    __author__ = 'Michael Liao'
    __description__ = 'Play a music online'
    __url__ = 'http://www.expressme.org/'

    @staticmethod
    def get_settings():
        return [
                widget.WidgetSetting(key='music_title', description='Music Title', required=False, default=''),
                widget.WidgetSetting(key='music_url', description='Music URL', required=True, default='http://'),
                widget.WidgetCheckedSetting(key='auto_play', label='Auto play when load', description='Auto play', default='True'),
                widget.WidgetCheckedSetting(key='repeat', label='Play repeatly', description='Play repeatly', default='False'),
        ]

    def get_content__raw__(self):
        # http://shop.zzaza.com/content/mp3/burning.mp3
        # http://listen.idj.126.net/uf/130/40ef517cda864fc98886a26f7c01caa2.mp3
        auto_start = self.auto_play=='True'
        return r'''

%s

<embed src="/widget/installed/music_player/static/player.swf?soundFile=%s&playerID=%s&bg=0xf8f8f8&leftbg=0xeeeeee&lefticon=0x666666&rightbg=0xcccccc&rightbghover=0x999999&righticon=0x666666&righticonhover=0xffffff&text=0x666666&slider=0x666666&track=0xFFFFFF&border=0x666666&loader=0x9FFFB8&loop=no&autostart=%s" type="application/x-shockwave-flash" wmode="transparent" height="24" width="100%%" />

''' % (self.music_title, self.music_url, self.__id__, auto_start)


from stl import STL, Signal

time_begin = 0  # global begin time
signal = Signal(py_dict={"0": {"content": {"x": 1, "y": 2}},
                         "1": {"content": {"x": 2, "y": 1}}})

#stl_spec = STL("G[0, 1](0 < x < 1)")
stl_eval = stl_spec.eval(time_begin, signal)

print()
#print("original STL expr: ")
#print(stl_spec)

print()
weakened_stl = stl_spec.weaken("ap-range", 2, 3)
#print(weakened_stl_spec_ap_range_1)
# G[0, 1](0-2 < x < 1+3)

# G[0, 1](-2 < x < 4)

print(weakened_stl.eval(time_begin, signal))


import signal
import subprocess
import os
import sys

def readCard():
    print(sys.platform)
    if(sys.platform == "linux"):
        proc = subprocess.run('javac -cp .:./lib/pteidlibj.jar main.java', shell=True,         stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        proc1 = subprocess.run('java -Djava.library.path=/usr/local/lib -cp lib/pteidlibj.jar:. main', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    elif(sys.platform == "win32"):
        proc = subprocess.run('javac -cp lib\pteidlibj.jar main.java',         stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        proc1 = subprocess.run('java -cp lib/pteidlibj.jar;. main', stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        return proc1

    return proc1.stdout

def terminate(proc):
    os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
    print("DEAD")


import cvxpy as cvp
import numpy as np
from collections import namedtuple

from mayavi import mlab
from mayavi.mlab import points3d, plot3d, quiver3d
import matplotlib.pyplot as plt

"""
http://www.larsblackmore.com/iee_tcst13.pdf

carrying the same assumption here that X is up (i.e. normal to land)

TODO:
    - fix q definition to be the y,z coordinate instead of xyz
    - figure out how to best pick an initial tf
    - make alpha a parameter istead of isp

"""

GFoldConfig = namedtuple('GFoldConfig', ['isp', 'm', 'm_fuel',
                                         'p1', 'p2',
                                         'g', 'pointing_lim', 'landing_cone',
                                         'q', 'v_max', 'w'])

_e1 = np.array([1, 0 ,0]).T
_e2 = np.array([0, 1 ,0]).T
_e3 = np.array([0, 0 ,1]).T
_E = np.array([[0, 1, 0], [0, 0, 1]])

def create_S(w):
    S = np.array([[0, -w[2], w[1]],
                  [w[2], 0, -w[0]],
                  [-w[1], w[0], 0]])
    return S

def create_A(w):
    S = create_S(w)
    A = np.zeros((6, 6))
    A[0:3, 3:6] = np.eye(3)
    A[3:6, 0:3] = -np.square(S)
    A[3:6, 3:6] = -2*S
    return A

def create_B():
    B = np.zeros((6, 3))
    B[0:3, :] = np.eye(3)
    return B

def get_cone(cone_angle):
    # cone angle between 0 and pi/2
    return _e1 / np.tan(cone_angle)

class GFOLDSolverPosition:
    def __init__(self, config, iterations):
        N = iterations
        self.N = N
        self.config = config

        # Parameters
        self.dt = cvp.Parameter()
        self.x_0 = cvp.Parameter(6)

        # Solved variables
        self.x = cvp.Variable((6, N))
        self.u = cvp.Variable((3, N))
        self.gam = cvp.Variable(N)
        self.z = cvp.Variable(N)

        # Problem 3
        self.constr = []
        self.constr = set_initial_constraints(self.constr, config, self.x, self.u, self.gam, self.z, N, self.x_0)
        self.constr = running_constraints(self.constr, config, self.x, self.u, self.gam, self.z, self.dt, N)
        self.obj = cvp.norm(self.x[0:3, N-1] - config.q[:])
        self.problem = cvp.Problem(cvp.Minimize(self.obj), self.constr)

    def initialize_dt(self, start_vel):
        alpha = 1.0 / (self.config.isp * 9.8)
        t_max = self.config.m / (alpha * self.config.p2)  # this differs from the paper, but using p1 results in cvp.log to return nan
        t_min = (self.config.m - self.config.m_fuel) * np.linalg.norm(start_vel) / self.config.p2
        print("Full time: ", (0.5*t_max + 0.5*t_min))
        self.dt.value = (0.5*t_max + 0.5*t_min) / self.N

    def solve(self, start_pos, start_vel):
        self.initialize_dt(start_vel)
        self.x_0.value = np.array([*start_pos, *start_vel])

        self.problem.solve(solver=cvp.ECOS, verbose=True)
        return self.x.value, self.u.value, self.gam.value, self.z.value

class GFOLDSolverMass(GFOLDSolverPosition):
    def __init__(self, config, iterations):
        super().__init__(config, iterations)
        self.d_p3 = cvp.Parameter(3)
        self.constr += [cvp.norm(self.x[:3, self.N-1] - config.q) <= cvp.norm(self.d_p3 - config.q)]
        self.problem = cvp.Problem(cvp.Maximize(self.z[self.N-1]), self.constr)

    def solve(self, d_p3, start_pos, start_vel):
        self.initialize_dt(start_vel)
        self.d_p3.value = d_p3
        self.x_0.value = np.array([*start_pos, *start_vel])

        self.problem.solve(solver=cvp.ECOS, verbose=False, max_iters=400)
        first_mass = self.z[-1].value
        print("Start dt: ", self.dt.value)
        self.dt.value = (self.N * self.dt.value + 1e-1)  / self.N
        print("end dt: ", self.dt.value)
        self.problem.solve(solver=cvp.ECOS, verbose=False, max_iters=400)
        second_mass = self.z[-1].value
        print("Mass change: ", first_mass - second_mass)
        return self.x.value, self.u.value, self.gam.value, self.z.value

class GFOLDSolver:
    def __init__(self, config, iterations):
        self.config = config
        self.position_solver = GFOLDSolverPosition(config, iterations)
        self.mass_solver  = GFOLDSolverMass(config, iterations)

    def solve(self, start_pos, start_vel):
        print("Solving position problem")
        x1, u1, gam1, z1 = self.position_solver.solve(start_pos, start_vel)
        # TODO: solve the mass problem efficiently!
        #print("Solving mass problem")
        #x2, u2, gam2, z2 = self.mass_solver.solve(x1[0:3,-1], start_pos, start_vel)
        return x1, u1, gam1, z1, self.position_solver.dt.value

def set_initial_constraints(constr, config, x, u, gam, z, N, x_0):
    constr += [x[:, 0] == x_0[:]]   # Initial velocity and position
    constr += [x[3:6, N-1] == np.array([0, 0, 0])]  # Final velocity == 0

    # TODO (make initial thrust direction a parameter)
    constr += [u[:, 0] == gam[0]*_e1] # Initial thrust is vertical
    constr += [u[:, N-1] == gam[N-1]*_e1] # final thrust is vertical (or 0)
    constr += [z[0] == cvp.log(config.m)] # Initial mass

    constr += [x[0, N-1] == 0]  # Final altitude should be 0
    constr += [x[0, 0:N-1] >= 0]  # All altitudes during flight should be above the ground
    return constr

def running_constraints(constr, config, x, u, gam, z, dt, N):
    A_w = create_A(config.w)
    alpha = 1.0 / (config.isp * 9.8)
    pointing_angle = np.cos(config.pointing_lim)
    p1 = config.p1
    p2 = config.p2
    v_max = config.v_max
    c = get_cone(config.landing_cone)
    g = config.g

    # Simple Euler integration
    for k in range(N-1):
        # Rocket dynamics constraints
        constr += [x[0:3, k+1] == x[0:3, k] + dt*(A_w@x[:, k])[0:3]]
        constr += [x[3:6, k+1] == x[3:6, k] + dt*(g + u[:, k])]
        constr += [z[k+1] == z[k] - dt*alpha*gam[k]]

        constr += [cvp.norm(x[3:6, k]) <= v_max]  # Velocity remains below maximum
        constr += [cvp.norm(u[:,k]) <= gam[k]]  # Helps enforce the magnitude of thrust vector == thrust magnitude
        constr += [u[0,k] >= pointing_angle*gam[k]]  # Rocket can only point away from vertical by so much
        constr += [cvp.norm(_E@(x[:3,k] - x[:3,-1])) - c.T@(x[:3, k] - x[:3,-1]) <= 0]  # Stay inside the glide cone

        if k > 0:
            z_0 = cvp.log(config.m - alpha * p2 * (k) * dt)
            z_1 = cvp.log(config.m - alpha * p1 * (k) * dt)

            sigma_lower = p1 * cvp.exp(-z_0) * (1 - (z[k] - z_0) + (z[k] - z_0))
            sigma_upper = p2 * cvp.exp(-z_0) * (1 - (z[k] - z_0))

            # Minimimum and maximum thrust constraints
            constr += [gam[k] <= sigma_upper]
            constr += [gam[k] >= sigma_lower]
            # Minimum and maximum mass constraints
            constr += [z[k] >= z_0]
            constr += [z[k] <= z_1]
    return constr

def solve_gfold(config, start_pos, start_vel, iterations=100):
    solver = GFOLDSolver(config, iterations)
    x, u, gam, z, dt = solver.solve(start_pos, start_vel)
    return x, u, gam, z, dt

if __name__ == "__main__":
    config = GFoldConfig(isp=350,
                         m=12000,
                         m_fuel=1000,
                         p1=0.001*250000,
                         p2=0.5*250000,
                         g=np.array([-3, 0, 0]),
                         pointing_lim=np.deg2rad(45),
                         landing_cone=np.deg2rad(30),
                         q=np.array([0, 0, 0]),
                         v_max=1000,
                         w=np.array([0, 0, 0])
                         )

    start_pos = np.array([25000, 10000, 10000])
    start_vel = np.array([-300, -300, 300])

    x, u, gam, z = solve_gfold(config, start_pos, start_vel)
    print(f"final values:\nx: {x[:,-1]}\nu: {u[:,-1]}", )

    f = mlab.figure(bgcolor=(0, 0, 0))
    points3d([0], [0], [0], scale_factor=200.0, resolution=128, color=(0, 0.5, 0.5))
    s = plot3d(x[0,:], x[1,:], x[2,:], tube_radius=5.0, colormap='Spectral')
    v = quiver3d(x[0,:], x[1,:], x[2,:], u[0,:], u[1,:], u[2,:])
    mlab.axes()
    mlab.show()


import logging.config

import os
from flask import Flask, Blueprint
import settings
from api.restplus import api
from api.auth.endpoints.register import ns as authentication_namespace
from database.models import mysql as db

app = Flask(__name__)
logging_conf_path = os.path.normpath(os.path.join(os.path.dirname(__file__), 'logging.conf'))
logging.config.fileConfig(logging_conf_path)
log = logging.getLogger(__name__)
# mysql = MySQL()

# MySQL configurations
# app.config['MYSQL_DATABASE_USER'] = 'jay'
# app.config['MYSQL_DATABASE_PASSWORD'] = 'jay'
# app.config['MYSQL_DATABASE_DB'] = 'BucketList'
# app.config['MYSQL_DATABASE_HOST'] = 'localhost'

def configure_app(flask_app):
    flask_app.config['SERVER_NAME'] = settings.FLASK_SERVER_NAME
    flask_app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI
    flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = settings.SQLALCHEMY_TRACK_MODIFICATIONS
    flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
    flask_app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_VALIDATE
    flask_app.config['RESTPLUS_MASK_SWAGGER'] = settings.RESTPLUS_MASK_SWAGGER
    flask_app.config['ERROR_404_HELP'] = settings.RESTPLUS_ERROR_404_HELP
    #===
    flask_app.config['MYSQL_DATABASE_HOST'] = 'localhost'
    flask_app.config['MYSQL_DATABASE_USER'] = 'root'
    flask_app.config['MYSQL_DATABASE_PASSWORD'] = 'admin'
    flask_app.config['MYSQL_DATABASE_DB'] = 'mydatabase'

def initialize_app(flask_app):
    configure_app(flask_app)

    db.init_app(flask_app)
    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api.init_app(blueprint)
    api.add_namespace(authentication_namespace)
    flask_app.register_blueprint(blueprint)

def main():
    # login_manager.init_app(app)
    print('asasd')
    initialize_app(app)

    log.info('>>>>> Starting development example at http://{}/api/ <<<<<'.format(app.config['SERVER_NAME']))
    app.run(debug=settings.FLASK_DEBUG)

if __name__ == "__main__":
    main()


# Title: Structure Of Balanced Networks
# Link: https://www.acmicpc.net/problem/16721

import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 6)

def read_single_int(): return int(sys.stdin.readline().strip())

def read_list_words(): return sys.stdin.readline().strip().split(' ')

def read_list_int(): return list(map(int, sys.stdin.readline().strip().split(' ')))

def find(x: int, parent: list):
    if x == parent[x]:
        return x
    else:
        p = find(parent[x], parent)
        parent[x] = p
        return p

def union(x: int, y: int, parent: list):
    x = find(x, parent)
    y = find(y, parent)
    if x != y:
        parent[y] = x

def solution_union_find(n: int, parents: list, m: int, query: list):
    ans = []
    for a, b in query:
        if find(a, parents) == find(b, parents):
            ans.append('+')
        else:
            ans.append('-')
    return '\n'.join(ans)

def main_union_find():
    n = read_single_int()
    parents = [i for i in range(n)]
    for r in range(n):
        for c, v in enumerate(read_list_words()):
            if v == '+':
                union(r, c, parents)
    m = read_single_int()
    query = []
    for _ in range(m):
        query.append(read_list_int())
    print(solution_union_find(n, parents, m, query))

def solution(n: int, side: list, m: int, query: list):
    ans = []
    for a, b in query:
        ans.append('+') if side[a] == side[b] else ans.append('-')
    return '\n'.join(ans)

def main():
    n = read_single_int()
    side = []
    for v in read_list_words():
        side.append(False) if v == '-' else side.append(True)
    for _ in range(n-1):
        sys.stdin.readline()

    m = read_single_int()
    query = []
    for _ in range(m):
        query.append(read_list_int())
    print(solution(n, side, m, query))

if __name__ == '__main__':
    # main_union_find()
    main()


import sys
input = sys.stdin.readline

def is_palindrome(word: str) -> bool:
    return word == word[::-1]

def is_similarity_palindrome(word: str) -> bool:
    n = len(word)
    left, right = 0, n-1
    delete = False
    while left <= right:
        if word[left] == word[right]:
            left += 1
            right -= 1
        elif not delete:
            tmp = word[left:right+1]
            if is_palindrome(tmp[1:]):
                left += 2
                right -= 1
            elif is_palindrome(tmp[:-1]):
                left += 1
                right -= 2
            else:
                return False
            delete = True
        else:
            return False
    return True

t = int(input())
for _ in range(t):
    word = input().rstrip()
    if is_palindrome(word):
        print(0)
    elif is_similarity_palindrome(word):
        print(1)
    else:
        print(2)


from sklearn.decomposition import PCA, TruncatedSVD, SparsePCA
from sklearn.feature_extraction.text import CountVectorizer
from mpl_toolkits import mplot3d
from matplotlib import pyplot as plt

import d2v_model
import iterate_docs
import numpy as np
from itertools import accumulate

def get_pca(docs):
  pca = PCA(n_components=3)
  d2vm = d2v_model.get_d2v_model()
  ret = pca.fit_transform([d2vm.infer_vector(doc.split(' ')) for doc in docs])
  return ret, list(accumulate(pca.explained_variance_ratio_))

def get_tsvd(docs):
  tsvd = TruncatedSVD(n_components=3)
  cts = CountVectorizer().fit_transform(docs)
  ret = tsvd.fit_transform(cts)
  return ret, list(accumulate(tsvd.explained_variance_ratio_))

def plot_points(dim_red_func, docs):
  points, freq_ = dim_red_func(docs)
  print('total variance preserved: ' + str(freq_))

  fig = plt.figure()
  ax = plt.axes(projection ='3d')
  dim_tuples = [(min(points.T[i])-1, max(points.T[i])+1) for i in range(3)]

  ax.set_xlim(*dim_tuples[0])
  ax.set_ylim(*dim_tuples[1])
  ax.set_zlim(*dim_tuples[2])

  print(dim_tuples)
  ax.scatter3D(points.T[0], points.T[1], points.T[2], cmap ='black')
  plt.show()

print(get_pca(iterate_docs.get_docs()[0:40])[1])
print(get_tsvd(iterate_docs.get_docs()[0:40])[1])


from django.urls import path
from . import views
from .views import Register

urlpatterns = [
    path('cart/', views.view_cart, name='cart'),
    path('add_to_cart/<int:product_id>/', views.add_to_cart, name='add_to_cart'),
    path('remove_from_cart/<int:cart_item_id>/', views.remove_from_cart, name='remove_from_cart'),
    path('<int:product_id>/', views.product_detail, name='product_detail'),
    path('update_cart_item/', views.update_cart_item_quantity, name='update_cart_item_quantity'),
    path('payment_result/', views.payment, name='payment_result'),
    path('checkout/', views.checkout, name='checkout'),
    path('order_success/', views.order_success, name='order_success'),
    path('register/', Register.as_view(), name='register'),
    path('products/', views.product_list, name='product_list'),
    path('', views.home, name='home'),
    path('products/<int:category_id>/', views.product_list, name='product_list_by_category'),

]


# Inspired by allennlp implementation at https://github.com/allenai/allennlp/blob/master/allennlp/common/params.py
def flatten(nested_dict: Dict[str, Any]) -> Dict[str, Any]:
    """
    Returns the parameters of a flat dictionary from keys to values.
    Nested structure is collapsed with periods.
    """
    flat_dict = {}

    def recurse(parameters, path):
        for key, value in parameters.items():
            newpath = path + [key]
            if isinstance(value, dict):
                recurse(value, newpath)
            else:
                flat_dict['.'.join(newpath)] = value

    recurse(nested_dict, [])
    return flat_dict

# Inspired by allennlp implementation at https://github.com/allenai/allennlp/blob/master/allennlp/common/params.py
def unflatten(flat_dict: Dict[str, Any]) -> Dict[str, Any]:
    """
    Given a "flattened" dict with compound keys, e.g.
        {"a.b": 0}
    unflatten it:
        {"a": {"b": 0}}
    """
    unflat: Dict[str, Any] = {}

    for compound_key, value in flat_dict.items():
        curr_dict = unflat
        parts = compound_key.split(".")
        for key in parts[:-1]:
            curr_value = curr_dict.get(key)
            if key not in curr_dict:
                curr_dict[key] = {}
                curr_dict = curr_dict[key]
            elif isinstance(curr_value, dict):
                curr_dict = curr_value
            else:
                raise ConfigurationError("flattened dictionary is invalid")
        if not isinstance(curr_dict, dict) or parts[-1] in curr_dict:
            raise ConfigurationError("flattened dictionary is invalid")
        else:
            curr_dict[parts[-1]] = value

    return unflat

def nested_dict_iter_1(nested):
    for key, value in nested.items():
        if isinstance(value, abc.Mapping):
            yield from nested_dict_iter(value)
        else:
            yield key, value

def nested_dict_iter_2(nested):
    for key, value in nested.items():
        if isinstance(value, abc.Mapping):
            yield from nested_dict_iter(top_level, value)
        elif isinstance(value, list):
            for value_item in value:
                yield key, value


import time

import timeit

def LinearSearch(A, key):
    current = 1
    found = False

    AlistSize = len(A)

    while current <= AlistSize and found != True:
        if(A[current] == key):
            found = True
            print('Found')
        else:
            current = current + 1
            print('Not Found')

    return found

A = list(range(0, 100001))

key = 99999

""" t = timeit.default_timer()

# replace this line with appropriate function name
a = LinearSearch(A, key)

elapsed_time = timeit.default_timer() - t
print(elapsed_time) """

t = time.process_time()

# replace this line with appropriate function name
a = LinearSearch(A, key)
elapsed_time = time.process_time() - t
print(elapsed_time)

# ATTENTION READ TIME CASE RESULTS BELOW

# Best case is O(1), runs once and finds match
# Best Case Time Result: 0.00026980, 0.000542499, .00036900

# Worse case is O(n), runs all the way and doesnt find any matches
# Worse case Time Results: 2.546875, 2.640625, 2.453125


def main(array:list):
    #* Step 0: assigning variables to the function
    array_filter    = list()
    number_of_pawer = [2,3,4,5,6,7,8,9]
    #* Step 1: filter a numbers
    for i in range(len(array)):
        #* Step 2: exclude any number less than one
        if array[i] > 1:
            #* Step 3: ensure that the number is an even number
            if array[i] % 2 == 0:
                #? Note: "continue" because we do not want the even number in the array after the filter
                continue

            #* Step 4: exclude odd numbers
            elif array[i] % 2 == 1:
            #* Step 5: putting a for loop to expel the odd numbers
                for j in range(len(number_of_pawer)):
                    #* Step 6: It is known that odd numbers are only divisible by themselves and one,
                    #* so here he is decomposing a matrix (analsys_number) and dividing it into two parts :
                    #* (an_part_o[analsys number one] and an_part_t[analsys number two]).

                    analsys_number       = str(array[i] / number_of_pawer[j]).split(".")
                    an_part_o, an_part_t = int(analsys_number[0]), int(analsys_number[1])

                    #* Step 7: A conditional order, one of the conditions of prime numbers is that the number is
                    #* integer and greater than one.
                    if (an_part_o != 1 or 0) and an_part_t == 0:
                        #* Step 8: Add the required after filtering
                        array_filter.append(array[i])
                        break
                    else:
                        continue
            else:
                continue
        else:
            #* Step 8: Add the required after filtering
            array_filter.append(array[i])
    #* Step 9: return after filtring
    return array_filter

#* Step 10: RUNING
array = [1,2,4,5,9,11]
print(f"----[Befor Filter]----\n{array}\n----[After Filter]----\n{main(array)}")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Minimum interval cover

jill-jênn vie et christoph dürr - 2014-2020
"""

from sys import stdin
from math import sqrt
from tryalgo.our_std import readarray

# pylint: disable=redefined-outer-name

def _solve(iles, rayon):
    II = []
    for x, y in iles:
        if y > rayon:
            return -1               # island is too far
        z = sqrt(rayon * rayon - y * y)   # find the interval
        II.append((x + z, x - z))
    II.sort()                        # sort by right side
    sol = 0
    last = float('-inf')
    for right, left in II:
        if last < left:             # uncovered interval
            sol += 1
            last = right            # put an antenna
    return sol

# snip{
def interval_cover(I):
    """Minimum interval cover

    :param I: list of closed intervals
    :returns: minimum list of points covering all intervals
    :complexity: O(n log n)
    """
    S = []
    # sort by right endpoints
    for start, end in sorted(I, key=lambda v: v[1]):
        if not S or S[-1] < start:
            S.append(end)
    return S
# snip}

if __name__ == "__main__":
    # http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1360
    testCase = 1
    while True:
        n, rayon = readarray(int)   # n=#islands, d=radius
        if n == 0:
            break            # end of instances
        iles = []
        for _ in range(n):
            x, y = readarray(int)
            iles.append((x, y))
        stdin.readline()          # consume empty line
        print("Case %i: %i" % (testCase, _solve(iles, rayon)))
        testCase += 1


"""
Created on Jul 24, 2018

@author: ionut
"""

import logging
import datetime
from reach.base import Reach

class ReachGPS(Reach):
    """
    GPS client implementation for Reach
    """

    def __init__(self, host, port, queue):
        Reach.__init__(self, host, port, queue, message_delimiter="\n$GNRMC")
        self.conn_buf = 4096
        self.tcp_buf_len = 64000

    @staticmethod
    def parse_coordinate(coord, hemi):
        """
        Parse ddmm.mmmm coordinate into dd.ddddd format
        :param coord: ddmm.mmmm coordinate data
        :param hemi: hemisphere data E,W,N or S
        :returns dd.ddddd coordinate
        """
        dot_position = coord.find(".")
        degrees = coord[:dot_position-2]
        minutes = coord[dot_position-2:]
        degrees = float(degrees) + float(minutes) / 60.0
        if hemi in ["S", "W"]:
            degrees = degrees * -1
        return degrees

    def parse_data(self, data):
        sentences = data.split("\n")
        position = {}
        for sentence in sentences:
            if sentence.startswith("$GNRMC"):
                parts = sentence.split(",")
                if parts[2] != "A":
                    logging.warning("invalid GNRMC data: %s", sentence)
                    continue
                position["ts"] = datetime.datetime.strptime(parts[9]+parts[1], "%d%m%y%H%M%S.%f")
                position["ts"] = position["ts"].replace(tzinfo=datetime.timezone.utc)
                position["lat"] = self.parse_coordinate(parts[3], parts[4])
                position["lng"] = self.parse_coordinate(parts[5], parts[6])
                position["speed"] = float(parts[7]) * 1.852  # knots to km/h
                # position["heading"] = float(parts[8]) #0-360
            elif sentence.startswith("$GNGST"):
                parts = sentence.split(",")
                position["acc"] = max(float(parts[6]), float(parts[7]))  # meters
            elif sentence.startswith("$GNGGA"):
                parts = sentence.split(",")
                position["alt"] = float(parts[9]) + float(parts[11])  # meters
                position["fix"] = float(parts[6])
        return position


import copy
import sys

# for linux env.
sys.path.insert(0, '..')
import time
import pickle
import argparse

from utils import *
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np
import torch
import torch.nn.functional as F
import random
import pandas as pd
import json
import matplotlib.pyplot as plt
from model import lstm, ml
import itertools
import functools
from dataset_lstm import LSTM_Dataset
from Vocab import *

print = functools.partial(print, flush=True)

def parse_args():
    parser = argparse.ArgumentParser(description='process parameters')
    # Input
    parser.add_argument('--dataset', type=str, choices=['apcd', 'hidd', 'khin'], default='khin')
    parser.add_argument("--random_seed", type=int, default=0)
    parser.add_argument('--feature_space', type=str, choices=['combined', 'local'], default='combined')
    parser.add_argument('--code_topk', type=int, default=300)
    # parser.add_argument('--run_model', choices=['LSTM', 'MLP'], default='MLP')

    # Deep PSModels
    parser.add_argument('--batch_size', type=int, default=256)  # 768)  # 64)
    parser.add_argument('--learning_rate', type=float, default=1e-3)  # 0.001
    parser.add_argument('--weight_decay', type=float, default=1e-6)  # )0001)
    parser.add_argument('--epochs', type=int, default=10)  # 30
    # LSTM
    parser.add_argument('--diag_emb_size', type=int, default=128)
    # parser.add_argument('--med_emb_size', type=int, default=128)
    # parser.add_argument('--med_hidden_size', type=int, default=64)
    parser.add_argument('--diag_hidden_size', type=int, default=64)
    parser.add_argument('--lstm_hidden_size', type=int, default=100)
    # MLP
    # parser.add_argument('--hidden_size', type=str, default='', help=', delimited integers')
    # Output
    parser.add_argument('--output_dir', type=str, default='output/lstm/')
    args = parser.parse_args()

    # Modifying args
    args.cuda = torch.cuda.is_available()
    args.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    if args.random_seed >= 0:
        rseed = args.random_seed
    else:
        from datetime import datetime
        rseed = datetime.now()
    args.random_seed = rseed
    args.save_model_filename = os.path.join(args.output_dir, '{}/lstm_S{}.model'.format(args.dataset,
                                                                                args.random_seed))
    check_and_mkdir(args.save_model_filename)
    #
    # args.hidden_size = [int(x.strip()) for x in args.hidden_size.split(',')
    #                     if (x.strip() not in ('', '0'))]

    return args

if __name__ == '__main__':
    # python main_lstm.py --dataset hidd --random_seed 0 2>&1 | tee  log/lstm_hidd_r0.txt

    start_time = time.time()
    args = parse_args()
    print('args: ', args)
    print('random_seed: ', args.random_seed)
    print('device: ', args.device)

    # reproducibility
    np.random.seed(args.random_seed)
    torch.manual_seed(args.random_seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed(args.random_seed)
    random.seed(args.random_seed)
    torch.backends.cudnn.deterministic = True

    #
    print('Dataset:', args.dataset)
    encode2namefile = r'dataset/icd9encode2name.pkl'
    majordatafile = r'dataset/final_pats_1st_neg_triples_{}-{}_new_labeled.pkl'.format(args.dataset, 'icd9')
    with open(encode2namefile, 'rb') as f:
        dx_name = pickle.load(f)
        print('len(dx_name):', len(dx_name))

    with open(majordatafile, 'rb') as f:
        data_1st_neg = pickle.load(f)
        print('len(data_1st_neg):', len(data_1st_neg))

    if args.feature_space == 'combined':
        # Load combined features
        with open('Pre_train/selected_features_apcd.obj', 'rb') as f:
            vocab_apcd = pickle.load(f)

        with open('Pre_train/selected_features_hidd.obj', 'rb') as f:
            vocab_hidd = pickle.load(f)

        with open('Pre_train/selected_features_khin.obj', 'rb') as f:
            vocab_khin = pickle.load(f)

        vocab_combined = copy.deepcopy(vocab_apcd)
        vocab_combined.extend_vocab(vocab_hidd)
        vocab_combined.extend_vocab(vocab_khin)

        print('Using combined feature space')
        my_dataset = LSTM_Dataset(data_1st_neg, diag_name=dx_name, diag_code_vocab=vocab_combined)

    else:
        print('Using local feature space, top k:', args.code_topk)
        my_dataset = LSTM_Dataset(data_1st_neg, diag_name=dx_name, diag_code_topk=args.code_topk)

    n_feature = my_dataset.DIM_OF_CONFOUNDERS
    feature_name = my_dataset.FEATURE_NAME
    print('n_feature: ', n_feature, ':')

    train_ratio = 0.7  # 0.5
    val_ratio = 0.1
    print('train_ratio: ', train_ratio,
          'val_ratio: ', val_ratio,
          'test_ratio: ', 1 - (train_ratio + val_ratio))

    dataset_size = len(my_dataset)
    indices = list(range(dataset_size))
    train_index = int(np.floor(train_ratio * dataset_size))
    val_index = int(np.floor(val_ratio * dataset_size))

    # data shuffle in here
    np.random.shuffle(indices)

    train_indices, val_indices, test_indices = indices[:train_index], \
                                               indices[train_index:train_index + val_index], \
                                               indices[train_index + val_index:]

    train_sampler = SubsetRandomSampler(train_indices)
    val_sampler = SubsetRandomSampler(val_indices)
    test_sampler = SubsetRandomSampler(test_indices)

    train_loader = torch.utils.data.DataLoader(my_dataset, batch_size=args.batch_size, sampler=train_sampler)
    val_loader = torch.utils.data.DataLoader(my_dataset, batch_size=args.batch_size, sampler=val_sampler)
    test_loader = torch.utils.data.DataLoader(my_dataset, batch_size=args.batch_size, sampler=test_sampler)
    data_loader = torch.utils.data.DataLoader(my_dataset, batch_size=args.batch_size, sampler=SubsetRandomSampler(indices))

    # train_loader_shuffled = torch.utils.data.DataLoader(my_dataset, batch_size=256, sampler=train_sampler)
    #
    # print('len(train_loader_shuffled): ', len(train_loader_shuffled),
    #       'train_loader_shuffled.batch_size: ', train_loader_shuffled.batch_size)
    #
    # for confounder, outcome, uid in train_loader_shuffled:
    #     print(confounder)

    print("**************************************************")
    print("**************************************************")
    print('LSTM-Attention PS PSModels learning:')

    paras_grid = {
        'hidden_size': [32, 64],  #  64, 128
        'diag_hidden_size': [32, 64],
        'diag_embedding_size': [32, 64],
        'lr': [1e-3, 1e-4],
        'weight_decay': [1e-4, 1e-5,],
        'batch_size': [1024],  # 50
    }
    hyper_paras_names, hyper_paras_v = zip(*paras_grid.items())
    hyper_paras_list = list(itertools.product(*hyper_paras_v))
    print('Model lstm Searching Space N={}: '.format(len(hyper_paras_list)), paras_grid)

    best_hyper_paras = None
    best_model = None
    best_auc = float('-inf')
    best_balance = float('inf')
    best_model_epoch = -1
    best_result_9 = None
    best_result_95 = None
    results = []
    i = -1
    i_iter = -1
    for hyper_paras in tqdm(hyper_paras_list):
        i += 1
        hidden_size, diag_hidden_size, diag_embedding_size, lr, weight_decay, batch_size = hyper_paras
        print('In hyper-paras space [{}/{}]...'.format(i, len(hyper_paras_list)))
        print(hyper_paras_names)
        print(hyper_paras)

        train_loader_shuffled = torch.utils.data.DataLoader(my_dataset, batch_size=batch_size, sampler=train_sampler)
        print('len(train_loader_shuffled): ', len(train_loader_shuffled),
              'train_loader_shuffled.batch_size: ', train_loader_shuffled.batch_size)

        model_params = dict(
            diag_hidden_size=diag_hidden_size,  # 64
            hidden_size=hidden_size,  # 100,
            bidirectional=True,
            diag_vocab_size=len(my_dataset.diag_code_vocab),
            diag_embedding_size=diag_embedding_size,  # args.diag_emb_size,  # 128
            # end_index=my_dataset.diag_code_vocab[CodeVocab.END_CODE],
            # pad_index=my_dataset.diag_code_vocab[CodeVocab.PAD_CODE],
        )
        print('Model: LSTM')
        print(model_params)
        model = lstm.LSTMModel(**model_params)
        if args.cuda:
            model = model.to('cuda')
        print(model)

        optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)

        for epoch in tqdm(range(args.epochs)):
            i_iter += 1
            epoch_losses = []
            uid_list = []
            for confounder, labels, outcome, uid in train_loader_shuffled:
                model.train()
                # train IPW
                optimizer.zero_grad()
                uid_list.extend(uid)
                if args.cuda:  # confounder = (diag, med, sex, age)
                    for ii in range(len(confounder)):
                        confounder[ii] = confounder[ii].to('cuda')
                    flag = labels.to('cuda').float()

                treatment_logits, _ = model(confounder)
                loss = F.binary_cross_entropy_with_logits(treatment_logits, flag)

                loss.backward()
                optimizer.step()
                epoch_losses.append(loss.item())

            # just finish 1 epoch
            # scheduler.step()
            epoch_losses = np.mean(epoch_losses)

            auc_val, loss_val, Y_val, Y_pred_val, uid_val = transfer_data(model, val_loader, cuda=args.cuda,
                                                                          normalized=False)

            auc_test, loss_test, Y_test, Y_pred_test, uid_test = transfer_data(model, test_loader, cuda=args.cuda,
                                                                               normalized=False)

            results.append((i_iter, i, epoch, hyper_paras, auc_val, auc_test))

            print('', flush=True)
            print('HP-i:{}, epoch:{}, loss:{}, val-auc:{}, test-auc:{}'.format(
                i, epoch, epoch_losses, auc_val, auc_test)
            )
            print('Validation set, len:', len(Y_val))
            result_9_val = ml.MLModels._performance_at_specificity_or_threshold(Y_pred_val, Y_val, specificity=0.9)
            result_95_val = ml.MLModels._performance_at_specificity_or_threshold(Y_pred_val, Y_val, specificity=0.95)
            print('Test set, len:', len(Y_test))
            result_9_test = ml.MLModels._performance_at_specificity_or_threshold(Y_pred_test, Y_test, specificity=0.9)
            result_95_test = ml.MLModels._performance_at_specificity_or_threshold(Y_pred_test, Y_test, specificity=0.95)

            if auc_val > best_auc:
                best_model = model
                best_hyper_paras = hyper_paras
                best_auc = auc_val
                best_model_epoch = epoch
                best_result_9 = result_9_val
                best_result_95 = result_95_val
                print('Save Best PSModel at Hyper-iter[{}/{}]'.format(i, len(hyper_paras_list)),
                      'Epoch: ', epoch, 'val-auc:', best_auc, "test-auc", auc_test)
                print(hyper_paras_names)
                print(hyper_paras)
                save_model(model, args.save_model_filename, model_params=model_params)

    col_name = ['i', 'ipara', 'epoch', 'paras', 'val_auc', 'test_auc']
    results = pd.DataFrame(results, columns=col_name)

    print('Model selection finished! Save Global Best PSModel at Hyper-iter [{}/{}], Epoch: {}'.format(
        i, len(hyper_paras_list), best_model_epoch), 'val-auc:', best_auc)

    print(hyper_paras_names)
    print(best_hyper_paras)

    results.to_csv(args.save_model_filename + '_ALL-model-select.csv')
    auc_test, loss_test, Y_test, Y_pred_test, uid_test = transfer_data(best_model, test_loader, cuda=args.cuda,
                                                                       normalized=False)

    print('Final results', 'loss_test', loss_test, "test-auc", auc_test)

    result_1 = ml.MLModels._performance_at_specificity_or_threshold(Y_pred_test, Y_test, specificity=0.9)
    print('......Results at specificity 0.95:')
    result_2 = ml.MLModels._performance_at_specificity_or_threshold(Y_pred_test, Y_test, specificity=0.95)

    df1 = pd.DataFrame([result_1 + (best_hyper_paras,), result_2 + (best_hyper_paras,)],
                       columns=["AUC", "threshold", "Specificity", "Sensitivity/recall", "PPV/precision",
                                "n_negative", "n_positive", "precision_recall_fscore_support", 'best_hyper_paras'],
                       index=['r_9', 'r_95'])
    df1.to_csv(os.path.join(os.path.dirname(args.save_model_filename),
                            'test_results_{}r{}.csv'.format('lstm', args.random_seed)))

    # to dump feature importance, how?
    # df3 = pd.DataFrame({'train_x_model': model.best_model.coef_[0]}, index=feature_name).reset_index()
    # df3.to_csv(os.path.join(os.path.dirname(args.save_model_filename),
    #                         'model_coef_train_LRr{}.csv'.format(args.random_seed)))

    print('Done! Total Time used:', time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time)))


#!/usr/bin/python3
"""new view for State objects"""
from api.v1.views import app_views
from models import storage
from models.state import State
from flask import jsonify, abort, request

@app_views.route(
    '/states',
    methods=['GET', 'POST'],
    strict_slashes=False
)
def states():
    """ GET and POST   """

    if request.method == "GET":
        states = [state.to_dict() for state in storage.all('State').values()]
        return jsonify(list(states))

    if request.method == "POST":
        jreq = request.get_json()
        if jreq is None:
            abort(400, 'Not a JSON')

        if 'name' not in jreq.keys():
            abort(400, 'Missing name')

        state = State(**jreq)
        state.save()
        return jsonify(state.to_dict()), 201

@app_views.route(
    '/states/<state_id>',
    methods=['GET', 'DELETE', 'PUT'],
    strict_slashes=False
)
def state(state_id):
    """ GET, DELETE, and PUT """

    state = storage.get(State, state_id)
    if state is None:
        abort(404)

    if request.method == "GET":
        return jsonify(state.to_dict())

    if request.method == "DELETE":
        state.delete()
        storage.save()
        return jsonify({})

    if request.method == "PUT":
        jreq = request.get_json()
        if jreq is None:
            abort(400, 'Not a JSON')

        for k, v in jreq.items():
            if k not in ['id', 'created_at', 'updated_at']:
                setattr(state, k, v)
        state.save()
        return jsonify(state.to_dict())