Example #1
0
def procedure(name, weight=1, monitor=None, debug=True):
    timer = None
    if debug:
        timer = Timer('Fetching Variables')
    data = BNSearch(name)
    if debug:
        print timer.stop()
        timer = Timer('Calculate Scores')
    data.score = ScoreBuilder(data.data, data.variables)(data.name)
    if debug:
        print timer.stop()

    # timer = Timer('Build Parent Graphs')
    # data.best_score = ParentBuilder(data)()
    # print timer.stop()

    if not monitor:
        monitor = Monitor(name)

    if debug:
        timer = Timer('Search')
    killed = False
    score = 1e99
    try:
        score = data.search(weight, monitor=monitor)
    except NotImplementedError, e:
        print 'Procedure {}:{} died with message: {}'.format(
            name, weight, e.message)
        killed = True
Example #2
0
def join_quiz(quiz_id, user_id=None):
    ## Get user from request
    if request:
        user = User.query.get(request.form['user_id'])
    else:
        user = User.query.get(user_id)
    quiz = Quiz.query.get(quiz_id)
    if Timer.query.filter(Timer.quiz_id == quiz_id).filter(
            Timer.user_id == user.id).first() is None:
        timer = Timer(quiz_id=quiz_id,
                      user_id=user.id,
                      last_answered=datetime.now())
        db.session.add(timer)

    if Response.query.filter(Response.quiz_id == quiz_id).filter(
            Response.user_id == user.id).first() is None:
        ## Create responses for user
        for index in range(0, 10):
            questions = json.loads(quiz.questions)
            response = Response(question_id=questions[index],
                                user_id=user.id,
                                quiz_id=quiz_id)
            db.session.add(response)

    ## Store responses for user
    db.session.commit()
    status_dict = dict()
    status_dict['status'] = 'JOINED'
    status_dict['quiz_id'] = quiz_id
    return jsonify(status_dict)
Example #3
0
File: main.py Project: pgsvox/bot
    async def timer(self, message, stripped, prefs):

        owner: int = message.guild.id

        if message.guild is None:
            owner = message.author.id

        if stripped == 'list':
            timers = session.query(Timer).filter(Timer.owner == owner)

            e = discord.Embed(title='Timers')
            for timer in timers:
                delta = int(unix_time() - timer.start_time)
                minutes, seconds = divmod(delta, 60)
                hours, minutes = divmod(minutes, 60)
                e.add_field(name=timer.name, value="{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds))

            await message.channel.send(embed=e)

        elif stripped.startswith('start'):
            timers = session.query(Timer).filter(Timer.owner == owner)

            if timers.count() >= 25:
                await message.channel.send(prefs.language.get_string('timer/limit'))

            else:
                n = stripped.split(' ')[1:2] or 'New timer #{}'.format(timers.count() + 1)

                if len(n) > 32:
                    await message.channel.send(prefs.language.get_string('timer/name_length').format(len(n)))

                elif n in [x.name for x in timers]:
                    await message.channel.send(prefs.language.get_string('timer/unique'))

                else:
                    t = Timer(name=n, owner=owner)
                    session.add(t)

                    session.commit()

                    await message.channel.send(prefs.language.get_string('timer/success'))

        elif stripped.startswith('delete '):

            n = ' '.join(stripped.split(' ')[1:])

            timers = session.query(Timer).filter(Timer.owner == owner).filter(Timer.name == n)

            if timers.count() < 1:
                await message.channel.send(prefs.language.get_string('timer/not_found'))

            else:
                timers.delete(synchronize_session='fetch')
                await message.channel.send(prefs.language.get_string('timer/deleted'))

                session.commit()

        else:
            await message.channel.send(prefs.language.get_string('timer/help'))
Example #4
0
def procedure(name, weight=1, monitor=None, debug=True):
    timer = None
    if debug:
        timer = Timer('Fetching Variables')
    data = BNSearch(name)
    if debug:
        print timer.stop()
        timer = Timer('Calculate Scores')
    data.score = ScoreBuilder(data.data, data.variables)(data.name)
    if debug:
        print timer.stop()

    # timer = Timer('Build Parent Graphs')
    # data.best_score = ParentBuilder(data)()
    # print timer.stop()

    if not monitor:
        monitor = Monitor(name)

    if debug:
        timer = Timer('Search')
    killed = False
    score = 1e99
    try:
        score = data.search(weight, monitor=monitor)
    except NotImplementedError, e:
        print 'Procedure {}:{} died with message: {}'.format(
            name, weight, e.message
        )
        killed = True
Example #5
0
class TestTimer(unittest.TestCase):
    def setUp(self):
        self.fn = Mock()
        self.kwargs = {'hello': 'world'}
        self.timer = Timer(5000, self.fn, **self.kwargs)

    def test_should_run_fn_on_first_tick(self):
        self.timer.tick()
        self.fn.assert_called_once_with(**self.kwargs)

    def test_tick_not_run_before_delay(self):
        self.timer.tick()
        self.timer.tick()
        self.fn.assert_called_once_with(**self.kwargs)

    @patch('models.datetime')
    def test_tick_run_after_delay(self, datetime_mock):
        datetime_mock.datetime.now.side_effect = [
            datetime.datetime.now(),
            datetime.datetime.now(),
            datetime.datetime.now() + datetime.timedelta(days=1),
            datetime.datetime.now()
        ]
        self.timer.tick()
        self.timer.tick()
        assert self.fn.call_count == 2
        expected = [call(**self.kwargs), call(**self.kwargs)]
        assert self.fn.call_args_list == expected
Example #6
0
    async def get_overdue_timers(self, time_border: datetime) -> List[Timer]:
        """
        Return timers with next_start date < time_border date

        :return: List of timers (possibly empty)
        """
        request = """
            SELECT * FROM timer
            WHERE next_start < $1
        """

        overdue_timers = await self.engine.make_fetch_rows(
            request, time_border)
        result = [Timer(**x) for x in overdue_timers]
        return result
Example #7
0
    async def get_nearest_timer(self,
                                time_border: datetime) -> Optional[Timer]:
        request = """
            SELECT * FROM timer
            WHERE next_start = (
                SELECT MIN(next_start) FROM timer
                WHERE next_start > $1
            );
        """

        answer = await self.engine.make_fetch_rows(request, time_border)
        if not answer:
            return None
        answer = answer[0]
        answer = Timer(**answer)
        return answer
Example #8
0
def add_timer_view(request):
    logger.debug("add_timer_view called by user %s" % request.user)
    if request.method == 'POST':
        form = TimerForm(request.POST)
        logger.debug("Request type POST contains form valid: %s" % form.is_valid())
        if form.is_valid():
            # Get character
            auth_info = AuthServicesInfoManager.get_auth_service_info(request.user)
            character = EveManager.get_character_by_id(auth_info.main_char_id)
            corporation = EveManager.get_corporation_info_by_id(character.corporation_id)
            logger.debug("Determined timer add request on behalf of character %s corporation %s" % (character, corporation))
            # calculate future time
            future_time = datetime.timedelta(days=form.cleaned_data['days_left'], hours=form.cleaned_data['hours_left'], minutes=form.cleaned_data['minutes_left'])
            current_time = timezone.now()
            eve_time = current_time + future_time
            logger.debug("Determined timer eve time is %s - current time %s, adding %s" % (eve_time, current_time, future_time))
            # handle valid form
            timer = Timer()
            timer.details = form.cleaned_data['details']
            timer.system = form.cleaned_data['system']
            timer.planet_moon = form.cleaned_data['planet_moon']
            timer.structure = form.cleaned_data['structure']
            timer.objective = form.cleaned_data['objective']
            timer.eve_time = eve_time
            timer.important = form.cleaned_data['important']
            timer.corp_timer = form.cleaned_data['corp_timer']
            timer.eve_character = character
            timer.eve_corp = corporation
            timer.user = request.user
            timer.save()
            logger.info("Created new timer in %s at %s by user %s" % (timer.system, timer.eve_time, request.user))
            return HttpResponseRedirect("/timers/")
    else:
        logger.debug("Returning new TimerForm")
        form = TimerForm()

    render_items = {'form': form}

    return render_to_response('registered/addtimer.html', render_items, context_instance=RequestContext(request))
Example #9
0
def add_timer_view(request):
    if request.method == 'POST':
        form = TimerForm(request.POST)

        if form.is_valid():
            # Get character
            auth_info = AuthServicesInfoManager.get_auth_service_info(request.user)
            character = EveManager.get_character_by_id(auth_info.main_char_id)
            corporation = EveManager.get_corporation_info_by_id(character.corporation_id)

            # calculate future time
            future_time = datetime.timedelta(days=form.cleaned_data['days_left'], hours=form.cleaned_data['hours_left'], minutes=form.cleaned_data['minutes_left'])
            current_time = datetime.datetime.utcnow()
            eve_time = current_time + future_time

            # handle valid form
            timer = Timer()
            timer.details = form.cleaned_data['details']
            timer.system = form.cleaned_data['system']
            timer.planet_moon = form.cleaned_data['planet_moon']
            timer.structure = form.cleaned_data['structure']
            timer.objective = form.cleaned_data['objective']
            timer.eve_time = eve_time
            timer.important = form.cleaned_data['important']
            timer.eve_character = character
            timer.eve_corp = corporation
            timer.user = request.user
            timer.save()
            return HttpResponseRedirect("/timers/")
    else:
        form = TimerForm()

    render_items = {'form': form}

    return render_to_response('registered/addtimer.html', render_items, context_instance=RequestContext(request))
Example #10
0
def add_timer_view(request):
    if request.method == 'POST':
        form = TimerForm(request.POST)

        if form.is_valid():
            # Get character
            auth_info = AuthServicesInfoManager.get_auth_service_info(request.user)
            character = EveManager.get_character_by_id(auth_info.main_char_id)
            corporation = EveManager.get_corporation_info_by_id(character.corporation_id)

            # handle valid form
            timer = Timer()
            timer.name = form.cleaned_data['name']
            timer.system = form.cleaned_data['system']
            timer.planet_moon = form.cleaned_data['planet_moon']
            timer.structure = form.cleaned_data['structure']
            timer.fleet_type = form.cleaned_data['fleet_type']
            timer.eve_time = form.cleaned_data['eve_time']
            timer.important = form.cleaned_data['important']
            timer.eve_character = character
            timer.eve_corp = corporation
            timer.user = request.user
            timer.save()
            return HttpResponseRedirect("/timers/")
    else:
        form = TimerForm()

    render_items = {'form': form}

    return render_to_response('registered/addtimer.html', render_items, context_instance=RequestContext(request))
Example #11
0
def add_timer_view(request):
    logger.debug("add_timer_view called by user %s" % request.user)
    if request.method == 'POST':
        form = TimerForm(request.POST)
        logger.debug("Request type POST contains form valid: %s" %
                     form.is_valid())
        if form.is_valid():
            # Get character
            auth_info = AuthServicesInfoManager.get_auth_service_info(
                request.user)
            character = EveManager.get_character_by_id(auth_info.main_char_id)
            corporation = EveManager.get_corporation_info_by_id(
                character.corporation_id)
            logger.debug(
                "Determined timer add request on behalf of character %s corporation %s"
                % (character, corporation))
            # calculate future time
            future_time = datetime.timedelta(
                days=form.cleaned_data['days_left'],
                hours=form.cleaned_data['hours_left'],
                minutes=form.cleaned_data['minutes_left'])
            current_time = timezone.now()
            eve_time = current_time + future_time
            logger.debug(
                "Determined timer eve time is %s - current time %s, adding %s"
                % (eve_time, current_time, future_time))
            # handle valid form
            timer = Timer()
            timer.details = form.cleaned_data['details']
            timer.system = form.cleaned_data['system']
            timer.planet_moon = form.cleaned_data['planet_moon']
            timer.structure = form.cleaned_data['structure']
            timer.objective = form.cleaned_data['objective']
            timer.eve_time = eve_time
            timer.important = form.cleaned_data['important']
            timer.corp_timer = form.cleaned_data['corp_timer']
            timer.eve_character = character
            timer.eve_corp = corporation
            timer.user = request.user
            timer.save()
            logger.info("Created new timer in %s at %s by user %s" %
                        (timer.system, timer.eve_time, request.user))
            return HttpResponseRedirect("/timers/")
    else:
        logger.debug("Returning new TimerForm")
        form = TimerForm()

    render_items = {'form': form}

    return render_to_response('registered/addtimer.html',
                              render_items,
                              context_instance=RequestContext(request))
Example #12
0
def add_timer_view(request):
    if request.method == 'POST':
        form = TimerForm(request.POST)

        if form.is_valid():
            # Get character
            auth_info = AuthServicesInfoManager.get_auth_service_info(
                request.user)
            character = EveManager.get_character_by_id(auth_info.main_char_id)
            corporation = EveManager.get_corporation_info_by_id(
                character.corporation_id)

            # handle valid form
            timer = Timer()
            timer.name = form.cleaned_data['name']
            timer.system = form.cleaned_data['system']
            timer.planet_moon = form.cleaned_data['planet_moon']
            timer.structure = form.cleaned_data['structure']
            timer.fleet_type = form.cleaned_data['fleet_type']
            timer.eve_time = form.cleaned_data['eve_time']
            timer.important = form.cleaned_data['important']
            timer.eve_character = character
            timer.eve_corp = corporation
            timer.user = request.user
            timer.save()
            return HttpResponseRedirect("/timers/")
    else:
        form = TimerForm()

    render_items = {'form': form}

    return render_to_response('registered/addtimer.html',
                              render_items,
                              context_instance=RequestContext(request))
Example #13
0
    def fill_context(self):
        data = self.request.POST or None
        instance = self.note
        if self.action == 'edit':
            self.attachment_formset = forms.AttachmentFormSet(
                data,
                self.request.FILES or None,
                instance=self.note,
                prefix='attachment')
        elif self.action == 'add_comment':
            old_description = instance.description
            instance.description = ''
        elif self.action == 'new':
            instance = Note(auteur_employe=self.employe,
                            demandeur_employe=self.employe,
                            type_note_id=4,
                            etat_note_id=1,
                            description='',
                            parent=self.note)
        else:
            raise NotImplemented
        if instance.pk:
            try:
                timer = Timer.objects.get(
                    note=instance, employe=self.employe,
                    effective_date=datetime.today())
            except Timer.DoesNotExist:
                timer = Timer(note=instance)
            self.timer_form = forms.TimerForm(instance=timer)

        self.form = self.FormClass(
            context=self.note,
            data=data,
            instance=instance,
            prefix=str(self.note.uid),
            is_superuser=self.authenticated_user.is_superuser
        )
        if data:
            is_valid = True
            if self.attachment_formset:
                if self.attachment_formset.is_valid():
                    self.attachment_formset.save()
                else:
                    is_valid = False
            if self.form.is_valid():
                if self.action == 'add_comment':
                    comment = self.form.cleaned_data['description']
                    self.form.instance.description = '%s\n' \
                        '<div class="group"><h6>%s %s</h6>\n' \
                        '<p>%s</p>\n' \
                        '</div><br/>' % (old_description,
                                         self.request.user, date(
                                             datetime.now(), "r"),
                                         comment)
                self.form.save(self.authenticated_user)

                timer, created = Timer.objects.get_or_create(
                    note=self.form.instance, employe=self.employe,
                    effective_date=datetime.today())
                timer.save()
                self.context['uid'] = self.form.instance.parent_id
            else:
                is_valid = False
            if is_valid:
                self.form.instance.notify_modifs()
                self.template = 'notesgroup/module_note_detail_list.html'
                self.done_message = True
                if self.action == 'new':
                    self.new = True
                    self.note = self.form.instance
                else:
                    self.new = False
Example #14
0
    async def list_timers(self, username: str) -> List[Timer]:
        request = "SELECT * FROM timer WHERE username = ($1)"

        timers = await self.engine.make_fetch_rows(request, username)
        return [Timer(**x) for x in timers]
Example #15
0
 def setUp(self):
     self.fn = Mock()
     self.kwargs = {'hello': 'world'}
     self.timer = Timer(5000, self.fn, **self.kwargs)