Exemple #1
0
	def fetchGamelogs(self, player):

		# Delete all gamelogs for player
		for gamelog in player.gamelogs:
			session.delete(gamelog)

		scraper = Scraper()
		logs = scraper.getGamelogs(player.id)
		gamelogs = []
		for log in logs:
			gamelog = Gamelog()
			gamelog.player = player
			gamelog.game_id = log['game_id']
			gamelog.MIN = log['MIN']
			gamelog.FGM = log['FGM']
			gamelog.FGA = log['FGA']
			gamelog.FG_PCT = log['FG_PCT']
			gamelog.FG3M = log['FG3M']
			gamelog.FG3A = log['FG3A']
			gamelog.FG3_PCT = log['FG3_PCT'] 
			gamelog.FG3M = log['FTM']
			gamelog.FG3A = log['FTA']
			gamelog.FG3_PCT = log['FT_PCT'] 
			gamelog.OREB = log['OREB']
			gamelog.DREB = log['DREB']
			gamelog.REB = log['REB'] 
			gamelog.AST = log['AST']
			gamelog.STL = log['STL']
			gamelog.BLK = log['BLK']
			gamelog.TOV = log['TOV']
			gamelog.PTS = log['PTS'] 
			gamelog.DK = self.calcDK(log)
			gamelogs.append(gamelog)
		session.add_all(gamelogs)
		session.commit()
Exemple #2
0
 def show_delete_project_dialog(self, project_id):
     project = session.query(Project).filter_by(id=project_id).first()
     result = messagebox.askquestion('Delete project "%s"' % project.name, 'Are You Sure?', icon='warning')
     if result == 'yes':
         session.delete(project)
         session.commit()
         self.update_projects_list()
         self.back_to_main_screen()
Exemple #3
0
 def show_delete_task_dialog(self, task_id):
     task = session.query(Task).filter_by(id=task_id).first()
     project_id = task.project_id
     result = messagebox.askquestion('Delete task "%s"' % task.name, 'Are You Sure?', icon='warning')
     if result == 'yes':
         session.delete(task)
         session.commit()
         self.popup.destroy()
         self.refresh_project_screen(project_id)
Exemple #4
0
def delete_test():
    tom = session.query(Teacher).get(1)
    print tom.students
    session.delete(tom)
    # lucy = session.query(Student).get(1)
    # session.delete(lucy)
    session.commit()
    print session.query(Teacher).all()
    print session.query(Student).all()
Exemple #5
0
def main():
    global r
    logging.config.fileConfig(path_to_cfg)
    
    while True:
        try:
            r = praw.Reddit(user_agent=cfg_file.get('reddit', 'user_agent'))
            logging.info('Logging in as {0}'
                         .format(cfg_file.get('reddit', 'username')))
            r.login(cfg_file.get('reddit', 'username'),
                    cfg_file.get('reddit', 'password'))
            sr_dict = get_enabled_subreddits()            
            settings_dict = {subreddit: update_from_wiki(sr, cfg_file.get('reddit', 'owner_username')) for subreddit, sr in sr_dict.iteritems()}
            break
        except Exception as e:
            logging.error('ERROR: {0}'.format(e))
            traceback.print_exc(file=sys.stdout)

    while True:
        try:
            bans_to_remove = session.query(Ban).filter(Ban.unban_after <= datetime.utcnow()).all()
            logging.debug("\nChecking due bans")
            
            for ban in bans_to_remove:
                logging.debug("  Unbanning /u/{0} from /r/{1}".format(ban.user, ban.subreddit))
                sr = sr_dict[ban.subreddit]
                sr.remove_ban(ban.user)
                session.add(Log(ban.user, ban.subreddit, 'unban'))
                session.delete(ban)
            
            sleep(5)
            logging.info("\nLOOP\n")

            updated_srs = process_messages(sr_dict, settings_dict)
            if updated_srs:
                if any(subreddit not in sr_dict.keys() for subreddit in updated_srs):
                    # settings and mod subs out of sync, reload everything
                    settings_dict = sr_dict.copy()
                    sr_dict = get_enabled_subreddits(reload_mod_subs=True)
                else:
                    sr_dict = get_enabled_subreddits(reload_mod_subs=False)
                    
                settings_dict.update(updated_srs)
            
        except (praw.errors.ModeratorRequired,
                praw.errors.ModeratorOrScopeRequired,
                praw.requests.HTTPError) as e:
            if not isinstance(e, praw.requests.HTTPError) or e.response.status_code == 403:
                logging.info('Re-initializing due to {0}'.format(e))
                sr_dict = get_enabled_subreddits()
        except KeyboardInterrupt:
            raise
        except Exception as e:
            logging.error('ERROR: {0}'.format(e))
            import traceback
            traceback.print_exc()
Exemple #6
0
    def drop(cls, jid):
        """ 删除一个成员
        Arguments:
            `jid`   -   成员jid
        """
        m = cls.get_one(jid)
        if m:
            session.delete(m)

        return
Exemple #7
0
    def empty_status():
        all_status = session.query(Status).all()
        for status in all_status:
            try:
                session.delete(status)
            except:
                session.rollback()

        try:
            session.commit()
        except:
            session.rollback()
Exemple #8
0
 def set_offline(cls, jid):
     m = cls.get_one(jid)
     if not m: return False
     try:
         status = session.query(Status)\
                 .filter(and_(Status.resource == jid.resource,
                              Status.member == m)).one()
         m.status.pop(m.status.index(status))
         try:
             session.delete(status)
             session.commit()
         except:
             session.rollback()
     except NoResultFound:
         pass
Exemple #9
0
def item_delete(item_title):
    item = session.query(Item).filter_by(
        title=item_title).one()
    user = session.query(User).filter_by(
        id=login_session.get('user_id')).one()
    if item.user is not None and item.user.id != user.id:
        return redirect(url_for('home'))
    if request.method == 'POST':
        img_filepath = vh.get_item_image_filepath(item.id)
        if os.path.isfile(img_filepath):
            os.remove(img_filepath)
        session.delete(item)
        session.commit()
        return redirect(url_for('home'))
    else:
        return render_template('item_delete.html',
                               item=item)
Exemple #10
0
 def delete(self, pk):
     endereco = session.query(Endereco).filter(Endereco.cep == pk)[0]
     session.delete(endereco)
     session.commit()
# notice that we flush here, but we don't commit. The change won't actually
# make it to the db so when we rerun this script, it'll still report 200/201
session.flush()

ct = Actor.query.count()
plog("Inserted Rick, New Count: {0} ".format(ct))


"""
Homework

Now that the new actor 'Rick' is added, remove him and verify that you get back
200 actors in the database
"""

session.delete(rick)
ct = Actor.query.count()
plog("Actor Count via .count(): {0} ".format(ct))

assert(ct == 200)


"""
Homework:

Tweak the actor class and add some helpful methods for:

a. Display the actors full name via a single method

"""
def deleteExistingItem(item):
    session.delete(item)
    return session.commit()
Exemple #13
0
    def exec_command(self, request):
        """
        Execute a studio-related command.
        """

        studio = Studio.find_by(slug=request['studio'])

        try:
            command = request['command']
            flag = request['flag']

            if studio is None:
                return

            if command == "live":
                if flag == "on":
                    studio.jukebox.state = u"stopped"
                    liq.set_var("%s.jukebox.switch" % studio.slug, False)
                    liq.set_var("%s.plateau.volume" % studio.slug, 1.0)

                elif flag == "off":
                    liq.set_var("%s.plateau.volume" % studio.slug, 0.0)
                    liq.set_var("%s.jukebox.volume" % studio.slug, 1.0)

                else:
                    self.send_feedback(request, "error", 'flag should be on or off')

                self.send_feedback(request)

            elif command == "start jukebox":
                studio.jukebox.state = u"playing"
                liq.set_var("%s.jukebox.switch" % studio.slug, True)

                self.send_feedback(request)

                # TODO: Create here a fade-in

                #if stack.lastSentStatus and stack.lastSentStatus["mode"] == "live":
                #    liq.set_var("%s.jukebox.volume" % studio.slug, 0.3)
                if studio.jukebox.current_element is not None and \
                   studio.jukebox.current_element.action is not None and \
                   studio.jukebox.current_element.action.command == "end show":
                    # TODO: ORLY ?
                    self.exec_command({"command": "end show", "studio": studio.slug})
                    studio.jukebox.current_element.mark_as_done()
                    studio.jukebox.curpos += 1
                    studio.mark_as_changed()
                    self.exec_command({"command": "live", "flag": "off", "studio": studio.slug})

            elif command == "start jukebox and live off":
                self.exec_command({"command": "start jukebox", "studio": studio.slug})
                self.exec_command({"command": "live", "flag": "off", "studio": studio.slug})

                self.send_feedback(request)

            elif command == "enable recorder":
                # TODO Enable a recorder
                pass

            elif command == "disable recorder":
                # TODO Disable a recorder
                pass

            elif command == "start recorder":
                # TODO Start a recorder
                pass

            elif command == "start recorder":
                # TODO Stop a recorder
                pass

            elif command == "start recording":
                # TODO Start all enabled recoders
                pass

            elif command == "stop recording":
                # TODO Stop all enabled recorders
                pass

            elif command == "start show":
                studio.jukebox.state = u"playing"
                self.exec_command({"command": "start recording", "studio": studio.slug})
                self.exec_global({"command": "select", "studio": studio.slug})
                self.exec_command({"command": "start jukebox", "studio": studio.slug})

                self.send_feedback(request)

            elif command == "end show":
                studio.jukebox.state = u"stopped"
                liq.set_var("%s.running" % studio.slug, False)
                liq.set_var("%s.jukebox.switch" % studio.slug, False)
                self.exec_command({"command": "stop recording", "studio": studio.slug})

                if studio.selected:
                    studio.selected = False
                    self.exec_command({"command": "go back to perm"})

                self.send_feedback(request)

            elif command == "bed" and flag == "on":
                liq.set_var("%s.bed.switch" % studio.slug, True)
                liq.send_command("%s-bed-switch.skip" % studio.slug)

                self.send_feedback(request)

            elif command == "bed" and flag == "off":
                liq.set_var("%s.bed.switch" % studio.slug, False)

                self.send_feedback(request)

            elif command == "skip":
                liq.send_command("%s-jukebox-stereo.skip" % studio.slug)
                studio.jukebox.current_element.mark_as_done()
                studio.jukebox.curpos += 1

                self.send_feedback(request)

            elif command == "set var":
                liq.set_var(request["key"], request["value"])

            elif command == "push":
                element = PlaylistElement.forge(request["element_type"], int(request["element_id"]))
                element.status = u"ready"

                studio.jukebox.add_element(element)

                self.send_feedback(request)

            elif command == "insert":
                if "action_id" in request:
                    element = session.query(Action).get(int(request["action_id"]))
                elif "media_id" in request:
                    element = session.query(Media).get(int(request["media_id"]))
                else:
                    # ERROR
                    return

                element.status = u"ready"

                studio.jukebox.insert_element(element, int(request["position"]))

                self.send_feedback(request)

            elif command == "remove":
                element = PlaylistElement.find_by(uid=int(request["element_id"]))

                studio.jukebox.remove_element(element)

                session.delete(element)

                self.send_feedback(request)

            elif command == "move":
                element = PlaylistElement.find_by(uid=int(request["element_id"]))

                studio.jukebox.move_element(element, int(request["position"]))

                self.send_feedback(request)

            elif command == "debug":
                if "action" in request:
                    if request["action"] == "set position":
                        studio.jukebox.curpos = int(request["position"])

                    elif request["action"] == "reload current":
                        if studio.jukebox.current_element is not None and \
                           studio.jukebox.current_element.status == "loaded":
                            studio.jukebox.current_element.status = "ready"
                            studio.mark_as_changed()

                    elif request["action"] == "force unselect":
                        studio.selected = False

                    else:
                        self.send_feedback(request, "error", "unknown action %s for debug" % request["action"])
                        return
                else:
                    self.send_feedback(request, "error", "action is required")
                    return

                self.send_feedback(request)

            else:
                self.send_feedback(request, "error", "Unknown command '%s', ignored." % command)

                sylog("Commande %s inconnue ; ignorée." % command)

        except SyCantMove as details:

            self.send_feedback(request, "error", details.message)

        if studio:
            studio.mark_as_changed()

        session.add(studio)
        session.commit()
Exemple #14
0
def process_messages(sr_dict, settings_dict):
    """Processes the bot's messages looking for invites/commands."""
    global r
    stop_time = int(cfg_file.get('reddit', 'last_message'))
    owner_username = cfg_file.get('reddit', 'owner_username')
    new_last_message = None
    update_srs = set()
    invite_srs = set()
    sleep_after = False

    logging.debug('Checking messages')

    try:
        for message in r.get_inbox():
            logging.debug("Reading message from {0}".format(message.author))
            # use exceptions to send error message reply to user
            try:
                if int(message.created_utc) <= stop_time:
                    logging.debug("  Message too old")
                    break
    
                if message.was_comment:
                    logging.debug("  Message was comment")
                    continue

                # don't get stuck in conversation loops with other bots
                if message.author.name.lower() in ['reddit', 'ban_timer', 'mod_mailer', 'f7u12_hampton', 'botwatchman']:
                    continue

                if not new_last_message:
                    new_last_message = int(message.created_utc)
    
                # if it's a subreddit invite
                if (message.subreddit and
                        message.subject.startswith('invitation to moderate /r/')):
                    message.mark_as_read()
                    raise UserspaceError("/u/ban_timer is currently in closed beta. Message the mods of /r/ban_timer for access.")
                    try:
                        subreddit = message.subreddit.display_name.lower()
                        # workaround for praw clearing mod sub list on accept
                        mod_subs = r.user._mod_subs
                        r.accept_moderator_invite(subreddit)
                        r.user._mod_subs = mod_subs
                        r.user._mod_subs[subreddit] = r.get_subreddit(subreddit)
                        logging.info('Accepted mod invite in /r/{0}'
                                     .format(subreddit))
                    except praw.errors.InvalidInvite:
                        pass
                # if it's a control message
                elif '/' in message.subject:
                    logging.debug("  Control Message")
                    sr_name = message.subject[message.subject.rindex('/')+1:].lower()
                    logging.debug("  /r/{0}".format(sr_name))
    
                    if sr_name in sr_dict:
                        sr = sr_dict[sr_name]
                    else:
                        logging.debug("  unknown subreddit /r/{0}".format(sr_name))
                        message.mark_as_read()
                        raise UserspaceError("/r/{0} is not registered with /u/ban_timer. "
                                        "Please invite /u/ban_timer to moderate /r/{0} "
                                        "with at least the `access` permission.".format(subreddit))
    
                    if (message.author in sr.get_moderators() or
                        message.author.name == owner_username):
                        pass
                    else:
                        logging.debug("  unauthorized user /u/{0}".format(message.author.name))
                        message.mark_as_read()
                        raise UserspaceError("You do not moderate /r/{0}".format(sr_name))
    
                    if message.body.strip().lower() == 'update':
                        if (message.author.name == owner_username or
                                message.author in sr.get_moderators()):
                            logging.debug("  update message")
                            update_srs.add((sr_name.lower(), message.author.name))
                    else:
                        logging.debug("  ban message")
                        
                        # add or remove a ban
                        args = message.body.strip().split("\n")
                        args = filter(lambda arg: arg.strip() != '', args)
                        user = args[1]
        
        #                 for mod in permissions:
        #                     print mod.permissions
        
                        if args[0].lower() == 'ban':
                            duration = args[2].lower() if 2 < len(args) else None
                            duration = duration if duration != 'forever' else None
                            note = args[3] if 3 < len(args) else None
                                                        
                            logging.debug("  Banning /u/{0}".format(user))
                            ban = Ban(sr_name, user, message.author.name, duration, note)
                            sr.add_ban(ban.user, note="<{0}> {1} | /u/ban_timer for /u/{2}".format(ban.duration, ban.note, ban.banned_by))
#                             sr.add_ban(ban.user)
                            session.add(ban)
                            message.mark_as_read()
                            raise UserspaceReply("Successfully banned /u/{0} from /r/{1} for {2}.".format(user, sr_name, duration))
                        elif args[0].lower() == 'unban':
                            logging.debug("  Unbanning /u/{0}".format(user))
                            ban = session.query(Ban).filter(Ban.user==user, Ban.subreddit==sr_name).one()
                            sr.remove_ban(ban.user)
                            session.delete(ban)
                            message.mark_as_read()
                            raise UserspaceReply("Successfully unbanned /u/{0} from /r/{1}".format(user, sr_name))
                        else:
                            message.reply('Unrecognized command syntax. Please check the command syntax documentation.')
                elif (message.subject.strip().lower() == 'sleep' and
                      message.author.name == owner_username):
                    logging.debug("  Sleep Message")
                    sleep_after = True
                    message.mark_as_read()
                else:
                    logging.debug("  Unknown Message")
            except UserspaceReply as e:
                message.reply("{0}".format(e))
            except UserspaceError as e:
                message.reply("Error: {0}".format(e))
        
        # do requested updates from wiki pages
        updated_srs = {}
        for subreddit, sender in update_srs:
            new_settings = update_from_wiki(r.get_subreddit(subreddit), r.get_redditor(sender))
            if new_settings:
                updated_srs[subreddit] = new_settings
                logging.info('Updated from wiki in /r/{0}'.format(subreddit))
            else:
                logging.info('Error updating from wiki in /r/{0}'
                             .format(subreddit))

        if sleep_after:
            logging.info('Sleeping for 10 seconds')
            sleep(10)
            logging.info('Sleep ended, resuming')

    except Exception as e:
        logging.error('ERROR: {0}'.format(e))
        raise
    finally:
        # update cfg with new last_message value
        if new_last_message:
            cfg_file.set('reddit', 'last_message', str(new_last_message))
            cfg_file.write(open(path_to_cfg, 'w'))
        # push bans to the database
        session.commit()


    return updated_srs
Exemple #15
0
def delete_todo(request, todoid):
    todo = session.query(ToDo).filter_by(todoid=todoid).first()
    if session.delete(todo):
        session.commit()
        return redirect("/")