示例#1
0
文件: lon.py 项目: chfr/spiffy
def lon(self, input):
    """How long till the next pay day in Sweden?"""
    
    month = None
    if input.args:
        try:
            month = int(input.args)
        except ValueError:
            pass
        else:
            if month > 12 or month < 1:
                month = None
    
    date = datetime.date.today()
    date = datetime.date(date.year, month or date.month, 25)

    if str(date.year) in self.storage:
        holidays = self.storage[str(date.year)]
    else:
        try:
            data = urllib2.urlopen(icsurl).read()
        except (urllib2.HTTPError, urllib2.URLError):
            holidays = {}
        else:
            holidays = {}            
            lastdate = None
            for line in data.split('\n'):
                line = line.strip('\r').strip('\n')
                if line.startswith('DTSTART;VALUE=DATE:'):
                    lastdate = line.split(':')[1]
                    holidays[lastdate] = None
                elif line.startswith('SUMMARY:'):
                    holidays[lastdate] = line.split(':')[1]
            self.storage[str(date.year)] = holidays
            self.storage.save()

    payday = None
    while date >= datetime.date(date.year, date.month, 1):
        if date.weekday() in (5, 6) or str(date) in holidays:
            date = date - datetime.timedelta(days = 1)
        else:
            payday = date
            break
        
    if payday is not None:
        datedif = datetime.datetime(*payday.timetuple()[:3]) - self.localtime()
        datedif = datedif.days * 24 * 3600 + datedif.seconds
        if datedif < 0:
            self.say(u"Lönen kom %s sedan (%s)" % (humantime(abs(datedif)), payday))
        elif datedif == 0:
            self.say(u"Lönen kommer nu!")
        else:
            self.say(u"Lönen kommer om %s (%s)" % (humantime(abs(datedif)), payday))
            
    else:
        self.say(u'Error: Ingen lön den här månaden?')
示例#2
0
def _comment_get(request, object_id, post_id):
    """
    This function _comment_get will get user's comments for post_id post from db
    sorting by time ascending, and make Commentlist and return.
    @version 0.5
    """

    user = request.user
    Commentlist = []

    if object_id == "":
        CommentDict = Comment.objects.filter(post_id=post_id)

        for CommentObj in CommentDict:
            UserObj = CommentObj.user_id
            comment_identity = Base.objects.get(user=CommentObj.user_id).identity

            Comment_wrap = {
                    "id": CommentObj.id,
                    "content": CommentObj.comment_content,
                    "date": str(CommentObj.comment_date),
                    "humandate": humantime(CommentObj.comment_date),
                    "username": UserObj.last_name,
                    "own": True,
                    "comment_identity": comment_identity
            }

            Commentlist.append(Comment_wrap)

    else:
        UserObj = User.objects.get(id=object_id)
        CommentDict = Comment.objects.filter(user_id=UserObj)
        

        for CommentObj in CommentDict:
            UserObj = CommentObj.user_id
            comment_identity = Base.objects.get(user=CommentObj.user_id).identity

            Comment_wrap = {
                    "id": CommentObj.id,
                    "content": CommentObj.comment_content,
                    "date": str(CommentObj.comment_date),
                    "humandate": humantime(CommentObj.comment_date),
                    "username": UserObj.last_name,
                    "own": False,
                    "comment_identity": comment_identity
            }

            Commentlist.append(Comment_wrap)

    return Commentlist
示例#3
0
def notice_post_get(request, object_id):
    """
    This function notice_post_get will get posts for this dentist request.user
    from new comment Event, then display on a single post & comment homepage.
    @version 0.5
    """

    PostObj = Post.objects.get(id=object_id)
    CommentDict = Comment.objects.filter(post_id=PostObj)

    post_user = PostObj.user_id
    if post_user.id == request.user.id: # leave extend for patient go notice post page
        own = True
        identity = 'D'
    else:
        own = False
        identity = 'P'

    BaseObj = Base.objects.get(user=post_user)
    post_humandate=humantime(PostObj.post_date)

    Commentlist = []

    for CommentObj in CommentDict:

        comment_identity = Base.objects.get(user=CommentObj.user_id).identity

        Comment_wrap = {
                    "id": CommentObj.id,
                    "lastname": CommentObj.user_id.last_name, 
                    "content": CommentObj.comment_content, 
                    "date": CommentObj.comment_date,
                    "humandate": humantime(CommentObj.comment_date),
                    "comment_identity": comment_identity
        }

        Commentlist.append(Comment_wrap)

    result = {
            "own": own,
            "identity": identity,
            "imagephoto": settings.MEDIA_URL + str(BaseObj.imagesmall),
            "PostObj": PostObj,
            "post_humandate": post_humandate,
            "Commentlist": Commentlist
            }

    return render_to_response('notification/post.html', result,
                          context_instance=RequestContext(request))
示例#4
0
def timeline_comment_get(request):
    """
    This function timeline_comment_get will get comments for this post_id post
    from db, and display On Patient's Page
    @version 0.3
    """

    user = request.user
    Commentlist = []
    post_id = request.POST['post_id']

    CommentDict = Comment.objects.filter(post_id=post_id)

    for CommentObj in CommentDict:
        UserObj = CommentObj.user_id
        comment_identity = Base.objects.get(user=CommentObj.user_id).identity

        Comment_wrap = {
                "id": CommentObj.id,
                "content": CommentObj.comment_content,
                "date": str(CommentObj.comment_date),
                "humandate": humantime(CommentObj.comment_date),
                "username": UserObj.last_name,
                # "own": True,
                "comment_identity": comment_identity
        }

        Commentlist.append(Comment_wrap)

    return JsonResponse(Commentlist)
示例#5
0
def timeline_post_get(request):
    """
    This function timeline_post_get will get posts for this patient request.user
    from all followed by him in relationship, then display on Patient's homepage.
    @version 0.5
    """

    Postlist = []

    try:
        page = request.POST['page']
    except:
        page = 1

    step = 10
    end = step * int(page)
    start = step * (int(page)-1)
    is_end = False

    following = [entry.dentist for entry in Relationship.objects.filter(patient=request.user)] # patient's following lists
    print(following)

    total = Post.objects.filter(user_id__in=following).count()

    if (end - total) < step:
        is_end = False
        PostDict = Post.objects.filter(user_id__in=following).order_by('-id')[start:end]

        for PostObj in PostDict:
            post_user = PostObj.user_id
            BaseObj = Base.objects.get(user=post_user)

            Post_wrap = {
                    "id": PostObj.id,
                    "content": PostObj.post_content,
                    "date": str(PostObj.post_date),
                    "humandate": humantime(PostObj.post_date),
                    "img": str(PostObj.img),
                    "img_s": str(PostObj.img_s),
                    "img_m": str(PostObj.img_m),
                    "url": PostObj.url,
                    "comments": PostObj.comment_count,
                    "dentist_id": post_user.id,
                    # "name": post_user.last_name,
                    "name": _show_obj_name(post_user.id),
                    "imagephoto": settings.MEDIA_URL + str(BaseObj.imagesmall),
                    "is_end": is_end
            }

            Postlist.append(Post_wrap)

    else:
        is_end = True
        Post_wrap = {
            "is_end": is_end
        }
        
        Postlist.append(Post_wrap)

    return JsonResponse(Postlist)
示例#6
0
 def run(self):
     start = time.time()
     if self.workers == 0:
         self.count_direct(self.f1)
     elif self.workers == 1:
         self.count_single(self.f1, self.filesize)
     else:
         pool = Pool(self.workers)
         res_list = []
         for i in range(self.workers):
             p1 = self.filesize * i // self.workers
             p2 = self.filesize * (i + 1) // self.workers
             args = [self, self.f1, p1, p2, self.filesize]
             res = pool.apply_async(func=wrap, args=args)
             res_list.append(res)
         pool.close()
         pool.join()
         self._c.update(reduce(operator.add, [r.get() for r in res_list]))
     if self.f2:
         with open(self.f2, "wb") as f:
             f.write(self.result.encode(self.coding))
     else:
         print(self.result)
     cost = time.time() - start
     cost = "{:.1f} seconds".format(cost) if cost < 60 else humantime(cost)
     size = humansize(self.filesize)
     tip = "\nFile size: {}. Workers: {}. Cost time: {}"
     print(tip.format(size, self.workers, cost))
     self.cost = cost + "s"
示例#7
0
文件: postpone.py 项目: chfr/spiffy
def postpone(self, input):
    """Postpones the given command for a given amount of time."""
    m = re.search(r'([^,]+),\s?(.+)', input.args or "", re.I)
    if not m:
        raise self.BadInputError()

    c = pdt.Calendar()
    now = datetime.datetime.utcnow()
    delta = datetime.datetime(*c.parse(m.group(1), now)[0][:-2]) - now
    seconds = delta.days*24*60*60 + delta.seconds + 1
    time = humantime(seconds)
    cmd = m.group(2)
    line = input.line.split(' :', 1)[0]+' :'+cmd
    
    if seconds <= 0:
        raise self.BadInputError('The time entered is invalid.')
    
    def send():
        self.say('\x02[PP]\x02[%s ago] <%s> %s' % (time, input.nick, cmd))
        prefix, command, params, text = self.parsemsg(line)
        if numeric_to_symbolic.has_key(command):
            command = numeric_to_symbolic[command]
        self.bot.handleCommand(command, prefix, params, text, line)
        
    self.say('Postponing the command for %s' % time)
    t = Timer(seconds, send)
    t.start()
示例#8
0
def comment_save(request):
    """
    This function comment_save will save user's comments for this post.
    @version 0.5
    """

    result = {}

    user = request.user
    print(request.user.username)
    UserObj = User.objects.get(username=user)

    print request.POST
    pid = request.POST['pid']
    comment = request.POST['comment']
    comment = comment.strip()

    if len(comment) > 600:
        result = {
                "status": False,
                "msg": "At most enter 600 characters."
        }

        return JsonResponse(result)

    else:
        ip = request.META['REMOTE_ADDR']

        PostObj = Post.objects.get(id = pid)
        comment_count_bef = PostObj.comment_count
        comment_count = comment_count_bef + 1

        Post.objects.filter(id = pid).update(comment_count=comment_count)
        print "Post Update Success!"
        PostObj_new = Post.objects.get(id = pid)

        CommentInsert = Comment(comment_content=comment, comment_author_ip=ip,
                                user_id=user, post_id=PostObj_new)
        CommentInsert.save(force_insert=True)

        CommentObj = Comment.objects.get(id=CommentInsert.id)
        print(str(CommentObj.comment_date))
        print(CommentObj.comment_date)
        print "Comment Insert Success!"
        comment_identity = Base.objects.get(user=CommentObj.user_id).identity

        result = {
                "status": True,
                "id": CommentObj.id,
                "content": CommentObj.comment_content,
                "date": str(CommentObj.comment_date),
                "humandate": humantime(CommentObj.comment_date),
                "username": user.last_name,
                "comment_count": PostObj_new.comment_count,
                "comment_identity": comment_identity
        }

        return JsonResponse(result)
示例#9
0
    def comment_desc(self):
        pid = self.post_id.id
        post_content = self.post_id.post_content
        post_piece = post_content[0:15]
        # print(post_piece)
        name = _show_obj_name(self.user_id.id)
        # print 0
        comment_date_show = humantime(self.comment_date)
        # print comment_date_show
        # print 11

        return (u' %s, %s commented on your post "%s"') % ( comment_date_show, name, post_piece)
示例#10
0
def post_save(request):
    """
    This function post_save will save user's posts in db.
    @version 0.6
    """

    result = {}

    news = request.POST['post']
    news = news.strip()

    try:
        img_s = request.POST['img']
        img = img_s.replace('/s/', '/o/')
        img_m = img_s.replace('/s/', '/m/')
        print 'img is:', img
    except:
        img = img_s = img_m = ''
    try:
        url = request.POST['url']
    except:
        url = ''

    if len(news) > 600:
        result = {
                "status": False,
                "msg": "At most enter 600 characters."
        }

        return JsonResponse(result)

    else:
        news = re.sub('<', '&lt', news) # for tag <a>|</a>
        news = re.sub('>', '&gt', news)
        for m in re.finditer('https?://\S+|www\.\S+', news):
            news = re.sub(m.group(0), (r'<a href="%s">%s</a>') % (m.group(0), m.group(0)), news, count=1)
            print 'news after replace: ', news

        UserObj = User.objects.get(username = request.user)
        BaseObj = Base.objects.get(user=request.user)

        PostInsert = Post(post_content=news, img=img, img_s=img_s, img_m=img_m, url=url, comment_count=0, user_id=UserObj)
        PostInsert.save(force_insert=True)
        # _put_wall_post(request, news)

        post_id = PostInsert.id
        print "Insert Success!"

        PostObj = Post.objects.get(id=post_id)
        print(str(PostObj.post_date))
        result = {
                "status": True,
                "id": PostObj.id,
                "content": PostObj.post_content,
                "date": str(PostObj.post_date),
                "humandate": humantime(PostObj.post_date),
                "img_s": str(PostObj.img_s),
                "img_m": str(PostObj.img_m),
                "url": PostObj.url,
                "name":_show_name(request),
                "imagephoto": settings.MEDIA_URL + str(BaseObj.imagesmall),
        }

        return JsonResponse(result)
示例#11
0
def _post_get(request, object_id, page):
    """
    This function _post_get will judge the user is himself or others,
    then decide to use which method to get user's posts from db 
    and sorting query result by time ascending, then make Postlist, return result.
    @version 0.4
    """

    Postlist = []

    # step for how many lines separate per page. then count nowa page's start line no. and end line no.
    step = 10
    end = step * int(page)
    start = step * (int(page)-1)
    is_end = False
    
    if object_id == "":
        total = Post.objects.filter(user_id=request.user).count()
        BaseObj = Base.objects.get(user=request.user)

        if (end - total) < step:
            is_end = False
            PostDict = Post.objects.filter(user_id=request.user).order_by('-id')[start:end]

            for PostObj in PostDict:
                Post_wrap = {
                        "id": PostObj.id,
                        "content": PostObj.post_content,
                        "date": str(PostObj.post_date),
                        "humandate": humantime(PostObj.post_date),
                        "img_s": str(PostObj.img_s),
                        "img_m": str(PostObj.img_m),
                        "url": PostObj.url,
                        "comments": PostObj.comment_count,
                        "is_end": is_end,
                        "name":_show_name(request),
                        "imagephoto": settings.MEDIA_URL + str(BaseObj.imagesmall),
                }

                Postlist.append(Post_wrap)

        else:
            is_end = True
            Post_wrap = {
                    "is_end": is_end
            }

            Postlist.append(Post_wrap)

    else:
        UserObj = User.objects.get(id=object_id)
        total = Post.objects.filter(user_id=UserObj).count()

        if (end - total) < step:
            is_end = False
            PostDict = Post.objects.filter(user_id=UserObj).order_by('-id')[start:end]

            for PostObj in PostDict:
                post_user = PostObj.user_id
                BaseObj = Base.objects.get(user=post_user)
                Post_wrap = {
                        "id": PostObj.id,
                        "content": PostObj.post_content,
                        "date": str(PostObj.post_date),
                        "humandate": humantime(PostObj.post_date),
                        "img": str(PostObj.img),
                        "img_s": str(PostObj.img_s),
                        "img_m": str(PostObj.img_m),
                        "url": PostObj.url,
                        "comments": PostObj.comment_count,
                        "is_end": is_end,
                        "name": _show_obj_name(post_user.id),
                        "imagephoto": settings.MEDIA_URL + str(BaseObj.imagesmall),
                }

                Postlist.append(Post_wrap)

        else:
            is_end = True
            Post_wrap = {
                    "is_end": is_end
            }

            Postlist.append(Post_wrap)

    return Postlist
示例#12
0
文件: sl.py 项目: liato/spiffy
def sl(self, input):
    """Queries sl.se for train/bus times"""

    cmd = input.args
    if input.command.lower() == "slf":
        cmd = "-f " + cmd

    m = re.search(
        r"(?P<fl>-fl)|-fa (?P<fafrom>[^,]+),\s*?(?P<fato>[^,]+),\s*?(?P<faname>.+)|-fr (?P<frmatch>.+)|-f (?P<favorite>[^,]+)(?:,\s*?(?P<ftime>[01-2]?[0-9][.:]?[0-5][0-9]))?|(?P<later>sen|tidig)(?:are)?|(?P<start>[^,]+),\s*(?P<stop>[^,]+)(?:,\s*?(?:(?P<date>\d{4}-\d{2}-\d{2} [012]?[0-9][.:]?[0-5][0-9])|(?P<time>[01-2]?[0-9][.:]?[0-5][0-9])))?",
        cmd,
        re.I,
    )
    if not m:
        raise self.BadInputError()
        return

    sl_api_key = self.config.get("sl_api_key", "")
    sl_api_url = self.config.get("sl_api_url", "")

    start = stop = sdate = stime = None

    stime = m.group("time") if m.group("time") else stime
    sdate = m.group("date") if m.group("date") else sdate
    user = input.nick.lower()
    if not user in self.storage:
        self.storage[user] = {}
    db = self.storage[user]

    laterTrip = False
    laterTime = None

    if m.group("later"):
        if not "lastTrip" in db:
            self.say("No previous requests on record, do a proper query")
            return

        laterTrip = True

        start, stop, depTime = db["lastTrip"]
        laterTime = depTime + datetime.timedelta(0, 60)
        sdate = laterTime.strftime("%Y-%m-%d %H:%M")

    if m.group("favorite"):
        if m.group("favorite").lower() in db:
            start, stop = db[m.group("favorite").lower().strip()]
            stime = m.group("ftime") if m.group("ftime") else stime
        else:
            self.say("No such favorite, .sl -fl to list your favorites  or .sl -fa <from>, <to>, <name> to add a new.")
            return

    if m.group("fl"):
        if len(db) > 0:
            self.notice(input.nick, "\x02Your favorites:")
            for name, dest in db.iteritems():
                self.notice(input.nick, " %s: %s -> %s" % (name, dest[0], dest[1]))
        else:
            self.notice(input.nick, "No favorites added yet, use .sl -fa <from>, <to>, <name> to add a new favorite.")
        return

    elif m.group("fafrom"):
        db[m.group("faname").strip()] = (m.group("fafrom").strip(), m.group("fato").strip())
        self.storage.save()
        self.notice(input.nick, "Favorite added!")
        return

    elif m.group("frmatch"):
        frmatch = m.group("frmatch").lower()
        for name, dest in db.items():
            if frmatch in name.lower() or frmatch in dest[0].lower() or frmatch in dest[1].lower():
                self.notice(input.nick, "Removing: %s: %s -> %s" % (name, dest[0], dest[1]))
                del db[name]
        self.storage.save()
        return

    start = start or m.group("start")
    stop = stop or m.group("stop")
    if start:
        isDepartureTime = True
        if (sdate or stime) and not laterTrip:
            isDepartureTime = False

        if sdate:
            sdate = sdate[:16]
        elif stime:
            if len(stime) is 1:
                stime = "0%s:00" % stime
            elif len(stime) is 2:
                stime = stime + ":00"
            elif len(stime) is 4:
                stime = stime[:2] + ":" + stime[2:]

            sdate = str(self.localtime())[:11] + stime
        else:
            sdate = str(self.localtime())[:16]

        r = urllib2.urlopen(
            "%sjourneyplanner/?key=%s" % (sl_api_url, sl_api_key),
            data=json.dumps(
                {
                    "origin": {"id": 0, "longitude": 0, "latitude": 0, "name": start},
                    "isTimeDeparture": isDepartureTime,
                    "time": sdate,
                    "destination": {"id": 0, "longitude": 0, "latitude": 0, "name": stop},
                }
            ),
        )

        data = r.read()
        d = json.loads(data)
        if d.get("numberOfTrips", 0) == 0:
            self.say("Couldn't find anything.")
            return
        else:
            trips = d["trips"]
            trip = None

            if not isDepartureTime:  # user specified a desired time of arrival
                desiredTime = datetime.datetime.strptime(sdate, "%Y-%m-%d %H:%M")

                bestTrip = None

                for t in trips:
                    arrivalString = t["arrivalDate"] + " " + t["arrivalTime"]
                    arrivalTime = datetime.datetime.strptime(arrivalString, "%d.%m.%y %H:%M")
                    delta = desiredTime - arrivalTime
                    if (delta.days * 3600 * 24 + delta.seconds) >= 0:
                        bestTrip = t
                    else:
                        break

                trip = bestTrip
            else:  # user wants to go as soon as possible
                bestTrip = None

                for t in trips:
                    departureString = t["departureDate"] + " " + t["departureTime"]
                    departureTime = datetime.datetime.strptime(departureString, "%d.%m.%y %H:%M")
                    delta = (laterTime or self.localtime()) - departureTime
                    if (delta.days * 3600 * 24 + delta.seconds) <= 0:
                        bestTrip = t
                        break
                trip = bestTrip

            if not trip:
                self.say("Couldn't find anything.")
                return

            departureString = trip["departureDate"] + " " + trip["departureTime"]
            departureTime = datetime.datetime.strptime(departureString, "%d.%m.%y %H:%M")
            db["lastTrip"] = (start, stop, departureTime)

            duration = trip["duration"].split(":")
            duration = humantime(int(duration[0]) * 60 * 60 + int(duration[1]) * 60)
            readableDate = datetime.datetime.strptime(trip["departureDate"], "%d.%m.%y").strftime("%Y-%m-%d")
            self.say(
                u"Från \x02%s\x02 till \x02%s\x02, %s %s - %s (%s), %s %s:"
                % (
                    trip["origin"]["name"],
                    trip["destination"]["name"],
                    readableDate,
                    trip["departureTime"],
                    trip["arrivalTime"],
                    duration,
                    (trip["changes"] if trip["changes"] is not 0 else "inga"),
                    ("byte" if trip["changes"] is 1 else "byten"),
                )
            )
            for subtrip in trip["subTrips"]:
                self.say(
                    u"[%s] %s - %s \x02%s\x02 från \x02%s\x02 mot \x02%s\x02. Kliv av vid \x02%s"
                    % (
                        subtrip["transport"]["type"],
                        subtrip["departureTime"],
                        subtrip["arrivalTime"],
                        subtrip["transport"]["name"],
                        subtrip["origin"]["name"],
                        subtrip["transport"]["towards"],
                        subtrip["destination"]["name"],
                    )
                )
示例#13
0
文件: remind.py 项目: chfr/spiffy
def remind(self, input):
    "Delivers a message at a specific time, either relative or absolute."

    if input.args.startswith("-l"):
        dbname = "tellremind.%s.s3db" % self.config["network"]

        if not input.sender.startswith("#"):
            return
            
        try:
            conn = sqlite3.connect(os.path.join("data",dbname))
        except:
            self.say("Could not open tell/remind database!")
            return
        
        c = conn.cursor()
        try:
            c.execute("select * from reminds")
        except:
            self.say("Couldn't read from the database!")
            return
        now = self.localtime()
        rows = c.fetchall()
        c.close()
        conn.close()

        rows = [e for e in rows if e[-1] == input.sender]

        if not rows:
            self.say("No reminds added yet")
            return

        for row in rows:
            id,sender,receiver,msg,time,asktime,chan = row
            time = datetime.datetime.strptime(time,"%Y-%m-%d %H:%M:%S")
            asktime = datetime.datetime.strptime(asktime,"%Y-%m-%d %H:%M:%S")

            self.say(u"Reminder from %s to %s, added on %s, will be delivered on %s:" %(sender,receiver,asktime,time))
            self.say(u'  "%s"' % msg)
        return

    
    i = 0
    use_in = None
    if re.search(r" in (\d{1,} ?d(?:ay)?s?)? ?(-?\d{1,} ?h(?:our)?s?)? ?(-?\d{1,} ?m(?:inute|in)?s?)? ?(-?\d{1,} ?s(?:econd|ec)?s?)?",input.args):
        # we have "remind someone blabla in 3d 1h 1m 3s"
        i = input.args.rindex(" in")
        use_in = True
    elif re.search(r" at (?:(20[0-9]{2})[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01]) ([01]?\d|2[0-3])[:.]?([0-5]\d)|(2[0-3]|[01]?\d)[:.]?([0-5]\d))", input.args):
        # we have "remind someone blabla at 2009-09-09 20:30 (or just 20:30)"
        i = input.args.rindex(" at")
        use_in = False
    else:
        raise self.BadInputError()
        return
    
    try:
        nick = input.args.split()[0]
        reqnick = input.nick
        task = unicode(input.args[input.args.index(nick)+len(nick)+1:i])
        rtime = input.args[i+4:]
    except (ValueError,IndexError):
        raise self.BadInputError()

    if nick == "me":
        nick = input.nick

    seconds = 0
    now = self.localtime()
    if use_in:
        match = re.search(r"(\d{1,} ?d(?:ay)?s?)? ?(-?\d{1,} ?h(?:our)?s?)? ?(-?\d{1,} ?m(?:inute|in)?s?)? ?(-?\d{1,} ?s(?:econd|ec)?s?)?", rtime)
        if match:
            c = pdt.Calendar()
            tup = c.parse(rtime,now)[0]
            then = datetime.datetime(*tup[:-2])

            delta = then - now
            seconds = delta.days*24*60*60 + delta.seconds
            
        else:
            self.say(usage)
            return
    else:
        if len(rtime) > 6: # 2008-08-08 20:30 is always longer than 6 characters
            if not re.match(r"(20[0-9]{2})[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01]) ([01]?\d|2[0-3])[:.]?([0-5]\d)",rtime):
                self.say("Invalid time: " + rtime)
                return
            then = datetime.datetime.strptime(rtime,"%Y-%m-%d %H:%M")
        else:
            if not re.match(r"(2[0-3]|[01]?\d)[:.]?([0-5]\d)",rtime):
                self.say("Invalid time: " + rtime)
                return
            then = datetime.datetime.strptime(now.strftime("%Y-%m-%d ") + rtime,"%Y-%m-%d %H:%M")
        delta = then - now
        seconds = delta.days*24*60*60 + delta.seconds
    

    if seconds < 1:
        self.say("Aborting! Module not found: timetravel.py (you probably suck at entering the time)")
        return
    
    if nick == input.nick:
        self.say(u"I'll tell '%s' to you in %s!" % (task, humantime(seconds)))
    else:
        self.say(u"I'll tell '%s' to %s in %s!" % (task, nick, humantime(seconds)))

    
    
    id = saveremind(self,reqnick,nick,task,
                    self.localtime() + datetime.timedelta(*divmod(seconds,86400)),self.localtime(),input.sender)

    t = Timer(seconds, lambda: tryremind(self,id,reqnick,nick,task,now,input.sender))
    t.start()
示例#14
0
文件: week.py 项目: chfr/spiffy
def week(self, input):
    """Displays the week and weekday for today or for a given date or a date and weekday given a week."""
    
    date = datetime.date(*self.localtime().timetuple()[:3])
    if input.args:
        try:
            date = datetime.date(*time.strptime(input.args, '%Y-%m-%d')[:3])
        except ValueError:
            try:
                isoweek = int(input.args)
                firstweek = datetime.date(date.year, 1, 4)
                thisweek = firstweek + datetime.timedelta(days=(isoweek-1)*7)
                thisweek = thisweek - datetime.timedelta(days=thisweek.isoweekday()-1)
                timedif = datetime.datetime(*thisweek.timetuple()[:3]) - self.localtime()
                timedif = timedif.days*24*3600 + timedif.seconds
                if not thisweek.year == date.year:
                    raise self.BadInputError('Year %d does not have a week %d.' % (date.year, isoweek))
                self.say('The first date of week \x02%d\x02 is \x02%s\x02 (%s %s)' % (thisweek.isocalendar()[1],
                                                                                      thisweek,
                                                                                      humantime(abs(timedif)),
                                                                                      ('left' if timedif > 0 else 'ago')))
                return
            except (ValueError, OverflowError):
                raise self.BadInputError('Invalid date or week.')
                
    self.say("\x02%s\x02 is a \x02%s\x02 in week \x02%d\x02" % (date,
                                       days[date.isoweekday()-1],
                                       date.isocalendar()[1]))
示例#15
0
def mail_history(request,object_id):

    UserObj =User.objects.get(username = request.user)
    contacter = User.objects.get(id = object_id)

    UserInfo =Base.objects.get(user=UserObj)
    contacterInfo =Base.objects.get(user=contacter)

    mails = [entry.mailtext for entry in MailInfo.objects.filter(receiver = UserObj)]
    mails_a = [entry.mailtext for entry in MailInfo.objects.filter(receiver = contacter)]

    mails_received = []
    mails_sended = []
    DATE_FORMAT = "%Y%m%d%H%M%s"
    for i in mails:
        if i.sender == contacter:
            MailInfo.objects.filter(receiver=UserObj,mailtext=i).update(status=1) #标记为已读
            time_reminder = i.content.find('#calendar')
            if time_reminder != -1:
                reminder = i.content[time_reminder+9:]
            else:
                reminder = ''
            mail = {
                # "sender":json_serialize(i.sender),
                "name":_show_obj_name(object_id),
                "avatar": settings.MEDIA_URL + str(contacterInfo.imagesmall),
                "uid":UserObj.id,
                "content":i.content[:time_reminder],
                "type": i.type,
                "reminder": reminder,
                "date":str(i.post_date),
                "humandate":humantime(i.post_date),
                "int_date": mktime(i.post_date.timetuple()),
                "own":False,
            }
            mails_received.append(mail)

    for i in mails_a:
        if i.sender == UserObj:
            time_reminder = i.content.find('#calendar')
            if time_reminder != -1:
                reminder = i.content[time_reminder+9:]
            else:
                reminder = ''
            mail = {
                # "sender":json_serialize(i.sender),
                "name":_show_name(request),
                "avatar": settings.MEDIA_URL + str(UserInfo.imagesmall),
                "uid":UserObj.id,
                "content":i.content[:time_reminder],
                "type": i.type,
                "reminder": reminder,
                "date":str(i.post_date),
                "humandate":humantime(i.post_date),
                "int_date": mktime(i.post_date.timetuple()),
                "own":True,
        }
            mails_sended.append(mail)
    mail_history = mails_received + mails_sended
    mail_history.sort(cmp=lambda x,y:cmp(y["int_date"],x["int_date"]))

    paginator = Paginator(mail_history,10)  ##分页处理
    try:
        page = int(request.GET.get('page','1'))
    except Valueerrors:
        page = 1
    try:
        mail_per_page = paginator.page(page)
    except(EmptyPage,InvalidPage):
        mail_per_page = paginator.page(paginator.num_pages)

    if Base.objects.get(user=UserObj).identity == "D":
        template_var = {
        
                'mail_per_page':mail_per_page,
                'mail_history': mail_history,
                'contacter_list':_get_patlist_info(request)["Connected_List"],
                'uid':object_id,
                'dentist':True,
                'name':_show_obj_name(object_id),
        } 
    else:
        template_var = {
        
                'mail_per_page':mail_per_page,
                'mail_history': mail_history,
                'contacter_list':_get_denlist_info(request)["Connected_List"],
                'uid':object_id,
                'dentist':False,
                'name':_show_obj_name(object_id),
        } 
    
    return template_var