Example #1
0
async def create_tasks_sleep():
    task1 = asyncio.create_task(delay(1))
    await asyncio.sleep(0)
    task2 = asyncio.create_task(delay(2))
    await asyncio.sleep(0)
    print('Gathering tasks:')
    await asyncio.gather(task1, task2)
Example #2
0
async def main():
    sleep_for_three = asyncio.create_task(delay(3))
    sleep_again = asyncio.create_task(delay(3))
    sleep_once_more = asyncio.create_task(delay(3))

    await sleep_for_three
    await sleep_again
    await sleep_once_more
Example #3
0
        def walk(self):
            while True:
                for i in range(0, self.__strip.numPixels()):
                    self.__strip.setPixelColor(i, color.Random())
                    self.__strip.show()
                    util.delay(100.0)

                util.delay(750.0)
Example #4
0
File: main.py Project: M-a-c/MacBar
 def run(self):
     delay(2000)
     leds[0].setColorRBGW(255,255,255,255)
     hardwareController.write()
     print("Start a tornado")
     asyncio.set_event_loop(asyncio.new_event_loop())
     self.application = tornado.web.Application([(r"/", WebSocketHandler),])
     self.application.listen(8888)
     tornado.ioloop.IOLoop.instance().start()
Example #5
0
        def twinkle(self):
            while True:
                for i in range(0, self.LIT_COUNT):
                    self.__strip.setPixelColor(self.last[i], color.Black())
                    self.last[i] = random.randint(0, self.__strip.numPixels())

                    self.__strip.setPixelColor(self.last[i], color.Random())

                self.__strip.show()
                util.delay(150)
Example #6
0
File: main.py Project: M-a-c/MacBar
    def run(self):
        delay(2000)
#        The enent loop
        print("here")
#        Runs at ~1.37k+ fps. DAMN. except in tkinter, cause tk sucks.
        while(True):
            for o in self.effects:
                o.step()
#            self.test.step()
            hardwareController.write()
            reset(leds)
Example #7
0
    def fight(self, enemy):
        """Fight an enemy."""
        
        if not enemy.is_alive():
            print "The %s is already dead." % enemy.name
            
        else:
            
            # Keep fighting the enemy until either the player or enemy dies.
            while self.is_alive() and enemy.is_alive():
        
                print "You attack!"
                delay()
                damage = randint(1, self.dmg)
                enemy.hp -= damage
                print "You do %d damage to the %s." % (damage, enemy.name)
                delay()
                
                if enemy.hp <= 0:
                    print "You killed the %s!" % enemy.name
                    enemy.isAlive = False
                
                else:
                    print "The %s attacks!" % enemy.name
                    delay()
                    damage = randint(1, enemy.dmg)
                    self.hp -= damage
                    print "The %s does %d damage to you." % (enemy.name, damage)
                    print "You have %d hp left." % (max(0, self.hp))
                    delay()

                    if self.hp <= 0:
                        print "The %s killed you!" % enemy.name
                        dead()
Example #8
0
async def main():
    task_one = asyncio.create_task(cpu_bound_work())
    task_two = asyncio.create_task(cpu_bound_work())
    delay_task = asyncio.create_task(delay(4))
    await task_one
    await task_two
    await delay_task
async def main():
    delay_task = asyncio.create_task(delay(2))
    try:
        result = await asyncio.wait_for(delay_task, timeout=1)
        print(result)
    except asyncio.exceptions.TimeoutError:
        print('Got a timeout!')
        print(f'Was the task cancelled? {delay_task.cancelled()}')
Example #10
0
def on(relay_num, log=True, max_duration=None):
    pin = relays[relay_num]
    GPIO.output(pin, ON)
    cancel_timer(relay_num)
    if max_duration is not None:
        timers[relay_num] = util.delay(off, max_duration, [relay_num], {"log_extra": "via timer"})
    if log:
        log_action(relay_num, "turn on")
Example #11
0
async def main():
    delay_task =  asyncio.create_task(delay(2))
    try:
        print("#####")
        result = await asyncio.wait_for(delay_task, timeout=1)
        print(result)
    except asyncio.exceptions.TimeoutError:
        print("got a timeout")
        print(f"was the task cancelled? {delay_task.cancelled()}")
Example #12
0
def on(relay_num, log=True, max_duration=None):
    pin = relays[relay_num]
    GPIO.output(pin, ON)
    cancel_timer(relay_num)
    if max_duration is not None:
        timers[relay_num] = util.delay(off, max_duration, [relay_num],
                                       {"log_extra": "via timer"})
    if log:
        log_action(relay_num, "turn on")
Example #13
0
def toggle(relay_num, log=True, max_duration=None):
    pin = relays[relay_num]
    new_state = not bool(GPIO.input(pin))
    GPIO.output(pin, new_state)
    cancel_timer(relay_num)
    if new_state == ON and max_duration is not None:
        timers[relay_num] = util.delay(off, max_duration, [relay_num], {"log_extra": "via timer"})
    if log:
        log_action(relay_num, "toggle %s" % ('off' if new_state == OFF else 'on'))
    return new_state
async def main():
    task = asyncio.create_task(delay(10))

    try:
        result = await asyncio.wait_for(asyncio.shield(task), 5)
        print(result)
    except asyncio.TimeoutError:
        print("Task took longer than five seconds!")
        result = await task
        print(result)
Example #15
0
def toggle(relay_num, log=True, max_duration=None):
    pin = relays[relay_num]
    new_state = not bool(GPIO.input(pin))
    GPIO.output(pin, new_state)
    cancel_timer(relay_num)
    if new_state == ON and max_duration is not None:
        timers[relay_num] = util.delay(off, max_duration, [relay_num],
                                       {"log_extra": "via timer"})
    if log:
        log_action(relay_num,
                   "toggle %s" % ('off' if new_state == OFF else 'on'))
    return new_state
Example #16
0
def test163():
	url = 'http://music.163.com/api/playlist/detail?id={}'.format(list_id[0])
	log.info(url)
	log.info('Grab album ...')
	r = requests.get(url)
	data = r.json()
	result = data['result']
	tracks = result['tracks']
	total = len(tracks)

	for i, item in enumerate(tracks):
		log.info('Deal with {}th/{} song'.format(i + 1, total))
		stamp = int(item['album']['publishTime']) / 1000
		t = datetime.fromtimestamp(stamp)

		if isSongExists(item['id']):
			log.warn('The song exists and skip')
			continue

		song = Song(item['id'], item['name'], item['artists'][0]['name'], item['mp3Url'], t, '163')
		song.save()
		delay(1)
Example #17
0
async def main():
    long_task = asyncio.create_task(delay(10))

    seconds_elapsed = 0

    while not long_task.done():
        print('Task not finished, checking again in a second.')
        await asyncio.sleep(1)
        seconds_elapsed = seconds_elapsed + 1
        if seconds_elapsed == 5:
            long_task.cancel()

    try:
        await long_task
    except CancelledError:
        print('Our task was cancelled')
Example #18
0
def merge_info(bench, samplers):
    path = data_path[bench]
    data = pd.read_csv(path + 'res.csv')
    another = delay(path, samplers)
    data['bench'] = bench
    data['time'] = [math.log(a) for a in another['time']]
    data['ctime'] = [a * 100 for a in another['ctime']]
    data['through'] = another['through']
    data['cthrough'] = another['cthrough']
    data['filesize'] = data['size'].apply(lambda x: x / (2**20))
    data.drop(columns=['size'], inplace=True)

    data.drop(['Unnamed: 0'], axis=1, inplace=True)
    data.index = ['always', 'bump', 'tbuckt', 'p0.1', 'p0.01']
    data = data.reindex(index=['always', 'p0.01', 'p0.1', 'bump', 'tbuckt'])
    data['node'] = data['node'] / data['node']['always']  # 和全采样的相除
    data['tree'] = data['tree'] / data['tree']['always']  # 和全采样的相除
    data['filesize'] = (data['filesize'] /
                        data['filesize']['always']) * 100  # 和全采样的相除
    data['filesize'] = [math.log(d) for d in data['filesize']]
    data['sampler'] = data.index
    return data
Example #19
0
async def main():
    stdin_reader = await create_stdin_reader()
    while True:
        delay_time = await stdin_reader.readline()
        asyncio.create_task(delay(int(delay_time)))
Example #20
0
from flask import request, redirect, session, jsonify, abort, render_template
import model
from util import delay, convert

router = {
    'login': delay('login.html', ['show_register']),
    'register': delay('register.html', []),
    'main': delay('main.html', ['is_regular', 'show_logout'], js='main.js'),
    'history': delay('history.html', ['is_regular', 'show_logout']),
    'report_one': delay('report_one.html', ['is_admin', 'show_logout']),
    'report_two': delay('report_two.html', ['is_admin', 'show_logout']),
    'report_three': delay('report_three.html', ['is_admin', 'show_logout']),
    'reset': delay('reset.html', ['is_admin', 'show_logout'])
}


def init(app):
    with app.app_context():
        model.init_app(app)

    @app.route('/login', methods=['GET', 'POST'])
    def login():
        if 'user_id' in session:
            return redirect('/')

        if request.method == 'POST':
            data = request.form.to_dict(flat=True)

            result = model.authenticate(data['username'], data['password'])

            if isinstance(result, model.User):
Example #21
0
def cancel_timer(relay_num, remove_only=False):
    if relay_num in timers:
        if not remove_only:
            timers[relay_num].cancel()
        del timers[relay_num]


def pulse(relay_num, duration=0.15, log=True, async=None):
    pin = relays[relay_num]
    GPIO.output(pin, ON)
    if duration < max_synchronous_delay:
        time.sleep(duration)
        GPIO.output(pin, OFF)
    else:
        util.delay(GPIO.output, duration, [pin, OFF])
    if log:
        log_action(relay_num, "pulse for %d sec" % duration)


def off(relay_num, log=True, log_extra=""):
    pin = relays[relay_num]
    GPIO.output(pin, OFF)
    cancel_timer(relay_num)
    if log:
        log_action(relay_num, "turn off %s" % log_extra)


def on(relay_num, log=True, max_duration=None):
    pin = relays[relay_num]
    GPIO.output(pin, ON)
Example #22
0
async def main() -> None:
    delay_times = [3, 3, 3]
    tasks = [asyncio.create_task(delay(seconds)) for seconds in delay_times]
    [await task for task in tasks]
Example #23
0
async def main():
    results = await asyncio.gather(delay(3), delay(1))
    print(results)
async def main() -> None:
    delay_times = [3, 3, 3]
    [await asyncio.create_task(delay(seconds)) for seconds in delay_times]
Example #25
0
def cancel_timer(relay_num, remove_only=False):
    if relay_num in timers:
        if not remove_only:
            timers[relay_num].cancel()
        del timers[relay_num]


def pulse(relay_num, duration=0.15, log=True, async=None):
    pin = relays[relay_num]
    GPIO.output(pin, ON)
    if duration < max_synchronous_delay:
        time.sleep(duration)
        GPIO.output(pin, OFF)
    else:
        util.delay(GPIO.output, duration, [pin, OFF])
    if log:
        log_action(relay_num, "pulse for %d sec" % duration)


def off(relay_num, log=True, log_extra=""):
    pin = relays[relay_num]
    GPIO.output(pin, OFF)
    cancel_timer(relay_num)
    if log:
        log_action(relay_num, "turn off %s" % log_extra)


def on(relay_num, log=True, max_duration=None):
    pin = relays[relay_num]
    GPIO.output(pin, ON)
Example #26
0
async def main():
    while True:
        delay_time = input('Enter a time to sleep:')
        asyncio.create_task(delay(int(delay_time)))
Example #27
0
async def main():
    first_delay = asyncio.create_task(delay(4))
    second_delay = asyncio.create_task(delay(4))
    await hello_every_second()
    await first_delay
    await second_delay
Example #28
0
				try:
					a = vcard.find("a")
					href = a["href"].encode('ascii', 'ignore')
					addr = util.normalize_addr(a.get_text())
					p_output = p_output_dir+"{0:0=3d}".format(p_order)+"_"+addr
					p_order = p_order + 1
					p_cmd = get_property_url(cmd,user_agent,url_base,href,p_output.encode('ascii', 'ignore'))
					
					print ("	Run property qry : " + p_cmd)
					call(p_cmd, shell=True)
					util.gzip_file(p_output)

					# update current sold date. only update it when it's not none
					sold_date = get_sold_date(vcard)
					if sold_date is not None and sold_date != SOLD_DATE_NA:
						sentinal_sold_date = sold_date

				except:
					print "Unexpected error:", sys.exc_info()[0]

			# if this is for "sold", we only get data for specified time range.
			# check if we should continue for next page
			if not util.if_contine(sentinal_sold_date,sentinal_page_count,SOLD_PAGE_START_FROM,SOLD_PAGE_COUNT):
				break

			sleep(util.delay()) 


fp.close()

Example #29
0
async def main():
    sleep_for_three = asyncio.create_task(delay(3))
    print(type(sleep_for_three))
    result = await sleep_for_three
    print(result)
Example #30
0
from flask import request, redirect, url_for, session, jsonify, abort
import model
from util import delay

router = {
    'login':
    delay('login.html', ['show_register']),
    'register':
    delay('register.html', []),
    'admin':
    delay('admin.html', []),
    'status':
    delay('status.html', ['show_logout'], js='status.js'),
    'info':
    delay('info.html', ['info_page']),
    'about':
    delay('about.html', ['about_page']),
    'add_spot':
    delay('add_spot.html', ['admin_page', 'show_logout']),
    'remove_spot':
    delay('remove_spot.html', ['admin_page', 'show_logout']),
    'remove_reservation':
    delay('remove_reservation.html', ['admin_page', 'show_logout']),
    'remove_user':
    delay('remove_user.html', ['admin_page', 'show_logout'])
}


def register(app):
    with app.app_context():
        model.init_app(app)