Ejemplo n.º 1
0
def sync_events(db, max_results = 12, events_log_file = "events.log"):
    delete_past_events(db, commit=False)
    now = datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    for room in db().select(db.rooms.ALL):
        try:
            print('Getting the upcoming {} events for room {}: {}'.format(max_results, room['id'], room['name']))
            events_result = get_calendar().events().list(
                    calendarId=room['calendar_id'], timeMin=now, maxResults=max_results, singleEvents=True, orderBy='startTime').execute()
            events = events_result.get('items', [])
            old_events = db(db.events.room_id == room['id']).select(db.events.ALL).as_dict('event_id')
            new_events = []
            for event in events:
                start_time = datetime.strptime(event['start'].get('dateTime', event['start'].get('date'))[:-6], '%Y-%m-%dT%H:%M:%S')
                end_time = datetime.strptime(event['end'].get('dateTime', event['end'].get('date'))[:-6], '%Y-%m-%dT%H:%M:%S')
                new_events.append(event['id'])
                db.events.update_or_insert(db.events.event_id == event['id'], event_id=event['id'],
                                           calendar_id=room['calendar_id'], room_id=room['id'],
                                           start_time=start_time, end_time=end_time, dict=event,)
            for event_id in old_events:
                if not event_id in new_events: db(db.events.event_id == event_id).delete()
        except:
            message = "Failed to get events for room {}: {} - calendar_id: {}".format(room['id'], room['name'], room['calendar_id'])
            print(message)
            with open(events_log_file, "a") as events_log:
                events_log.write("{} {}\n".format(str(datetime.now()).split('.')[0], message))
    db.commit()
Ejemplo n.º 2
0
def redrawAll(canvas, data):
    #table
    canvas.create_rectangle(5,5,data.width-5,data.height-5,fill = 'orange4')
    canvas.create_rectangle(10,10,data.width-10,data.height-10,fill = 'green4')
    #gametext
    canvas.create_text(20,30,text = 'Players: %s' % ', '.join(data.botTuple),
        anchor = 'sw', font = 'msserif 12')
    drawAllActive(canvas, data)
    #readout
    if data.gameOver:
        canvas.create_text(data.width/2, 40, text = 'Game Over', 
            fill = 'white', font = 'msserif 12 bold')
    n = data.readoutCount!=None 
    if n and data.readoutCount>len(data.allHistories)-1 and not data.gameOver:
        canvas.create_text(data.width/2, 40, text = 'Game Over',
         fill = 'white', font = 'msserif 12 bold')
        data.gameOver = True
    if not n or data.readoutCount>len(data.allHistories)-1: pass
    else:
        currEvent = data.allHistories[data.readoutCount]
        db('currEvent',currEvent)
        readOut = parseEvent(data,currEvent)
        db('readout',readOut)
        if readOut!=None:
            readoutParse(readOut,data,canvas,currEvent)
Ejemplo n.º 3
0
def grade2():
    lastxs=db().select(db.zuoye.zuozhe).last().zuozhe
    banji=db.auth_user[lastxs].banji
    if len(request.args):
        banji=request.args[0]
    rows=db((db.keshi.xuenian==xuenian)&(db.keshi.xueqi==xueqi)&(db.keshi.nianji==2)).select(left=db.keshi.on(db.keshi.kecheng==db.course.id))
    return dict(rows=rows,banji=banji)
Ejemplo n.º 4
0
def update():
    (db, table) = get_table(request)
    keyed = hasattr(db[table], '_primarykey')
    record = None
    db[table]._common_filter = None
    if keyed:
        key = [f for f in request.vars if f in db[table]._primarykey]
        if key:
            record = db(
                db[table][key[0]] == request.vars[key[0]]).select().first()
    else:
        record = db(db[table].id == request.args(2)).select().first()

    if not record:
        qry = query_by_table_type(table, db)
        session.flash = T('record does not exist')
        redirect(URL('select', args=request.args[:1], vars=dict(query=qry)))

    if keyed:
        for k in db[table]._primarykey:
            db[table][k].writable = False

    form = SQLFORM(db[table],
                   record,
                   deletable=True,
                   delete_label=T('Check to delete'),
                   ignore_rw=ignore_rw and not keyed,
                   linkto=URL('select', args=request.args[:1]),
                   upload=URL(r=request, f='download', args=request.args[:1]))

    if form.accepts(request.vars, session):
        session.flash = T('done!')
        qry = query_by_table_type(table, db)
        redirect(URL('select', args=request.args[:1], vars=dict(query=qry)))
    return dict(form=form, table=db[table])
Ejemplo n.º 5
0
def create_profile(op, msg, usrid):
    req = proto_profile.CreateProfile()
    try:
        req.ParseFromString(msg)
    except:
        raise IlleagalMsgExcept(op, '')

    query = db().query(Profile)
    pf = query.get(usrid)
    if pf:
        err = proto_common.RequestError()
        err.errop = op
        err.errno = ACCOUNT_EXIST
        return opcode_response.REQUEST_ERROR, err.SerializeToString()
    
    pf = Profile(usrid, req.nickname, 1, 0, 0, 0)
    db().add(pf)
    db().commit()
    #db().flush()

    log_root().info('create profile %d:%s' % (usrid, req.nickname))

    ret = proto_profile.CreateProfileResponse()
    return opcode_response.CREATE_PROFILE_RESPONSE, \
      ret.SerializeToString()
Ejemplo n.º 6
0
def connect_conf():
    if session.man_id:
        man = db.men[ session.man_id ]
        if man:
            db(db.man_keys.man_id == man.id).delete()
            redirect(URL('cabinet', 'index'))

    key = request.args(0)
    if not key:
        return dict(h = T('Пустой Ключ'))
    
    if key != session.mail_connect_key:
        rec = db(db.man_keys.temp_key == key).select().first()
        if rec:
            del db.man_keys[ rec.id ]
        return dict(h = T('неверная сессия'))
        
    rec = db(db.man_keys.temp_key == key).select().first()
    if not rec:
        return dict(h = T('Такой Ключ не найден'))
    
    man = db.men[ rec.man_id ]
    del db.man_keys[ rec.id ]
    if not man:
        return dict(h = T('Человек не найден'))
    
    set_session(session, man)
    redirect(URL('cabinet','index'))
Ejemplo n.º 7
0
def get_by_tag():
    """
    return list of images for the selected tag value 
    this is an ajax response - caller will expect json format
    """
    if not request.vars.search: return []
    tname = request.vars.search    
    if len(tname) < 2 : return []
    
    try:
        tg = db(db.xtg.name==tname).select().first()
    except:
        return ['No Matches Found']
    
    if not tg:   return ['No matches found']
    #tg_eu = db(db.xtg.name=='EU').select().first()
    rows = (db(db.xref.xtg==tg.id).select())
    #rows = (db(db.xref.xtg==tg.id).select()).as_list()
    imglist = []
    for r in rows:
        #imglist.append(r.xim.title)
        # build array here for proprt table rendering by 'TABLE'
        imglist.append([r.xim.title])

    #xmlstr =""
    #tbl = TABLE(TR(*rows) for rows in imglist).xml()
    tbl = TABLE(*[TR(*rows) for rows in imglist])
    return tbl
Ejemplo n.º 8
0
def GetTxMessageName():
    for i in db().TxMessageIndex:
        temp = list(db().TxMessageSignal[i])
        del temp[-1]
        temp = ''.join(temp)
        db().TxMessageSignal[i] = ''.join(temp)
        db().TxMessage.append(temp)
Ejemplo n.º 9
0
def previous():
    id = session['id']
    cmd = "SELECT customer_firstname from customer where customer_ID = %s;" % id
    rows = db(cmd)
    name = rows[0][0]
    cmd = "SELECT * from reservation where customer_ID = '%s';" % id
    rows = db(cmd)
    return render_template('bookings.html', rows=rows, name=name)
Ejemplo n.º 10
0
def get_outlets(db, room_id=None):
    if room_id: outlets = db(db.outlets.room_id == room_id).select(db.outlets.ALL)
    else: outlets = db().select(db.outlets.ALL)
    for outlet in outlets:
        outlet['name'] = outlet['name'].strip()
        outlet['mac'] = outlet['mac'].strip().lower() #EUI(outlet['mac'])
        outlet['ip'] = outlet['ip'].strip().lower()
    return outlets
Ejemplo n.º 11
0
    def put(self, record):
        """
        stores a record

            >>> db = setup_test()
            >>> class Person(Record): pass
            >>> class People(RecordStore): pass
            >>> people = People(db, Person)
            >>> sally = Person(name='Sally', age=25)
            >>> sally
            <Person {'name': 'Sally', 'age': 25}>
            >>> id = people.put(Person(name='Sally', age=25))
            >>> id
            1L
            >>> sally
            <Person {'name': 'Sally', 'age': 25}>
            >>> sally = people.get(id)
            >>> sally
            <Person {'name': 'Sally', 'age': 25}>
            >>> sally.age = 35
            >>> people.put(sally)
            1L
            >>> person = people.get(id)
            >>> person
            <Person {'name': 'Sally', 'age': 35}>
            >>> id = people.put({'name':'James', 'age':15})
            >>> id
            2L
            >>> people.get(id)
            <Person {'name': 'James', 'age': 15}>
        """


        keys        = [k for k in record.keys() if k <> '_id']
        values      = [record[k] for k in keys]
        datatypes   = [repr(type(i)).strip("<type >").strip("'") for i in values]
        values      = [i for i in values]
        valid_types = ['str','unicode','long','int','float','datetime.date','datetime.datetime','bool','NoneType']

        db = self.db

        for atype in datatypes:
            if atype not in valid_types:
                raise TypeException,'unsupported type <type %s>' % atype

        if '_id' in record:
            id = record['_id']
            sc = ', '.join('%s=%s' % (i,'%s') for i in keys)
            cmd = 'update %s set %s where id=%d' % (self.kind, sc, id)
            db(cmd, *values) 
        else:
            kc = ', '.join(keys)
            placeholders = ','.join(['%s'] * len(keys))
            cmd = 'insert into %s (%s) values (%s)' % (self.kind, kc, placeholders)
            _id = db(cmd, *values)
            id = record['_id'] = _id

        return id
Ejemplo n.º 12
0
def remove_user():
    from tests.fixtures import TEST_USER
    db._adapter.reconnect()
    print("\nRemoving test user.")
    dev_user = db(User.email == TEST_USER.email).select()
    print("Admin: {}\n".format(dev_user.as_dict()))
    db(User.email == TEST_USER.email).delete()
    print("Test user successfully deleted.")
    db.commit()
Ejemplo n.º 13
0
def remove_admin():
    from tests.fixtures import TEST_ADMIN
    db._adapter.reconnect()
    print("\nRemoving test admin.")
    dev_admin = db(User.email == TEST_ADMIN.email).select()
    print("Admin: {}\n".format(dev_admin.as_dict()))
    db(User.email == TEST_ADMIN.email).delete()
    print("Test admin successfully deleted.")
    db.commit()
Ejemplo n.º 14
0
def GetRxMessageName():
    for i in db().RxMessageIndex:
        #temp = db().RxMessageSignal[i]
        #temp = list(temp)
        temp = list(db().RxMessageSignal[i])
        del temp[-1]
        db().RxMessageSignal[i] = ''.join(temp)
        temp = ''.join(temp)
        db().RxMessage.append(temp)
Ejemplo n.º 15
0
def grade1():
    lastxs = db().select(db.zuoye.zuozhe).last().zuozhe
    banji = db.auth_user[lastxs].banji
    if len(request.args):
        banji = request.args[0]
    rows = db((db.keshi.xuenian == xuenian) & (db.keshi.xueqi == xueqi)
              & (db.keshi.nianji == 1)).select(left=db.keshi.on(
                  db.keshi.kecheng == db.course.id))
    return dict(rows=rows, banji=banji)
Ejemplo n.º 16
0
def read_edges(identifier=None):

    if identifier:
        edge = db().find(Edge, Edge.identifier == identifier)
        export = edge.one().serialize()
    else:
        all_edges = db().find(Edge)
        export = map(lambda edge: edge.serialize(), all_edges)
   
    return json.dumps(export)
Ejemplo n.º 17
0
def read_nodes(identifier=None):

    if identifier:
        node = db().find(Node, Node.identifier == identifier)
        export = node.one().serialize()
    else:
        all_nodes = db().find(Node)
        export = map(lambda node: node.serialize(), all_nodes)
   
    return json.dumps(export)
Ejemplo n.º 18
0
def read_nodes(identifier=None):

    if identifier:
        node = db().find(Node, Node.identifier == identifier)
        export = node.one().serialize()
    else:
        all_nodes = db().find(Node)
        export = map(lambda node: node.serialize(), all_nodes)

    return json.dumps(export)
Ejemplo n.º 19
0
def read_edges(identifier=None):

    if identifier:
        edge = db().find(Edge, Edge.identifier == identifier)
        export = edge.one().serialize()
    else:
        all_edges = db().find(Edge)
        export = map(lambda edge: edge.serialize(), all_edges)

    return json.dumps(export)
Ejemplo n.º 20
0
def do_mybot():
    #这里添加自己的机器人处理
    q = request.forms.get('q')
    if q:
        url = "https://www.sogou.com/labs/webservice/sogou_word_seg.php"
        r = requests.post(url, {'q': q.decode('utf8'), 'fmt': 'js'})
        if not r.text:
            return {'code': 1, 'msg': u'分词器异常'}
        qfc = json.loads(r.text)
        h = {}
        if qfc['status'] == 'OK':
            for i in qfc['result']:
                r = db().get1(
                    """SELECT
	t2.cy,
	t2.cx,
	t1.qz
FROM
	wb_ck AS t3
CROSS JOIN wb_gx AS t1 ON t3.id = t1.cid
OR t1.kid = t3.id
CROSS JOIN wb_ck AS t2 ON t1.cid = t2.id
OR t2.id = t1.kid
WHERE
	t3.cy = %s
ORDER BY
	t1.qz DESC""", i[0])
                if r:
                    h[r[1]] = r[0]
            if not h:
                #return {'code':1,'msg':u'数据获取异常'}
                return u'呃,不知道你在说什么'
            g = 'rdvn'
            s = ''
            for gg in g:
                if h.has_key(gg):
                    s += h[gg]
                else:
                    if gg in 'rdvn':
                        r = db().get1(
                            """SELECT
	wb_ck.cy,
	RAND() AS r
FROM
	wb_ck
WHERE
	wb_ck.cx = %s
ORDER BY
	r
LIMIT 1""", gg)
                        s += r[0]
            return s
        else:
            return {'code': 1, 'msg': u'分词接口无有效数据'}
    return {'code': 1, 'msg': u'无输入值'}
Ejemplo n.º 21
0
def createupdate_node():
    req = request.get_json()

    try:

        identifier = req[u"id"]

        node = db().find(Node, Node.identifier == identifier).one()

        if node is None:
            node = db().add(Node())
            node.identifier = identifier

        props = db().find(NodeProperty, NodeProperty.node_id == Node.id, Node.identifier == identifier)

        for prop in props:
            db().remove(prop)

        for key, value in req[u"properties"].items():
            prop = NodeProperty()
            prop.key = unicode(key)
            prop.value = unicode(value)
            node.properties.add(prop)

        db().commit()

    except Exception, e:
        db().rollback()
        raise e
Ejemplo n.º 22
0
def createupdate_node():
    req = request.get_json()

    try:

        identifier = req[u"id"]

        node = db().find(Node, Node.identifier == identifier).one()

        if node is None:
            node = db().add(Node())
            node.identifier = identifier

        props = db().find(NodeProperty, NodeProperty.node_id == Node.id,
                          Node.identifier == identifier)

        for prop in props:
            db().remove(prop)

        for key, value in req[u"properties"].items():
            prop = NodeProperty()
            prop.key = unicode(key)
            prop.value = unicode(value)
            node.properties.add(prop)

        db().commit()

    except Exception, e:
        db().rollback()
        raise e
Ejemplo n.º 23
0
def delete_edge(identifier=None):

    edge = db().find(Edge, Edge.identifier == identifier).one()

    if not node:
        raise Exception("not found")

    db().remove(edge)
    db().commit()

    return ""
Ejemplo n.º 24
0
 def create_test_tables(db):
     db("""
     create table if not exists person (
         id int not null auto_increment,
         name      varchar(100),
         age       smallint,
         kids      smallint,
         birthdate date,
         PRIMARY KEY (id)
         )
     """)
Ejemplo n.º 25
0
def delete_edge(identifier=None):
    
    edge = db().find(Edge, Edge.identifier == identifier).one()
    
    if not node:
        raise Exception("not found")

    db().remove(edge)
    db().commit()
    
    return ""
Ejemplo n.º 26
0
def createaccount():
    firstname = request.form['userName']
    lastname = request.form['lastname']
    email = request.form['email']
    password = request.form['password']
    age = request.form['age']
    phone = request.form['phone']

    cmd = "INSERT INTO customer(customer_firstname,customer_lastname,customer_email,customer_password,customer_age,customer_phonenumber) values('%s','%s','%s','%s',%s,%s);" % (
        firstname, lastname, email, password, age, phone)
    db(cmd)
    return render_template('index.html')
Ejemplo n.º 27
0
def addwenti():
    keshi_id = request.args[0]
    keshi = db.keshi[keshi_id]
    course = keshi.kecheng
    timus = db(db.timu.course == course).select()
    for timu in timus:
        db.lianxi.update_or_insert(
            (db.lianxi.keshi == keshi_id) & (db.lianxi.timu == timu),
            keshi=keshi_id,
            timu=timu)
    lianxis = db(db.lianxi.keshi == keshi_id).select()
    return dict(timus=timus, lianxis=lianxis)
Ejemplo n.º 28
0
def query_by_img():
    """
    get all tags for an image
    """
    cnt = 0
    img = db(db.xim.title=='Paris').select().first()
    rows = (db(db.xref.xim==img.id).select())
    tlist = []
    for r in rows:
        cnt +=1
        tlist.append(r.xtg.name)
        
    return
Ejemplo n.º 29
0
def addwenti():
    keshi_id=request.args[0]
    keshi=db.keshi[keshi_id]
    course=keshi.kecheng
    timus=db(db.timu.course==course).select()
    for timu in timus:
        db.lianxi.update_or_insert(
                                   (db.lianxi.keshi==keshi_id)&
                                   (db.lianxi.timu==timu),
                                   keshi=keshi_id,
                                   timu=timu
                                   )
    lianxis=db(db.lianxi.keshi==keshi_id).select()
    return dict(timus=timus,lianxis=lianxis)
Ejemplo n.º 30
0
def uitslag():
    T.force("nl")
    jaar = str(mvhutils.huidigJaar())
    kalender = db.kalender(db.kalender.jaar==jaar)
    uitslagen = db(db.uitslag)._select(db.uitslag.wedstrijd, distinct=True)
    print "uitslagen = ", uitslagen
    wedstrijden = db((db.wedstrijd.kalender==kalender) &
                     (db.wedstrijd.id.belongs(uitslagen))).select(db.wedstrijd.id,
                                       db.wedstrijd.datum,
                                       db.wedstrijd.omschrijving,
                                       orderby=db.wedstrijd.datum
    )
    print "wedstrijden = ", wedstrijden
    return dict(wedstrijden=wedstrijden, jaar=jaar)
Ejemplo n.º 31
0
def list_by_image():
    """
    build a dict of images and related tags
    """
    imgs = db(db.xim.id>0).select()
    imgdict = {}    
    for img in imgs:
        rows = (db(db.xref.xim==img.id).select())
        tlist = []
        for r in rows:
            tlist.append(r.xtg.name)
        # key is a tuple of image title and tag count        
        dk = (img.title,len(tlist))
        imgdict[dk] = tlist    
    return imgdict
Ejemplo n.º 32
0
def historial():
    C = Storage()
    C.escuela = db.escuela(1)
    menu_migas.append(T("Control de cambios"))

    tbl_n = request.args(0)
    r_id = int(request.args(1))

    C.titulo = T("Historial de cambios TABLA: {} REGISTRO ID: {}").format(tbl_n, r_id)

    tbl = db["{}_archive".format(tbl_n)]
    query = (tbl.current_record == r_id)

    for f in tbl:
        f.readable = True
    tbl.current_record.readable = False

    C.current_record = SQLTABLE(db(db[tbl_n].id == r_id).select(),
                                headers="labels",
                                _class="table")
    C.grid = SQLFORM.grid(query, args=request.args[:2],
                          orderby=[~tbl.modified_on],
                          create=False,
                          searchable=False,
                          editable=False,
                          deletable=False,
                          details=False,
                          csv=False)

    return dict(C=C)
Ejemplo n.º 33
0
def codice_geografia(stato, provincia, comune, db):
    """Le lettere dalla dodicesima alla quindicesima, per il luogo di nascita.
    @param db: un callable che restituisce il codice (pescandolo da un db
               o altro storage). La signature del callable deve essere
               db(stato, provincia, comune).
    """
    return db(stato, provincia, comune)
Ejemplo n.º 34
0
def login():
    if request.method == 'POST':
        customer_ID = request.form['userName']
        entered_password = request.form['userPass']

    session['id'] = customer_ID

    cmd = "SELECT customer_password,customer_firstname FROM customer WHERE customer_ID = %s;" % customer_ID

    rows = db(cmd)

    #return str(rows)
    if rows:
        #return '1'
        (customer_password, customer_firstname) = rows[0]

        if entered_password == customer_password:
            #return customer_firstname
            #return redirect(url_for('/main'),id = customer_ID)
            session['logged_in'] = True
            return redirect(url_for('mainpage'))
            #, id = customer_ID, name = customer_firstname)

        else:
            return render_template('recordnotexist.html')

    else:
        return render_template('recordnotexist.html')
Ejemplo n.º 35
0
def read_nodes(identifier, degrees):

    if degrees > 5:
        raise Exception("I am sorry, this doesn't scale - at all")
    
    init_node = db().find(Node, Node.identifier == identifier).one()

    nodes = set((init_node,))
    edges = set()

    for i in range(degrees):

        for node in list(nodes):

            for inbound in node.inbound:
                edges.add(inbound)
                nodes.add(inbound.source)

            for outbound in node.outbound:
                edges.add(outbound)
                nodes.add(outbound.target)

    return json.dumps({
        "edges": map(lambda edge: edge.serialize(), edges),
        "nodes": map(lambda nodes: nodes.serialize(), nodes)
        })
Ejemplo n.º 36
0
def map():
    """
    Exposes the information for the map
    """
    map_lon = request.vars.lon
    map_lat = request.vars.lat
    map_zoom = request.vars.zoom
    map_origin = request.vars.origin
    layer_data = db(db.gis_layers.status == 1).select(
        db.gis_layers.name,
        db.gis_layers.file_data,
        db.gis_layers.style_data,
        db.gis_layers.rule_data,
        db.gis_layers.popup,
        orderby=db.gis_layers.priority | db.gis_layers.id)
    if map_lon is None:
        map_lon = -75.88400
    if map_lat is None:
        map_lat = -8.0078125
    if map_zoom is None:
        map_zoom = 8
    if map_origin is None:
        map_origin = 'sphericalm'
    return dict(layer_data=layer_data,
                map_lon=map_lon,
                map_lat=map_lat,
                map_zoom=map_zoom,
                map_origin=map_origin)
Ejemplo n.º 37
0
def test_profile_page(logged_client):
    db._adapter.reconnect()
    rows = db(User.email == TEST_USER.email).select()
    test_user_id = rows[0].id
    resp = logged_client.get('/user/{}'.format(test_user_id))
    assert TEST_USER.first_name in resp.data
    assert TEST_USER.last_name in resp.data
Ejemplo n.º 38
0
def probar_base_de_datos():
    """Retorna True si la base de datos ya esta inicializada"""
    db = current.db
    if db(db.auth_user.id > 0).count() > 0:
        return True
    # en cc retornar Falso
    return False
Ejemplo n.º 39
0
def read_nodes(identifier, degrees):

    if degrees > 5:
        raise Exception("I am sorry, this doesn't scale - at all")

    init_node = db().find(Node, Node.identifier == identifier).one()

    nodes = set((init_node, ))
    edges = set()

    for i in range(degrees):

        for node in list(nodes):

            for inbound in node.inbound:
                edges.add(inbound)
                nodes.add(inbound.source)

            for outbound in node.outbound:
                edges.add(outbound)
                nodes.add(outbound.target)

    return json.dumps({
        "edges": map(lambda edge: edge.serialize(), edges),
        "nodes": map(lambda nodes: nodes.serialize(), nodes)
    })
Ejemplo n.º 40
0
def get_by_name():
    """
    return list of images by title 
    (implement search like using gae)
    this is an ajax response - caller will expect json format
    """
    if not request.vars.search: return []
    tname = request.vars.search    
    if len(tname) > 2 : return []
    
    #rows = db(buyer.id>0).select().find(lambda row:row.name.startswith('C'))
    #rows = db(db.xim.id>0).select().find(lambda row:row.title.startswith(tname))
    
    rows = db(db.xim.id>0).select().find(lambda row:row.title.startswith(tname))
    
    #rows = db(db.xim.id>0).select()

    if not rows:   return ['No matches found']
    
    imglist = []
    for r in rows:
        #imglist.append(r.xim.title)
        # build array here for proprt table rendering by 'TABLE'
        # need to serve the blob as an image file
        # need to reformat the display here 
        #imglist.append([r.title, r.image])
        imglist.append([r.title, r.image_blob])

    #xmlstr =""
    #tbl = TABLE(TR(*rows) for rows in imglist).xml()
    tbl = TABLE(*[TR(*rows) for rows in imglist])
    return tbl
Ejemplo n.º 41
0
def wedstrijduitslag():
    T.force("nl")
    wedstrijd_id = request.args(0)
    wedstrijd = db.wedstrijd(wedstrijd_id)
    uitslagen = (
        db(db.uitslag.wedstrijd==wedstrijd.id).select(orderby=db.uitslag.volgorde))
    return dict(wedstrijd=wedstrijd, uitslagen=uitslagen)
Ejemplo n.º 42
0
def codice_geografia(stato, provincia, comune, db):
    """Le lettere dalla dodicesima alla quindicesima, per il luogo di nascita.
    @param db: un callable che restituisce il codice (pescandolo da un db
               o altro storage). La signature del callable deve essere
               db(stato, provincia, comune).
    """
    return db(stato, provincia, comune)
Ejemplo n.º 43
0
	def sendMsgToQueue(self,id_virloc, mensaje,vircom):

		id_mensaje = self.getIDMensaje()
		id_mensaje_hex = hex(int(id_mensaje)).replace("0x","").zfill(4)
		
		DB = db()
		DB.sqlInsert('mensajes', 'id_mensaje=%s,id_mensaje_hex="%s",mensaje="%s", equipos_id=%s,vircom=%s' % (id_mensaje, id_mensaje_hex, mensaje, id_virloc,vircom))
Ejemplo n.º 44
0
def connect_form(res=''):
    if session.man_id:
        ##redirect(URL('cabinet','index'))
        return
    
    form_to_view = True
    form = FORM(
        DIV(
            DIV(LABEL(T('Введите Ваш Е-майл'),': '), _class='col-sm-4'),
            DIV(INPUT(_name='em', requires=IS_EMAIL()), _class='col-sm-8'),
        _class = 'row'),
             INPUT(_type='submit', _class='btn btn-' + CLRS_btn))
    if form.accepts(request, session, keepvalues=True):
        man = db(db.men.email == form.vars.em).select().first()
        form_to_view = False
        if not man:
            import time
            time.sleep(2)
            import random
            import string
            while True:
                ref_key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(10))
                if not db(db.men.ref_key == ref_key).select().first():
                    break
            man_id = db.men.insert(email = form.vars.em, ref_key = ref_key, ref_man = GIFT_CODE) ## , name = form.vars.mm, 
            db.commit()
            man = db.men[ man_id ]


        #response.flash = CENTER(B(T('Email with access key send to Your. Check email and spam folder')))
        response.flash = CENTER(B(T('Письмо выслано на Ваш Емэйл. На всякий случай проверьте папку для спама.')))
        res = mail_connect(man, request)
    elif form.errors:
        response.flash = CENTER(T('Проверьте данные, обнаружена ошибка!'))
    else:
        ##response.flash = CENTER('please fill the form')
        pass
    
    h = DIV(H2(T('Подключение к Персональному Кабинету')),
            P(T('Для подключения введите Ваш емэйл и мы вышлем Вам ключ доступа'),'.'),
            BR(), form if form_to_view else '',
            P(T('Пожалуйста используйте броузер Google Chrome для корректной посылки письма. При этом сессия будет создана именно для этого броузера.')),
            res,
            BR(),
            _class='inv')
    
    return h
Ejemplo n.º 45
0
def index():
    """Gestor de unidades orgánicas"""
    C = Storage()
    C.escuela = db.escuela(1)
    menu_migas.append(T("Unidades Orgánicas"))

    # permisos
    editar = auth.has_membership(role=myconf.take('roles.admin'))
    crear = auth.has_membership(role=myconf.take('roles.admin'))
    deletable = auth.has_membership(role=myconf.take('roles.admin'))

    # configurar grid
    query = (db.unidad_organica.id > 0)
    query &= (db.unidad_organica.escuela_id == C.escuela.id)
    campos = [db.unidad_organica.id,
              db.unidad_organica.nombre]

    if 'new' in request.args:
        db.unidad_organica.escuela_id.default = C.escuela.id
        db.unidad_organica.escuela_id.writable = False

    if 'edit' in request.args:
        db.unidad_organica.escuela_id.writable = False
    if 'view' in request.args:
        redirect(URL('unidad', 'index', args=[request.args(2)]))

    db.unidad_organica.id.readable = False

    C.unidades = grid_simple(query,
                       orderby=[db.unidad_organica.nombre],
                       fields=campos,
                       maxtextlength=100,
                       editable=editar,
                       create=crear,
                       details=True,
                       history=False,
                       searchable=False,
                       deletable=deletable)

    cantidad = db(query).count()
    if (session.entrada_directa is None) and cantidad == 1:
        session.entrada_directa = True
        u = db(query).select(db.unidad_organica.ALL).first()
        redirect(URL('unidad', 'index', args=[u.id]))


    return dict(C=C)
Ejemplo n.º 46
0
def count_by_years_table():
	
	# make a list of countries in the UNGC list
	clist = []
	# Fill cursor buffer
	database = db()
	database.query('select distinct country from ungc order by country;')
	# dump cursor buffer into list

	for line in database.query_results:
		# country is a tuple, like ('country', ) so it needs the index
		#print(line[0])
		clist.append(line[0])
		
	# let's just start a new table
	database.execute('drop table if exists BY_COUNTRY;')
	database.execute("CREATE TABLE BY_COUNTRY (Country VARCHAR(250), Year INT, Firms INT, Sectors INT, Types INT, CPI INT);")


	start = timer()

	print('before def')
	def ungc_total_count(database, year, cry):
		'''Returns query '''
		st = "SELECT count(name), count(distinct sector), count(distinct org_type) from UNGC where date_joined < '%s' and date_due >= '%s' and country='%s';" % (year, year+10000, cry)
		database.query(st)
		return(database.query_results[0])
	print('after 1st def')
	def get_cpi(database, yr, cry):
		year = str(yr)[:4]
		# like works for CPI, let's hope world bank follows
		st = "SELECT val from CPI where year='%s' and country ilike('%s');" % (year, cry)
		database.query(st)
		if len(database.query_results) == 0:
			#print(cry)
			return(False)
		else:
			return(database.query_results[0])

	
	print(len(clist))
	for j in range(len(clist)):
		cry = clist[j]
		# ISO standard date format
		yr = 19950101
		for i in range(1,22):
			#print(yr)
			cpi_counts = get_cpi(database, yr, cry)
			# indexed because it's one tuple in a list
			ungc_counts = ungc_total_count(database, yr, cry)
			if cpi_counts is not False:
				year = int(str(yr)[:4])
				st = (cry, year, ungc_counts[0], ungc_counts[1], ungc_counts[2], cpi_counts[0])
				print(st)
			yr = yr + 10000

	end = timer()

	print(end - start)
Ejemplo n.º 47
0
def search(key):
	#key = input("Keyword : ")
	cmd = "SELECT url from links where txt like '%" + key + "%';"
	print (cmd)
	rows = db(cmd)
	for row in rows:
		print(row[0])
	return rows
Ejemplo n.º 48
0
def view_inventory():
    # query for partnum
    # partnum should be in html request
    # ex. view_inventory?partnum=LAMP-1
    row = db(db.invent.partnum == request.get_vars.partnum).select().first()
    # display queried object
    record = crud.read(db.invent, row.id)
    return dict(record=record)
Ejemplo n.º 49
0
def add_CPI_table():
	''' Adds CPI data from Transparency International. Not country rank though, not really useful for anything '''
	# CPI_Final has the CPI data from TI, with 0 instead of blanks, 
	# and countries removed if they have data for fewer than 15 years b/t 1995 and 2015.
	
	fields = ("country", "year", "val")
	database = db()
	database.execute('drop table if exists CPI;')
	# we just make year int because m/d doesn't matter
	
	database.execute("CREATE TABLE CPI (%s varchar(250), %s int, %s float);" % fields)
	
	
	def is_number(s):
		''' is s a number? needed for line_fix '''
		try:
			float(s)
			return True
		except ValueError:
			return False

	def line_fix(line):
		''' dammit costa rica!
		necessary for countries with multiple words '''
		l = line.split('\t')
		i = 0
		c = ""
		while is_number(l[i]) is False:
			c += l[i]
			i += 1
		c = "".join([ch for ch in c if ch not in string.punctuation])
		c = c.lower()
		return([c] + l[i:])
	
	with open("./CPI_Final.txt", 'r') as f:
		years = f.readline().split()
		for line in f:
			# clean the line; we want [country, 1995_val, 1996_val, etc] and not [cou, ntry, etc]
			l = line_fix(line)

			country = l[0]
			
			# because the split('\t') leaves \n on the last one...
			l[-1] = l[-1].split()[0]
			
			for i in range(1, len(l)):
				# we only want to add table for years with values
				if l[i] != '0':
					data = (country, years[i-1], l[i])
				
					cmd0 = "INSERT INTO CPI (%s, %s, %s) " % fields
					cmd1 = "VALUES (%r, %r, %r);" % data
					cmd = cmd0 + cmd1	
					# Add to our db:
					database.execute(cmd)

	database.commit()
	database.close()
Ejemplo n.º 50
0
def reserve():
    id = session['id']
    seats = request.form['selected_seats']
    #return str(seats)
    bus_ID = request.form['bus_ID']
    fplace = request.form['fplace']
    tplace = request.form['tplace']
    date = request.form['date']
    #return date
    cmd = "SELECT bus_no_of_seats_available from bus where bus_ID = '%s';" % bus_ID
    rows = db(cmd)
    #return str(rows)
    row = int(rows[0][0]) - int(seats)
    row = str(row)
    cmd = "UPDATE bus set bus_no_of_seats_available = %s where bus_ID = '%s';" % (
        row, bus_ID)
    db(cmd)
    cmd = "SELECT * from bus where bus_ID = '%s';" % bus_ID
    #return str(db(cmd))
    #cmd = "SELECT route_ID from route where bus_ID"
    cmd = "INSERT into reservation(customer_ID,bus_ID,route_origin,route_destination,res_no_of_seats,res_timestamp) values (%s,'%s','%s','%s',%s,'%s');" % (
        id, bus_ID, fplace, tplace, seats, date)
    db(cmd)
    cmd = "SELECT customer_firstname from customer where customer_ID = %s;" % id
    rows = db(cmd)
    name = rows[0][0]

    cmd = "SELECT * from reservation where customer_ID = %s and res_timestamp = '%s';" % (
        id, date)
    rows = db(cmd)
    #return str(rows)

    return render_template('ticketbooked.html', rows=rows, name=name)
Ejemplo n.º 51
0
def mainpage():
    id = session['id']
    if session['logged_in'] is False:
        abort(401)
    cmd = "SELECT customer_firstname from customer where customer_ID = %s;" % id
    rows = db(cmd)
    customer_firstname = rows[0][0]
    #return str(customer_firstname)
    return render_template("main.html", id=id, name=customer_firstname)
Ejemplo n.º 52
0
	def getIDMensaje(self):
		DB = db()
		d = DB.sqlSelect("max(id_mensaje) as id_mensaje", "mensajes", "")
		id_respuesta = 8000
		for id_mensaje in d.fetchone():
			if id_mensaje:
				if id_mensaje + 1 != 65535:
					id_respuesta = id_mensaje + 1
		return str(id_respuesta).zfill(4)
Ejemplo n.º 53
0
def check_places(form):
    #place = form.vars.name
    #area = form.vars.area
    #data = db(db.places.name==place) & (db.places.area==area)).select()
    query = db.places.name == form.vars.name
    query &= db.places.area == form.vars.area
    if db(query).count():
        form.errors.user = T("Relation Between Place/Name already exists!")
    return
Ejemplo n.º 54
0
def index():
    begin_maand, einde_maand = mvhutils.beginEindeHuidigeMaand()
    query = ((db.wedstrijd.datum >= begin_maand)&
             (db.wedstrijd.datum <= einde_maand))
    wedstrijden = db(query).select(db.wedstrijd.datum,
                                   db.wedstrijd.omschrijving,
                                   db.wedstrijd.aanvang,
                                   db.wedstrijd.opmerkingen)
    return dict(wedstrijden=wedstrijden)
Ejemplo n.º 55
0
def get_bal_lvl(man_id, cash_id, max_bal):
    if max_bal == 0:
        return 0
    man_bal = db((db.man_bals.man_id == man_id)
               & (db.man_bals.cash_id == cash_id)).select().first()
    if man_bal and man_bal.bal:
        return int(5 * man_bal.bal / max_bal)
    
    return 0
Ejemplo n.º 56
0
def query_by_tag():
    """
    get all images for a tag
    """
    
    #rows = (db(purchase.buyer==kenny).select()|db(purchase.buyer==cartman).select())
    
    # find matches by tag
    cnt = 0
    tg_eu = db(db.xtg.name=='EU').select().first()
    rows = (db(db.xref.xtg==tg_eu.id).select())
    #rows = (db(db.xref.xtg==tg_eu.id).select()).as_list()
    imglist = []
    for r in rows:
        cnt +=1
        imglist.append(r.xim.title)
        
    return
Ejemplo n.º 57
0
def upload_image():
	"""
	This is where an artist uploads a work of art.
	"""

	form = SQLFORM(db.xim, _name='xim_form',
			fields=['title', 'description', 'image'])

	if request.env.web2py_runtime_gae:
		from google.appengine.ext import blobstore
		import uuid
		#get the blob_info.  NOTE this MUST be done before any other operations on
		# the request vars.  otherwise something modifies them (perhaps the form
		# validators) in a way that makes this not work
		blob_info = None
		if request.vars.image != None:
			blob_info = blobstore.parse_blob_info(request.vars.image)

		upload_url = blobstore.create_upload_url(URL(r=request,f='upload_image',
													 args=request.args))

		form['_action']=upload_url
		if form.accepts(request.vars,session, formname="ximform"):
			#@TODO: can this blob-key update be a post-validation function?
			#get the record we just inserted/modified
			row = db(db.xim.id == form.vars.id).select().first()
			if request.vars.image__delete == 'on' or \
				(form.vars.image != None and (row and row.blob_key)):
				#remove from blobstore because of delete or update of image
				key = row.blob_key
				blobstore.delete(key)
				#remove reference in the xim record
				row.update_record(blob_key=None, image=None)
			if form.vars.image != None:
				#add reference to image in this record
				row.update_record(image = \
					"xim.image."+str(uuid.uuid4()).replace('-','')+".jpg",
					blob_key = blob_info.key())
			crud.archive(form)
			#Raise the HTTP exception so that the response content stays empty.
			#calling redirect puts content in the body which fails the blob upload
			raise HTTP(303,
					   Location= URL(r=request,f='list_blob_images'))
		elif form.errors:
			#logging.info("form not accepted")
			logging.info(form.errors)
			session.flash=BEAUTIFY(form.errors)
			#there was an error, let's delete the newly uploaded image
			if request.vars.image != None:
				blobstore.delete(blob_info.key())
			#Raise the HTTP exception so that the response content stays empty.
			#calling redirect puts content in the body which fails the blob upload
			raise HTTP(303,
					   Location= URL(r=request,f='upload_image'))

	return dict(form=form)
Ejemplo n.º 58
0
 def __init__(self):
     
     # Create System Dummy nodes.
     self.system1Node = render.attachNewNode('system 1')
     print self.system1Node
     
     # DB Instance.
     # So we can get data from 'planetData' table.
     DB = db()
     self.planets(DB)