Ejemplo n.º 1
0
def import_urls(user, fresh_urls, mark_read):
    group = uuid()
    size = len(fresh_urls)
    for url in fresh_urls:
        async(subscribe_to_imported_url, user, url, mark_read, group=group)
    start = time.time()
    while True:
        # print("Time", time.time() - start, "count", count_group(group))
        if (time.time() - start) > IMPORT_WAIT:
            # print("TIME!")
            break
        if count_group(group) == size:
            # print("COUNT!")
            break
        time.sleep(1)
    import_results = Counter(result_group(group))
    pretty_results = ', '.join("{}: {}".format(*x) for x in import_results.items())
    num_added = import_results['added']
    num_existed = import_results['existed']
    num_errors = import_results['error']
    if num_added:
        async_messages.success(user, "Import complete - you subscribed to {sub} feed{s}.".format(sub=num_added, s=pluralize(num_added)))
    else:
        async_messages.info(user, "Import complete - no new subscriptions were added.")
    if num_existed:
        async_messages.info(user,
                            "You were already subscribed to {sub_exists} imported feed{s}.".format(sub_exists=num_existed, s=pluralize(num_existed)))
    if num_errors:
        async_messages.error(user, "There was an error subscribing to {errors} imported feed{s}.".format(errors=num_errors, s=pluralize(num_errors)))
    logger.info('User %(user)s OPML import complete - %(results)s', {'user': user, 'results': pretty_results})
    delete_group(group, tasks=True)
    return pretty_results
Ejemplo n.º 2
0
    def run(self, queue):
        """
        Get the comment and create/update/delete it
        """
        super(CommentEditJob, self).run(queue)

        gh = self.gh
        if not gh:
            return  # it's delayed !

        mode = self.mode.hget()

        try:
            comment = self.object
        except self.model.DoesNotExist:
            return None

        try:
            if mode == 'delete':
                comment.dist_delete(gh)
            else:
                comment = comment.dist_edit(mode=mode, gh=gh)
                if mode == 'create':
                    self.created_pk.hset(comment.pk)

        except ApiError, e:
            message = None

            if e.code == 422:
                message = u'Github refused to %s your comment on the %s on <strong>%s</strong>' % (
                    mode, self.obj_message_part(comment), comment.repository.full_name)

            elif e.code in (401, 403):
                tries = self.tries.hget()
                if tries and int(tries) >= 5:
                    message = u'You seem to not have the right to %s a comment on the %s on <strong>%s</strong>' % (
                        mode, self.obj_message_part(comment), comment.repository.full_name)

            if message:
                messages.error(self.gh_user, message)
                if mode == 'create':
                    comment.delete()
                else:
                    try:
                        comment.fetch(gh, force_fetch=True)
                    except ApiError:
                        pass
                return None

            else:
                raise
Ejemplo n.º 3
0
    def run(self, queue):
        """
        Get the label and create/update/delete it
        """
        super(LabelEditJob, self).run(queue)

        try:
            label = self.label
        except Label.DoesNotExist:
            # the label doesn't exist anymore, stop here
            self.status.hset(STATUSES.CANCELED)
            return None

        gh = self.gh
        if not gh:
            return  # it's delayed !

        mode = self.mode.hget()

        try:
            if mode == 'delete':
                label.dist_delete(gh)
            else:
                label.dist_edit(mode=mode, gh=gh)

        except ApiError, e:
            message = None

            if e.code == 422:
                message = u'Github refused to %s the label <strong>%s</strong> on <strong>%s</strong>' % (
                                mode, label.name, label.repository.full_name)

            elif e.code in (401, 403):
                tries = self.tries.hget()
                if tries and int(tries) >= 5:
                    message = u'You seem to not have the right to %s the label <strong>%s</strong> on <strong>%s</strong>' % (
                            mode, label.name, label.repository.full_name)

            if message:
                messages.error(self.gh_user, message)
                if mode == 'create':
                    label.delete()
                else:
                    try:
                        label.fetch(gh, force_fetch=True)
                    except ApiError:
                        pass
                return None

            else:
                raise
Ejemplo n.º 4
0
    def run(self, queue):
        """
        Get the issue and update it
        """
        super(BaseIssueEditJob, self).run(queue)

        gh = self.gh
        if not gh:
            return  # it's delayed !

        try:
            issue = self.issue
        except Issue.DoesNotExist:
            # the issue doesn't exist anymore, stop here
            self.status.hset(STATUSES.CANCELED)
            messages.error(self.gh_user, 'The issue you wanted to %s seems to have been deleted' % self.action_verb)
            return False

        try:
            issue = self.edited_issue = issue.dist_edit(mode=self.edit_mode, gh=gh, fields=self.editable_fields, values=self.values)
        except ApiError, e:
            message = None

            if e.code == 422:
                message = u'Github refused to %s the %s %s on <strong>%s</strong>' % (
                    self.action_verb, issue.type, self.get_issue_title_for_message(issue),
                    issue.repository.full_name)
                self.status.hset(STATUSES.CANCELED)

            elif e.code in (401, 403):
                tries = self.tries.hget()
                if tries and int(tries) >= 5:
                    message = u'You seem to not have the right to %s the %s %s on <strong>%s</strong>' % (
                        self.action_verb, issue.type, self.get_issue_title_for_message(issue),
                        issue.repository.full_name)
                    self.status.hset(STATUSES.CANCELED)

            if message:
                messages.error(self.gh_user, message)
                try:
                    # don't use "issue" cache
                    self.object.fetch(gh, force_fetch=True)
                except Exception:
                    pass
                return None

            else:
                raise
Ejemplo n.º 5
0
 def test_error(self):
     messages.error(self.user, "Hello")
     self.assertMessageOk(constants.ERROR)
Ejemplo n.º 6
0
def initialize_simulation(simulation_id):
    """
    Initialize the simulation (async Celery task).

    -Creates stocks
    -Creates a liquidity manager
    -Initialize the ticker
    -Creates opening transactions

    :param simulation: Simulation object
    :return: None
    """
    simulation = Simulation.objects.get(pk=simulation_id)
    msg_info = ""
    msg_error = ""
    if simulation.teams.count() == 0:
        messages.error(simulation.user, _("You need to select at least one team for the simulation!"))
    else:
        if simulation.simulation_type == Simulation.INTRO or simulation.simulation_type == Simulation.ADVANCED:
            msg_info += _("Initialization of simulation running...") + "<br />"
            # stocks creation
            print("Initialization of simulation running...")
            print("Create generic stocks")
            stocks = create_generic_stocks(simulation.id)
            if stocks > 0:
                msg_info += _("%s stocks were created..." % stocks) + "<br />"
                print("%s stocks created" % stocks)
            else:
                msg_error += _("No stocks were created!") + "<br />"

        elif simulation.simulation_type == Simulation.LIVE or simulation.simulation_type == Simulation.INDEXED:
            if simulation.simulation_type == Simulation.LIVE:
                full_clock = clock_erpsim(simulation.id, full=True)
                ticker = simulation.ticker
                ticker.nb_companies = full_clock['nb_teams']
                ticker.nb_rounds = full_clock['max_rounds']
                ticker.nb_days = full_clock['max_days']
                ticker.save()
                create_generic_stocks(simulation.id)
            else:
                game = create_mssql_simulation(simulation.id)
                ticker = simulation.ticker
                ticker.nb_companies = game['nb_teams']
                ticker.nb_rounds = game['max_rounds']
                ticker.nb_days = game['max_days']
                ticker.save()
                create_generic_stocks(simulation_id, symbols=game['list_of_teams'])

        if simulation.simulation_type in (Simulation.INTRO, Simulation.ADVANCED, Simulation.LIVE, Simulation.INDEXED):
            liquidity_manager = create_liquidity_manager(simulation.id)
            if liquidity_manager:
                msg_info += _("%s was created..." % liquidity_manager.name) + "<br />"
            else:
                msg_error += _("No liquidity manager was created!") + "<br />"

            # initialize ticker
            if simulation.simulation_type == Simulation.INTRO or simulation.simulation_type == Simulation.ADVANCED:
                for stock in simulation.stocks.all():
                    create_company_simulation(simulation.id, stock.id)

            elif simulation.simulation_type == Simulation.LIVE or simulation.simulation_type == Simulation.INDEXED:
                for stock in simulation.stocks.all():
                    create_company_live(simulation.id, stock.id)

            # opening transactions (gives cash and stock to each team)
            print("Process openings...............")
            process_opening_transactions(simulation.id)

            if msg_info != "":
                msg_info += _("Initialization succeeded! You can start running the simulation.")
                messages.info(simulation.user, msg_info)
            if msg_error != "":
                msg_error += _("There were errors during the initialization process!")
                messages.error(simulation.user, msg_error)

        else:
            messages.error(simulation.user, _("Initialization of simulation failed!"))
Ejemplo n.º 7
0
def initialize_simulation(simulation_id):
    """
    Initialize the simulation (async Celery task).

    -Creates stocks
    -Creates a liquidity manager
    -Initialize the ticker
    -Creates opening transactions

    :param simulation: Simulation object
    :return: None
    """
    simulation = Simulation.objects.get(pk=simulation_id)
    msg_info = ""
    msg_error = ""
    if simulation.teams.count() == 0:
        messages.error(
            simulation.user,
            _("You need to select at least one team for the simulation!"))
    else:
        if simulation.simulation_type == Simulation.INTRO or simulation.simulation_type == Simulation.ADVANCED:
            msg_info += _("Initialization of simulation running...") + "<br />"
            # stocks creation
            print("Initialization of simulation running...")
            print("Create generic stocks")
            stocks = create_generic_stocks(simulation.id)
            if stocks > 0:
                msg_info += _("%s stocks were created..." % stocks) + "<br />"
                print("%s stocks created" % stocks)
            else:
                msg_error += _("No stocks were created!") + "<br />"

        elif simulation.simulation_type == Simulation.LIVE or simulation.simulation_type == Simulation.INDEXED:
            if simulation.simulation_type == Simulation.LIVE:
                full_clock = clock_erpsim(simulation.id, full=True)
                ticker = simulation.ticker
                ticker.nb_companies = full_clock['nb_teams']
                ticker.nb_rounds = full_clock['max_rounds']
                ticker.nb_days = full_clock['max_days']
                ticker.save()
                create_generic_stocks(simulation.id)
            else:
                game = create_mssql_simulation(simulation.id)
                ticker = simulation.ticker
                ticker.nb_companies = game['nb_teams']
                ticker.nb_rounds = game['max_rounds']
                ticker.nb_days = game['max_days']
                ticker.save()
                create_generic_stocks(simulation_id,
                                      symbols=game['list_of_teams'])

        if simulation.simulation_type in (Simulation.INTRO,
                                          Simulation.ADVANCED, Simulation.LIVE,
                                          Simulation.INDEXED):
            liquidity_manager = create_liquidity_manager(simulation.id)
            if liquidity_manager:
                msg_info += _(
                    "%s was created..." % liquidity_manager.name) + "<br />"
            else:
                msg_error += _("No liquidity manager was created!") + "<br />"

            # initialize ticker
            if simulation.simulation_type == Simulation.INTRO or simulation.simulation_type == Simulation.ADVANCED:
                for stock in simulation.stocks.all():
                    create_company_simulation(simulation.id, stock.id)

            elif simulation.simulation_type == Simulation.LIVE or simulation.simulation_type == Simulation.INDEXED:
                for stock in simulation.stocks.all():
                    create_company_live(simulation.id, stock.id)

            # opening transactions (gives cash and stock to each team)
            print("Process openings...............")
            process_opening_transactions(simulation.id)

            if msg_info != "":
                msg_info += _(
                    "Initialization succeeded! You can start running the simulation."
                )
                messages.info(simulation.user, msg_info)
            if msg_error != "":
                msg_error += _(
                    "There were errors during the initialization process!")
                messages.error(simulation.user, msg_error)

        else:
            messages.error(simulation.user,
                           _("Initialization of simulation failed!"))
 def test_error(self):
     messages.error(self.user, "Hello")
     self.assertMessageOk(constants.ERROR)