Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 14

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 14 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 142018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 14)

Each ofthese functions creates a list, msgs. In each case, the list contains tuplesin which the first item is the key, according to which the messages shouldbe sorted, and the second item is the message content.68APPLICATION BUILDING AND SMS INBOXWe use the list’s sort() function to sort the list. In Python, listsare sorted as follows: if a list contains only strings, they are sorted intoalphabetical order; if a list contains only integers, they are sorted intoascending order; if a list contains tuples or lists, the first item of the listor tuple is used as the sorting key; if the list contains items of differenttypes, items of the same type are grouped together and each type is sortedseparately.In this case, the sorting key depends on the user’s choice:•The sort time() function uses the Inbox object’s time() function to fetch the time when the message was received.

The timeis returned in seconds since 1 January 1970, which is the standardstarting point for time measurements in many operating systems.•The sort sender() function uses the sender’s phone number,returned by the address() function, as the sorting key.•The sort unread() function uses the function unread() whichreturns 1 if the message is unread and 0 otherwise.Since Python’s sort() function sorts integers into ascending order, wehave to make the timestamp and the unread flag negative,-box.time(sms id) and -box.unread(sms id), as we prefer thenewest and the unread messages at the top of the list.Each of these three functions prepares a list, msgs, that is ready to besorted in the desired way. The actual sorting and showing the resultinglist is the same in all the cases, so this task is separated into a function ofits own, show list().After the msgs list has been sorted, we can drop off the sorting keys anduse only the second item in the tuple, the message content, to construct anew list that includes message excerpts, as in the previous example.

Afterthis, the sorted messages are ready to be displayed.You could integrate Examples 15 and 16 to make a combined Inboxsearcher and sorter – a fully fledged personal messaging assistant. There isone more related function, delete(), available in the Inbox object. Itworks exactly like the functions content(), address() and time().It is used to delete a message, so make sure you have backed up yourSMS inbox before trying it!4.4.4 Receiving MessagesIf you want to build a service which is controlled by SMS messages,your program must be able to react to incoming messages.

In theory, youcould accomplish this task by calling the sms messages() function atconstant intervals and checking whether the list has been changed sincethe last call.SMS INBOX69This approach is likely to perform lots of unnecessary work. Luckily,PyS60 provides an alternative: a callback function can be called whenevera new message is received.Example 17: SMS receiverimport inbox, appuifw, e32def message_received(msg_id):box = inbox.Inbox()appuifw.note(u"New message: %s" % box.content(msg_id))app_lock.signal()box = inbox.Inbox()box.bind(message_received)print "Waiting for new SMS messages.."app_lock = e32.Ao_lock()app_lock.wait()print "Message handled!"The Inbox object’s bind() function binds a callback function toan event that is generated by an incoming message.

In this example,the function message received() is called when a new messagearrives.The callback function takes one parameter, namely the ID of theincoming message, msg id. Based on this ID, the message contents,or any other attribute, can be retrieved from the SMS inbox, as we sawabove.The program should not execute from start to finish at once. Instead, itshould wait for an event to occur. This time the event is not generated bythe user directly, but by an incoming SMS message. Waiting is handledin the familiar manner, using the Ao lock object.When a new message arrives, the function message received() iscalled.

It opens a popup note that shows the contents of the newly arrivedmessage. Then the Ao lock is released and the program finishes withthe message ‘Message handled!’. The only way to terminate this programproperly is to send an SMS message to your phone.4.4.5Forwarding MessagesAs you know from everyday usage of your mobile phone, an arriving textmessage triggers a sound notification, as well as a popup note saying thata new message has arrived.However, if you make a program that handles messages automatically,the notification may not be desirable.

Luckily, the sound and the dialogcan be avoided if the message is deleted immediately in the callbackfunction when the new message has arrived.70APPLICATION BUILDING AND SMS INBOXIn Example 18, we demonstrate this feature with a filtering SMS gateway. The gateway receives a new message, removes all nasty words in itand forwards the censored message to another phone.Example 18: Filtering SMS gatewayimport messaging, inbox, e32PHONE_NUMBER = "+18982111111"nasty_words = ["Java", "C++", "Perl"]def message_received(msg_id):box = inbox.Inbox()msg = box.content(msg_id)sender = box.address(msg_id)box.delete(msg_id)for word in nasty_words:msg = msg.replace(word, "XXX")messaging.sms_send(PHONE_NUMBER, msg)print "Message from %s forwarded to %s" %\(sender, PHONE_NUMBER)box = inbox.Inbox()box.bind(message_received)print "Gateway activated"app_lock = e32.Ao_lock()app_lock.wait()This script should disable any notifications caused by arriving SMS messages.

As in the previous example, the function message received()is called when a new message arrives.The function message received() fetches the contents of the newmessage and deletes it immediately from the inbox. Nasty words arereplaced with ‘XXX’ and the cleaned message is forwarded to anotherphone, specified in the PHONE NUMBER. A log message is printed out foreach forwarded SMS, which shows both the sender’s and the recipient’sphone numbers.Note that you should not specify your own number in the PHONENUMBER.

This would make the program forward messages to itself,resulting in an infinite loop!4.5 SMS Game ServerWe have already covered a number of new concepts in this chapter. Wehave learnt how to use the standard user interface framework, how tomanipulate strings and how to read and receive SMS messages. In theconcluding example, all these features will be put to good use.SMS GAME SERVER71The application is an SMS game server with a user interface. It implements the classic game of Hangman, which is described by Wikipedia asfollows:One player thinks of a word and the other tries to guess it by suggestingletters.

The word to guess is represented by a row of dashes, giving thenumber of letters. If the guessing player suggests a letter which occurs inthe word, the other player writes it in all its correct positions. The game isover when the guessing player completes the word or guesses the wholeword correctly.Note that our implementation omits the drawing part of the game.Adding graphics to the game would be an interesting exercise after youhave read Chapter 5, which introduces the required functions.You are the game master who runs the server. You can input theword to be guessed by way of the user interface.

Other players sendtext messages to your phone, either to guess individual characters (e.g.‘GUESS a’), or to guess the whole word (e.g. ‘WORD cat’). After eachguess, a reply message containing the current status of the word is sentback to the guesser. There is no limit to the number of players.This application provides a fully working example of how to buildSMS services of your own. You can easily adapt it to your own ideas.

Theconcept is simple. The user interface provides an option to initialize anew game and an option to see the status of the current game. An inboxcallback handles all incoming messages, parses them, modifies the gamestate and sends a reply to the guessing player.The implementation contains some features which have not beenintroduced earlier, but they are presented in the following discussion.Since the code listing does not fit into one page nicely, we have divided itinto three parts.

You should combine the parts to form the full application.Example 19: Hangman server (1/3)import inbox, messaging, appuifw, e32, contactscurrent_word = Noneguessed = Nonenum_guesses = 0def new_game():global current_word, guessed, num_guessesword = appuifw.query(u"Word to guess", "text")if word:current_word = word.lower()guessed = list("_" * len(current_word))num_guesses = 0print "New game started. Waiting for messages..."def game_status():if current_word:72APPLICATION BUILDING AND SMS INBOXappuifw.note(u"Word to guess: %s\n" % current_word +\"Current guess: %s\n" % "".join(guessed) +\"Number of gusses: %d" % num_guesses)else:appuifw.note(u"Game has not been started")def quit():print "HANGMAN SERVER EXITS"app_lock.signal()The first section of the code contains the functions to handle UI events:new game(), game status() and exit().

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6447
Авторов
на СтудИзбе
306
Средний доход
с одного платного файла
Обучение Подробнее