Exemple #1
0
 def GET(self):
     resp = client.request1('/account/notification', 'GET', {'mode': 'lite'})
     data = json.loads(resp.read())
     amount = data['mentions']
     count = 60 if amount > 20 else 20
     pages = amount / count + 2
     for page in range(1, pages):
         body = {'count': count, 'page': page, 'mode': 'lite'}
         resp = client.request1('/statuses/mentions', 'GET', body)
         for item in json.loads(resp.read()):
             act = self.argv(item['text'])
             user_id = item['user']['id']
             user_name = item['user']['name']
             if store.sent.select(item['id']):
                 continue
             if act == '-join' and not store.user.select(user_id):
                 store.user.insert(user_id, user_name)
                 store.sent.insert(item['id'])
                 body = (user_id, user_name, act)
                 add_task(web.ctx, '/poems/info', json.dumps(body))
             elif act == '-quit' and store.user.select(user_id):
                 store.user.delete(user_id)
                 store.sent.insert(item['id'])
                 body = (user_id, user_name, act)
                 add_task(web.ctx, '/poems/info', json.dumps(body))
Exemple #2
0
def test(r, n, p):
	def _internal(t, r):
		p=t.data[1]
		n=t.data[0]
		r.screen.draw_line(n["color"], p.get_center(), p.parent.targeted.rotated_rect.center, n["thickness"])
	tasks.add_task(r, "render_last", tasks.Task(_internal, n["duration"], (n, p)))
	return True
Exemple #3
0
    def run_in_ship(self, ship):
        #print "called in ship"
        def _internalab(t, r):
            t.data[0].play()
            t.data[0].blit(r.screen, (t.data[1][0], t.data[1][1]))

        def _internalde(t, r):
            if t.delete:
                tasks.add_task(
                    self.root, "render_after_entities",
                    tasks.Task(self.root, _internalab,
                               self.config["style"]["sum_duration"], t.data))

        ax = ship.rotated_rect.centerx + random.choice(
            xrange(int(-ship.rotated_rect.size[0] / 2),
                   int(ship.rotated_rect.size[0] /
                       2))) - self.config["style"].get("offset", [0, 0])[0]
        ay = ship.rotated_rect.centery + random.choice(
            xrange(int(-ship.rotated_rect.size[1] / 2),
                   int(ship.rotated_rect.size[1] /
                       2))) - self.config["style"].get("offset", [0, 0])[1]

        built_array = []
        for i in self.config["style"]["frames"]:
            built_array.append([self.root.gamedb(i[0]), i[1]])
        animation = pyganim.PygAnimation(built_array, loop=0)
        #animation.play()

        tasks.add_task(
            self.root, "render_last",
            tasks.Task(self.root, _internalde, self.config["time"],
                       (animation, [ax, ay])))
Exemple #4
0
def test_update():
    """
    test updating a record
    """
    tasks.add_task(datetime.date(2020, 4, 1), "Wake up")
    tasks.edit_task(datetime.date(2020, 4, 1), 1, "Make coffee")
    assert tasks.get_task(datetime.date(2020, 4, 1), 0) == "Make coffee"
Exemple #5
0
 def GET(self):
     resp = utils.client.request1('/account/notification', 'GET', {'mode': 'lite'})
     data = json.loads(resp.read())
     if data['direct_messages']:
         add_task(web.ctx, '/whale/learn', 'to learn')
     if data['mentions']:
         add_task(web.ctx, '/whale/talk', str(data['mentions']))
    def run_in_ship(self, ship):
        def _internal(t, r):
            r.screen.blit(t.data[1], t.data[0])

        tasks.add_task(
            self.root, "render_before_particles",
            tasks.Task(self.root, _internal, self.config["time"],
                       (ship.rotated_rect.copy(), ship.rotated_image.copy())))
Exemple #7
0
 def GET(self):
     last_call = store.ctx.last_call or 0
     if time.time() - last_call < 600: return
     
     if utils.stage() != store.ctx.stage:
         add_task(web.ctx, '/whale/hello', utils.stage())
     if utils.stage() != 'sleep':
         add_task(web.ctx, '/whale/greet', utils.stage())
Exemple #8
0
def test_list():
    """
    test cursor.fetchall()
    """
    # tasks.add_task(datetime.date(2020, 4, 1), "Wake up")
    tasks.add_task(datetime.date(2020, 4, 1), "Make coffee")
    assert tasks.list_task(datetime.date(2020, 4,
                                         1)) == ["Wake up", "Make coffee"]
Exemple #9
0
def test_list_tasks(client):
    task1_key = tasks.add_task(client, 'Test task 1')
    task2_key = tasks.add_task(client, 'Test task 2')

    @backoff.on_exception(backoff.expo, AssertionError, max_time=120)
    def _():
        task_list = tasks.list_tasks(client)
        assert [x.key for x in task_list] == [task1_key, task2_key]
def test_list_tasks(client):
    task1_key = tasks.add_task(client, 'Test task 1')
    task2_key = tasks.add_task(client, 'Test task 2')

    @eventually_consistent.call
    def _():
        task_list = tasks.list_tasks(client)
        assert [x.key for x in task_list] == [task1_key, task2_key]
def test_list_tasks(client):
    task1_key = tasks.add_task(client, 'Test task 1')
    task2_key = tasks.add_task(client, 'Test task 2')

    @eventually_consistent.call
    def _():
        task_list = tasks.list_tasks(client)
        assert [x.key for x in task_list] == [task1_key, task2_key]
    def run(self):
        def _internalsx(t, r):
            if t.delete:
                r.gamedb.get_asset(t.data).play()

        tasks.add_task(
            self.root, "render_last",
            tasks.Task(self.root, _internalsx, self.config["time"],
                       self.config["sound"]))
Exemple #13
0
	def do_screen_flash_end(self):
		DURATION=0.4
		EXPONENT=2.2
		def _internal(t, r):
			surf=pygame.Surface((1300,700))
			surf.fill(pygame.Color(255,255,255))
			surf.set_alpha(255-((t.curr_time**EXPONENT)*(255/DURATION**EXPONENT)))
			r.screen.screen.blit(surf, (0,0))
		tasks.add_task(self.root, "render_last", tasks.Task(self.root, _internal, DURATION))
Exemple #14
0
 def GET(self):
     now, path = datetime.datetime.now(UTC(8)), None
     if now.hour == 8 and now.minute < 5:
         path = '/poems/send'
     elif now.hour == 4 and now.minute < 5:
         path = '/poems/update'
         
     if path:
         for item in store.user.fetchall().items():
             add_task(web.ctx, path, json.dumps(item))
Exemple #15
0
 def POST(self):
     amount = int(web.data())
     count = 60 if amount > 20 else 20
     pages = amount / count + 2
     for page in range(1, pages):
         body = {'count': count, 'page': page, 'mode': 'lite'}
         resp = utils.client.request1('/statuses/mentions', 'GET', body)
         data = json.loads(resp.read())
         for body in self.filter(data):
             add_task(web.ctx, '/whale/send', json.dumps(body))
Exemple #16
0
def test(r, n, p):
    def _internal(t, r):
        p = t.data[1]
        n = t.data[0]
        r.screen.draw_line(n["color"], p.get_center(),
                           ship2.rotated_rect.center, n["thickness"])

    tasks.add_task(r, "render_last",
                   tasks.Task(_internal, n["duration"], (n, p)))
    return True
def test_format_tasks(client):
    task1_key = tasks.add_task(client, 'Test task 1')
    tasks.add_task(client, 'Test task 2')
    tasks.mark_done(client, task1_key.id)

    output = tasks.format_tasks(tasks.list_tasks(client))

    assert 'Test task 1' in output
    assert 'Test task 2' in output
    assert 'done' in output
    assert 'created' in output
def add_task():
    if request.method == 'POST':
        # For debugging
        print request.data
        if request.data:
            data = request.data.split()
            return tasks.add_task(data[0], data[1], data[2])
        else:
            body = request.form['body']
            group_id = request.form['group_id']
            due_date = request.form['due_date']
            return tasks.add_task(group_id, body, due_date)
    return utils.json_message("not supposed to happen")
def test_format_tasks(client):
    task1_key = tasks.add_task(client, 'Test task 1')
    tasks.add_task(client, 'Test task 2')
    tasks.mark_done(client, task1_key.id)

    @eventually_consistent.call
    def _():
        output = tasks.format_tasks(tasks.list_tasks(client))

        assert 'Test task 1' in output
        assert 'Test task 2' in output
        assert 'done' in output
        assert 'created' in output
	def run_in_ship(self, ship):
		def _internalde(t,r):
			if t.delete:
				t.root.particlemanager.add_particles(particles.make_explosion_cfg(t.root,
					t.data[0], t.data[1], t.data[2]))

		ax=ship.rotated_rect.centerx+random.choice(xrange(int(-ship.rotated_rect.size[0]/2), int(ship.rotated_rect.size[0]/2)))
		ay=ship.rotated_rect.centery+random.choice(xrange(int(-ship.rotated_rect.size[1]/2), int(ship.rotated_rect.size[1]/2)))

		tasks.add_task(self.root, "render_last", tasks.Task(self.root, _internalde, self.config["time"], (
			ax,
			ay,
			self.config["style"])))
def test_format_tasks(client):
    task1_key = tasks.add_task(client, 'Test task 1')
    tasks.add_task(client, 'Test task 2')
    tasks.mark_done(client, task1_key.id)

    @eventually_consistent.call
    def _():
        output = tasks.format_tasks(tasks.list_tasks(client))

        assert 'Test task 1' in output
        assert 'Test task 2' in output
        assert 'done' in output
        assert 'created' in output
def test_format_tasks(client):
    task1_key = tasks.add_task(client, "Test task 1")
    tasks.add_task(client, "Test task 2")
    tasks.mark_done(client, task1_key.id)

    @eventually_consistent.call
    def _():
        output = tasks.format_tasks(tasks.list_tasks(client))

        assert "Test task 1" in output
        assert "Test task 2" in output
        assert "done" in output
        assert "created" in output
Exemple #23
0
def days_of_the_week_handler(update, context):
    # Get user id and user language
    user_id = update.message.from_user.id
    language = get_user_language(user_id=user_id, short=True)

    # Check pushed button of keyboard
    pushed_button = check_button(update, KEYBOARDS["static"]["cancel_back"],
                                 language)

    # If pushed button is "cancel" exit user from conversation
    if pushed_button == "cancel":
        return exit_from_conversation(update)

    # If pushed button is "back" return user to previous
    # stage of task adding - write task title
    if pushed_button == "back":
        update.message.reply_text(get_message("write_task_title", language),
                                  reply_markup=get_menu_keyboard(
                                      "cancel", language))

        return "title_handler"

    # Get days of the week from user message
    days_of_the_week_str = get_days_of_the_week_from_string(
        update.message.text, language)

    # Check if message is incorrect
    if not days_of_the_week_str:
        update.message.reply_text(get_message("invalid_input", language))
        return "days_of_the_week_handler"

    # Load days of the week to context.user_data for new task
    context.user_data["new_task"]["days_of_the_week"] = days_of_the_week_str

    # Get data from context.user_data
    new_task_data = context.user_data["new_task"]

    # Add new task to database
    add_task(user_id, new_task_data["title"],
             new_task_data["days_of_the_week"])

    # Clear context.user_data for new task
    context.user_data["new_task"] = {}

    # Send message to user about successful adding
    update.message.reply_text(get_message("task_added", language))

    # Exit from conversation
    return exit_from_conversation(update)
Exemple #24
0
def test_format_tasks(client):
    task1_key = tasks.add_task(client, 'Test task 1')
    tasks.add_task(client, 'Test task 2')
    tasks.mark_done(client, task1_key.id)

    @backoff.on_exception(backoff.expo, AssertionError, max_time=120)
    def run_sample():
        output = tasks.format_tasks(tasks.list_tasks(client))

        assert 'Test task 1' in output
        assert 'Test task 2' in output
        assert 'done' in output
        assert 'created' in output

    run_sample()
Exemple #25
0
    def run_in_item(self, item):
        def _internal(t, r):
            p = t.data[1]
            n = t.data[0]
            try:
                r.screen.draw_line(
                    n["color"], t.data[1].get_center(),
                    t.data[1].parent.targeted.rotated_rect.center,
                    n["thickness"])
            except BaseException:
                pass

        tasks.add_task(
            self.root, "render_last",
            tasks.Task(self.root, _internal, self.config["duration"],
                       (self.config, item)))
Exemple #26
0
def main(argv) -> int:
    logging.addLevelName(logging.INFO+5, 'NOTICE')
    logging.basicConfig()

    log_level = os.environ.get('PYTHONLOGLEVEL', str(logging.INFO))
    try:
        log_level = int(log_level)
    except ValueError:
        pass
    logging.root.setLevel(log_level)

    attributes = {'user': argv[1], 'url': argv[2]}
    if not attributes['url'].endswith('/'):
        attributes['url'] += '/'

    logger.info('Fetching tickets from WebDesk...')
    tickets = webdesk.get_tickets(attributes)

    tw = tasks.get_tw()
    logger.debug('Getting tickets from TaskWarrior...')
    tasks_ = tasks.get_tasks(tw)

    new_tasks = tickets.keys() - tasks_.keys()
    existing_tasks = tickets.keys() & tasks_.keys()
    missing_tasks = tasks_.keys() - tickets.keys()
    logger.info('%d new, %d existing and %d missing tasks', len(new_tasks), len(existing_tasks), len(missing_tasks))

    for k in new_tasks:
        tasks.add_task(tw, tickets[k]['task'])

    for k in existing_tasks:
        tickets[k]['task']['webdesk_unhide'] = 1
        tasks.update_task(tw, tickets[k]['task'])

    if missing_tasks:
        logger.info('Fetching missing tickets from WebDesk...')
    missing_tickets = webdesk.get_tickets(attributes, {k: v for k, v in tasks_.items() if k in missing_tasks})
    for k, v in missing_tickets.items():
        v['task']['webdesk_hidden'] = 1
        tasks.update_task(tw, v['task'])

        if v['task']['webdesk_status'] == 'Closed':
            tasks.complete_task(tw, v['task'])

    return 0
Exemple #27
0
    def event_state(self, state, event):
        if event.type == pygame.USEREVENT:
            if event.sg_type == triggers.UE_SHL_DAMAGE_DEALT:
                if event.system.shields > 30:
                    if not event.x:
                        event.x, event.y = event.source.rotated_rect.center

                    # dx =  - event.source.rotated_rect.centerx - event.x
                    # dy =  - event.source.rotated_rect.centery - event.y

                    angle = get_angle(event.system.ship.rotated_rect.centerx,
                                      event.x,
                                      event.system.ship.rotated_rect.centery,
                                      event.y)

                    orig_image = pygame.transform.scale(
                        absroot.gamedb("image_shield_hit_default"),
                        (event.system.ship.rotated_rect.width + 30,
                         event.system.ship.rotated_rect.height + 30))

                    def _(t, r):
                        orig_rect = pygame.Rect((0, 0), orig_image.get_size())
                        orig_rect.center = (
                            event.system.ship.rotated_rect.centerx,
                            event.system.ship.rotated_rect.centery)

                        rot_image, rot_rect = rot_center(
                            orig_image, orig_rect, angle)
                        absroot.screen.blit(rot_image, rot_rect)

                    tasks.add_task(self.root, "render_after_entities",
                                   tasks.Task(absroot, _, 2))
            if event.sg_type == triggers.UE_SHIELDS_DOWN:
                if absroot.game_time - self.last_shields_warning > 10:
                    self.last_shields_warning = absroot.game_time
                    if (event.system.ship ==
                            absroot.state_manager.getcurr().player):
                        absroot.gamedb("snd_shelds_down_warning_player").play()
            if event.sg_type == triggers.UE_HUL_DAMAGE_DEALT:
                if absroot.game_time - self.last_hull_warning > 10:
                    if event.system.hull < 20:
                        self.last_hull_warning = absroot.game_time
                        if (event.system.ship ==
                                absroot.state_manager.getcurr().player):
                            absroot.gamedb("snd_hull_breach_player").play()
    def run_in_ship(self, ship):
        def _internalde(t, r):
            if t.delete:
                t.root.particlemanager.add_particles(
                    particles.make_explosion_cfg(t.root, t.data[0], t.data[1],
                                                 t.data[2]))

        ax = ship.rotated_rect.centerx + random.choice(
            xrange(int(-ship.rotated_rect.size[0] / 2),
                   int(ship.rotated_rect.size[0] / 2)))
        ay = ship.rotated_rect.centery + random.choice(
            xrange(int(-ship.rotated_rect.size[1] / 2),
                   int(ship.rotated_rect.size[1] / 2)))

        tasks.add_task(
            self.root, "render_last",
            tasks.Task(self.root, _internalde, self.config["time"],
                       (ax, ay, self.config["style"])))
Exemple #29
0
    def run_in_impact(self, item, impacted, projectile):
        def _internal(t, r):
            t.data[0].blit(r.screen, (t.data[1][0], t.data[1][1]))

        built_array = []
        for i in self.config["style"]["frames"]:
            built_array.append([self.root.gamedb(i[0]), i[1]])
        animation = pyganim.PygAnimation(built_array, loop=0)
        animation.play()
        x = projectile.rigidbody.x - self.config["style"].get(
            "offset", [0, 0])[0]
        y = projectile.rigidbody.y - self.config["style"].get(
            "offset", [0, 0])[1]
        tasks.add_task(
            self.root, "render_after_entities",
            tasks.Task(self.root, _internal,
                       self.config["style"]["sum_duration"],
                       (animation, [x, y])))
Exemple #30
0
 def set_timer(self, timestring, nick, host, message=None, targeted=0):
     t = timestring.split(':')  # [h,m,s]
     if not self.timestring_OK(t, True):
         raise TimeFormatException(timestring)
     elif len(t) == 3:
         time = dt.now() + datetime.timedelta(hours=int(t[0]), minutes=int(t[1]), seconds=int(t[2]))
     # n = Notification(nick, time, message, target)
     if message is None:
         message = default_message
     return tasks.add_task(nick, host, tasks.TaskType.alarm.value, time.isoformat(' '), message, targeted)
Exemple #31
0
 def filter(self, data):
     for item in data:
         text = utils.htmlec(item['text']).strip()
         user_id = item['user']['id']
         msg_id = item['id']
         if store.sent.select(msg_id) or item['is_self'] or item.get('repost_status_id'):
             continue
         if utils.is_cmd(text):
             add_task(web.ctx, '/whale/cmd', json.dumps(item))
             store.sent.insert(msg_id)
         else:
             talk_ans = None
             for ask, ans in store.talk.fetchall().items():
                 if ask in text:
                     talk_ans = random.choice(ans)
             if talk_ans:
                 store.sent.insert(msg_id)
                 msg = u'@%s %s' % (item['user']['name'], talk_ans)
                 yield {'status': msg, 'in_reply_to_status_id': msg_id, 'mode': 'lite'}
Exemple #32
0
 def set_alarm(self, timestring, nick, host, message=None, targeted=0):
     t = timestring.split(':')  # [h,m,s]'
     now = dt.now()
     if not self.timestring_OK(t, False):
         raise TimeFormatException(timestring)
     elif len(t) == 3:
         time = now.replace(hour=int(t[0]), minute=int(t[1]), second=int(t[2]))
         if time < now:
             time.replace(day=now.day + 1)
     # n = Notification(nick, time, message, target)
     if message is None:
         message = default_message
     return tasks.add_task(nick, host, tasks.TaskType.alarm.value, time.isoformat(' '), message, targeted)
Exemple #33
0
	def do_screen_flash(self):
		DURATION=0.4
		EXPONENT=2.2
		def _internal(t, r):
			surf=pygame.Surface((1300,700))
			surf.fill(pygame.Color(255,255,255))
			surf.set_alpha((t.curr_time**EXPONENT)*(255/DURATION**EXPONENT))
			r.screen.screen.blit(surf, (0,0))
		tasks.add_task(self.root, "render_last", tasks.Task(self.root, _internal, DURATION))
		def _internalt(t, r):
			self=t.data
			if t.delete:
				self.xwd_charge_status=0
				self.xwd_is_charging=0
				self.xwd_at_warp=1
				self.xwd_orig_speed=self.parent.max_speed
				if self.xwd_warp_factor:
					self.parent.max_speed*=self.xwd_warp_factor
				else:
					self.parent.max_speed=self.xwd_warp_speed
				self.parent.rigidbody._vector.magnitude=self.parent.max_speed
		tasks.add_task(self.root, "render_last", tasks.Task(self.root, _internalt, DURATION, self))
Exemple #34
0
    def _run(self):
        while not empty():
            url, kwargs, callback, retries = get_task()

            # Default request method to GET
            kwargs.setdefault("method", "GET")

            # Include our OAuth hook
            kwargs.update(self.hooks)

            try:
                # Construct and send request
                request = requests.Request(url, **kwargs)
                request.send()
                response = request.response

            except requests.RequestException as e:
                sys.stderr.write("Error requesting %s: %s, " %
                                 (request.full_url, e.message))

                if retries < self.max_retries:
                    # Retry...
                    sys.stderr.write("retrying...\n")
                    add_task(url, kwargs, callback, retries + 1)

                else:
                    # Give up
                    sys.stderr.write("giving up...\n")

            else:
                # Invoke callback
                if callable(callback):
                    callback(response, self)

                # Stay within rate limits
                throttle(response)

        sys.stderr.write("%s exiting...\n" % str(self))
def main():
    args = sys.argv
    try:
        command = args[1]
    except IndexError:
        print("Invalid arguments!")
        sys.exit(1)

    if command not in (ADD, REMOVE, LIST):
        print("Invalid command\n Use {0}/{1}/{2}".format(ADD, REMOVE, LIST))
        sys.exit(1)

    if command == ADD:
        title = args[2]
        content = args[3]
        t.add_task(title, content)
    elif command == REMOVE:
        task_id = args[2]
        t.remove_task(task_id)
    elif command == LIST:
        t.list_task()
    else:
        print("invalid command!")
Exemple #36
0
    def _run(self):
        while not empty():
            url, kwargs, callback, retries = get_task()
            
            # Default request method to GET
            kwargs.setdefault("method", "GET")

            # Include our OAuth hook
            kwargs.update(self.hooks)

            try:
                # Construct and send request
                request = requests.Request(url, **kwargs)
                request.send()
                response = request.response

            except requests.RequestException as e:
                sys.stderr.write("Error requesting %s: %s, " % (request.full_url, e.message))

                if retries < self.max_retries:
                    # Retry...
                    sys.stderr.write("retrying...\n")
                    add_task(url, kwargs, callback, retries + 1)

                else:
                    # Give up
                    sys.stderr.write("giving up...\n")

            else:
                # Invoke callback
                if callable(callback):
                    callback(response, self)

                # Stay within rate limits
                throttle(response)

        sys.stderr.write("%s exiting...\n" % str(self))
	def event_state(self, state, event):
		if event.type==pygame.USEREVENT:
			if event.sg_type==triggers.UE_SHL_DAMAGE_DEALT:
				if event.system.shields > 30:
					if not event.x:
						event.x, event.y = event.source.rotated_rect.center

					# dx =  - event.source.rotated_rect.centerx - event.x
					# dy =  - event.source.rotated_rect.centery - event.y
					
					angle=get_angle(event.system.ship.rotated_rect.centerx, event.x, 
						event.system.ship.rotated_rect.centery, event.y)

					orig_image=pygame.transform.scale(absroot.gamedb("image_shield_hit_default"), (event.system.ship.rotated_rect.width+30, event.system.ship.rotated_rect.height+30 ) )


					def _(t, r):
						orig_rect=pygame.Rect( (0,0), orig_image.get_size())
						orig_rect.center=(event.system.ship.rotated_rect.centerx,
							event.system.ship.rotated_rect.centery)

						rot_image, rot_rect=rot_center(orig_image, orig_rect, angle)
						absroot.screen.blit(rot_image, rot_rect)

					tasks.add_task(self.root, "render_after_entities", tasks.Task(absroot, _, 2))
			if event.sg_type==triggers.UE_SHIELDS_DOWN:
				if absroot.game_time - self.last_shields_warning > 10:
					self.last_shields_warning=absroot.game_time
					if (event.system.ship == absroot.state_manager.getcurr().player):
						absroot.gamedb("snd_shelds_down_warning_player").play()
			if event.sg_type==triggers.UE_HUL_DAMAGE_DEALT:
				if absroot.game_time - self.last_hull_warning > 10:
					if event.system.hull < 20:
						self.last_hull_warning=absroot.game_time
						if (event.system.ship == absroot.state_manager.getcurr().player):
							absroot.gamedb("snd_hull_breach_player").play()
Exemple #38
0
 def POST(self):
     self.stage = web.data()
     store.ctx.last_call = time.time()
     try:
         resp = utils.request(utils.request_url, 'GET', {'count': 60, 'mode': 'lite'})
         data = json.loads(resp.read())
         for body in self.filter(data):
             add_task(web.ctx, '/whale/send', json.dumps(body))
     finally:
         if self.stage != utils.stage(): 
             add_task(web.ctx, '/whale/hello', self.stage)
         else:
             time.sleep(4)
             add_task(web.ctx, '/whale/greet', self.stage)
def test_delete_task(client):
    task_key = tasks.add_task(client, 'Test task 1')
    tasks.delete_task(client, task_key.id)
    assert client.get(task_key) is None
def test_list_tasks(client):
    task1_key = tasks.add_task(client, 'Test task 1')
    task2_key = tasks.add_task(client, 'Test task 2')
    task_list = tasks.list_tasks(client)
    assert [x.key for x in task_list] == [task1_key, task2_key]
def test_mark_done(client):
    task_key = tasks.add_task(client, 'Test task')
    tasks.mark_done(client, task_key.id)
    task = client.get(task_key)
    assert task
    assert task['done']
def test_add_task(client):
    task_key = tasks.add_task(client, 'Test task')
    task = client.get(task_key)
    assert task
    assert task['description'] == 'Test task'
def test_mark_done(client):
    task_key = tasks.add_task(client, "Test task")
    tasks.mark_done(client, task_key.id)
    task = client.get(task_key)
    assert task
    assert task["done"]
Exemple #44
0
 def _internalde(t, r):
     if t.delete:
         tasks.add_task(
             self.root, "render_after_entities",
             tasks.Task(self.root, _internalab,
                        self.config["style"]["sum_duration"], t.data))
def test_add_task(client):
    task_key = tasks.add_task(client, "Test task")
    task = client.get(task_key)
    assert task
    assert task["description"] == "Test task"
	def run(self):
		def _internalsx(t,r):
			if t.delete:
				r.gamedb.get_asset(t.data).play()
		tasks.add_task(self.root, "render_last", tasks.Task(self.root, _internalsx, self.config["time"], self.config["sound"]))
Exemple #47
0
def add_request(url, kwargs, callback=None):
    add_task(url, kwargs, callback)
Exemple #48
0
    if request.method == 'GET':
        return HttpResponseNotAllowed("GET requests not allowed")
    if not request.body:
        return HttpResponseBadRequest('No URLs contained in request')
    try:
        data = json.loads(request.body)
    except ValueError, e:
        return HttpResponseBadRequest('Request body is not a JSON object')
    urls = data.get('urls')
    if not urls:
        return HttpResponseBadRequest('No URLs field in input JSON')
    if type(urls) != list:
        return HttpResponseBadRequest('URLs field in input JSON is not a list')
    job = Job()
    job.save()
    for url in urls:
        add_task(job.id, url, MAX_LEVEL)
    return HttpResponse(job.id)

def scrape_status(request, job_id):
    tasks = Task.objects.filter(job_id=job_id)
    total = tasks.count()
    completed = tasks.filter(count=0).count()
    data = {'In progress': total, 'Completed': completed}
    return HttpResponse(json.dumps(data), content_type="application/json")

def scrape_result(request, job_id):
    results = Result.objects.filter(job_id=job_id).values('image_url')
    data = {'images': list(set([result['image_url'] for result in results]))}
    return HttpResponse(json.dumps(data), content_type="application/json")
	def run_in_ship(self, ship):
		def _internal(t, r):
			r.screen.blit(t.data[1], t.data[0])
		tasks.add_task(self.root, "render_before_particles",
			tasks.Task(self.root, _internal, self.config["time"], (ship.rotated_rect.copy(), ship.rotated_image.copy())))