예제 #1
0
파일: user.py 프로젝트: sdslabs/forsit
	def __init__(self, erd_handle, cfs_handle = '', options = {}, app_name = "local", number_to_recommend = 50):
		self.training_problems = {}
		self.options = {}
		self.options['tag_based'] = 0
		self.options['normalize'] = 0
		self.options['sample_data'] = 1
		self.options['penalize'] = 1
		if 'tag_based' in options:
			self.options['tag_based'] = options['tag_based']
		if 'normalize' in options:
			self.options['normalize'] = options['normalize']
		if 'sample_data' in options:
			self.options['sample_data'] = options['sample_data']
		if 'penalize' in options:
			self.options['penalize'] = options['penalize']

		self.conn=db.connect()
		self.cursor = self.conn.cursor()
		self.remote_conn = db.connect('remote')
		self.remote_cursor = self.remote_conn.cursor()

		self.cfs_url = "http://codeforces.com/api/user.info"
		self.erd_url = "http://erdos.sdslabs.co/users/"
		self.cfs_handle = 'cfs' + str(cfs_handle)
		self.erd_handle = 'erd' + str(erd_handle)
		self.number_to_recommend = number_to_recommend
		self.uid = self.get_uid()
		# print self.uid
		self.calculate_difficulty()
예제 #2
0
파일: test_db.py 프로젝트: kalafut/decks
def db(request):
    _db.connect("sqlite://", init=True)

    def close():
        _db.disconnect()
    request.addfinalizer(close)
    return _db
예제 #3
0
파일: admin.py 프로젝트: alcinnz/WyWeb
    def admin_institutions_remove(self, id):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST':
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "DELETE FROM institution WHERE institutionid=%s"
            cursor.execute(query, (id,))
            query = "DELETE FROM course where institutionid = %s"
            cursor.execute(query, (id,))
            cursor.close()
            cnx.close()

            return templating.render("redirect.html", STATUS="alert-success", 
                                    MESSAGE="Institution deleted...")
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "SELECT institution_name FROM institution WHERE institutionid=%s"
            cursor.execute(query, (id,))
            name = cursor.fetchone()[0]
            cursor.close()
            cnx.close()

            return templating.render("confirm.html", TITLE="Are you sure you want to delete "+name+"?",
                                MESSAGE="The institution and all it's courses will be permanently removed.",
                                CONFIRM_LABLE="DELETE")
예제 #4
0
파일: admin.py 프로젝트: alcinnz/WyWeb
    def admin_institutions(self, institution="", *args, **kwargs):
        """
        Lists available institutions.

        >>> authorizeTests()
        >>> self = Admin()
        >>> ret = self.admin_institutions()
        >>> ('Victoria University of Wellington', 2) in ret.OPTION
        True
        >>> ret = self.admin_institutions(2)
        >>> ret.INSTITUTION_ID, ret.INSTITUTION, ret.CONTACT, ret.WEBSITE, ret.DESCRIPTION
        (2, 'Victoria University of Wellington', None, None, None)
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        allow(["HEAD", "GET", "POST"])
        redirect = "NO"
        options = []

        if institution:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = ("SELECT institution_name, institutionid from institution order by institution_name")
            cursor.execute(query)
            options = list(cursor)
            cursor.close()
            cnx.close()
        displayInstitution = ""
        displayContact = ""
        displayWebsite = ""
        displayDescription = ""

        if institution == "":
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = ("SELECT institution_name, institutionid from institution order by institution_name")
            cursor.execute(query)
            institution = ""
            for (institute) in cursor:
                options.append(institute)
                if institution == "":
                    institution = institute[1]

            cursor.close()
            cnx.close()

        cnx, status = db.connect()
        cursor = cnx.cursor()
        query = (
            "SELECT institution_name,description,contact,website from institution where institutionid = '" + str(institution) + "'")
        cursor.execute(query)
        displayInstitution, displayDescription, displayContact, displayWebsite = cursor.fetchone()
        cursor.close()
        cnx.close()

        return templating.render("admin_institutions.html", ROOT_URL=config.VIRTUAL_URL, ERROR="", 
                               REDIRECT=redirect, OPTION=options, INSTITUTION_ID=institution,
                               INSTITUTION=displayInstitution, CONTACT=displayContact, WEBSITE=displayWebsite,
                               DESCRIPTION=displayDescription, IS_ADMIN=isAdmin(userid))
예제 #5
0
파일: admin.py 프로젝트: alcinnz/WyWeb
    def admin_course_remove(self, id):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST':
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "DELETE FROM course WHERE courseid=%s"
            cursor.execute(query, (id,))
            cursor.close()
            cnx.close()

            return templating.render("redirect.html", STATUS="alert-success", 
                                    MESSAGE="Course deleted...")
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = """SELECT course.course_name, institution.institution_name FROM course, institution 
                    WHERE course.courseid=%s AND institution.institutionid = course.institutionid"""
            cursor.execute(query, (id,))
            course, institution = cursor.fetchone()
            cursor.close()
            cnx.close()

            return templating.render("confirm.html",
                            TITLE="Are you sure you want to delete %s at %s?" % (course, institution),
                            MESSAGE="This course will be permanently removed.", CONFIRM_LABLE="DELETE")
예제 #6
0
파일: admin.py 프로젝트: alcinnz/WyWeb
    def admin_teacher_revoke(self, id):
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        if request.method == 'POST':
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "DELETE FROM teacher_info WHERE userid=%s"
            cursor.execute(query, (id,))
            cursor.close()
            cnx.close()

            return templating.render("redirect.html", STATUS="alert-success", 
                                    MESSAGE="Admin rights revoked...")
        else:
            cnx, status = db.connect()
            cursor = cnx.cursor()
            query = "SELECT username FROM whiley_user WHERE userid=%s"
            cursor.execute(query, (id,))
            name = cursor.fetchone()[0]
            cursor.close()
            cnx.close()

            return templating.render("confirm.html", 
                                TITLE="Are you sure you want to revoke %s's teaching rights?" % name,
                                MESSAGE="", CONFIRM_LABLE="REVOKE")
예제 #7
0
파일: main.py 프로젝트: PhilipSkinner/repo1
def main():
  import app
  import db
  import handlers
  
  application = app.app(handlers.URLS)
  settings.APP_SETTINGS['debug'] = True
  settings.APP_SETTINGS['static_path'] = os.path.join('/home/philip/Development/repo1/server', "static"),
  
  db.connect(
    'repo1',
    host='localhost',
    port=27017
  )
  
  #insert default data
  if 1==2:
#    code = db.QR(url='testing')
#    code.save()
    bar = db.Bar(name="Freds bar")
    bar.save()
    
  server = tornado.httpserver.HTTPServer(application)
  server.listen(80)
  tornado.ioloop.IOLoop.instance().start()
예제 #8
0
def main():
    logger = logging.getLogger('poke-receiver')
    logger.addHandler(logging.FileHandler(settings.LOGFILE_RECEIVER)) 
    logger.setLevel(logging.INFO)    
    logger.info("receiver.py started")
    conn = db.connect(settings.DATABASE)
    run = True
    i = timestamp()
    while run:
        i += 1
        try:
            data = pickle.load(sys.stdin)
        except EOFError:
            run = False
        except pickle.UnpicklingError:
            logger.error("couldn't unpickle sys.stdin, ignoring...")
        else:            
            db.store(conn, data, i)
            logger.info("data stored: %s %s" % (i, data))
        if i % settings.DB_COMPRESSION_INTERVAL == 0:
            db.compress(conn, i)
            conn.close()
            try:
                time.sleep(settings.DB_COMPRESSION_SLEEP)
            except KeyboardInterrupt:
                run = False
            else:
                conn = db.connect(settings.DATABASE)
                logger.info("db compressed, reconnected")
    conn.close()
예제 #9
0
파일: hpc_config.py 프로젝트: cbajema/Edgar
    def connectDB():
        config = None
        with open(HPCConfig.importingConfigPath, 'rb') as f:
            config = json.load(f)

        db.connect(config)

        return db
예제 #10
0
파일: auth.py 프로젝트: alcinnz/WyWeb
    def user_courses(self, studentinfoid=None, institution="", validationcode="", courseid="", *args, **kwargs):
        """Assign user to select course
        
        """
        if studentinfoid is None:
            raise cherrypy.HTTPRedirect("/")
        allow(["HEAD", "GET", "POST"])
        error = False
        error_msg = " "
        redirect = "NO"
        options = []

        course_list = []
        
        if institution:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query) 
            options = list(cursor)
            cursor.close()

        if courseid:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            error = insertuserdetails(studentinfoid, institution, courseid, validationcode)
            cursor.close()
            if error is False:
                message="User Created, Welcome! Redirecting..."
                template = lookup.get_template("redirect.html")
                return template.render(STATUS="alert-success", MESSAGE=message)
            else:
                error_msg= "Wrong Validation Code"

        if institution == "":          
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query)
            for (institutionid,institution_name) in cursor:
                options.append((institutionid, institution_name))
                if institution == "":
                    institution = str(institutionid)
            cursor.close()

        ##get courses list
        cnx, status = db.connect()
        cursor = cnx.cursor() 
        query = ("SELECT courseid,code from course where institutionid = '" + institution + "' order by code")
        cursor.execute(query)
        course_list = list(cursor)
        cursor.close()

        return templating.render("user_institutions.html", ERROR=error, ERRORMSG=error_msg, NOTALLOWED=False, 
                                ROOT_URL=config.VIRTUAL_URL, OPTION=options, 
                                COURSE_LIST=course_list, STUDENTINFOID=studentinfoid, INSTITUTION=institution)
예제 #11
0
def make(filename):
	db.connect()
	db.make()
	if filename:
		process_file(filename)
	else:
		import_groups()
		#import_data_gov_in.start()
		#import_devinfo.start()
		import_worldbank_data.start()
    def test_db_connect(self):
        dbFileName = 'xxxx.txt'
        with self.assertRaises(db.DBFileNameError):
            conn, cursor = db.connect(dbFileName)

        dbFileName = 'unittest_%d.db' % time.time()
        conn, cursor = db.connect(dbFileName)
        self.assertTrue(dbFileName in os.listdir('.'))
        self.assertTrue(isinstance(conn, sqlite3.Connection))
        self.assertTrue(isinstance(cursor, sqlite3.Cursor))
예제 #13
0
파일: admin.py 프로젝트: alcinnz/WyWeb
    def admin_courses(self, institution="", *args, **kwargs):
        """
        Lists all available courses. 

        >>> authorizeTests()
        >>> self = Admin()
        >>> ret = self.admin_courses()
        >>> (2, 'Victoria University of Wellington') in ret.OPTION
        True
        >>> ret = self.admin_courses('2')
        >>> (2, 'Victoria University of Wellington') in ret.OPTION
        True
        >>> ret.INSTITUTION
        '2'
        >>> (1, 'SWEN302') in ret.COURSE_LIST
        True
        """
        userid = cherrypy.session.get(auth.SESSION_USERID)
        requireAdmin(userid)

        allow(["HEAD", "GET", "POST"])
        error = ""
        redirect = "NO"
        options = []

        course_list = []
        
        if institution:
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query) 
            options = list(cursor)
            cursor.close()
        else:          
            cnx, status = db.connect()
            cursor = cnx.cursor() 
            query = ("SELECT institutionid,institution_name from institution order by institution_name")
            cursor.execute(query)
            for (institutionid,institution_name) in cursor:
                options.append((institutionid, institution_name))
                if institution == "":
                    institution = str(institutionid)
            cursor.close()
                
        cnx, status = db.connect()
        cursor = cnx.cursor() 
        query = ("SELECT courseid,code from course where institutionid = '" + institution + "' order by code")
        cursor.execute(query)
        course_list = list(cursor)
        cursor.close()

        return templating.render("admin_courses.html", ROOT_URL=config.VIRTUAL_URL, ERROR=error,
                                REDIRECT=redirect, OPTION=options, INSTITUTION=institution, 
                                COURSE_LIST=course_list, IS_ADMIN=isAdmin(userid))
예제 #14
0
def main():
	db.connect()
	
	if db.roadhouse is None:
		print('FATAL: Cannot connect to the database!')
		return
		
	tornado.options.parse_command_line()
	app = Application()
	app.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()
예제 #15
0
파일: http.py 프로젝트: 1ngmar/ianki
 def newfunc():
     web._context[threading.currentThread()] = tmpctx
     # Create new db cursor if there is one else background thread
     # overwrites foreground cursor causing rubbish data into dbase
     if web.config.get('db_parameters'):
         import db
         db.connect(**web.config.db_parameters)
     func(*a, **kw)
     myctx = web._context[threading.currentThread()]
     for k in myctx.keys():
         if k not in ['status', 'headers', 'output']:
             try: del myctx[k]
             except KeyError: pass
예제 #16
0
def check_con_params():
    if con_params:
        try:
            connect()
        except Exception:
            print('''Error with connection to database. \
                    \nCheck connection parameters in file db.py''')
            return False
        else:
            return True
    else:
        print('Lack of connection parameters in file db.py')
        return False
예제 #17
0
def setup():
    """Call once to set everything up:"""
    db.connect(db_config)

    #Map all the model objects to the column families:
    for cf in db_config["column_families"]:
        try:
            model_obj = globals()[cf]
            if model_obj.__base__ != ModelBase:
                continue
            cass_cf = getattr(db,cf)
        except KeyError:
            continue
        model_obj.objects = pycassa.ColumnFamilyMap(model_obj, cass_cf)
예제 #18
0
def load():
    """
    Loads a new context for the thread.
    
    You can ask for a function to be run at loadtime by 
    adding it to the dictionary `loadhooks`.
    """
    _context[threading.currentThread()] = storage()
    ctx.status = '200 OK'
    ctx.headers = []
    if config.get('db_parameters'):
        import db
        db.connect(**config.db_parameters)
    
    for x in loadhooks.values(): x()
예제 #19
0
파일: main.py 프로젝트: alcinnz/WyWeb
def save(project_name, filename, data):
    userid = cherrypy.session.get(auth.SESSION_USERID)
    cnx, status = db.connect()
    cursor = cnx.cursor()
    print "saving Project:", project_name, userid
    sql = "SELECT p.projectid FROM project p where p.userid = %s AND p.project_name = %s"
    cursor.execute(sql, (userid,project_name))
    project = cursor.fetchone()
    if project:
        projectid = project[0]
    else:
        sql = "INSERT INTO project (project_name, userid) VALUES (%s, %s)"
        cursor.execute(sql, (project_name, userid))
        projectid = cursor.lastrowid

    sql = "INSERT INTO file (projectid, filename, source) VALUES (%s, %s, %s)"
    print projectid, filename, data
    print sql
    cursor = cnx.cursor()
    cursor.execute(sql, (projectid, filename, data))
    if cursor.fetchwarnings():
        for item in cursor.fetchwarnings():
            print item
    cursor.close()
    cursor = cnx.cursor()
    cursor.execute("select * from file where projectid = %s", (projectid, ))
    print cursor.fetchall()
예제 #20
0
파일: card.py 프로젝트: oujiaqi/suiyue
 def change_porder(cid,porder):
     conn=connect()
     cursor=conn.cursor()
     cursor.execute("update card set porder=%s where cid=%s",[porder,cid])
     conn.commit()
     cursor.close()
     conn.close()
예제 #21
0
파일: card.py 프로젝트: oujiaqi/suiyue
 def change_fid(cid,fid):
     conn=connect()
     cursor=conn.cursor()
     cursor.execute("update card set fid=%s where cid=%s",[fid,cid])
     conn.commit()
     cursor.close()
     conn.close()
예제 #22
0
파일: card.py 프로젝트: oujiaqi/suiyue
 def change_main(cid,main):
     conn=connect()
     cursor=conn.cursor()
     cursor.execute("update card set main=%s where cid=%s",[main,cid])
     conn.commit()
     cursor.close()
     conn.close()
예제 #23
0
파일: card.py 프로젝트: oujiaqi/suiyue
 def del_one_card(cid):
     conn=connect()
     cursor=conn.cursor()
     cursor.execute("delete from card where cid=%s",[cid])
     conn.commit()
     cursor.close()
     conn.close()
예제 #24
0
    def export_to_database(self):
        connection = db.connect()
        c = connection.cursor()

        c.execute("SELECT id FROM indicators WHERE name = 'Population'")
        population_id = c.fetchone()[0]
        c.execute("SELECT id FROM indicators WHERE name = 'Dwellings'")
        dwellings_id = c.fetchone()[0]
        c.execute("SELECT id FROM indicators WHERE name = 'Occupied dwellings'")
        occupied_dwellings_id = c.fetchone()[0]

        c.execute('DELETE FROM indicator_region_values WHERE indicator_id IN %s', ((population_id, dwellings_id, occupied_dwellings_id),))

        c.execute("""
            PREPARE insert_region_values (INT, INT, INT, INT, CHAR) AS
            INSERT INTO indicator_region_values (region_id, indicator_id, value_integer, note)
            VALUES
            ($1, %d, $2, $5),
            ($1, %d, $3, $5),
            ($1, %d, $4, $5)
            """ % (population_id, dwellings_id, occupied_dwellings_id))

        for region_id, statistics in self._region_statistics.items():
            c.execute('EXECUTE insert_region_values (%s, %s, %s, %s, %s)',
                    (region_id, statistics.population, statistics.n_dwellings,
                        statistics.n_occupied_dwellings, statistics.note))

        connection.commit()
예제 #25
0
파일: lastblog.py 프로젝트: liangxh/idu
def exists(mid, threshold = 1, con = None):
	import db
	if con == None:
		conn = db.connect()
		cur = conn.cursor()

	cur.execute('SELECT user_id, timestamp FROM microblogs WHERE mid = %s LIMIT 1'%(mid))
	res = cur.fetchone()

	if res == None:
		print 'lastblog: [warning] blogs of MID %s not found'%(mid)
		res = False
	else:
		uid, post_time = res
		time_str = datetime.datetime.strftime(post_time, '%Y-%m-%d %H:%M:%S')

		cur.execute('SELECT mid FROM microblogs WHERE user_id = %s and timestamp < "%s" LIMIT %d'%(
				uid, time_str, threshold
			))
		mids = cur.fetchall()
		res = not ((mids is None) or (len(mids) < threshold))

	cur.close()
	
	if con == None:
		conn.close()

	return res
예제 #26
0
파일: lastblog.py 프로젝트: liangxh/idu
def get(mid, con = None):
	import db
	if con == None:
		conn = db.connect()
		cur = conn.cursor()

	cur.execute('SELECT user_id, timestamp FROM microblogs WHERE mid = %s LIMIT 1'%(mid))
	res = cur.fetchone()

	if res == None:
		print 'lastblog: [warning] blogs of MID %s not found'%(mid)
		res = None
	else:
		uid, post_time = res
		time_str = datetime.datetime.strftime(post_time, '%Y-%m-%d %H:%M:%S')

		cur.execute('SELECT mid, timestamp FROM microblogs WHERE user_id = %s and timestamp < "%s" ORDER BY timestamp DESC'%(uid, time_str))
		res = cur.fetchall()

	cur.close()
	
	if con == None:
		conn.close()

	return res
예제 #27
0
파일: card.py 프로젝트: oujiaqi/suiyue
 def add_one_card(pic,fid,main):
     conn=connect()
     cursor=conn.cursor()
     cursor.execute("insert into card(pic,fid,main) values(%s,%s,%s)",[pic,fid,main])
     conn.commit()
     cursor.close()
     conn.close()
예제 #28
0
파일: statica.py 프로젝트: liangxh/emozh
def main():
	con = db.connect()
	cur = con.cursor()
	
	emo_mids = {}

	limit = 25000000
	pbar = progbar.start(limit)
	i = 0

	cur.execute("SELECT mid, text FROM microblogs WHERE comments_count > 0 AND comments_count < 100 LIMIT %d"%(limit))
	for mid, text in cur:
		text, emos = blogger.extract(text)
		
		if len(emos) > 0 and len(emos) < 6:
			samples = blogger.prepare_sample(text, emos)
			for e, t in samples:
				if emo_mids.has_key(e):
					emo_mids[e].append(mid)
				else:
					emo_mids[e] = [mid, ]

		i += 1
		pbar.update(i)

	pbar.finish()

	cPickle.dump(emo_mids, open('../output/emo_mids.pkl', 'w'))
예제 #29
0
파일: ui.py 프로젝트: stuhlmueller/poke
 def update(self):
     conn = db.connect(settings.DATABASE)
     raw_data = db.getdata(conn)
     if raw_data == None:
         logger.info("data is None, skipping ui update...")
         return
     raw_data = list(raw_data)
     conn.close()
     if not raw_data:
         logger.info("no data, skipping ui update...")
         return        
     data = sorted(raw_data, reverse=True)[:settings.WINDOWSIZE]
     i, pairs = data[0]
     logger.info(str((i, pairs)))
     
     self.vars = [var for [var, val] in pairs]
     
     self.data = {}
     for (i, pairs) in data:
         for [var, val] in pairs:
             if var in self.vars:
                 self.data.setdefault(var, [])
                 self.data[var].append(val)
     
     self.hists = {}
     for var in self.vars:
         self.hists[var] = hist(self.data[var])
예제 #30
0
파일: card.py 프로젝트: oujiaqi/suiyue
 def change_pic(cid,pic):
     conn=connect()
     cursor=conn.cursor()
     cursor.execute("update card set pic=%s where cid=%s",[pic,cid])
     conn.commit()
     cursor.close()
     conn.close()
예제 #31
0
def main():
    import db
    source_db = db.connect()

    worker = create_worker(source_db, 256)
    work_queue = _WorkQueue(source_db, 'work_queue2',
                            ['zoom_level', 'tile_row', 'tile_column'], worker)
    work_queue.work()
예제 #32
0
def get_dataset():
    con = connect()
    sql = '''SELECT symbol, date, open, high, low, close, volume FROM time_series_daily WHERE date >= '2018-01-01' ORDER BY date;'''
    # sql = '''SELECT symbol, date, open, high, low, close, volume FROM time_series_daily WHERE date < '2018-01-01' ORDER BY date;'''
    ds = pd.read_sql_query(sql, con)
    con.close()

    return ds
예제 #33
0
def main():
    """Connect to DB"""

    cur, conn = connect()
    print("AWS Redshift connection established OK.")
    load_staging_tables(cur, conn)
    insert_tables(cur, conn)
    conn.close()
예제 #34
0
파일: api.py 프로젝트: Masclins/signepedia
def new_user(newUser):
    cnx = db.connect()
    cursor = cnx.cursor(dictionary=True)
    answer = users.new_user(json.loads(newUser), cursor)
    cursor.close()
    cnx.commit()
    cnx.close()
    return answer
예제 #35
0
def cuisineFinder(id):
    conn = db.connect()
    cursor = conn.cursor()

    result = cursor.execute(
        "SELECT cuisine from restaurants where RID={id}".format(
            id=id)).fetchone()
    return json.dumps(result)
예제 #36
0
def get_area_id_by_name(area_name):
    connection = db.connect(db.config)
    with connection.cursor() as cursor:
        sql = "SELECT id FROM area WHERE name = %s"
        cursor.execute(sql, (area_name, ))
        result = cursor.fetchone()[0]
    db.close(connection)
    return result
예제 #37
0
def weekAnalyze(userid):
    conn = db.connect()
    cursor = conn.cursor()
    sql = "select SUM(f.carbohydrate) as car, SUM(f.protein) as pro, SUM(f.fat) as fat from diet as d JOIN food as f on d.food_id = f.food_id where user_id=%d and d.date between DATE_ADD(NOW(), INTERVAL -1 WEEK) AND NOW();"%(userid)
    cursor.execute(sql)
    result = cursor.fetchall()[0]
    db.close(conn)
    return result['car'], result['pro'], result['fat']
def create_relationships():
    print("Creating relationships...")
    with db.connect() as driver:
        with driver.session() as session:
            tx = session.begin_transaction()
            for query in queries:
                tx.run(query)
            tx.commit()
def getIngredientData():
    conn, cur = connect()

    ingredient_counts = get_total_ingredient_counts(conn)

    disconnect(conn, cur)

    return json.loads((json.dumps(ingredient_counts, indent=2)))
예제 #40
0
def run():
    batch_time = datetime.now().replace(microsecond=0)
    conn = db.connect()
    rows = []
    rows.append(sync_data(conn, "zutrittsberechtigte-nr.json", "Nationalrat", batch_time))
    rows.append(sync_data(conn, "zutrittsberechtigte-sr.json", "Ständerat", batch_time))
    conn.close()
    print_summary(rows, batch_time)
예제 #41
0
파일: transaction.py 프로젝트: hxnyk/xsspay
def get_transactions_for_user(uid):
    with db.connect() as cursor:
        cursor.execute(
            "SELECT * from transactions where sender = %s or receiver = %s",
            (uid, uid))
        return cursor.fetchall()

    return None
예제 #42
0
	def __init__(self, list_pid, app_name = "local", min_support = 0.15 , min_confidence = 0.6, max_iterations = 50):	
			
		self.min_support = min_support
		self.min_confidence = min_confidence
		self.conn = db.connect(app_name)
		self.cursor = self.conn.cursor()
		self.max_iterations = max_iterations
		self.list_pid = list_pid
예제 #43
0
def main():
    '''
    Run some tests.
    '''
    logging.basicConfig(level=logging.INFO)

    db_conn = db.connect('enwiki.labsdb', 'enwiki_p', '~/replica.my.cnf')
    local_db_conn = db.connect('tools.labsdb', 's53463__actrial_p',
                               '~/replica.my.cnf')

    datapoints = gather_historic(local_db_conn, db_conn, dt.date(2016, 4, 14),
                                 dt.date(2016, 4, 15))
    print('got {} data points'.format(len(datapoints)))
    # print(datapoints[0])
    print(datapoints)

    return ()
예제 #44
0
def test_add_match_non_existing_player(players):
    res = slackbot.handle_command(
        "match <@{}> <@XXXXXXXXX> nd 11 0".format(test_user_id), test_user_id)
    conn, cursor = db.connect()
    matches = db.get_matches(cursor)
    conn.close()

    assert res == responses.player_does_not_exist()
    assert len(matches) == 0
예제 #45
0
def players():
    conn, cursor = db.connect()
    p1 = Player(test_user_id, "erlend", 1000)
    p2 = Player(pingpongbot_id, "pingpong", 1000)
    db.create_player(cursor, p1)
    db.create_player(cursor, p2)
    conn.commit()
    conn.close()
    yield p1, p2
예제 #46
0
    def db_connect(self):
        '''
        Connect to the Tool database and the replicated Wikipedia database.
        '''
        try:
            self.wiki_db_conn = db.connect(self.wiki_host, self.wiki_db_name,
                                           self.db_config)
        except:
            raise DatabaseConnectionError

        try:
            self.tool_db_conn = db.connect(self.tool_host, self.tool_db,
                                           self.db_config)
        except:
            raise DatabaseConnectionError

        ## all ok
        return ()
예제 #47
0
def get_school_info(school_id):
    conn = db.connect(settings.DB_HOST, settings.DB_USER, 
        settings.DB_PASSWD, settings.DB_NAME)
    
    # school uf
    school_uf = db.get_school_uf(conn, school_id)
    if school_uf is not None:
        uf_score_avg = db.get_uf_score_avg(conn, school_uf)
    school_city = db.get_school_city(conn, school_id)
    if school_city is not None:
        city_score_avg = db.get_city_score_avg(conn, school_city)
        
    # num students
    total_students = db.get_total_lines(conn, school_id)
    total_absents = db.get_total_absents(conn, school_id)
    
    # avg
    avg_score1, avg_score2, avg_score3, avg_score4, avg_score5, avg_total = db.get_score_avg(conn, school_id)
    
    # sex
    score_avg_sex = db.get_score_avg_sex(conn, school_id)
       
    # score interval
    score_count = [
        db.get_count_per_score_interval(conn, 0, 0, school_id),
        db.get_count_per_score_interval(conn, 1, 99, school_id),
        db.get_count_per_score_interval(conn, 100, 199, school_id),
        db.get_count_per_score_interval(conn, 200, 299, school_id),
        db.get_count_per_score_interval(conn, 300, 399, school_id),
        db.get_count_per_score_interval(conn, 400, 499, school_id),
        db.get_count_per_score_interval(conn, 500, 599, school_id),
        db.get_count_per_score_interval(conn, 600, 699, school_id),
        db.get_count_per_score_interval(conn, 700, 799, school_id),
        db.get_count_per_score_interval(conn, 800, 899, school_id),
        db.get_count_per_score_interval(conn, 900, 999, school_id),
        db.get_count_per_score_interval(conn, 1000, 1000, school_id)
    ]

    db.close_connection(conn)

    score_interval_data = [
        ['notas', 'alunos', { 'role': 'annotation' }],
        ["0", int(score_count[0]), int(score_count[0])],
        ["1-99", int(score_count[1]), int(score_count[1])],
        ["100-199", int(score_count[2]), int(score_count[2])],
        ["200-299", int(score_count[3]), int(score_count[3])],
        ["300-399", int(score_count[4]), int(score_count[4])],
        ["400-499", int(score_count[5]), int(score_count[5])],
        ["500-599", int(score_count[6]), int(score_count[6])],
        ["600-699", int(score_count[7]), int(score_count[7])],
        ["700-799", int(score_count[8]), int(score_count[8])],
        ["800-899", int(score_count[9]), int(score_count[9])],
        ["900-999", int(score_count[10]), int(score_count[10])],
        ["1000", int(score_count[11]), int(score_count[11])]
    ]
    
    return render_template('school_info.html', **locals())
예제 #48
0
    def getScoreboard():
        '''If row with specified id exists, creates and returns corresponding ORM
           instance. Otherwise Exception raised.'''
        
        with db.connect() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT U.username, U.highest_score FROM Users U ORDER BY U.highest_score")

        return [{'username': row['username'], 'highest_score': row['highest_score']} for row in cursor]
예제 #49
0
def del_mes(id_chat, id_message, id_user):
    conn = connect()
    cur = conn.cursor()
    cur.execute('update from "Messages" set "del_mes"= 1 where "id_chat" = ' +
                id_chat.__str__() + ' and "id_message" = ' +
                id_message.__str__() + ' and "id_user" = ' + id_user.__str__())
    conn.commit()
    conn.close()
    return
예제 #50
0
def main():
    with open('items.csv', 'r', newline='') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        with db.connect() as conn:
            with conn.cursor() as cur:
                for row in csv_reader:
                    cur.execute(
                        'INSERT INTO items (wiki_link, canonical_name) VALUES (%s, %s)',
                        (row['wiki_link'], row['name']))
예제 #51
0
파일: api.py 프로젝트: Masclins/signepedia
def search_word_user(word, userId):
    cnx = db.connect()
    cursor = cnx.cursor(dictionary=True)
    register.searches(word, cursor)
    resp = jsonify(main.get_result_user(word, userId, cursor))
    cursor.close()
    cnx.commit()
    cnx.close()
    return resp
예제 #52
0
def get_user_id(username):
    with db.connect() as cursor:
        cursor.execute("SELECT id from users where username = %s",
                       (username.lower(), ))
        result = cursor.fetchone()

        return result["id"] if result else None

    return None
예제 #53
0
def test(verbose):
    """Test database connectivity."""
    utils.configureLogging(verbose)
    config = utils.loadConfig()
    logging.debug(f"Testing DB connection...")
    db_conn = db.connect(config["DB_HOST"], config["DB_NAME"],
                         config["DB_USER"], config["DB_PASS"])
    logging.info(db.show_version(db_conn))
    db.close(db_conn)
예제 #54
0
    def connect(self):
        '''Connect to the appropriate Wikipedia and user databases.'''
        try:
            self.wiki_db_conn = db.connect(self.wiki_host,
                                           self.wiki_db_name,
                                           self.db_config)
        except:
            raise DatabaseConnectionError

        try:
            self.tool_db_conn = db.connect(self.tool_host,
                                           self.tool_db,
                                           self.db_config)
        except:
            raise DatabaseConnectionError

        ## all ok
        return()
예제 #55
0
def post_later(endpoint, payload):
    """
    Store the POST data in the database for sending later.
    """
    sql = db.connect()
    posts = sql['posts']
    postId = posts.insert(dict(endpoint=endpoint, payload=json.dumps(payload)))
    l.warning("Failed to send %s to photostreamer-server endpoint %s. Saved for resend as ID %d.",
        payload, endpoint, postId)
예제 #56
0
def getprogrambyid(id):
    dbase = db.connect()
    cursor = dbase.cursor()
    cursor.execute("SELECT * FROM coursedetails WHERE id = %d" % (id))
    data = cursor.fetchone()
    coursename = data[1]
    cursor.close()
    dbase.close()
    return coursename
예제 #57
0
def _():
    (vodlist, paginationlist) = WebSession().get(plugin.path, VodShowParser())
    db.connect()
    items = []

    for path, rating in vodlist:
        poster, label, info = db.fetchone_vod(path)
        item = ListItem(label, poster=poster, info=info, rating=rating)
        items.append((plugin.url_for(path), item, True))

    for path, title in paginationlist:
        item = ListItem(title, properties={'SpecialSort': 'bottom'})
        items.append((plugin.url_for(path), item, True))

    db.close()
    xbmcplugin.setContent(plugin.handle, 'tvshows')
    xbmcplugin.addDirectoryItems(plugin.handle, items, len(items))
    xbmcplugin.endOfDirectory(plugin.handle)
예제 #58
0
def register(regno, fname, lname, courseid, year):
    dbase = db.connect()
    cursor = dbase.cursor()
    cursor.execute(
        "INSERT INTO students (regnumber, firstname, surname, courseid, year) values ('%s', '%s', '%s', %d, %d)"
        % (regno, fname, lname, courseid, year))
    dbase.commit()
    cursor.close()
    dbase.close()
def run():
    global db
    db = connect(host=args.mongo_host, port=args.mongo_port)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(login_accounts(accounts, args.cookie_dir))
    loop.run_until_complete(login_guests())
    app = web.Application()
    app.add_routes(routes)
    web.run_app(app, host=args.host, port=args.port)
예제 #60
0
 def updateScore(username, data):
     score = data['score']
     '''Writes back instance values into database'''
     with db.connect() as conn:
         cursor = conn.cursor()
         cursor.execute("UPDATE Users SET highest_score = ? WHERE username = ? AND highest_score>?",
                            (score, username, score))
         conn.commit()
     return