Example #1
0
def clean_db():
	db.open()
	try:
		stamp = get_period_time_stamp()
		db.clean(stamp)
	finally:
		db.db.close()
Example #2
0
def add_wagons(loco_id, wagons):
    for wagon in wagons:
        wagon_type_id = add_wagon.get_wagon_type_id(str(wagon["name"]))
        if wagon_type_id is None:
            print "could not find wagon:", str(wagon["name"])
            continue
        sql = '''
            select id
              from wagons
             where locomotive_id is null
               and wagon_type_id = ?
             limit ?
        '''
        db.open()
        cur = db.conn.cursor()
        cur.execute(sql, (wagon_type_id, wagon.get("count", 1)))
        wagon_ids = []
        for res in cur.fetchall():
            wagon_ids.append((loco_id, res[0]))
        print "adding", len(wagon_ids), str(wagon["name"]), "wagons"
        sql = '''
            update wagons
               set locomotive_id = ?
             where locomotive_id is null
               and id = ?
        '''
        cur.executemany(sql, wagon_ids)
        db.commit()
        db.close()
Example #3
0
def select_top_db():
	db.open()
	dict = {}
	try:
		result = db.select_all()
		for row in result:
			if(not dict.has_key(row[1])):
				summary = MsgSummary()
				summary.msg = row[3]
				summary.prefix_msg = row[1]
				summary.time = row[2]
				summary.id_list = [row[0]]
				
				
				dict[row[1]] = [1, summary]
			else:
				dict[row[1]][0] += 1
				dict[row[1]][1].id_list.append(row[0])	
		
		happenList = []
		
		for k,v in dict.items():
			
			happenList.append((v[0], v[1].time, v[1]))
	finally:
		db.db.close()
	print happenList
	happenList = sorted(happenList, key=itemgetter(0,1) , reverse=True)
	print happenList
	return happenList
Example #4
0
def get_wagon_type_id(name):
    db.open()
    cur = db.conn.cursor()
    wagon_id = None
    sql = 'select id from wagon_types where name = ?'
    cur.execute(sql, (name, ))
    res = cur.fetchone()
    if res is not None:
        wagon_id = res[0]
    db.close()
    return wagon_id
Example #5
0
def get_locomotive_type_id(name):
    l_id = None
    sql = 'select id from locomotive_types where name = ?'
    db.open()
    cur = db.conn.cursor()
    cur.execute(sql, (name, ))
    res = cur.fetchone()
    if res is not None:
        l_id = res[0]
    db.close()
    return l_id
Example #6
0
def add_wagon_type(wagon_type, name, capacity, profit, cargo):
    db.open()
    cur = db.conn.cursor()
    sql = """
        insert into wagon_types (super_type, type, name, capacity, profit, cargo)
        values (?, ?, ?, ?, ?, ?)
        """
    super_type = wagon_super_types.get(wagon_type, 'cargo')
    cur.execute(sql, (super_type, wagon_type, name, capacity, profit, cargo))
    last_id = cur.lastrowid
    db.commit()
    db.close()
    return last_id
Example #7
0
def process_msg():

	db.open()
	try:
		stamp = get_period_time_stamp()
		inb = inbox.Inbox()
		i=0
		
		msgs = inb.sms_messages()
		count = len(msgs)
		for i in range(count):
			if(i >= limit):
				break
			
			id = msgs[i]
			
			if(inb.address(id) != txNum):
				continue
			
			t = inb.time(id)
			
			if(t < stamp):
				#too early msg
				break
			#print t
			#print strftime("%Y-%m-%d %H:%M:%S", time.localtime(t))
			msg = inb.content(id)
			
			msg = msg.rstrip(u"【腾讯科技】")
			
			if(msg[:4] == "2/2)"):
				continue
				
			elif(msg[:4] == "1/2)"):
				if(i != 0):
					# i != 0, indicates that we already have both two pieces of the whole message
					newmsg = msg[4:] + inb.content(msgs[i-1])[4:].rstrip(u"【腾讯科技】")
			else:
				newmsg = msg
			
			msgArr = newmsg.split("|")
			
			if(len(msgArr) >= 2):
				main = msgArr[1]
				db.insert(id, main, inb.time(id), newmsg)
			
			
	finally:
		db.db.close()
Example #8
0
def add_locomotive(name, operation, l_type = None, power = None):
    sql = '''
        insert into locomotives (locomotive_type_id, operation)
        values (?, ?)
    '''
    l_id = get_locomotive_type_id(name)
    if l_id is None:
        l_id = add_locomotive_type(name, l_type, power)
    db.open()
    cur = db.conn.cursor()
    cur.execute(sql, (l_id, operation))
    last_id = cur.lastrowid
    db.commit()
    db.close()
    return last_id
Example #9
0
def save(result):
    import db
    count = len(result)
    i = 0.00
    db.open()
    db.begin()
    for r in result:
        print '\b' * 8, '%2.2f%%' % (i * 100 / count),
        r['numbers'] = ''.join(r['numbers'])
        r['numbers'] = r['numbers'][:-2] + '+' + r['numbers'][-2:]
        db.tinsert('ssq', r)
        i += 1
    db.commit()
    print '\b' * 8, '100.00%'
    db.close()
Example #10
0
def save(result):
    import db
    count = len(result)
    i = 0.00
    db.open()
    db.begin()
    for r in result:
        print '\b' * 8, '%2.2f%%' % (i * 100 / count),
        r['numbers'] = ''.join(r['numbers'])
        r['numbers'] = r['numbers'][:-2] + '+' + r['numbers'][-2:]
        db.tinsert('ssq', r)
        i += 1
    db.commit()
    print '\b' * 8, '100.00%'
    db.close()
Example #11
0
def add_wagon(name, wagon_type = None, capacity = None, profit = None, cargo = None):
    sql = '''
        insert into wagons (wagon_type_id)
        values (?)
    '''
    wagon_id = get_wagon_type_id(name)
    if wagon_id is None:
        wagon_id = add_wagon_type(wagon_type, name, capacity, profit, cargo)
    db.open()
    cur = db.conn.cursor()
    cur.execute(sql, (wagon_id, ))
    last_id = cur.lastrowid
    db.commit()
    db.close()
    return last_id
Example #12
0
def main(force_all=False):
    DB = db.open(config)

    t = time()
    for asset in DB.query({'path': db.ANY, 'xt': db.ANY}):
        if asset.get(u'@linked') and not force_all:
            continue

        for p in asset['path']:
            dst = path.normpath(path.join(LINKDIR, p)).encode('utf8')
            if not dst.startswith(LINKDIR):
                print "Warning! %s tries to break out of directory!" % dst
                continue

            tgt = path.join(BHFUSEDIR, magnet.fromDbObject(asset))
            try:
                oldtgt = os.readlink(dst)
            except OSError:
                oldtgt = None

            if oldtgt == tgt:
                continue
            elif oldtgt: 
                os.unlink(dst)

            dstdir = path.dirname(dst)
            if not path.exists(dstdir):
                os.makedirs(dstdir)
            os.symlink(tgt, dst)
        asset[u'@linked'] = db.ValueSet((u'true',), t=t)
        DB.update(asset)
    DB.commit()
Example #13
0
def checkNewNicks(self):
    """
		check any new posts for new nicknames	
	"""
    query = "select address, data from posts where post_id > " + str(
        self.savedAllPostId) + " and data like 'nick:%'"
    rows = putQuery(self, query)
    if rows is False:
        return False
    conn = db.open()
    c = conn.cursor()
    for row in rows['rows']:
        c.execute('select id from nicks where address = ?;', (row[0], ))
        nickId = c.fetchone()
        nick = row[1].split(':', 1)
        if nickId is None:
            c.execute('insert into nicks (nick, address) values (?,?);',
                      (nick[1], row[0]))
        else:
            c.execute('update nicks set nick = ? where address = ?;',
                      (nick[1], row[0]))
        #also check follows for potential updates
        c.execute('select nick from follows where address = ?;', (row[0], ))
        checkNick = c.fetchone()
        if checkNick is not None:
            if nick[1] != checkNick[0]:
                c.execute('update follows set nick=? where address=?;',
                          (nick[1], row[0]))
    db.close(conn)
    return
Example #14
0
def main():
    DB = db.open(config)
    tmppath = TXTPATH+".tmp"
    outfile = open(tmppath, 'w')
    count = util.Counter()
    storage = util.Counter()

    def onStatusUpdate(asset, status, db_asset):
        if status.status == bithorde.message.SUCCESS:
            if int(count):
                outfile.write(',\n')
            count.inc()
            storage.inc(status.size)
            json.dump(db_asset, outfile, cls=Encoder, indent=2)

    outfile.write('[')

    client = bithorde.BitHordeIteratorClient(list_db(DB), onStatusUpdate)
    bithorde.connectUNIX(UNIXSOCKET, client)
    bithorde.reactor.run()

    outfile.write(']')
    outfile.close()

    if os.path.exists(TXTPATH):
        shutil.copymode(TXTPATH, tmppath)
    os.rename(tmppath, TXTPATH)

    print "Exported %d assets, with %.2fGB worth of data." % (count, storage.inGibi())
Example #15
0
 def open(self):
     """If the database keeps a connection, prepare it."""
     for db in self.dbs:
         result = db.open()
         if result != self.OK:
             return result
     return self.OK
Example #16
0
def checkNewNicks(self):
	"""
		check any new posts for new nicknames	
	"""
	query = "select address, data from posts where post_id > " + str(self.savedAllPostId) + " and data like 'nick:%'"
	rows = putQuery(self, query)
	if rows is False:
		return False
	conn = db.open()
	c = conn.cursor()
	for row in rows['rows']:
		c.execute('select id from nicks where address = ?;', (row[0],))
		nickId = c.fetchone()
		nick = row[1].split(':', 1)
		if nickId is None:
			c.execute('insert into nicks (nick, address) values (?,?);', (nick[1], row[0]))
		else:
			c.execute('update nicks set nick = ? where address = ?;', (nick[1], row[0]))
		#also check follows for potential updates
		c.execute('select nick from follows where address = ?;', (row[0],))
		checkNick = c.fetchone()
		if checkNick is not None:
			if nick[1] != checkNick[0]:
				c.execute('update follows set nick=? where address=?;', (nick[1], row[0]))
	db.close(conn)
	return
Example #17
0
 def open(self):
     """If the database keeps a connection, prepare it."""
     for db in self.dbs:
         result = db.open()
         if result != self.OK:
             return result
     return self.OK
Example #18
0
def disassemble(loco_id):
    db.open()
    cur = db.conn.cursor()
    sql = '''
        update wagons
           set locomotive_id = null
         where locomotive_id = ?
    '''
    cur.execute(sql, (loco_id,))
    sql = '''
        update locomotives
           set operation = ?
         where id = ?
    '''
    cur.execute(sql, ("unused", loco_id))
    db.commit()
    db.close()
Example #19
0
def add_locomotive_type(name, l_type, power):
    sql = '''
        insert into locomotive_types (name, type, power, bonus_on, bonus)
        values (?, ?, ?, ?, ?)
    '''
    db.open()
    cur = db.conn.cursor()
    bonus_vals = bonuses.get(l_type)
    bonus = None
    bonus_on = None
    if bonus_vals is not None:
        bonus_on = str(bonus_vals.get('bonus_on'))
        bonus = str(bonus_vals.get('bonus'))
    cur.execute(sql, (name, l_type, power, bonus_on, bonus))
    last_id = cur.lastrowid
    db.commit()
    db.close()
    return last_id
Example #20
0
def get_unused_locos():
    sql = '''
        select id, locomotive_type_id
          from locomotives
         where id not in (
            select distinct(locomotive_id)
              from wagons
             where locomotive_id is not null);
    '''
    locos = []
    db.open()
    cur = db.conn.cursor()
    cur.execute(sql)
    for res in cur.fetchall():
        loco = locomotive_metadata[res[1]].copy()
        loco["id"] = res[0]
        locos.append(loco)
    db.close()
    return locos
Example #21
0
def get_unused_wagons(wagon_type = None):
    sql = '''
        select wagon_type_id, count(1)
          from wagons
         where locomotive_id is null
         group by wagon_type_id
    '''
    wagons = []
    db.open()
    cur = db.conn.cursor()
    cur.execute(sql)
    for res in cur.fetchall():
        if wagon_type is not None:
            if wagon_type != str(wagon_metadata[res[0]]["type"]):
                continue
        wagon = wagon_metadata[res[0]].copy()
        wagon["count"] = res[1]
        wagons.append(wagon)
    db.close()
    return wagons
Example #22
0
def getNick(self, address):
	"""
		get the nickname associated with the specified address
	"""
	conn = db.open()
	c = conn.cursor()
	c.execute('select nick from nicks where address = ?;', (address,))
	nick = c.fetchone()
	db.close(conn)
	if nick is None:
		return address
	else:
		return nick[0]
Example #23
0
def getNick(self, address):
    """
		get the nickname associated with the specified address
	"""
    conn = db.open()
    c = conn.cursor()
    c.execute('select nick from nicks where address = ?;', (address, ))
    nick = c.fetchone()
    db.close(conn)
    if nick is None:
        return address
    else:
        return nick[0]
Example #24
0
def getFollows(self):
	"""
		return the list of follows from the db
		update the list of nicks first
	"""
	if pollAllPosts(self):
		checkNewNicks(self)
	conn = db.open()
	c = conn.cursor()
	c.execute('select nick, address from follows where profile=?;', (str(self.agentAddress),))
	follows = c.fetchall()
	db.close(conn)
	return follows
Example #25
0
def getFollows(self):
    """
		return the list of follows from the db
		update the list of nicks first
	"""
    if pollAllPosts(self):
        checkNewNicks(self)
    conn = db.open()
    c = conn.cursor()
    c.execute('select nick, address from follows where profile=?;',
              (str(self.agentAddress), ))
    follows = c.fetchall()
    db.close(conn)
    return follows
Example #26
0
def get_trains(loco_id = None):
    db.open()
    cur = db.conn.cursor()
    trains_dict = {}
    sql = '''
        select l.id, l.locomotive_type_id, l.operation, w.id, w.wagon_type_id
          from wagons w,
               locomotives l
         where w.locomotive_id = l.id
         order by l.id, w.id
    '''
    cur.execute(sql)
    all_res = cur.fetchall()
    for res in all_res:
        if loco_id is not None:
            if loco_id != res[0]:
                continue
        loco = (res[0], res[1], str(res[2]))
        new_wagon = (res[3], res[4])
        wagons = trains_dict.get(loco, [])
        wagons.append(new_wagon)
        trains_dict[loco] = wagons
    db.close()
    return populate_trains_info(trains_dict)
Example #27
0
def getAddressFromNick(nick):
	"""
		find and return the address value for the associated nick
		check nicks as we should store every possible one
		nick is automatically the address if no nick is set
		return False if nick not found
	"""
	conn = db.open()
	c = conn.cursor()
	c.execute('select address from nicks where nick=?;', (nick,))
	data = c.fetchone()
	if data is None:
		return False
	else:
		return data[0]
Example #28
0
def getSeedFromNick(nick):
    """
		find and return the seed value for the associated nick
		check profiles as we only store seeds for those
		nick is automatically the address if no nick is set
		return False if nick not found
	"""
    conn = db.open()
    c = conn.cursor()
    c.execute('select seed from profiles where nick=?;', (nick, ))
    data = c.fetchone()
    if data is None:
        return False
    else:
        return data[0]
Example #29
0
def getSeedFromNick(nick):
	"""
		find and return the seed value for the associated nick
		check profiles as we only store seeds for those
		nick is automatically the address if no nick is set
		return False if nick not found
	"""
	conn = db.open()
	c = conn.cursor()
	c.execute('select seed from profiles where nick=?;', (nick,))
	data = c.fetchone()
	if data is None:
		return False
	else:
		return data[0]
Example #30
0
def getAddressFromNick(nick):
    """
		find and return the address value for the associated nick
		check nicks as we should store every possible one
		nick is automatically the address if no nick is set
		return False if nick not found
	"""
    conn = db.open()
    c = conn.cursor()
    c.execute('select address from nicks where nick=?;', (nick, ))
    data = c.fetchone()
    if data is None:
        return False
    else:
        return data[0]
Example #31
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Description:   创建实时数据表格
"""
import db
import datetime
import os
import random
db.open('phems')

now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
if not os.path.exists('../log'):
    os.mkdir('../log')
file = open("../log/create_data_%s.txt" % now, 'w')


def log(*k, sp=' ', end='\n'):
    print(k)
    global file
    for i in k:
        file.write(i + sp)
    file.write(end)


def create_data():
    sls = [
        i['f_station_id']
        for i in db.query_dict("select * from public.t_energy_station")
    ]
    dtypes = [
Example #32
0
def init_db():
	db.open()
	try:
		db.init_table()
	finally:
		db.db.close()
Example #33
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Description:   创建温度实时数据
"""
import db
import datetime
import os
import random
import json
db.open('pcems')

now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
if not os.path.exists('../log'):
    os.mkdir('../log')
file = open("../log/create_data_%s.txt" % now, 'w')


def log(*k, sp=' ', end='\n'):
    print(k)
    global file
    for i in k:
        file.write(i + sp)
    file.write(end)


def create_data():
    tablename = 'trd_2018_1_11_m'

    data_temp = {
        "data": [{
Example #34
0
import db,json
import sys

print >> sys.stderr, 'building object...'
a = db.open('dg-new.db')
obj = db.toobj(a)

print >> sys.stderr, 'mangling object...'

# Precompute some data.
artist_fwd = {}
song_fwd = {}
for k in obj['artists']:
  k['playcount'] = 0
  artist_fwd[k['id']] = k
for k in obj['songs']:
  k['plays'] = []
  song_fwd[k['id']] = k
for set in obj['sets']:
  for play in set['plays']:
    song_fwd[play['songid']]['plays'].append(set['id'])
    artist_fwd[song_fwd[play['songid']]['artistid']]['playcount'] += 1

# Then, compress the object by mangling keys.
zobj = {
  'version': 2,
  'artists': [ { '_i': v['id'], '_a': v['artist'], '_p': v['playcount'] } for v in obj['artists'] ],
  'songs': [ { '_i': v['id'], '_a': v['artistid'], '_t': v['title'], '_p': v['plays'] } for v in obj['songs'] ],
  'sets': [ { '_i': v['id'],
              '_d': v['date'],
              '_p': [ [ v2['songid'], v2['request'] ] for v2 in v['plays'] ] 
Example #35
0
from flask import *
import sys
import re

from page_code import *
from passwd import hash

import db

logname = "/var/log/security_events.log"
db.open("/home/admin/employee.db")

app = Flask(__name__)


@app.route('/')
def index():
    login_url = url_for('first_login')
    return redirect(login_url)


@app.route('/favicon.ico')
def favicon():
    return redirect(url_for('static', filename='favicon.ico'))


@app.route('/login', methods=['GET', 'POST'])
def first_login():
    if request.method == 'POST':
        if request.form is None:
            abort(400)
Example #36
0
 def openDB(self):
     db = self.application.db.clone()
     self._db_ = db
     db.open()  # open 时 autocommit=False
     return db
Example #37
0
                      action="store_true", dest="recursive", default=False,
                      help="Recursively add files from a folder")
    parser.add_option("-e", "--ext",
                      action="append", dest="exts",
                      help="Define file extensions to be added. Only valid with -r / --recursive-add")

    (options, args) = parser.parse_args()
    if len(args) < 1:
        parser.error("At least one file or directory must be specified.")

    do_export = False

    # Parse into DB-tag-objects
    tags = cliopt.parse_attrs(options.tags)

    DB = db.open(config)

    def add(file, tags, exts):
        '''Try to upload one file to bithorde and add to index'''
        file = unicode(path.normpath(file), sys.stdin.encoding or 'UTF-8')
        name = options.sanitizer(file)
        mtime = path.getmtime(file)
        ext = os.path.splitext(file)[1]
        tags = tags or {}
        exts = exts or set()

        if type(exts).__name__ == 'list':
           exts = set(exts)

        try:
            for e in config.get('ADD', 'extensions').split(','):
Example #38
0
def GetTableDB():
    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName(gbl.dbPath)
    db.open()
    return db
Example #39
0
def load_metadata():
    db.open()
    load_wagons()
    load_locomotives()
    db.close()
Example #40
0
 def init(db_file="casket.kch"):
     global db
     KyotoDB._DB = kc.DB()
     if not db.open(db_file, kc.DB.OWRITER | kc.DB.OCREATE):
         raise db.DataBaseError("open error: " + str(db.error()))
Example #41
0
    return iter_series()

def scrape_for(obj):
    if obj.get('imdb'):
        return imdb_scraper(obj, obj['imdb'].any())
    elif obj.get('title') and obj.get('year'):
        return imdb_search(obj)
    elif obj.get('series') and obj.get('season') and obj.get('episode'):
        return tvdb_search(obj)

if __name__ == '__main__':
    import db, config, sys, cliopt

    config = config.read()
    db = db.open(config)

    usage = "usage: %prog [options] [assetid] ..."
    parser = cliopt.OptionParser(usage=usage)
    parser.add_option("-a", "--add", action="append", dest="adds",
                      help="Add a value for an attr for objects, such as '-tname:monkey'. Previous tags for the attribute will be kept.")
    parser.add_option("-s", "--set", action="append", dest="attrs",
                      help="Overwrite an attr tag for objects, such as '-tname:monkey'. Previous tags for the attribute will be removed.")
    (options, args) = parser.parse_args()

    attrs = cliopt.parse_attrs(options.attrs)
    adds = cliopt.parse_attrs(options.adds)

    for arg in args:
        obj = db[arg]
Example #42
0
yt = build("youtube", "v3", developerKey=api_key)

# https://developers.google.com/youtube/v3/docs/videos/list
op = yt.videos().list(part='statistics', id=video_id)


def extract_stats(result):
    # result here is something like
    # {'kind': 'youtube#videoListResponse', 'etag': 'E6-Bzb4X_fDK5xKsNzx6LWpuOdY', 'items': [{'kind': 'youtube#video', 'etag': 'CTSoVMDunhrUb-G04W0MqgsMtFI', 'id': 'drvH4XbZoPs', 'statistics': {'viewCount': '281260', 'likeCount': '2271', 'dislikeCount': '29', 'favoriteCount': '0', 'commentCount': '50'}}], 'pageInfo': {'totalResults': 1, 'resultsPerPage': 1}}

    return result['items'][0]['statistics']


import db

db_conn = db.open()

while True:
    result = op.execute()
    stats = extract_stats(result)

    now = datetime.datetime.now(datetime.timezone.utc)

    print("{}, {}".format(now, stats['viewCount']))

    db.put(db_conn, now, video_id, stats)

    # it seems that the statistics are updated every 5 minutes.
    time.sleep(5 * 60)
Example #43
0
def usage():
    print "Usage: %s [-c <config>]" % sys.argv[0]
    sys.exit(2)

def main():
    try: opts, args = getopt.getopt(
        sys.argv[1:], "hsc:", ["help", "secure", "config="])
    except getopt.GetoptError, err:
        print str(err)
        usage()
    
    configfile = "perscon.conf"
    https = False
    for o, a in opts:
        if o in ("-c", "--config"): configfile = a
        elif o in ("-s", "--secure"): https = True
        elif o in ("-h", "--help"): usage()
        else: usage()

    config.parse(configfile)
    db.open()
    port = config.port()
    
    print "Listening on port %d" % port
    if https: server = SecureHTTPServer(('', port), PersconHandler)
    else: server = HTTPServer(('', port), PersconHandler)
    
    server.serve_forever()

if __name__ == '__main__': main()
Example #44
0
    def __init__(self, db):
        self._db = db;

    def list(self, filter=[]):
        for k,v in self._db.filter(path=filter):
            print "%s: %s"%(timestamp_to_str(v.timestamp), v.name)

    def dir(self, prefix=[]):
        for path, count in self._db.dir("path", prefix).iteritems():
            print count, '\t', path

if __name__=='__main__':
    parser = OptionParser(usage="usage: %prog [options] <PATH>")
    parser.add_option("-d", "--dir", action="store_true", dest="dir",
                      help="dir-mode, list subdirectory")
    parser.add_option("-l", "--list", action="store_false", dest="dir",
                      help="list-mode, list files")

    (options, args) = parser.parse_args()
    if len(args)>1:
        parser.error("Only one path-argument supported")
    elif args:
        path=db.path_str2lst(args[0])
    else:
        path=[]

    thisdb = DB(db.open(config))
    if options.dir:
        thisdb.dir(path)
    else:
        thisdb.list(path)
Example #45
0
def main():
    print('Bienvenido: Simulador')
    db.open()
    elements = db.getElements()

    root = Tk()
    ##app = Window(root)
    root.wm_title("Simulador")  # set window title

    # Define form
    FLabel = Label(root, text="F").grid(row=0, column=0)
    f = StringVar()
    usernameEntry = Entry(root, textvariable=f).grid(row=0, column=1)

    zfLabel = Label(root, text="Zf").grid(row=1, column=0)
    zfLabel = Label(root, text="XLF").grid(row=1, column=3)
    zfLabel = Label(root, text="XHF").grid(row=1, column=4)

    rowCounter = 2
    elementDicc = dict()
    for i in range(len(elements)):
        rowCounter += i
        element = elements[i]
        elementDicc[element] = dict()
        elementDicc[element]['is_select'] = IntVar()
        elementDicc[element]['is_xlf'] = IntVar()
        elementDicc[element]['is_xhf'] = IntVar()
        elementDicc[element]['value'] = StringVar()
        elementDicc[element]['db_row'] = i + 1

        Checkbutton(root, variable=elementDicc[element]['is_select']).grid(
            row=rowCounter, column=0)
        Label(root, text=str(element)).grid(row=rowCounter, column=1)
        zfEntry = Entry(root, textvariable=elementDicc[element]['value']).grid(
            row=rowCounter, column=2)
        Checkbutton(root, variable=elementDicc[element]['is_xlf']).grid(
            row=rowCounter, column=3)
        Checkbutton(root, variable=elementDicc[element]['is_xhf']).grid(
            row=rowCounter, column=4)

    rowCounter += 1
    pLabel = Label(root, text="P").grid(row=rowCounter, column=0)
    p = StringVar()
    pEntry = Entry(root, textvariable=p).grid(row=rowCounter, column=1)

    rowCounter += 1
    tfLabel = Label(root, text="Tf").grid(row=rowCounter, column=0)
    tf = StringVar()
    tfEntry = Entry(root, textvariable=tf).grid(row=rowCounter, column=1)

    rowCounter += 1
    columnaPLabel = Label(root, text="Columna P").grid(row=rowCounter,
                                                       column=0)
    columnaP = StringVar()
    columnaPEntry = Entry(root, textvariable=columnaP).grid(row=rowCounter,
                                                            column=1)

    rowCounter += 1
    xlkLabel = Label(root, text="XLK").grid(row=rowCounter, column=0)
    xlk = StringVar()
    xlkEntry = Entry(root, textvariable=xlk).grid(row=rowCounter, column=1)

    rowCounter += 1
    xhkLabel = Label(root, text="XHK").grid(row=rowCounter, column=0)
    xhk = StringVar()
    xhkEntry = Entry(root, textvariable=xhk).grid(row=rowCounter, column=1)

    rowCounter += 1
    ropLabel = Label(root, text="R OP").grid(row=rowCounter, column=0)
    R_OP = StringVar()
    xhkEntry = Entry(root, textvariable=R_OP).grid(row=rowCounter, column=1)

    if (env_dev_flag):
        f.set(100)
        for element in elementDicc:
            elementDicc[element]['is_select'].set(1)
            # if element == 'n-Hexano':
            #     print('----->   Set Etano to XLF',)
            #     elementDicc[element]['is_xlf'].set(1)
            # if element == 'Acetato de Etilo':
            #     print('----->   Set Cumeno to XHF',)
            #     elementDicc[element]['is_xhf'].set(1)

        elementDicc['Benceno']['value'].set(0.05)
        elementDicc['Acetona']['value'].set(0.01)
        elementDicc['n-Butano']['value'].set(0.15)
        elementDicc['Etano']['value'].set(0.05)
        elementDicc['Cumeno']['value'].set(0.1)
        elementDicc['n-Heptano']['value'].set(0.1)
        elementDicc['n-Hexano']['value'].set(0.1)
        elementDicc['o-Xileno']['value'].set(0.1)
        elementDicc['Acetato de Etilo']['value'].set(0.1)
        elementDicc['n-Octano']['value'].set(0.1)
        p.set(1)
        tf.set(120)
        columnaP.set(4)
        xlk.set(0.97)
        xhk.set(0.03)
        R_OP.set(0.4)
    startsSimulation = partial(start, f, elementDicc, p, tf, columnaP, xlk,
                               xhk, R_OP)

    rowCounter += 1
    startButton = Button(root,
                         text="Simular",
                         highlightbackground='#000000',
                         command=startsSimulation).grid(row=rowCounter,
                                                        column=1)
    #show window
    print("Show window")
    root.mainloop()
    print('Programa terminado')
Example #46
0
        tagText = label.get('for')
        tag = tagText.split('-')[1]
        sText = label.string
        s = sText.strip()
        data.append([tag, s])

    return data


def get_request(url, category, open_url):
    #category[0] - category_id
    return [open_url.get(url), category]


if __name__ == '__main__':
    sql_conn, sql_cursor = db.open()
    open_url = openurl()

    if db.category_is_empty(sql_cursor) or defines.ALWAYS_REINIT_CATEGORY:
        print("open catalog..")
        db.clear_category(sql_cursor)
        #categories = parseCategories(open('test.html'))
        catalog = open_url.get(defines.CATALOG_HEAD_URL)

        with codecs.open("test.html", "w", encoding='utf8') as f:
            f.write(catalog)

        categories = parseCategories(open_url.get(defines.CATALOG_HEAD_URL))
        for category in categories:
            db.set_category(sql_cursor, category)
    else:
Example #47
0
def select_db():
	db.open()
	try:
		db.select_all()
	finally:
		db.db.close()
Example #48
0
def GetTableDB():
	db = QSqlDatabase.addDatabase('QSQLITE')
	db.setDatabaseName(gbl.dbPath)
	db.open()
	return db
Example #49
0
def timed(method):
    def timed(*args, **kw):
        with Timed("%r (%r, %r)" % (method.__name__, args, kw)):
            res = method(*args, **kw)
            if isinstance(res, GeneratorType):
                return list(res)
            else:
                return res

        return result

    return timed

import db, config
config = config.read()
DB=db.open(config.get('DB', 'file'))

fields=set((u'directory', u'name', u'ext', u'xt', u'bh_status', u'bh_status_confirmed', u'bh_availability', u'filesize'))
def scan(directory_obj):
    dir_prefix = directory_obj.id+'/'
    for obj in DB.query({u'directory': db.Starts(dir_prefix)}, fields=fields):
        name_found = 0
        for directory in obj['directory']:
            if directory.startswith(dir_prefix):
                name = directory[len(dir_prefix):]
                if name:
                    name_found += 1
                    yield name, obj

        if not name_found and obj.any('name'):
            name = obj.any('name')
Example #50
0
@app.route('/remove_comment/<string:site_id>/<int:cid>/<path:page_uri>', methods=['POST'], strict_slashes=True)
def remove_comment(site_id, cid, page_uri):
    if not request.json:
        abort(400)
    
    if md5(bytes(request.json['password'], 'utf-8')).hexdigest() != config.moderate_pass_hash:
        return jsonify( { 'status' : 'denied' } )
    
    print('removing comment {0}'.format(cid))
    # remove comment from list
    removed = app.db.list_remove(cid, 0, 'comments', site_id, page_uri)
    if removed:
        # remove actual comment content
        app.db.remove_dict(COMMENT_FIELDS, 'comment', cid)
        status = 'ok'
    else:
        status = 'notfound'
    return jsonify( { 'status' : status } )

if __name__ == '__main__':
    from os import environ
    if 'CA_USE_CONFIG_JS' in environ:
        app.configjs = environ['CA_USE_CONFIG_JS']
    else:
        app.configjs = None
    app.db = db.open(config.server, config.port, config.password)
    if 'PORT' in environ:
        app.run(debug=False, host='0.0.0.0', port=int(environ['PORT']))
    else:
        app.run(debug=True)
Example #51
0
import db

db.open()
cur = db.conn.cursor()

tables = 'wagons, wagon_types, locomotives, locomotive_types'
table_list = tables.split(',')

for table in table_list:
    cur.execute("delete from " + table)

cur.execute("vacuum")
cur.close()
db.close()