Пример #1
0
    def _connect_to_db(self):
        # connect to db at class init and use it globally
        if DB == "mysql":

            class MySQLCursorDict(database.cursor.MySQLCursor):
                def _row_to_python(self, rowdata, desc=None):
                    row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
                    if row:
                        return dict(zip(self.column_names, row))
                    return None

            self.dbcon = database.connect(
                database=common.db_name,
                user=common.db_user,
                password=common.db_pass,
                host=common.db_address,
                buffered=True,
                charset="utf8",
            )
            self.dbcur = self.dbcon.cursor(cursor_class=MySQLCursorDict, buffered=True)
        else:
            self.dbcon = database.connect(self.db)
            self.dbcon.row_factory = (
                database.Row
            )  # return results indexed by field names and not numbers so we can convert to dict
            self.dbcon.text_factory = str
            self.dbcur = self.dbcon.cursor()
Пример #2
0
 def onPlayBackStarted(self):
     xbmc.log("1Channel: Service: Playback started")
     self.tracking = self.check()
     if self.tracking:
         xbmc.log("1Channel: Service: tracking progress...")
         win = xbmcgui.Window(10000)
         self.title = win.getProperty("1ch.playing.title")
         self.imdb = win.getProperty("1ch.playing.imdb")
         self.season = win.getProperty("1ch.playing.season")
         self.year = win.getProperty("1ch.playing.year")
         self.episode = win.getProperty("1ch.playing.episode")
         if self.season or self.episode:
             self.video_type = "tvshow"
         else:
             self.video_type = "movie"
         self._totalTime = self.getTotalTime()
         sql = "SELECT bookmark FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?"
         if DB == "mysql":
             sql = sql.replace("?", "%s")
             db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
         else:
             db = database.connect(db_dir)
         cur = db.cursor()
         cur.execute(sql, (self.video_type, self.title, self.season, self.episode, self.year))
         bookmark = cur.fetchone()
         db.close()
         if bookmark:
             bookmark = float(bookmark[0])
             if not (self._sought and (bookmark - 30 > 0)):
                 question = "Resume %s from %s?" % (self.title, format_time(bookmark))
                 resume = xbmcgui.Dialog()
                 resume = resume.yesno(self.title, "", question, "", "Start from beginning", "Resume")
                 if resume:
                     self.seekTime(bookmark)
                 self._sought = True
Пример #3
0
def mysql(u,username='******',password=''):
 try:
  mconn.connect(host=u,user=username, password=password)
  return True
 except Exception as e:
  pass
 return False
Пример #4
0
def ListAlbum(url):
    sql = 'SELECT distinct artist_url,album,img FROM songs where artist_url=? order by album'

    if DB == 'mysql':
        db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
        sql = sql.replace('?','%s')
    else: db = database.connect( db_dir )
    cur = db.cursor()

    cur.execute(sql, (url,))
    favs = cur.fetchall()
    artist=""
    totalalbum = 0
    addLink("Refresh Album Database",url,9,"")
    for row in favs:
        totalalbum=totalalbum+1
        arturl = row[0]
        album   = row[1]
        albumimg   = row[2]
        addDir(album,arturl,7,albumimg)
    db.close()
    if(totalalbum==0):
        (SongList,xmlpath)=GetSongs(url)
        for albid,auth,alimg,alname,tracks in SongList:
                addDir(TAG_RE.sub('', alname),url,7,xmlpath+alimg)
Пример #5
0
 def onPlayBackStarted(self):
     xbmc.log('1Channel: Service: Playback started')
     self.tracking = self.check()
     if self.tracking:
         xbmc.log('1Channel: Service: tracking progress...')
         win = xbmcgui.Window(10000)
         self.title = win.getProperty('1ch.playing.title')
         self.imdb = win.getProperty('1ch.playing.imdb')
         self.season = win.getProperty('1ch.playing.season')
         self.year = win.getProperty('1ch.playing.year')
         self.episode = win.getProperty('1ch.playing.episode')
         if self.season or self.episode:
             self.video_type = 'tvshow'
         else:
             self.video_type = 'movie'
         self._totalTime = self.getTotalTime()
         sql = 'SELECT bookmark FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?'
         if DB == 'mysql':
             sql = sql.replace('?', '%s')
             db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
         else:
             db = database.connect(db_dir)
         cur = db.cursor()
         cur.execute(sql, (self.video_type, self.title, self.season, self.episode, self.year))
         bookmark = cur.fetchone()
         db.close()
         if bookmark:
             bookmark = float(bookmark[0])
             if not (self._sought and (bookmark - 30 > 0)):
                 question = 'Resume %s from %s?' % (self.title, format_time(bookmark))
                 resume = xbmcgui.Dialog()
                 resume = resume.yesno(self.title, '', question, '', 'Start from beginning', 'Resume')
                 if resume: self.seekTime(bookmark)
                 self._sought = True
Пример #6
0
def ListArtist(url,arttype):
    sql = 'SELECT * FROM artist where art_type =? ORDER BY name'

    if DB == 'mysql':
        db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
        sql = sql.replace('?','%s')
    else: db = database.connect( db_dir )
    cur = db.cursor()

    cur.execute(sql, (arttype,))
    favs = cur.fetchall()
    artist=""
    totalartist = 0
    addLink("Refresh Artist Database",url+"|"+arttype,8,"")
    for row in favs:
        totalartist=totalartist+1
        artistname = row[0]

        artisturl   = row[1].replace(" ","%20")

        artistimg   = row[2]

        addDir(artistname,artisturl,6,artistimg)


    db.close()
    if(totalartist==0):
        artistlist=GetArtist(url,arttype)
        for vurl,vimg,aname in artistlist:
                        cursql=""
                        addDir(TAG_RE.sub('', aname),vurl,6,vimg)
Пример #7
0
    def __init__(self, db_host='localhost', db_user='', db_user_passwd='', db_name='', charset = '', debug = 0, db_port=3306, curstype='TUPLE'):
        """
            初始化数据库连接
            @param db_host: 地址
            @param db_user: 用户名
            @param db_user_passwd: 密码
            @param db_name: 数据库名称
            @param charset: 字符集
            @param debug: 调试模式
            @param db_port: 端口号
        """
        try:
            if isinstance(db_host, unicode):db_host = db_host.encode('utf8')
            if isinstance(db_user, unicode):db_user = db_user.encode('utf8')
            if isinstance(db_user_passwd, unicode):db_user_passwd = db_user_passwd.encode('utf8')
            if isinstance(db_name, unicode):db_name = db_name.encode('utf8')
            if isinstance(charset, unicode):charset= charset.encode('utf8')
            if isinstance(db_port, unicode):db_port= db_port.encode('utf8')
            if isinstance(db_port, str):db_port= int(db_port)

            if charset != '':
                self.mdb = dblib.connect(host=db_host, port=db_port, user=db_user, passwd=db_user_passwd, db=db_name, charset=charset, use_unicode = False ) #, charset='utf8'
                self.charset = charset
            else:
                self.mdb = dblib.connect(db_host, db_user, db_user_passwd, db_name, db_port )
            self.debug = debug
            #print "character_set_name:",self.mdb.character_set_name()
        except dblib.Error, error:
            print "Connect MySql[%s %s/%s %s] DB Error:"%(db_host,db_user,db_user_passwd,db_name),error,"\n"
Пример #8
0
 def __init__(self, addon_id, sys_argv=''):
     
     #Check if a path has been set in the addon settings
     if common.db_path:
         self.path = xbmc.translatePath(common.db_path)
     else:
         self.path = xbmc.translatePath(common.default_path)
     
     self.addon_id = addon_id
     self.sys_argv = sys_argv
     self.cache_path = common.make_dir(self.path, '')
     self.addon = Addon(self.addon_id, self.sys_argv)
     
     self.db = os.path.join(self.cache_path, self.local_db_name)
     
     # connect to db at class init and use it globally
     if DB == 'mysql':
         class MySQLCursorDict(database.cursor.MySQLCursor):
             def _row_to_python(self, rowdata, desc=None):
                 row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
                 if row:
                     return dict(zip(self.column_names, row))
                 return None
         self.dbcon = database.connect(common.db_name, common.db_user, common.db_pass, common.db_address, buffered=True, charset='utf8')
         self.dbcur = self.dbcon.cursor(cursor_class=MySQLCursorDict, buffered=True)
     else:
         self.dbcon = database.connect(self.db)
         self.dbcon.row_factory = database.Row # return results indexed by field names and not numbers so we can convert to dict
         self.dbcon.text_factory = str
         self.dbcur = self.dbcon.cursor()
             
     self._create_favorites_tables()
Пример #9
0
def connect_db():
    if DB == 'mysql':
        db = orm.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_ADDR, buffered=True)
    else:
        db = orm.connect(DB_DIR)
        db.text_factory = str
    return db
Пример #10
0
 def __connect_to_db(self):
     if not self.db:
         if self.db_type == DB_TYPES.MYSQL:
             self.db = db_lib.connect(database=self.dbname, user=self.username, password=self.password, host=self.address, buffered=True)
         else:
             self.db = db_lib.connect(self.db_path)
             self.db.text_factory = str
Пример #11
0
 def __init__(self):
     
     #Check if a path has been set in the addon settings
     db_path = common.addon.get_setting('local_db_location')
     if db_path:
         self.path = xbmc.translatePath(db_path)
     else:
         self.path = xbmc.translatePath('special://profile/addon_data/script.icechannel/databases')
     
     self.path = common.make_dir(self.path, '')
     
     self.db = os.path.join(self.path, self.local_db_name)
     
     # connect to db at class init and use it globally
     if DB == 'mysql':
         class MySQLCursorDict(database.cursor.MySQLCursor):
             def _row_to_python(self, rowdata, desc=None):
                 row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
                 if row:
                     return dict(zip(self.column_names, row))
                 return None
         self.dbcon = database.connect(database=common.addon.get_setting('db_name'), user=common.addon.get_setting('db_user'), 
             password=common.addon.get_setting('db_pass'), host=common.addon.get_setting('db_address'), buffered=True, charset='utf8')                
         self.dbcur = self.dbcon.cursor(cursor_class=MySQLCursorDict, buffered=True)
     else:
         self.dbcon = database.connect(self.db)
         self.dbcon.row_factory = database.Row # return results indexed by field names and not numbers so we can convert to dict
         self.dbcon.text_factory = str
         self.dbcur = self.dbcon.cursor()
             
     self._create_subscription_tables()
Пример #12
0
def ListSongs(artist_url,album):

    sql = 'SELECT artist_url,album, img, name,url FROM songs where artist_url=? and album =? ORDER BY name'

    if DB == 'mysql':
        db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
        sql = sql.replace('?','%s')
    else: db = database.connect( db_dir )
    cur = db.cursor()

    cur.execute(sql, (artist_url,album))
    favs = cur.fetchall()
    artist=""
    totalsong = 0
    xbmc.PlayList(0).clear()
    addLink("Play All",artist_url,10,"")
    for row in favs:
        totalsong=totalsong+1
        arturl = row[0]
        album=row[1]
        songImg=row[2]
        songname   = row[3]
        songurl   = row[4].replace(" ","%20")
        addPlaylist(songname,songurl,songImg,"")
        songitem(songname,songurl,songImg,album,artist, totalsong)


    db.close()
Пример #13
0
def initDatabase():

    print 'Building Khmermusic Database'

    if DB == 'mysql':

        db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)

        cur = db.cursor()

        cur.execute('CREATE TABLE IF NOT EXISTS artist ( name TEXT,artist_url VARCHAR(255) UNIQUE,img VARCHAR(255) ,art_type VARCHAR(255),PRIMARY KEY (url))')

        cur.execute('CREATE TABLE IF NOT EXISTS songs (artist_url VARCHAR(255), album TEXT,img VARCHAR(255) ,name TEXT, url VARCHAR(255) UNIQUE,PRIMARY KEY (url))')

        cur.execute('CREATE TABLE IF NOT EXISTS playlist (playlist_id,url VARCHAR(255), name UNIQUE)')



    else:

        if not os.path.isdir(os.path.dirname(db_dir)):

            os.makedirs(os.path.dirname(db_dir))

        db = database.connect(db_dir)

        db.execute('CREATE TABLE IF NOT EXISTS artist (name,artist_url PRIMARY KEY,img, art_type)')

        db.execute('CREATE TABLE IF NOT EXISTS songs ( artist_url, album TEXT,img,name, url PRIMARY KEY)')

        db.execute('CREATE TABLE IF NOT EXISTS playlist (playlist_id INTEGER PRIMARY KEY AUTOINCREMENT,song_id,url, name)')

    db.commit()

    db.close()
Пример #14
0
    def onPlayBackStopped(self):
        xbmc.log('1Channel: Playback Stopped')
        if self.tracking:
            playedTime = int(self._lastPos)
            watched_values = [.7, .8, .9]
            min_watched_percent = watched_values[int(ADDON.getSetting('watched-percent'))]
            percent = int((playedTime / self._totalTime) * 100)
            pTime = format_time(playedTime)
            tTime = format_time(self._totalTime)
            xbmc.log('1Channel: Service: %s played of %s total = %s%%' % (pTime, tTime, percent))
            if playedTime == 0 and self._totalTime == 999999:
                raise RuntimeError('XBMC silently failed to start playback')
            elif ((playedTime / self._totalTime) > min_watched_percent) and (
                        self.video_type == 'movie' or (self.season and self.episode)):
                xbmc.log('1Channel: Service: Threshold met. Marking item as watched')
                if self.video_type == 'movie':
                    videotype = 'movie'
                else:
                    videotype = 'episode'
                ChangeWatched(self.imdb, videotype, self.title, self.season, self.episode, self.year, watched=7)

                if self.librarymode:
                    dbidnum = xbmc.getInfoLabel('ListItem.DBID')
                    if dbidnum != 0:
                        if self.video_type == 'movie':
                            jsonquery = '{"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {"movieid" : %s, "playcount" : 1 }, "id": 1 }'
                        else:
                            jsonquery = '{"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid" : %s, "playcount" : 1 }, "id": 1 }'

                        jsonquery = jsonquery % dbidnum

                        xbmc.log('1Channel: Service: Updating Library. Json query is %s' % jsonquery)
                        xbmc.executeJSONRPC(jsonquery)

                sql = 'DELETE FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?'
                if DB == 'mysql':
                    sql = sql.replace('?', '%s')
                    db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
                else:
                    db = database.connect(db_dir)
                cur = db.cursor()
                cur.execute(sql, (self.video_type, unicode(self.title, 'utf-8'), self.season, self.episode, self.year))
                db.commit()
                db.close()
            else:
                xbmc.log('1Channel: Service: Threshold not met. Saving bookmark')
                sql = 'REPLACE INTO bookmarks (video_type, title, season, episode, year, bookmark) VALUES(?,?,?,?,?,?)'
                if DB == 'mysql':
                    sql = sql.replace('?', '%s')
                    db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
                else:
                    sql = 'INSERT or ' + sql
                    db = database.connect(db_dir)
                cur = db.cursor()
                cur.execute(sql, (self.video_type, unicode(self.title, 'utf-8'), self.season,
                                  self.episode, self.year, playedTime))
                db.commit()
                db.close()
        self.reset()
 def __init__(self):
     try:
         self.dbConnection = mysql.connect(host='localhost',user='******',db='dewi_experiments',buffered=True)
     except mysql.Error, e:
         self.dbConnection = mysql.connect(host='localhost',user='******',buffered=True)
         cursor = self.dbConnection.cursor()
         cursor.execute("CREATE DATABASE dewi_experiments DEFAULT CHARACTER SET 'utf8'")     
         self.dbConnection.database = 'dewi_experiments'
Пример #16
0
def SaveData(SQLStatement): #8888
    if DB == 'mysql':
        db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
    else:
        db = database.connect( db_dir )
    cursor = db.cursor()
    cursor.execute(SQLStatement)
    db.commit()
    db.close()
Пример #17
0
def initDatabase():
    if DB == 'mysql':
        db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
        cur = db.cursor()
        cur.execute('CREATE TABLE IF NOT EXISTS favorites (type VARCHAR(10), name TEXT, url VARCHAR(255) UNIQUE, imgurl VARCHAR(255))')
    else:
        if not os.path.isdir(os.path.dirname(db_dir)):
            os.makedirs(os.path.dirname(db_dir))
        db = database.connect(db_dir)
        db.execute('CREATE TABLE IF NOT EXISTS favorites (type, name, url, imgurl)')
    db.commit()
    db.close()
Пример #18
0
def upgrade_db():
    _1CH.log('Upgrading db...')
    for table in ('subscriptions', 'favorites'):
        sql = "UPDATE %s SET url = replace(url, 'http://www.1channel.ch', '')" % table
        if DB == 'mysql':
            db = orm.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDR, buffered=True)
        else:
            db = orm.connect(DB_DIR)
        cur = db.cursor()
        cur.execute(sql)
        db.commit()
        db.close()
    def _insert_metadata(self, table):
        '''
        Batch insert records into existing cache DB

        Used to add extra meta packs to existing DB
        Duplicate key errors are ignored
        
        Args:
            table (str): table name to select from/insert into
        '''

        common.addon.log('Inserting records into table: %s' % table, 0)
        # try:
        if DB == 'mysql':
            try: 	from sqlite3  import dbapi2 as sqlite
            except: from pysqlite2 import dbapi2 as sqlite

            db_address = common.addon.get_setting('db_address')
            db_port = common.addon.get_setting('db_port')
            if db_port: db_address = '%s:%s' %(db_address,db_port)
            db_user = common.addon.get_setting('db_user')
            db_pass = common.addon.get_setting('db_pass')
            db_name = common.addon.get_setting('db_name')

            db = database.connect(db_name, db_user, db_pass, db_address, buffered=True)
            mysql_cur = db.cursor()
            work_db = sqlite.connect(self.work_videocache);
            rows = work_db.execute('SELECT * FROM %s' %table).fetchall()

            cur = work_db.cursor()
            rows = cur.execute('SELECT * FROM %s' %table).fetchall()
            if rows:
                cols = ','.join([c[0] for c in cur.description])
                num_args = len(rows[0])
                args = ','.join(['%s']*num_args)
                sql_insert = 'INSERT IGNORE INTO %s (%s) VALUES(%s)'%(table, cols, args)
                mysql_cur.executemany(sql_insert, rows)
            work_db.close()

        else:
            sql_insert = 'INSERT OR IGNORE INTO %s SELECT * FROM work_db.%s' % (table, table)        
            common.addon.log('SQL Insert: %s' % sql_insert, 0)
            common.addon.log(self.work_videocache, 0)
            db = database.connect(self.videocache)
            db.execute('ATTACH DATABASE "%s" as work_db' % self.work_videocache)
            db.execute(sql_insert)
        # except Exception, e:
            # common.addon.log('************* Error attempting to insert into table: %s with error: %s' % (table, e), 4)
            # pass
            # return False
        db.commit()
        db.close()
        return True
Пример #20
0
def DeleteFav(name,url): 
    builtin = 'XBMC.Notification(Remove Favorite,Removed '+name+' from Favorites,2000)'
    xbmc.executebuiltin(builtin)
    sql_del = 'DELETE FROM favorites WHERE name=%s AND url=%s'
    if DB == 'mysql':
            db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
    else:
            db = database.connect( db_dir )
            db.text_factory = str
            sql_del = sql_del.replace('%s','?')
    cursor = db.cursor()
    cursor.execute(sql_del, (name, url))
    db.commit()
    db.close()
Пример #21
0
 def onPlayBackStopped(self):
     try: xbmc.log('PrimeWire: Playback Stopped')
     except: pass
     if self.tracking:
         playedTime = int(self._lastPos)
         watched_values = [.7, .8, .9]
         min_watched_percent = watched_values[int(ADDON.getSetting('watched-percent'))]
         percent = int((playedTime / self._totalTime) * 100)
         pTime = format_time(playedTime)
         tTime = format_time(self._totalTime)
         try: xbmc.log('PrimeWire: Service: %s played of %s total = %s%%' % (pTime, tTime, percent))
         except: pass
         if playedTime == 0 and self._totalTime == 999999:
             raise RuntimeError('XBMC silently failed to start playback')
         elif ((playedTime / self._totalTime) > min_watched_percent) and (
                     self.video_type == 'movie' or (self.season and self.episode)):
             try: xbmc.log('PrimeWire: Service: Threshold met. Marking item as watched')
             except: pass
             if self.video_type == 'movie':
                 videotype = 'movie'
             else:
                 videotype = 'episode'
             ChangeWatched(self.imdb, videotype, self.title, self.season, self.episode, self.year, watched=7)
             sql = 'DELETE FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?'
             if DB == 'mysql':
                 sql = sql.replace('?', '%s')
                 db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
             else:
                 db = database.connect(db_dir)
             cur = db.cursor()
             cur.execute(sql, (self.video_type, unicode(self.title, 'utf-8'), self.season, self.episode, self.year))
             db.commit()
             db.close()
         else:
             try: xbmc.log('PrimeWire: Service: Threshold not met. Saving bookmark')
             except: pass
             sql = 'REPLACE INTO bookmarks (video_type, title, season, episode, year, bookmark) VALUES(?,?,?,?,?,?)'
             if DB == 'mysql':
                 sql = sql.replace('?', '%s')
                 db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
             else:
                 sql = 'INSERT or ' + sql
                 db = database.connect(db_dir)
             cur = db.cursor()
             cur.execute(sql, (self.video_type, unicode(self.title, 'utf-8'), self.season,
                               self.episode, self.year, playedTime))
             db.commit()
             db.close()
     self.reset()
Пример #22
0
    def test_connect(self):
        """Interface exports the connect()-function"""
        self.assertTrue(inspect.isfunction(myconn.connect),
                        "Module does not export the connect()-function")
        cnx = myconn.connect(use_pure=True, **tests.get_mysql_config())
        self.assertTrue(isinstance(cnx, myconn.connection.MySQLConnection),
                        "connect() not returning by default pure "
                        "MySQLConnection object")

        if tests.MYSQL_CAPI:
            # By default use_pure=False
            cnx = myconn.connect(**tests.get_mysql_config())
            self.assertTrue(isinstance(cnx,
                                       myconn.connection_cext.CMySQLConnection),
                            "The connect()-method returns incorrect instance")
Пример #23
0
    def conn(self):
        """
This is a cross between other connection properties I've seen
and my own experimentation for dealing with an annoyingly
intermittent connection.

I guess it'd be nice if it could wait a while and try again in
the event of a missing connection, but I suppose it just waits
60 seconds and then crashes.
        """
        try:
            if self._db is None:
                self._db = sqlc.connect(user=self.login,
                                        password=self.passwd,
                                        host=self.host,
                                        database=self.database)

        except sqlc.Error as e:
            print ("MySQL exception #{0} getting connection: {1}".format(e.errno, e.msg))
            if e.errno == 2003:
                exit(-1)
        except Exception as e:
            print ("Couldn't get connection property: {0}".format(e.message))
        finally:
            return self._db
Пример #24
0
def SaveData(SQLStatement): #8888
    if DB == 'mysql':
        db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
    else:
        db = database.connect( db_dir )
    cursor = db.cursor()
    #try: 
        
    #    builtin = 'XBMC.Notification(Save Favorite,Added to Favorites,2000)'
    #    xbmc.executebuiltin(builtin)
    #except database.IntegrityError: 
    #    builtin = 'XBMC.Notification(Save Favorite,Item already in Favorites,2000)'
    #    xbmc.executebuiltin(builtin)
    cursor.execute(SQLStatement)
    db.commit()
    db.close()
Пример #25
0
def conv_db_htmin2daily(db_table, inst_file, out_table = 'hist_fut_daily', database = 'hist_data'):
    conf_dict = {}
    instIDs = []
    if inst_file == '':
        instIDs =  get_col_dist_values(database + '.' + db_table, 'instID',{})
        conf_dict = {'instIDs': instIDs}
        try:
            inst_file = 'instID_file.json'
            with open(inst_file, 'w') as ofile:
                json.dump(conf_dict, ofile)
        except:
            pass
    else:
        with open(inst_file, 'r') as infile:
            conf_dict = json.load(infile)
        instIDs = conf_dict['instIDs']
    dbconfig = {'user': '******', 'password':'******', 'host':'localhost', 'database': database}
    cnx = mysqlconn.connect(**dbconfig)
    for inst in instIDs:
        mdf = load_hist_min(db_table, inst)
        if len(mdf) == 0:
            continue
        ddf = conv_min2daily(mdf)
        ddf.to_sql(name = out_table, flavor = 'mysql', con = cnx, if_exists='append')
        cnx.commit()
        print inst, len(ddf)
    cnx.close()
    return
Пример #26
0
def copia_tablas():
    exporta = ['not_clasif', 'noticias', 'not_relacion', 'not_nombres_relaciones', \
               'not_importancia_noticias', 'not_importancia_ners', 'not_imagenes', 'ners'];
    try:
        con = my.connect(**con_data)
    except my.Error as err:
        print(format(err))
    cur = con.cursor()
    for tabla in exporta:
        copia = "/var/www/noticias"+DIR_LOCAL+tabla+".sql"
        if os.path.exists(copia):
            try:
                os.remove(copia)
            except OSError as err:
                print(format(err))
                sys.exit()
    
        q = "SELECT * INTO OUTFILE '%s' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' \
            LINES TERMINATED BY '\n' FROM %s" % (copia, tabla)
        try:
            cur.execute(q)
        except my.Error as err:
            print(format(err))
            sys.exit()
        print("%s copiada con exito a %s" % (tabla, copia))
Пример #27
0
 def get_conexao(self):
     _host = 'localhost'
     _name = 'namedatabase'
     _user = '******'
     _passwd = 'passwd'
     db = msc.connect(host=_host, database=_name, user=_user, passwd=_passwd)
     return db
Пример #28
0
def main():
   # Connect to the DB
   # host='24.205.232.5'
   conn = mysql.connect(
      host='127.0.0.1',
      user='******',
      passwd='tweetlection12',
      db='tweetlection'
   )

   cursor = conn.cursor()

   tweets = None;
   # Pull the first 100 tweets
   try:
      cursor.execute(
         "SELECT text, retweet_count FROM tweets "
         "WHERE retweet_count > 1000 "
         "GROUP BY text "
         "HAVING max(retweet_count) "
         "ORDER BY retweet_count")
      tweets = cursor.fetchall()
      for tweet in tweets:
         print tweet
   except Exception, e:
      raise e
Пример #29
0
def load_hist_min(db_table, instID):
    dbconfig = {'user': '******', 'password':'******', 'host':'localhost', 'database': 'hist_data'}
    stmt = "select instID, exch, datetime, date, min_id, open, high, low, close, volume, openInterest from {dbtable} where instID='{inst}' ".format(dbtable=db_table, inst=instID)
    stmt += "order by date, min_id;"
    cnx = mysqlconn.connect(**dbconfig)
    df = pd.io.sql.read_sql(stmt, cnx, index_col = 'datetime')
    return df
Пример #30
0
    def sql_read(self):
        sql_file_picked = []
        sql_file_picked.append(AggregateFunctionsAndGroupBy.sql_files_list[int(self.picked_menu_number) - 1])
        sql_file = []

        for picked_file in sql_file_picked:
            file = open(
                "c:/Pycharm_Projects/week_8a_sql/queries/queries_02_aggregate_functions_and_group_by/" + picked_file,
                "r",
            )
            sql_file.append(file.read())
            file.close()
        connect = mysql_connector.connect(
            user="******",
            password="******",
            host="127.0.0.1",
            charset="utf8",
            use_unicode=True,
            autocommit=True,
        )
        cursor = connect.cursor()

        for one_command in sql_file:
            for one_data in cursor.execute(one_command, multi=True):
                for cursor_message in cursor:
                    print(cursor_message)
            connect.close()
Пример #31
0
from xml.etree import ElementTree as ET
from mysql.connector import connect
from mysql.connector.errors import IntegrityError
import re
import time
import sys
import os

dir = '/home/andre/Desktop/Sistema/NFe'  # Diretório para testes

pretag = '{http://www.portalfiscal.inf.br/nfe}'

mydb = connect(host='localhost', user='******', passwd='', database='rodabras')


def ext_emitente(arq):
    dict = {}
    emit = arq.find(pretag + 'NFe').find(pretag + 'infNFe').find(pretag +
                                                                 'emit')
    ender_emit = emit.find(pretag + 'enderEmit')
    cnpj_cpf = emit.find(pretag + 'CNPJ')
    if cnpj_cpf is not None:
        dict['cnpj_cpf'] = cnpj_cpf
    else:
        dict['cnpj_cpf'] = emit.find(pretag + 'CPF')
    dict['nome'] = emit.find(pretag + 'xNome')
    dict['fantasia'] = emit.find(pretag + 'xFant')
    dict['logradouro'] = ender_emit.find(pretag + 'xLgr')
    dict['numero'] = ender_emit.find(pretag + 'nro')
    dict['complemento'] = ender_emit.find(pretag + 'xCpl')
    dict['bairro'] = ender_emit.find(pretag + 'xBairro')
Пример #32
0
from jinja2 import Markup
import mysql.connector as sql

# infoDict['js']= Markup(js)

ENV_FILE = find_dotenv()
if ENV_FILE:
    load_dotenv(ENV_FILE)

app = Flask(__name__)
app.debug = True
app.secret_key = "super secret key"

#  Here i am making a connection with mysql database hosted by the xampp server!
db = sql.connect(host="localhost",
                 user="******",
                 password="",
                 database="project_wang_reda")
#  Then i am making a cursor to execute sql commands in the following below functions and decorators
cursor = db.cursor()


@app.errorhandler(Exception)
def handle_auth_error(ex):
    response = jsonify(message=str(ex))
    response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)
    return response


oauth = OAuth(app)

auth0 = oauth.register(
Пример #33
0
import mysql.connector  as con
import json
import csv


mydb = con.connect(
  host="localhost",
  user="******",
  passwd="MYSQL123",
  db="demo"
)
cur=mydb.cursor()

cur.execute("select * from json_to_db ")

res=cur.fetchall()
for x in res:
    print(x)
print(res)
li=[]
for x,y in res:
    li.append(x)
print(li)
d0={}
for word in li:
    if word not in d0:
        d0[word]=1
    else:
        d0[word]+=1
print(d0)
li2=list(d0.keys())
Пример #34
0
def update_null():
    try:
        with connect(host=HOST,
                     user=DB_USER,
                     password=DB_PASS,
                     database=DB_NAME,
                     autocommit=True) as connection:
            with connection.cursor(buffered=True) as cursor:
                #fetch tables from database
                cursor.execute("SHOW TABLES")
                for table in cursor:
                    print(table)

                #manually select table from options
                create_query = "SELECT * FROM {}"
                selected_table = input("Which table? ")
                cursor.execute(create_query.format(selected_table))

                #fetch columns from table and create a list
                describe_query = "DESCRIBE {}"
                cursor.execute(describe_query.format(selected_table))
                meta = cursor.fetchall()
                column_names = []
                for row in meta:
                    column_names.append(row[0])

                #check for empty cell and insert value
                def update():
                    cursor.execute(create_query.format(selected_table))
                    update_query_total = ""
                    for row in cursor:
                        row_id = row[0]
                        for cell, column in zip(list(row), column_names):
                            if cell != None and cell != "":
                                pass
                            else:
                                #skip if no value is entered
                                value = input("Input %s for %s: " %
                                              (column, row_id))
                                if value == "":
                                    continue

                                update_query = """
                                    UPDATE 
                                        {}
                                    SET
                                        {}="{}"
                                    WHERE
                                        {}={};
                                    """.format(
                                    selected_table,  #table that needs update
                                    column,  #column that needs update
                                    value,  #new value
                                    column_names[0],  #where id_column
                                    row_id,  #row_id
                                )
                                update_query_total = update_query_total + update_query
                                print(update_query_total)
                    return (update_query_total)

                cursor.execute(update())
    except Error as e:
        print("error: ", e)
Пример #35
0
import mysql.connector as mysql
from mysql.connector import Error
import config.db as db
import dbconnect as sql
import datos_fbgotw as medios
import datos_mediamath as mm
import datos_adform as adf
import datos_mediosextras as mediosextras
import datos_adsmovil as am
import sys

if __name__ == '__main__':

    # Iniciamos la conexion
    conn = mysql.connect(host='3.95.117.169',
                         database='MediaPlatformsReports',
                         user='******',
                         password='******',
                         autocommit=True)
    try:
        dfni = mediosextras.Spreadsheet(db.PHD_Medios_Externos['key'],
                                        db.PHD_Medios_Externos['DATA'])
        mediosextras.campanas(dfni, conn)
        mediosextras.metricas_campanas(dfni, conn, 'PHD')
        # mediosextras.diario_campanas(dfni, conn)

    except Exception as e:
        print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno),
              type(e).__name__, e)
Пример #36
0
 def _opendb(self):
     self.conn = connector.connect(**self.dbdesc['kwargs'])
Пример #37
0
import mysql.connector as mariadb

mariadb_connection = mariadb.connect(user='******', password='******', database='mysql')
cursor = mariadb_connection.cursor()
Пример #38
0

# Requires the Flask and MySQL libraries
# To use this app:
#   pip install mysql-connector-python

from flask import Flask, request
from datetime import *
import time
from mysql.connector import connect
import dbconfig
from details import *

app = Flask(__name__)

con = connect(user=dbconfig.DB_USER, password=dbconfig.DB_PASS, database='wsoapp2', host=dbconfig.DB_HOST) 
cursor = con.cursor()

error_msg = ["New service was successfully created!", "Another service is being held at the same time.", 
            "Could not update song.", "The date field was not provided." ]

@app.route('/details')  #Calls getDetails()
def details():
    global cursor
    svc_id = request.args.get('svc_id')
    return getDetails(svc_id, cursor)

#Home page of the website that lists services
@app.route('/')
def home():
    global cursor
Пример #39
0
 def DB_Connect(self):
     self.conn = mdb.connect(host="localhost", user="******", password="******", database="youtube_tutorial")
     self.cur = self.conn.cursor()
Пример #40
0
# Try entering the following in the search box:
#  3 or 1=1

import bottle
from datetime import datetime
from mysql.connector import connect

con = connect(user='******', password='******', database='simpledb')
cursor = con.cursor()


@bottle.route('/')
def hello():
    qty = 0
    if 'qty' in bottle.request.params:
        qty = bottle.request.params['qty']

    # SQL Injection vulnerability here:
    cursor.execute("""
    select ProdId, ProdName, Quantity, ProdNextShipDate
    from product
    where Quantity < {0}
    """.format(qty))  # Also try   ProdName = '{0}'

    # Retrieve results
    result = cursor.fetchall()

    table = """
        <table>
        <tr>
            <td>Product ID`
Пример #41
0
def establishConnection():
    return mc.connect(host='localhost',
                      user='******',
                      passwd='ayushi',
                      db='attendance_management_system')
            content = 'From the archive: ' + content
        elif post_type == 'Archive' and len(tweet_text) > 102:
            content = 'From the archive: ' + social_queue[n][0]

        buffer_post(platform, content, page_url)

        n = +1


def main_proc():
    generate_media_queue()
    daily_loads()


global cursor

parser = ConfigParser()
parser.read("whconfig.ini")

wh_host = parser.get('MYSQL', 'host')
wh_user = parser.get('MYSQL', 'user')
wh_pass = parser.get('MYSQL', 'password')

conn = mysql.connect(host=wh_host,
                     user=wh_user,
                     password=wh_pass,
                     database='NovaraWH')

cursor = conn.cursor()

main_proc()
Пример #43
0
#     ("Priyanka Das", 11, "D"),
#     ("Rupankar Das", 11, "C")
# ]

# #myCursor
# for x in userData:
#     myCursor.execute(Q1, x)

# myCursor.execute("SELECT * FROM table1 OREDER BY sec ASC/DESC ")
# for x in myCursor:
#     print(x)


import mysql.connector as mc

db = mc.connect(host = "localhost", user = "******", password = "******", database = "testimonials")

Cursor = db.cursor()

executer = "DROP TABLE IF EXISTS users"

Cursor.execute(executer)

db.close()






import mysql.connector as mysql

#Connecting to database
db = mysql.connect(host="localhost",
                   user="******",
                   password="",
                   database="college")

#Creating handler to excute quarys
command_handler = db.cursor(buffered=True)


# Admin login
def auth_admin():
    username = input(str("Username : "******"Password : "******"admin":
        if password == "admin":
            admin_accs()
        else:
            print("Wrong password")
    else:
        print("Wrong cradentials")


#Admin Work
def admin_accs():
    while 1:
        print("Admin Menu")
        print("1. New Student Entry")
        print("2. New teacher Entry")
Пример #45
0
import mysql.connector as conn
import time

while True:
    try:
        db = conn.connect(host="10.0.10.3",
                          user="******",
                          password="******",
                          database="projekt")
        break
    except Exception:
        time.sleep(2)

curr = db.cursor()
curr.execute(
    "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), login VARCHAR(255))"
)

insert = "INSERT INTO users (name, login) VALUES (%s, %s)"
val = [("Pawel", "paww"), ("Robert", "robb"), ("Jarek", "kwakwa")]
curr.executemany(insert, val)
db.commit()
print(curr.rowcount, " was inserted")


def print_menu():
    print("1. SELECT")
    print("2. INSERT")
    print("3. UDATE")
    print("4. DELETE")
Пример #46
0
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 22:20:57 2018

@author: Pippo
"""
#import pyodbc
import mysql.connector as mariadb
#import MySQLdb
mariadb_connection = mariadb.connect(user='******',
                                     password='******',
                                     database='hausapp')
c = mariadb_connection.cursor()

c.execute("DESCRIBE gumtree;")

rows = c.fetchall()

for eachRow in rows:
    print(eachRow)
def get_mysql_connection():
    mysqlClient = connect(user=MYSQL_USER,
                          password=MYSQL_PASSWORD,
                          host=MYSQL_HOST,
                          database=MYSQL_DATABASE)
    return mysqlClient
Пример #48
0
#!/usr/bin/python2

import cgi
import commands

print 'content-type:text/html'

print ''

import mysql.connector as mariadb

db = mariadb.connect(user='******', password='******', database='welkins')

cursor = db.cursor()

print '''

<!DOCTYPE html>
<html>
<head>
<style>
.but{
	background:blue;
	color:white;
	text-align:center;
	text-decoration:none;
	border-radius:4px;
	border:2px groove blue;
	padding:4px;
}
</style>
Пример #49
0
from bs4 import BeautifulSoup
import urllib.request
from FoodParser import FoodParser
import sys

import fuzzywuzzy as fuzzywuzzy
from fuzzywuzzy import process
from fuzzywuzzy import fuzz
import mysql.connector as mysql

# connecting to the database using 'connect()' method
# it takes 3 required parameters 'host', 'user', 'passwd'
db = mysql.connect(host="localhost",
                   user="******",
                   passwd="3476269507",
                   database="wegmansdb",
                   auth_plugin='mysql_native_password')
#
# # creating an instance of 'cursor' class which is used to execute the 'SQL' statements in 'Python'


class Parser:
    def __init__(self, url):
        self.urlData = url

    urlData = ""
    parsedIngredients = []
    names = []

    def ingredientParser(self):
Пример #50
0
def initialiser():
    global conn, cur
    conn = mysql.connect(**config_mysql)
    cur = conn.cursor()
    cur.execute("USE gsb_formation")
Пример #51
0
# from binascii import a2b_base64
import mysql.connector as conn
import os

mimeMap = {
    'html': 'text/html',
    'css': 'text/css',
    'js': 'text/javascript',
    'json': 'text/json',
    'txt': 'text/plain',
    'ico': 'image/x-icon',
    'jpg': 'image/jpg',
    'png': 'image/png'
}
myDB = conn.connect(user='******',
                    host='localhost',
                    password='******',
                    database='rahul7')

myCrsr = myDB.cursor(dictionary=True)
rExt = re.compile(r'(?<=\.).+')


class Server(BaseHTTPRequestHandler):
    def _send_headers(self, ext):
        self.send_response(200)
        self.send_header('Content-Type', mimeMap[ext])
        self.end_headers()

    def do_GET(self):
        self.path = '/templates/index.html' if self.path == '/' else '/templates' + self.path
        ext = re.findall(rExt, self.path)[0]
Пример #52
0
 def __init__(self):
     try:
         self.cnx = mysqldb.connect(**dbcfg)
         self.cursor = self.cnx.cursor(dictionary=True)
     except mysqldb.Error:
         log.exception("An exception has occurred in {}: ".format(__name__))
Пример #53
0
import time
import datetime
import csv
import pandas as pd
from PIL import Image
import numpy as np


#========================= B A C K E N D ==========================#

########################## SQL ##########################

import mysql.connector as msql
from mysql.connector import Error
try:
    conn = msql.connect(host='localhost', user='******',
                        password='******', db='opencv')
    cursor = conn.cursor()

except Error as e:
    print("Error while connecting to MySQL", e)

########################## Basic Methods ##########################


def path_existence(path):
    """
    This function will create the directory if it does not exist
    """
    dir = os.path.dirname(path)
    if not os.path.exists(dir):
        os.makedirs(dir)
Пример #54
0
# -*- coding: utf-8 -*-
import mysql.connector as db
import pandas as pd
import sys
import hashlib
import random
import traceback
NUMBER_OF_USERS = 116903
"""def check_hex(val):
    try:
        hexval = int(val)
"""
conn = db.connect(host="localhost",
                  user="******",
                  passwd="PennConnect@123",
                  database="pennconnect")
print("connected!")
cursor = conn.cursor()
print("got cursor!")
df_data = pd.read_csv(sys.argv[1])
print("loaded dataframe!")
user_id = 1
i = 0
insert_sql = "UPDATE user SET major=\'{}\', degree_type=\'{}\', graduation_year=\'{}\' WHERE user_id=\'{}\'"
while (user_id <= NUMBER_OF_USERS):
    random_major = df_data.sample(1)['Major'].iloc[0]
    print(random_major)
    degree_type = random.choice(['UG', 'MS', 'PHD'])
    graduation_year = random.choice(range(2025, 2018, -1))
    try:
        print("query = " + insert_sql.format(random_major, degree_type,
Пример #55
0
#!/usr/bin/python2

import cgi,cgitb
cgitb.enable()
import mysql.connector as mariadb
import commands
print "Content-type:text/html"
print ""

web_data=cgi.FieldStorage()

uip= web_data.getvalue('uip')
password= web_data.getvalue('password')
conn=mariadb.connect(user='******',password='******',database='autolab',host='localhost')
cursor=conn.cursor()
cursor.execute('select uip from user where uip="{}";'.format(uip))
out=cursor.fetchall()
if len(out)>0:
	cursor.execute('delete from user where uip="{}");'.format(uip,password))
	conn.commit() 
	print "<body style="'background-color:linen;padding-top:100px;'"><center><h1 style="'color:blue;'"><h1>"
	print " User Removed."
	print "</h1></center></body>"
	print "<meta http-equiv='refresh' content='3;http://127.0.0.1/AutoLab/explore.html'>"	

else :
	
	print "<body style="'background-color:linen;padding-top:100px;'"><center><h1 style="'color:blue;'"><h1>"
	print " User Doesn't Exists."
	print "</h1></center></body>"
	print  "<meta http-equiv='refresh' content='3;http://127.0.0.1/delete_client.html'>"
Пример #56
0
import mysql.connector as m
mydb = m.connect(host = "localhost",user = "******", password = "******")
mycursor = mydb.cursor()
mycursor.execute("create database loginpage")
# you should make the aboue statement(  mycursor.execute("create database studentdb")  ) as comments after you run it once (WHY? we cannot create the same database multiple times)
mycursor.execute("show databases")
for i in mycursor:
    print(i)
def main(currency):
    time.sleep(1)
    update_tables(currency)
    with open('config.json') as json_file:
        file = json.load(json_file)
        config = file['mysql']

    # =============================================================================
    # Data
    # =============================================================================

    db_connection = sql.connect(host=config['host'],
                                database=config['database'],
                                user=config['user'],
                                password=config['password'],
                                port=9306)

    dataset = pd.read_sql_query(
        'SELECT id, value from historic_%s order by id desc LIMIT 180' %
        currency,
        db_connection,
        coerce_float=False)
    db_connection.close()
    # =============================================================================
    # Train & Test
    # =============================================================================

    sc = MinMaxScaler(feature_range=(0, 1))
    AUX1 = sc.fit_transform(np.array(dataset["value"]).reshape(-1, 1))
    dataset["close_escalado"] = AUX1

    train = dataset['close_escalado']

    # Pasar a numpy
    train = np.array(train)

    # =============================================================================
    # Variables para longitudes secuenciales
    # =============================================================================
    predictor_range = 180
    prediction_range = 45

    # =============================================================================
    # Secuencias
    # =============================================================================
    X_train = train
    y_train = train[-45:]
    # for i in range(predictor_range, (train.shape[0] - prediction_range)):
    #     X_train.append(train[i - predictor_range:i])
    #     y_train.append(train[i:i + prediction_range])
    # X_train, y_train = np.array(X_train), np.array(y_train)

    X_train = np.reshape(X_train, (-1, 1, predictor_range))
    # y_train = np.reshape(y_train, (-1,1,prediction_range))
    y_train = np.reshape(y_train, (-1, prediction_range))

    # =============================================================================
    # Evaluacion modelo
    # =============================================================================
    # Cojo la ultima secuencia del train, para predecir la siguiente
    cadena_ultima_X_Y = list(X_train[-1].reshape(-1)) + list(
        y_train[-1].reshape(-1))
    cadena_ultima_X_Y = np.array(cadena_ultima_X_Y[-predictor_range:]).reshape(
        1, 1, predictor_range)

    # =============================================================================
    # Modelo DL
    # =============================================================================
    model = tf.keras.models.load_model('CNN_%s.h5' % currency)

    model.compile(optimizer=tf.train.AdamOptimizer(),
                  loss='mean_squared_error')

    hypams = {
        'epochs': 1,
        'batch_size': 32,
        'verbose': 1,
        'early_stopping': 5,
        'min_delta': 0.000001
    }

    callbacks = [
        EarlyStopping(monitor='loss',
                      min_delta=hypams['min_delta'],
                      patience=hypams['early_stopping'],
                      verbose=0,
                      mode='min',
                      restore_best_weights=True)
    ]
    model.fit(X_train,
              y_train,
              epochs=hypams['epochs'],
              verbose=hypams['verbose'],
              callbacks=callbacks,
              batch_size=hypams['batch_size'])

    # GENERAR PREDICCION

    prediction = sc.inverse_transform(model.predict(cadena_ultima_X_Y))[0]

    # GUARDAR PREDICCION EN LA BASE DE DATOS
    db_connection = sql.connect(host=config['host'],
                                database=config['database'],
                                user=config['user'],
                                password=config['password'],
                                port=9306)
    db_cursor = db_connection.cursor()

    first_date = dataset.iloc[0]['id']

    first_value = dataset.iloc[0]['value']

    date_range = np.array(
        [first_date + datetime.timedelta(minutes=i) for i in range(1, 46)])

    db_cursor.execute(
        'INSERT INTO prediction_%s_cnn (id, value) VALUES ("%s", %s) ON DUPLICATE KEY UPDATE value=%s'
        % (currency, first_date, first_value, first_value))

    for n in range(len(prediction)):
        db_cursor.execute(
            'INSERT INTO prediction_%s_cnn (id, value) VALUES ("%s", %s) ON DUPLICATE KEY UPDATE value=%s'
            % (currency, date_range[n], prediction[n], prediction[n]))

    db_connection.commit()
    db_connection.close()

    model.save("CNN_%s.h5" % currency)
Пример #58
0
#run this package First...it call trail module whose signup button calls signup page and generaUsernamePassword
#submit button will be calling new page full of options to do like irctc
#
from ekanshDBMS import trial
from tkinter import messagebox
import mysql.connector as sq
#====================================================================>
conn = sq.connect(host="localhost",
                  user="******",
                  password="******",
                  database="test2",
                  auth_plugin='mysql_native_password')


# catch(ModuleNotFoundError):
#     print("Handeled")
#=====================================================================>
def login_in(username, password):
    cursor = conn.cursor()
    cursor.execute(
        "select * from username where username='******'".format(username))
    items = cursor.fetchall()
    for nm, pasd, email in items:
        nm = str(nm)
        pasd = str(pasd)
        # print(type(pasd))
        if (nm == username and pasd == password):
            from ekanshDBMS.venv import AfterLoginSuccess
            #messagebox.showinfo("Success","Successful Login To YOUR ACCOUNT")
            #trial.root.destroy()
            #messagebox.showinfo("success", "All Done..Now Login")
Пример #59
0
 def assistant(speech):
     cmd=str(speech)
     delete,p=0,0
     if "note" in cmd:
         print("your voice will be converted to text & will be saved in dictate.txt file")
         time.sleep(5)
         print("start")
         say("start")
         note()
         p=1
     if "what is the time" in cmd or "show me the time" in cmd or "time" in cmd:
         t = time.localtime()
         currenttime = time.strftime("%H:%M", t)
         a=str(currenttime)
         if int(a[:2])>0 and int(a[:2])<12:
             a=a+" AM "
         if int(a[:2])>=12 and int(a[:2])<24:
             h=str(int(a[:2])-12)
             a=h+a[2:]+" PM "
             atext='The time is '+str(a)
             say(atext)
             print(a)
         p=1
     if "set" in cmd and "alarm" in cmd:
         stop = False
         tm=str(input("enter time:"))
         label=str(input("enter label of alarm:"))
         atext='The alarm is set'
         myobj = gTTS(text=atext, lang='en')
         myobj.save("time.mp3")
         a1="time"
         playaudio('time.mp3')
         time.sleep(2)
         c=0
         while stop == False and c!=1:
             rn = str(datetime.datetime.now().time())
             if tm==rn[:8]:
                 print(label,rn[:8])
                 say("wake up wake up wake up wake up wake up wake up wake up wake up wake up wake up wake up wake up ")
                 c,p=1,1
     if "date" in cmd:
         today = datetime.date.today()
         atext='The date is '+str(today)
         say(atext)
         print("Today's date:", today)
         p=1
     if "calendar" in cmd:
         today = datetime.date.today()
         say("calendar of the year is given below")
         y=str(today)
         year=y[0:4]
         print (calendar.calendar(int(year), 2, 1, 6))
         p=1       
     if "who are you" in cmd or "what is your name" in cmd or "your name please" in cmd:
         print("Hello, my name is Catalina.")
         say("Hello, my name is Catalina.")
         p=1
     if "translate" in cmd:
         d={"English":"en","Hindi":"hi","Kannada":"kn","Telugu":"te","Marathi":"mr","French":"fr",
             "Punjabi":"pa","Korean":"ko","Latin":"la","German":"de",'Malayalam':"ml",'Russian':"ru",'Gujarati':"gu"}
         lan="English"
         for i in d:
             if i in cmd:
                 lan=str(i)
             else:
                 a=10
         l=str(d[lan])
         text4=str(input("enter the text to know details:"))
         s = Translator().translate(text=text4, dest=l).text
         atext1=str(s)
         myobj = gTTS(text=atext1, lang=l,slow=False)
         myobj.save("lantranslate.mp3")
         playaudio('lantranslate.mp3')
         print("translated :  ",s)
         p=1
     if "one more" in cmd or "again" in cmd:
         p=1
         con1=cs.connect(host="localhost",user="******",passwd="",database="catalina")
         cursor1=con1.cursor()
         query1="select * from history"
         cursor1.execute(query1)
         dat1=cursor1.fetchall()
         c,count=-1,0
         while count!=6:
             recent=str((dat1[c]))
             if "again" not in recent[44:] or recent[44:] is not "" or "one more" not in recent[44:]:
                 sp=recent[44:]
                 assistant(sp)
                 break
             else:
                 c=c-1
                 count=count+1
         con1.close()
     if "open" in cmd:
         p=1#'''or "Open"''':  
         if "open file" in cmd :
             cmd=cmd[9:]
             cmd=cmd[1:]
             print(cmd)
             print("The file will only be searched in C disk")
             say("searching file in C disk. Wait .")
             findfile(cmd)
         if "" in cmd:
             cmd=cmd.lower()
             print(cmd)
             apps={"chrome":'C:/Program Files/Google/Chrome/Application/chrome.exe',
                   'powerpoint':'C:/Program Files/Microsoft Office/root/Office16/POWERPNT.exe',
                   'settings':'C:/Windows/System32/control.exe',
                   'word':'C:/Program Files/Microsoft Office/root/Office16/WINWORD.exe',
                   'access':'C:/Program Files/Microsoft Office/root/Office16/MSASCCESS.exe',
                   'excel':'C:/Program Files/Microsoft Office/root/Office16/EXCEL.exe',
                   'task manager':'C:/Windows/system32/Taskmgr.exe',
                   'onenote':'C:/Program Files/Microsoft Office/root/Office16/ONENOTE.exe',
                   'command prompt':'C:/Windows/system32/cmd.exe',
                   'onscreen keyboard':'C:/Windows/system32/osk.exe',
                   'notepad':'C:/Windows/system32/notepad.exe',
                   'paint':'C:\Windows\system32\mspaint.exe',
                   'this pc':'C:/'}
             for i in apps:
                 if str(i) in cmd:
                     p=1
                     text3="opening"+str(i)
                     say(text3)
                     os.startfile(apps[i])
         else:
             say("i think software is not installed please install the software and then try again")
             p=1
     if "open YouTube" in cmd or "video of" in cmd:
         if "video of" in cmd or "videos related to" in cmd or "videos" in cmd:
             url="https://www.youtube.com/results?search_query="+cmd
             webbrowser.open(url)
             p=1
     if "history" in cmd:
         if "delete" in cmd :
             delhistory()
             p=1
         else:
             say("fetching your data")
             con1=cs.connect(host="localhost",user="******",passwd="",database="catalina")
             cursor1=con1.cursor()
             query1="select * from history"
             cursor1.execute(query1)
             p=1
             dat1=cursor1.fetchall()
             for i in dat1:
                 print(i)
             con1.close()
     if "os" in cmd or "operating system" in cmd and "my" in cmd:
         import platform
         a=str(platform.platform())
         say(a)
         print(a)
         p=1
     if "show me" in cmd or "" in cmd:
         text3="I found this for you."
         if "images" in cmd or "photos" in cmd:
             r1=cmd
             r1=r1.lstrip("show me images of")
             url="https://www.google.com/search?q="+str(r1)+"&source=lnms&tbm=isch&sa"
             say("i found this ")
             webbrowser.open(url)
             p=1
         if "news" in cmd:
             r1=cmd
             r1=r1.lstrip("show me news of")
             url="https://www.google.com/search?q="+str(r1)+"&tbm=nws&source=lnms&tbm=nws&sa"
             say("i found this ")
             webbrowser.open(url)
             p=1
     if "what can you do" in cmd:   
         say("i can do a lot like managing your activities, play a game, set a remainder,entertain,play a video, and a lot more")
         p=1
     if "copy" in cmd:
         t=cmd[5:]
         pyperclip.copy(t)
         say('text copied')
         p=1
     if "game" in cmd or "play" in cmd:
         if "game" in cmd or "a game" in cmd:
             url1="https://www.google.com/search?q=tic+tac+toe"
             url2="https://www.google.com/search?q=minesweeper"
             url3="https://www.google.com/search?q=play%20snake"
             url4="https://doodlecricket.github.io"
             url5="https://www.bing.com/fun/sudoku"
             url6="https://www.bing.com/fun/chess"
             r5=random.randint(0,5)
             url=[url1,url2,url3,url4,url5,url6]
             url=url[r5]
             say("OK let's play a game")
             print(p)
             p=1
             webbrowser.open(url)
         if "video" in cmd or "music" in cmd or "song" in cmd:
             g=".mp4"
             q=5
             lst=[]
             if 'music' in cmd or "song" in cmd:
                 g=".mp3"
             if q==5:
                 if " " in cmd :
                     say("searching file in c disk")
                     r1=5
                     for x,d,f in os.walk("c:\\"):
                         for files in f:
                             if g in files:
                                 location=str(os.path.join(x,files))
                                 lst.append(location)
                     p=1
                     w=random.randint(0,len(lst)-1)
                     ob=lst[w]
                     print("location:",ob)
                     os.startfile(ob)
     if "image to text" in cmd:
         pr=0
         try:
             from PIL import Image
         except ImportError:
             import Image
         import pytesseract
         import cv2
         file=str(input("enter image name:"))
         if " " in cmd :
             say("searching file in c disk")
             for x,d,f in os.walk("c:\\"):
                 if pr==0:
                     for files in f:
                         if files ==file and pr==0:
                             location=str(os.path.join(x,files))
                             print("location of file------   ",location)
                             img = cv2.imread(location)
                             p,pr=1,1
                             print("____________________________IMAGE PROCESSED TO TEXT________________________________")
                             print(pytesseract.image_to_string(Image.open(location)))
                             project()
                             break
     if "screenshot" in cmd or "take a photo of my screen" in cmd:
         time.sleep(5)
         if __name__ == '__main__':
             im = ImageGrab.grab()
             say("screenshot taken")
             n=str(input("enter name of the file:"))
             im.save(n+'.png')
             p=1
             time.sleep(3)
             im.show()
     if "tell me a joke" in cmd or "make me laugh" in cmd or "make me smile" in cmd or " joke " in cmd:
         j1='''A snail walks into a bar and the barman tells him there's a strict policy about having snails in the bar and so kicks
         him out.A year later the same snail re-enters the bar and asks the barman "What did you do that for?'''
         j2='''Three mice are being chased by a cat. The mice were cornered when one of the mice turned around and barked, "Ruff! Ruff! Ruff!" The surprised cat ran away scared.
         Later when the mice told their mother what happened, she smiled and said, "You see, it pays to be bilingual!"'''
         j3='''A nervous old lady on a bus was made even more nervous by the fact that the driver periodically took his arm out of the window. When she couldn't stand it any longer, she tapped him on the shoulder and whispered on his ear:
         "Young man...you keep both hands on the wheel...I'll tell you when it's raining!"'''
         j4='''Customer: Waiter, waiter! There is a frog in my soup!!! 
         Waiter: Sorry, sir. The fly is on vacation. '''
         j=[j1,j2,j3,j4]
         w1=random.randint(0,3)
         select=j[w1]
         say(select)
         for i in select:
             print(i,end="")
             time.sleep(0.047)
         print()
         p=1
     if "search for" in cmd:
         cmd=cmd.lstrip("search for")
         url="https://www.google.com/search?q="+cmd+"&source"
         say("i found this according to your search")
         p=1
         webbrowser.open(url)
     if "credits" in cmd or "made" in cmd and "you" in cmd:
         say("this is an open source project made by varun, mayank, souranh hope you liked it")
         p=1
     if "features" in cmd or "help" in cmd:
         features=["opening a file/app","entertain","search","weather","calculate","history","game","quiz","puzzle","video",
                 "take screenshot","download video","show time","note","OCR from image","alarm","math problems",'Q and A',"and many more"]
         for i in features:
             say(i)
             print(i)
         p=1
     if "feedback" in cmd:
         say("feel free to leave your feedback")
         os.startfile(cloc+"\\"+"main.html")
         p=1
     if "hello" in cmd:
         say('hello, how can I help you')
         p=1
     if "close" in cmd or "turn off"in cmd or "shutdown" in cmd and "computer" in cmd :
         os.system("shutdown -s")
         say("shutting down in  minute")
         p=1
     if "restart" in cmd and"computer" in cmd:
         os.system("shutdown /r /t 1")
         p=1
     if "exit" in cmd or "quit" in cmd or"close" in cmd:
         exit()
         p=1
     if "" in cmd and p==0:
         import wolframalpha
         client = wolframalpha.Client('42XG9Q-L76KJ35T39')
         try:
             res =client.query(cmd)
             output =next(res.results).text
             a=str(output)
             print(output)
             say(a)
             p=1
         except:
             try:
                 if p==0:
                     a=wikipedia.summary(cmd)
                     print(a)
                     say('According to Wikipedia'+a)
             except:
                 link='https://www.google.com/search?q='+str(cmd)
                 webbrowser.open(link)
                 p=1
     if delete!=1:
         con=cs.connect(host="localhost",user="******",passwd="",database="catalina")
         cursor=con.cursor()
         a=datetime.date.today()
         timesave=datetime.datetime.now().time()
         rn = str(timesave)
         tm=rn[:10]
         data=[(str(a),str(tm),cmd)]
         query='insert into history(date,time,word) values(%s,%s,%s)'
         cursor.executemany(query,data)
         con.commit()
         con.close()
         p=1
Пример #60
0
#!/usr/bin/python2

import mysql.connector as mysql  # pip install mysql-connector

conn = mysql.connect(user='******',
                     password='******',
                     host='localhost',
                     database='adhoc2')

cur = conn.cursor()
cur.execute("select name,email from student")
output = cur.fetchall()
print output

print "1. insert,   2. exit"

value = raw_input("enter choice")

if value == '1':
    #cur=conn.cursor()
    cur.execute("insert into student (name,email) values ('abhi','gmail.com')")
    print('one row inserted')
    print(cur.rowcount)
    conn.commit()

else:
    exit()