Beispiel #1
0
def dialog(request):
	spotId = request.GET.get('id','').strip().encode("ascii")
	spot = Spot()
	sp = {}
	for s in spot.short_list():
		if s['id'] == spotId:
			sp = s
	return render_to_response('dialog.html', {'spot':sp,'gateway':spot.get_gateway().get_info(), 'host':request.get_host().split(':')[0]})  
Beispiel #2
0
def input():
    form = Input()
    if form.validate_on_submit():
        try:
            # print(float(form.mood.data), float(form.danceability.data), float(form.energy.data))
            if not 0 <= float(form.mood.data) <= 1.0 or not 0 <= float(
                    form.danceability.data) <= 1 or not 0 <= float(
                        form.energy.data) <= 1:
                flash('Please make sure your inputs are correct')
                return redirect('/input')
            # flash('Name: {}, Mood: {}'.format(form.username.data, form.mood.data))

            user = session.get('user', None)
            token = users[user]
            if token.is_expiring:
                token = cred.refresh(token)
                users[user] = token
            with spotify.token_as(users[user]):
                #     # tracks = spotify.current_user_top_tracks(limit=10)
                #     # for track in tracks.items:
                #     #     print(track.name)
                #     top_artists_name = [] #name used to avoid duplicates
                #     top_artists_uri = [] #uniform resource indicator to connect direct with spotify api

                #     ranges = ['short_term', 'medium_term', 'long_term'] #4 weeks, 6 months, all time
                #     for r in ranges:
                #         print(r)
                #         top_artists_all_data = spotify.current_user_top_artists(limit=50, time_range=r) #get their top artists
                #         top_artists_data = top_artists_all_data.items
                #         for artist_data in top_artists_data:
                #             if artist_data.name not in top_artists_name:
                #                 top_artists_name.append(artist_data.name)
                #                 top_artists_uri.append(artist_data.uri)

                #     followed_artists_all_data = spotify.followed_artists(limit=50)
                #     print("bruh")

                # print(top_artists_name)
                s = Spot(form.username.data, form.mood.data, spotify)
                s.grab_songs(float(form.mood.data),
                             float(form.danceability.data),
                             float(form.energy.data))
                # s.do_stuff()
            return redirect('/index')
        except:
            flash('Please input your username and a mood from 0 to 1')
            return redirect('/input')
    flash('Please input a mood from 0 to 1')
    return render_template('input.html',
                           title='Create Your Concert!',
                           form=form)
Beispiel #3
0
 def __init__(self, cols, rows):
     self.cols = cols  # temp
     self.rows = rows  # temp
     w = WIDTH / cols
     h = HEIGHT / rows
     self.spots = [[Spot(r, c, w, h) for c in range(cols)]
                   for r in range(rows)]
Beispiel #4
0
def index_old(request):
	#if request.session.get('user',False):
  		spot = Spot()
  		lanIdx = request.GET.get('lan','0')
		lan = etree.parse(BASE_DIR + '/languages/' + lanIdx + '.xml')
		str_monitor = lan.find("monitor_source").get("string");
		str_single = lan.find("single").get("string");
		str_split = lan.find("split").get("string");
		str_screen = lan.find("screen").get("string");
		str_screens = lan.find("screens").get("string");
		str_exit = lan.find("exit").get("string");	
		str_devicelist = lan.find("device_list").get("string");
		str_fullscreen = lan.find("fullscreen").get("string");	
		str_down = lan.find("down_plugin").get("string");
		str_confirmexit = lan.find("confirm_exit").get("string");
		return render_to_response('monitor.html', {'lan':lanIdx,'spot_list':spot.short_list(), 'gateway':spot.get_gateway().get_info(), 'host':request.get_host().split(':')[0], 'monitor':str_monitor, 'single':str_single,'split':str_split,'screen':str_screen, 'screens':str_screens, 'exit':str_exit, 'devicelist':str_devicelist,'fullscreen':str_fullscreen, 'down':str_down, 'confirm_exit':str_confirmexit})  
Beispiel #5
0
def genBoard():    
    for i in range(0, filas):
        row = []
        for j in range(0,columnas):
            b = Spot(i,j)
            row.append(b)
        board.append(row)
Beispiel #6
0
    def post(self):

        '''
        #logging.info('request = %s', self.request)
        logging.info('url = %s', self.request.url)
        logging.info('body = %s', self.request.body)
        '''
        queryDict = simplejson.loads(self.request.body)
        
        uid = queryDict['talky_uid']
        lon = queryDict['lon']
        lat = queryDict['lat']

        #logging.info('Receive GetSpot Request. lon = %s, lat = %s', lon, lat)
        
        spots = Spot.query(lat=lat, lon=lon, max_results=2, min_params=(2,0))

        spotList = [];

        for distance, spot in spots:
            user_num = spot.users.count()
            spotList.append({'id':spot.key().id(), 'name':spot.name, 'description':spot.description,'user_num':user_num})

        response = {'success':True, 'spots':spotList }

        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
        self.response.out.write(simplejson.dumps(response))
 def create_board(rows):
     board = []
     for x in range(rows):
         board.append([])
         for y in range(rows):
             board[x].append(Spot(y, x, Params.spot_width, Params.ROWS))
     return board
Beispiel #8
0
 def _create_grid(self):
     my_grid = []
     for i in range(self.nb_rows):
         my_grid.append([])
         for j in range(self.nb_cols):
             spot = Spot(i, j, self.cell_size)
             my_grid[i].append(spot)
     return my_grid
Beispiel #9
0
def make_grid(win_rows, spot_width, btn_height=0):
    grid = []
    for i in range(win_rows):
        grid.append([])
        for j in range(win_rows):
            spot = Spot(i, j, spot_width, btn_height, win_rows)
            grid[i].append(spot)
    return grid
Beispiel #10
0
def setNodes(rows, cols, step, generateWallRate):
    nodes = []
    for y in range(rows):
        temp = []
        for x in range(cols):
            temp.append(Spot(x, y, step, generateWallRate))
        nodes.append(temp)
    return nodes
def makeBoard(window, WIDTH):
    board = []
    for i in range(3):
        row = []
        for j in range(3):
            row.append(Spot((i, j), WIDTH))
        board.append(row)
    return board
Beispiel #12
0
def init_grid(rows):
    grid = []
    for row in range(rows):
        grid.append([])
        for column in range(rows):
            spot = Spot(row, column, rows, None)
            grid[row].append(spot)

    return grid
Beispiel #13
0
def make_grid(rows, width):
    grid = []
    gap = width // rows
    for i in range(rows):
        grid.append([])
        for j in range(rows):
            spot = Spot(i, j, gap, rows)
            grid[i].append(spot)

    return grid
Beispiel #14
0
def lambda_handler(event, context):
    dynamo = boto3.resource('dynamodb').Table('Spotlights')
    videoId = str(event["videoId"])
    response = dynamo.get_item(Key={'videoId': videoId})
    if ('Item' not in response):
        spot = {"videoId": videoId, "data": Spot(videoId).toJson}
        dynamo.put_item(Item=spot)
    else:
        spot = response['Item']

    return spot['data']
Beispiel #15
0
def prepare_cell_data():
    rows = HEIGHT // SIZE
    cols = WIDTH // SIZE

    grid = []
    for r in range(rows):
        grid.append([])
        for c in range(cols):
            spot = Spot(r, c)
            grid[r].append(spot)

    return grid
Beispiel #16
0
def make_grid(rows, width, maze=False):
	#If maze wanted return a grid that has a random maze produced by prims algorithm
	if maze:
		return make_borders(rows, width)

	#Else return an grid of white spots
	grid = []
	gap = width // rows
	for i in range(rows):
		grid.append([])
		for j in range(rows):
			spot = Spot(i, j, gap, rows)
			grid[i].append(spot)

	return grid
Beispiel #17
0
    def detect_and_fit(self,
                       detector=DoG,
                       min_sigma=1,
                       max_sigma=5,
                       sigma_ratio=1.3,
                       threshold=0.01,
                       background_kernel=(30, 30, 10)):

        valid = ['DoG', 'LoG', 'DoH']
        if detector.__name__ not in valid:
            raise ValueError('Detector not adapted, use one of DoG, LoG, DoH.')

        if self._verbose > 0:
            print("\nDetecting...", end="", flush=True)

        # Get the background signal by smoothing with a much larger kernel than the spot width.

        blobs = detector(min_sigma=min_sigma,
                         max_sigma=max_sigma,
                         sigma_ratio=sigma_ratio,
                         threshold=threshold).locate(self.image_raw)

        self.spots = [Spot(tuple(c.astype(int))) for c in blobs[:, :3]]
        if self._verbose > 0:
            print('%i spots detected.' % blobs.shape[0])

        sigmas = blobs[:, 3]

        if self._verbose > 0:
            print("\nFitting...", end="", flush=True)
        for s, p in zip(self.spots, sigmas):
            s.model = Gaussian()
            ex = self.image_raw[extract_cube(s.coordinates,
                                             side=background_kernel)]
            background = numpy.mean(ex)
            p = itertools.chain(s.coordinates, [background],
                                [self.image_raw[s.coordinates] - background],
                                [p, p, p / max(self.image_raw.shape[:2])])
            p_names = signature(s.model.function).parameters.keys()
            s.model.params = {k: v for (k, v) in zip(p_names, p)}
        if self._verbose > 0:
            print("fit.")

        funcs = [
            s.model.function(*s.model.params.values()) for s in self.spots
        ]

        self.mixture_model = lambda x, y, z: sum([f(x, y, z) for f in funcs])
    def _initialize_template(self, template):
        template_file = open('templates/{}'.format(template))
        template_arr = [row_template.split() for row_template in template_file]

        for i in xrange(len(template_arr)):
            new_row = []

            for j in xrange(len(template_arr[i])):
                spot_size = int(template_arr[i][j])

                new_spot = Spot(size=spot_size)
                new_row.append(new_spot)

                self._queue[spot_size].append(new_spot)

            self._rows.append(new_row)
Beispiel #19
0
    def updateSpots(self, t, dt=0):
        # If no spots then ignore
        if not self.spots == None:
            # Update active latitudes first
            if dt > 0: self.updateActiveRegion(dt)

            # Update spots and remove if dead
            doCull = []
            for spot in self.spots:
                if dt > 0: spot.update(self, t, dt)
                if spot.dead: doCull.append(spot)

            # Remove dead spots and replace
            if len(doCull) > 0:
                spotsToAddBack = len(doCull)
                for obj in doCull:
                    self.spots.remove(obj)
                for i in range(spotsToAddBack):
                    self.spots.append(Spot.gen_spot(self.params, self, t))
Beispiel #20
0
    def make_default_spots(self, default_spot_image):
        XC = self.XC
        YC = self.YC
        M = self.M
        N = self.N

        self.YTOP = YC - int((M / 2.) * default_spot_image.get_height())
        self.YBOT = YC + int((M / 2.) * default_spot_image.get_height())
        self.XLHS = XC - int((N / 2.) * default_spot_image.get_width())
        self.XRHS = XC + int((N / 2.) * default_spot_image.get_width())

        for midx in range(0, M):
            for nidx in range(0, N):
                spot = Spot(default_spot_image, midx, nidx, 'REG')
                w = spot.image.get_width()
                h = spot.image.get_height()
                spot.rect.center = (XC + int(
                    (-N / 2. + nidx + .5) * w), YC + int(
                        (-M / 2. + midx + .5) * h))
                self.add(spot)
Beispiel #21
0
    def post(self):
        
        logging.info(self.request.body)

        request = simplejson.loads(self.request.body)
 
        name = unicode(request['name'])

        logging.info(name)
        description = request['description']
        lat = float(request['lat'])
        lon = float(request['lon'])
        
        print name.encode('utf-8')
        print description
        print lat
        print lon

        new_spot = Spot.add(name=name,lat=lat, lon=lon, description=description)
        
        self.response.out.write('done')
Beispiel #22
0
    def _detect_spots(self, detector=LocalMax, **kwargs):
        """
        DEPRECATED, replaced by detect_and_fit for simplicity and speed issues.

        Detect spots with a specified detector (from the spotdetector.py module)
        and the detection params from utils module.
        Spots are identified by their position, i.e. 'x.y.z'.

        :param detector: an instance of the SpotDetector or subclass, i.e. implementing a 'locate' method returning
        array of positions of spots.
        :return: None, the spots attribute is a dict filled with spots (name i.e.  their position 'x.y.z' and their
        actual positions.)
        """
        if self._verbose > 0:
            print("Detecting...", end="")

        spots = detector(**kwargs).locate(self.image_filtered)

        # Spots are identified by their position:
        self.spots = [Spot(tuple(s)) for s in spots]
        if self._verbose > 0:
            print('%i spots detected.' % len(self.spots))
Beispiel #23
0
    def post(self):
        
        logging.info('CheckinHandler...')
        request = simplejson.loads(self.request.body)
        
        talky_uid = int(request['talky_uid'])
        spot_id   = int(request['spot_id'])

        user = TalkyUser.get_by_id(talky_uid)
        spot = Spot.get_by_id(spot_id)
        
        user.spot = spot.key()
        user.put()

        response = {
            'success':True,
            'checkin_times':1,
            'user_list':[]
        }

        self.response.out.write(simplejson.dumps(response))
        logging.info('CHECK-IN ... OK')
Beispiel #24
0
    def create_board(self, mouse_row, mouse_col, rows=ROWS, cols=COLS):
        #Create 2d array of Spots
        self.grid = []
        for i in range(rows):
            temp = []
            for j in range(cols):
                temp.append(Spot(i, j, GRID_WIDTH))
            self.grid.append(temp)

        #Create Mines out of spots
        n = 0
        while n < NUM_MINES:
            i,j = random.randint(0,rows-1), random.randint(0,cols-1)
            dist = int(((mouse_row-i)**2 + (mouse_col-j)**2)**(1/2))
            if not self.grid[i][j].mine and dist > 2:
                n += 1
                self.grid[i][j].mine = True

        #Update neighbors of each spot and give number of mines around
        for row in self.grid:
            for spot in row:
                spot.update_neighbors(self.grid)
Beispiel #25
0
class Bot:
    def __init__(self):
        self.keyword_fetcher = Keywords()
        self.spot_client = Spot()

    def fetch_spot(self, sentence):
        result = self.keyword_fetcher.extract_from_sentence(sentence)

        message = {}
        message_body = ''
        spot = self.spot_client.recommend_spot(list(result[1])[0], result[0])
        if spot:
            message_body += spot['name']
            message_body += 'はどうでしょうか?'
            message_body += 'オススメポイントは'
            message_body += spot['reason']
            message_body += ' です'
            message['body'] = message_body
            message['image'] = spot['image']
        else:
            message_body = '申し訳ありません、候補が見つかりませんでした'
            message['body'] = message_body
        
        return message
Beispiel #26
0
def main(user_id):
    """
    main
    """
    token = spotipy.util.prompt_for_user_token(user_id,
                                               ' '.join(SCOPE),
                                               client_id=CLIENT_ID,
                                               client_secret=CLIENT_SECRET,
                                               redirect_uri=REDIRECT_URI)

    if token:
        spot = Spot(token, user_id, trace=False)
        # spot.purge_db()
        # spot.fetch()
        # spot.display_table('tracks', order_by='created, played_at')
        # spot.display_table('albums', order_by='created')
        # spot.display_table('artists', order_by='created')
        # spot.display_table('_default')
        spot.update_recommendations()
        spot.db_info()
    else:
        print("Can't get token for", user_id)
Beispiel #27
0
 def add_goal(self, x, y):
     self.goals.add(Spot(x, y))
Beispiel #28
0
 def add_wall(self, x, y):
     self.walls.add(Spot(x, y))
Beispiel #29
0
from spot import Spot
from direction import Direction

L = Direction(Spot(-1, 0), 'l')
R = Direction(Spot(1, 0), 'r')
U = Direction(Spot(0, -1), 'u')
D = Direction(Spot(0, 1), 'd')
directions = [U, R, D, L]


class Board:
    def __init__(self, dir_list):
        self.dir_list = dir_list
        self.walls = set()
        self.goals = set()
        self.boxes = set()
        self.fboxes = frozenset() # since set is not hashable
        self.player = None
        self.width = 0
        self.height = 0
        self.cost = 1  # used for heuristics
        self.is_stuck = False

    """ Override class functions """
    def __eq__(self, other):
        """ Used for comparing board instances """
        return self.boxes.issubset(other.boxes) and self.player == other.player

    def __hash__(self):
        """
        http://www.asmeurer.com/blog/posts/what-happens-when-you-mess-with-hashing-in-python/
Beispiel #30
0
    data = (str(id), )
    db = DB(Var.hostname, Var.port, Var.dbname, Var.username, Var.password)
    return db.execute(query, data)


from dataaccess import DataAccess
from db import DB
#da = DataAccess()
#print("----")
spot_list = get_spotsid("1")
for spot in spot_list:
    print(spot)

from spot import Spot

spot1 = Spot()
spot1.id = "1"
spot1.data1 = '赤レンガ倉庫'
spot1.data2 = 35.4516872
spot1.data3 = 139.6437905
spot2 = Spot()
spot2.id = "2"
spot2.data1 = '江ノ島'
spot2.data2 = 35.3110403
spot2.data3 = 139.4875402
spot3 = Spot()
spot3.id = "3"
spot3.data1 = '高徳院(鎌倉大仏)'
spot3.data2 = 35.3168463
spot3.data3 = 139.5357335
Beispiel #31
0
import socket
import sys
import pygame

from spot import Spot
from env import *
from player import Player

counter = 0
is_zoom = False

spot = Spot(WIDTH / 2, HEIGHT / 2)
p1 = Player()
p2 = Player()


def get_client_socket():
    client = None
    try:
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect((HOST, PORT))
        clientMessage = str("OK")
        client.sendall(clientMessage.encode())

    except socket.error as msg:
        print(msg)
        client.close()
        quit()
    return client

Beispiel #32
0
from src.utility.gsclient import GsClient

GsClient.updateCredentials(
    'C:\\Users\\Chris.Williams\\.gcs\\gla001-232b82940cbf.json')
client = GsClient('gla-datastore001')
"""
blob_names = client.getBlobNameList( 'pleiades', [ '.zip' ] )
root_path = 'ssgp/raw'

for name in blob_names:

    obj = Pleiades( name )    

    path = os.path.join ( root_path, obj.getSubPath() )
    pathname = os.path.join ( path, os.path.basename( name ) )

    blob = client.moveBlob( name, dst_name=pathname )
"""

blob_names = client.getBlobNameList('spot', ['.zip'])
root_path = 'ssgp/raw'

for name in blob_names:

    obj = Spot(name)

    path = os.path.join(root_path, obj.getSubPath())
    pathname = os.path.join(path, os.path.basename(name))

    blob = client.moveBlob(name, dst_name=pathname)
Beispiel #33
0
def spots(request):
	spot = Spot()
	return render_to_response('spots.html', {'spot_list':spot.short_list(), 'gateway':spot.get_gateway().get_info(), 'host':request.get_host().split(':')[0]})
Beispiel #34
0
def get_onlines(request):
	spot = Spot()
	return HttpResponse(spot.get_onlines())	
Beispiel #35
0
 def add_box(self, x, y):
     self.boxes.add(Spot(x, y))
Beispiel #36
0
 def set_player(self, x, y):
     self.player = Spot(x, y)
def make_borders(rows, width):
    grid = []
    gap = width // rows
    for i in range(rows):
        if i == 0 or i == rows - 1:
            temp = []
            for j in range(rows):
                spot = Spot(i, j, gap, rows)
                spot.make_barrier()
                temp.append(spot)
            grid.append(temp)
        else:
            spot = Spot(i, 0, gap, rows)
            spot.make_barrier()
            temp = [spot]
            for j in range(1, rows - 1):
                temp.append(Spot(i, j, gap, rows))
            spot = Spot(i, rows - 1, gap, rows)
            spot.make_barrier()
            temp.append(spot)
            grid.append(temp)

    return grid
Beispiel #38
0
def get(request):
	id = request.GET["id"];
	spot = Spot()
	return HttpResponse(spot.getGis(id))
Beispiel #39
0
def spots1(request):
	spot = Spot()
	return HttpResponse(json.dumps(spot.short_list1(), ensure_ascii=False))