import time
from threading import Thread
run = True
def ticker():
while run:
time.sleep(1)
print('Тик')
time.sleep(1)
print('Так')
# Запуск функции ticker в отдельном потоке.
# Параметр daemon=True нужен чтобы
# дочерний поток умирал вместе с основным
# в случае внештатного выхода.
Thread(target=ticker, daemon=True).start()
while run:
command = input('Для выхода введите "exit"\n')
if command.lower() == 'exit':
run = False
import asyncio
import signal
def shutdown():
# Отменяем все задачи, кроме вызвавшей
for task in asyncio.Task.all_tasks():
if task is not asyncio.tasks.Task.current_task():
task.cancel()
async def user_io():
loop = asyncio.get_event_loop()
# Ждём действия от пользователя
while True:
# Запускаем input() в отдельном потоке и ждём его завершения
command = await loop.run_in_executor(None, input, 'Для выхода введите "exit"\n')
if command.lower() == 'exit':
shutdown() # Отменяем все задачи
break # и выходим из цикла
# Сопрограмма, выполняемая параллельно с ожиданием пользовательского ввода
async def task_manager():
counter = 0
while True:
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
break # Выходим из цикла, если задачу отменили
counter += 1
print("I'm a task manager {}!".format(counter))
if __name__ == '__main__':
# Устанавливаем обработчик Ctrl+C
signal.signal(signal.SIGINT, lambda n, f: shutdown())
# Запускаем цикл событий
loop = asyncio.get_event_loop()
# Задача ждущая завершения сопрограм user_io и task_manager
main_task = asyncio.wait([user_io(), task_manager()])
try:
loop.run_until_complete(main_task)
except asyncio.CancelledError:
# Позволяем main_task завершиться
loop.run_until_complete(main_task)
loop.close()
from os.path import splitext
from transliterate import slugify
def slugify_upload(instance, filename):
name, ext = splitext(filename)
return slugify(name) + ext
class Dancer(models.Model):
photo = models.ImageFiled(upload_to=slugify_upload, ...)
...
import asyncio
import aioredis
from tornado import web, websocket
from tornado.ioloop import IOLoop
connections = []
class WSHandler(websocket.WebSocketHandler):
def open(self):
connections.append(self)
def on_message(self, message):
...
def on_close(self):
connections.remove(self)
class GetHandler(web.RequestHandler):
def get(self):
self.render("chat.html")
async def consumer(channel):
while await channel.wait_message():
msg = await channel.get(encoding='utf-8')
for connection in connections:
await connection.write_message(msg)
async def setup():
connection = await aioredis.create_redis('redis://localhost')
channel = await connection.subscribe('notifications')
asyncio.ensure_future(consumer(channel))
application = web.Application([
(r'/', GetHandler),
(r'/chat/', WSHandler),
])
if __name__ == '__main__':
application.listen(8000)
loop = IOLoop.current()
loop.add_callback(setup)
loop.start()
To ensure efficient use of Elastic IP addresses, we impose a small hourly charge if an Elastic IP address is not associated with a running instance, or if it is associated with a stopped instance or an unattached network interface. While your instance is running, you are not charged for one Elastic IP address associated with the instance, but you are charged for any additional Elastic IP addresses associated with the instance.
MOV DX, 2000 ; Number of times to repeat whole routine.
MOV BX, 1 ; Frequency value.
MOV AL, 10110110B ; The Magic Number (use this binary number only)
OUT 43H, AL ; Send it to the initializing port 43H Timer 2.
NEXT_FREQUENCY: ; This is were we will jump back to 2000 times.
MOV AX, BX ; Move our Frequency value into AX.
OUT 42H, AL ; Send LSB to port 42H.
MOV AL, AH ; Move MSB into AL
OUT 42H, AL ; Send MSB to port 42H.
IN AL, 61H ; Get current value of port 61H.
OR AL, 00000011B ; OR AL to this value, forcing first two bits high.
OUT 61H, AL ; Copy it to port 61H of the PPI Chip
; to turn ON the speaker.
MOV CX, 100 ; Repeat loop 100 times
DELAY_LOOP: ; Here is where we loop back too.
LOOP DELAY_LOOP ; Jump repeatedly to DELAY_LOOP until CX = 0
INC BX ; Incrementing the value of BX lowers
; the frequency each time we repeat the
; whole routine
DEC DX ; Decrement repeat routine count
CMP DX, 0 ; Is DX (repeat count) = to 0
JNZ NEXT_FREQUENCY ; If not jump to NEXT_FREQUENCY
; and do whole routine again.
; Else DX = 0 time to turn speaker OFF
IN AL, 61H ; Get current value of port 61H.
AND AL, 11111100B ; AND AL to this value, forcing first two bits low.
OUT 61H, AL ; Copy it to port 61H of the PPI Chip
; to turn OFF the speaker.
class SomeFormHandler(FormView):
def form_invalid(self, form):
if self.request.is_ajax():
data = {'status': 'error', 'erros': []}
for field, errors in form.errors.items():
for error in errors:
data['errors'].append({'key': field, 'desc': error})
return JsonResponse(data)
else:
...
$.post($(form).attr('action'), $(form).serialize(), function(result) {
if(result.status == 'ok') {
form.reset();
showAlert('Сообщение успешно отправлено', 'success');
}
else if(result.status == 'error') {
for(var ndx in result.errors) {
if(result.errors[ndx].key == '__all__') showAlert(result.errors[ndx].desc);
$(form).find('[name=' + result.errors[ndx].key + ']').parent().addClass('has-error');
}
}
}).fail(function(xhr, textStatus, error) {
showAlert('Ошибка отправки сообщения');
});