def get_tracks_by_days(): try: tracks = [] days = request.args.get('days') assert(days.isnumeric()) query = f"""SELECT spotifyid, title, valence, play_date FROM tracks WHERE play_date >= date('now','-{days} days') ORDER BY play_date ASC; """ with sqlite3.connect(dbFile) as connection: cur = connection.cursor() cur.execute(query) queriedTracks = cur.fetchall() print(queriedTracks) for (spotifyid, title, valence, date) in queriedTracks: current_track = Track( id=spotifyid, title=title, valence=valence, playDate=date ) tracks.append(current_track.asJSON()) except Exception as e: print(e) return Response(status=500, mimetype='application/json') if len(tracks) == 0: return jsonify(tracks), 204 else: return jsonify(tracks), 200
def get_current_track(now_playing): # Get current user playing track artists = [] progress_ms = now_playing['progress_ms'] global progress_ms_prev global track_id_prev if now_playing: track_name = now_playing['item']['name'] if track_name == "": return None with open(path, 'r') as json_file: # Reading JSON file json_data = json.load(json_file) time.sleep(2) if now_playing['item'][ 'id'] == track_id_prev: # Check is current track id is the same with previous print(str(progress_ms_prev) + ">" + str(progress_ms)) if progress_ms_prev > progress_ms: # Check if the same song is repeated print(now_playing['progress_ms']) for json_i in json_data: if now_playing['item']['id'] == json_i[ 'track_id']: # Check if the song is in the JSON json_i['count'] = json_i[ 'count'] + 1 # If song exists count+1 in JSON with open(path, 'w') as file: # Write to JSON new data json.dump(json_data, file, indent=2) break progress_ms_prev = progress_ms else: # else current track id is different with previous track track_id_prev = now_playing['item']['id'] progress_ms_prev = 0 print(progress_ms_prev) for json_i in json_data: # Parsing JSON if now_playing['item']['id'] == json_i[ 'track_id']: # If current id is in File count+1 json_i['count'] = json_i['count'] + 1 with open(path, 'w') as file: # Write to JSON new data json.dump(json_data, file, indent=2) break else: # if current id doesn't exist in file write new track to file count = 1 track_id = now_playing['item']['id'] album_name = now_playing['item']['album']['name'] temp_artists = now_playing['item']['artists'] played_date = datetime.datetime.now() played_date = str(played_date) external_url = now_playing['item']['external_urls']['spotify'] thumbnail = now_playing['item']['album']['images'][0]['url'] print(played_date) for artist in temp_artists: artists.append(artist['name']) track = Track(count=count, name=track_name, track_id=track_id, artists=artists, album=album_name, played_date=played_date, external_url=external_url, thumbnail=thumbnail) track_as_dict = track.get_track_as_dict() return track_as_dict
def __set_pure_state__(self, state): """ Method called by UrmasPersist to allow the object to refresh before it's items are created """ Track.__set_pure_state__(self, state) self.closed = state.closed self.maintainUpDirection = state.maintainUpDirection spc = 0 for i, item in enumerate(state.items): if not "stopitem" in dir(item): Logging.info("Add spline point spc=%d,i=%d, itemnum=%d" % (spc, i, item.itemnum), kw="animator") tp = self.addSplinePoint(spc, 0, point=item.point) tp.__set_pure_state__(item) spc += 1 else: Logging.info("Add stop point i=%d, itemnum=%d" % (i, item.itemnum), kw="animator") tp = self.addStopPoint(i) tp.__set_pure_state__(item) #self.updatePositions() for i, item in enumerate(self.items): print "item at %d: %s" % (i, str(item)) self.paintTrack()
def generateFeatures(tracks, elevationPoints): for track in tracks: track.assignElevation(elevationPoints) for range in track.ranges: tempTrack = Track(track.name, track.filterPoints(range[0], range[1])) tempTrack.calculateRise() for point in tempTrack.trackingpoints: yield (point.latitude, point.longitude, round(point.velocity, 1), int(point.rise * 100.0))
def InitGL(self): size = self.GetClientSize() print self.name, 'initGL', size glClearColor(0.5, 0.7, 1, 1.0) glShadeModel(GL_SMOOTH) glEnable(GL_DEPTH_TEST) glEnable(GL_MULTISAMPLE) self.track = Track() self.initpov()
def setSelected(self, event): """ Selects this track """ Track.setSelected(self, event) lib.messenger.send(None, "set_keyframe_mode", 0) self.splineEditor.setViewMode(0) if event: self.showSpline() self.control.setSplineInteractionCallback(self.updateLabels)
def get_all_tracks(self, filename): events = self.get_all_particles_in_event(filename) tracks = [] for event in events: track = Track() for hit in event.tracker_hits: if (hit.magnitude() < 5): track.add_point(hit) tracks.append(track) return tracks
def __set_pure_state__(self, state): """ Method called by UrmasPersist to allow the object to refresh before it's items are created """ Track.__set_pure_state__(self, state) for i, item in enumerate(state.items): tp = self.addTimepoint(i, item.timepoint, 0) tp.__set_pure_state__(item) #self.updatePositions() self.paintTrack()
def __init__(self, id, controller): Thread.__init__(self) self.controller = controller self.precedentPiste = None self.suivantPiste = None self.id = id self.track = Track("Banque/silence.wav") #Creation du thread pour la lecture du son self.thPlaySound = ThreadPlaySound(self.track) #Creation du thread pour la modification du son self.thModifySound = ThreadModifySound(self.thPlaySound, self.track, self)
def removeActiveItem(self): """ Remove the currently selected item """ Track.removeActiveItem(self) spc = 0 for i, item in enumerate(self.items): if not item.isStopped(): self.items[i].setItemNumber(spc) self.items[i].setText("%d" % spc) spc += 1 self.showSpline()
def create_tracks(lengths, types=['random', 'random', 'random', 'random'], curvatures=[0.5, 0.5, 0.5, 0.5], circ_dirs=['left', 'left', 'left', 'left']): tracks = [] width= const.learn_track_width curvature = 0.5 for i in range(len(lengths)): track = Track(lengths[i], width=width, curvature=curvatures[i], path_type=types[i], circ_dir=circ_dirs[i]) plt.axis('equal') track.draw() plt.savefig(path_root + 'track' + str(i+1)) plt.clf() tracks.append(track) return tracks
def test_get_nearest_point(self): track = Track("TestTrack", [ TrackingPoint( 3.5, 8.8, datetime.datetime.strptime( '2016-11-11T12:00:00.000Z', datetimeFormat)), TrackingPoint( 3.4, 8.8, datetime.datetime.strptime( '2016-11-11T12:00:10.000Z', datetimeFormat)) ]) indexOfNearestPoint = track.getNearestPointIndex(3.4001, 8.8) self.assertEqual(indexOfNearestPoint, 1)
def create_track(self): track_list = [] while self.use_num < len(self.talk_list): morning_list = self._match_session(self.MORNING) afternoon_list = self._match_session(self.AFTERNOON) new_morning = MorningSession() new_morning.talk_list = copy.deepcopy(morning_list) new_afternoon = AfternoonSession() new_afternoon.talk_list = copy.deepcopy(afternoon_list) new_track = Track() new_track.morning_session = new_morning new_track.afternoon_session = new_afternoon track_list.append(new_track) self._check_last_track(track_list) self._track_list = track_list
def test_should_prepare_training_data(self): track = Track("TestTrack", [ TrackingPoint( 3.5, 8.8, datetime.datetime.strptime( '2016-11-11T12:00:00.000Z', datetimeFormat)), TrackingPoint( 3.4, 8.8, datetime.datetime.strptime( '2016-11-11T12:00:10.000Z', datetimeFormat)), TrackingPoint( 3.3, 8.8, datetime.datetime.strptime( '2016-11-11T14:00:10.000Z', datetimeFormat)) ]) elevationPoints = [ ElevationPoint(3.3, 8.8, 30.0), ElevationPoint(3.4, 8.8, 20.0), ElevationPoint(3.5, 8.8, 10.0) ] result = list( movementDataPreparation.generateFeatures([track], elevationPoints)) self.assertEqual(result[0][2], 0.0, result) self.assertEqual(result[0][3], 0.0, result) self.assertGreater(result[1][2], 0.0, result) self.assertGreater(result[1][3], 0.0, result) self.assertEqual(result[2][2], 0.0, result) self.assertEqual(result[2][3], 0.0, result)
def append_track_data(username, playlists, spotify): for p in playlists: tracks = [] results = spotify.user_playlist_tracks(username, p.id) track_data = results['items'] while results['next']: results = spotify.next(results) track_data.extend(results['items']) track_info = [(t['track']['id'], t['track']['name'], t['track']['artists'], t['track']['popularity']) for t in track_data] track_ids = [x[0] for x in track_info] chunks = [ track_ids[i:i + CHUNK_SIZE] for i in range(0, len(track_ids), CHUNK_SIZE) ] track_features = [] for chunk in chunks: track_features.extend([(t['key'], t['mode'], t['valence'], t['energy']) for t in spotify.audio_features(chunk)]) for track_info, track_features in zip(track_info, track_features): id, name, artists, popularity = track_info key, mode, valence, energy = track_features tracks.append(Track(name, id, artists, key, mode, energy, valence)) p.tracks = tracks return playlists
def trackFeatures(token, username): sp = spotipy.Spotify(auth=token) user = sp.user(username) saved_tracks = sp.current_user_saved_tracks(limit=50) pp = pprint.PrettyPrinter(indent=1, depth=2) #pp.pprint(saved_tracks['items']) tracks = [] for track in saved_tracks['items']: #pp.pprint(track['track']['id']) #track_analysis = sp.audio_analysis(track['track']['id']) track_features = sp.audio_features(track['track']['id']) duration = track_features[0]['duration_ms'] duration /=1000 danceability = track_features[0]['danceability'] energy = track_features[0]['energy'] key = track_features[0]['key'] loudness = track_features[0]['loudness'] acousticness = track_features[0]['acousticness'] speechiness = track_features[0]['speechiness'] instrumentalness = track_features[0]['instrumentalness'] liveness = track_features[0]['liveness'] valence = track_features[0]['valence'] mode = track_features[0]['mode'] artist = track['track']['album']['artists'][0]['name'] title = track['track']['name'] newTrack = Track(artist, title, duration, danceability, energy, key, loudness, acousticness, speechiness, instrumentalness, liveness, valence, mode) tracks.append(newTrack) analyze(tracks)
def add_track(self, track): with self.rlock: if not isinstance(track, Track): track = Track(track) self._list.append(track) if len(self._list) == 1: self._current = self._list[0]
def shiftItems(self, direction): """ Shift items in the given direction """ Track.shiftItems(self, direction) for i in self.items: i.setText("%d" % i.getItemNumber()) #spc=0 #for i,item in enumerate(self.items): # if not item.isStopped(): # self.items[i].setItemNumber(spc) # self.items[i].setText("%d"%spc) # spc+=1 # self.items[i].updateItem() # self.items[i].drawItem() self.showSpline()
def __init__(self, M=None, S=None): """ Construct a new 'Main' object given all params or none. :param M: number of tracks :param L0: Time it takes for a train to pass through a tunnel. :param L1: Time it takes for the next train to arrive. :param S: Time that the player stays on each track before jumping to another. :return: returns nothing """ if (M == None): #exception handling....... self.M = int(input("Input the number of tracks: ")) self.S = int( input( "Input the time that the player stays on each track before jumping to another: " )) else: self.M = M self.S = S self.current_time = 0 self.prob = self.getProb() #distribution self.trackList = [Track(self.prob) for i in range(M) ] #creates list of tracks based on prob self.player = Player( 100, self.trackList[0] ) #Creates the default player with 100 health on track 1 self.hobo = Hobo( None, None, self.M) #creates a hobo with no health or staring and give M self.playGame()
def find_around_track_list(lat=0, lng=0, page_number=1, page_size=8): logger.info('lat={}, lng ={}, page_number={}, page_size={}'.format( lat, lng, page_number, page_size)) headers = { 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Cookie': 'pgv_pvid=8835094330; UM_distinctid=1700e0fb6fb23f-0841f4aa994d1e-47e1039-181db4-1700e0fb6fc94c; JSESSIONID=0D958763C840C4037891792E223B5949-n2; CNZZDATA1000341086=1941407547-1542934706-%7C1581405252', 'DNT': '1', 'Host': 'www.2bulu.com', 'Pragma': 'no-cache', # 'Referer': # 'http://www.2bulu.com/track/track_nearby_map.htm?lng=116.439606&lat=40.323242&remark=%E5%8C%97%E4%BA%AC%E5%B8%82-%E5%A4%A7%E7%BE%8A%E5%B1%B1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' } params = { 'lat': str(lat), 'lng': str(lng), 'pageNumber': str(page_number), 'pageSize': str(page_size) } response = requests.get(FIND_AROUND_TRACK_LIST_URL, params=params, headers=headers) html_content = etree.HTML(response.text) li_id_list = html_content.xpath('//ul/li/input/@value') title_list = html_content.xpath( '//ul/li/div[@class=\'list_left\']/p/@title') span_km_list = html_content.xpath( '//ul/li/div[@class=\'list_left\']/span[@class=\'km\']') span_num_list = html_content.xpath( '//ul/li/div[@class=\'list_left\']/span[@class=\'num\']') track_list = [] if (len(li_id_list) == len(span_km_list) and len(li_id_list) == len(span_num_list) and len(li_id_list) == len(title_list)): for li_id, title, km, num in zip(li_id_list, title_list, span_km_list, span_num_list): # km.text maybe 4km, 0.4km, 4.4km km_pattern = re.compile(r'(\d*.*\d+)km') distance = float(km_pattern.search(km.text).group(1)) track_list.append(Track(li_id, str(title), distance, int(num.text))) return track_list
def create_tracks(self, num: int) -> None: self.tracks = [] i = 0 while i < np.pi: self.tracks.append( Track(self.screen, Point(self.size.x // 2, self.size.y // 2), self.radius, i)) i += np.pi / num
def initiate_track(self, detection): self.tracks.append( Track( detection, track_id= -1, # it will be assigned later so we will not increase track id for every false detection max_lost_counter=self.max_lost_counter, adulthood_age=self.adulthood_age))
def onDown(self, event): """ Item is clicked """ ret = Track.onDown(self, event) if self.overlayItem and self.overlayPos != -1: self.paintTrack() self.Refresh() return ret
def run_non_const_learner(self, learner, policy): self.logger = Logger(learner, policy, self.gran) for i in range(1): self.learner = create_learner(learner, policy) self.track = Track(self.screen, i) self.nonStopCarRun_learning() self.logger.close()
def track_add(self, funcion, frecuencia, volumen): """Agrega un track con el sonido indicado. Parametros: funcion (string) nombre de la funcion frecuencia (int) frecuencia de onda volumen (float) volumen del sonido comprendido entre 0 y 1""" if funcion.lower() not in self.FUNCIONES_DISPONIBLES: raise ValueError('El sonido introducido no existe') self.tracks.append(Track(funcion, int(frecuencia), float(volumen)))
def get_track_names_ids(playlist_id, playlist_length, user, username): """Returns a list of tracks with track names and IDs""" list_of_tracks =[] for offset in range(0, playlist_length, 100): playlist_info = user.user_playlist_tracks(username, playlist_id, None, 100, offset) for item in playlist_info['items']: track_id = item['track']['id'] list_of_tracks.append(Track(item['track']['name'], track_id)) return list_of_tracks
def mostrarBebidas(self): showTracks = self.cur.execute("SELECT * from Playlist").fetchall() tracks = [] i = 0 for t in showTracks: tracks.append(Track(t[0], t[1], t[2], t[3], t[4])) i+=1 return tracks
def __getstate__(self): """ Return the dict that is to be pickled to disk """ odict = Track.__getstate__(self) n = 0 pos = 0 for key in ["closed", "maintainUpDirection"]: odict[key] = self.__dict__[key] return odict
def play_next(self): if len(self.playList) > 0: self.play(self.playList.pop()) elif len(self.history) > 0: t = random.sample(self.history, 1)[0] t = json.loads(t) t = Track(t['srcId'], t['trackId'], t['duration'], t['meta']) self.play(t) else: # No tracks to play, try again in 1 second reactor.callLater(1, self.play_next)
def _getDeezerResponse(self): url = 'http://api.deezer.com/album/' + self.id rawResponse = requests.get(url).content self._response = loadResponse(rawResponse) self.artist = self._response['contributors'][0]['name'] self.title = self._response['title'] self.isLoaded = True self.barcode = self._response['upc'] for track in self._response['tracks']['data']: t: Track = Track(track['id']) self.tracks.append(t)
def __init__(self, name, parent, **kws): self.nameColor = (128, 195, 155) self.fg = (0, 0, 0) self.bg = self.nameColor # A flag that indicates that keyframe track is similiar to # camera path track in that it defines the camera movement self.trackType = "DEFINE_TIMEPOINT" Track.__init__(self, name, parent, **kws) self.itemClass = kws.get("item", TrackItem) self.paintOverlay = 1 self.overlayColor = ((255, 255, 255), 25) dt = UrmasDropTarget(self, "Timepoint") self.SetDropTarget(dt) self.thumbnail = 1 # added this because was commented out in Track self.sizer = wx.GridBagSizer()
def __init__(self, name, parent, **kws): self.nameColor = (0, 148, 213) self.fg = (0, 0, 0) self.bg = self.nameColor # A flag that indicates that keyframe track is similiar to # camera path track in that it defines the camera movement self.trackType = "DEFINE_CAMERA" self.noMoreItems = 0 Track.__init__(self, name, parent, **kws) self.paintOverlay = 1 self.overlayColor = ((0, 0, 255), 25) self.maintainUpDirection = 0 #self.namePanel.setColor((0,0,0),self.nameColor) self.itemClass = kws.get("item", SplinePoint) self.closed = kws.get("closed", 0) dt = UrmasDropTarget(self, "Spline") self.SetDropTarget(dt)
def __set_pure_state__(self, state): """ Method called by UrmasPersist to allow the object to refresh before it's items are created """ Track.__set_pure_state__(self, state) self.closed = state.closed self.maintainUpDirection = state.maintainUpDirection spc = 0 for i, item in enumerate(state.items): if not "stopitem" in dir(item): Logging.info("Add spline point spc=%d,i=%d, itemnum=%d" % (spc, i, item.itemnum), kw = "animator") tp = self.addSplinePoint(spc, 0, point = item.point) tp.__set_pure_state__(item) spc += 1 else: Logging.info("Add stop point i=%d, itemnum=%d" % (i, item.itemnum), kw = "animator") tp = self.addStopPoint(i) tp.__set_pure_state__(item) #self.updatePositions() for i, item in enumerate(self.items): print "item at %d: %s" % (i, str(item)) self.paintTrack()
class WeatherView(TrackView): sectorClicked = pyqtSignal(int) def __init__(self, parent=None): TrackView.__init__(self, parent) self.setScene(QGraphicsScene()) self._track = None handlers = {('init', 'sectors'): self._initTrack, ('init', 'weather'): self._setWeather, ('update', 'weather'): self._setWeather} OTPApplication.registerMsgHandlers(handlers) def mousePressEvent(self, event): handled = False for item in self.items(event.pos()): if isinstance(item, PhysicalSector): sectId = item.sectorId() if sectId is not None: self.sectorClicked.emit(sectId) handled = True break if not handled: TrackView.mousePressEvent(self, event) def _initTrack(self, sectors): self._track = Track(sectors, lambda: Qt.darkGray) self._track.enableHoverEffect() self.scene().addItem(self._track) self.refitSceneInView() def _setWeather(self, weather): for sectId, rain in weather: r = g = 100 - rain * 10 b = 50 + (360 / (12 - rain)) self._track.setSectorColor(sectId, QColor(r, g, b)) self._track.setSectorToolTip(sectId, "Amount of rain: %i" % rain)
def _initTrack(self, sectors): self._track = Track(sectors, lambda: Qt.darkGray) self._track.enableHoverEffect() self.scene().addItem(self._track) self.refitSceneInView()