Esempio n. 1
0
def alerts(request, serviceid):
    field_vars = {
        'section': 'alerts',
        'service': Service.objects.get(pk=serviceid),
    }

    # add last reviewed on to field vars if it's present
    if 'alerts_reviewed_on' in request.session and serviceid in request.session[
            'alerts_reviewed_on']:
        field_vars['alerts_reviewed_on'] = request.session[
            'alerts_reviewed_on'][serviceid]

    if 'show_all' in request.GET:
        # just show all of them
        field_vars['alerts'] = Alert.objects.filter(
            alert_type__service__id=serviceid)
        field_vars['show_all'] = True
    elif 'from' in request.GET:
        # parse at least the from field, and preferably the to field as well
        p = pdt.Calendar()
        from_clean = urllib.unquote(request.GET['from'].replace('+', ' '))
        from_time = p.parse(from_clean)
        from_datetime = datetime.fromtimestamp(time.mktime(from_time[0]))

        field_vars['from'] = from_clean
        if 'custom' in request.GET: field_vars['custom'] = 'true'

        if 'to' not in request.GET or request.GET['to'].strip() == "":
            # use only the from field
            field_vars['alerts'] = Alert.objects.filter(
                alert_type__service__id=serviceid, add_date=from_datetime)
        else:
            # attempt to parse to, since it's here
            to_clean = urllib.unquote(request.GET['to'].replace('+', ' '))
            to_time = p.parse(to_clean)

            field_vars['to'] = to_clean

            if (to_time[1] > 0):
                # it was parseable, make the range reflect this
                to_datetime = datetime.fromtimestamp(time.mktime(to_time[0]))
                field_vars['alerts'] = Alert.objects.filter(
                    alert_type__service__id=serviceid,
                    add_date__gte=from_datetime,
                    add_date__lte=to_datetime)
            else:
                # it was unparseable, just use from
                field_vars['alerts'] = Alert.objects.filter(
                    service__id=serviceid, add_date__gte=from_datetime)
    elif 'alerts_reviewed_on' in request.session and serviceid in request.session[
            'alerts_reviewed_on']:
        field_vars['alerts'] = Alert.objects.filter(
            alert_type__service__id=serviceid,
            add_date__gte=request.session['alerts_reviewed_on'][serviceid])
    else:
        # the default is also just to show all records (perhaps combine with first clause somehow)
        field_vars['alerts'] = Alert.objects.filter(
            alert_type__service__id=serviceid)

    merge_contextuals(field_vars, request, serviceid)
    return render_to_response('dashboard/contexts/monitor/alerts.html',
                              field_vars,
                              context_instance=RequestContext(request))
Esempio n. 2
0
def messagelog(request, patientid, mode='sms'):
    field_vars = {
        'section': 'messagelog',
        'patient': Patient.objects.get(pk=patientid)
    }

    # import the authoritative rapidsms message log
    from rapidsms.contrib.messagelog.models import Message

    # and grab the patient's identity from the Patient object
    if mode:
        address = field_vars['patient'].get_mode_address(mode)
    else:
        address = field_vars['patient'].address

    if 'from' in request.GET:
        # parse at least the from field, and preferably the to field as well
        p = pdt.Calendar()
        from_clean = urllib.unquote(request.GET['from'].replace('+', ' '))
        from_time = p.parse(from_clean)
        from_datetime = datetime.datetime.fromtimestamp(
            time.mktime(from_time[0]))

        field_vars['from'] = from_clean
        if 'custom' in request.GET: field_vars['custom'] = 'true'

        if 'to' not in request.GET or request.GET['to'].strip() == "":
            # use only the from field
            field_vars['messages'] = Message.objects.filter(
                connection__identity=address, date__gte=from_datetime)
        else:
            # attempt to parse to, since it's here
            to_clean = urllib.unquote(request.GET['to'].replace('+', ' '))
            to_time = p.parse(to_clean)

            field_vars['to'] = to_clean

            if (to_time[1] > 0):
                # it was parseable, make the range reflect this
                to_datetime = datetime.datetime.fromtimestamp(
                    time.mktime(to_time[0]))
                field_vars['messages'] = Message.objects.filter(
                    connection__identity=address,
                    date__gte=from_datetime,
                    date__lte=to_datetime)
            else:
                # it was unparseable, just use from
                field_vars['messages'] = Message.objects.filter(
                    connection__identity=address, date__gte=from_datetime)
    else:
        field_vars['messages'] = Message.objects.filter(
            connection__identity=address)

    # order by add date descending after we have a list
    # django lazy query evaluation means that nothing is actually happening here
    # the ordering will occur when the page iterates over 'processes'
    field_vars['messages'] = field_vars['messages'].extra(
        select={
            'day': """strftime('%%m/%%d/%%Y', date)"""
        }).order_by('date')

    merge_contextuals(field_vars, request, patientid)
    return render_to_response('dashboard/contexts/patients/messagelog.html',
                              field_vars,
                              context_instance=RequestContext(request))
Esempio n. 3
0
def parse_time(time_string):
	p = pdt.Calendar()
	tz = get_localzone()
	return datetime.datetime(*p.parse(time_string)[0][:6]).replace(tzinfo=tz)
Esempio n. 4
0
import datetime
import logging

try:
    from parsedatetime import parsedatetime
except ImportError:
    import parsedatetime

pdt = parsedatetime.Calendar()

from tsresolve.constants import *

log = logging.getLogger('tsresolve')
# log.setLevel(logging.DEBUG)

RE_DATES = re.compile(r'(?P<date>\d{1,2}st|\d{1,2}nd|\d{1,2}rd|\d{1,2}th)')
RE_YEAR = re.compile(r'(?P<year>\s\d{4})(\s|$)')
RE_AMMOD = re.compile(
    r'(?P<ammod>\sprevious|\sthis|\snext|\slast|\scoming|\supcoming)')
RE_MONTH_NAMES = re.compile(
    r'(?P<ammod>previous|this|next|last|coming|upcoming)?\s(?P<month>january|february|march|april|'
    r'may|june|july|august|september|october|november|december)\s?'
    r'(?P<date>\d{1,2}st|\d{1,2}nd|\d{1,2}rd|\d{1,2}th)?\s?(?P<year>\d{4})?')
RE_DAYS = re.compile(
    r'%s?\s(?P<day>sunday|monday|tuesday|wednesday|thursday|friday|saturday|weekend)'
    % RE_AMMOD.pattern)
RE_TILL = re.compile(
    r'(?P<today>till\stoday|till\sdate|until\stoday|till\snow|till\stime|till\syesterday|till\stomorrow)'
)

RE_TIME = re.compile(
Esempio n. 5
0
import os
import datetime
import csv

from django.template.defaultfilters import slugify

from parsedatetime import parsedatetime as pdt, parsedatetime_consts as pdc
import time, datetime

#### parsedatetime stuff

# create an instance of Constants class so we can override some of the defaults
c = pdc.Constants()

# create an instance of the Calendar class and pass in our Constants # object instead of letting it create a default
p = pdt.Calendar(c)

# parse "tomorrow" and return the result
#result = p.parse("tomorrow")

# parseDate() is a helper function that bypasses all of the # natural language stuff and just tries to parse basic dates # but using the locale information
#result = p.parseDate("4/4/80")

#### globals

trace = 0
teeth = 0  # whether to get latest extract from zope
dbteeth = 1  # whether to update db

if dbteeth:
    from django_eracks.apps.orders.models import ImportedOrderLine
def parse(s):
    """
    Parse the string using parsedatetime and format it to the current timezone
    """
    return TZ.localize(
        datetime(*tuple(pdt.Calendar(pdc.Constants()).parse(s)[0])[:7]))
Esempio n. 7
0
def create_event_message(event, user):
#    if event['name'] == 'Convideu al canal':
#        if event['invite'] == 'yes':
#            user_f = user['first_name']
#            user_ln = user['last_name']
#            user_u = user['username']
#            if user_ln != "" and user_u != "":
#               user_d= user_f + " " + user_ln + "* (podeu contactar-hi amb @" + user_u + ")"
#            elif user_ln == "" and user_u != "":
#               user_d= user_f + "* (podeu contactar-hi amb @" + user_u + ")" 
#            elif user_ln != "" and user_u == "":
#               user_d= user_f + " " + user_ln + "*"
#            elif user_ln == "" and user_u == "":
#               user_d= user_f + "*"
#            message_text = 'Missatge del robot del CELP\n\n\u2709\uFE0F *' +user_d + " us convida al canal privat *«CELP familiar»*.\n\nPer entrar-hi premeu el botó \U0001F4E2 _Entreu a CELP familiar_, i a continuació seleccioneu *«JOIN»* o bé *«AFEGEIX-M'HI»*.\n\nSi us afegiu a aquest canal privat només rebreu informació de les excursions i tindreu l'opció d'apuntar-vos-hi, però això no és un grup, per tant ningú hi pot escriure."
#            return message_text
#    else:
        eventdate2= int(event['date']) + 600

        today= datetime.datetime.now()
        day = str(today.day)
        month = str(today.month)
        year = str(today.year)
        hour = str(today.hour)
        minute = str(today.minute)
        today2= month + '/' + day + '/' + year + ' ' + hour + ':' + minute

        cal = parsedatetime.Calendar()
        time_struct, parse_status = cal.parse(today2)
        timestamp = time.mktime(datetime.datetime(*time_struct[:6]).timetuple())
        today3= int(timestamp)

        if event['type'] == 'Senderisme':
            emojitype = Emoji.ATHLETIC_SHOE
        elif event['type'] == 'Bicicleta':
            emojitype = Emoji.MOUNTAIN_BICYCLIST
        elif event['type'] == 'Nocturna':
            emojitype = Emoji.MILKY_WAY

        message_text = (emojitype + " *{name}*\n{date}\n").format(
            name=event['name'],
            date=format_date(event['date'])
        )

        if 'difficulty' in event:
            message_text += 'Dificultat: ' + event['difficulty'] +'\n'

        if 'description' in event:
            message_text += '\n_' + event['description'] + '_\n'

        if 'duration' in event:
            message_text += '\n⏱️ ~' + event['duration'] + '\n'

        if 'place' in event:
            if event['place'].find('|') > 0:
               (latit, longi) = tuple(event['place'].split('|'))
               message_text += Emoji.ROUND_PUSHPIN + ' [Punt de trobada](https://www.openstreetmap.org/?mlat=' + latit + '&mlon=' + longi + '#map=15/' + latit + '/' + longi + ').\n'

            else:
               message_text += Emoji.ROUND_PUSHPIN + ' ' + event['place'] + ' [(mapa)](http://www.openstreetmap.org/search?query=' + urllib.parse.quote(event.get("place")) + ').\n'

        if 'parking' in event:
            if event['parking'].find('|') > 0:
               (latit, longi) = tuple(event['parking'].split('|'))
               message_text += Emoji.AUTOMOBILE + ' [Punt d\'aparcament](https://www.openstreetmap.org/?mlat=' + latit + '&mlon=' + longi + '#map=15/' + latit + '/' + longi + ').\n'
            else:
               message_text += Emoji.AUTOMOBILE + ' ' + event['parking'] + ' [(mapa)](http://www.openstreetmap.org/search?query=' + urllib.parse.quote(event.get("parking")) + ').\n'

    #   if 'route' in event:
    #       message_text += '\n' + Emoji.CLOCKWISE_DOWNWARDS_AND_UPWARDS_OPEN_CIRCLE_ARROWS + ' [Mapa amb la ruta](' + event['route'] + ')'

        if 'users' in event and len(event['users']) > 0:
            if today3 >= eventdate2:
                message_text += '\nS\'hi van apuntar: \n'
            else:
                message_text += '\nHi aniran: \n'
            for u in event['users']:
                message_text += '\u27A9 '

                if u.get('username'):
                    message_text += "["

                message_text += u['first_name']

                if u.get('last_name'):
                    message_text += ' ' + u['last_name']

                if u.get('username') and eventdate2 > today3:
                    message_text += "](t.me/" + u['username'] + ")"
                message_text += ' '

                #Famílies de pare amb 1 o 2 fills
                if u['man'] == 1 and u['woman'] == 0 and u['boy'] == 1 and u['girl'] == 0:
                    message_text += '\U0001F468\u200D\U0001F466'
                elif u['man'] == 1 and u['woman'] == 0 and u['boy'] == 0 and u['girl'] == 1:
                    message_text += '\U0001F468\u200D\U0001F467'
                elif u['man'] == 1 and u['woman'] == 0 and u['boy'] == 1 and u['girl'] == 1:
                    message_text += '\U0001F468\u200D\U0001F467\u200D\U0001F466'
                elif u['man'] == 1 and u['woman'] == 0 and u['boy'] == 2 and u['girl'] == 0:
                    message_text += '\U0001F468\u200D\U0001F466\u200D\U0001F466'
                elif u['man'] == 1 and u['woman'] == 0 and u['boy'] == 0 and u['girl'] == 2:
                    message_text += '\U0001F468\u200D\U0001F467\u200D\U0001F467'
                #Famílies de mare amb 1 o 2 fills
                elif u['man'] == 0 and u['woman'] == 1 and u['boy'] == 1 and u['girl'] == 0:
                    message_text += '\U0001F469\u200D\U0001F466'
                elif u['man'] == 0 and u['woman'] == 1 and u['boy'] == 0 and u['girl'] == 1:
                    message_text += '\U0001F469\u200D\U0001F467'
                elif u['man'] == 0 and u['woman'] == 1 and u['boy'] == 1 and u['girl'] == 1:
                    message_text += '\U0001F469\u200D\U0001F467\u200D\U0001F466'
                elif u['man'] == 0 and u['woman'] == 1 and u['boy'] == 2 and u['girl'] == 0:
                    message_text += '\U0001F469\u200D\U0001F466\u200D\U0001F466'
                elif u['man'] == 0 and u['woman'] == 1 and u['boy'] == 0 and u['girl'] == 2:
                    message_text += '\U0001F469\u200D\U0001F467\u200D\U0001F467'
                #Famílies de parella i 1 o 2 fills
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 1 and u['girl'] == 0:
                    message_text += '\U0001F46A'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 0 and u['girl'] == 1:
                    message_text += '\U0001F468\u200D\U0001F469\u200D\U0001F467'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 1 and u['girl'] == 1:
                    message_text += '\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 2 and u['girl'] == 0:
                    message_text += '\U0001F468\u200D\U0001F469\u200D\U0001F466\u200D\U0001F466'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 0 and u['girl'] == 2:
                    message_text += '\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F467'
                #Famílies de parella i 3 fills
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 0 and u['girl'] == 3:
                    message_text += '\U0001F468\u200D\U0001F467\u200D\U0001F467\U0001F469\u200D\U0001F467'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 1 and u['girl'] == 2:
                    message_text += '\U0001F468\u200D\U0001F467\u200D\U0001F466\U0001F469\u200D\U0001F467'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 3 and u['girl'] == 0:
                    message_text += '\U0001F468\u200D\U0001F466\u200D\U0001F466\U0001F469\u200D\U0001F466'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 2 and u['girl'] == 1:
                    message_text += '\U0001F468\u200D\U0001F466\u200D\U0001F466\U0001F469\u200D\U0001F467'

                #Famílies de parella i 4 fills
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 0 and u['girl'] == 4:
                    message_text += '\U0001F468\u200D\U0001F467\u200D\U0001F467\U0001F469\u200D\U0001F467\u200D\U0001F467'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 1 and u['girl'] == 3:
                    message_text += '\U0001F468\u200D\U0001F467\u200D\U0001F466\U0001F469\u200D\U0001F467\u200D\U0001F467'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 2 and u['girl'] == 2:
                    message_text += '\U0001F468\u200D\U0001F466\u200D\U0001F466\U0001F469\u200D\U0001F467\u200D\U0001F467'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 3 and u['girl'] == 1:
                    message_text += '\U0001F468\u200D\U0001F466\u200D\U0001F466\U0001F469\u200D\U0001F467\u200D\U0001F466'
                elif u['man'] == 1 and u['woman'] == 1 and u['boy'] == 4 and u['girl'] == 0:
                    message_text += '\U0001F468\u200D\U0001F466\u200D\U0001F466\U0001F469\u200D\U0001F466\u200D\U0001F466'
                else:
                     if u.get('man') and u['man'] == 1:
                         message_text += '\U0001F468\U0001F3FB'
                     if u.get('man') and u['man'] == 2:
                         message_text += '\U0001F468\U0001F3FB\U0001F468\U0001F3FB'
                     if u.get('man') and u['man'] == 3:
                         message_text += '\U0001F468\U0001F3FB\U0001F468\U0001F3FB\U0001F468\U0001F3FB'
                     if u.get('man') and u['man'] == 4:
                         message_text += '\U0001F468\U0001F3FB\U0001F468\U0001F3FB\U0001F468\U0001F3FB\U0001F468\U0001F3FB'
                     if u.get('man') and u['man'] == 5:
                         message_text += '\U0001F468\U0001F3FB\U0001F468\U0001F3FB\U0001F468\U0001F3FB\U0001F468\U0001F3FB\U0001F468\U0001F3FB'
                     if u.get('woman') and u['woman'] == 1:
                         message_text += '\U0001F469\U0001F3FB'
                     if u.get('woman') and u['woman'] == 2:
                         message_text += '\U0001F469\U0001F3FB\U0001F469\U0001F3FB'
                     if u.get('woman') and u['woman'] == 3:
                         message_text += '\U0001F469\U0001F3FB\U0001F469\U0001F3FB\U0001F469\U0001F3FB'
                     if u.get('woman') and u['woman'] == 4:
                         message_text += '\U0001F469\U0001F3FB\U0001F469\U0001F3FB\U0001F469\U0001F3FB\U0001F469\U0001F3FB'
                     if u.get('woman') and u['woman'] == 5:
                         message_text += '\U0001F469\U0001F3FB\U0001F469\U0001F3FB\U0001F469\U0001F3FB\U0001F469\U0001F3FB\U0001F469\U0001F3FB'
                     if u.get('boy') and u['boy'] == 1:
                         message_text += '\U0001F466\U0001F3FC'
                     if u.get('boy') and u['boy'] == 2:
                         message_text += '\U0001F466\U0001F3FC\U0001F466\U0001F3FC'
                     if u.get('boy') and u['boy'] == 3:
                         message_text += '\U0001F466\U0001F3FC\U0001F466\U0001F3FC\U0001F466\U0001F3FC'
                     if u.get('boy') and u['boy'] == 4:
                         message_text += '\U0001F466\U0001F3FC\U0001F466\U0001F3FC\U0001F466\U0001F3FC\U0001F466\U0001F3FC'
                     if u.get('boy') and u['boy'] == 5:
                         message_text += '\U0001F466\U0001F3FC\U0001F466\U0001F3FC\U0001F466\U0001F3FC\U0001F466\U0001F3FC\U0001F466\U0001F3FC'
                     if u.get('girl') and u['girl'] == 1:
                         message_text += '\U0001F467\U0001F3FC'
                     if u.get('girl') and u['girl'] == 2:
                         message_text += '\U0001F467\U0001F3FC\U0001F467\U0001F3FC'
                     if u.get('girl') and u['girl'] == 3:
                         message_text += '\U0001F467\U0001F3FC\U0001F467\U0001F3FC\U0001F467\U0001F3FC'
                     if u.get('girl') and u['girl'] == 4:
                         message_text += '\U0001F467\U0001F3FC\U0001F467\U0001F3FC\U0001F467\U0001F3FC\U0001F467\U0001F3FC'
                     if u.get('girl') and u['girl'] == 5:
                         message_text += '\U0001F467\U0001F3FC\U0001F467\U0001F3FC\U0001F467\U0001F3FC\U0001F467\U0001F3FC\U0001F467\U0001F3FC'
                if u.get('car') and u['car'] == 1:
                    message_text += '\U0001F697'
                if u.get('car') and u['car'] == 2:
                    message_text += '\U0001F697\U0001F697'
                if u.get('car') and u['car'] == 3:
                    message_text += '\U0001F697\U0001F697\U0001F697'
                message_text += '\n'
        if today3 >= eventdate2:
             message_text += "\n\U0001F5C3 Excursió arxivada."
#        else:
#             message_text += "\n\U0001F527 Instruccions d'ús dels botons: [aquí](http://telegra.ph/Instruccions-d%c3%bas-CELP-familiar-11-28)."

        return message_text
Esempio n. 8
0
 def __init__(self):
     self.pdtCalendar = parsedatetime.Calendar()
Esempio n. 9
0
import datetime
import json

from django.http import HttpResponse

from parsedatetime import parsedatetime, parsedatetime_consts


def json_r(data_dict, cls=None):
    if not cls:
        cls = HttpResponse
    return cls(json.dumps(data_dict), mimetype='application/json')


def smart_int(string, fallback=0):
    """Convert a string to int, with fallback for invalid strings or types."""
    try:
        return int(float(string))
    except (ValueError, TypeError):
        return fallback


date_constants = parsedatetime_consts.Constants()
date_parser = parsedatetime.Calendar(date_constants)


def strtodatetime(string):
    return datetime.datetime(*date_parser.parse(string)[0][0:6])
Esempio n. 10
0
    def parse_natural_time(self, time_str):
        cal = pdt.Calendar()
        time_tuple = cal.parse(time_str)[0][:-2]

        return datetime.datetime(*time_tuple)
Esempio n. 11
0
def parsetask():
    if not g.user:
        abort(404)
    else:
        # F**K IT
        # # parse natural language
        # unparsed = request.form['new_task']
        # # parse the input to get name, dueday, duetime, estimate
        # # 6.033 pset due next friday at 10pm should take about 3 hours
        # # 6.033 pset due friday 10pm 3hr

        # # right now doing a primitive version, TODO: use Hamming distance or classifiers / HMM to get true accuracy / robustness
        # # keywords: before due, after due, after at, before hours
        # split_up = unparsed.split()
        # due_index = split_up.index('due')
        # if unparsed.find('at') != -1:
        #     at_index = split_up.index('at')
        # else:
        #     at_index = None 
        # if unparsed.find('hours') != -1:
        #     hours_index = split_up.index('hours')
        # else:
        #     hours_index = None

        # errors = []

        # # TODO: refactor this crap

        # # name of task. return: STRING
        # name = ' '.join(split_up[:due_index])
        # if not name:
        #     errors.append('No task name found')

        # # due day. return: UNIX TIMESTAMP
        # if at_index != 
        # day_string = ' '.join(split_up[due_index:at_index])
        # cal = pdt.Calendar()
        # due_day = cal.parse(day_string)
        # if due_day[1] == 0 or due_day[1] == 2:
        #     errors.append('No due day found')
        # elif due_day[1] == 1 or due_day[1] == 3:
        #     due_day = time.mktime(datetime(due_day[0].tm_year,due_day[0].tm_mon,due_day[0].tm_mday).timetuple())

        # # due time. return: MILLISECONDS
        # time_string = split_up[at_index+1]
        # due_time = cal.parse(time_string)
        # if due_time[1] == 2:
        #     #good
        #     due_time = time.mktime(datetime(due_time[0].tm_hour))
        # else:
        #     # no time string, this is okay
        #     due_time = None

        # # estimated time required. return: MILLISECONDS
        # estimate = split_up[hours_index-1]

        # Assume that inputs come in already parsed
        name = request.form['name']
        day_string = request.form['date'] # Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
        #time_string = request.form['due_time']  # HH:MM
        time_string = "noon"
        estimate = request.form['length']

        cal = pdt.Calendar()
        # estimated number of seconds
        n = datetime.now()
        current_unix = time.mktime(n.timetuple())
        est, what2 = cal.parse(estimate)
        intermediate = datetime(*est[:6])
        est_unix = int(intermediate.strftime("%s"))
        required = int(est_unix - current_unix)
        # due day
        dt = None
        okay = day_string.split()[1]+' at '+time_string
        print okay
        due, what = cal.parse(okay)
        print due, what
        unixstmp = None
        if what in (1, 2):
            # result is struct_time
            dt = datetime(*due[:6])
            unixstmp = int(dt.strftime("%s"))
            print "unixstmp",unixstmp
        else:
            # result is datetime
            unixstmp = int(time.mktime(due))
            print "unixstmp",unixstmp
        if not unixstmp:
            print "Could not understand"
            abort(404)
        # is this year or next year closer?
        next_year = abs(int(unixstmp) - int(current_unix))
        this_year = abs(int(unixstmp) - 31557600 - int(current_unix))
        if this_year < next_year:
            unixstmp = int(unixstmp) - 31557600
        # make/add new Task
        task = Task(name, unixstmp, required)
        g.user.tasks.append(task)
        db.session.commit()
        return str(task.id)
Esempio n. 12
0
 def __init__(self, datamgr=None):
     self.pdtCal = pdt.Calendar()
     if datamgr:
         self.data_lumbergh = datamgr
Esempio n. 13
0
    def d(text):
        p = pdt.Calendar()
        result = p.parse(text)

        return strftime(format, result[0])
Esempio n. 14
0
    'poppy_nogood': 'chtr',
    'octavious': 'joshc'
})

server = 'irc.freenode.net'
channel = '#rhnoise'

# filename of weechat style irc log
logfile = 'fish_scraps'

# filename of shelved .delays
shelffile = 'bookshelf'

# parsedatetime constants
pdc_const = pdc.Constants()
pdc_cal = pdt.Calendar(pdc_const)


class MarkBotFactory(protocol.ClientFactory):
    def __init__(self, channel, filename):
        self.channel = channel
        self.filename = filename

    def buildProtocol(self, addr):
        p = MarkBot()
        p.factory = self
        p.reshelve()
        return p

    def clientConnectionLost(self, connector, reason):
        connector.connect()
Esempio n. 15
0
def create_keyboard(event, user):
#    if event.get('invite'):
#        button = [
#            InlineKeyboardButton(
#                text="\U0001F4E2 Entreu a CELP familiar",
#                url=links['channel']
#            )
#        ]
#        return [button, []]
#
#    else:
        eventdate2= int(event['date']) + 600

        today= datetime.datetime.now()
        day = str(today.day)
        month = str(today.month)
        year = str(today.year)
        hour = str(today.hour)
        minute = str(today.minute)
        today2= month + '/' + day + '/' + year + ' ' + hour + ':' + minute

        cal = parsedatetime.Calendar()
        time_struct, parse_status = cal.parse(today2)
        timestamp = time.mktime(datetime.datetime(*time_struct[:6]).timetuple())
        today3= int(timestamp)

        button = [
            InlineKeyboardButton(
                text="\U0001F465 Apunta'm / Desapunta'm",
                callback_data='go_' + str(event.eid)
            )
        ]

        button2 = [
            InlineKeyboardButton(
                text="\U0001F468\U0001F3FB",
                callback_data='goman_' + str(event.eid)
            ),
            InlineKeyboardButton(
                text="\U0001F469\U0001F3FB",
                callback_data='gowoman_' + str(event.eid)
            )#,
#            InlineKeyboardButton(
#                text="\U0001F466\U0001F3FC",
#                callback_data='goboy_' + str(event.eid)
#            ),
#            InlineKeyboardButton(
#                text="\U0001F467\U0001F3FC",
#                callback_data='gogirl_' + str(event.eid)
#            )
        ]

        if event.get('parking'):
            button2.append(InlineKeyboardButton(
                text="\U0001F697",
                callback_data='gocar_' + str(event.eid)
            ))

        buttons = [
#            InlineKeyboardButton(
#                text="\U0001F5D3 Calendari",
#                url='http://celapalma.org/calendari_celp/add.html#' + create_event_payload(event)
#            )
        ]

        if event.get('route'):
            if event['route'].find('id=') >= 0:
                address0 = event['route'].split('id=')
                if address0[1].isdigit():
                    address1 = "https://ca.wikiloc.com/wikiloc/spatialArtifacts.do?event=view&id=" + address0[1] + "&measures=on&title=off&near=off&images=off&maptype=S"
                else:
                    address1 = event.get('route')
            else:
                address1 = event.get('route')

            buttons.append(InlineKeyboardButton(
                 text="🏞 Ruta",
                 url=address1
	     ))

        if event.get('parking') and event['parking'].find('|') >= 0:
            buttons.append(InlineKeyboardButton(
                 text="🗺 Com arribar",
                 callback_data='parking_' + str(event.eid)
            ))
        elif event.get('place') and event['place'].find('|') >= 0:
            buttons.append(InlineKeyboardButton(
                 text="🗺 Com arribar",
                 callback_data='place_' + str(event.eid)
            ))

        if today3 >= eventdate2:
             return [buttons, []]
        else:
             return [button, button2, buttons, []]
Esempio n. 16
0
def parsedate(s):
    p = pdt.Calendar()
    if s == '--':
        return None
    return datetime.date(*p.parse(s)[0][0:3])
Esempio n. 17
0
    def callback_handler(self, bot, update):
      query = update.callback_query
      data = query.data
      user = query.from_user.__dict__

      (command, event_id) = tuple(data.split('_'))

      event = self.store.get_event(event_id)

      eventdate2= int(event['date']) + 600

      today= datetime.datetime.now()
      day = str(today.day)
      month = str(today.month)
      year = str(today.year)
      hour = str(today.hour)
      minute = str(today.minute)
      today2= month + '/' + day + '/' + year + ' ' + hour + ':' + minute

      cal = parsedatetime.Calendar()
      time_struct, parse_status = cal.parse(today2)
      timestamp = time.mktime(datetime.datetime(*time_struct[:6]).timetuple())
      today3= int(timestamp)

      if data.startswith( 'enviagrup' ):
        callback_query_id=query.id
        bot.answerCallbackQuery(callback_query_id=query.id, text="S'ha enviat l'excursió al grup.")
        bot.sendMessage(
             chat_id = chats['group'],
             text = create_event_message(event, user),
             reply_markup = InlineKeyboardMarkup(inline_keyboard = create_keyboard(event, user)),
             parse_mode = ParseMode.MARKDOWN,
	     disable_web_page_preview = True
         )

      else:

        if not event.get('users'):
            event['users'] = []

        if any(u['id'] == user['id'] for u in event['users']):
              if any(u['id'] == user['id'] and u['man'] == 0 for u in event['users']):
                    user.update({'man': 0})
              elif any(u['id'] == user['id'] and u['man'] == 1 for u in event['users']):
                    user.update({'man': 1})
              elif any(u['id'] == user['id'] and u['man'] == 2 for u in event['users']):
                    user.update({'man': 2})
              elif any(u['id'] == user['id'] and u['man'] == 3 for u in event['users']):
                    user.update({'man': 3})
              elif any(u['id'] == user['id'] and u['man'] == 4 for u in event['users']):
                    user.update({'man': 4})
              elif any(u['id'] == user['id'] and u['man'] == 5 for u in event['users']):
                    user.update({'man': 5})

              if any(u['id'] == user['id'] and u['woman'] == 0 for u in event['users']):
                    user.update({'woman': 0})
              elif any(u['id'] == user['id'] and u['woman'] == 1 for u in event['users']):
                    user.update({'woman': 1})
              elif any(u['id'] == user['id'] and u['woman'] == 2 for u in event['users']):
                    user.update({'woman': 2})
              elif any(u['id'] == user['id'] and u['woman'] == 3 for u in event['users']):
                    user.update({'woman': 3})
              elif any(u['id'] == user['id'] and u['woman'] == 4 for u in event['users']):
                    user.update({'woman': 4})
              elif any(u['id'] == user['id'] and u['woman'] == 5 for u in event['users']):
                    user.update({'woman': 5})

              if any(u['id'] == user['id'] and u['boy'] == 0 for u in event['users']):
                    user.update({'boy': 0})
              elif any(u['id'] == user['id'] and u['boy'] == 1 for u in event['users']):
                    user.update({'boy': 1})
              elif any(u['id'] == user['id'] and u['boy'] == 2 for u in event['users']):
                    user.update({'boy': 2})
              elif any(u['id'] == user['id'] and u['boy'] == 3 for u in event['users']):
                    user.update({'boy': 3})
              elif any(u['id'] == user['id'] and u['boy'] == 4 for u in event['users']):
                    user.update({'boy': 4})
              elif any(u['id'] == user['id'] and u['boy'] == 5 for u in event['users']):
                    user.update({'boy': 5})

              if any(u['id'] == user['id'] and u['girl'] == 0 for u in event['users']):
                    user.update({'girl': 0})
              elif any(u['id'] == user['id'] and u['girl'] == 1 for u in event['users']):
                    user.update({'girl': 1})
              elif any(u['id'] == user['id'] and u['girl'] == 2 for u in event['users']):
                    user.update({'girl': 2})
              elif any(u['id'] == user['id'] and u['girl'] == 3 for u in event['users']):
                    user.update({'girl': 3})
              elif any(u['id'] == user['id'] and u['girl'] == 4 for u in event['users']):
                    user.update({'girl': 4})
              elif any(u['id'] == user['id'] and u['girl'] == 5 for u in event['users']):
                    user.update({'girl': 5})

              if any(u['id'] == user['id'] and u['car'] == 0 for u in event['users']):
                    user.update({'car': 0})
              elif any(u['id'] == user['id'] and u['car'] == 1 for u in event['users']):
                    user.update({'car': 1})
              elif any(u['id'] == user['id'] and u['car'] == 2 for u in event['users']):
                    user.update({'car': 2})
              elif any(u['id'] == user['id'] and u['car'] == 3 for u in event['users']):
                    user.update({'car': 3})

        if command == 'go' and eventdate2 > today3:
            event = self.toggle_user(event, user)
            self.update_message(bot, event, update, user)
            
        elif command == 'goman' and eventdate2 > today3:
            event = self.toggle_man(event, user)
            self.update_message(bot, event, update, user)

        elif command == 'gowoman' and eventdate2 > today3:
            event = self.toggle_woman(event, user)
            self.update_message(bot, event, update, user)

        elif command == 'goboy' and eventdate2 > today3:
            event = self.toggle_boy(event, user)
            self.update_message(bot, event, update, user)

        elif command == 'gogirl' and eventdate2 > today3:
            event = self.toggle_girl(event, user)
            self.update_message(bot, event, update, user)

        elif command == 'gocar' and eventdate2 > today3:
            event = self.toggle_car(event, user)
            self.update_message(bot, event, update, user)

        elif today3 >= eventdate2 and command != 'parking' and command != 'place' and command != 'elimina':
            event = self.past_event(event, user)
            self.update_message(bot, event, update, user)


        if data.startswith( 'goman' ):
            if eventdate2 > today3:
                if event is not True and any(u['id'] == user['id'] for u in event['users']):
                     callback_query_id=query.id
                     bot.answerCallbackQuery(callback_query_id=query.id, text="Has canviat el nombre d'homes que hi aniran.")
            else:
                callback_query_id=query.id
                bot.answerCallbackQuery(callback_query_id=query.id, text="\u231B\uFE0F Ha vençut la data i s'ha arxivat l'excursió.")
        elif data.startswith( 'gowoman' ):
            if eventdate2 > today3:
                if event is not True and any(u['id'] == user['id'] for u in event['users']):
                    callback_query_id=query.id
                    bot.answerCallbackQuery(callback_query_id=query.id, text="Has canviat el nombre de dones que hi aniran.")
            else:
                callback_query_id=query.id
                bot.answerCallbackQuery(callback_query_id=query.id, text="\u231B\uFE0F Ha vençut la data i s'ha arxivat l'excursió.")
        elif data.startswith( 'goboy' ):
            if eventdate2 > today3:
                if event is not True and any(u['id'] == user['id'] for u in event['users']):
                    callback_query_id=query.id
                    bot.answerCallbackQuery(callback_query_id=query.id, text="Has canviat el nombre de xiquets que hi aniran.")
            else:
                callback_query_id=query.id
                bot.answerCallbackQuery(callback_query_id=query.id, text="\u231B\uFE0F Ha vençut la data i s'ha arxivat l'excursió.")
        elif data.startswith( 'gogirl' ):
            if eventdate2 > today3:
                if event is not True and any(u['id'] == user['id'] for u in event['users']):
                    callback_query_id=query.id
                    bot.answerCallbackQuery(callback_query_id=query.id, text="Has canviat el nombre de xiquetes que hi aniran.")
            else:
                callback_query_id=query.id
                bot.answerCallbackQuery(callback_query_id=query.id, text="\u231B\uFE0F Ha vençut la data i s'ha arxivat l'excursió.")
        elif data.startswith( 'gocar' ):
            if eventdate2 > today3:
                if event is not True and any(u['id'] == user['id'] for u in event['users']):
                    callback_query_id=query.id
                    bot.answerCallbackQuery(callback_query_id=query.id, text="Has canviat el nombre de cotxes per a l'excursió.")
            else:
                callback_query_id=query.id
                bot.answerCallbackQuery(callback_query_id=query.id, text="\u231B\uFE0F Ha vençut la data i s'ha arxivat l'excursió.")
        elif data.startswith( 'go' ):
            if eventdate2 > today3:
                callback_query_id=query.id
                bot.answerCallbackQuery(callback_query_id=query.id, text="Has canviat la teua assistència a l'excursió.")
        elif data.startswith( 'parking' ):
            if eventdate2 > today3:
                callback_query_id = query.id
                (latit, longi) = tuple(event['parking'].split('|'))
                bot.answerCallbackQuery(callback_query_id=query.id, text="S'ha enviat la ubicació de l\'aparcament.")
                bot.sendMessage(chat_id=query.message.chat.id,
                                text = "Si voleu saber com arribar a l'aparcament, obriu amb la vostra aplicació de Mapes preferida la ubicació que vos envie i configureu la ruta.",
                                parse_mode = "Markdown",
                                disable_notification = True
                )
                bot.sendLocation(chat_id=query.message.chat.id,
                                 latitude = float(latit),
                                 longitude = float(longi),
                                 reply_to_message_id = query.message.message_id,
                                 disable_notification = True
                )
            else:
                callback_query_id=query.id
                bot.answerCallbackQuery(callback_query_id=query.id, text="\u231B\uFE0F Ha vençut la data i s'ha arxivat l'excursió.")
        elif data.startswith( 'place' ):
            if eventdate2 > today3:
                callback_query_id = query.id
                (latit, longi) = tuple(event['place'].split('|'))
                bot.answerCallbackQuery(callback_query_id=query.id, text="S'ha enviat la ubicació del punt de trobada.")
                bot.sendMessage(chat_id=query.message.chat.id,
                                text = "Si voleu saber com arribar al punt de trobada, obriu amb la vostra aplicació de Mapes preferida la ubicació que vos envie i configureu la ruta.",
                                parse_mode = "Markdown",
                                disable_notification = True
                )
                bot.sendLocation(chat_id=query.message.chat.id,
                                 latitude = float(latit),
                                 longitude = float(longi),
                                 reply_to_message_id = query.message.message_id,
                                 disable_notification = True
                )
            else:
                callback_query_id=query.id
                bot.answerCallbackQuery(callback_query_id=query.id, text="\u231B\uFE0F Ha vençut la data i s'ha arxivat l'excursió.")
        elif data.startswith( 'elimina' ):
            callback_query_id = query.id
            if event_id == "1":
                bot.answerCallbackQuery(callback_query_id = query.id, text = "")
                bot.editMessageText(text = "S'ha cancel·lat el procés d'eliminació.",
                            chat_id = query.message.chat.id,
                            message_id = query.message.message_id
                )
            elif event_id == "01":
                bot.answerCallbackQuery(callback_query_id = query.id, text = "")
                bot.editMessageText(text = "*Atenció!* Aquesta opció *no es pot desfer*.\n\nSegur que voleu eliminar tots els esdeveniments?",
                            chat_id = query.message.chat.id,
                            message_id = query.message.message_id,
                            parse_mode=ParseMode.MARKDOWN,
                            reply_markup = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="Sí, elimina'ls", callback_data='elimina_001'), InlineKeyboardButton(text="No, cancel·la-ho!", callback_data='elimina_1')]])
                )
            elif event_id == "001":
                bot.answerCallbackQuery(callback_query_id = query.id, text = "")
                self.store.events_db.purge()
                self.store.insert_event(event)
                bot.editMessageText(text = "S'han eliminat *tots* els esdeveniments.",
                            chat_id = query.message.chat.id,
                            message_id = query.message.message_id,
                            parse_mode=ParseMode.MARKDOWN,
                )
            else:
                textmissatge = "S'ha eliminat l'excursió número " + str(int(event_id) - 1) + ". *" + event['name'] + "* 👍."

                bot.editMessageText(text = textmissatge,
                            chat_id = query.message.chat.id,
                            message_id = query.message.message_id,
                            parse_mode="Markdown",
                )
                bot.answerCallbackQuery(callback_query_id = query.id, text = "Esdeveniment eliminat.")

                self.store.remove_event(event)
Esempio n. 18
0
def action_note(args):
    # Get action title (from arguments, or ask users if no argument supplied)
    args.action_title = args.action_title or    \
                        raw_input('Enter action title: ').strip()
    # Extract title-args that override command-line args
    extract_args_from_title(args)
    # Deduce when-context from title or argument (if supplied), or ask user
    if args.action_title[0] in '123456':
        when_prefix = args.action_title[0]
        # remove the prefix from the title
        args.action_title = ' '.join(args.action_title.split()[1:])
    else:
        when_prefix = args.when or raw_input(
            'Enter action when context (single digit): ').strip()
    if args.when and when_prefix <> args.when:
        # inconsistency! Go with the title..
        print 'Detected when-context inconsistency. Choosing', when_prefix
    if not when_prefix in '123456':
        raise RuntimeError('I don\'t like you (not in range 1..6)')
    # Get action context (from arguments, or ask user if not supplied).
    context = deduce_context(args.context)
    # Process reminder, if specified
    if args.reminder:
        import parsedatetime.parsedatetime as pdt
        cal = pdt.Calendar(pdt.Constants('he_IL', True))
        res_date, res_flag = cal.parse(args.reminder)
        if 1 == res_flag:
            # parsed as date - so use 9am as default time
            res_date = res_date[:3] + g_DefaultReminderTime + res_date[6:]
        if 0 == res_flag:
            # Not parsed at all
            print 'Failed parsing reminder date/time'
            args.action_title = 'FIX REMINDER %s' % (args.action_title)
            args.reminder = None
        else:
            # Convert reminder date/time object to UTC datetime string
            args.reminder = strftime('%Y%m%dT%H%M00Z',
                                     gmtime(mktime(res_date)))

    # Prepare template dictionary
    tmpl_params = {
        'WhenPrefix': when_prefix,
        'ActionTitle': args.action_title,
        'WhenContext': '%s-%s' % (when_prefix, when_mapping[int(when_prefix)]),
        'ActionContext': context,
        'Reminder': args.reminder and '<note-attributes>'  \
                '<reminder-order>%s</reminder-order>'  \
                '<reminder-time>%s</reminder-time>' \
                '<reminder-done-time>00001231T000000Z</reminder-done-time>' \
                '</note-attributes>' %  \
                (strftime('%Y%m%dT%H%M%SZ', gmtime()), args.reminder) or ''
        }

    # Apply template
    import_file_path = apply_template(args.template, tmpl_params)

    notebook = None
    if args.notebook:
        # Get list of notebook by running ENScript listNotebooks
        # it writes the notebooks the stdout, one per line
        p = Popen(['ENScript.exe', 'listNotebooks'], stdout=PIPE)
        notebooks, _ = p.communicate()
        notebooks = [nb.strip() for nb in notebooks.split('\n')]

        def get_notebook(query):
            # Try a best-effort exact match
            query_matcher = re.compile('(.*)%s(.*)' % (re.escape(query)),
                                       re.IGNORECASE)
            min_miss_len = max(map(len, notebooks))
            notebook = None
            for nb in notebooks:
                qm = query_matcher.match(nb)
                if qm:
                    miss_len = len(qm.group(1)) + len(qm.group(2))
                    if 0 == miss_len:
                        # Perfect match! Return immediately!
                        return nb
                    if miss_len < min_miss_len:
                        min_miss_len = miss_len
                        notebook = nb
            # If had any luck, return now
            if notebook:
                return notebook
            # Otherwise, try maximal word-overlap matching
            def to_words(str):
                return set(str.lower().replace('-', ' ').split())

            in_words = to_words(query)
            max_intersect = 0
            for nb in notebooks:
                nb_words = to_words(nb)
                intersection = len(nb_words.intersection(in_words))
                if intersection > max_intersect:
                    max_intersect = intersection
                    notebook = nb
            return notebook

        notebook = get_notebook(args.notebook)

    timestr = strftime('%Y%m%dT%H%M00')
    # Import the note to Evernote
    # (into specific notebook if supplied, or default one otherwise)
    call_args = ['importNotes', '/s', import_file_path]
    if notebook:
        call_args.append('/n')
        call_args.append(notebook)
    call_enscript(call_args)

    # Open the note in a separate window after importing (if flagged to do so)
    if args.open_note:
        open_first_note('created:%s tag:.Action' % (timestr))
Esempio n. 19
0
from yakr.plugin_base import *
from threading import Timer
import pickle
import datetime
import parsedatetime.parsedatetime as pdt

_DT_PARSER = pdt.Calendar()

ALARM_STORE = "AlarmStore.pkl"
_ALARM_CACHE = []
_NEXT_ALARM = None


def load_alarms():
    global _ALARM_CACHE
    try:
        _ALARM_CACHE = pickle.load(file(ALARM_STORE))
    except:
        _ALARM_CACHE = []


def save_alarms():
    pickle.dump(_ALARM_CACHE, file(ALARM_STORE, "w"))


def parse_time(time_string):
    return datetime.datetime(*_DT_PARSER.parse(time_string)[0][:6])


def add_alarm(what, where, when):
    _ALARM_CACHE.append((when, where, what))
Esempio n. 20
0
    def adapt_csv(self, valueDict):
        import parsedatetime.parsedatetime as pdt
        c = pdt.Constants()
        p = pdt.Calendar(c)

        self.app_date_string = valueDict["Postmark Date"].strip()
        appDate = p.parse(valueDict["Postmark Date"])
        if (appDate[1] == 1):
            self.app_date = date(*appDate[0][0:3]).isoformat()
        else:
            self.app_date = date.today().isoformat()[0:10]

        self.name = {
            'last': valueDict["Last"].strip().title(),
            'first': valueDict["First"].strip().title(),
            'middle': valueDict["Middle"].strip().title(),
            'nickname': valueDict["Nick"].strip().title()
        }

        self.address['street'] = valueDict["Address"].strip().title()
        self.address['city'] = valueDict["City"].strip().title()
        self.address['county'] = "Unknown"
        self.address['state'] = valueDict["ST"].strip().upper()
        self.address['zip'] = valueDict["Zip Code"].strip()
        self.address['phone_day'] = valueDict["Phone Number"].strip()
        self.address['phone_mbl'] = valueDict["Secondary"].strip()
        self.address['email'] = valueDict["Email"].strip()

        self.birth_date_string = valueDict["DOB"].strip()
        appDOB = p.parse(valueDict["DOB"])
        if (appDOB[1] == 1):
            bd = date(*appDOB[0][0:3])
            if (bd is None):
                bd = date.today()
            if (bd > date.today()):
                bd = datetime(bd.year - 100, *bd.timetuple()[1:-2])
            self.birth_date = bd.isoformat()[0:10]

        self.gender = valueDict["Male/Female"].strip().upper()[:1]
        self.shirt = {
            'size':
            valueDict["Tshirt Size"].strip().upper().replace(
                "XXXXL", "4XL").replace("XXXL", "3XL").replace("XXL", "2XL")
        }
        self.guardian = {
            'pref_notes': valueDict["Assigned Guardian"].strip(),
            'id': '',
            'name': '',
            'history': []
        }
        self.vet_type = valueDict["Conflict"].split(
            ' ',
            1)[0].strip().title().replace("Korean",
                                          "Korea").replace("Wwii", "WWII")
        self.service['branch'] = valueDict["Branch"].strip()
        self.call = {
            'mail_sent': len(valueDict["Letter"].strip()) > 0,
            'history': []
        }
        self.flight = {
            'status': 'Active',
            'id': 'None',
            'seat': '',
            'group': '',
            'bus': 'None',
            'waiver': valueDict["Waiver"].strip().title() == "Yes",
            'history': []
        }
        self.medical = {
            'release': valueDict["Health"].strip().title() == "Yes"
        }
Esempio n. 21
0
    'a',
    'abbr',
    'acronym',
    'b',
    'blockquote',
    'code',
    'em',
    'i',
    'li',
    'ol',
    'strong',
    'ul',
    'p'
]

CAL = parsedatetime.Calendar()


def parse_calendarjs(response):
    def parse_text(text) -> (str, str, str):
        event_time = None
        soup = BeautifulSoup(text, 'html.parser')
        for token in soup.stripped_strings:
            result, flag = CAL.parse(token)
            if flag == 2:
                event_time = datetime.fromtimestamp(mktime(result)).time()
                break
        return event_time, ' '.join(soup.stripped_strings)

    def parse_date(text) -> date:
        return datetime.strptime(text, '%m/%d/%Y').date()  # 2/8/2017
Esempio n. 22
0
 def setUp(self):
     self.cal = pt.Calendar()
     self.yr, self.mth, self.dy, self.hr, self.mn, self.sec, self.wd, self.yd, self.isdst = time.localtime(
     )
Esempio n. 23
0
def parse_date(src_string):
    cal = parsedatetime.Calendar()
    time_struct, status = cal.parse(src_string)
    return datetime(*time_struct[:6])
Esempio n. 24
0
def edit(request, post_id, post=None):
    if not post:
        post = get_object_or_404(SMPost, pk=post_id)

    if (post.sent and not post.sent_error) or not can_edit_post(request.user, post) or post.sending:
        message = {
            "mtype": "status",
        }

        if post.sent:
            message['mtext'] = "This post has already been sent and cannot be edited"

        elif not can_edit_post(request.user, post):
            message['mtext'] = "You do not have permission to edit this post"

        elif post.sending:
            message['mtext'] = "This post is currently sending and cannot be edited"

        site_message = MeowSetting.objects.get(
            setting_key='site_message').setting_value
        context = {
            "user": request.user,
            "sections": Section.objects.all(),
            "post": post,
            "message": message,
            "site_settings": get_settings(),
        }
        return render(request, 'scheduler/view.html', context)

    message = {}
    if request.method == "POST" and can_edit_post(request.user, post):
        post.story_url = request.POST.get('url', None).strip(" \t\n\r")
        if len(post.story_url) > 4 and post.story_url[0:4] != "http":
            try:
                index_of_protocol = post.story_url.index("://")
                if index_of_protocol <= 5:
                    post.story_url = "http" + \
                        post.story_url[post.story_url.index("://"):]
            except:
                post.story_url = "http://" + post.story_url
        post.slug = request.POST.get('slug', None)
        try:
            post.section = Section.objects.get(
                pk=request.POST.get('section', None))
        except:
            post.section = None
        post.post_twitter = request.POST.get('tweet', None)
        post.post_facebook = request.POST.get('fb', None)
        post.post_instagram = request.POST.get('ig', None)
        post.post_notes = request.POST.get('notes', None)
        # date_str = request.POST.get('pub_date', None)
        # time_str = request.POST.get('pub_time', None)
        date_time_str = request.POST.get('pub_date_time', None)

        # Date
        cal = pdt.Calendar()
        date_parsed = cal.parse(date_time_str)
        time_parsed = cal.parse(date_time_str)
        if date_parsed[1] == 1 or date_parsed[1] == 3:
            post.pub_date = datetime.date(
                date_parsed[0][0], date_parsed[0][1], date_parsed[0][2])
            post.pub_time = datetime.time(time_parsed[0][3], time_parsed[0][4])
        else:
            post.pub_date = None
            post.pub_time = None

        # Time
        # time_parsed = cal.parse(time_str)
        # if time_parsed[1] == 2 or time_parsed[1] == 3:
        #     post.pub_time = datetime.time(time_parsed[0][3], time_parsed[0][4])
        # else:
        #     post.pub_time = None

        # Checkboxes
        if request.user.has_perm('scheduler.approve_copy'):
            if request.POST.get('approve-copy', False) == 'on':
                if post.pub_ready_copy == False:
                    post.pub_ready_copy_user = request.user
                post.pub_ready_copy = True
            else:
                post.pub_ready_copy = False
                post.pub_ready_copy_user = None

        if request.user.has_perm('scheduler.approve_online'):
            if request.POST.get('approve-online', False) == 'on':
                if post.pub_ready_online == False:
                    post.pub_ready_online_user = request.user
                post.pub_ready_online = True
            else:
                post.pub_ready_online = False
                post.sent_error = False
                post.sent = False
                post.pub_ready_online_user = None

        post.last_edit_user = request.user

        post.save()
        message = {
            "mtype": "success",
            "mtext": "Your changes were saved!",
        }
    if request.method == "GET" and request.user.has_perm('scheduler.add_edit_post'):
        if request.GET.get('add', None) == "true":
            message = {
                "mtype": "success",
                "mtext": "Your post was successfully created!",
            }

    site_message = MeowSetting.objects.get(
        setting_key='site_message').setting_value
    context = {
        "user": request.user,
        "sections": Section.objects.all(),
        "post": post,
        "today": timezone.localdate(),
        "message": message,
        "twitter_limit": MeowSetting.objects.get(setting_key='twitter_character_limit').setting_value,
        "site_settings": get_settings(),
    }
    return render(request, 'scheduler/edit.html', context)
Esempio n. 25
0
    def setUp(self):
        self.ptc = ptc.Constants('en_AU', usePyICU=False)
        self.cal = pt.Calendar(self.ptc)

        self.yr, self.mth, self.dy, self.hr, self.mn, self.sec, self.wd, self.yd, self.isdst = time.localtime()
Esempio n. 26
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with cuZmeură. If not, see <http://www.gnu.org/licenses/>.

import re
import time

from bs4 import BeautifulSoup
from parsedatetime import parsedatetime as pdt

from newhackers import config


cal = pdt.Calendar()


def parse_comments(page):
    """Parse comments from an HN comments page

    :page: an HTML document with comments

    Returns a dict of metadata about the story and a list of comments. E.g.

    {'title': "I sooo don't like Apple anymore",
     'link': "http://iwoz.woo",
     'comments_no': 1337,
     'score': 42,
     'time': 1350901062.0,
     'author': 'woz',
Esempio n. 27
0
class html_compiler(pyjade.ext.html.HTMLCompiler):
    def visitCode(self, code):
        if not code.buffer and not code.block:
            exec code.val.lstrip() in self.global_context, self.local_context
        pyjade.ext.html.HTMLCompiler.visitCode(self, code)


def jade2html(tmpl, globals, locals):
    compiler = html_compiler(pyjade.Parser(tmpl).parse())
    env = dict(globals)
    env.update(locals)
    with pyjade.ext.html.local_context_manager(compiler, env):
        return compiler.compile()


date_parser = pdt.Calendar(pdc.Constants())
now = dt.datetime.now()


def month_of(date):
    return date + rd.relativedelta(day=1)


def fmt_time(time):
    return time.strftime('%a %Y-%m-%d %I:%M %p')


def fmt_date(date, short=False):
    return date.strftime('%m/%d/%Y') if not short else \
        '%s/%s/%s' % (date.month, date.day, date.year)