Example #1
0
 def post(self, request, format=None):
     data = request.data
     try:
         player = request.user
         song = Song.objects.get(pk=data['song'])
         play = Play(player=player, song=song)
         play.save()
         serial = SongSerializer(song)
         song.plays += 1
         song.save()
         return Response(serial.data, status=status.HTTP_201_CREATED)
     except Song.DoesNotExist:
         return Response("Song PK DNE", status=status.HTTP_400_BAD_REQUEST)
Example #2
0
 def createPlays(self,chromossomes,population):
     for i in range(len(self.gameUsers)):
         # Distribui os chromossomos entre os jogadores
         for j in range(5):
             a = random.randint(0,len(chromossomes)-1)
             b = -1
             isDifferent = True
             while isDifferent:
                 b = random.randint(0,len(chromossomes)-1)
                 if a != b:
                     isDifferent = False
             play = Play(answer = -1, level = self.currentLevel, chromosomeOne = chromossomes[a], chromosomeOneIndex = a,
                         chromosomeTwo = chromossomes[b], chromosomeTwoIndex = b,play_player = self.gameUsers[i], play_experiment = self.Experiment, answer_time = -1, points = -1)
             play.save()
Example #3
0
def Play_add():
    form = PlayForm()
    if request.method == 'POST':
        name = form.name.data
        content = form.content.data
        local = form.local.data
        origin = form.origin.data
        playC_id = form.playC_id.data
        image = form.images.data
        img_url = upload_image(image)
        if name and content and local and origin and playC_id:
            try:
                new_play = Play(name=name,
                                content=content,
                                image=img_url,
                                local=local,
                                origin=origin,
                                playC_id=playC_id)
                db.session.add(new_play)
                db.session.commit()
                return '上传成功'
            except Exception as e:
                print(e)
                flash('添加周边失败')
                db.session.rollback()
                return '添加失败'
        else:
            return '参数出错'

    return render_template('upload.html', form=form)
Example #4
0
    def test_most_played_songs(self):
        """Test that the most played song's object is returned"""

        song = Song(external_song_key=SONG_JSON['key'],
                    song_genre=SONG_JSON['genres']['primary'])

        db.session.add(song)
        db.session.commit()

        play = Play(user_id=self.user.id, song_id=song.id)

        db.session.add(play)
        db.session.commit()

        self.assertIn(song, self.user.most_played_songs())
Example #5
0
def add_play():
    """Add song play to plays."""

    if not g.user: abort(401, "Sign up to add play.")

    song_key = request.json['key']
    song = add_to_songs(song_key)

    if not song:
        song = Song.query.filter_by(external_song_key=song_key).first()

    play = Play(user_id=g.user.id, song_id=song.id)
    
    db.session.add(play)
    db.session.commit()
    
    return jsonify(action="added")
Example #6
0
def build_db(filename):
    """
    Create a new database from CSV
    1. Delete the database file
    2. Create the database structure
    3. Populate the database
    """
    if os.path.exists(f"{filename}.db"):
        os.remove(f"{filename}.db")

    db.create_all()
    complete_works = read_csv(f"{filename}")
    for play in complete_works:
        the_play = Play(
            play_id=play[0],
            title=play[1],
            text=play[2],
        )
        db.session.add(the_play)
    db.session.commit()
    db.create_all()
def import_game_data(game, team_dict):
	path = game.path
	with open(path, 'r') as file:
		contents = file.read()
		game_dict = json.loads(contents)
		play_data = game_dict['Game Data']
		
		play_numbers = game_dict['Game Data']['Play#']
		num_rows = len(play_numbers)
		current_play_index = None
		current_play = None
		for i in range(0, num_rows):
			next_play_index = play_numbers[i]
			if next_play_index != current_play_index:
				
				current_play_index = next_play_index
				#make a play
				current_play, created_ = Play.get_or_create(
					game = game,
					offense = team_dict[ play_data['Off'][i] ],
					defense = team_dict[ play_data['Def'][i] ],
					index = play_data['Play#'][i],
					quarter = play_data['Q'][i],
					down = transform_down( play_data['Dwn'][i] ),
					half = play_data['Half'][i],
					yards_to_go = transform_Y2G( play_data['Y2G'][i] ),
					yards_line = transform_Y2G( play_data['Yd Ln'][i] ),
					result = play_data['Res'][i] or None
				)
			#make a collaboration
			collaboration, created_ = Collaboration.get_or_create(
				index = i,
				play = current_play
			)
			#make all the actions  
			make_quarterback_action(game_dict['Quarterback'], collaboration, i)
Example #8
0
from peewee import SQL, fn

from models import Channel, Play, Song

xml = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
"""

for channel in Channel.select().where(Channel.has_data == 1):
    xml += "<url><loc>https://radiostats.lw1.at/{channel}</loc></url>".format(
        channel=channel.shortname)
    get = Play.select(Play.song, Song.id, fn.Count(SQL('*')).alias("count")) \
        .join(Channel).switch(Play).join(Song) \
        .where((Song.show == 0) & (Channel.shortname == channel.shortname)) \
        .group_by(Play.song).order_by(SQL('count').desc()).limit(500)
    for i in get:
        song = i.song.id
        xml += "<url><loc>https://radiostats.lw1.at/{channel}/song/{songid}</loc></url>".format(
            channel=channel.shortname, songid=song)

xml += "</urlset>"

with open('sitemap.xml', 'w') as file:
    file.write(xml)
Example #9
0
def gatraThirdparty_PostPlay(request):
    allowed_methods = ['POST', 'OPTIONS']

    if request.method == 'OPTIONS':
        response = HttpResponse('', status=http_REQUEST_OK)
        response['Allow'] = ', '.join(allowed_methods)
        return response

    if request.method != 'POST':
        return HttpResponse('', status=http_NOT_ALLOWED)

    try:
        jsonData = json.loads(request.body)
    except:
        return HttpResponse('Could not load json', status=http_BAD_REQUEST)

    if ('device_type' in jsonData.keys() and
        'user_agent' in jsonData.keys() and
        'user_id' in jsonData.keys() and
        'access' in jsonData.keys() and
        'country' in jsonData.keys() and
        'idp' in jsonData.keys() and
        'media_id' in jsonData.keys()):

        play = Play()
        if 'title' in jsonData.keys():
            play.title = jsonData['title']
        if 'duration' in jsonData.keys():
            play.duration = jsonData['duration']
        play.device_type = jsonData['device_type']
        play.user_agent = jsonData['user_agent']
        if 'ip_source' in jsonData.keys():
            play.ip_source = jsonData['ip_source']
        if 'user_name' in jsonData.keys():
            play.user_name = jsonData['user_name']
        play.user_id = jsonData['user_id']
        play.access = jsonData['access']
        play.country = jsonData['country']
        play.idp = jsonData['idp']
        play.media_id = jsonData['media_id']
        if 'media_filename' in jsonData.keys():
            play.media_filename = jsonData['media_filename']
        if 'media_type' in jsonData.keys():
            play.media_type = jsonData['media_type']

        if 'season' in jsonData.keys():
            play.season = jsonData['season']

        if 'episode' in jsonData.keys():
            play.episode = jsonData['episode']

        if 'idp_name' in jsonData.keys():
            play.idp_name = jsonData['idp_name']

        play.save()

        status = http_POST_OK
        response = HttpResponse('', status=status, content_type='application/json')
        return response

    return HttpResponse('Mandatory json value not found', status=http_BAD_REQUEST)
Example #10
0
def gatraPlayer_PostPlay(request):

    allowed_methods = ['POST', 'OPTIONS']

    if request.method == 'OPTIONS':
        response = HttpResponse('', status=http_REQUEST_OK)
        response['Allow'] = ', '.join(allowed_methods)
        return response

    if request.method != 'POST':
        return HttpResponse(request.META, status=http_NOT_ALLOWED)

    if 'HTTP_GATRA_HASH' in request.META.keys():
        _hash = request.META['HTTP_GATRA_HASH']
        try:
            h = Hash.objects.get(valid_hash = _hash)
        except:
            return HttpResponse(_hash, status=http_UNAUTHORIZED)
    else:
        return HttpResponse('', status=http_UNAUTHORIZED)

    try:
        jsonData = json.loads(request.body)
    except:
        return HttpResponse('Could not load json', status=http_BAD_REQUEST)

    if ('title' in jsonData.keys() and
       'duration' in jsonData.keys() and
       'user_name' in jsonData.keys() and
       'user_id' in jsonData.keys() and
       'country' in jsonData.keys() and
       'idp' in jsonData.keys() and
       'media_id' in jsonData.keys() and
       'media_filename' in jsonData.keys() and
       'media_type' in jsonData.keys()):

        play = Play()
        play.title          = jsonData['title']
        play.duration       = jsonData['duration']

        play.user_agent     = get_user_agent(request)

        ua = parse(play.user_agent)
        if ua.is_mobile:
            play.device_type = 'mobile'
        elif ua.is_tablet:
            play.device_type = 'tablet'
        elif ua.is_pc:
            play.device_type = 'desktop'
        else:
            play.device_type = 'unknown'

        play.ip_source      = get_client_ip(request)
        play.user_name      = jsonData['user_name']
        play.user_id        = jsonData['user_id']
        play.country        = jsonData['country']
        play.idp            = jsonData['idp']
        play.media_id       = jsonData['media_id']
        play.media_filename = jsonData['media_filename']
        play.media_type     = jsonData['media_type']

        if 'season' in jsonData.keys():
            play.season = jsonData['season']

        if 'episode' in jsonData.keys():
            play.episode = jsonData['episode']

        if 'idp_name' in jsonData.keys():
            play.idp_name = jsonData['idp_name']

        play.save()

        location = "http://gatra.zolechamedia.net:6969/play/" + str(play.id) + "/"
        status = http_POST_OK
        data = {'location' : location};
        response =  HttpResponse(json.dumps(data), status=status, content_type='application/json')
    #    response['Location'] = location
        return response

    return HttpResponse('Mandatory json value not found', status=http_BAD_REQUEST)
Example #11
0
 def get_play_from_played_at_utc_and_track_id(self, played_at_utc,
                                              track_id):
     played_at_utc = convert_played_at_from_response_to_datetime(
         played_at_utc)
     played_at_utc = set_timezone_to_datetime(played_at_utc, timezone='UTC')
     played_at_cet = convert_datetime_from_timezone_to_timezone(
         played_at_utc, from_tz_code='UTC', to_tz_code='CET')
     # Play
     play = Play()
     play.user_name = self.user_name
     play.played_at_utc_timestamp = played_at_utc.timestamp() * 1000
     play.played_at_utc = played_at_utc
     play.played_at_cet = played_at_cet
     play.day = played_at_cet.day
     play.month = played_at_cet.month
     play.year = played_at_cet.year
     play.hour = played_at_cet.hour
     play.minute = played_at_cet.minute
     play.second = played_at_cet.second
     play.day_of_week = played_at_cet.weekday()
     play.week_of_year = played_at_cet.date().isocalendar()[1]
     # Track
     track = self.get_track(track_id)
     play.track = track
     play.track_id = track_id
     return play
Example #12
0
def read_data(csvfile):
  with open(csvfile, 'rU') as f:
    next(f)
    reader = csv.reader(f)
    week = 0 #this is for the week number of the season
    week_cutoff = None
    for row in reader:
      if all([r == '' for r in row]):
        break
      gid = row[0]
      #we can get the date now
      date = datetime.datetime.strptime(gid[0:8],'%Y%m%d')
      #now we want to deal with the week number
      if week_cutoff != next_tuesday(date):
        week += 1
        week_cutoff = next_tuesday(date)
        print 'season ' + csvfile[5:9] + ': Week ' + str(week)
      qtr = int(row[1])
      #need to deal with kickoff, should be 60 if both are 0
      #also play under review...
      row3errors = set(['.M', '**', 'ND','.O','.B','.H','.W','.G'])
      if row[3] in row3errors:
        #play under review...
        minute = 0
        second = 0
      else:
        minute = int(row[2]) if row[2] else 0
        second = int(row[3]) if minute and row[3] else 0
      off_team = row[4]
      def_team = row[5]
      down_num = int(row[6]) if row[6] else -1
      togo = int(row[7]) if row[7] else -1
      yardline = int(row[8]) if row[8] else -1
      description = row[9]
      if description and description[0] == '\xa0':
        description =''
      offscore = int(row[10]) if row[10] else 0
      defscore = int(row[11]) if row[11] else 0
      season = int(csvfile[5:9])
      playoffs = True if week > 16 else False #things greater than week 16 are playoffs
      formation, turnover, yardage, action, success, points, penalty = parse_description(description)
      key_rows = [0,1,2,3,6,7,8,10,11]
      key = ''.join([row[ind] for ind in key_rows])
      plays = Play.objects.filter(key=key)
      #now we want to get the info
      if not plays or all([p.description == description for p in plays]):
        play = Play(gid=gid,
                    date=date,
                    description=description,
                    offence_team=off_team,
                    defence_team=def_team,
                    offence_score=offscore,
                    defence_score=defscore,
                    week=week,
                    quarter=qtr,
                    minute = minute,
                    second = second,
                    down = down_num,
                    togo = togo,
                    yardline = yardline,
                    season = season,
                    playoffs = playoffs,
                    formation = formation,
                    turnover = turnover,
                    yardage = yardage,
                    action = action,
                    success = success,
                    points = points,
                    penalty = penalty,
                    key = key,
                    )
        play.save()
Example #13
0
    Message3 = Message(name='校训3', content='有恒')
    db.session.add_all([Message1, Message2, Message3])
    db.session.commit()

    # 5.学校周边(无关用户)
    # 周边分类
    PlayC1 = PlayC(name='美食')
    PlayC2 = PlayC(name='娱乐')
    PlayC3 = PlayC(name='游玩')
    PlayC4 = PlayC(name='出行')
    db.session.add_all([PlayC1, PlayC2, PlayC3, PlayC4])
    db.session.commit()
    # 周边
    play1 = Play(name='草莓冰',
                 content='草莓冰好吃',
                 local='十二中',
                 phone='10086',
                 origin='草莓冰',
                 playC_id=PlayC1.id)
    play2 = Play(name='天天乐',
                 content='天天乐好吃',
                 local='鮀浦',
                 phone='10086',
                 origin='天天乐',
                 playC_id=PlayC2.id)
    play3 = Play(name='小公园',
                 content='小公园好吃',
                 local='西堤',
                 phone='10086',
                 origin='小公园',
                 playC_id=PlayC3.id)
    play4 = Play(name='潮汕站',