当前位置: 首页>>代码示例>>Python>>正文


Python Contest.get_from_id方法代码示例

本文整理汇总了Python中cms.db.SQLAlchemyAll.Contest.get_from_id方法的典型用法代码示例。如果您正苦于以下问题:Python Contest.get_from_id方法的具体用法?Python Contest.get_from_id怎么用?Python Contest.get_from_id使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cms.db.SQLAlchemyAll.Contest的用法示例。


在下文中一共展示了Contest.get_from_id方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: do_export

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def do_export(self):
        """Run the actual export code.

        """
        logger.operation = "exporting contest %s" % self.contest_id
        logger.info("Starting export.")

        logger.info("Creating dir structure.")
        try:
            os.mkdir(self.spool_dir)
        except OSError:
            logger.error("The specified directory already exists, "
                         "I won't overwrite it.")
            return False
        os.mkdir(self.upload_dir)

        with SessionGen(commit=False) as session:
            self.contest = Contest.get_from_id(self.contest_id, session)

            # Creating users' directory.
            for user in self.contest.users:
                if not user.hidden:
                    os.mkdir(os.path.join(self.upload_dir, user.username))

            self.export_submissions()
            self.export_ranking()

        logger.info("Export finished.")
        logger.operation = ""

        return True
开发者ID:invinciblejha,项目名称:cms,代码行数:33,代码来源:SpoolExporter.py

示例2: do_export

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def do_export(self):
        """Run the actual export code.

        """
        logger.operation = "exporting contest %d" % self.contest_id
        logger.info("Starting export.")

        export_dir = self.export_target
        archive_info = get_archive_info(self.export_target)

        if archive_info["write_mode"] != "":
            # We are able to write to this archive.
            if os.path.exists(self.export_target):
                logger.critical("The specified file already exists, " "I won't overwrite it.")
                return False
            export_dir = os.path.join(tempfile.mkdtemp(), archive_info["basename"])

        logger.info("Creating dir structure.")
        try:
            os.mkdir(export_dir)
        except OSError:
            logger.critical("The specified directory already exists, " "I won't overwrite it.")
            return False

        files_dir = os.path.join(export_dir, "files")
        descr_dir = os.path.join(export_dir, "descriptions")
        os.mkdir(files_dir)
        os.mkdir(descr_dir)

        with SessionGen(commit=False) as session:

            contest = Contest.get_from_id(self.contest_id, session)

            # Export files.
            logger.info("Exporting files.")
            files = contest.enumerate_files(self.skip_submissions, self.skip_user_tests, light=self.light)
            for _file in files:
                if not self.safe_get_file(_file, os.path.join(files_dir, _file), os.path.join(descr_dir, _file)):
                    return False

            # Export the contest in JSON format.
            logger.info("Exporting the contest in JSON format.")
            with open(os.path.join(export_dir, "contest.json"), "w") as fout:
                json.dump(contest.export_to_dict(self.skip_submissions, self.skip_user_tests), fout, indent=4)

        # If the admin requested export to file, we do that.
        if archive_info["write_mode"] != "":
            archive = tarfile.open(self.export_target, archive_info["write_mode"])
            archive.add(export_dir, arcname=archive_info["basename"])
            archive.close()
            shutil.rmtree(export_dir)

        logger.info("Export finished.")
        logger.operation = ""

        return True
开发者ID:vishan,项目名称:cms,代码行数:58,代码来源:ContestExporter.py

示例3: initialize

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def initialize(self, ranking):
        """Send to the ranking all the data that are supposed to be
        sent before the contest: contest, users, tasks. No support for
        teams, flags and faces.

        ranking ((string, string)): address and authorization string
                                    of ranking server.
        return (bool): success of operation

        """
        logger.info("Initializing rankings.")
        connection = httplib.HTTPConnection(ranking[0])
        auth = ranking[1]

        with SessionGen(commit=False) as session:
            contest = Contest.get_from_id(self.contest_id, session)
            if contest is None:
                logger.error("Received request for unexistent contest id %s." %
                             self.contest_id)
                raise KeyError
            contest_name = contest.name
            contest_url = "/contests/%s" % encode_id(contest_name)
            contest_data = {"name": contest.description,
                            "begin": contest.start,
                            "end": contest.stop}

            users = [["/users/%s" % encode_id(user.username),
                      {"f_name": user.first_name,
                       "l_name": user.last_name,
                       "team": None}]
                     for user in contest.users
                     if not user.hidden]

            tasks = [["/tasks/%s" % encode_id(task.name),
                      {"name": task.title,
                       "contest": encode_id(contest.name),
                       "max_score": 100.0,
                       "extra_headers": [],
                       "order": task.num,
                       "short_name": encode_id(task.name)}]
                     for task in contest.tasks]

        safe_put_data(connection, contest_url, contest_data, auth,
                      "sending contest %s" % contest_name)

        for user in users:
            safe_put_data(connection, user[0], user[1], auth,
                          "sending user %s" % (user[1]["l_name"] + " " +
                                                user[1]["f_name"]))

        for task in tasks:
            safe_put_data(connection, task[0], task[1], auth,
                          "sending task %s" % task[1]["name"])

        return True
开发者ID:volpino,项目名称:cms,代码行数:57,代码来源:ScoringService.py

示例4: add_user

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
def add_user(contest_id, first_name, last_name, username,
             password, ip_address, email, hidden):
    with SessionGen(commit=True) as session:
        contest = Contest.get_from_id(contest_id, session)
        user = User(first_name=first_name,
                    last_name=last_name,
                    username=username,
                    password=password,
                    email=email,
                    ip=ip_address,
                    hidden=hidden,
                    contest=contest)
        session.add(user)
开发者ID:VittGam,项目名称:cms,代码行数:15,代码来源:AddUser.py

示例5: precache_files

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def precache_files(self, contest_id):
        """RPC to ask the worker to precache of files in the contest.

        contest_id (int): the id of the contest

        """
        # TODO - Check for lock
        logger.info("Precaching files for contest %d" % contest_id)
        with SessionGen(commit=False) as session:
            contest = Contest.get_from_id(contest_id, session)
            for digest in contest.enumerate_files():
                self.file_cacher.get_file(digest)
        logger.info("Precaching finished")
开发者ID:volpino,项目名称:cms,代码行数:15,代码来源:Worker.py

示例6: __init__

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def __init__(self, contest_id, export_target, skip_submissions, skip_user_tests, light):
        self.contest_id = contest_id
        self.skip_submissions = skip_submissions
        self.skip_user_tests = skip_user_tests
        self.light = light

        # If target is not provided, we use the contest's name.
        if export_target == "":
            with SessionGen(commit=False) as session:
                contest = Contest.get_from_id(self.contest_id, session)
                self.export_target = "dump_%s.tar.gz" % contest.name
        else:
            self.export_target = export_target

        self.file_cacher = FileCacher()
开发者ID:vishan,项目名称:cms,代码行数:17,代码来源:ContestExporter.py

示例7: prepare

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def prepare(self):
        """This method is executed at the beginning of each request.

        """
        self.set_header("Cache-Control", "no-cache, must-revalidate")

        self.sql_session = Session()
        self.contest = Contest.get_from_id(self.application.service.contest, self.sql_session)

        localization_dir = os.path.join(os.path.dirname(__file__), "mo")
        if os.path.exists(localization_dir):
            tornado.locale.load_gettext_translations(localization_dir, "cms")

        self._ = self.get_browser_locale().translate
        self.r_params = self.render_params()
开发者ID:volpino,项目名称:cms,代码行数:17,代码来源:ContestWebServer.py

示例8: precache_files

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def precache_files(self, contest_id):
        """RPC to ask the worker to precache of files in the contest.

        contest_id (int): the id of the contest

        """
        # Lock is not needed if the admins correctly placed cache and
        # temp directories in the same filesystem. This is what
        # usually happens since they are children of the same,
        # cms-created, directory.
        logger.info("Precaching files for contest %d." % contest_id)
        with SessionGen(commit=False) as session:
            contest = Contest.get_from_id(contest_id, session)
            for digest in contest.enumerate_files(skip_submissions=True):
                self.file_cacher.get_file(digest)
        logger.info("Precaching finished.")
开发者ID:invinciblejha,项目名称:cms,代码行数:18,代码来源:Worker.py

示例9: _initialize_scorers

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def _initialize_scorers(self):
        """Initialize scorers, the ScoreType objects holding all
        submissions for a given task and deciding scores, and create
        an empty ranking view for the contest.

        """
        with SessionGen(commit=False) as session:
            contest = Contest.get_from_id(self.contest_id, session)

            for task in contest.tasks:
                try:
                    self.scorers[task.id] = get_score_type(task=task)
                except Exception as error:
                    logger.critical("Cannot get score type for task %s: %r" %
                                    (task.name, error))
                    self.exit()
            session.commit()
开发者ID:gcampax,项目名称:cms,代码行数:19,代码来源:ScoringService.py

示例10: search_jobs_not_done

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def search_jobs_not_done(self):
        """Look in the database for submissions that have not been
        scored for no good reasons. Put the missing job in the queue.

        """
        # Do this only if we are not still loading old submission
        # (from the start of the service).
        if self.scoring_old_submission:
            return True

        with SessionGen(commit=False) as session:
            contest = Contest.get_from_id(self.contest_id, session)

            new_submission_results_to_score = set()
            new_submissions_to_token = set()

            for submission in contest.get_submissions():
                for dataset in get_datasets_to_judge(submission.task):
                    sr = submission.get_result(dataset)
                    sr_id = (submission.id, dataset.id)

                    if sr is not None and (sr.evaluated() or
                            sr.compilation_outcome == "fail") and \
                            sr_id not in self.submission_results_scored:
                        new_submission_results_to_score.add(sr_id)

                if submission.tokened() and \
                        submission.id not in self.submissions_tokened:
                    new_submissions_to_token.add(submission.id)

        new_s = len(new_submission_results_to_score)
        old_s = len(self.submission_results_to_score)
        new_t = len(new_submissions_to_token)
        old_t = len(self.submissions_to_token)
        logger.info("Submissions found to score/token: %d, %d." %
                    (new_s, new_t))
        if new_s + new_t > 0:
            self.submission_results_to_score |= new_submission_results_to_score
            self.submissions_to_token |= new_submissions_to_token
            if old_s + old_t == 0:
                self.add_timeout(self.score_old_submissions, None,
                                 0.5, immediately=False)

        # Run forever.
        return True
开发者ID:s546360316,项目名称:cms,代码行数:47,代码来源:ScoringService.py

示例11: rankings_initialize

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def rankings_initialize(self):
        """Send to all the rankings all the data that are supposed to be
        sent before the contest: contest, users, tasks. No support for
        teams, flags and faces.

        """
        logger.info("Initializing rankings.")

        with SessionGen(commit=False) as session:
            contest = Contest.get_from_id(self.contest_id, session)

            if contest is None:
                logger.error("Received request for unexistent contest "
                             "id %s." % self.contest_id)
                raise KeyError

            contest_id = encode_id(contest.name)
            contest_data = {
                "name": contest.description,
                "begin": int(make_timestamp(contest.start)),
                "end": int(make_timestamp(contest.stop)),
                "score_precision": contest.score_precision}

            users = dict((encode_id(user.username),
                          {"f_name": user.first_name,
                           "l_name": user.last_name,
                           "team": None})
                         for user in contest.users
                         if not user.hidden)

            tasks = dict((encode_id(task.name),
                          {"name": task.title,
                           "contest": encode_id(contest.name),
                           "max_score": 100.0,
                           "score_precision": task.score_precision,
                           "extra_headers": [],
                           "order": task.num,
                           "short_name": task.name})
                         for task in contest.tasks)

        for ranking in self.rankings:
            ranking.data_queue.put((ranking.CONTEST_TYPE,
                                    {contest_id: contest_data}))
            ranking.data_queue.put((ranking.USER_TYPE, users))
            ranking.data_queue.put((ranking.TASK_TYPE, tasks))
开发者ID:beyondai,项目名称:cms,代码行数:47,代码来源:ScoringService.py

示例12: harvest_contest_data

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
def harvest_contest_data(contest_id):
    """Retrieve the couples username, password and the task list for a
    given contest.

    contest_id (int): the id of the contest we want.
    return (tuple): the first element is a dictionary mapping
                    usernames to passwords; the second one is the list
                    of the task names.

    """
    users = {}
    tasks = []
    with SessionGen() as session:
        contest = Contest.get_from_id(contest_id, session)
        for user in contest.users:
            users[user.username] = {'password': user.password}
        for task in contest.tasks:
            tasks.append((task.id, task.name))
    return users, tasks
开发者ID:NorskInformatikkolympiade,项目名称:cms,代码行数:21,代码来源:StressTest.py

示例13: __init__

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def __init__(self, contest_id, export_target,
                 dump_files, dump_model, light,
                 skip_submissions, skip_user_tests):
        self.contest_id = contest_id
        self.dump_files = dump_files
        self.dump_model = dump_model
        self.light = light
        self.skip_submissions = skip_submissions
        self.skip_user_tests = skip_user_tests

        # If target is not provided, we use the contest's name.
        if export_target == "":
            with SessionGen(commit=False) as session:
                contest = Contest.get_from_id(self.contest_id, session)
                self.export_target = "dump_%s.tar.gz" % contest.name
                logger.warning("export_target not given, using \"%s\""
                               % self.export_target)
        else:
            self.export_target = export_target

        self.file_cacher = FileCacher()
开发者ID:Mloc,项目名称:cms,代码行数:23,代码来源:ContestExporter.py

示例14: do_export

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def do_export(self):
        """Run the actual export code.

        """
        logger.operation = "exporting contest %d" % self.contest_id
        logger.info("Starting export.")

        export_dir = self.export_target
        archive_info = get_archive_info(self.export_target)

        if archive_info["write_mode"] != "":
            # We are able to write to this archive.
            if os.path.exists(self.export_target):
                logger.critical("The specified file already exists, "
                                "I won't overwrite it.")
                return False
            export_dir = os.path.join(tempfile.mkdtemp(),
                                      archive_info["basename"])

        logger.info("Creating dir structure.")
        try:
            os.mkdir(export_dir)
        except OSError:
            logger.critical("The specified directory already exists, "
                            "I won't overwrite it.")
            return False

        files_dir = os.path.join(export_dir, "files")
        descr_dir = os.path.join(export_dir, "descriptions")
        os.mkdir(files_dir)
        os.mkdir(descr_dir)

        with SessionGen(commit=False) as session:

            contest = Contest.get_from_id(self.contest_id, session)

            # Export files.
            logger.info("Exporting files.")
            files = contest.enumerate_files(self.skip_submissions,
                                            self.skip_user_tests,
                                            light=self.light)
            for _file in files:
                if not self.safe_get_file(_file,
                                          os.path.join(files_dir, _file),
                                          os.path.join(descr_dir, _file)):
                    return False

            # Export the contest in JSON format.
            logger.info("Exporting the contest in JSON format.")

            self.ids = {contest: "0"}
            self.queue = [contest]

            data = dict()
            i = 0
            while i < len(self.queue):
                obj = self.queue[i]
                data[self.ids[obj]] = self.export_object(obj)
                i += 1

            def maybe_sort_numerically(x):
                try:
                    if isinstance(x, tuple) or isinstance(x, list):
                        x = x[0]
                    x = int(x)
                except:
                    pass
                return x
            with open(os.path.join(export_dir, "contest.json"), 'w') as fout:
                json.dump(data, fout, indent=4, sort_keys=True, item_sort_key=maybe_sort_numerically)

        # If the admin requested export to file, we do that.
        if archive_info["write_mode"] != "":
            archive = tarfile.open(self.export_target,
                                   archive_info["write_mode"])
            archive.add(export_dir, arcname=archive_info["basename"])
            archive.close()
            shutil.rmtree(export_dir)

        logger.info("Export finished.")
        logger.operation = ""

        return True
开发者ID:bblackham,项目名称:cms,代码行数:85,代码来源:ContestExporter.py

示例15: do_reimport

# 需要导入模块: from cms.db.SQLAlchemyAll import Contest [as 别名]
# 或者: from cms.db.SQLAlchemyAll.Contest import get_from_id [as 别名]
    def do_reimport(self):
        """Ask the loader to load the contest and actually merge the
        two.

        """
        # Create the dict corresponding to the new contest.
        yaml_contest = self.loader.import_contest(self.path)
        yaml_users = dict(((x['username'], x) for x in yaml_contest['users']))
        yaml_tasks = dict(((x['name'], x) for x in yaml_contest['tasks']))

        with SessionGen(commit=False) as session:

            # Create the dict corresponding to the old contest, from
            # the database.
            contest = Contest.get_from_id(self.contest_id, session)
            cms_contest = contest.export_to_dict()
            cms_users = dict((x['username'], x) for x in cms_contest['users'])
            cms_tasks = dict((x['name'], x) for x in cms_contest['tasks'])

            # Delete the old contest from the database.
            session.delete(contest)
            session.flush()

            # Do the actual merge: first of all update all users of
            # the old contest with the corresponding ones from the new
            # contest; if some user is present in the old contest but
            # not in the new one we check if we have to fail or remove
            # it and, in the latter case, add it to a list
            users_to_remove = []
            for user_num, user in enumerate(cms_contest['users']):
                try:
                    user_submissions = \
                        cms_contest['users'][user_num]['submissions']
                    cms_contest['users'][user_num] = \
                        yaml_users[user['username']]
                    cms_contest['users'][user_num]['submissions'] = \
                        user_submissions
                except KeyError:
                    if self.force:
                        logger.warning("User %s exists in old contest, but "
                                       "not in the new one" % user['username'])
                        users_to_remove.append(user_num)
                        session.delete(contest.users[user_num])
                    else:
                        logger.error("User %s exists in old contest, but "
                                     "not in the new one" % user['username'])
                        return False

            # Delete the users
            for user_num in users_to_remove:
                del cms_contest['users'][user_num]

            # The append the users in the new contest, not present in
            # the old one.
            for user in yaml_contest['users']:
                if user['username'] not in cms_users.keys():
                    cms_contest['users'].append(user)

            # The same for tasks: update old tasks.
            tasks_to_remove = []
            for task_num, task in enumerate(cms_contest['tasks']):
                try:
                    cms_contest['tasks'][task_num] = yaml_tasks[task['name']]
                except KeyError:
                    if self.force:
                        logger.warning("Task %s exists in old contest, but "
                                       "not in the new one" % task['name'])
                        tasks_to_remove.append(task_num)
                        session.delete(contest.tasks[task_num])
                    else:
                        logger.error("Task %s exists in old contest, but "
                                     "not in the new one" % task['name'])
                        return False

            # Delete the tasks
            for task_num in tasks_to_remove:
                del cms_contest['tasks'][task_num]

            # And add new tasks.
            for task in yaml_contest['tasks']:
                if task['name'] not in cms_tasks.keys():
                    cms_contest['tasks'].append(task)

            # Reimport the contest in the db, with the previous ID.
            contest = Contest.import_from_dict(cms_contest)
            contest.id = self.contest_id
            session.add(contest)
            session.flush()

            logger.info("Analyzing database.")
            analyze_all_tables(session)
            session.commit()

        logger.info("Reimport of contest %s finished." % self.contest_id)

        return True
开发者ID:NorskInformatikkolympiade,项目名称:cms,代码行数:98,代码来源:YamlReimporter.py


注:本文中的cms.db.SQLAlchemyAll.Contest.get_from_id方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。