import sys
from PIL import Image
from Node2 import Node
import math
from heapq import *

OPEN_LAND_COLOR = (248, 148, 18, 255)
ROUGH_MEADOW_COLOR = (255, 192, 0, 255)
EASY_MOVE_FOREST_COLOR = (255, 255, 255, 255)
SLOW_RUN_FOREST_COLOR = (2, 208, 60, 255)
WALK_FOREST_COLOR = (2, 136, 40, 255)
IMPASS_VEG_COLOR = (5, 73, 24, 255)
WATER_COLOR = (0, 0, 255, 255)
ROAD_COLOR = (71, 51, 3, 255)
FOOTPATH_COLOR = (0, 0, 0, 255)
OOB_COLOR = (205, 0, 101, 255)

ICE_COLOR = (0, 255, 255, 255)  # for winter only
PATH_COLOR = (255, 0, 0, 255)   # path will be red

# Speed in miles per hour
def getSpeed(node, terrain_pixel_map, elevation_file_name):
    x = node.getX()
    y = node.getY()

    location = terrain_pixel_map[x, y]

    speed = 0

    # Set base speed based on terrain
    if location == OOB_COLOR or location == IMPASS_VEG_COLOR or location == WATER_COLOR:
        speed = 0
    elif location == ROUGH_MEADOW_COLOR:
        speed = 1.5
    elif location == WALK_FOREST_COLOR:
        speed = 2.5
    elif location == EASY_MOVE_FOREST_COLOR or location == SLOW_RUN_FOREST_COLOR:
        speed = 3
    elif location == OPEN_LAND_COLOR or location == ROAD_COLOR or location == FOOTPATH_COLOR:
        speed = 4
    else:
        print("Terrain not recognized.")
        print(location)

    # Edit speed based on elevation change
    with open(elevation_file_name) as elevation_file:
        pass

    # print("end speed gotten")
    return speed

def getAdj(currentNode, target, terrain_pixel_map):
    x = currentNode.getX()
    y = currentNode.getY()
    nodes = []
    if (x - 1) >= 0:
        node = Node(currentNode.getG() + 1, x - 1, y, target, currentNode)
        speed = getSpeed(node, terrain_pixel_map, elevation_file_name)
        if speed != 0:      # we avoid any impassable terrain with this if
            nodes.append(node)
        if (y - 1) >= 0:
            node = Node(currentNode.getG() + 1, x - 1, y - 1, target, currentNode)
            speed = getSpeed(node, terrain_pixel_map, elevation_file_name)
            if speed != 0:
                nodes.append(node)
        if (y + 1) < 500:   # 500 is max height of map
            node = Node(currentNode.getG() + 1, x - 1, y + 1, target, currentNode)
            speed = getSpeed(node, terrain_pixel_map, elevation_file_name)
            if speed != 0:
                nodes.append(node)
    if (x + 1) < 395:       # 395 is max width of map
        node = Node(currentNode.getG() + 1, x + 1, y, target, currentNode)
        speed = getSpeed(node, terrain_pixel_map, elevation_file_name)
        if speed != 0:
            nodes.append(node)
        if (y - 1) >= 0:
            node = Node(currentNode.getG() + 1, x + 1, y - 1, target, currentNode)
            speed = getSpeed(node, terrain_pixel_map, elevation_file_name)
            if speed != 0:
                nodes.append(node)
        if (y + 1) < 500:   # 500 is max height of map
            node = Node(currentNode.getG() + 1, x + 1, y + 1, target, currentNode)
            speed = getSpeed(node, terrain_pixel_map, elevation_file_name)
            if speed != 0:
                nodes.append(node)
    if (y - 1) >= 0:
        node = Node(currentNode.getG() + 1, x, y - 1, target, currentNode)
        speed = getSpeed(node, terrain_pixel_map, elevation_file_name)
        if speed != 0:
            nodes.append(node)
    if (y + 1) < 500:
        node = Node(currentNode.getG() + 1, x, y + 1, target, currentNode)
        speed = getSpeed(node, terrain_pixel_map, elevation_file_name)
        if speed != 0:
            nodes.append(node)

    return nodes

# Path drawn in red
def drawPath(path, terrain_image, output_image_filename):
    out_image = Image.open(terrain_image_name)
    out_pixel_map = out_image.load()
    for node in path:
        x = node.getX()
        y = node.getY()
        out_pixel_map[x, y] = PATH_COLOR

    out_image.save(output_image_filename)

# simple A* search
def search(terrain_pixel_map, elevation_file_name, path_file_name, output_image_filename, location, target):
    # openList = []
    # closedList = []
    close_set = set()
    came_from = {}
    start = Node(0, location[0], location[1], target, None)   # g, x, y, target, parent
    startSpeed = getSpeed(start, terrain_pixel_map, elevation_file_name)
    start.setSpeed(startSpeed)
    start.setF(0)
    gscore = {start:0}
    fscore = {start:start.getH() + startSpeed}
    oheap = []

    heappush(oheap, (fscore[start], start))
    # openList.append(start)
    # while openList != []:
    while oheap:
        # currentNode = openList[0]
        currentNode = heappop(oheap)[1]
        # print("Current node ", currentNode.getX(), currentNode.getY())
        # determine node in open list with lowest f
        # oIndex = -1
        # currentIndex = 0
        # for node in openList:
        #     oIndex += 1
        #     if node.getF() < currentNode.getF():
        #         currentNode = node
        #         currentIndex = oIndex
        # # openList.remove(currentNode)
        # openList.pop(currentIndex)
        # print(open)
        # closedList.append(currentNode)

        if currentNode.x == target[0] and currentNode.y == target[1]:
            data = []
            while currentNode in came_from:
                data.append(currentNode)
                currentNode = came_from[currentNode]
            return data

        close_set.add(currentNode)

        # Base case
        if currentNode.getX() == target[0] and currentNode.getY() == target[1]:
            print("LOCAL TARGET FOUND", currentNode.getX(), currentNode.getY())
            target = getLoc(path_file_name)
            if target == []:    # if target = [], we're at the end of the search
                print("FINAL TARGET FOUND", currentNode.getX(), currentNode.getY())
                path = []
                current = currentNode
                while current is not None:
                    # print("Current node ", current)
                    path.append(current)
                    current = current.parent
                return path[::-1]

        # Get adjacent nodes to currentNode
        nodes = getAdj(currentNode, target, terrain_pixel_map)

        close_set.add(currentNode)
        for i, j in nodes:
            node = currentNode[0] + i, current[1] + j
            tent_g = gscore[current] + node.getH()

        for node in nodes:
            # if node is contained in closedList
            for element in closedList:
                if element == node:
                    continue

            # speed = getSpeed(node, terrain_pixel_map, elevation_file_name)
            speed = node.grabSpeed()
            pythag = math.sqrt(abs((node.getX() - target[0])**2 + (node.getY() - target[1])**2 ))   # pythagorean theorem used as additional heuristic
            node.setH(speed + pythag)
            node.setF(node.getG() + node.getH())

            for element in openList:
                if node.getX() == element.getX() and node.getY() == element.getY() and node.getG() > element.getG():
                    continue

                # else:
            openList.append(node)

# Trims the last 5 elements from every line to make each line 395 long
def trimElev(elevation_map_name):
    with open(elevation_file_name, 'r+') as elevation_file:
        lines = elevation_file.readlines()
        for line in lines:
            words = line.split()
            elevation_file.writelines(words[0:-5])

# return location at top of path file, removes top line
def getLoc(path_file_name):
    with open(path_file_name) as path_file:
        line = path_file.readline()
        loc = line.split()
        location = []
        if(loc != []):
            location.append(int(loc[0]))
            location.append(int(loc[1]))
        lines = path_file.readlines()
    with open(path_file_name, 'w') as path_file:
        path_file.writelines(lines[0:])
    return location

def fall():
    print("FALL")

def winter():
    print("WINTER")

def spring():
    print("SPRING")

if __name__ == "__main__":
    # Read in arguments
    terrain_image_name = ''
    elevation_file_name = ''
    path_file_name = ''
    season = ''
    output_image_filename = ''

    try:
        terrain_image_name = sys.argv[1]
        elevation_file_name = sys.argv[2]
        path_file_name = sys.argv[3]
        season = sys.argv[4]
        output_image_filename = sys.argv[5]
    except:
        print("Error: args should be formatted [terrain-image, elevation-file, path-file, season (summer,fall,winter,or spring), output-image-filename]")
        sys.exit()

    print(terrain_image_name)
    print(elevation_file_name)
    print(path_file_name)
    print(season)
    print(output_image_filename)

    terrain_image = Image.open(terrain_image_name)
    terrain_pixel_map = terrain_image.load()

    trimElev(elevation_file_name)

    '''
    TODO: implement fall winter and spring to do changes to globals in writeup
    '''
    if season == 'fall':
        fall()
    elif season == 'winter':
        winter()
    elif season == 'spring':
        spring()

    location = getLoc(path_file_name)   # starting location, first location in path file
    target = getLoc(path_file_name)

    if location == [] or target == []:
        print("The path only has one node.")
        sys.exit()

    path = search(terrain_pixel_map, elevation_file_name, path_file_name, output_image_filename, location, target)
    drawPath(path, terrain_image, output_image_filename)


a=[]
b=[]
c=0
d=0
for i in range (3):
    n=int(input())
    a.append(n)

for j in range (3):
    m=int(input())
    b.append(m)

for i in range (len(a)):
        if((b[i]>100 or b[i]<1) or (a[i]>100 or a[i]<1)):
            print("Invalid")
        else:
           if(a[i]>b[i]):
             c=c+1
           else :
              if(a[i]<b[i]):
                d=d+1

print(c,d)


import pygame
import imgui

from Framework.Vector import vec2
from GameObject import GameObject
from Tilemap import TileTypes

class PlayerTilemapFree(GameObject):
    def __init__(self, tilePosition, sprite, animationFrames, tilemap):
        super().__init__( vec2( 0, 0 ), sprite, animationFrames[0] )
        self.animationFrames = animationFrames
        self.tilemap = tilemap
        self.currentAnimation = 1 # Moving down.
        self.currentFrame = 0
        self.animationTimer = 0.2
        self.position = self.tilemap.getWorldPositionForTilePosition( tilePosition )

    def onEvent(self, event):
        super().onEvent( event )

        # Inputs will set the direction the player is moving.
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                self.direction.y += 1
            if event.key == pygame.K_s:
                self.direction.y += -1
            if event.key == pygame.K_a:
                self.direction.x += -1
            if event.key == pygame.K_d:
                self.direction.x += 1

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_w:
                self.direction.y -= 1
            if event.key == pygame.K_s:
                self.direction.y -= -1
            if event.key == pygame.K_a:
                self.direction.x -= -1
            if event.key == pygame.K_d:
                self.direction.x -= 1

    def doesPositionFitOnTilemap(self, position, size):
        # Check if the player's new X position is valid on this tilemap.
        tileTypeBL = self.tilemap.getTileTypeForWorldPosition( vec2( position.x,          position.y ) )
        tileTypeBR = self.tilemap.getTileTypeForWorldPosition( vec2( position.x + size.x, position.y ) )
        tileTypeTL = self.tilemap.getTileTypeForWorldPosition( vec2( position.x,          position.y + size.y ) )
        tileTypeTR = self.tilemap.getTileTypeForWorldPosition( vec2( position.x + size.x, position.y + size.y ) )

        # If it fits, set the new X position.
        if tileTypeBL == TileTypes.Empty and tileTypeBR == TileTypes.Empty and tileTypeTL == TileTypes.Empty and tileTypeTR == TileTypes.Empty:
           return True

        return False

    def update(self, deltaTime):
        # GameObject update will do the actual player movement.
        # super().update( deltaTime )

        collisionOffset = vec2( 0.15, 0.05 )
        playerSize = vec2( self.tilemap.tileSize.x * 0.7, self.tilemap.tileSize.y * 0.45 )
        newPosition = vec2( self.position.x + self.direction.x * self.speed * deltaTime,
                            self.position.y + self.direction.y * self.speed * deltaTime )

        # Check if the player's new X position is valid on this tilemap.  If it fits, set it.
        newPositionOnXAxis = vec2( newPosition.x + collisionOffset.x, self.position.y + collisionOffset.y )
        if self.doesPositionFitOnTilemap( newPositionOnXAxis, playerSize ):
            self.position.x = newPosition.x

        # Check if the player's new Y position is valid on this tilemap.  If it fits, set it.
        newPositionOnYAxis = vec2( self.position.x + collisionOffset.x, newPosition.y + collisionOffset.y )
        if self.doesPositionFitOnTilemap( newPositionOnYAxis, playerSize ):
            self.position.y = newPosition.y

        # Set the correct animation based on the direction we're going.
        # Animations are in this order: Up, Down, Left, Right
        # Each animation is 3 frames long.
        if self.direction.y > 0:
            self.currentAnimation = 0 # Moving up.
        if self.direction.y < 0:
            self.currentAnimation = 1 # Moving down.
        if self.direction.x < 0:
            self.currentAnimation = 2 # Moving left.
        if self.direction.x > 0:
            self.currentAnimation = 3 # Moving right.

        # Update the timer and switch frames on the animation.
        self.animationTimer -= deltaTime
        if self.animationTimer < 0:
            self.animationTimer = 0.2
            self.currentFrame += 1
            if self.currentFrame > 2:
                self.currentFrame = 0

        # If the player isn't moving, just force the first frame of the animation.
        if self.direction.x == 0 and self.direction.y == 0:
            self.currentFrame = 0

        # Set the player's current texture.
        self.texture = self.animationFrames[self.currentAnimation * 3 + self.currentFrame]

        # Debug info displayed using imgui.
        imgui.begin( "Player", True )
        changed, newvalue = imgui.slider_float2( "Position", self.position.x, self.position.y, 0, 20 )
        self.position.x = newvalue[0]
        self.position.y = newvalue[1]
        tiletype = self.tilemap.getTileTypeForWorldPosition( self.position + collisionOffset )
        imgui.text( "Tile Type: " + str(tiletype) )
        imgui.end()

    def draw(self):
        super().draw()


#!/usr/bin/env python
__author__ = 'tbeltramelli'

import argparse
from modules.Utils import *
from modules.Filtering import *

def main():
    images = ["assets/IMG_2560.jpg", "assets/IMG_0258.jpg", "assets/IMG_0257.jpg", "assets/IMG_0256.jpg",
              "assets/IMG_0253.jpg"]

    for image_path in images:
        get_url_segment(image_path)

def get_url_segment(image_path):
    original_image = Utils.get_image(image_path)

    kernels = ["assets/kernel.png"]

    result = search_for_template(original_image, kernels)
    if result is None:
        result = search_for_template(original_image, kernels, use_negative=True)

    if result is not None:
        Utils.show(Utils.resize(original_image, 600))
        Utils.show(result)

    return result

def search_for_template(original_image, kernels, use_negative=False):
    best = 0
    url_image = None

    for kernel_path in kernels:
        kernel = Utils.get_image(kernel_path)
        kernel = Filtering.get_gray_scale_rgb(kernel)
        if use_negative:
            kernel = Filtering.negative(kernel)

        result, score = detect_url(original_image, kernel)

        if result is None:
            continue

        if score > best:
            best = score
            url_image = result

    if url_image is not None:
        return url_image

    return None

def detect_url(original_image, template, score_threshold=0.4, to_extract=True, to_show=False):
    template_width, template_height = template.shape[::-1]

    color_image = np.copy(original_image)

    scores = []
    coordinates = []
    for i in range(0, 5):
        height, width, depth = color_image.shape
        target_width = width / 1.25
        image, color_image = preprocess(color_image, target_width)

        response = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)

        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(response)
        top_left = max_loc
        bottom_right = (top_left[0] + template_width, top_left[1] + template_height)

        scores.append(np.amax(response))
        coordinates.append((top_left, bottom_right, target_width))

    best_score = np.max(scores)
    if best_score < score_threshold:
        return None, best_score

    best_candidate = coordinates[np.argmax(scores)]

    result, img = preprocess(np.copy(original_image), best_candidate[2])
    result_height, result_width = result.shape

    sample_width = best_candidate[1][0] - best_candidate[0][0]
    sample_height = best_candidate[1][1] - best_candidate[0][1]

    start_x = best_candidate[0][0] - sample_width
    start_y = best_candidate[0][1] - (sample_height / 2)
    end_x = result_width - sample_width
    end_y = best_candidate[1][1] + (sample_height / 2)

    if to_extract:
        resulting_img = result[start_y:end_y, start_x:end_x]
    else:
        resulting_img = np.zeros((result_height, result_width), np.float32)
        resulting_img[start_y:end_y, start_x:end_x] = result[start_y:end_y, start_x:end_x]

    if to_show:
        image_to_show = np.copy(original_image)
        image_to_show = Utils.resize(image_to_show, best_candidate[2])
        cv2.rectangle(image_to_show, (start_x, start_y), (end_x, end_y), [0, 0, 255], 2)
        Utils.show(Utils.resize(image_to_show, 600))
        Utils.show(Utils.resize(Filtering.get_rgb_scale_gray(resulting_img), 600))

    return resulting_img, best_score

def preprocess(color_image, target_width):
    color_image = Utils.resize(color_image, target_width)
    image = Filtering.get_gray_scale_rgb(color_image)
    image = Filtering.sharpen(image, 5)
    thr, image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
    return image, color_image

if __name__ == "__main__":
    main()


import sys

# Get the input file
assert len(sys.argv) > 1
inputname = sys.argv[1]

# Read input
with open(inputname, 'r') as f:
    n, k = tuple(map(int, f.readline().split()))
    a = list(map(int, f.readline().split()))

def solution(a):
    # Strategy: to avoid exhaustive search over all combinations,
    # sort the array to have, for each element, its closest
    # elements (in terms of |a_i - a_j|) next to it.

    # Remember the original order to reorder the output. Sort the array.
    sorted_indices  = sorted(range(len(a)), key=a.__getitem__)
    reverse_indices = sorted(range(len(a)), key=sorted_indices.__getitem__)
    a = [a[i] for i in sorted_indices]

    # Main loop
    result = [0 for i in a] # To store minimal distances
    for i in range(len(a)):
        dist = 0 # Accumulator of distances
        left, right = i-1, i+1 # Left and right neighbours of the i-th element
        for neighbour in range(k):
            # If on either of the edges of the array, only one neighbour is possible:
            if left == -1:
                dist += abs(a[i] - a[right])
                right += 1
            elif right == len(a):
                dist += abs(a[i] - a[left])
                left -= 1
            # Otherwise, always take the closest neighbour into the distance calculation.
            else:
                dist_right = abs(a[i] - a[right])
                dist_left  = abs(a[i] - a[left ])
                dist += min(dist_left, dist_right)
                if dist_right < dist_left:
                    right += 1
                else:
                    left -= 1
        result[reverse_indices[i]] = dist
    return result#[result[i] for i in reverse_indices]

# Write to the output file
outputname = inputname[0:-3] + '.res'
with open(outputname, 'w') as f:
	f.write(' '.join(map(str, solution(a)))+'\n')


import json
from collections import defaultdict

import pandas as pd
from responsibly.dataset import COMPASDataset, GermanDataset
from sklearn.preprocessing import LabelEncoder

'''class DatasetType(Enum):
    """
    Enumeration of the Datasets under consideration.
    Values represent the sensitive attributes for each of the dataset types
    """
    COMPAS = ['age', 'sex']
    GERMAN_CREDIT = ['credit']
'''

class Dataset:
    """
    The Dataset Interface for all fairness analysis
    """

    def __init__(self, config_file) :
        f = open(config_file, 'r')
        config = json.loads(f.read())
        self.type = config['dataset']
        _dataset = COMPASDataset() if self.type == 'COMPAS' else GermanDataset()
        self._sensitive_attributes = config["sensitive_attributes"]
        self._non_numeric_attributes = config["non_numeric_attributes"]

        self._n_attributes_dict = config["numeric_attributes"]
        self._numeric_attributes = list(self._n_attributes_dict.keys()) if self._n_attributes_dict else []
        self._date_attributes_dict = config["date_attributes"]
        self._date_attributes = list(self._date_attributes_dict.keys()) if self._date_attributes_dict else []

        self._target = config['ground_truth']
        self._predictions = config['predictions']

        self._data_x_readable = pd.DataFrame(_dataset.df
                                             [
                                                 self._sensitive_attributes+self._non_numeric_attributes+self._numeric_attributes+self._date_attributes])
        self._data_y_readable = pd.DataFrame(_dataset.df[self._target])
        self._encoder_dict_x = defaultdict(LabelEncoder)
        self._encoder_dict_y = defaultdict(LabelEncoder)
        self._data_x, self._data_y = self._preprocess_data()

    def _preprocess_data(self) :
        """
        Private method to process data by converting all text features to numeric
        :return: Tuple containing encoded features and targets
        """

        if self.type == 'COMPAS' :
            self._data_x_readable.fillna('', inplace=True)

        self._data_x_readable = self._data_x_readable.loc[:, ~self._data_x_readable.columns.duplicated()]

        # write a date attribute function

        if self._numeric_attributes :
            for attribute in self._numeric_attributes :
                self._data_x_readable[attribute+'_bins'] = pd.cut(x=self._data_x_readable[attribute],
                                                                  bins=self._n_attributes_dict[attribute])
                self._data_x_readable = self._data_x_readable.drop(columns=[attribute])
                self._data_x_readable = self._data_x_readable.rename(columns={attribute+'_bins' : attribute})

        return self._data_x_readable.apply(lambda x : self._encoder_dict_x[x.name].fit_transform(x)), \
               self._data_y_readable.apply(lambda y : self._encoder_dict_y[y.name].fit_transform(y))

    def get_sensitive_attributes(self) :
        return self._sensitive_attributes

    def get_data(self, readable=False) :
        """
        Method to get the data
        :param readable: Boolean flag to set if the returned data is human-readable
        :return: Tuple of data features and targets
        """
        if readable :
            return self._data_x_readable, self._data_y_readable
        return self._data_x, self._data_y

    # this as sort of useless. The init function ensures readable and unreadable forms are available as private vars,
    # accessible by get_data - skv2109
    def make_data_readable(self, x_df, y_df=None) :
        """
        Method to convert encoded data to their human readable form
        :param x_df: The encoded feature dataframe
        :param y_df: Optional dataframe with targets
        :return: Decoded features and targets
        """
        if self.type == 'COMPAS' :
            x_df.fillna('', inplace=True)
        x_readable = x_df.loc[:, ~self._data_x_readable.columns.duplicated()]
        x_readable = x_readable.apply(
            lambda x : self._encoder_dict_x[x.name].inverse_transform(x))
        if y_df is None:
            return x_readable
        y_readable = y_df.apply(lambda y: self._encoder_dict_y[y.name].inverse_transform(y))
        return x_readable, y_readable

    def encode_data(self, x_df, y_df=None):
        """
        Method to encode data to be processed by a computational model
        :param x_df: The human readable feature dataframe
        :param y_df: Optional dataframe with human readable targets
        :return: Encoded features (and targets)
        """
        # if self.type == 'COMPAS':
        # x_df.fillna('', inplace=True)
        x_encoded = x_df.loc[:, ~self._data_x_readable.columns.duplicated()]
        x_encoded = x_encoded.apply(
            lambda x : self._encoder_dict_x[x.name].transform(x))
        if y_df is None :
            return x_encoded
        y_encoded = y_df.apply(lambda y : self._encoder_dict_y[y.name].transform(y))
        return x_encoded, y_encoded

if __name__ == '__main__' :
    dataset = Dataset('config_compas.json')
    x, y = dataset.get_data(readable=True)


import pickle
import platform
import subprocess

from django.conf import settings
from django.core.files import File

def get_system_config():
    sysconfig = {}

    os = platform.system()
    if os == "Linux":
        command = "cat /proc/cpuinfo"
        cpu_info = subprocess.check_output(command, shell=True).strip()

        if not type(cpu_info) == str:
            cpu_info = cpu_info.decode()

        clock_speed = cpu_info.split('@')[1].split(' ')[1].split('\n')[0]
        sysconfig['clock_speed'] = clock_speed

        cores = cpu_info.split('\n')[12].split(':')[1].strip()
        sysconfig['cpu'] = cores

        command = "cat /proc/meminfo"
        ram_info = subprocess.check_output(command, shell=True).strip()

        if not type(ram_info) == str:
            ram_info = ram_info.decode()

        ram_size = int(ram_info.split('\n')[0].split(':')[1].strip(
        ).split(' ')[0]) / 1024.0**2
        sysconfig['ram'] = ram_size

        sysconfig['architecture'] = platform.architecture()[0]

        return sysconfig

def save_encrypted_file(algorithm, filename, content):
    '''
    saves the encrypted file to database.
    '''

    filename = settings.MEDIA_ROOT + '/files/' + algorithm + "_" + filename
    with open(filename, 'wb+') as f:
        encrypted_file = File(f)

        if isinstance(content, list):
            pickle.dump(content, encrypted_file)
        else:
            encrypted_file.write(content)

    return filename


#! /usr/bin/env python

import re
from pprint import pprint

with open("input.txt", 'r') as f:
	content = f.readlines()

food_items = [c.strip() for c in content]
ingredients_allergens_re = re.compile(r'''([\ a-z]+)\ \(contains\ ([\ a-z\,]+)\)''')

allergens_map = {}
ingredients_list = []

for line in food_items:

	ingredients, allergens = ingredients_allergens_re.match(line).groups()
	ingredients = set(ingredients.split(" "))
	allergens = set(allergens.split(", "))

	for allergen in allergens:
		if allergen not in allergens_map:
			allergens_map[allergen] = []
		allergens_map[allergen].append(ingredients)

	ingredients_list.append(list(ingredients))

for allergen in allergens_map:
	common_ingredients = allergens_map[allergen][0]
	for l in allergens_map[allergen][1:]:
		common_ingredients = common_ingredients.intersection(l)
	allergens_map[allergen] = common_ingredients

all_allergen_items = set([v for f in list(allergens_map.values()) for v in f])
non_allergen_count = 0

for line in ingredients_list:
	for ing in line:
		if ing not in all_allergen_items:
			non_allergen_count += 1

print(non_allergen_count)


"""
adapted from https://github.com/FeliMe/feature-autoencoder
"""
from argparse import ArgumentParser
from collections import defaultdict
from time import time
import numpy as np
import torch
from UPD_study.models.FAE.FAEmodel import FeatureReconstructor
from torch import Tensor
from torchinfo import summary
from UPD_study.utilities.common_config import common_config
from UPD_study.utilities.utils import (save_model, test_inference_speed, seed_everything,
                                       load_data, load_pretrained,
                                       misc_settings, log, load_model)
from UPD_study.utilities.evaluate import evaluate
from typing import Tuple
import pathlib

""""""""""""""""""""""""""""""""""" Config """""""""""""""""""""""""""""""""""

def get_config():
    parser = ArgumentParser()
    parser = common_config(parser)

    # Training Hyperparameters

    parser.add_argument('--lr', type=float, default=2e-4, help='Learning rate')
    parser.add_argument('--weight_decay', type=float, default=0.0,
                        help='Weight decay')
    parser.add_argument('--max_steps', type=int, default=10000,
                        help='Number of training steps')
    parser.add_argument('--batch_size', type=int, default=32, help='Batch size')

    # Model Hyperparameters
    parser.add_argument('--hidden_dims', type=int, nargs='+',
                        default=[100, 150, 200, 300],
                        help='Autoencoder hidden dimensions')
    parser.add_argument('--dropout', type=float, default=0.1, help='Dropout rate')
    parser.add_argument('--loss_fn', type=str, default='ssim', help='loss function',
                        choices=['mse', 'ssim'])
    parser.add_argument('--extractor_cnn_layers', type=str, nargs='+',
                        default=['layer0', 'layer1', 'layer2'])
    parser.add_argument('--keep_feature_prop', type=float, default=1.0,
                        help='Proportion of ResNet features to keep')

    return parser.parse_args()

# set initial script settings
config = get_config()
config.method = 'FAE'
config.model_dir_path = pathlib.Path(__file__).parents[0]
config.center = True
misc_settings(config)

""""""""""""""""""""""""""""""""" Load data """""""""""""""""""""""""""""""""

# specific seed for creating the dataloader
seed_everything(42)

train_loader, val_loader, big_testloader, small_testloader = load_data(config)

""""""""""""""""""""""""""""""""" Init model """""""""""""""""""""""""""""""""
# Reproducibility
seed_everything(config.seed)

print("Initializing model...")
model = FeatureReconstructor(config).to(config.device)

# load CCD pretrained backbone
if config.load_pretrained:
    config.arch = 'resnet18'
    model.extractor.backbone = load_pretrained(model.extractor.backbone, config)

# Init optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=config.lr,
                             weight_decay=config.weight_decay)

# Load saved model to evaluate
if config.eval:
    model.load_state_dict(load_model(config))
    print('Saved model loaded.')

# Space Benchmark
if config.space_benchmark:
    a = summary(model, (16, 3, 128, 128), verbose=0)
    params = a.total_params
    print('Number of Million parameters: ', params / 1e06)
    exit(0)

""""""""""""""""""""""""""""""""""" Training """""""""""""""""""""""""""""""""""

def train_step(input) -> dict:
    """
    Training step
    """
    model.train()
    optimizer.zero_grad()
    loss_dict = model.loss(input)
    loss = loss_dict['rec_loss']
    loss.backward()
    optimizer.step()
    return loss_dict

def val_step(input, test_samples: bool = False) -> Tuple[dict, Tensor]:
    """
    Validation step on validation or evaluation (test samples == True) validation set.
    """
    model.eval()
    with torch.no_grad():
        loss_dict = model.loss(input)
        anomaly_map = model.predict_anomaly(input)

    # for MRI apply brainmask
    if config.modality == 'MRI':
        mask = torch.stack([inp > inp.min() for inp in input])
        anomaly_map *= mask
        anomaly_score = torch.tensor([map[inp > inp.min()].max() for map, inp in zip(anomaly_map, input)])

    elif config.modality == 'RF':
        anomaly_score = torch.tensor([map.max() for map in anomaly_map])

    elif config.modality == 'CXR':
        anomaly_score = torch.tensor([map.mean() for map in anomaly_map])

    if test_samples:
        return anomaly_map, anomaly_score
    else:
        return loss_dict, anomaly_map, anomaly_score

def train():
    """
    Main training logic
    """

    print(f'Starting training {config.name}...')
    train_losses = defaultdict(list)
    t_start = time()

    while True:
        for input in train_loader:
            config.step += 1
            input = input.to(config.device)
            loss_dict = train_step(input)

            # Add to losses
            for k, v in loss_dict.items():
                train_losses[k].append(v.item())

            if config.step % config.log_frequency == 0:
                # Print training loss
                log_msg = " - ".join([f'{k}: {np.mean(v):.4f}' for k,
                                      v in train_losses.items()])
                log_msg = f"Iteration {config.step} - " + log_msg
                log_msg += f" - time: {time() - t_start:.2f}s"
                print(log_msg)

                # Log to wandb
                log(
                    {f'train/{k}': np.mean(v) for k, v in train_losses.items()},
                    config
                )

                # Reset
                train_losses = defaultdict(list)

            if config.step % config.val_frequency == 0:
                validate(val_loader, config)

            if config.step % config.anom_val_frequency == 0:
                evaluate(config, small_testloader, val_step)

            if config.step >= config.max_steps:
                save_model(model, config)
                print(f'Reached {config.max_steps} iterations. Finished training {config.name}.')
                return

def validate(val_loader, config) -> None:
    """
    Validation logic on normal validation set.
    """
    val_losses = defaultdict(list)
    i_val_step = 0

    for input in val_loader:

        i_val_step += 1

        input = input.to(config.device)

        loss_dict, anomaly_map, anomaly_score = val_step(input)

        for k, v in loss_dict.items():
            val_losses[k].append(v.item())

        if i_val_step >= config.val_steps:
            break

    # Print validation results
    log_msg = 'Validation losses on normal samples: '
    log_msg += " - ".join([f'{k}: {np.mean(v):.4f}' for k, v in val_losses.items()])
    print(log_msg)

    # Log to wandb
    log(
        {f'val/{k}': np.mean(v)
         for k, v in val_losses.items()},
        config
    )

    # log images and residuals

    log({
        'val/input': input,
        'val/res': anomaly_map,
    }, config)

    return np.mean(val_losses['rec_loss'])

if __name__ == '__main__':
    if config.speed_benchmark:
        test_inference_speed(val_step)
        exit(0)
    if config.eval:
        print(f'Evaluating {config.name}...')
        evaluate(config, big_testloader, val_step)
    else:
        train()


import matplotlib.pyplot as plt
import argparse
import logging  # 디버그할 때 로그찍어주는 모듈
import cv2  # opencv 모듈
import numpy as np
import imutils
import math
import time
import sys
from ImageProcessing_py import utils
from ImageProcessing_py.detection.Detection import Detection

if __name__ == '__main__':  # 플러그
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('video_path', type=str, help="paths to one or more images or image directories")
    parser.add_argument('-b', '--debug', dest='debug', action='store_true', help='enable debug logging')
    parser.add_argument('-q', '--quiet', dest='quiet', action='store_true', help='disable all logging')
    parser.add_argument('-d', '--display', dest='display', action='store_true', help="display result")
    parser.add_argument('-s', '--save', dest='save', action='store_true', help="save result to file")
    parser.add_argument("--save_path", dest='save_path', default="stitched.png", type=str, help="path to save result")
    parser.add_argument('-k', '--knn', dest='knn', default=2, type=int, help="Knn cluster value")
    parser.add_argument('-l', '--lowe', dest='lowe', default=0.7, type=float, help='acceptable distance between points')
    parser.add_argument('-m', '--min', dest='min_correspondence', default=10, type=int, help='min correspondences')
    args = parser.parse_args()

    if args.debug:  # 예외처리
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger("main")

    logging.info("beginning sequential matching")

    if utils.helpers.is_cv2():  # opencv 버전 별
         sift = cv2.SIFT()
    elif utils.helpers.is_cv3():
         sift = cv2.xfeatures2d.SIFT_create()
    elif utils.helpers.is_cv4():
         sift = cv2.SIFT_create()
    else:
         raise RuntimeError("error! unknown version of python!")

    flann = cv2.FlannBasedMatcher({'algorithm': 1, 'trees': 5}, {'checks': 50})

    cap = cv2.VideoCapture(args.video_path)
    beforeResult = cv2.imread("res/sam/0520sam/result10-1.jpg")
    beforeResult_gray = cv2.cvtColor(beforeResult, cv2.COLOR_BGR2GRAY)
    length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    print("length : ", length)
    print("width : ", width)
    print("height : ", height)
    print("fps : ", fps)
    i = 0
    resultT = None
    features1 = None
    h, w, f = 404, 720, 950
    K = np.array([[f, 0, w / 2], [0, f, h / 2], [0, 0, 1]], dtype=np.float32)
    angles = math.pi / 180
    theta = [angles * 0, angles * 45, angles * 45]
    R = utils.helpers.eulerAnglesToRotationMatrix(theta)
    #print("R : " + str(R))
    #video = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'MP4V'), 10, (beforeResult.shape[1],beforeResult.shape[0]))
    tm = cv2.TickMeter()

    object_detector = Detection()
    i = 0
    meanTime1 = 0
    meanTime2 = 0
    meanTime3 = 0
    meanTime4 = 0
    j = 0
    while True:

        ret, frame = cap.read()
        if i % 3 != 0:
            i = i + 1
            continue
        i = i + 1

        if not ret:  # 제대로 못읽었을 경우
            break
        else:  # 제대로 읽었을 경우 그레이로 바꾸기
            j += 1

            if frame.shape[1] > 720:
                frame = imutils.resize(frame, width=720)

            tm.reset()
            tm.start()
            t1 = time.time()

            warper = cv2.PyRotationWarper('spherical', float(f))
            corner, frame = warper.warp(frame, K, R, cv2.INTER_LINEAR, cv2.BORDER_CONSTANT)

            tm.stop()
            ms = tm.getTimeSec()  # 밀리 초 단위 시간을 받아옴
            meanTime1 += ms
            print('spherical warp mean time : {}s.'.format(meanTime1 / j))

            frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            tm.reset()
            tm.start()
            t1 = time.time()
            #detection
            frame = object_detector.detectObject(frame)
            tm.stop()
            ms = tm.getTimeSec()  # 밀리 초 단위 시간을 받아옴
            meanTime2 += ms
            print('detection mean time : {}s.'.format(meanTime2 / j))

            tm.reset()
            tm.start()
            t1 = time.time()

            features0 = sift.detectAndCompute(frame_gray, None)
            if features1 is None:
                features1 = sift.detectAndCompute(beforeResult_gray, None)

            matches_src, matches_dst, n_matches = utils.compute_matches(
                features0, features1, flann, knn=args.knn)

            tm.stop()
            ms = tm.getTimeSec()  # 밀리 초 단위 시간을 받아옴
            meanTime3 += ms
            print('feature mean time : {}s.'.format(meanTime3 / j))

            if n_matches < args.min_correspondence:
                logger.error("error! too few correspondences")
                continue

            tm.reset()
            tm.start()
            t1 = time.time()
            H, mask = cv2.findHomography(matches_src, matches_dst, cv2.RANSAC, 5.0)

            if resultT is None:
                h0, w0 = beforeResult.shape[0:2]
                resultT = np.zeros((h0, w0, 3), np.uint8)
            resultT, contours = utils.combine_images(beforeResult, frame, H, resultT)
            tm.stop()
            ms = tm.getTimeSec()  # 밀리 초 단위 시간을 받아옴
            meanTime4 += ms
            print('mean time : {}s.'.format(meanTime4 / j))

            img = utils.display_red("result", resultT, contours)
            cv2.waitKey(1)
            #video.write(img)

    logger.info('{0} is completed'.format(args.video_path))
    cap.release()
    #video.release()
    cv2.destroyAllWindows()
    if args.save:
        utils.helpers.save_image(args.video_path, resultT)


# https://leetcode.com/problems/largest-plus-sign/
# tags: #array, #dp
#
# Great explanation at:
# https://leetcode.com/problems/largest-plus-sign/discuss/1453636/Intuitiveor-Explained-with-image-or-Short-and-Clean-or-C%2B%2B
#
# Another explanation:
# https://leetcode.com/problems/largest-plus-sign/discuss/113314/JavaC++Python-O(N2)-solution-using-only-one-grid-matrix/114381
#
# For each position (i, j) of the grid matrix, we try to extend in each of the four directions (left, right, up, down)
# as long as possible:
# 1. For the left direction, i is a row index while j is a column index.
# For each row, j goes from left to right (increasing).
# 2. For the right direction, i is a row index while k is a column index.
# For each row, k goes from right to left (decreasing).
# 3. For the up direction, i is a column index while j is a row index.
# For each column, j goes from top to bottom (increasing).
# 4. For the down direction, i is a column index while k is a row index.
# For each column, k goes from bottom to top (decreasing).
#
# Time Complexity: O(n^2), Space complexity: O(n^2)
from typing import List

class Solution:
    def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:
        matrix = [[n] * n for _ in range(n)]
        for mine in mines:
            matrix[mine[0]][mine[1]] = 0

        for i in range(n):
            left, right, top, bottom = 0, 0, 0, 0

            for j, k in zip(range(n), reversed(range(n))):
                left = left + 1 if matrix[i][j] > 0 else 0
                if left < matrix[i][j]:
                    matrix[i][j] = left

                right = right + 1 if matrix[i][k] > 0 else 0
                if right < matrix[i][k]:
                    matrix[i][k] = right

                top = top + 1 if matrix[j][i] > 0 else 0
                if top < matrix[j][i]:
                    matrix[j][i] = top

                bottom = bottom + 1 if matrix[k][i] > 0 else 0
                if bottom < matrix[k][i]:
                    matrix[k][i] = bottom

        result = 0
        for i in range(n):
            for j in range(n):
                result = max(result, matrix[i][j])

        return result

if __name__ == "__main__":
    sol = Solution()
    print(sol.orderOfLargestPlusSign(n=5, mines=[[4, 2]]))  # 2


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.read_csv("Backend/table.csv")
# data.head(10)
# data = d.copy()

# data.columns
# d.head(5)
l = []
for i in range(0, len(data)):
    # d["venue"][i] = list(' '.split(d["venue"][i]))[-2]
    l.append(data["venue"][i].split()[-1])

data["location"] = l

data = data.to_csv("sample.csv", index=False)

print(data)

# data.venue.value_counts(dropna=False).sort_index().plot(kind='barh')
# plt.show()


#!/usr/bin/env python3

import sys
import logging
import PIL.Image
import PIL.ImageDraw
import PIL.ImageTk
# GUI
import tkinter as tk
import tkinter.font as tkFont
# OSM
import smopy
# GPS
import pynmea2

class GPSMap(tk.Frame):
    zoom = 13
    font = None
    spdLabel = None
    mapLabel = None
    lastGpsPosition = None
    fg = "black"
    bg = "white"
    defaultImagename = None
    defaultImage = None
    postition = None

    def __init__(self, master=None, position=None, font=None, bg=None, fg=None, defaultImagename=None, zoom=13):
        # super().__init__()
        self.font = font
        if fg is not None:
            self.fg = fg
        if bg is not None:
            self.bg = bg
        self.zoom = zoom
        self.defaultImagename = defaultImagename
        self.position = position
        tk.Frame.__init__(self, master, bg=self.bg)

        self.initUI()
        self.pack()
        if self.position:
            self.updateGUI(position=self.position)

    def initUI(self):
        try:
            if self.defaultImagename:
                image = PIL.Image.open(self.defaultImagename)
                self.defaultImage = PIL.ImageTk.PhotoImage(image)

            if self.font is None:
                self.font = tkFont.Font(family="Lucida Grande", size=20)

            positionFrame = tk.Frame(master=self, bg=self.bg)  # , bg='red')
            positionFrame.pack(side=tk.LEFT)

            frameValue = tk.Frame(positionFrame, bg=self.bg)
            frameValue.pack(side=tk.TOP, fill=tk.X)
            label = tk.Label(frameValue, text="Time:", font=self.font, fg=self.fg, bg=self.bg)
            label.pack(side=tk.LEFT)
            self.timeLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
            self.timeLabel.pack(side=tk.RIGHT)

            frameValue = tk.Frame(positionFrame, bg=self.bg)
            frameValue.pack(side=tk.TOP, fill=tk.X)
            label = tk.Label(frameValue, text="Lat:", font=self.font, fg=self.fg, bg=self.bg)
            label.pack(side=tk.LEFT)
            self.latLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
            self.latLabel.pack(side=tk.RIGHT)

            frameValue = tk.Frame(positionFrame, bg=self.bg)
            frameValue.pack(side=tk.TOP, fill=tk.X)
            label = tk.Label(frameValue, text="Lon:", font=self.font, fg=self.fg, bg=self.bg)
            label.pack(side=tk.LEFT)
            self.lonLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
            self.lonLabel.pack(side=tk.RIGHT)

            frameValue = tk.Frame(positionFrame, bg=self.bg)
            frameValue.pack(side=tk.TOP, fill=tk.X)
            label = tk.Label(frameValue, text="Alt:", font=self.font, fg=self.fg, bg=self.bg)
            label.pack(side=tk.LEFT)
            self.altLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
            self.altLabel.pack(side=tk.RIGHT)

            frameValue = tk.Frame(positionFrame, bg=self.bg)
            frameValue.pack(side=tk.TOP, fill=tk.X)
            label = tk.Label(frameValue, text="Sat:", font=self.font, fg=self.fg, bg=self.bg)
            label.pack(side=tk.LEFT)
            self.satLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
            self.satLabel.pack(side=tk.RIGHT)

            # frameValue = tk.Frame( positionFrame )
            # frameValue.pack( side=tk.TOP, fill=tk.X )
            # label = tk.Label( frameValue, text = "Speed:", font=self.font )
            # label.pack( side=tk.LEFT )
            # self.spdLabel = tk.Label( frameValue, text="", font=self.font, anchor=tk.W )
            # self.spdLabel.pack( side=tk.RIGHT )

            self.mapLabel = tk.Label(self, image=self.defaultImage, fg=self.fg, bg=self.bg)
            self.mapLabel.pack(side=tk.LEFT)

            buttonFrame = tk.Frame(master=self, bg=self.bg)  # , bg='cyan')
            buttonFrame.pack(side=tk.LEFT)

            self.plusButton = tk.Button(buttonFrame, text="+", command=self.zoomIn, font=self.font, fg=self.fg, bg=self.bg)
            self.plusButton.pack(side=tk.TOP, fill=tk.X)

            self.zoomLabel = tk.Label(buttonFrame, text=str(self.zoom), font=self.font, fg=self.fg, bg=self.bg)
            self.zoomLabel.pack(side=tk.TOP, fill=tk.X)

            self.minusButton = tk.Button(buttonFrame, text="-", command=self.zoomOut, font=self.font, fg=self.fg, bg=self.bg)
            self.minusButton.pack(side=tk.TOP, fill=tk.X)

        except:
            e = sys.exc_info()
            logging.error(e, exc_info=True)
        logging.info("GUI created")

    def updateGUI(self, data=None, position=None, zoom=None):
        try:
            if self.mapLabel:
                if zoom:
                    self.zoom = zoom
                self.zoomLabel['text'] = str(self.zoom)
                if data is not None and data.gpsPosition is not None:
                    self.lastGpsPosition = data.gpsPosition
                if position is not None:
                    self.lastGpsPosition = position

                if self.lastGpsPosition is not None:
                    lat = self.lastGpsPosition.latitude
                    lon = self.lastGpsPosition.longitude

                    self.timeLabel['text'] = self.lastGpsPosition.timestamp.strftime('%H:%M:%S')
                    if lat is not None:
                        self.latLabel['text'] = "{:.4f}".format(lat)
                    if lon is not None:
                        self.lonLabel['text'] = "{:.4f}".format(lon)
                    if self.lastGpsPosition.altitude is not None:
                        self.altLabel['text'] = "{:.1f}".format(self.lastGpsPosition.altitude)
                    if self.lastGpsPosition.num_sats is not None:
                        self.satLabel['text'] = "{}".format(self.lastGpsPosition.num_sats)
                    if self.spdLabel is not None:
                        self.spdLabel['text'] = "{}".format(self.lastGpsPosition.geo_sep)

                    s = 0.000001
                    map = smopy.Map((lat - s, lon - s, lat + s, lon + s), z=self.zoom)
                    # show position
                    x, y = map.to_pixels(lat, lon)
                    # logging.info( "pos: " + str(x) + "/" + str(y) )
                    image = map.img
                    draw = PIL.ImageDraw.Draw(image)
                    r = 5
                    shape = [(x - r, y - r), (x + r, y + r)]
                    draw.ellipse(shape, fill="red", outline="black")
                    del draw

                    # logging.info( "size: " + str(image.size) )
                    image = image.resize((256, 256))
                    self.img = PIL.ImageTk.PhotoImage(image)
                    self.mapLabel['image'] = self.img
                    self.mapLabel.pack()
                    logging.info("map updated")
                else:
                    self.mapLabel['image'] = self.defaultImage
                    self.mapLabel.pack()
        except:
            e = sys.exc_info()
            logging.error(e, exc_info=True)
        logging.debug("GUI updated")

    def zoomIn(self):
        self.zoom += 1
        if(self.zoom > 17):
            self.zoom = 17
        logging.info("zoom: " + str(self.zoom))
        self.updateGUI()

    def zoomOut(self):
        self.zoom -= 1
        if(self.zoom < 0):
            self.zoom = 0
        logging.info("zoom: " + str(self.zoom))
        self.updateGUI()

def main():
    logging.basicConfig(level=logging.INFO, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s')

    root = tk.Tk()
    app = GPSMap(master=root, defaultImagename="../pic_free/karte.png", zoom=5)
    gpsPosition = pynmea2.parse("$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D")
    app.updateGUI(position=gpsPosition)
    root.mainloop()

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Gives functions related to LaTeX generation.

Created on Fri Apr 16 18:43:50 2021
@author: Joachim Favre & Alberts Reisons
"""
from datetime import datetime
import os

MONTHS = ["January", "February", "March", "April", "May", "June", "July",
          "August", "September", "October", "November", "December"]

RESULT_DIRECTORY = "result"

def format_day(day_number):
    """
    Adds the good extension to a number to make the 'day' part of a date.
    """
    result = str(day_number)
    if result[-1] == '1' and day_number != 11:
        return result + "st"
    if result[-1] == '2' and day_number != 12:
        return result + "nd"
    if result[-1] == '3' and day_number != 13:
        return result + "rd"
    return result + "th"

def get_date():
    """
    Returns the current date, well formatted.
    """
    current_time = datetime.now()
    result = (format_day(current_time.day) + " " + MONTHS[current_time.month-1]
              + " " + str(current_time.year))
    return result

def concatenate_lines(lines):
    """
    Takes a list of lines (strings) in parameters and returns the full
    concatenation.
    Differs from full_concatenate(str_list) from text_gestion.py since it adds
    a carriage return at the end of each line. This function is thus more used
    for LaTeX code generation.
    """
    result = ""
    for line in lines:
        result += line + "\n"
    return result

def write_as_list(expression_list):
    """
    Takes a list of mathematical expressions and write it well formated (as
    "elem1, elem2, elem3, ..., elemn and elemem" (mostly for the comas and
    the "and" at the end)).
    """
    if len(expression_list) == 0:
        return ""
    result = "${}$"
    if len(expression_list) > 1:
        result += ", ${}$"*(len(expression_list) - 2)
        result += " and ${}$"
    result = result.format(*expression_list)
    return result

def convert_2_latex(text):
    """
    Takes some text that the user may have given and that is used by the
    program when verifying the proof, and replaces the right things by
    LaTeX commands. For example, '(' becomes '\\left('.
    """
    result = ""
    closing_bracket_in = []
    for index, character in enumerate(text):
        if character == "(":
            for index_bckt, how_many_left in enumerate(closing_bracket_in):
                closing_bracket_in[index_bckt] = how_many_left + 1
            result += "("
        elif character == ")":
            result += ")"
            for index_bckt, how_many_left in enumerate(closing_bracket_in):
                how_many_left -= 1
                closing_bracket_in[index_bckt] = how_many_left
                if how_many_left == 0:
                    closing_bracket_in.remove(0)  # only one can be at 0
                    result += "}"
        elif character == "*":
            try:
                int(text[index+1])
                result += "\\cdot"
            except ValueError:
                pass
        elif character == '^' and text[index+1] == "(":
            result += '^{'
            closing_bracket_in.append(0)
        else:
            result += character

    # result = result.replace("*", "\\cdot ")
    # result = result.replace("*", "")
    result = result.replace("(", "\\left(")
    result = result.replace(")", "\\right)")
    # result = result.replace("**", "^")

    return result

def init_latex_code(title, author):
    """
    Returns the header of a LaTeX file.
    """
    lines = [r"\documentclass[a4paper]{article}",
             r"\usepackage[T1]{fontenc}",
             r"\usepackage[utf8]{inputenc}",
             r"\usepackage[left=2.5cm, right=2.5cm, top=2.5cm, "
             "bottom=2.5cm]{geometry}",
             r"\usepackage[breaklinks, hidelinks]{hyperref}",
             r"\usepackage{xcolor}",
             r"\usepackage{titlesec}",
             r"\usepackage{tocloft}",
             r"\usepackage{fancyhdr}",
             r"\usepackage{ifthen}",
             "",
             r"\titleformat*{\section}{\large\bfseries}",
             r"\titleformat*{\subsection}{\normalsize\bfseries}",
             "",
             r"\setcounter{tocdepth}{1}",
             r"\renewcommand{\cftsecfont}{\normalfont}",
             r"\renewcommand{\cftsecpagefont}{\normalfont}",
             r"\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}",
             r"\setlength{\cftsecindent}{0.5cm}",
             r"\let\oldpart\part",
             r"\newcommand{\parttitle}{}",
             r"\renewcommand{\part}[1]{\oldpart{#1}"
             + r"\renewcommand{\parttitle}{#1}}",
             "",
             r"\pagestyle{fancy}",
             r"\lhead{\ifthenelse{\equal{\thepart}{}}{Contents}"
             + r"{Part \thepart~---~\parttitle}}",
             r"\rhead{" + author + "}",
             "",
             r"\title{" + title + "}",
             r"\author{" + author + "}",
             r"\date{" + get_date() + "}",
             "",
             r"\begin{document}",
             r"\maketitle",
             r"\tableofcontents",
             r"\newpage",
             ""]

    return concatenate_lines(lines)

def end_latex_code():
    """
    Returns the last necessary lines of a LaTeX file.
    """
    lines = ["",
             r"\end{document}"]
    return concatenate_lines(lines)

def write_to_file(latex_code, file_name, no_ending=False):
    """
    Writes some LaTeX code to a file at ./RESULT_DIRECTORY/{file_name} and
    compiles it. TThe no_ending parameter can be used to tell
    this function to add an ending to the latex_code, using end_latex_code().
    """
    if no_ending:
        latex_code += end_latex_code()

    result_path = RESULT_DIRECTORY + '/' + file_name

    with open(result_path + '.tex', 'w', encoding='utf-8') as file:
        file.write(latex_code)

    compil_cmd = ("pdflatex -output-directory "
                  + RESULT_DIRECTORY + " " + result_path + ".tex")

    print("Compiling the first time...")
    if os.system(compil_cmd) != 0:
        print("There was a problem during the first LaTeX compilation. Do "
              "not hesitate to take a look to the .log file to see what "
              "wnet wrong. You may have kept the pdf document opened, for "
              "example.")
        return

    print("Compiling the second time...")
    if os.system(compil_cmd) != 0:
        print("There was a problem during the second LaTeX compilation. Do "
              "not hesitate to take a look to the .log file to see what "
              "went wrong.")
        return


#Step 1~3
from tkinter import*
from tkinter.filedialog import*
import os

def saveFile():
    f=asksaveasfile(mode="w",defaultextension=".txt") #defaultextension;확장자
    if f is None:
        return
    ts=str(ta.get(1.0,END))
    f.write(ts)
    f.close()

top=Tk()
top.title("메모장")
top.geometry("400x400")

ta=Text(top)
top.grid_rowconfigure(0,weight=1)
top.grid_columnconfigure(0,weight=1)
ta.grid(sticky=N+E+S+W)

file=None

mb=Menu(top) #Menu라는 top이라는 윈도우에 포함
fi=Menu(mb)
mb.add_cascade(label="파일",menu=fi)
fi.add_command(label="저장",command=saveFile)

top.config(menu=mb)

top.mainloop()


import math
import os

import cv2
import numpy as np
import sympy as smpy

def compute(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)

    (minVal, maxVal, minLoc, (x, y)) = cv2.minMaxLoc(image)

    return x, y, maxVal

class Point:
    def __init__(self, index):
        self.index = index

        self.image_0 = cv2.imread(f'images/0/{index}.png')
        self.image_90 = cv2.imread(f'images/90/{index}.png')
        self.image_180 = cv2.imread(f'images/180/{index}.png')
        self.image_270 = cv2.imread(f'images/270/{index}.png')

        self.x = None
        self.y = None
        self.z = None

        self.image_0_x = None
        self.image_0_y = None
        self.image_0_weight = None

        self.image_90_x = None
        self.image_90_y = None
        self.image_90_weight = None

        self.image_180_x = None
        self.image_180_y = None
        self.image_180_weight = None

        self.image_270_x = None
        self.image_270_y = None
        self.image_270_weight = None

        self.dist_to_prev = None
        self.dist_to_next = None

    def compute_all(self):
        self.set_coordinates(0, *compute(self.image_0))
        self.set_coordinates(90, *compute(self.image_90))
        self.set_coordinates(180, *compute(self.image_180))
        self.set_coordinates(270, *compute(self.image_270))

    def set_coordinates(self, angle, x, y, weight):
        setattr(self, f"image_{angle}_x", x)
        setattr(self, f"image_{angle}_y", y)
        setattr(self, f"image_{angle}_weight", weight)

    def adjust_to_bounds(self, min_x, min_y):
        for angle in [0, 90, 180, 270]:
            if getattr(self, f"image_{angle}_x") is not None:
                x = getattr(self, f"image_{angle}_x")
                y = getattr(self, f"image_{angle}_y")

                x = x - min_x
                y = y - min_y

                self.set_coordinates(angle, x, y, getattr(self, f"image_{angle}_weight"))

    def flip_opposites(self, min_x, max_x):
        for angle in [180, 270]:
            if getattr(self, f"image_{angle}_x") is not None:
                x = getattr(self, f"image_{angle}_x")
                y = getattr(self, f"image_{angle}_y")

                x = -x + max_x

                self.set_coordinates(angle, x, y, getattr(self, f"image_{angle}_weight"))

    def compute_3d_estimate(self, angle_1, angle_2):
        x_1 = getattr(self, f"image_{angle_1}_x")
        y_1 = getattr(self, f"image_{angle_1}_y")

        x_2 = getattr(self, f"image_{angle_2}_x")
        y_2 = getattr(self, f"image_{angle_2}_y")

        if x_1 is None or y_1 is None or x_2 is None or y_2 is None:
            return None, None, None

        # When seeing the point from it's side (angle_2), the x position is the depth (z) and the y position is the height
        x = x_1
        y = (y_1 + y_2) / 2
        z = x_2

        return x, y, z

    def compute_3d(self):
        estimate_1 = self.compute_3d_estimate(0, 90)
        estimate_2 = self.compute_3d_estimate(180, 270)

        if estimate_1[0] is None or estimate_1[1] is None or estimate_1[2] is None:
            return estimate_2

        if estimate_2[0] is None or estimate_2[1] is None or estimate_2[2] is None:
            return estimate_1

        if estimate_1[0] is None or estimate_1[1] is None or estimate_1[2] is None and estimate_2[0] is None or \
                estimate_2[1] is None or estimate_2[2] is None:
            return None, None, None

        x = (estimate_1[0] + estimate_2[0]) / 2
        y = (estimate_1[1] + estimate_2[1]) / 2
        z = (estimate_1[2] + estimate_2[2]) / 2

        return x, y, z

    def set_3d(self):
        x, y, z = self.compute_3d()
        self.x = x
        self.y = y
        self.z = z


from unittest import result
import ñ

while True:
    text = input("ñ >> ")
    if text.strip() == "": continue
    res, error = ñ.exe("<input>",text)

    if error: print(error.como_str())
    elif res:
        if len(res.elementos) == 1:
            print(repr(res.elementos[0]))
        else:
            print(repr(res))


import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.variable import Variable

from .resnet import *
from .vgg import *
from .densenet import *
from .funcs import *
from .Network import *

import sys
import numpy as np

dim_dict = {
    'densenet169': [64, 128, 256, 640, 1664],
    'vgg16': [64, 128, 256, 512, 512],
    'mobilenet2': [32, 24, 32, 64, 1280],
    'resnet101': [64, 256, 512, 1024, 2048]
}

class Progressive_Unet(nn.Module):
    def __init__(self, ch_en=32, scale=5, base='resnet50', prev_layer=None):
        super(Progressive_Unet, self).__init__()

        self.scale = scale
        self.base = base
        self.ch_en = ch_en
        self.init_model = Initial_Layer()

        self.decoder1_1 = SkipUpScale(self.ch_en * 64, self.ch_en * 16, skip_in = self.ch_en * 16)
        self.decoder1_2 = SkipUpScale(self.ch_en * 16, self.ch_en * 8, skip_in = self.ch_en * 8)
        self.decoder1_3 = SkipUpScale(self.ch_en * 8, self.ch_en * 4, skip_in = self.ch_en * 4)
        self.decoder1_4 = SkipUpScale(self.ch_en * 4, self.ch_en * 2, skip_in = self.ch_en * 2)
        self.decoder1_5 = SkipUpScale(self.ch_en * 2, self.ch_en, skip_in = self.ch_en)
        self.out1_1 = nn.Conv2d(self.ch_en * 16, 1, kernel_size=1, padding=0)
        self.out1_2 = nn.Conv2d(self.ch_en * 8, 1, kernel_size=1, padding=0)
        self.out1_3 = nn.Conv2d(self.ch_en * 4, 1, kernel_size=1, padding=0)
        self.out1_4 = nn.Conv2d(self.ch_en * 2, 1, kernel_size=1, padding=0)
        self.out1_5 = nn.Conv2d(self.ch_en, 1, kernel_size=1, padding=0)

        self.decoder2_1 = SkipUpScale(self.ch_en * 64, self.ch_en * 16, skip_in = self.ch_en * 16)
        self.decoder2_2 = SkipUpScale(self.ch_en * 16, self.ch_en * 8, skip_in = self.ch_en * 8)
        self.decoder2_3 = SkipUpScale(self.ch_en * 8, self.ch_en * 4, skip_in = self.ch_en * 4)
        self.decoder2_4 = SkipUpScale(self.ch_en * 4, self.ch_en * 2, skip_in = self.ch_en * 2)
        self.decoder2_5 = SkipUpScale(self.ch_en * 2, self.ch_en, skip_in = self.ch_en)
        self.out2_1 = nn.Conv2d(self.ch_en * 16, 1, kernel_size=1, padding=0)
        self.out2_2 = nn.Conv2d(self.ch_en * 8, 1, kernel_size=1, padding=0)
        self.out2_3 = nn.Conv2d(self.ch_en * 4, 1, kernel_size=1, padding=0)
        self.out2_4 = nn.Conv2d(self.ch_en * 2, 1, kernel_size=1, padding=0)
        self.out2_5 = nn.Conv2d(self.ch_en, 1, kernel_size=1, padding=0)

        self.orig = ConvBlock(3, 64, 3, padd=1)
        self.orig2 = ConvBlock(64, 32, 3, padd=1)

        if prev_layer is not None:
            self.prev = self.prev_model(prev_layer)

    def prev_model(self, layer):
        new_model = nn.Sequential()
        for i, (name, m) in enumerate(layer.named_children()):
            if not name == 'out':
                new_model.add_module(name, m)
                new_model[-1].load_state_dict(m.state_dict())

        return new_model

    def forward(self, x):

        orig = self.orig(x)
        orig = self.orig2(orig)

        x = self.init_model.scale1(x)
        s4 = self.init_model.skip4(x)
        x = self.init_model.scale2(x)
        s3 = self.init_model.skip3(x)
        x = self.init_model.scale3(x)
        s2 = self.init_model.skip2(x)
        x = self.init_model.scale4(x)
        s1 = self.init_model.skip1(x)
        x = self.init_model.scale5(x)
        o1 = self.init_model.out1(x)
        o2 = self.init_model.out2(x)

        if self.scale == 4 or self.scale == 3 or self.scale == 2 or self.scale == 1 or self.scale == 0:
            x1 = self.decoder1_1(x, s1)
            x2 = self.decoder2_1(x, s1)
            o1 = self.out1_1(x1)
            o2 = self.out2_1(x2)
            if self.scale == 3 or self.scale == 2 or self.scale == 1 or self.scale == 0:
                x1 = self.decoder1_2(x1, s2)
                x2 = self.decoder2_2(x2, s2)
                o1 = self.out1_2(x1)
                o2 = self.out2_2(x2)
                if self.scale == 2 or self.scale == 1 or self.scale == 0:
                    x1 = self.decoder1_3(x1, s3)
                    x2 = self.decoder2_3(x2, s3)
                    o1 = self.out1_3(x1)
                    o2 = self.out2_3(x2)
                    if self.scale == 1 or self.scale == 0:
                        x1 = self.decoder1_4(x1, s4)
                        x2 = self.decoder2_4(x2, s4)
                        o1 = self.out1_4(x1)
                        o2 = self.out2_4(x2)
                        if self.scale == 0:
                            x1 = self.decoder1_5(x1, orig)
                            x2 = self.decoder2_5(x2, orig)
                            o1 = self.out1_5(x1)
                            o2 = self.out2_5(x2)

        return [torch.sigmoid(o1), torch.sigmoid(o2)]

class Initial_Layer(nn.Module):
    def __init__(self):
        super(Initial_Layer, self).__init__()

        self.ch_en = 32

        base_model = resnet50(pretrained=True)
        base_model = nn.Sequential(*list(base_model.children())[:-2])  # Remove last layers

        self.scale1 = nn.Sequential(*base_model[:3])
        self.skip4 = ConvBlock(64, 64, k_size=1, padd=0)
        self.scale2 = nn.Sequential(*base_model[3:5])
        self.skip3 = ConvBlock(256, 128, k_size=1, padd=0)
        self.scale3 = base_model[5]
        self.skip2 = ConvBlock(512, 256, k_size=1, padd=0)
        self.scale4 = base_model[6]
        self.skip1 = ConvBlock(1024, 512, k_size=1, padd=0)
        self.scale5 = base_model[7]

        self.out1 = nn.Conv2d(self.ch_en * 64, 1, kernel_size=1, padding=0)
        self.out2 = nn.Conv2d(self.ch_en * 64, 1, kernel_size=1, padding=0)

    def forward(self, x):
        x = self.scale1(x)
        x = self.scale2(x)
        x = self.scale3(x)
        x = self.scale4(x)
        x = self.scale5(x)

        x = self.out(x)

        return torch.sigmoid(x)


from django.urls import path
from django.urls import  re_path

from .views import (
OrderListView,
OrderDetailView,
VerifyOwnership
)

urlpatterns = [
    path('', OrderListView.as_view(), name="list"),
    path('endpoint/verify/ownership/', VerifyOwnership.as_view(), name="verify-ownership"),
    re_path(r'^(?P<order_id>[0-9A-Za-z]+)/$', OrderDetailView.as_view(), name="detail"),

]


#!/usr/bin/python3
from subprocess import PIPE, CalledProcessError, Popen, TimeoutExpired
from subprocess import run as sub_run
import logging
import os
import shutil
import shlex
import signal
from concurrent.futures import ThreadPoolExecutor, wait

try:
    import click
except ImportError as e:
    if 'No module named \'click\'' in e.msg:
        sub_run('sudo pip3 install click'.split(), check=True)
        import click
    else:
        raise ImportError('Something other than a missing module is wrong: {}'.format(e.msg))

logging.basicConfig(format='[%(asctime)s]\t%(levelname)s: %(message)s')

def install_gazebo(log):
    '''Installs the latest version of Gazebo. Note: Only Ubuntu is officially supported.'''
    log.info('Installing Gazebo')
    # These commands are taken from the official Ubuntu install sequence
    # at http://gazebosim.org/tutorials?tut=install_ubuntu&cat=install
    install_commands = [
            'sudo sh -c \'echo "deb http://packages.osrfoundation.org/gazebo/ubuntu-stable\
 `lsb_release -cs` main" > /etc/apt/sources.list.d/gazebo-stable.list\'',
            'wget http://packages.osrfoundation.org/gazebo.key -O - | sudo apt-key add -',
            'sudo apt-get update',
            'sudo apt-get install gazebo7 libgazebo7-dev'
            ]
    for command in install_commands:
        # Yes, running in a shell has security concerns. It should be OK for this instance,
        # though - no non-hardcoded commands running, and it's easier than setting up the
        # necessary pipes and such
        sub_run(command, shell=True, check=True)
    log.info('Gazebo has been successfully installed!')

def download_assignment(log, assignment_name):
    '''Downloads and extracts the provided files for the given assignment'''
    url = 'https://rpal.cs.cornell.edu/teaching/foundations/assignments/' + assignment_name
    base_cmd = 'wget ' + url
    log.info('Downloading and extracting archive for {}'.format(assignment_name))
    def unzip(f):
        if not f.exception():
            sub_run('tar xzvf {}.tar.gz -C {}'.format(assignment_name, assignment_name).split())
        else:
            raise f.exception()

    with ThreadPoolExecutor(max_workers=1) as e:
        download_future = e.submit(lambda: sub_run(('wget ' + url + '.tar.gz').split(), check=True))
        download_future.add_done_callback(unzip)
    log.info('Downloading version signature for {}'.format(assignment_name))
    sub_run(('wget -O .sigs/{} ' + url + '.sig').format(assignment_name).split(), check=True)
    wait([download_future])
    log.info('Done downloading and extracting materials for {}'.format(assignment_name))

def remove_assignment(log, assignment_name):
    log.info('Deleting old assignment archive and directory')
    shutil.rmtree(assignment_name)
    os.remove('{}.tar.gz'.format(assignment_name))

def fetch_assignment(log, assignment_name):
    '''Fetch the most up-to-date version of the assignment specified'''
    url_format = 'https://rpal.cs.cornell.edu/teaching/foundations/assignments/{}.sig'
    # Check if assignment has already been fetched and is up to date
    if os.path.isdir(assignment_name):
        log.info('Found directory for {}'.format(assignment_name))
        log.info('Checking version signature for {}'.format(assignment_name))
        current_sig = sub_run(
                'wget -qO- {}'.format(url_format.format(assignment_name)).split(),
                stdout=PIPE,
                universal_newlines=True,
                check=True
                ).stdout
        with open('.sigs/{}'.format(assignment_name, assignment_name), 'r') as sigfile:
            old_sig = sigfile.readline()
        if old_sig != current_sig:
            log.info('Version of {} appears to be outdated. Downloading current version.'
                     .format(assignment_name))
            remove_assignment(log, assignment_name)
            os.mkdir(assignment_name)
            download_assignment(log, assignment_name)
        else:
            log.info('Version of {} is up to date; proceeding'.format(assignment_name))
    else:
        log.info('Found no existing files for {}. Downloading current version.'
                 .format(assignment_name))
        os.mkdir(assignment_name)
        if not os.path.isdir('.sigs'):
            os.mkdir('.sigs')
        download_assignment(log, assignment_name)

def build_assignment(log, assignment_name):
    # TODO: This seems unnecessary
    def ensure_dir(dirname):
        if not os.path.isdir(dirname):
            os.mkdir(dirname)
    curr_dir = os.getcwd()
    log.info('Moving into assignment directory')
    os.chdir(assignment_name)
    log.info('Ensuring existence of build directory')
    ensure_dir('build')
    os.chdir('build')
    if not os.path.isfile('Makefile'):
        log.info('No Makefile; running CMake')
        sub_run('cmake ..'.split(), check=True)
    log.info('Running make')
    sub_run('make', check=True)
    os.chdir(curr_dir)
    log.info('Building done. {} is ready to run'.format(assignment_name))

def run_gazebo(log, assignment_name, problem):
    log.info('Running test driver for {}'.format(assignment_name))
    driver_proc = Popen(
            '{}/build/{}'.format(assignment_name, problem),
            stdin=None,
            stdout=None,
            stderr=None
            )
    env  = os.environ.copy()
    env['GAZEBO_PLUGIN_PATH'] = '{}/{}/build/'.format(os.getcwd(), assignment_name)
    env['GAZEBO_MODEL_PATH'] = '{}/{}/models/'.format(os.getcwd(), assignment_name)
    log.info('Running gazebo with the world for {}'.format(assignment_name))
    gazebo_proc = Popen(
            shlex.split('gazebo --verbose {}/{}.world'.format(assignment_name, assignment_name)),
            stdin=None,
            stdout=None,
            stderr=None,
            env=env
        )
    # Run for 60 seconds max
    try:
        driver_proc.wait(timeout=60)
    except TimeoutExpired:
        os.killpg(os.getpgid(driver_proc.pid), signal.SIGTERM)
    log.info('Wrapping up execution...')
    os.killpg(os.getpgid(gazebo_proc.pid), signal.SIGTERM)
    log.info('Done with execution')

@click.group()
def cli():
    pass

# TODO: Add no-check option
@cli.command()
@click.argument('assignment')
@click.argument('problem')
def run(assignment, problem):
    '''Build (if necessary) and run the given assignment problem.'''
    log = logging.getLogger('simulator-run')
    log.setLevel(logging.INFO)
    fetch_assignment(log, assignment)
    build_assignment(log, assignment)
    run_gazebo(log, assignment, problem)

@cli.command()
def install():
    '''Install Gazebo'''
    log = logging.getLogger('simulator-install')
    log.setLevel(logging.INFO)
    log.info('Checking to see if we already have gazebo')
    if shutil.which('gazebo'):
        log.info('Gazebo is already installed! Exiting.')
        return
    else:
        log.info("Gazebo doesn't seem to be installed.")
        install_gazebo(log)

# TODO: Add no-check option
@cli.command()
@click.argument('assignment')
def build(assignment):
    '''Build the given assignment'''
    log = logging.getLogger('simulator-build')
    log.setLevel(logging.INFO)
    fetch_assignment(log, assignment)
    build_assignment(log, assignment)

@cli.command()
@click.argument('assignment')
def get(assignment):
    '''Download the given assignment'''
    log = logging.getLogger('simulator-get')
    log.setLevel(logging.INFO)
    fetch_assignment(log, assignment)

if __name__ == '__main__':
    cli()


"""
usuarios = [
    ["Eduardo", "LATAM", 30, 0, "deportes"],
    ["Ignacio", "LATAM", 18, 0, "natación"],
    ["Anthony", "USA", 40, 0, "autos"],
    ["Jeff", "CND", 60, 0, "computacion"],
    ["MACRON", "FR", 50, 0, "nada"]
]
"""
user = ["", "", "", "", ""]

nombre = input(f"ingrese su nombre:\n")
locale = input(f"ingrese su zona, ej: LATAM, USA, CND:\n")
edad = int(input(f"ingrese su edad , ej: 18, 35:\n"))
intereses = input(f"ingrese sus afinidad por los deportes, ej deportes, natación, nada:\n")
contador = user[3] = 0

print(f"Gracias por colabiración, estimad@ {nombre:}\n")
print("vendiendo sus datos al mejor postor, espere por favor...\n")
# habitos
if locale == "LATAM" and contador < 3:
    print("recibirá el formulario de hábitos alimenticios")
    contador += 1
# empleabilidad
if 18 <= edad <= 29 and contador < 3:
    print("recibirá el formulario de empleabilidad")
    contador += 1
# experiencia
if 30 <= edad <= 59 and locale == "LATAM":
    print("recibirá el formulario de experiencia laboral")
    contador += 1
# recreativas
if edad >= 60 and contador < 3:
    print("recibirá el formulario de actividades recreativas")
    contador += 1
# deportes, menores de 60
if intereses == "deportes" and contador < 3 and edad < 60:
    print("recibirá el formulario de deportes")
    contador += 1
# atletismo: deportistas menores de 60
if intereses == "deportes" and contador < 3 and edad < 60:
    print("recibirá el formulario de atletismo")
    contador += 1
# natación: LATAMs deportistas menores de 60
if intereses == "deportes" and contador < 3 and edad < 60 and locale == "LATAM":
    print("recibirá el formulario de natación")
    contador += 1
# notDeportes
if intereses != "deportes":
    print("vas a recibir un formulario de deportes y te va a gustar")
    contador += 1

print("fin del main")


# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 19:29:03 2020
Homework 7 - Q2
@author: Adi Pall
"""

import numpy as np
from numpy.random import rand   # for a random number

def norm(x):
    "get vector norm -> sqrt(sum of squares)"
    return np.sqrt(sum((v**2 for v in x)))

def stationary(pt, steps = 100, tol = 1e-5):
    """Power method to find stationary distribution.
       Given the largest eigenvalue is 1, finds the eigenvector.
       Default steps = 100
       Default tolerance = 1e-5
    """
    x = rand(pt.shape[0])  # random initial vector
    x /= sum(x)
    count_it = steps # if it finishes the for loop without breaking, steps = iter
    for it in range(steps):
        temp = x
        x = np.dot(pt, x)
        # to get overall vector error, need sqrt(sum of squares)
        err = abs(norm(x)-norm(temp))
        if (err <= tol):
            count_it = it
            break
    return x, count_it+1 # return dist and steps taken (iter+1 since iter starts @ 0)

def pagerank_Q2(alpha):
    """ page rank example (five nodes).
        takes alpha as an input, where 1-alpha is the chance of teleporting """
    n = 5
    p_matrix = np.array([[0, 1/3, 1/3, 1/3, 0],
                         [1/2, 0, 0, 0, 1/2],
                         [1/2, 1/2, 0, 0, 0],
                         [1/2, 1/2, 0, 0, 0],
                         [0, 1, 0, 0, 0]])
    # note: there are no dead ends in this markov chain
    pt_mod = np.zeros((n, n))
    for j in range(n):
        for k in range(n):
            pt_mod[j, k] = alpha*p_matrix[k, j] + (1-alpha)*(1/n)

    dist, steps = stationary(pt_mod)
    print("distribution:", dist)
    print("steps taken:", steps)

if __name__ == '__main__':
    # Q2b
    pagerank_Q2(0.95)
    # need about 20 steps to get to the point when taking another step changes
    # distribution by less than 1e-5, which is how I am defining "stationary"

    # additionally, the distribution makes sense, given that most (four) of the
    # arrows are pointing to node 1, and then second most (three) are pointing
    # to node 0
    # resulting dist: [0.271 0.358 0.096 0.096 0.18 ]
    # then, ordering: 1,0,4,2-3 (tie)
    print('---------------------------------')
    # Q2c
    pagerank_Q2(0.01)
    # node 1 will always be the highest ranked, but the trend is:
    # as alpha decreases, the distributions get closer and closer together
    # lim of alpha -> 0 translates to lim stationary dist -> 1/5


from tkinter import *
tk = Tk()

def event():
    label = Label(tk, text='집가고 싶으신가요?')
    label.pack()
    tk.mainloop()
    button['text'] = '탈락!'

button = Button(tk, text= '네', command = event)
button2 = Button(tk, text= '아니오')
button.pack(side=LEFT,padx=10, pady=10)
button2.pack(side=LEFT, padx=10, pady=10)
tk.mainloop()


from flask import request
from flask_socketio import emit
from app import db
from app.models.bro import Bro
from json import loads
from sqlalchemy import func
import random

from app.models.bro_bros import BroBros
from app.models.broup import Broup
from app.models.broup_message import BroupMessage
from datetime import datetime

from app.util.util import remove_last_occur, update_broups

def add_bro(data):
    token = data["token"]
    bros_bro_id = data["bros_bro_id"]
    logged_in_bro = Bro.verify_auth_token(token)
    if logged_in_bro:
        bro_to_be_added = Bro.query.filter_by(id=bros_bro_id).first()

        logged_in_bro_room = "room_%s" % logged_in_bro.id
        bro_added_exists = BroBros.query.filter_by(bro_id=logged_in_bro.id, bros_bro_id=bros_bro_id).first()
        if bro_added_exists:
            # If the bro object already exists, he is probably removed. We will undo the removing.
            bro_added_exists.re_join()
            db.session.add(bro_added_exists)
            db.session.commit()
            emit("message_event_add_bro_success", bro_added_exists.serialize, room=logged_in_bro_room)
        elif bro_to_be_added:
            if bro_to_be_added.id != logged_in_bro.id:
                chat_colour = '%02X%02X%02X' % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
                bros_bro = logged_in_bro.add_bro(bro_to_be_added, chat_colour)
                bros_bro_added_bro = bro_to_be_added.add_bro(logged_in_bro, chat_colour)
                db.session.commit()
                if bros_bro:
                    emit("message_event_add_bro_success", bros_bro.serialize, room=logged_in_bro_room)
                else:
                    emit("message_event_add_bro_failed", "Bro was already added", room=logged_in_bro_room)

                if bros_bro_added_bro:
                    bro_room = "room_%s" % bro_to_be_added.id
                    emit("message_event_bro_added_you", bros_bro_added_bro.serialize, room=bro_room)
            else:
                emit("message_event_add_bro_failed", "You tried to add yourself", room=logged_in_bro_room)
        else:
            emit("message_event_add_bro_failed", "failed to add bro", room=logged_in_bro_room)
    else:
        emit("message_event_add_bro_failed", "failed to add bro", room=request.sid)

def add_broup(data):
    token = data["token"]
    logged_in_bro = Bro.verify_auth_token(token)
    if not logged_in_bro:
        emit("message_event_add_broup_failed", "failed to add broup", room=request.sid)
    else:
        participants = loads(data["participants"])

        broup_name = data["broup_name"]
        broup_name += " " + logged_in_bro.bromotion

        max_broup_id = db.session.query(func.max(Broup.broup_id)).scalar()
        if max_broup_id is None:
            max_broup_id = 0
        broup_id = max_broup_id + 1

        bro_ids = [logged_in_bro.id]
        admins = [logged_in_bro.id]
        broup = [logged_in_bro]
        for part in participants:
            bro_for_broup = Bro.query.filter_by(id=part).first()
            if bro_for_broup is None:
                emit("message_event_add_broup_failed", "failed to add broup", room=request.sid)
                return
            else:
                broup.append(bro_for_broup)
                broup_name += "" + bro_for_broup.bromotion
                bro_ids.append(bro_for_broup.id)

        broup_colour = '%02X%02X%02X' % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        for bro in broup:
            b = bro.add_broup(broup_name, broup_id, bro_ids, broup_colour, admins)
            room = "room_%s" % bro.id
            if b is not None:
                emit("message_event_added_to_broup", b.serialize, room=room)

        db.session.commit()

        emit("message_event_add_broup_success", "broup was added!", room=request.sid)
        return

def add_bro_to_broup(data):
    token = data["token"]
    logged_in_bro = Bro.verify_auth_token(token)
    if not logged_in_bro:
        emit("message_event_add_bro_to_broup_failed", "adding bro to broup failed", room=request.sid)
    else:
        broup_id = data["broup_id"]
        bro_id = data["bro_id"]

        broup_objects = Broup.query.filter_by(broup_id=broup_id)
        if broup_objects is None:
            emit("message_event_add_bro_to_broup_failed", "adding bro to broup failed", room=request.sid)
            return
        else:
            new_bro_for_broup = Bro.query.filter_by(id=bro_id).first()
            if not new_bro_for_broup:
                emit("message_event_add_bro_to_broup_failed", "adding bro to broup failed", room=request.sid)
                return

            bro_broup = Broup.query.filter_by(broup_id=broup_id, bro_id=bro_id).first()
            if bro_broup is not None and not bro_broup.has_left() and not bro_broup.is_removed():
                emit("message_event_add_bro_to_broup_failed", "adding bro to broup failed", room=request.sid)
            else:
                broup_name = ""
                broup_colour = ""
                broup_description = ""
                bro_ids = [bro_id]
                admins = []
                for broup in broup_objects:
                    if not broup.has_left() and not broup.is_removed():
                        broup_name = broup.get_broup_name() + "" + new_bro_for_broup.get_bromotion()
                        broup.set_broup_name(broup_name)
                        broup.add_participant(bro_id)
                        db.session.add(broup)
                        # Appending the bro ids from each of the broups
                        bro_ids.append(broup.get_bro_id())
                        # These should be the same in all broup objects
                        admins = broup.get_admins()
                        broup_colour = broup.get_broup_colour()
                        broup_description = broup.get_broup_description()

                new_bro_room = "room_%s" % new_bro_for_broup.id
                if bro_broup:
                    # If a broup object already exists than it has to be because the bro left or removed this broup.
                    # We add the bro again to the broup
                    bro_broup.set_participants(bro_ids)
                    bro_broup.set_broup_name(broup_name)
                    bro_broup.set_admins(admins)
                    bro_broup.update_description(broup_description)
                    bro_broup.update_colour(broup_colour)
                    bro_broup.rejoin()
                    db.session.add(bro_broup)
                    emit("message_event_added_to_broup", bro_broup.serialize, room=new_bro_room)
                else:
                    b = new_bro_for_broup.add_broup(broup_name, broup_id, bro_ids, broup_colour, admins, broup_description)
                    if b is not None:
                        emit("message_event_added_to_broup", b.serialize, room=new_bro_room)

                broup_message = BroupMessage(
                    sender_id=bro_id,
                    broup_id=broup_id,
                    body="%s has been added to the broup!" % new_bro_for_broup.get_full_name(),
                    text_message="",
                    timestamp=datetime.utcnow(),
                    info=True
                )
                db.session.add(broup_message)
                db.session.commit()

                broup_room = "broup_%s" % broup_id
                emit("message_event_send", broup_message.serialize, room=broup_room)

                update_broups(broup_objects)

def change_broup_remove_bro(data):
    token = data["token"]
    broup_id = data["broup_id"]
    bro_id = data["bro_id"]
    logged_in_bro = Bro.verify_auth_token(token)

    if logged_in_bro is None:
        emit("message_event_change_broup_remove_bro_failed", "token authentication failed", room=request.sid)
    else:
        broup_objects = Broup.query.filter_by(broup_id=broup_id)
        remove_broup = Broup.query.filter_by(broup_id=broup_id, bro_id=bro_id).first()
        remove_bro = Bro.query.filter_by(id=bro_id).first()
        if broup_objects is None or remove_broup is None or remove_bro is None:
            emit("message_event_change_broup_remove_bro_failed", "broup finding failed", room=request.sid)
        else:
            remove_bromotion = remove_bro.get_bromotion()
            for broup in broup_objects:
                broup_name = remove_last_occur(broup.get_broup_name(), remove_bromotion)
                broup.set_broup_name(broup_name)
                broup.remove_bro(bro_id)
                db.session.add(broup)

            # It's possible that the user who left was the only admin in the broup at the moment.
            # When there are no admins left we randomly assign a user to be admin.
            if len(remove_broup.get_admins()) == 0:
                # In this special event we will make everyone remaining an admin.
                for broup in broup_objects:
                    if not broup.has_left() and not broup.is_removed():
                        new_admin_id = broup.bro_id
                        for broup2 in broup_objects:
                            broup2.add_admin(new_admin_id)
                            db.session.add(broup2)

            # It's possible, that the user left the broup and that there are no more bros left.
            # In this case we will remove all the messages
            if len(remove_broup.get_participants()) == 0:
                messages = BroupMessage.query.filter_by(broup_id=broup_id)
                for message in messages:
                    db.session.delete(message)

            remove_broup.leave_broup()
            db.session.add(remove_broup)

            leave_message = "%s has been removed" % remove_bro.get_full_name()
            if bro_id == logged_in_bro.id:
                leave_message = "%s has left" % remove_bro.get_full_name()

            broup_message = BroupMessage(
                sender_id=bro_id,
                broup_id=broup_id,
                body=leave_message,
                text_message="",
                timestamp=datetime.utcnow(),
                info=True
            )
            db.session.add(broup_message)

            db.session.commit()

            update_broups(broup_objects)

            broup_room = "broup_%s" % broup_id
            emit("message_event_send", broup_message.serialize, room=broup_room)

            bro_room = "room_%s" % remove_broup.bro_id
            emit("message_event_chat_changed", remove_broup.serialize, room=bro_room)


from sys import stdin
BigMonth = ['1','3','5','7','8','10','12']
SmallMonth = ['2','4','6','9','11']
for row in stdin:
    ans = row.replace('\n','')
    if ans in BigMonth:
        print('>')
    elif ans in SmallMonth:
        print('<')
    else:
        print('!')


from pydantic import validator, AnyHttpUrl

from tracardi.service.plugin.domain.register import Plugin, Spec, MetaData, Documentation, PortDoc, Form, FormGroup, \
    FormField, FormComponent
from tracardi.service.plugin.runner import ActionRunner
from tracardi.service.plugin.domain.result import Result
from tracardi.service.notation.dot_template import DotTemplate
from tracardi.service.plugin.domain.config import PluginConfig

class Configuration(PluginConfig):
    type: str = "success"
    message: str
    hide_after: str
    position_x: str
    position_y: str
    uix_mf_source: AnyHttpUrl = "http://localhost:8686"

    @validator("message")
    def should_no_be_empty(cls, value):
        if len(value) == 0:
            raise ValueError("Message should not be empty")
        return value

    @validator("hide_after")
    def hide_after_should_be_numeric(cls, value: str):
        if not value.isnumeric():
            raise ValueError("This value should be numeric")
        return value

def validate(config: dict):
    return Configuration(**config)

class SnackBarUx(ActionRunner):

    config: Configuration

    async def set_up(self, init):
        self.config = validate(init)

    async def run(self, payload: dict, in_edge=None) -> Result:
        dot = self._get_dot_accessor(payload)
        template = DotTemplate()

        message = template.render(self.config.message, dot)

        self.ux.append({
            "tag": "div",
            "props": {
                "class": "tracardi-uix-snackbar",
                "data-type": self.config.type,
                "data-message": message,
                "data-vertical": self.config.position_y,
                "data-horizontal": self.config.position_x,
                "data-auto-hide": self.config.hide_after
            }
        })
        self.ux.append({"tag": "script", "props": {"src": f"{self.config.uix_mf_source}/uix/snackbar/index.js"}})

        return Result(port="payload", value=payload)

def register() -> Plugin:
    return Plugin(
        start=False,
        spec=Spec(
            module=__name__,
            className='SnackBarUx',
            inputs=["payload"],
            outputs=["payload"],
            init={
                "type": "success",
                "message": "",
                "hide_after": 6000,
                "position_x": "center",
                "position_y": "bottom",
                "uix_mf_source": "http://localhost:8686"
            },
            version='0.6.1',
            license="MIT",
            author="Risto Kowaczewski",
            form=Form(groups=[
                FormGroup(
                    name="Widget Message Configuration",
                    fields=[
                        FormField(
                            id="message",
                            name="Pop-up message",
                            description="Provide message that will be shown on the web page.",
                            component=FormComponent(type="textarea", props={"label": "message"})
                        ),
                        FormField(
                            id="type",
                            name="Alert type",
                            description="Select alert type.",
                            component=FormComponent(type="select", props={"label": "Alert type", "items": {
                                "error": "Error",
                                "warning": "Warning",
                                "success": "Success",
                                "info": "Info"
                            }})
                        ),
                        FormField(
                            id="hide_after",
                            name="Hide message after",
                            description="Type number of milliseconds the message must be visible. Default: 6000. 6sec.",
                            component=FormComponent(type="text", props={"label": "hide after"})
                        ),
                        FormField(
                            id="position_y",
                            name="Vertical position",
                            description="Select where would you like to place the message.",
                            component=FormComponent(type="select", props={"label": "Vertical position", "items": {
                                "bottom": "Bottom",
                                "top": "Top"
                            }})
                        ),
                        FormField(
                            id="position_x",
                            name="Horizontal position",
                            description="Select where would you like to place the message.",
                            component=FormComponent(type="select", props={"label": "Horizontal position", "items": {
                                "left": "Left",
                                "center": "Center",
                                "right": "Right"
                            }})
                        ),
                    ]),
                FormGroup(
                    name="Widget Source Location",
                    fields=[
                        FormField(
                            id="uix_mf_source",
                            name="Micro frontend source location",
                            description="Provide URL where the micro frontend source is located. Usually it is the "
                                        "location of Tracardi API. Type different location if you use CDN.",
                            component=FormComponent(type="text", props={"label": "URL"})
                        ),
                    ],
                ),
            ]),

        ),
        metadata=MetaData(
            name='Show snack bar',
            desc='Shows snack bar pop-up on the front end.',
            icon='react',
            group=["UIX Widgets"],
            documentation=Documentation(
                inputs={
                    "payload": PortDoc(desc="This port takes payload object.")
                },
                outputs={"payload": PortDoc(desc="This port returns input payload object.")}
            ),
            frontend=True
        )
    )