Exemple #1
0
 def startup(self):
     indigo.insteon.subscribeToIncoming()
     indigo.insteon.subscribeToOutgoing()
     indigo.x10.subscribeToIncoming()
     indigo.x10.subscribeToOutgoing()
     indigo.devices.subscribeToChanges() # -> def deviceUpdated(self, origDev, newDev)
     db.setup()
Exemple #2
0
def main():
    db.setup()
    PROCESSES = 5
    print('Creating pool with %d processes\n' % PROCESSES)

    with mp.Pool(PROCESSES) as pool:
        """The main process"""
        q = mp.Queue()

        workr = mp.Process(target=worker, args=(running_flag, q))
        wdog = mp.Process(target=watchdog, args=(q, ))

        # run the watchdog as daemon so it terminates with the main process
        wdog.daemon = True

        workr.start()
        print("[MAIN]: starting process P1")
        wdog.start()

        # Poll the queue
        for i in range(9):
            msg = q.get()
            if msg == "KILL WORKER":
                print("[MAIN]: Terminating slacking WORKER")
                workr.terminate()
                time.sleep(0.1)
                if not workr.is_alive():
                    print("[MAIN]: WORKER is a goner")
                    workr.join()
                    print("[MAIN]: Joined WORKER successfully!")
                    q.close()
                    break  # watchdog process daemon gets terminated
Exemple #3
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup({ 'host': 'localhost', 'user': '******', 'passwd': 'test', 'db': 'lilac'})
     self.task = Task(
         None, 'task_id', 'job_test', 'job.test', {'args': (), 'kw': {}}, 'every 5')
     Backend('task').delete_by_name('job_test')
     Backend('task').save(self.task)
 def __init__(self, max_page=20, debug=False):
     # Setup database table
     db.setup()
     # Setup browser simulator (that can navigate through Tor)
     browser.setup()
     # Instance attributes
     self._max_page = max_page
     self._page = 1
     self._debug = debug
     # Create a pretty printer
     self._pp = pprint.PrettyPrinter(indent=4)
     # Copy the Meta class to a private attributes
     self._meta = self.Meta
     # Copy attributes from Scraper.Meta to the current meta class
     for attr in Scraper.Meta.__dict__.keys():
         # Does NOT import private attributes
         if attr[:1] != '_' and not hasattr(self.Meta, attr):
             # Copy from the parent
             setattr(self._meta, attr, getattr(Scraper.Meta, attr))
     # True if the given name is a field
     is_field = lambda m: isinstance(getattr(self, m), Field)
     # Save fields list
     self._fields = [ m for m in dir(self) if is_field(m) ]
     # Sort the fields
     self._fields.sort(key=lambda f: getattr(self, f)._count)
Exemple #5
0
	def sameTags():
		"Two users might want to have the same tag, one nega and one posi!"
		db.setup("CREATE TABLE uzerTags2 (id SERIAL PRIMARY KEY, tag INTEGER REFERENCES tags(id),uzer INTEGER REFERENCES uzers(id), nega BOOLEAN DEFAULT FALSE)",
			"INSERT INTO uzerTags2 (tag,uzer,nega) SELECT id,uzer,nega FROM uzerTags",
			"DROP TABLE uzerTags",
			"ALTER TABLE uzerTags2 RENAME TO uzerTags",
			"CREATE UNIQUE INDEX nodupeuzertags ON uzerTags(tag,uzer)")
Exemple #6
0
def main(): 
    timeout = 30
    num_cpus = psutil.cpu_count()
    logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',filename='app.log',level=logging.DEBUG) 
    print(os.getpid())
    print(os.getppid())
    if not ray.is_initialized():
        ray.init(include_webui=True)

    files = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']

    db.setup()
    print(os.getpid())
    print(os.getppid())
    with ray.profile('Event'):

        for i in range(10):
            time.sleep(randint(0, 4))
            try:
                ray.get(worker.remote(i))
            except Exception as e:
                raise e
                print(e.message)
            finally:
                print('finally')
Exemple #7
0
def build_db(subjects):
    if os.path.exists('prevent.db'):
        os.remove('prevent.db')
    db.setup()

    for subject in subjects:
        parse_subject_dir(subject)
Exemple #8
0
def load_s_data(dbo, filename):
    now = datetime.now()
    uid = config.settings["mdm"]["uid"]

    tablename = config.settings["db"]["tablename_s_data"]
    db.setup(dbo)

    sql = 'insert or replace into %s (source, id, json, ts) values(?, ?, ?, ?)' % tablename

    with open(filename, 'r', encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            doc = json.loads(line)

            if uid in doc:
                id = doc[uid]
            else:
                id = doc["id"]

            if "source" in doc:
                source = doc["source"]
            else:
                source = "_unknown"

            logging.warning("file %s: processing id = %s, source = %s" %
                            (filename, id, source))
            values = (source, id, json.dumps(doc, ensure_ascii=False), now)
            logging.debug(sql)
            db.execute(dbo, sql, values)

    sql = "update %s set ts=CURRENT_TIMESTAMP where ts is null" % tablename
    logging.debug(sql)
    db.execute(dbo, sql)

    db.commit(dbo)
Exemple #9
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup(config, adapter='pymysql')
     db.execute('DROP TABLE IF EXISTS `users`')
     db.execute("""CREATE TABLE `users` (
             `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
             `name` varchar(20) NOT NULL,
             PRIMARY KEY (`uid`))""")
Exemple #10
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup({ 'host': 'localhost', 'user': '******', 'passwd': 'test', 'db': 'lilac'})
     self.user = User('username', 'email', 'real_name', 'password', 'actived')
     db.execute('DELETE FROM users WHERE email=%s or email=%s',
                (self.user.email, 'email2'))
     Backend('user').save(self.user)
     self.uid = db.query('SELECT uid FROM users WHERE email=%s', (self.user.email,))[0][0]
Exemple #11
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup(config, adapter='pymysql')
     _create()
     users = []
     for i in range(1, 6):
         users.append((i, 'user_' + str(i)))
     db.execute('INSERT INTO users VALUES(%s, %s)', users)
Exemple #12
0
    def __init__(self, name=None):
        #	Maybe set up AutoLoginKey
        db.setup()

        #	Unimplemented
        identity = lambda x: x
        self.after_map = identity
        self.update_config_schema = identity
Exemple #13
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup(config,adapter='pymysql')
     db.execute('DROP TABLE IF EXISTS `users`')
     db.execute("""CREATE TABLE `users` (
             `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
             `name` varchar(20) NOT NULL,
             PRIMARY KEY (`uid`))""")
Exemple #14
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup(config,adapter='pymysql')
     _create()
     users = []
     for i in range(1, 6):
         users.append((i, 'user_' + str(i)))
     db.execute('INSERT INTO users VALUES(%s, %s)', users)
Exemple #15
0
def _():
	# batch clearing of neighbors for deleting
	db.setup(
			'''CREATE TABLE IF NOT EXISTS doomed (
			id INTEGER PRIMARY KEY REFERENCES media(id) ON DELETE CASCADE)
			''',
			'''ALTER TABLE blacklist ADD COLUMN oldmedium INTEGER''',
			'''ALTER TABLE dupes ADD COLUMN oldmedium INTEGER''')
Exemple #16
0
def init_db():
    db.setup(db_config,
             minconn=2,
             maxconn=6,
             adapter='mysql',
             key='default',
             slave=False)
    logger.info('init database')
Exemple #17
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup(config)
     _create()
     users = []
     for i in range(1, 6):
         users.append((i, 'user_' + str(i)))
     db.execute('INSERT INTO users VALUES(%s, %s)', users)
     self.delete = db.delete('users')
Exemple #18
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup(config)
     _create()
     users = []
     for i in range(1, 6):
         users.append((i, 'user_' + str(i)))
     db.execute('INSERT INTO users VALUES(%s, %s)', users)
     self.delete = db.delete('users')
Exemple #19
0
def startup():

	settings.load('settings.ini')

	db.setup()

	logging.getLogger().info("Checking database integrity.")
	#db.connection.execute("VACUUM")
	logging.getLogger().info("Integrity check complete. Continuing.")
Exemple #20
0
 def initially():
     db.setup('''CREATE TABLE videos (
     id INTEGER PRIMARY KEY REFERENCES things(id),
     width integer,
     height integer,
     fps float,
     vcodec text,
     acodec text,
     container text)''')
Exemple #21
0
def _():
	db.setup('''CREATE TABLE blacklist(
		id SERIAL PRIMARY KEY,
	  oldmedium INTEGER NOT NULL REFERENCES media(id),
		hash character varying(28) UNIQUE,
		reason TEXT)''',
			 '''CREATE TABLE dupes(
		id SERIAL PRIMARY KEY,
		medium INTEGER REFERENCES media(id),
		hash character varying(28) UNIQUE,
		inferior BOOLEAN DEFAULT FALSE,
		UNIQUE(medium,hash))''')
Exemple #22
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup(config, key='test')
     db.setup(config, key='test', slave=True)
     db.execute('DROP TABLE IF EXISTS `users`', key='test')
     db.execute("""CREATE TABLE `users` (
             `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
             `name` varchar(20) NOT NULL,
             PRIMARY KEY (`uid`))""", key='test')
     rows = []
     for _ in range(1, 10):
         rows.append('(%d , "name_%d")' % (_,  _))
     db.execute('INSERT INTO users VALUES ' + ', '.join(rows), key='test')
Exemple #23
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup(config, key='test')
     db.setup(config, key='test', slave=True)
     db.execute('DROP TABLE IF EXISTS `users`', key='test')
     db.execute("""CREATE TABLE `users` (
             `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
             `name` varchar(20) NOT NULL,
             PRIMARY KEY (`uid`))""",
                key='test')
     rows = []
     for _ in range(1, 10):
         rows.append('(%d , "name_%d")' % (_, _))
     db.execute('INSERT INTO users VALUES ' + ', '.join(rows), key='test')
Exemple #24
0
def addColumn():
    db.setup(
        'ALTER TABLE media RENAME COLUMN pHash TO derpHash',
        'ALTER TABLE media ADD COLUMN pHashFail BOOLEAN DEFAULT FALSE',
        'ALTER TABLE media ADD COLUMN pHash int8',
        '''UPDATE media SET 
    phash = ('x' || encode(substring(uuid_send(derpHash) from 10),'hex'))::bit(64)::int8, 
        pHashFail = (('x' || encode(substring(uuid_send(derpHash) from 1 for 8),'hex'))::bit(64)::int8 = 2)''',
        '''CREATE TABLE nadupes (
        id serial primary key,
    sis INTEGER references media(id),
    bro INTEGER references media(id),
    UNIQUE(sis,bro)
);''',
        '''INSERT INTO nadupes (sis,bro) SELECT a.id,b.id FROM media as a, media as b 
             WHERE a.id > b.id AND a.phash = b.phash AND (('x' || encode(substring(uuid_send(a.derpHash) from 1 for 8),'hex'))::bit(64)::int8 = 3) AND (('x' || encode(substring(uuid_send(b.derpHash) from 1 for 8),'hex'))::bit(64)::int8 = 3)''')
Exemple #25
0
    def __init__(self, settings, load=True):
        self.name = settings["plugin"]
        self.loaded = False
        self.hooks = []
        self.module = None
        self.settings = settings
        self.channels = settings.get("channels", None)
        _plugins[self.name] = self

        if self.settings.get("db", False):
            import db

            db.setup()

        if load:
            self.load()
Exemple #26
0
	def wrapper(*a,**kw):
		try:
			return f(*a,**kw)
		except db.Error as e:
			if not b'schema "resultcache" does not exist' in e['message']:
				raise
			
			intrans = db.c.inTransaction
			if intrans:
				db.rollback()
			print("loading schema...")
			db.setup("sql/resultCache.sql",source=True,named=False)
			if intrans:
				db.begin()
		# now try it with the db setup
		return f(*a,**kw)
Exemple #27
0
 def startFactory(self):
     logging.getLogger().info("Loading Session Certificates")
     caFile = open("keys/SessionCACert.pem")
     self.sessionCACert = crypto.load_certificate(crypto.FILETYPE_PEM,caFile.read())
     caFile.close()
     sessionCertFile = open("keys/SessionCert.pem")
     self.sessionCert = crypto.load_certificate(crypto.FILETYPE_PEM, sessionCertFile.read())
     sessionCertFile.close() 
     logging.getLogger().info("Setting Up Database")
     db.setup()
     logging.getLogger().info("Connection to Database")
     self.dbConnection = db.getConnection()
     logging.getLogger().info("Loading Plugin Framework")
     PluginManager.load_api_keys()
     PluginManager.load_plugins()
     logging.getLogger().info("Server is running and listening for connections")
Exemple #28
0
 def startFactory(self):
     logging.getLogger().info("Loading Session Certificates")
     caFile = open("keys/SessionCACert.pem")
     self.sessionCACert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                  caFile.read())
     caFile.close()
     sessionCertFile = open("keys/SessionCert.pem")
     self.sessionCert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                sessionCertFile.read())
     sessionCertFile.close()
     logging.getLogger().info("Setting Up Database")
     db.setup()
     logging.getLogger().info("Connection to Database")
     self.dbConnection = db.getConnection()
     logging.getLogger().info("Loading Plugin Framework")
     PluginManager.load_api_keys()
     PluginManager.load_plugins()
     logging.getLogger().info(
         "Server is running and listening for connections")
 def startFactory(self):
     logging.getLogger().info("Loading Session Certificates")
     caFile = open("keys/SessionCACert.pem")
     self.sessionCACert = crypto.load_certificate(crypto.FILETYPE_PEM,caFile.read())
     caFile.close()
     sessionCertFile = open("keys/SessionCert.pem")
     self.sessionCert = crypto.load_certificate(crypto.FILETYPE_PEM, sessionCertFile.read())
     sessionCertFile.close() 
     logging.getLogger().info("Setting Up Database")
     db.setup()
     logging.getLogger().info("Connection to Database")
     self.dbConnection = db.getConnection()
     logging.getLogger().info("Loading Plugin Framework")
     PluginManager.load_api_keys()
     PluginManager.load_plugins()
     datenow = datetime.datetime.now()
     timenow = datetime.time(12, 55, 0)
     timestamp = datetime.datetime.combine(datenow, timenow)
     logging.getLogger().info("{0}: Server is listening for connections".format(timestamp))
     logging.getLogger().warning("{0}: Server is listening for connections".format(timestamp))
     logging.getLogger().error("{0}: Server is listening for connections".format(timestamp))
Exemple #30
0
def test():
    db.setup()
    PROCESSES = 5
    print('Creating pool with %d processes\n' % PROCESSES)

    with multiprocessing.Pool(PROCESSES) as pool:
        #
        # Tests
        #

        TASKS = [(mul, (i, 7)) for i in range(10)] + \
                [(plus, (i, 8)) for i in range(10)]

        results = [pool.apply_async(calculate, t) for t in TASKS]
        imap_it = pool.imap(calculatestar, TASKS)
        imap_unordered_it = pool.imap_unordered(calculatestar, TASKS)

        print('Ordered results using pool.apply_async():')
        for r in results:
            print('\t', r.get())
            print('\t', os.getpid())
        print()

        print('Ordered results using pool.imap():')
        for x in imap_it:
            print('\t', x)
            print('\t', os.getpid())
        print()

        print('Unordered results using pool.imap_unordered():')
        for x in imap_unordered_it:
            print('\t', x)
            print('\t', os.getpid())
        print()

        print('Ordered results using pool.map() --- will block till complete:')
        for x in pool.map(calculatestar, TASKS):
            print('\t', x)
            print('\t', os.getpid())
        print()
Exemple #31
0
    def test_database(self):
        db.setup(config, adapter='pymysql')
        self.assertEqual(db.database(), db.database('default', slave=True))
        conns = getattr(db, '__db', [])
        self.assertEqual(len(conns['default.slave']), 1)

        db.setup(config, slave=True)
        self.assertNotEqual(db.database(), db.database('default', slave=True))
        conns = getattr(db, '__db', [])
        self.assertEqual(len(conns['default.slave']), 1)

        db.setup(config, slave=True)
        conns = getattr(db, '__db', [])
        self.assertEqual(len(conns['default.slave']), 2)
Exemple #32
0
    def test_database(self):
        db.setup(config,adapter='pymysql')
        self.assertEqual(db.database(), db.database('default', slave=True))
        conns = getattr(db, '__db', [])
        self.assertEqual(len(conns['default.slave']), 1)

        db.setup(config, slave=True)
        self.assertNotEqual(db.database(), db.database('default', slave=True))
        conns = getattr(db, '__db', [])
        self.assertEqual(len(conns['default.slave']), 1)

        db.setup(config, slave=True)
        conns = getattr(db, '__db', [])
        self.assertEqual(len(conns['default.slave']), 2)
Exemple #33
0
def initially():
	db.setup('''CREATE TABLE randomSeen (
	id SERIAL PRIMARY KEY,
	media INTEGER NOT NULL REFERENCES things(id) ON DELETE CASCADE,
	category integer NOT NULL DEFAULT 0,
	UNIQUE(media,category))''')
Exemple #34
0
from db import ProgrammingError
import db

import urllib.parse

db.setup(
	'CREATE TABLE hosts (id SERIAL PRIMARY KEY, host TEXT UNIQUE, resume TIMESTAMPTZ UNIQUE)',
	'''CREATE TABLE parseQueue (
	id SERIAL PRIMARY KEY,
	medium INTEGER REFERENCES media(id),
	added TIMESTAMPTZ DEFAULT now() NOT NULL, 
	tries integer default 0, 
	uri TEXT UNIQUE,
	host INTEGER REFERENCES hosts(id))''')

def host(uri):
	host = urllib.parse.urlsplit(uri).netloc
	colon = host.rfind(':')
	if colon > 0:
		host = host[:colon]
	r = db.execute('SELECT id FROM hosts WHERE host = $1',(host,))
	if r:
		host = r[0][0]
	else:
		host = db.execute('INSERT INTO hosts (host) VALUES ($1) RETURNING id',(host,))[0][0]
	return host

def enqueue(uri):
	if len(uri) > 2712: return
	try: h = host(uri)
	except ValueError: return
Exemple #35
0
 def boot_database(self):
     db.setup(self.config.get('db'))
     pedis.setup(**self.config.get('redis'))
Exemple #36
0
def initialize():
    db.setup()
Exemple #37
0
    def test_invalid_key(self):
        f = lambda: db.setup(config, key='dd.xx')

        self.assertRaises(TypeError, f)
Exemple #38
0
def setup():
    db_module.setup()
Exemple #39
0
register('apropos', on_search_for_quote_command)


# TODO(mtwilliams): We should prevent people from calling `purge` too often.
async def on_purge_command(context, raw):
    # Caller can provide the number of messages they wish to delete.
    try:
        limit = int(raw)
    except ValueError:
        # Default to one message.
        limit = 1

    # Clamp the provided number to a sane value.
    limit = max(1, min(limit, 100))

    # Note who called this since it's destructive.
    print(
        f'Deleting {limit} messages from {context.channel} at request of {context.author}.'
    )
    await context.channel.purge(limit=limit)


register('purge', on_purge_command, help='Deletes some number of messages.')

# Setup our database.
db.setup(DATABASE)

# Run our bot until the end of time.
# This will use the default asynchronous loop.
bot.run(TOKEN)
Exemple #40
0
def initialize():
    db.setup()
    auth0_setup()
Exemple #41
0
def reset():
    db_module.teardown()
    db_module.setup()
Exemple #42
0
from pprint import pprint
from utility import MappedRow, FetchPage
from config import CONFIG
import db

Models = db.setup()

def stat_parser(self, data):
    table = data.select('table.data.stats tr')
    stat_keys = [row.text.strip() for row in table[0].select('th')]
    stat_keys.append('uri')
    # Skipping the navigation row
    table = table[2:]
    stat_rows = []
    # Yes I know its O^2
    for row in table:
        stat_row = [field.text.strip() for field in row]
        link = row.select('a')[0]
        stat_row.append(link.get('href'))
        stat_rows.append(MappedRow(stat_row, stat_keys))

    for row in stat_rows:
        player = Models.PlayerModel()
        player['name'] = row['Player']
        player['team'] = row['Team']
        player['pos'] = row['Pos']
        player['uri'] = row['uri']
        try:
            player.save()
        except Exception:
            pprint("Issue saving %s" % player['name'])
Exemple #43
0
        c = request.app['db'].execute('insert into User ("E-Mail") values (?)',
                                      [post['email']])
        request.app['db'].commit()
        session['user_id'] = int(c.lastrowid)
        raise web.HTTPFound('/')
    raise web.HTTPFound('/signup')


ws_to_mbed = asyncio.Queue()
mbed_to_ws = asyncio.Queue()
app = web.Application()
loop = asyncio.get_event_loop()

aiohttp_session.setup(app, EncryptedCookieStorage(SECRET_KEY))
app.middlewares.append(user_middleware)
db.setup(app)
aiohttp_jinja2.setup(app,
                     loader=jinja2.FileSystemLoader(pathfromroot('templates')))
wshandler.setup(app, ws_to_mbed, mbed_to_ws)
embeddedhandler.setup(app, ws_to_mbed, mbed_to_ws, loop)

app.router.add_get('/wsmap', wshandler.wshandler)
app.router.add_get('/', jinja_view("index"))
app.router.add_get('/login', jinja_view("login", wrapper=public_page))
app.router.add_post('/login', login_handler)
app.router.add_get('/signup', jinja_view("signup", wrapper=public_page))
app.router.add_post('/signup', signup_handler)
app.router.add_get('/stats', jinja_view("stats", wrapper=admin_only))
app.router.add_get('/account', jinja_view("account"))
app.router.add_get('/logout', logout_handler)
app.router.add_static('/static', pathfromroot('static'))
Exemple #44
0
    def test_invalid_key(self):
        f = lambda: db.setup(config, key='dd.xx')

        self.assertRaises(TypeError, f)
Exemple #45
0
 def test_dup_key(self):
     db.setup(config,adapter='pymysql')
     f = lambda: db.setup(config,adapter='pymysql')
     self.assertRaises(db.DBError, f)
Exemple #46
0
from db import setup
setup()

import sys
import transforms

from maltego_trx.registry import register_transform_function, register_transform_classes
from maltego_trx.server import app, application
from maltego_trx.handler import handle_run

register_transform_classes(transforms)


class RateLimitingMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        # TODO add rate limiting mechanism
        return self.app(environ, start_response)


app.wsgi_app = RateLimitingMiddleware(app.wsgi_app)

handle_run(__name__, sys.argv, app)
Exemple #47
0
def qualifiedSources():
	print('Differentiating sources that provide tags, and sources that uniquely identify media')
	db.setup('''ALTER TABLE sources ADD COLUMN hasTags boolean default FALSE NOT NULL''',
			 '''ALTER TABLE sources ADD COLUMN uniquelyIdentifies boolean default TRUE''')
Exemple #48
0
 def wrapped(*args, **kwargs):
     conn = getattr(g, '_database', None)
     if not conn:
         conn = g._database = db.setup()
     return func(conn, *args, **kwargs)
Exemple #49
0
if __name__ == '__main__':
    def get_date(url, session='xxx'):
        date = None
        try:
            r = urllib2.urlopen(url)
            date = r.info().dict['date']
        except:
            LOGGER.info('open failed')
        LOGGER.info('session: %s, date:%s,', session, date)
     
    def setdebug(debug=False):
        level = logging.DEBUG if debug else logging.INFO
        logging.basicConfig(level=level,
                                format='%(asctime)s %(levelname)-8s %(message)s',
                                datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')
    setdebug(False)
    db.setup({ 'host': 'localhost', 'user': '******', 'passwd': 'test', 'db': 'lilac'})
     
    app = App()
    app.add_task('task.test', get_date)
    scheduler = Scheduler(app, 20, 20, 100)
     
    db.execute('delete from cron')
    for i in range(100):
        if i % 2 == 0:
            print i
            action = 'task.not_found'
        else:
            action = 'task.test'
        scheduler.add_task('name_%d' %(i), 'every 2', action, datetime.now(), 'http://www.google.com', session=i)
    scheduler.run()
Exemple #50
0
def initialize():
    db.setup()
    auth.setup()
    global auth0
    auth0 = auth.auth0
Exemple #51
0
 def boot_database(self):
     db.setup(self.config.get('db'))
     pedis.setup(**self.config.get('redis'))
Exemple #52
0
def _():
	db.setup('ALTER TABLE randomSeen ADD COLUMN seen BOOLEAN NOT NULL DEFAULT FALSE',
					 'UPDATE randomSeen SET seen = TRUE',
					 'CREATE INDEX haveSeenRandom ON randomSeen(seen,category)')
Exemple #53
0
@app.route('/nodes/root')
@api_response
@use_db
def root_node(conn):
    return db.get_root_node(conn)


@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('static/js', path)


@app.route('/css/<path:path>')
def send_css(path):
    return send_from_directory('static/css', path)


@app.teardown_appcontext
def close_db(exception):
    conn = getattr(g, '_database', None)
    if conn:
        conn.close()


if __name__ == '__main__':
    db.setup()

    app.debug = True
    app.run()
 def __init__(self, **kwargs):
     db.setup()
Exemple #55
0
 def test_dup_key(self):
     db.setup(config)
     f = lambda: db.setup(config)
     self.assertRaises(db.DBError, f)
Exemple #56
0
db.setup('''
CREATE OR REPLACE FUNCTION setComicPage(_medium INT, _comic INT, _which INT) RETURNS VOID AS
$$
BEGIN
	LOOP
		-- first try to update the key
		UPDATE comicPage set medium = _medium where comic = _comic and which = _which;
		IF found THEN
			RETURN;
		END IF;
		-- not there, so try to insert the key
		-- if someone else inserts the same key concurrently,
		-- we could get a unique-key failure
		BEGIN
			INSERT INTO comicPage(medium,comic,which) VALUES (_medium,_comic,_which);
			RETURN;
		EXCEPTION WHEN unique_violation THEN
			-- Do nothing, and loop to try the UPDATE again.
		END;
	END LOOP;
END;
$$
LANGUAGE plpgsql''',
'''
CREATE OR REPLACE FUNCTION findURISource(_uri TEXT) RETURNS int AS
$$
DECLARE
_id int;
BEGIN
	LOOP
		-- first try to find it
		SELECT id INTO _id FROM urisources WHERE uri = _uri;
		IF found THEN
			return _id;
		END IF;
		BEGIN
			INSERT INTO sources DEFAULT VALUES RETURNING id INTO _id;
			INSERT INTO urisources (id,uri) VALUES (_id,_uri);
		EXCEPTION WHEN unique_violation THEN
			-- Do nothing we can just find it now.
		END;
	END LOOP;
END;
$$
LANGUAGE plpgsql''')
Exemple #57
0
def db_restart(update, context):
    if(auxf.check_admin(update.message.from_user.id)):
        update.message.reply_text("Setting Up DB...")
        db.setup()
    else:
        update.message.reply_text("Você não tem permissão para executar esse comando.")
Exemple #58
0
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import model
from orm import Backend
import db

db.setup({'host': 'localhost', 'user': '******', 'passwd': 'test', 'db': 'blog'})

user = Backend('user').find_by_username('username')
if user and user.check('password'):
    print('auth')

user = model.User('username', 'email', 'real_name', 'password', 'bio',
                  'status', 'role')
if Backend('user').create(user):
    print('fine')

user = Backend('user').find(12)
user.real_name = 'blablabla....'
if Backend('user').save(user):
    print('user saved')
Exemple #59
0
x = logging.getLogger("logger")
x.setLevel(log_levels[options.logLevel])

if options.logfile != None:
    h = logging.FileHandler(options.logfile)
else:
    h = logging.StreamHandler()

f = logging.Formatter(u"%(levelname)s %(funcName)s %(message)s")
h.setFormatter(f)
x.addHandler(h)


#setup database
db.setup()

#load Plugins
PluginManager.load_api_keys()
PluginManager.load_plugins()


#start server
x.info("Starting Server")
server = SiriServer('', options.port)
try:
    asyncore.loop()
except (asyncore.ExitNow, KeyboardInterrupt, SystemExit):
    x.info("Caught shutdown, closing server")
    asyncore.dispatcher.close(server)
    exit()
Exemple #60
0
	def __init__(self, name=None):
		#	Maybe set up UserOrgRelation
		db.setup(populate=tk.config.get('ckan.saabreg.auto_populate', True))
		
		#	Not implemented
		self.after_map = lambda x: x