示例#1
0
 def _component2Task(self, container, component, data):
     """Create todo and adds it to container together
     with it's children
     """
     # create todo item
     todo = Todo(uid=component.contents['uid'][0].value,
                 summary=component.contents['summary'][0].value)
     if component.contents.get('dtstamp', None) is not None:
         todo.dtstamp = component.contents['dtstamp'][0].value
     if component.contents.get('created', None) is not None:
         todo.created = component.contents['created'][0].value
     if component.contents.get('last-modified', None) is not None:
         todo.last_modified = component.contents['last-modified'][0].value
     if component.contents.get('related-to', None) is not None:
         todo.related_to = component.contents['related-to'][0].value
     if component.contents.get('completed', None) is not None:
         todo.completed = component.contents['completed'][0].value
     if component.contents.get('percent-complete', None) is not None:
         todo.percent_complete = component.contents['percent-complete'][0].value
     if component.contents.get('x-kde-ktimetracker-totalsessiontime', None) is not None:
         todo.x_kde_ktimetracker_totalsessiontime = component.contents['x-kde-ktimetracker-totalsessiontime'][0].value
     if component.contents.get('x-kde-ktimetracker-totaltasktime', None) is not None:
         todo.x_kde_ktimetracker_totaltasktime = component.contents['x-kde-ktimetracker-totaltasktime'][0].value
     if component.contents.get('x-kde-ktimetracker-bctype', None) is not None:
         todo.x_kde_ktimetracker_bctype = component.contents['x-kde-ktimetracker-bctype'][0].value
     
     # add it to container
     todo = container.add(todo)
     
     # now it's time to collect all todo's children
     for item in data.get(todo.uid, []):
         child = self._component2Task(todo, item, data)
     
     return todo
示例#2
0
文件: main.py 项目: rahul-pl/todo
	def get(self):
		todo = self.request.get('todo')
		
		todo_obj = Todo(todo=todo, date=datetime.datetime.now().time())
		todo_obj.put()
		
		self.response.headers['Content-Type'] = 'text/plain'
		self.response.out.write('Request to create ' + todo + ' received')
示例#3
0
文件: main.py 项目: rahul-pl/todo
	def get(self):
		todos_query = Todo.all().order('-date')
		todos = todos_query.fetch(10)
		
		template_values = {
			'todos' : todos
		}
		
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, template_values))
示例#4
0
 def get(self):
   user = users.get_current_user()
   if user:
     names = ['To', 'Do' ,  user.nickname() ]
   else:
     names = ['To', 'Do' , 'No user' ]
   template_data = {
     'names': names,
     'version': VERSION,
     'user': user,
     'page': 'todos',
     'appid': APPID,
     'appname': APPNAME,
     'todos': [ t.__str__() for t in Todo.getAll()],
   }
   t = Todo.createTodo('Todos Index REMOVE ME at every index...')
   #if user:
   #    self.response.headers['Content-Type'] = 'text/plain'
   #    self.response.out.write('[ProvaPally Obsolete]: Groezi Mittenand, liebe gaeste' + user.nickname())
   #else:
   #    self.redirect(users.create_login_url(self.request.uri))
   jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
   template = jinja_environment.get_template('todos-index.html')
   self.response.write(template.render(template_data))
示例#5
0
class TodoTestCase(object):

    def __init__(self):
        self._todo = Todo()

    def set_up(self):
        self._todo.clear()

    def test_add_todo_adds_pending_item(self):
        self._todo.add("Sandwich")

        items = self._todo.items()
        assert_equal(("Sandwich", Todo.PENDING), items)

    def test_add_return_value(self):
        add_return_index = self._todo.add("Sandwich")
        assert_equal(0, add_return_index)
示例#6
0
def delete_todo(request):
    # 找到当前登录的用户, 如果没登录, 就 redirect 到 /login
    uname = current_user(request)
    u = User.find_by(username=uname)
    if u is None:
        return redirect('/login')
    # 得到当前删除的 todo 的 id
    todo_id = int(request.query.get('id', -1))
    # 找到当前被删除的条目的数据,按照当前编辑的 todo 的 id来寻找,
    # 比如编辑 {"id": 3, "title": "喝水", "user_id": 1},那么按照"id": 3取数据文件中查询
    # 比如 t = < Todo id: (3) title: (喝水) user_id: (1) >
    t = Todo.find_by(id=todo_id)
    # log('找到当前登录用户要编辑的数据的对应id', t)
    # 判断被删除的这个数据对应的用户id(t.user_id)和编辑这个数据的用户id(u.id)是否一致
    # 比如 t.user_id = 1, u.id = 1
    # 如果两者相等说明登录用户在修改自己的数据,不相等说明登录用户在修改别人的数据,那这个是不允许的,就重定向到登录页面
    if t.user_id != u.id:
        return redirect('/login')
    # 如果t不是None,意思就是说被删除的这个数据是存在的,那么就用remove函数把t删除掉
    if t is not None:
        t.remove()
    # 浏览器发送数据过来被处理后, 重定向到首页
    # 浏览器在请求新首页的时候, 就能看到新增的数据了
    return redirect('/todo')
示例#7
0
def edit(request):
    """
    todo edit 的路由函数
    """
    headers = {
        'Content-Type': 'text/html',
    }
    uname = current_user(request)
    u = User.find_by(username=uname)
    # 得到当前编辑的 todo 的 id
    todo_id = int(request.query.get('id', -1))
    t = Todo.find_by(id=todo_id)
    if t.user_id != u.id:
        return redirect('/login')
    # if todo_id < 1:
    #     return error(404)
    # 替换模板文件中的标记字符串
    body = template('todo_edit.html')
    body = body.replace('{{todo_id}}', str(t.id))
    body = body.replace('{{todo_title}}', str(t.title))
    # 下面 3 行可以改写为一条函数, 还把 headers 也放进函数中
    header = response_with_headers(headers)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
示例#8
0
def update(request):
    """
    用于增加新 todo 的路由函数
    """
    uname = current_user(request)
    u = User.find_by(username=uname)
    if u is None:
        return redirect('/login')
    if request.method == 'POST':
        # 修改并且保存 todo
        form = request.form()
        print('debug update', form)
        todo_id = int(form.get('id', -1))
        log("debug todo_id", todo_id)
        t = Todo.find_by(id=todo_id)
        log("t", t)
        t.title = form.get('title', t.title)
        if form.get('user_id') == 
            t.save()
        else:
            return redirect('/login')
    # 浏览器发送数据过来被处理后, 重定向到首页
    # 浏览器在请求新首页的时候, 就能看到新增的数据了
    return redirect('/todo')
 def test_command_line_input(self):
     todo = Todo()
     self.assertIsInstance(todo.cl_input(), str)
示例#10
0
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
'''
处理
队列数据
'''

'''
product 为生成环境配置
test 为测试环境配置
'''
_config_set = 'test'

from todo import Todo
import sys

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print "参数有错,如:'python2.7 main.py test'测试环境 或 'python2.7 main.py product'生产环境"
        sys.exit(0)
    _config_set = str(sys.argv[1].lower())
    todo = Todo(_config_set)    
    print "todo start ", todo.getNowDatetime(), ""
    todo.alarm()
    print "todo end   ", todo.getNowDatetime(), "\n"
示例#11
0
def main():
    """ main UI function """

    todo_list = Todo()

    while True:
        cmd, args = ask_option()
        cmd = cmd.lower()

        try:
            if cmd == "add":
                todo_list.add(args)

            elif cmd == "del":
                todo_list.remove(args)

            elif cmd == "ls" and args:
                print(todo_list.show(args))

            elif cmd == "ls":
                for todo in todo_list.show_all():
                    print(todo)

            elif cmd == "save":
                todo_list.save(args)

            elif cmd == "load":
                todo_list.load(args)

            elif cmd == "help":
                print(HELPER)

            elif cmd == "q":
                break

            else:
                print("Invalid option")

        except Exception as err:
            print("ERROR: " + str(type(err)) + " - " + str(err))
示例#12
0
# dunder or magic method

# x = [1,2,3,4]

# # it does same thing in the back
# print(dir(x))
# print(x.__dir__())
# print(2+2)
# print(int.__add__(2,2))

from todo import Todo

s_todo = Todo(name='Sarkash')
t_todo = Todo(name='Tina')

s_todo.add('take the dogs out')
s_todo.add('have breakfast')
s_todo.add('do nothing then')

t_todo.add('company with Sarkash')

print(s_todo > t_todo)
print(s_todo < t_todo)
示例#13
0
    def process(self, msg):
        # array  consisting of all the words
        message_id = msg["id"]
        content = msg["content"].split()
        sender_email = msg["sender_email"]
        ttype = msg["type"]
        stream_name = msg['display_recipient']
        stream_topic = msg['subject']
        timestamp = msg['timestamp']

        if sender_email == BOT_MAIL:
            return

        if content[0].lower() == "neo" or content[0] == "@**neo**":
            message = ""
            if content[1].lower() == "hello":
                message = "Hi"
            elif content[1].lower() == "news":
                try:
                    news = self.news.getTopNews()
                    for item in news:
                        message += "**" + item.title + "**"
                        message += '\n'
                        message += item.des
                        message += '\n\n'
                except:
                    message = "Unable to get news"

            elif content[1].lower() == "translate":
                try:
                    message = content[2:]
                    message = " ".join(message)
                    print(message)
                    message = self.translate.translateMsg(message)
                except:
                    message = "Type in following format : neo translate **word**"

            elif content[1].lower() == "weather":
                try:
                    api_key = fetch_api_key()
                    if len(content) > 2 and content[2].lower() != "":
                        # Query format: Neo weather London
                        weather = get_weather(api_key, content[2].lower())
                        if str(weather['cod']) != "404":
                            message += "[](http://openweathermap.org/img/w/{}.png)".format(
                                weather['weather'][0]['icon'])
                            message += "**Weather report for {}**\n".format(
                                content[2].lower())
                            message += "Temperature: **{}**\n".format(
                                str(weather['main']['temp']) + "° C")
                            message += "Pressure: **{}**\n".format(
                                str(weather['main']['pressure']) + " hPa")
                            message += "Humidity: **{}**\n".format(
                                str(weather['main']['humidity']) + "%")
                            message += "Wind Speed: **{}**".format(
                                str(weather['wind']['speed']) + " $$m/s^2$$")
                        else:
                            message = "City not found!\nabc"
                    else:
                        message = "Please add a location name."
                except:
                    message = "Something went wrong"

            elif content[1].lower() == "geolocation":
                try:
                    place = content[2]
                    result = self.location.getLocation(place)
                    message = "**Latitude** : " + str(
                        result.lat) + "\n" + "**Longitude** : " + str(
                            result.lng)
                except:
                    message = "Type a correct place in following format : neo geolocation **place**"

            elif content[1].lower() == "currency":
                if len(content) == 3 and content[2].lower() != "":
                    # Query format: Neo currency USD
                    currency = fetch_currency_exchange_rate(
                        "", content[2].upper())
                    message += "**Showing all currency conversions for 1 {}:**\n".format(
                        content[2].upper())
                    for curr in currency['rates']:
                        message += "1 {} = ".format(
                            content[2].upper()) + "{}".format(
                                format(currency['rates'][curr],
                                       '.2f')) + " {}\n".format(curr)
                    message += "Last Updated: *{}*".format(currency['date'])
                elif len(content) == 5 and content[2].lower(
                ) != "" and content[4].lower() != "":
                    # Query format: Neo currency INR to USD
                    currency = fetch_currency_exchange_rate(
                        content[2].upper(), content[4].upper())
                    message += "1 {} = ".format(
                        content[4].upper()) + "{}".format(
                            format(currency['rates'][content[2].upper()],
                                   '.2f')) + " {}\n".format(content[4].upper())
                    message += "Last Updated: *{}*".format(currency['date'])
                else:
                    message = "Please ask the query in correct format."

            elif content[1].lower() == "todo":
                # Has to do some more modifications
                try:
                    if content[2].lower() == "add":
                        todoItem = " ".join(content[3:]).lower()
                        Todo("add", self.todoList, todoItem)
                        message = "** The todo is added **\n The current Todo List is :\n\n"
                        message = displayTodo(message, self.todoList)
                    elif content[2].lower() == "done":
                        if content[3].lower().isdigit():
                            itemNo = int(content[3].lower())
                            # print(itemNo)
                            message += "** The item is marked as done **\n"
                            Todo("done", self.todoList, "", itemNo)
                            message = displayTodo(message, self.todoList)
                        else:
                            message = "Enter the Todo item number"
                    elif content[2].lower() == "undone":
                        if content[3].lower().isdigit():
                            itemNo = int(content[3].lower())
                            # print(itemNo)
                            message += "** The item is marked as undone **\n"
                            Todo("undone", self.todoList, "", itemNo)
                            message = displayTodo(message, self.todoList)
                        else:
                            message = "Enter the Todo item number"
                    elif content[2].lower() == "remove":
                        if content[3].lower() != "all":
                            if content[3].lower().isdigit():
                                itemNo = int(content[3].lower())
                                Todo("remove", self.todoList, "", itemNo)
                                message = "** The todo item is removed **\nThe current Todo List is :\n\n"
                                message = displayTodo(message, self.todoList)
                            else:
                                message = "Enter the Todo item number"
                        elif content[3].lower() == "all":
                            Todo("remove_all", self.todoList, "", -1)
                            message = "The Todo list is cleared"
                        else:
                            message = "Invalid todo command"
                    else:
                        message = "Invalid todo command."
                except:
                    message = "Something went wrong"
            elif content[1].lower() == "summarize":
                try:
                    sentenceCount = int(content[2].lower())
                    summarizerType = content[3].upper()
                    document = " ".join(content[4:]).lower()
                    summary = summarizeDoc(summarizerType, document,
                                           sentenceCount)
                    message = "The summary is:\n" + summary
                except:
                    message = "Something went wrong with the command you typed. Please check"
            elif content[1].lower() == "digest":
                # Get all users
                (message, summary) = digest(stream_name, message_id,
                                            sender_email, BOT_MAIL)
                message += "\n** The summary of the messages is : **\n" + summary
            elif content[1].lower() == "checkspam":
                message = ""
                users = client.get_members()
                emails = []
                flag_admin = 1
                for member in users["members"]:
                    if (member["email"] == sender_email):
                        if (not member["is_admin"]):
                            flag_admin = 0
                            break
                    emails.append(member["email"])
                if (flag_admin):
                    results = checkSpam("announce", message_id, emails)
                    flag = 1
                    for item in results:
                        if ((item.similarityRank > 5) and (item.timeRank > 3)):
                            message += "**" + item.email + "** : Suspected\n"
                            flag = 0
                            print(message)
                    if (flag):
                        message = "There is no suspected users"
                else:
                    message = "Function access denied"
            elif content[1].lower() == "discussion":
                # Reminder bot format : neo discussion on <subject> at <time> <Date>
                print(content)

                # Get subject
                subject = ""
                i = 0
                while content[i].lower() != "on":
                    i += 1
                i += 1
                while content[i].lower() != "at":
                    subject += content[i] + " "
                    i += 1
                print("Subject: {}".format(subject))

                # time (Assumed to be UTC)
                time = ""
                i = 0
                while content[i].lower() != "at":
                    i += 1
                i += 1
                time += content[i]
                i += 2
                date = content[i]
                print("Time: {}".format(time))
                print("Date: {}".format(date))
                privateText = "{} arranged a meeting about {} at {} on {}.".format(
                    sender_email, subject, time, date)
                emails = getAllUsers(sender_email, BOT_MAIL)
                print(emails)
                for email in emails:
                    request = {
                        "type": "private",
                        "to": email,
                        "content": privateText
                    }
                    self.client.send_message(request)
                message = "Meeting arranged successfully."
                # print("abc {}".format(timestamp))

                # Reminder
                dt = datetime.utcnow()
                print(dt)
                dt64 = np.datetime64(dt)
                ts = (dt64 -
                      np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(
                          1, 's')
                currSec = int(ts)
                print("Timestamp now: {}".format(currSec))
                meetingTime = date + " " + time
                dt64 = np.datetime64(meetingTime)
                ts = (dt64 -
                      np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(
                          1, 's')
                meetingSec = int(ts)
                print("Timestamp meeting: {}".format(currSec))
                diff = meetingSec - currSec - 1800
                if diff > 0:
                    print("Reminder after {} seconds".format(diff))
                    privateText = "REMINDER: {} arranged a meeting about {} at {} on {}.".format(
                        sender_email, subject, time, date)

                    def abc():
                        print("REMINDER")
                        for email in emails:
                            request = {
                                "type": "private",
                                "to": email,
                                "content": privateText
                            }
                            result = self.client.send_message(request)
                            print("Email:{}, Status:{}".format(
                                email, result['result']))
                        timer.cancel()

                    timer = threading.Timer(diff, abc)
                    timer.start()
            else:
                message = "HELP options : \n"
                message += "**1**. To show top 10 news : **neo news**\n"
                message += "**2**. To set a meeting easier : **neo discussion on <subject> at <time> <date>**\n"
                message += "**3**. To check spam users : **neo checkspam**\n"
                message += "**4**. To summerize any paragraph : **neo summarize <sentence count> <summarization type> <sentences>**\n"
                message += "**5**. To get the summary of previous messages in the stream : **neo digest**\n"
                message += "**6**. ToDo Funtionalities : **neo todo add <name of task>**\n"
                message += "** --** **neo todo done <index of task>**\n"
                message += "** --** **neo todo remove/undone <index of task>**\n"
                message += "** --** **neo todo remove all**\n"
                message += "**7**. To display relative currency values : **neo currency <currency type>**\n"
                message += "** --** **neo currency <type 1> to <type 2>**\n"
                message += "**8**. To get the geolocation : **neo geolocation <place name>**\n"
                message += "**9**. To translate any language to english : **neo translate <word>**\n"
                message += "**10**. To get the weather report of a place : **neo weather <place>**\n"
            self.client.send_message({
                "type": "stream",
                "subject": msg["subject"],
                "to": msg["display_recipient"],
                "content": message
            })
示例#14
0
 def test_no_todo_removed(self):
     todo_app = TodoApp(None)
     todos = [Todo(1, 'two', 1, 1), Todo(2, 'three', 2, 1)]
     reordered_todos = todo_app.recalculate_ordering(todos)
     self.assertEqual(reordered_todos[0].ordering, 1)
     self.assertEqual(reordered_todos[1].ordering, 2)
示例#15
0
    def setUp(self):
        patch('todo.TodoManager._load').start()
        patch('todo.TodoManager._save').start()

        self.manager = TodoManager()
        self.manager.todos = [Todo('foo'), Todo('bar')]
示例#16
0
 def testDifferentDueDates(self):
     comparisonDate = datetime.date(2012,3,7)
     for timeString, result in self.knownValues:
         testTodo = Todo("some dummy stuff +_" + timeString)
         self.assertEqual(testTodo.getDueDistance(comparisonDate), result)
示例#17
0
 def test_default_done(self):
     todo = Todo('bar', True)
     self.assertEqual(todo.task, 'bar')
     self.assertTrue(todo.done)
示例#18
0
 def test_toggle_done(self):
     todo = Todo('baz')
     todo.toggle()
     self.assertTrue(todo.done)
示例#19
0
from todo import Todo

todo = Todo()
data = {
    'title': 66,
    'body': 'validation done for the insertion',
}
todo.create(data)
示例#20
0
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
'''
处理
队列数据
'''
'''
product 为生成环境配置
test 为测试环境配置
'''
_config_set = 'test'

from todo import Todo
import sys

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print "参数有错,如:'python2.7 main.py test'测试环境 或 'python2.7 main.py product'生产环境"
        sys.exit(0)
    _config_set = str(sys.argv[1].lower())
    todo = Todo(_config_set)
    print "todo start ", todo.getNowDatetime(), ""
    todo.alarm()
    print "todo end   ", todo.getNowDatetime(), "\n"
示例#21
0
def create_todo(description: str):
    todo = Todo(description)
    db.session.add(todo)
    db.session.commit()
示例#22
0
 def __init__(self, todo_service: Todo_Service):
     super().__init__(Todo(0, '', '', False), todo_service)
     self.whatyoudoing = 'Adding'
示例#23
0
 def test_default(self):
     todo = Todo('foo')
     self.assertEqual(todo.task, 'foo')
     self.assertFalse(todo.done)
示例#24
0
 def __init__(self):
     self._todo = Todo()
示例#25
0
from todo import Todo
from todo_list import TodoList

print('''
1. Wyswietl liste.
2. Dodaj zadanie.
3. Usun zadanie.
4. Wyjdz.
''')

todo_list = TodoList()

while True:
    option = input('Wybierz czynnosc: (1|2|3|4): ')

    if option == '1':
        todo_list.show()

    if option == '2':
        content = input('Podaj tresc zadania: ')
        new_todo = Todo(content)
        todo_list.add(todo=new_todo)

    if option == '3':
        idx = int(input('Podaj indeks zadania do usuniecia: '))
        todo_list.remove(idx)

    if option == '4':
        break

print('Koniec dzialania progrmu.')
示例#26
0
def create_todo(**kwargs):
    global todos
    todo = Todo(**kwargs)
    todos[todo.id] = todo
    return todo
示例#27
0
  def addTodo(self, data, todo_type = 'todo'):
    todo = Todo(data)
    next_id = self.getNextId()
    if todo_type == 'todo':
      todo.setDone(False)
    elif todo_type == 'done':
      todo.setDone()
      todo.setCompletedDate(time.strftime('%Y-%m-%d'))
    self.data['todos'][next_id] = todo
    self.data['ids'].append(next_id)

    if 'context' not in data:
      todo.setContext('default')

    if 'tracks_id' not in data:
      todo.setTracksId(None)

    if todo.getContext() not in self.data['contexts']:
      self.addContext(todo.getContext())
    self.data['contexts'][data['context']].append(next_id)

    if 'project' not in data:
      data['project'] = 'default'

    if data['project'] not in self.data['projects']:
      self.addProject(data['project'])
    self.data['projects'][data['project']].append(next_id)
示例#28
0
# print(len(x))
# # or
# print(x.__len__())

# print(6+8)
# # or
# print(int.__add__(6,8))

# print('f' + 'w')
# # or
# print(str.__add__('f','w'))
# # this is how Python reads instructions

from todo import Todo

t_todo = Todo(name='Thandiwe')
w_todo = Todo(name='Wanja')
# t_todo is a new object

# print(dir(t_todo))
# print()
# print(dir(Todo))

# print(t_todo)
# # or
# print(repr(t_todo))

# print(str(t_todo))
# print(str(w_todo))

# # these give the same result:
示例#29
0
# DBを毎回手打ちすると辛いので、作り直すためのデフォルトソース
from todo import db, User, Todo

# 一旦データベースを作り直す
db.drop_all()
db.create_all()

# admin ユーザを再作成
user = User('admin')
db.session.add(user)
db.session.commit()

# admin Todoの投稿を2件作成
todo1 = Todo('todotext1', user.id, 0)
todo2 = Todo('todotext2', user.id, 0)
db.session.add(todo1)
db.session.add(todo2)
db.session.commit()
示例#30
0
 def test_reorder_one_todo(self):
     todo_app = TodoApp(None)
     todos = [Todo(1, 'two', 2, 1)]
     reordered_todos = todo_app.recalculate_ordering(todos)
     self.assertEqual(reordered_todos[0].ordering, 1)
示例#31
0
def main():
    # 1
    usename_input = input('Podaj nazwę użytkownika: ')
    password_input = input('Podaj hasło użtkownika: ')
    user = User(usename_input, password_input)

    # 2
    tasks = Todo()  # tworzymy obiekt z klasy todo

    # 3
    tasks.assign_user_to_todo(user)
    print(tasks.assigned_user)

    # 5
    first_note = TodoItem('zrobić zakupy')
    second_note = TodoItem('ogarnąć się')
    third_note = TodoItem('nauczyć się programować')
    # 4
    tasks.add_note(first_note)
    tasks.add_note(second_note)
    tasks.add_note(third_note)

    tasks.display_notes  # przed zmianą wyświetlamy
    tasks.notes[0].toggle_done()  # zmieniamy na 'Done'
    tasks.display_notes()  # po zmianie wyśiwetlamy
示例#32
0
  def addTodo(self, data, todo_type = 'todo'):
    todo = Todo(data)
    # Replace spaces to underscores to avoid todo.txt limitation
    if data['project']:
      data['project'] = data['project'].replace(' ','_')
    if data['context']:
      data['context'] = data['context'].replace(' ','_')
    next_id = self.getNextId()
    if todo_type == 'todo':
      todo.setDone(False)
    elif todo_type == 'done':
      todo.setDone()
      todo.setCompletedDate(time.strftime('%Y-%m-%d'))
    self.data['todos'][next_id] = todo
    self.data['ids'].append(next_id)

    if 'context' not in data:
      todo.setContext('default')

    if 'tracks_id' not in data:
      todo.setTracksId(None)

    # Replace spaces to underscores to avoid todo.txt limitation
    if todo.getContext().replace(' ','_') not in self.data['contexts']:
      self.addContext(todo.getContext().replace(' ','_'))
    self.data['contexts'][data['context']].append(next_id)

    if 'project' not in data:
      data['project'] = 'default'

    if data['project'] not in self.data['projects']:
      self.addProject(data['project'])
    self.data['projects'][data['project']].append(next_id)
示例#33
0
from todo import Todo

mlab.connect()

loop = True
while loop:
    print('''1. New todo
2. View ALL Todos
3. Mark a Todo COMPLETED
4. Delete a Todo
5. Exit''')
    cmd = input("Enter your command? ").upper()
    if cmd == "1":
        name = input("Name: ")
        description = input("Description: ")
        new_todo = Todo(name=name, description=description)
        new_todo.save()
    elif cmd == "2":
        print("= " * 20)
        if Todo.objects().count() == 0:
            print("EMPTY")
        else:
            todo_list = Todo.objects()
            todo_no = 1
            for todo in todo_list:
                print(todo_no, todo, sep=". ")
                todo_no += 1
                print()
        print("= " * 20)
    elif cmd == "3":
        i = int(input("Which one? ")) - 1
示例#34
0
# # dunder or magic method


from todo import Todo

# x= [1,2,3,4]

# print (len(x))

# # the above code can be written in dunder method below and achieve the same result Thus:

# print(x.__len__())

#=========================


k_todo = Todo(name='Kingsley')

e_todo= Todo(name= 'Emmanuel')

k_todo.add('buy milk')
k_todo.add('code python')
k_todo.add('cook dinner')

print(k_todo > e_todo)
示例#35
0
            loadDashboardTodo(todo)
        else:
            print("Date format is not correct")


def viewtask(todo, date):
    print("The task for the date {} are".format(date))
    for index, task in enumerate(todo.tasks[date]):
        print(index + 1, task.getTitle())
    time.sleep(2)


def loadUpdate(todo):
    todo.date


def loadRemove(todo):
    todo.date


if __name__ == "__main__":
    todo = Todo()
    answer = loadWelcome()
    todo.setQuote(getQuote())
    todo.setState("welcome")
    if (answer == 1):  ##Create a new todolist
        newDoc(todo)
    else:  ##Load a new todolist
        loadFile(todo)
    loadDashboardTodo(todo)
示例#36
0
def create_todo():
    input = request.form['todo-text']
    Todo.create_from_form(input)

    return redirect(url_for("index"))
示例#37
0
    def addTodo(self, data, todo_type='todo'):
        todo = Todo(data)
        next_id = self.getNextId()
        if todo_type == 'todo':
            todo.setDone(False)
        elif todo_type == 'done':
            todo.setDone()
            todo.setCompletedDate(time.strftime('%Y-%m-%d'))
        self.data['todos'][next_id] = todo
        self.data['ids'].append(next_id)

        if 'context' not in data:
            todo.setContext('default')

        if 'tracks_id' not in data:
            todo.setTracksId(None)

        if todo.getContext() not in self.data['contexts']:
            self.addContext(todo.getContext())
        self.data['contexts'][data['context']].append(next_id)

        if 'project' not in data:
            data['project'] = 'default'

        if data['project'] not in self.data['projects']:
            self.addProject(data['project'])
        self.data['projects'][data['project']].append(next_id)
示例#38
0
文件: tdl.py 项目: lucasgomesdef/tdl
def todo():
    todos = Todo()
    if len(sys.argv) == 1:
        print('Incorrect usage!')
    else:
        cmd = sys.argv[1]
        if cmd == 'add':
            name = sys.argv[2]
            todos.add(name)
        elif cmd == 'remove':
            id = sys.argv[2]
            todos.remove(id)
        elif cmd == 'show':
            todos.show()
        elif cmd == 'done':
            id = sys.argv[2]
            todos.done(id)
        elif cmd == 'undone':
            id = sys.argv[2]
            todos.undone(id)
        elif cmd == 'clear':
            todos.clear()
    todos.save()
示例#39
0
    def setData(self, data):
        if 'todos' in data:
            for index, todo in data['todos'].items():
                data['todos'][index] = Todo(todo)

        self.data = data
示例#40
0
from todo import Todo
import utils
import webrepl
import network
import time

if __name__ == "__main__":
    try:
        utils.do_quick_reset()
        wlan_ap = network.WLAN(network.AP_IF)
        wlan_ap.active(False)
        if utils.try_connect_internet():
            webrepl.stop()
            wlan_ap.active(False)
            time.sleep(0.3)

            target = Todo()
            target.run()

            # 业务逻辑执行成功,主板灯闪烁3次
            utils.flash_board_led(3)
        else:
            wlan_ap.active(True)
            webrepl.start()

            # 如果网络未连接,主板灯常亮
            utils.flash_board_led(off_time=-1)

    except KeyboardInterrupt:
        print("\nPress CTRL+D to reset device.")
示例#41
0
class TodoDisplay:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("todo")

        self.todo = Todo()
        self.todo_list_box_dict = {}

        self.todo_list_frame = Frame(self.root)
        self.todo_list_frame.grid(column=0, row=1)
        self.todo_detail_frame = Frame(self.root)
        self.todo_detail_frame.grid(column=1, row=1)
        self.function_frame = Frame(self.root)
        self.function_frame.grid(column=0, columnspan=2, row=0)

        self.listbox = Listbox(master=self.todo_list_frame,
                               master_of_detail_text=self.todo_detail_frame)

        self.add_todo_button = Button(master=self.function_frame)
        self.add_todo_button.grid(column=3, row=0)
        self.add_todo_button["text"] = "TODO追加"
        self.add_todo_button["command"] = self.add_todo

        self.refresh_button = Button(master=self.function_frame)
        self.refresh_button.grid(column=2, row=0)
        self.refresh_button["text"] = "更新"
        self.refresh_button["command"] = self.refresh

        self.dir_combbox = Combobox(master=self.function_frame)
        self.dir_combbox.grid(column=1, row=0, padx=(0, 100))
        self.set_value_for_dir_combbox()

        self.sort_combbox = Combobox(master=self.function_frame)
        self.sort_combbox.grid(column=0, row=0, padx=(0, 100))
        self.set_value_for_sort_combbox()

    def display_todo(self):
        todo_list_box_id = 0
        self.todo_list_box_dict = {}
        paths = self.get_paths_which_todo_file_have()

        for path in paths:
            todo_information = self.get_info_which_todo_have(path)
            contents_to_display = self.get_contents_to_display_which_todo_have(
                todo_information)
            self.listbox.insert(todo_list_box_id, contents_to_display)

            importance_color = self.todo.search_importance(
                todo_information["file_name"])
            self.listbox.itemconfig(todo_list_box_id, {'bg': importance_color})

            self.todo_list_box_dict[todo_list_box_id] = path
            todo_list_box_id = todo_list_box_id + 1

        self.listbox.set_todo_list(self.todo_list_box_dict)

    def get_paths_which_todo_file_have(self):
        paths = self.todo.get_paths_which_result_of_search(
            self.dir_combbox.get())
        sorted_paths = self.todo.sort_todo(paths,
                                           method=self.sort_combbox.get())

        return sorted_paths

    def get_info_which_todo_have(self, todo_file_path):
        metadata_list = self.todo.search_meta_data(todo_file_path)
        todo_file_name = todo_file_path.split("\\")[-1].split(".")[0]

        todo_information = {
            "metadata_list": metadata_list,
            "file_name": todo_file_name
        }

        return todo_information

    def get_contents_to_display_which_todo_have(self, todo_information) -> str:
        """
        Listboxへ表示するtodo名、メタデータ名を作成し返す関数

        Parameters
        ----------
        todo_information: dict
            todoに関する情報を格納したディクショナリ

        Returns
        -------
        " ".join(flatten(content_list)): str
            Listboxへ表示する文字列(todo名、メタデータ名を含む)
        """

        content_list = [
            re.sub(r"\[.*\]", "", todo_information["file_name"]),
            todo_information["metadata_list"],
        ]

        return " ".join(flatten(content_list))

    def refresh(self, event=None):
        self.listbox.delete(0, "end")
        self.display_todo()

    def add_todo(self, event=None):
        """
        todoファイルを追加するためにDialogオブジェクトを呼び出す。

        Parameters
        ----------
        event:

        Returns
        -------
        None
        """
        dir_names_items: dict = self.todo.dir_names_items
        DialogForAddTodo(self.root, items_for_combobox=dir_names_items)

    def set_value_for_dir_combbox(self):
        self.dir_combbox["value"] = ["all"] + self.todo.get_dir_name_keys()

    def set_value_for_sort_combbox(self):
        self.sort_combbox["value"] = ["importance", "limit"]

    def mainloop(self):
        self.root.mainloop()