Пример #1
0
def exploit_ambiguity(nb_samples=1000, embbeding_size=100, nb_classes=10,
                      nb_random_repeat=30, report=False):
    zero_features = np.zeros([nb_samples, embbeding_size])
    unsorted_labels = np.arange(nb_samples) % nb_classes
    sorted_labels = np.sort(unsorted_labels)
    shuffled_labels = sorted_labels.copy()
    np.random.shuffle(shuffled_labels)
    zero_map = np.zeros([1, 5])
    zero_map[0, 0] = map.get_map(zero_features, unsorted_labels,
                                 mode="unspecified")
    zero_map[0, 1] = map.get_map(zero_features, sorted_labels,
                                 mode="unspecified")
    zero_map[0, 2] = map.get_map(zero_features, shuffled_labels,
                                 mode="unspecified")
    zero_map[0, 3] = map.get_map(zero_features, sorted_labels,
                                 mode="pessimistic")
    zero_map[0, 4] = map.get_map(zero_features, sorted_labels,
                                 mode="optimistic")

    rnd_map = np.zeros([nb_random_repeat, 3])
    for k in range(nb_random_repeat):
        rnd_features = np.random.rand(*zero_features.shape)
        rnd_map[k, 0] = map.get_map(rnd_features, unsorted_labels,
                                    mode="unspecified")
        rnd_map[k, 1] = map.get_map(rnd_features, sorted_labels,
                                    mode="unspecified")
        rnd_map[k, 2] = map.get_map(rnd_features, shuffled_labels,
                                    mode="unspecified")

    if report:
        plt.clf()
        plt.plot(unsorted_labels)
        plt.plot(sorted_labels)
        plt.legend(["mAP 10.31%", "mAP 18.68%"])
        plt.title("All 0 embedding labeling")
        plt.xlabel("Sample")
        plt.ylabel("Label")
        plt.savefig("all_zero_map.pdf", bbox_inches='tight')
        rnd_map_sorted = np.sort(rnd_map[:, :2], axis=1)
        print "Zero embbeding exploit:\nRandom Embedings:"
        print "\tOver %d repetitions: min:%3.2f max:%3.2f" % (
            nb_random_repeat, rnd_map_sorted.min() * 100,
            rnd_map_sorted.max() * 100)
        least_range_idx = np.argmin(rnd_map_sorted[:, 1] - rnd_map_sorted[:, 0])
        greatest_range_idx = np.argmax(
            rnd_map_sorted[:, 1] - rnd_map_sorted[:, 0])
        print "\tSmallest range in %d repetitions: min:%3.2f max:%3.2f" % (
            nb_random_repeat, rnd_map_sorted[least_range_idx, 0] * 100,
            rnd_map_sorted[least_range_idx, 1] * 100)
        print "\tGreatest range in %d repetitions: min:%3.2f max:%3.2f" % (
            nb_random_repeat, rnd_map_sorted[greatest_range_idx, 0] * 100,
            rnd_map_sorted[greatest_range_idx, 1] * 100)
        print "\tmean mAP over %d repetions %3.2f with a deviation of %3.4f" % (
            nb_random_repeat, (rnd_map[:, :2] * 100).mean(),
            (rnd_map[:, :2] * 100).std())
        print "Zero emdeddings:\n\tmin (shufled labels):%3.2f, max(sorted_labels):%3.2f, expectation(shuffled):%3.2f" % (
            zero_map[0, 0] * 100, zero_map[0, 1] * 100, zero_map[0, 2] * 100)
        print "\tmin(pessimist):%3.2f, max(optimist):%3.2f" % (
            zero_map[0, 3] * 100, zero_map[0, 4] * 100)
Пример #2
0
def item_on_ground_message():
    """Prints what item is on the ground when moved onto

    PARAM player a correctly formatted dictionary
    PARAM dungeon_map a list of lists
    PRECONDITION player is a correctly formatted dictionary
    PRECONDITION dungeon_map is a list with lists with 12 elements each
    POSTCONDITION prints a message about what item is on the ground is printed

    """
    dungeon_map = map.get_map()
    player = character.get_character_info()
    # prints a message if player is on a key
    if dungeon_map[player['row']][player['column']] == ' K ':
        print('You see a key on a table')
    # prints a message if player is on a sword
    elif dungeon_map[player['row']][player['column']] == ' S ':
        print(
            'There is a sword propped up against the wall, it seems to be in good condition'
        )
    # prints a message if player is on bread
    elif dungeon_map[player['row']][player['column']] == ' B ':
        print('You see some bread left on a bench, it looks edible')
    # prints a message if player is on treasure
    elif dungeon_map[player['row']][player['column']] == ' C ':
        print('You find the treasure you were searching for')
Пример #3
0
def user_input() -> str:
    """Takes user input and returns it when a correct input is entered

    PARAM player a correctly formatted dictionary
    PARAM dungeon_map a list of lists
    PRECONDITION player is a correctly formatted dictionary
    PRECONDITION dungeon_map is a list with lists with 12 elements each
    POSTCONDITION prints error messages until a correct input is entered
    RETURN user input once it is a correct input
    """
    error = True
    dungeon_map = map.get_map()
    while error:
        player_input = input()
        if player_input == 'east' or player_input == 'west' or player_input == 'north' or player_input == 'south':
            error = collision_check(player_input)
        elif player_input[0:4] == 'take':
            error = take_item_check(player_input)
        elif player_input[-4:] == 'door':
            error = adjacent_door_check(player_input)
        elif player_input == 'help':
            help_menu()
            error = False
        elif player_input[0:3] == 'use':
            error = dont_have_item_check(player_input)
        elif player_input == 'quit':
            error = False
        else:
            print('i dont understand')
    return player_input
Пример #4
0
    def get(self):
        player = get_player()

        try:
            if users.is_current_user_admin():
                player.has_moved = False
            if player.has_moved:
                self.redirect('/room?error=You are too tired')
                return
            target_exit = int(self.request.get('exit'))
            exits = player.location.exits 
            exit_keys = player.location.exit_keys
            if target_exit >= len(exits) or exits[target_exit] == -1:
                self.redirect('/room?error=Invalid Exit')
                return
            if target_exit == 4:
                # Go down stairs
                depth = player.location.parent().depth
                player.level = player.level + 1
                if depth == map.final_depth:
                    player.has_won = True
                    player.put()
                    self.redirect('/win')
                    return
                player.health = min(100, player.health + 10)
                player.attack = min(0, player.attack + 3)
                player.location = map.get_map(depth + 1).start
            else:
                player.location = room.Room.get(exit_keys[exits[target_exit]])
            player.has_moved = True
            player.put()
            self.redirect('/room')
        except Exception, e:
            self.redirect('/room?error=Python Error:' + str(e))
Пример #5
0
def scenario_message():
    """Prints a message about the environment

    PARAM player a correctly formatted dictionary
    PARAM dungeon_map a list of lists
    PRECONDITION player is a correctly formatted dictionary
    PRECONDITION dungeon_map is a list with lists with 12 elements each
    POSTCONDITION prints a message about the environment the player is on
    """
    dungeon_map = map.get_map()
    player = character.get_character_info()
    if player['row'] == 9 and player['column'] == 4:
        print('You come across a church that is still in good condition')
        print('There is a door that seems to be unlocked')
    elif player['row'] == 7 and player['column'] == 4:
        print('There is a run down shack to your left')
    elif dungeon_map[player['row']][player['column']] == '| |':
        print('You walk over the stone bridge')
    elif dungeon_map[player['row']][player['column'] - 1] == ' L ':
        print('You reach the treasury but it looks like the door is locked')
        print('You will need some sort of key to get through')
    elif dungeon_map[player['row']][player['column']] == '   ':
        print('You are on a dirt path')
    elif dungeon_map[player['row']][player['column']] == '...':
        print('The wooden boards creak underneath your feet')
    elif dungeon_map[player['row']][player['column']] == ':::':
        print('You are on a grassy field')
    elif dungeon_map[player['row']][player['column']] == '###':
        print('You walk over the cold stone floor of the church')
    elif dungeon_map[player['row']][player['column']] == '"""':
        print('You are in the treasury')
Пример #6
0
    def reset(self):
        self.scheduled_events = []

        m, self.game_id = get_map(self.game_id)
        self.world = World(m, self.N_GROUND_TILES)
        self.new_pos = Point(self.world.player.pos.x, self.world.player.pos.y)

        self.state = GameState.STARTED
Пример #7
0
def take_item_check(player_input: str) -> bool:
    """if user inputs to take an item checks if it is on the players tile

    PARAM player a correctly formatted dictionary
    PARAM dungeon_map a list of lists
    PARAM player_input a string
    PRECONDITION player is a correctly formatted dictionary
    PRECONDITION dungeon_map is a list of lists with 12 elements each
    PRECONDITION player_input is a string
    POSTCONDITION Prints nothing or an error message if input is incorrect
    RETURN True if error in input and False if no error
    """
    dungeon_map = map.get_map()
    player = character.get_character_info()
    # if player inputs take key checks if key is on the player and takes it if it is
    if player_input == 'take key' and dungeon_map[player['row']][
            player['column']] == ' K ':
        dungeon_map[player['row']][player['column']] = '###'
        player['inventory'].append('key')
        return False

    # if player inputs take sword checks if sword is on the player and takes it if it is
    elif player_input == 'take sword' and dungeon_map[player['row']][
            player['column']] == ' S ':
        dungeon_map[player['row']][player['column']] = '...'
        player['inventory'].append('sword')
        return False

    # if player inputs take bread checks if bread is on the player and takes it if it is
    elif player_input == 'take bread' and dungeon_map[player['row']][
            player['column']] == ' B ':
        dungeon_map[player['row']][player['column']] = '   '
        player['inventory'].append('bread')
        return False

    # if player inputs take treasure checks if treasure is on the player and takes it if it is
    elif player_input == 'take treasure' and dungeon_map[player['row']][
            player['column']] == ' C ':
        dungeon_map[player['row']][player['column']] = '"""'
        player['inventory'].append('treasure')
        return False

    # the item the user tried to take is not on the player, prints an error
    else:
        print('You cant take that')
        return True
Пример #8
0
 def post(self):
     user = users.get_current_user()
     old_player = Player.gql("WHERE user = :1", user).get()
     if old_player is None or old_player.is_alive == False:
         player = Player()
         player.user = users.get_current_user()
         player.is_alive = True
         player.location = map.get_map(1).start
         player.image = images.player[int(self.request.get('class'))]
         player.name = self.request.get('name')
         player.health = 100
         player.level = 1
         player.messages = []
         player.attack = 12
         player.score = 0
         player.has_won = False
         player.idle_out = 0
         player.put()
     self.redirect('/room')
Пример #9
0
def collision_check(player_input: str) -> bool:
    """Checks if there is a wall where the player is trying to move

    PARAM player a correctly formatted dictionary
    PARAM dungeon_map a list of lists
    PARAM player_input a string
    PRECONDITION player is a correctly formatted dictionary
    PRECONDITION dungeon_map is a list of lists with 12 elements each
    PRECONDITION player_input is the string north, east, south, or west
    POSTCONDITION Prints nothing or an error message if there is a wall
    RETURN True if user cant walk in that direction False otherwise
    """
    # list of all un-walkable terrain
    unwalkable_terrain = ('---', ' | ', ' \ ', ' / ', '~~~', '|||', ' D ',
                          ' L ')
    dungeon_map = map.get_map()
    player = character.get_character_info()

    # Checks user move direction and whether that directions area is in un-walkable terrain
    if player_input == 'east' and dungeon_map[player['row']][
            player['column'] + 1] not in unwalkable_terrain:
        character.set_column(player['column'] + 1)
        return False
    elif player_input == 'west' and dungeon_map[player['row']][
            player['column'] - 1] not in unwalkable_terrain:
        character.set_column(player['column'] - 1)
        return False
    elif player_input == 'north' and dungeon_map[player['row'] - 1][
            player['column']] not in unwalkable_terrain:
        character.set_row(player['row'] - 1)
        return False
    elif player_input == 'south' and dungeon_map[player['row'] + 1][
            player['column']] not in unwalkable_terrain:
        character.set_row(player['row'] + 1)
        return False
    # User tried to move toward an un-walkable terrain, prints error
    else:
        print('You cant move in that direction')
        return True
Пример #10
0
def adjacent_door_check(player_input: str) -> bool:
    """if user tries to interact with a door, checks if the door is adjacent

    PARAM player a correctly formatted dictionary
    PARAM dungeon_map a list of lists
    PARAM player_input a string
    PRECONDITION player is a correctly formatted dictionary
    PRECONDITION dungeon_map is a list of lists with 12 elements each
    PRECONDITION player_input is a string
    POSTCONDITION Prints nothing or an error message if input is incorrect
    RETURN True if error in input and False if no error
    """
    dungeon_map = map.get_map()
    player = character.get_character_info()
    # if user inputs unlock door, has a key, and there is a locked door then the door opens
    if player_input == 'unlock door' and dungeon_map[player['row']][player['column'] - 1] == ' L ' \
            and 'key' in player['inventory']:
        dungeon_map[player['row']][player['column'] - 1] = '   '
        return False

    # if user inputs open door and there is a door then the door opens
    elif player_input == 'open door' and dungeon_map[player['row']][
            player['column'] + 1] == ' D ':
        dungeon_map[player['row']][player['column'] + 1] = '   '
        return False

    # if user inputs unlock door but has no key the prints an error message
    elif player_input == 'unlock door' and dungeon_map[player['row']][player['column'] - 1] == ' L ' \
            and 'key' not in player['inventory']:
        print('You do not have a key to open that door')
        return True

    # user input was incorrect so prints an error message
    else:
        print('i dont understand')
        return True
Пример #11
0
Файл: q2.py Проект: jskhu/mte544
from helpers import read_pgm, simulate
from objects import Circle, Line, Robot
from map import get_map
from kd_tree import KdTree
from a_star import a_star

if __name__ == "__main__":
    pgm = read_pgm('sim_map.pgm')

    # simulation code
    t_max = 25
    dt = 0.1
    ts = np.arange(0, t_max + dt, dt)
    length = 10
    num_pix = 100
    m = get_map(pgm)

    # Robot parameters
    b = 4.5
    robot = Robot(np.array([5, 5, np.radians(90)]), b)

    # Generate milestones for kd-tree
    np.random.seed(42)
    coordinates = np.random.rand(70, 2) * 97 + 1

    milestones = []
    milestones.append(np.array([5, 5]))

    for coord in coordinates:
        circle = Circle(coord, robot.b / 2)
        if len(m.get_intersecting_rects(circle)) == 0:
Пример #12
0
import pygame
import requests
import sys
import os
from map import get_map, bbox

response = None
try:
    x = input().split()
    map_file = get_map(x[0], x[1], x[2], x[3])
except IOError as ex:
    print("Ошибка записи временного файла:", ex)
    sys.exit(2)

# Инициализируем pygame
pygame.init()
screen = pygame.display.set_mode((450, 450))
# Рисуем картинку, загружаемую из только что созданного файла.

screen.blit(pygame.image.load(x[3]), (0, 0))
# Переключаем экран и ждем закрытия окна.
pygame.display.flip()
running = True
x[2] = int(x[2])
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYUP:
            print(x[2])
            if event.key == 280:
Пример #13
0
 def test_get_map(self):
     self.assertEqual(list("|                .     FEDERATION     *         .             |\n"), get_map()[10])
Пример #14
0
print(
    "The OpenSky Network, http://www.opensky-network.org or by citing the paper Bringing up OpenSky: A large-scale ADS-B sensor network for research Matthias Schäfer, Martin Strohmeier, Vincent Lenders, Ivan Martinovic, Matthias WilhelmACM/IEEE International Conference on Information Processing in Sensor Networks, April 2014"
)
response = None
MYEVENTTYPE = 30
#Частота обновлениея ~20 секунд
#Сделано для того чтобы не нагружать систему

pygame.time.set_timer(MYEVENTTYPE, 20000)
slovar = test.test()[1][:-1]
slovar1 = test.test()[0]
try:
    x = [30, 50, 8, "map.png"]  #input().split()
    print(test.test()[1])
    map_file = get_map(x[0], x[1], x[2], x[3], test.test()[1][:-1])
except IOError as ex:
    print("Ошибка записи временного файла:", ex)
    sys.exit(2)

# Инициализируем pygame
pygame.init()
screen = pygame.display.set_mode((500, 400))
# Рисуем картинку, загружаемую из только что созданного файла.

screen.blit(pygame.image.load(x[3]), (0, 0))
# Переключаем экран и ждем закрытия окна.

pygame.display.flip()
running = True
x[2] = int(x[2])
Пример #15
0
def main():
    '''
    option flags:
    -1: isolate and write images of an input
    -2: isolate images of an input type in real time or video
    -3: write streetview images from a latitude/longitude

    -s: search for only a specific type of object
    -h: for more accurate, but slower detection
    '''
    print(HEADER[1])
    (options, args) = getopt.getopt(sys.argv[1:], '1234sh')
    if ('-1', '') in options:  # isolate and write images of an input
        print(HEADER[0] + HEADER[2])
        type = DEFAULT
        image_name = input('Please provide a specific image.\n')
        image = cv2.imread(image_name)
        if np.shape(image) == ():  # if the image doesn't exist
            print('image not found... :(')
            exit()
        results = detect_objects(image)
        if ('-s', '') in options:
            type = input(
                'Please provide an object type. Types can be found in labels.txt.\n'
            )
            # reference labels.txt for valid types
            results = detect_objects(image, type)
        if not results[
                1]:  # if no results were found, then bboxes will be empty
            print('no objects of type ' + type + ' found. :(')
        # TODO insert to DB?
        image_with_boxes = get_image_with_boxes(np.copy(image), results[1],
                                                results[2], results[3])
        cv2.imshow('image', image_with_boxes)  # show image with boxes
        cv2.waitKey(0)

        isolated_images = isolate_from_image(image, results[1], results[2],
                                             results[3])
        for im_set in isolated_images:  # show all isolated images as well
            cv2.imshow(im_set[1] + ' ' + str(im_set[2]), im_set[0])
            cv2.waitKey(0)
        cv2.destroyAllWindows()
    elif (
            '-2', ''
    ) in options:  # isolate images of an input type in real time or video
        print(HEADER[0] + HEADER[3])
        use_small_model = (False if ('-h', '') in options else True)
        video_name = input(
            'Please provide a video file path (default is real time video).\n')
        if not file_exists(video_name):
            print('Video not found. Real time video will be used instead...')
            video_name = 0  # 0 is the analogous to real time input
        if ('-s', '') in options:
            type = input(
                'Please provide an object type. Types can be found in labels.txt.\n'
            )
            isolate_from_video(video_name, type, use_small_model)
        else:
            isolate_from_video(video_name, use_small_model=use_small_model)
    elif ('-3',
          '') in options:  # write streetview images from a latitude/longitude
        print(HEADER[0] + HEADER[4])
        query = input(
            'Please enter the name of a location or input a location in the following format: latitude,longitude.\n'
        ).replace('/', ',')
        search_type = ''
        if ('-s', '') in options:
            search_type = input(
                'Please provide an object type. Types can be found in labels.txt.\n'
            )
        num_points_str = input(
            'Please provide number of points to add. Enter \'0\' if you don\'t want to add any.\n'
        )
        # '' converts to 0
        num_points = int(num_points_str) if num_points_str else 0
        db = My_MongoDB()
        locations = (get_location(query))[0]
        type = search_type if search_type else DEFAULT
        for location in locations:
            map_set = get_map(location, type, num_points)
            map = map_set[0]
            ids = map_set[1]
            print('Map ready!  Displaying now...')
            cv2.imshow(query, map)
            cv2.waitKey(0)
            for id in ids:
                cur_doc = (db.get_documents(type, '_id', id))[0]
                cur_type = cur_doc['type']
                cur_image = cur_doc['image']
                cur_loc = cur_doc['location']
                cur_direction = cur_doc['direction']
                cur_title = cur_type + ' ' + cur_loc + ' ' + cur_direction
                cv2.imshow(cur_title, cur_image)
                cv2.waitKey(0)
            cv2.destroyAllWindows()

    else:
        print('Sorry, please input an option flag... (options in README.md)')
        exit()
import numpy as np
import matplotlib.pyplot as plt
import map
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import networkx as nx
import folium
import glob
import PIL.Image
from selenium import webdriver
import os

res = []
count = []
dic = {}
inf = []
bart_map = map.get_map()
count_map_1 = []
count_map_2 = []


def get_intensity(a):

    if a < 100:
        return '#ffb2b2'
    elif a < 300:
        return '#ff7f7f'
    elif a < 500:
        return '#ff4c4c'
    elif a < 800:
        return '#ff3232'
    else: