예제 #1
0
def main():
    # Make a .montehelper dir in HOME
    mhdir = os.path.join(os.path.expanduser('~'), '.montehelper')
    if not os.path.exists(mhdir):
        os.makedirs(mhdir)
    # Initialize logging
    logfile = os.path.join(mhdir, 'montehelper.log')
    fh = logging.FileHandler(logfile)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.info('Logging initialized')
    # Database backup
    cfg = Preferences()
    dbfile = cfg.GetProperty('sqlite', 'dbfile')
    # Backup database file
    sfile = SimpleRotater(dbfile)
    sfile.backup()
    # Check database version and do necessary updates
    version = int(cfg.GetProperty('program', 'version'))
    db = Database()
    db.updatedb(version)
    # Create instances of needed classes
    li = Listeners() #@UnusedVariable
    # Create GUI and show
    mh = MonteHelper(0)
    logger.info('Main window created, starting main loop')
    mh.MainLoop()
예제 #2
0
class Cashier:
	def __init__(self):
		self.db = Database()
	def checkout(self, items):
		itemDetails = []
		for item in items:
			x = list(self.db.getItemDetails(item[0]))
			x.append(item[1])
			itemDetails.append(x)
		print itemDetails
		self.cost = []
		print "\n\n Summary: \n\n"
		for i in itemDetails:
			print "id = "+str(i[0])
			print "name = "+str(i[1])
			print "category = "+str(i[2])
			print "life time since date of manufacture(in days) = "+str(i[3])
			print "price = "+str(i[4])
			print "quantity = "+str(i[5])
			print "cost for that quantity = " + str(i[5] * i[4])
			self.cost.append(i[4]*i[5])
		print "net cost = " + str(sum(self.cost))

		answer = str(raw_input("proceed? yes/no"))
		if answer == "yes":
			print "purchase accepted."
			for item in items:
				self.db.updateInventory(item)
		else:
			print "no purchase"
		print "Thank you for visiting."
	def close(self):
		self.db.close()
  def LiveLog(self, username, projectname, packagename, branchname, distro, release, arch):
      data = self.GetJob(username, projectname, packagename, branchname, distro, release, arch, "")
      if data is None:
        return ("No build is planned for this package at the moment...", -1)
      elif data['status'] == 'BUILDING':
        rowsToShow=40
        con = Database(self.config)
        stmt = "SELECT * FROM log WHERE buildid = ? ORDER BY id DESC LIMIT ?"
        cursor = con.execute(stmt, (data['id'], rowsToShow))
        data = cursor.fetchall()
        con.close()
        output = ""
        for row in data:
          output = row['line'] + output
        timeout = 2
      elif data['status'] == 'CANCELLED':
        return ("This build has been removed from the build queue...", -1)
      elif data['status'] == 'WAITING':
        return ("We are waiting for a build machine to become available...", 10)
      elif data['status'] == 'FINISHED':
        output = Logger().getLog(username, projectname, packagename, branchname, distro, release, arch, data['buildnumber'])
        # stop refreshing
        timeout=-1

      return (output, timeout)
 def CheckForHangingBuild(self):
     # check for hanging build (BuildingTimeout in config.yml)
     con = Database(self.config)
     stmt = "SELECT * FROM build "
     stmt += "WHERE status = 'BUILDING' and hanging = 0 "
     stmt += "AND datetime(started,'+" + str(self.config['lbs']['BuildingTimeout']) + " seconds') < '" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "'"
     stmt += " ORDER BY id DESC"
     cursor = con.execute(stmt)
     data = cursor.fetchall()
     cursor.close()
     for row in data:
       stmt = "SELECT * FROM log WHERE buildid=? AND datetime(created,'+" + str(self.config['lbs']['BuildingTimeout']) + " seconds') > '" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "'"
       cursor = con.execute(stmt, (row['id'],))
       if cursor.fetchone() is None:
         # mark the build as hanging, so that we don't try to release the machine several times
         stmt = "UPDATE build SET hanging = 1 WHERE id = ?"
         cursor = con.execute(stmt, (row['id'],))
         con.commit()
         # check if the machine is still occupied with that build
         #stmt = "SELECT * FROM machine WHERE username = ? and projectname = ? and packagename = ? AND name = ?"
         #cursor = con.execute(stmt, (row['username'], row['projectname'], row['packagename'], row['buildmachine']))
         #if cursor.fetchone() is None:
         #  # TODO mark build as stopped. do not release the machine, it might already build something else?
         #  con.close()
         #  return
         print("stopping machine %s because of hanging build %d" % (row["buildmachine"], row["id"]))
         print("current time: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
         print("sql statement: %s" % (stmt))
         con.close()
         self.ReleaseMachine(row["buildmachine"], True)
         # when the build job realizes that the buildmachine is gone:
         #   the log will be written, email sent, and logs cleared
         #   the build will be marked as failed as well
         return
     con.close()
예제 #5
0
파일: Main.py 프로젝트: magwas/smsregistry
class Main:
    def __init__(self, mailer=None):
        if mailer is None:
            mailer = Mailer()
        self.mailer = mailer
        self.db = Database(mailer)
        self.phone = Phone()
        self.doRemove = self.remove

    def processLoop(self, storage):
        for sms in storage.getValids():
                self.db.add(sms)
                self.doRemove(sms)

    def remove(self,sms):
        self.phone.removeSms(sms)

    def oneStep(self):
        allsms = Phone().getAllSms()
        store = SmsStorage(allsms)
        self.processLoop(store)

    def main(self):
        while True:
            try:
                self.oneStep()
            except Exception, e:
                exctype, exc, tb = sys.exc_info()
                syslog.syslog("%s:%s:%s"%(exctype,str(exc),traceback.format_tb(tb)))
            time.sleep(1)
예제 #6
0
def show_experiments():
    dbname = inform.getvalue("db")
    print h2("Database:  " + dbname)
    print h2("Experiments")
    db = Database(dbname)
    exprs = db.get_experiments()
    headings = ("ID","Name","Date","Experimenter")
    link_f = lambda x: link("show_plates","[ {0} ]".format(str(x)),
                            db=dbname,experiment=str(x))
    display = (link_f,None,None,None)
    print table_from_tuples(exprs,headings,display=display)
    
    print h2("Create New Experiment")
    form = Form(action=SCRIPT_NAME,method="get")
    form.add_hidden("action","create_experiment")
    form.add_hidden("db",dbname)
    form.add_text_field("name","Name")
    form.add_return()
    form.add_text_field("experimenter","Experimenter")
    form.add_return()
    for i in range(1,N_PLATES+1):
        form.add_text_field("plateid","Plate ID  ")
        form.add_text_field("platename","  Plate Name  ")
        form.add_return()
    form.add_submit("Create")
    print form
예제 #7
0
    def buy(self, symbol, quantity, buyPrice, profitableSellingPrice):

        # Do you have an open order?
        self.check_order()

        try:

            # Create order
            orderId = Orders.buy_limit(symbol, quantity, buyPrice)

            # Database log
            Database.write([orderId, symbol, 0, buyPrice, 'BUY', quantity, self.option.profit])

            #print('Buy order created id:%d, q:%.8f, p:%.8f' % (orderId, quantity, float(buyPrice)))
            self.logger.info('%s : Buy order created id:%d, q:%.8f, p:%.8f, Take profit aprox :%.8f' % (symbol, orderId, quantity, float(buyPrice), profitableSellingPrice))

            self.order_id = orderId

            return orderId

        except Exception as e:
            #print('bl: %s' % (e))
            self.logger.debug('Buy error: %s' % (e))
            time.sleep(self.WAIT_TIME_BUY_SELL)
            return None
예제 #8
0
 def runWorkload(self, datadir, scaleFactor, pageSize, workloadMode):
   db = Database(pageSize=pageSize)
   self.createRelations(db)
   self.loadDataset(db, datadir, scaleFactor)
   self.runOperations(db, workloadMode)
   db.close()
   shutil.rmtree(db.fileManager().dataDir, ignore_errors=True)
   del db
 def GetFinishedQueue(self):
     con = Database(self.config)
     cursor = con.execute("SELECT * FROM build WHERE status='FINISHED' ORDER BY finished DESC LIMIT ?", (self.config['lbs']['ShowNumberOfFinishedJobs'],))
     data = cursor.fetchall()
     con.close()
     result = deque()
     for row in data:
       result.append(row)
     return result
 def GetBuildQueue(self):
     con = Database(self.config)
     cursor = con.execute("SELECT * FROM build WHERE status='WAITING' ORDER BY id ASC")
     data = cursor.fetchall()
     con.close()
     result = deque()
     for row in data:
       result.append(row)
     return result
예제 #11
0
 def __init__(self, normalized, website, camperid, day, dest, page, year, refresh):
     Database.__init__(self, website, camperid, day, dest, page, year, refresh)
     self.normalized = normalized
     csv_object_in = normalized.csv_object   
     self.folder_out = csv_object_in.foldername
     self.csv_accumulated = self.obtainAccumulatedRecords(csv_object_in)
     #self.csv_object = self.recordsSpecialFields(self.csv_accumulated)
     self.csv_object = self.csv_accumulated
     return None
예제 #12
0
파일: Url.py 프로젝트: uknof/shortener
 def get_all(createdby=None):
     urls = []
     if createdby is None:
         urlrows = db.query_db('select short from urls')
     else:
         urlrows = db.query_db('select short from urls where createdby = ?', [createdby])
     for row in urlrows:
         url = Url(row["short"])
         urls.append(url)
     return urls
예제 #13
0
def collect_data():
    global reads
    global current_data
    starttime = time.clock()
    for x in range(0,numReaders):
        XBeeStatus[x]=0                                                                                                                                                                              
    for x in range(0,numReaders):
        #xbee.send('tx',dest_addr_long=XBeeAddress[x],dest_addr=UNKNOWN,data=b't')
        time.sleep(1)
        current_data=''
        xbee.send('tx',dest_addr_long=XBeeAddress[x],dest_addr=UNKNOWN,data=b'D')
        start = time.clock()
        time.sleep(2)
        while XBeeStatus[x] != 12:
            if (time.clock()-start)>30:
                #xbee.send('tx',dest_addr_long=XBeeAddress[x],dest_addr=UNKNOWN,data=b'D')
                #XBeeStatus[x]=0
                #current_data=''
                #start = time.clock()
                #print ("Re-sent DATA_SEND to {0}".format(x))
                #time.sleep(2)
                print "Did not recieve data"
                XBeeStatus[x] = 12
                #xbee.send('tx',dest_addr_long=XBeeAddress[x],dest_addr=UNKNOWN,data=b't')
                current_data=1594*'0'
            if (time.clock()-starttime)>115:
                print ("Exceeded time limit")
                return
            try:
                if packets.qsize() > 0:
                    newPacket = packets.get_nowait()
                    handlePacket(newPacket)
            except KeyboardInterrupt:
                break      
        # Save to database
        db = Database(dbname)
        for res in range(0,4):
            data = current_data[res*394:res*394+394]
            well_data = ''
            for well in range(0,96):
                well_data = well_data+','+str(int(data[12+well*4:14+well*4]+data[10+well*4:12+well*4],16))
                current_time = int(data[6:8]+data[4:6]+data[2:4]+data[0:2],16)       
            db.add_data(exp_id,XBeeID[x],current_time,data[8:10],well_data) 
        db.close()

        # Save to text file
        save_path = '/media/usbhdd'
        filename = os.path.join(save_path,XBeeFilenames[x])  
        current_file = open(filename,'a')
        current_file.write(current_data)
        current_file.write('\n')
        current_file.close()
    reads = reads+1
    print ("Recieved data: {0}".format(reads))
    return
예제 #14
0
class DatabaseConnectionTest(unittest.TestCase):
  def setUp(self):
    self.db = Database()
    self.db.setup()

  def tearDown(self):
    self.db.dropTables()

  def test_countResponses(self):
    count = self.db.countResponses()
    self.assertEquals(count, 0)

  def test_insertsResponseIntoTable(self):
    oldCount = self.db.countResponses()

    resp = Response()
    resp.recog = "True"
    resp.comp = "Composer"
    resp.comp_conf = "5"
    resp.piece = "Piece"
    resp.piece_conf = "3"
    resp.name = "Name"
    resp.age = "23"

    self.db.saveResponse(resp)

    newCount = self.db.countResponses()
    newResponses = newCount - oldCount

    self.assertEquals(newResponses, 1)
예제 #15
0
def make_database_from_pairs(df, bizpairs):
    """
    make the database from the pairs returned from mrjob.
    df is the dataframe, smalldf or fulldf.
    bizpairs are a list of elements, each of which is a list of two
        lists. The first of these lists has the two business id's, while
        the second has the similarity and the common support
    Returns an instance of the Database class.
    """
    dbase=Database(df)
    cache={}
    for bp,corrs in bizpairs:
        b1,b2=bp
        i1=dbase.uniquebizids[b1]
        i2=dbase.uniquebizids[b2]
        sim,nsup=corrs
        dbase.database_sim[i1][i2]=sim
        dbase.database_sim[i2][i1]=sim
        dbase.database_sup[i1][i2]=nsup
        dbase.database_sup[i2][i1]=nsup
        if cache.has_key(b1):
            nsup1=cache[b1]
        else:
            nsup1=dbase.df[dbase.df.business_id==b1].user_id.count()
            cache[b1]=nsup1
        if cache.has_key(b2):
            nsup2=cache[b2]
        else:
            nsup2=dbase.df[dbase.df.business_id==b2].user_id.count()
            cache[b2]=nsup2
        dbase.database_sim[i1][i1]=1.0
        dbase.database_sim[i2][i2]=1.0
        dbase.database_sup[i1][i1]=nsup1
        dbase.database_sup[i2][i2]=nsup2
    return dbase
예제 #16
0
def main ():
    
    my_database = Database()
    my_database.add_user('cool_user_jim_bob')
    new_users = [
            User(name='wendy', fullname='Wendy Williams', password='******'),
            User(name='otherperson', fullname='Cool Beans', password='******'),
            User(name='yay', fullname='NEVAR potatoes', password='******')
            ]
    my_database.add_all_users(new_users)
    print my_database.session.query(User).filter_by(password='******').first().name
 def GetMachines(self):
   con = Database(self.config)
   stmt = "SELECT name FROM machine"
   cursor = con.execute(stmt)
   data = cursor.fetchall()
   cursor.close()
   con.close()
   result = []
   for row in data:
     result.append(row['name'])
   return result
 def ProcessBuildQueue(self):
     # loop from left to right
     # check if a project might be ready to build
     con = Database(self.config)
     cursor = con.execute("SELECT * FROM build WHERE status='WAITING' ORDER BY id ASC")
     data = cursor.fetchall()
     for row in data:
       self.attemptToFindBuildMachine(con, row)
     cursor.close()
     con.close()
     self.CheckForHangingBuild()
예제 #19
0
class Dispatcher(object):
    """ Dispatcher class to control process of working. """

    def __init__(self):
        create_or_check_path("logs/")

        fileConfig('config/logger.conf')

        self.database = Database()
        self.parser = Parser()
        self.event_processor = EventProcessor()
        self.downloader = Downloader()

        self.new_events_file = None
        self.new_data = None
        self.new_event = None

    def processor(self):
        """ Process of downloading, parsing and saving information. """
        download_status = True
        while download_status:
            getting_event_status = self.get_event()
            if getting_event_status:
                processing_event_status = self.process_event()
                if processing_event_status:
                    self.process_data()
            else:
                download_status = self.download()

    def get_event(self):
        """ Asks Parser for a new event.
        :return: False if getting event failed else True
        """
        self.new_event = self.parser.get_event(self.new_events_file)
        return False if self.new_event is None else True

    def download(self):
        """ Sends a request to Downloader.
        :return: False if downloading failed else True
        """
        self.new_events_file = self.downloader.download_archive()
        return False if self.new_events_file is None else True

    def process_event(self):
        """ Asks EventProcessor to get data from event.
        :return: False if processing event failed else True
        """
        self.new_data = self.event_processor.process_event(self.new_event)
        return False if self.new_data is None else True

    def process_data(self):
        """ Sends data to Database. """
        self.database.process_data(self.new_data)
  def CanFindMachineBuildingProject(self, username, projectname):
    con = Database(self.config)
    stmt = "SELECT * FROM machine WHERE status = ? AND username = ? AND projectname = ?"
    cursor = con.execute(stmt, ('BUILDING', username, projectname))
    data = cursor.fetchone()
    cursor.close()
    con.close()

    if data is not None:
          # there is a machine building a package of the specified project
          return True
    return False
class ChatBot:

    def __init__(self):
        self.intros = {"Hello.","Hi!","Hey.","What's up?",
                       "Nice to see you.","Greetings.","...",
                       "Get on with it.","I haven't got all day.",
                       "*Sigh*","What a life..."}
        self.database = Database()
        self.database.readDatabase()
        self.exits = {"Bye.","Goodbye.","Good bye.","Have a nice day.",
                      "See you.","See you again soon.",
                      "Nice talking with you."}
##        self.setExit(self.shutdown)
##
##    def setExit(self,f):
##        if os.name == "nt":
##            try:
##                import win32api
##            except ImportError:
##                pass
##            else:
##                win32api.SetConsoleCtrlHandler(f,True)              
##        else: #Assume unix-like
##            import signal
##            signal.signal(signal.SIGTERM,f)
            
    def shutdown(self,frame=None):
        res = random.sample(self.exits,1)
        print(res[0])
        self.database.writeDatabase()
        input()
        
    def run(self):
        print("Running ChatBot...\n")
        res = random.sample(self.intros,1)
        res = res[0]
        lines = []
        lines.append(res)
        try: 
            while True:
                sleep(0.6)
                userResponse = input("ChatBot: " + res + '\nYou: ')
                lines.append(userResponse)
                if len(lines) is 4: #Must be even
                    ss = Snapshot()
                    [ss.append(l) for l in lines]
                    self.database.addSnapshot(ss)
                    lines = lines[2:] #Chop off oldest exchange
                res = self.database.getFinale(userResponse)                        
                lines.append(res)
        except (KeyboardInterrupt, EOFError):
            try:
                sleep(2) #Get remaining interrupts
            except:
                pass
            res = random.sample(self.exits,1)
            print(res[0])
            self.database.writeDatabase()
 def GetJob(self,username, projectname, packagename, branchname, distro, release, arch, where):
     con = Database(self.config)
     stmt = "SELECT * FROM build "
     stmt += "WHERE username = ? AND projectname = ? AND packagename = ? AND branchname = ? AND distro = ? AND release = ? AND arch = ? "
     stmt += "AND hanging = 0 "
     stmt += where
     stmt += " ORDER BY id DESC"
     cursor = con.execute(stmt, (username, projectname, packagename, branchname, distro, release, arch))
     data = cursor.fetchone()
     cursor.close()
     con.close()
     return data
예제 #23
0
def create_experiment():
    dbname = inform.getvalue("db")
    db = Database(dbname)
    exp_name = inform.getvalue("name","")
    experimenter = inform.getvalue("experimenter","")
    exp_id = db.add_experiment(name=exp_name,experimenter=experimenter)
    
    ids = inform.getlist("plateid")
    names = inform.getlist("platename")
    for pid,name in zip(ids,names):
        db.add_plate(exp_id,pid,name)
    
    show_experiments()
예제 #24
0
 def process_item(self, item, spider):
     # log.msg("\n\nitem: " + item.__str__() + "scrape id: " + spider.spider_id.__str__(), level = log.ERROR)
     soup = BeautifulSoup(item["text"])
     item["text"] = "".join(soup.findAll(text=True))
     stripped_content = item["text"].replace(" ", "")
     myhash = hashlib.sha1(stripped_content.__str__()).digest()
     base64encoding = base64.b64encode(myhash)
     item["content_hash"] = base64encoding
     if base64encoding not in self.text_hashes:
         # log.msg("\n\nitem: " + item.__str__(), level = log.ERROR)
         self.text_hashes.append(base64encoding)
         database = Database()
         database.add_item(item, spider.spider_id, spider.search_term)
예제 #25
0
    def __init__(self, roomnaam):
        self.room_name = roomnaam

        db = Database()
        cursor = db.get_cursor()
        cursor.execute(("SELECT * FROM `rooms` WHERE `name` = '%s'" % self.room_name))
        row = cursor.fetchone()

        try:
            self.room_id = row[0]

        except TypeError:
            raise ValueError("Room doesn't exist!")
예제 #26
0
    def __init__(self):
        Database.__init__(self)

        # get a logger
        self.__logger = logging.getLogger("chattest.server.MySQLDatabase")
        self.__logger.debug("Created a new MySQLDatabase object...")

        # get a configuration
        self.__configuration = configuration()

        # init member variables
        self.__connection = None
        self.__cursor = None
예제 #27
0
파일: Url.py 프로젝트: uknof/shortener
    def hits_record(self, sourceip):
        d = db.get_db()
        ip = ipaddr.IPAddress(sourceip)
        hittoday = db.query_db("select * from hits where short=? and hitdate=date('now')", [self.short])
        hitfield = "hits%s" % (ip.version)
        # update hit counters
        if len(hittoday) == 0:
            d.execute("insert into hits (short,hitdate,%s) values (?,date('now'),1)" % (hitfield), [self.short])
        else:
            d.execute("update hits set %s=%s+1 where short=? and hitdate=date('now')" % (hitfield, hitfield), [self.short])
        d.commit()

        return
예제 #28
0
파일: User.py 프로젝트: uknof/shortener
 def authenticate(username, password):
     username = username.lower().strip()
     if len(username) == 0 or len(password) == 0:
         return None
     userdb = db.query_db("select * from users where username = ?", [username])
     if len(userdb) == 1:
         # user exists, check the hash
         hash = userdb[0]["password"]
         if pbkdf2_sha256.verify(password, hash):
             d = db.get_db()
             d.execute("update users set logins = logins + 1, last_login = date('now') where username = ?", [username])
             d.commit()
             return User(username)
     return None
예제 #29
0
    def __init__(self):
        Database.__init__(self)

        self.total_downloads = 0
        self.queue = Queue(0)
        self.report = {'success':[], 'failure':[]}
        self.threads = []

        for i in range(c.cfg('download-threads')):
            thread = self.Downloader(self.queue, self.report)
            thread.start()
            self.threads.append(thread)
        if self.queue.qsize() > 0:
            self.queue.join()
예제 #30
0
    def getStatus(self):
        db = Database()
        cursor = db.get_cursor()
        cursor.execute(("SELECT * FROM `light` WHERE `light_id` = %s ORDER BY `datetime` DESC" % self.light_id))
        row = cursor.fetchone()

        cursor.close()
        db.closeConnection()

        # item 2 of the tuple is in
        if row[2] == 1:
            return "true"
        else:
            return "false"
예제 #31
0
import Database.Database as Database
# MH

from Problem.util import read_instance as Instance
from Problem import SCP as Problem
from Metrics import Diversidad as dv

# RepairGPU
from Problem.util import SCPProblem

# Definicion Environments Vars
workdir = os.path.abspath(os.getcwd())
workdirInstance = workdir + env('DIR_INSTANCES')

connect = Database.Database()


def HHO_SCP(id, instance_file, instance_dir, population, maxIter,
            discretizacionScheme, repair):

    print(f'repair: {repair}')
    instance_path = workdirInstance + instance_dir + instance_file

    if not os.path.exists(instance_path):
        print(f'No se encontró la instancia: {instance_path}')
        return False

    instance = Instance.Read(instance_path)

    problemaGPU = SCPProblem.SCPProblem(instance_path)
예제 #32
0
    def saveConfigSetting(self):
        product_cfg_buf_dic = deepcopy(self.data_of_select_product_cfg_js_dic)
        # 数据库
        product_cfg_buf_dic['database']['host'] = self.led_db_ip.text()
        product_cfg_buf_dic['database']['user'] = self.led_db_user.text()
        product_cfg_buf_dic['database']['pw'] = self.led_db_pw.text()
        product_cfg_buf_dic['database']['port'] = int(self.led_db_port.text())
        product_cfg_buf_dic['database'][
            'db_reslt'] = self.led_db_chk_name.text()
        product_cfg_buf_dic['database'][
            'tb_reslt'] = self.led_db_chk_table.text()
        product_cfg_buf_dic['database'][
            'db_param'] = self.led_db_rec_name.text()
        product_cfg_buf_dic['database'][
            'tb_param'] = self.led_db_rec_table.text()
        # 附加标签
        product_cfg_buf_dic['label_add']['height'] = float(
            self.led_add_label_height.text())
        product_cfg_buf_dic['label_add']['width'] = float(
            self.led_add_label_width.text())
        product_cfg_buf_dic['label_add']['x_offset'] = float(
            self.led_add_label_x_offset.text())
        product_cfg_buf_dic['label_add']['y_offset'] = float(
            self.led_add_label_y_offset.text())
        product_cfg_buf_dic['label_add']['left_margin'] = float(
            self.led_add_label_left_margin.text())
        product_cfg_buf_dic['label_add']['right_margin'] = float(
            self.led_add_label_right_margin.text())
        # 标签
        product_cfg_buf_dic['label']['width'] = float(
            self.led_label_width.text())
        product_cfg_buf_dic['label']['height'] = float(
            self.led_label_height.text())

        product_cfg_buf_dic['label']['has_bar_code'] = int(
            self.ckb_use_barcode.isChecked())
        product_cfg_buf_dic['label']['bar_code_size'] = float(
            self.led_label_barcode_size.text())
        product_cfg_buf_dic['label']['bar_x_offset'] = float(
            self.led_label_barcode_x_offset.text())
        product_cfg_buf_dic['label']['bar_y_offset'] = float(
            self.led_label_barcode_y_offset.text())

        product_cfg_buf_dic['label']['has_qr_code'] = int(
            self.ckb_use_qrcode.isChecked())
        product_cfg_buf_dic['label']['qr_code_size'] = float(
            self.led_label_qrcode_size.text())
        product_cfg_buf_dic['label']['qr_x_offset'] = float(
            self.led_label_qrcode_x_offset.text())
        product_cfg_buf_dic['label']['qr_y_offset'] = float(
            self.led_label_qrcode_y_offset.text())

        product_cfg_buf_dic['label']['has_hr'] = int(
            self.ckb_use_hr.isChecked())
        product_cfg_buf_dic['label']['hr_size'] = float(
            self.led_label_hr_size.text())
        product_cfg_buf_dic['label']['hr_x_offset'] = float(
            self.led_label_hr_x_offset.text())
        product_cfg_buf_dic['label']['hr_y_offset'] = float(
            self.led_label_hr_y_offset.text())
        # 保存打印机名
        if self.printer_name_cur_str == '':
            product_cfg_buf_dic['printer_name'] = self.led_printer_name.text()
        else:
            product_cfg_buf_dic['printer_name'] = self.printer_name_cur_str
        tempStr = ''
        if self.beChangeDefaultCfg:
            if float(product_cfg_buf_dic['label']['width']) == 12.0 and float(
                    product_cfg_buf_dic['label']['height']) == 5.5:
                fp = open(self.first_cfg_path, 'w')
                json.dump(product_cfg_buf_dic, fp, indent=4)
                fp.close()
                tempStr = "\n并保存默认配置为:" + format('%s' % self.first_cfg_path)
            elif float(
                    product_cfg_buf_dic['label']['width']) == 37.8 and float(
                        product_cfg_buf_dic['label']['height']) == 16.8:
                fp = open(self.third_cfg_path, 'w')
                json.dump(product_cfg_buf_dic, fp, indent=4)
                fp.close()
                tempStr = "\n并保存默认配置为:" + format('%s' % self.third_cfg_path)
            elif float(
                    product_cfg_buf_dic['label']['width']) == 18.0 and float(
                        product_cfg_buf_dic['label']['height']) == 40.0:
                fp = open(self.second_cfg_path, 'w')
                json.dump(product_cfg_buf_dic, fp, indent=4)
                fp.close()
                tempStr = "\n并保存默认配置为:" + format('%s' % self.second_cfg_path)
            else:
                pass
        try:
            DBproduct.SaveCfgToDB(self.strmacid, self.model_name,
                                  self.strstationid, product_cfg_buf_dic)
            QMessageBox.warning(
                None, 'PASS',
                '已存入当前配置到' + format('%s.' % self.db_db_param_str) +
                format('%s中' % self.db_tb_param_str) + tempStr)
            self.btn_quit_config.setEnabled(1)
        except Exception:
            QMessageBox.warning(None, 'Error', '未存入当前产品配置')
            return
예제 #33
0
    def get_user_item_score(self):
        hm_db = Database(self.id)
        hm_db.connect()

        return hm_db.get_item_score()
예제 #34
0
    def get_user_peace_status(self):
        hm_db = Database(self.id)
        hm_db.connect()

        return hm_db.get_peace_status()
예제 #35
0
    def update_user_records(self, battles_lost, battles_won, total_winnings):
        hm_db = Database(self.id)
        hm_db.connect()

        return " Your new battle records: **" \
               + str(hm_db.update_battle_records(battles_lost, battles_won, total_winnings)) + "**"
예제 #36
0
    def update_user_peace_cooldown(self):
        hm_db = Database(self.id)
        hm_db.connect()

        return hm_db.update_peace_cooldown()
예제 #37
0
from tkinter import *

from windowManager import windowManager
from Order import Order
from History import History
from Database import Database
from startModule import *

root = Tk()
root.geometry('550x450')
root.title('')

data = Database()
manager = windowManager(root, data)

root.mainloop()
예제 #38
0
    return pairings


def opponentMatchWins(p):
    '''Returns player p's oppenents match wins count'''

    match_qry = """SELECT winner, loser
    FROM Matches
    WHERE winner = (%s)
    OR
    loser = (%s)"""

    # wins_qry = """SELECT wins FROM Players WHERE id = (%s)"""
    wins_qry = """SELECT COUNT(*) FROM Matches WHERE winner = (%s)"""
    OWM = 0

    with Cursor(tournament_database) as cursor:
        cursor.execute(match_qry, [p, p])
        p_opps = [opp for tpl in cursor.fetchall() for opp in tpl if opp != p]

        for opp in p_opps:
            qry = wins_qry
            cursor.execute(qry, [opp])
            OWM += cursor.fetchone()[0]

    return OWM


tournament_database = Database('tournament', 'tournament.sql')
예제 #39
0
from Human import Human
from Student import Student
from Dean import Dean
from Semester import Semester
from Database import Database
from Leader import Leader
from Course import Course
from Subject import Subject
from Friends import Friends
import random

prowadzacyList = []

database = Database()
people = database.get_leaders()
for person in people:
    leader = Leader(person[3], person[4], person[5], person[1])
    prowadzacyList.append(leader)

kursyList = []

przedmioty = database.get_courses()
for przedmiot in przedmioty:
    course = Course(przedmiot[1])
    kursyList.append(course)

przedmiotyList = []

kursy = database.get_subjects()
for kurs in kursy:
    subject = Subject(kurs[1])
예제 #40
0
class Trader(object):

    # Static variables
    logger = logging.getLogger("Trader")
    client = Client(API_KEY, API_SECRET)
    exchange_data_lock = threading.Lock()
    exchange_data = DictMap({})
    db_lock = threading.Lock()
    database = Database()
    close_prices = deque(maxlen=50)
    symbol_info = DictMap(client.get_symbol_info(symbol=TRADING_PAIR))
    order_queue = Queue()
    order_queue_lock = threading.Lock()
    analyzed_data = DictMap({})
    analyzed_data_lock = threading.Lock()
    buy_prices = []
    buy_prices_lock = threading.Lock()
    buying_lock = threading.Lock()
    selling_analyzed_data = DictMap({})

    def __init__(self):
        self.order_id = 0
        self.last_buy_price = None
        self.last_sell_price = None
        self.buying_lock_acquired = False
        self.partially_filled_wait_start_time = None
        self.order_wait_start_time = None
        self.stoploss_triggered = False

    def timeout(self, t, order_type='partially_filled'):
        """
        Check for timeout
        """
        if order_type == 'partially_filled':
            if int(time.time()) > (int(t) + PARTIALLY_FILLED_WAIT_TIME):
                return True
        else:
            if int(time.time()) > (int(t) + ORDER_WAIT_TIME):
                return True
        return False

    @staticmethod
    def get_exchange_data():
        """
        Get exchange data
        """
        def get_order_book(symbol):
            """
                {
                    "lastUpdateId": 1027024,
                    "bids": [
                        [
                            "4.00000000",     # PRICE
                            "431.00000000",   # QTY
                            []                # Can be ignored
                        ]
                    ],
                    "asks": [
                        [
                            "4.00000200",
                            "12.00000000",
                            []
                        ]
                    ]
                }
            """
            order_book = Trader.client.get_order_book(symbol=symbol, limit=10)
            return DictMap(order_book)

        def get_balance(asset):
            """
                {
                    "asset": "BTC",
                    "free": "4723846.89208129",
                    "locked": "0.00000000"
                }
            """
            balance = Trader.client.get_asset_balance(asset)
            return DictMap(balance)

        def get_order_book_ticker(symbol):
            """
                {
                    "symbol": "LTCBTC",
                    "bidPrice": "4.00000000",
                    "bidQty": "431.00000000",
                    "askPrice": "4.00000200",
                    "askQty": "9.00000000"
                }
            """
            ticker = Trader.client.get_orderbook_ticker(symbol=symbol)
            return DictMap(ticker)

        def get_sell_prices(symbol):
            open_orders = Trader.client.get_open_orders(symbol=symbol)
            sell_prices = [
                float(open_order['price']) for open_order in open_orders
                if open_order['side'] == 'SELL'
                and open_order['status'] in ['NEW', 'PARTIALLY_FILLED']
            ]
            return list(set(sell_prices))

        order_book = get_order_book(TRADING_PAIR)
        order_book_ticker = get_order_book_ticker(TRADING_PAIR)
        sell_prices = get_sell_prices(TRADING_PAIR)

        return DictMap({
            'order_book': order_book,
            'ticker': order_book_ticker,
            'sell_prices': sell_prices
        })

    @staticmethod
    def print_exchange_info():
        """
        Print exchange information
        """
        ask = Trader.exchange_data.ticker.askPrice
        bid = Trader.exchange_data.ticker.bidPrice
        diff = '%.8lf' % (float(ask) - float(bid))
        spread = '%.2lf' % ((float(ask) / float(bid) - 1) * 100)
        Trader.logger.info("*** ask: %s - bid: %s - diff: %s - spread: %s" %
                           (ask, bid, diff, spread))

    @staticmethod
    def update_exchange_info():
        """
        Update the exchange data periodically.
        Start as a daemon thread in main program
        """
        while True:
            Trader.logger.debug("Updating exchange data...")
            start_time = time.time()
            Trader.exchange_data_lock.acquire()
            try:
                Trader.exchange_data = Trader.get_exchange_data()
            except Exception as e:
                Trader.logger.exception(e)

            Trader.exchange_data_lock.release()
            Trader.print_exchange_info()
            end_time = time.time()
            time_diff = end_time - start_time
            if time_diff < UPDATE_EXCHANGE_WAIT_TIME:
                Trader.logger.debug("Sleeping ...")
                time.sleep(UPDATE_EXCHANGE_WAIT_TIME - time_diff)

    @staticmethod
    def get_order_status(order_id):
        """
            {
                "symbol": "LTCBTC",
                "orderId": 1,
                "clientOrderId": "myOrder1",
                "price": "0.1",
                "origQty": "1.0",
                "executedQty": "0.0",
                "status": "NEW",
                "timeInForce": "GTC",
                "type": "LIMIT",
                "side": "BUY",
                "stopPrice": "0.0",
                "icebergQty": "0.0",
                "time": 1499827319559
            }
        """
        try:
            order = Trader.client.get_order(orderId=order_id,
                                            symbol=TRADING_PAIR)
        except:
            order = {}
        return DictMap(order)

    def buy(self, quantity, price):
        """
        Create buy order
        """
        price = self.format_price(price)
        fmtd_price = '{0:.8f}'.format(price).rstrip(
            '0')  # in case, str(price) is in exponential notation
        quantity = self.format_quantity(quantity)
        self.logger.info("Buying %s at %s..." % (str(quantity), str(price)))
        try:
            order = Trader.client.order_limit_buy(symbol=TRADING_PAIR,
                                                  quantity=quantity,
                                                  price=fmtd_price,
                                                  newOrderRespType='RESULT')
        except Exception as e:
            self.logger.exception(e)
            raise
        self.last_buy_price = price
        self.logger.info("Buying order %s created." % order['orderId'])
        return order['orderId']

    def sell(self, quantity, price):
        """
        Create sell order
        """
        price = self.format_price(price)
        fmtd_price = '{0:.8f}'.format(price).rstrip('0')
        quantity = self.format_quantity(quantity)
        self.logger.info("Selling %s at %s..." % (str(quantity), str(price)))
        try:
            order = Trader.client.order_limit_sell(symbol=TRADING_PAIR,
                                                   quantity=quantity,
                                                   price=fmtd_price,
                                                   newOrderRespType='RESULT')
        except Exception as e:
            self.logger.exception(e)
            raise
        self.last_sell_price = price
        self.logger.info("Selling order %s created." % order['orderId'])
        return order['orderId']

    def cancel(self, order_id):
        """
        Cancel open order
        """
        try:
            resp = Trader.client.cancel_order(symbol=TRADING_PAIR,
                                              orderId=order_id)
        except Exception as e:
            self.logger.exception(e)
            raise
        self.logger.info("Order %s has been cancelled." % resp['orderId'])
        return resp['orderId']

    @staticmethod
    def analyze(signal):
        """
        Analyze data
        """
        close_prices = list(signal)
        rsi = relative_strength_index(close_prices, RSI_PERIOD)
        Trader.logger.debug("RSI: %.2lf" % rsi[-1])
        buy_now = False
        sell_now = False
        if rsi[-2] <= RSI_OVERSOLD_PERCENTAGE and rsi[-1] > rsi[-2]:
            buy_now = True
        if rsi[-1] >= RSI_OVERBOUGHT_PERCENTAGE:
            sell_now = True
        return DictMap({'buy_now': buy_now, 'sell_now': sell_now})

    @staticmethod
    def analyze_market_data():
        """
        Analyze market data
        Start as daemon thread
        """
        server_time = Trader.client.get_server_time()
        server_time_offset = int(time.time() * 1000) - int(
            server_time['serverTime'])
        Trader.logger.debug("Time offset: %d" % server_time_offset)
        close_time = 0
        while True:
            Trader.logger.debug("RUNNING...")
            st = time.time()
            if len(Trader.close_prices) == 0:  # first time fetch
                data = Trader.client.get_klines(
                    symbol=TRADING_PAIR,
                    interval=KLINE_INTERVAL_1MINUTE,
                    limit=500)
                for point in data:
                    Trader.close_prices.append(float(point[4]))
                close_time = int(data[-1][6])
            else:
                current_time_with_offset = int(
                    time.time() * 1000) - server_time_offset
                Trader.logger.debug("close time: " + str(close_time))
                Trader.logger.debug("current time with offset: " +
                                    str(current_time_with_offset))
                if current_time_with_offset > close_time:
                    try:
                        data = Trader.client.get_klines(
                            symbol=TRADING_PAIR,
                            interval=KLINE_INTERVAL_1MINUTE,
                            limit=2)
                    except Exception as e:
                        Trader.logger.exception(e)
                        continue
                    close_time_new = int(data[-1][6])
                    if close_time != close_time_new:  # to avoid duplicate
                        close_time = close_time_new
                        Trader.close_prices.append(float(data[0][4]))
                        Trader.analyzed_data_lock.acquire()
                        Trader.analyzed_data = Trader.analyze(
                            Trader.close_prices)
                        Trader.logger.debug(str(Trader.analyzed_data))
                        Trader.analyzed_data_lock.release()
            et = time.time()
            if (et - st) < ANALYZE_WAIT:
                Trader.logger.debug("SLEEPING...")
                time.sleep(ANALYZE_WAIT - (et - st))

    @staticmethod
    def check_order():
        """
        Check status for orders in queue
        Start as daemon thread
        """
        while True:
            Trader.order_queue_lock.acquire()
            order_queue_empty = Trader.order_queue.empty()
            Trader.order_queue_lock.release()
            if not order_queue_empty:
                Trader.order_queue_lock.acquire()
                order_id = Trader.order_queue.get()
                Trader.order_queue_lock.release()
                Trader.logger.info("Checking for order #%d status..." %
                                   order_id)
                order_status = Trader.get_order_status(order_id)
                if not order_status:
                    continue
                Trader.logger.info("Order #%s status: %s" %
                                   (order_id, order_status.status))
                Trader.db_lock.acquire()
                order_data = {
                    'order_id': str(order_id),
                    'price': order_status.price,
                    'orig_quantity': order_status.origQty,
                    'executed_quantity': order_status.executedQty,
                    'side': order_status.side,
                    'time': order_status.time,
                    'status': order_status.status
                }
                Trader.database.order_update(order_data)
                Trader.db_lock.release()
                Trader.logger.info("Checking done for order #%d" % order_id)
            else:
                Trader.logger.info(
                    "Order queue is empty. Waiting for new order...")
                time.sleep(CHECK_ORDER_WAIT_TIME)

    def update_balance(self,
                       name,
                       initial_amount=None,
                       initial_quantity=None,
                       executed_quantity=None,
                       price=None,
                       side=None,
                       first_time=False):
        """
        Update balance to database
        """
        Trader.logger.debug("Updating balance...")
        data = {'thread_name': name, 'pairs': {}}
        modifier = 1 - FEE / 100.0
        Trader.db_lock.acquire()
        if first_time:
            if not initial_amount:
                data['pairs']['initial_amount'] = '0.0'
                data['pairs']['current_amount'] = '0.0'
            else:
                data['pairs']['initial_amount'] = str(initial_amount)
                data['pairs']['current_amount'] = str(initial_amount)
            if not initial_quantity:
                data['pairs']['initial_quantity'] = '0.0'
                data['pairs']['current_quantity'] = '0.0'
            else:
                data['pairs']['initial_quantity'] = str(initial_quantity)
                data['pairs']['current_quantity'] = str(initial_quantity)
        else:
            executed_quantity = float(executed_quantity)
            price = float(price)
            current_amount = float(
                Trader.database.trader_read(
                    name, key='current_amount')['pairs']['current_amount'])
            current_quantity = float(
                Trader.database.trader_read(
                    name, key='current_quantity')['pairs']['current_quantity'])
            if executed_quantity > 0.0:
                if side == 'SELL':
                    current_quantity = current_quantity - executed_quantity
                    current_amount = current_amount + executed_quantity * price * modifier
                else:  #BUY
                    current_quantity = current_quantity + executed_quantity * modifier
                    current_amount = current_amount - executed_quantity * price
            else:
                return
            data['pairs']['current_amount'] = str(current_amount)
            data['pairs']['current_quantity'] = str(current_quantity)

        Trader.database.trader_update(data)
        Trader.db_lock.release()

    def validate(self, quantity, price):
        """
        Check validity of an order before sending it to the exchange
        """
        filters = Trader.symbol_info.filters
        price_filter = filters[0]
        lot_size_filter = filters[1]
        notional_filter = filters[2]
        min_price = float(price_filter['minPrice'])
        max_price = float(price_filter['maxPrice'])
        tick_size = float(price_filter['tickSize'])
        min_quantity = float(lot_size_filter['minQty'])
        max_quantity = float(lot_size_filter['maxQty'])
        step_size = float(lot_size_filter['stepSize'])
        min_notional = float(notional_filter['minNotional'])
        if price < min_price or price > max_price:
            raise Exception('PRICE_EXCEPTION')
        if quantity < min_quantity or quantity > max_quantity:
            raise Exception('QUANTITY_EXCEPTION')
        if price * quantity < min_notional:
            raise Exception('MIN_NOTIONAL')
        return True

    def amount_to_quantity(self, amount, price):
        """
        Calculate quantity
        """
        quantity = amount / price
        return self.format_quantity(quantity)

    def format_quantity(self, quantity):
        """
        Format quantity
        """
        step_size = float(Trader.symbol_info.filters[1]['stepSize'])
        return round(
            float(step_size * math.floor(float(quantity) / step_size)), 8)

    def format_price(self, price):
        """
        Format price
        """
        tick_size = float(Trader.symbol_info.filters[0]['tickSize'])
        return round(float(tick_size * math.floor(float(price) / tick_size)),
                     8)

    def calc_profit(self, price):
        """
        Calculate the profit
        """
        profit = (price / self.last_buy_price - 1) * 100
        return profit

    def is_profitable(self, price):
        """
        Check for profitability
        """
        if self.calc_profit(price) >= PREFERRED_PROFIT:
            return True
        return False

    def is_stoploss(self, price):
        """
        Check for loss
        """
        loss_perc = 100 * (1 - price / float(self.last_buy_price))
        if loss_perc >= STOPLOSS_TRIGGER_PERCENTAGE:
            return True
        return False

    def calc_profitable_price(self):
        """
        Calculate the profitable price
        """
        price = self.last_buy_price * (1 + PREFERRED_PROFIT / 100.0)

        return self.format_price(price)

    def calc_buy_price(self):
        """
        Calculate buy price
        """
        order_book = self.exchange_data.order_book
        orders = order_book.bids
        last_ask = float(order_book.asks[0][0])
        quantities = [float(order[1]) for order in orders]
        prices = [float(order[0]) for order in orders]
        for i in range(1, len(quantities)):
            if sum(quantities[:i]) >= (QUANTITY_COEFFICIENT * INITIAL_AMOUNT /
                                       prices[0]):
                break
        optimal_prices = prices[:i]
        tick_size = float(Trader.symbol_info.filters[0]['tickSize'])
        buy_price = optimal_prices[-1]
        while True:
            buy_price = buy_price + tick_size
            if buy_price not in optimal_prices:
                break
        buy_price = buy_price + (BUY_PRICE_TICK_OFFSET - 1) * tick_size
        if buy_price > last_ask:
            buy_price = last_ask
        return self.format_price(buy_price)

    def calc_sell_price(self):
        """
        Calculate sell price
        """
        order_book = self.exchange_data.order_book
        sell_prices = self.exchange_data.sell_prices  # our sell prices in order book
        orders = order_book.asks
        last_bid = float(order_book.bids[0][0])
        quantities = [float(order[1]) for order in orders]
        prices = [float(order[0]) for order in orders]
        for i in range(1, len(quantities)):
            if sum(quantities[:i]) >= (QUANTITY_COEFFICIENT * INITIAL_AMOUNT /
                                       prices[0]):
                break
        optimal_prices = prices[:i]
        cmn_prices = sorted(set(sell_prices) & set(optimal_prices))
        if cmn_prices:
            sell_price = cmn_prices[0]
        else:
            tick_size = float(Trader.symbol_info.filters[0]['tickSize'])
            sell_price = optimal_prices[-1]
            while True:
                sell_price = sell_price - tick_size
                if sell_price not in optimal_prices:
                    break
            sell_price = sell_price - (SELL_PRICE_TICK_OFFSET - 1) * tick_size
            if sell_price < last_bid:
                sell_price = last_bid
        return self.format_price(sell_price)

    def calc_sell_quantity(self):
        """
        Calculate sell quantity
        """
        name = threading.currentThread().getName()
        Trader.db_lock.acquire()
        balance = float(
            Trader.database.trader_read(
                name, key='current_quantity')['pairs']['current_quantity'])
        Trader.db_lock.release()
        return self.format_quantity(balance)

    def calc_buy_quantity(self, price):
        """
        Calculate buy quantity
        """
        name = threading.currentThread().getName()
        Trader.db_lock.acquire()
        balance = float(
            Trader.database.trader_read(
                name, key='current_amount')['pairs']['current_amount'])
        Trader.db_lock.release()
        return self.amount_to_quantity(balance, price)

    def calc_price_range(self, price=None, side='buy'):
        """
        Calculate price range. 
        If the price of an open order is out of this range, cancel that order and place it again with new price.
        """
        order_book = self.exchange_data.order_book
        tick_size = float(Trader.symbol_info.filters[0]['tickSize'])
        if side == 'buy':
            orders = order_book.bids
        else:  #sell
            orders = order_book.asks
        lower_price = float(orders[0][0])
        quantities = [float(order[1]) for order in orders]
        prices = [float(order[0]) for order in orders]
        if price:
            my_price = float(price)
            try:
                idx = prices.index(my_price)
            except:
                idx = None
                Trader.logger.debug(
                    "my price is not on the book. Set lower_price to my_price")
                lower_price = my_price
            if idx and idx < len(prices) - 1:
                if abs(my_price -
                       float(orders[idx + 1][0])) > DIFF_TICKS * tick_size:
                    lower_price = float(orders[idx + 1][0])
        for i in range(1, len(quantities)):
            if sum(quantities[:i]) >= (QUANTITY_COEFFICIENT * INITIAL_AMOUNT /
                                       lower_price):
                break
        upper_price = float(orders[i - 1][0])

        return [lower_price, upper_price]

    def buy_action(self, status=None):
        self.logger.info("*** BUY ACTION ***")
        if status == 'filled' or status == 'cancelled_partially_filled':
            if status == 'filled' and self.stoploss_triggered:
                self.stoploss_triggered = False
            self.partially_filled_wait_start_time = None
            self.order_wait_start_time = None
            Trader.buy_prices_lock.acquire()
            Trader.logger.debug("Removing price %s from buy_prices" %
                                (str(self.last_buy_price)))
            Trader.logger.debug("buy_prices: %s" % str(Trader.buy_prices))
            Trader.buy_prices = list(set(Trader.buy_prices))
            try:
                Trader.buy_prices.remove(self.last_buy_price)
            except Exception as e:
                Trader.logger.info(
                    "Probably the buy order was partially filled but not enough to sell."
                )
                Trader.logger.exception(e)
            Trader.logger.debug("buy_prices: %s" % str(Trader.buy_prices))
            Trader.buy_prices_lock.release()
        if not self.buying_lock_acquired:
            # Acquire the lock until the buying action is complete
            # It blocks other threads to avoid multiple buy orders at a time
            Trader.logger.debug("Acquiring buying lock...")
            Trader.buying_lock.acquire()
            self.buying_lock_acquired = True
            Trader.logger.debug("Buying lock acquired.")
        if not status or status == 'filled' or status == 'cancelled_partially_filled':
            self.order_id = 0
            buy_price = self.calc_buy_price()
            ask = self.calc_sell_price()
            Trader.buy_prices_lock.acquire()
            buy_prices = Trader.buy_prices
            Trader.buy_prices_lock.release()

            Trader.analyzed_data_lock.acquire()
            buy_now = Trader.analyzed_data.buy_now
            Trader.analyzed_data_lock.release()

            if not buy_now:
                return
            if len(buy_prices) > 0:
                Trader.logger.debug("buy_prices: %s" % str(buy_prices))
                min_price = min(buy_prices)
                min_price_perc = (min_price / buy_price - 1) * 100
                if min_price_perc >= BUY_MORE_PRICE_PERCENTAGE:
                    pass
                else:
                    Trader.logger.info(
                        "There are incomplete actions. Waiting...")
                    return

            bid_ask_spread = 100. * (ask / buy_price - 1)
            if bid_ask_spread < BID_ASK_SPREAD:
                Trader.logger.info("BID:  %s - ASK: %s - SPREAD: %.2lf" %
                                   (str(buy_price), str(ask), bid_ask_spread))
                return

            quantity = self.calc_buy_quantity(buy_price)
            try:
                self.validate(quantity, buy_price)
                self.order_id = self.buy(quantity, buy_price)
            except Exception as e:
                Trader.logger.exception(e)
                Trader.logger.info("An error occurred during buying.")
                Trader.logger.debug("Releasing the buying lock...")
                self.buying_lock_acquired = False
                Trader.buying_lock.release()

        elif status == 'new' or status == 'partially_filled':
            if status == 'new':
                if not self.order_wait_start_time:
                    self.order_wait_start_time = time.time()
                if not self.timeout(self.order_wait_start_time,
                                    order_type='new'):
                    return

            if status == 'partially_filled':
                if not self.partially_filled_wait_start_time:
                    self.partially_filled_wait_start_time = time.time()
                if not self.timeout(self.partially_filled_wait_start_time):
                    Trader.logger.info(
                        "Partially filled. Waiting for order to be filled...")
                    return
                else:
                    Trader.logger.info("Waiting for order timed out.")

            ask = self.calc_sell_price()
            bid_ask_spread = 100. * (ask / self.last_buy_price - 1)

            price_range = self.calc_price_range(side='buy',
                                                price=self.last_buy_price)
            self.logger.debug("BUY_ACTION: price_range: %s" % str(price_range))
            # if the price is not in range, cancel and try to place an order again
            if self.last_buy_price > price_range[
                    0] or self.last_buy_price < price_range[
                        1] or bid_ask_spread < BID_ASK_SPREAD:
                try:
                    self.cancel(self.order_id)
                except Exception as e:
                    Trader.logger.exception(e)

    def sell_action(self, status=None):
        self.logger.info("*** SELL ACTION ***")
        sell_price = self.calc_sell_price()
        quantity = self.calc_sell_quantity()
        profitable_price = self.calc_profitable_price()

        if not status or status == 'filled' or status == 'cancelled' or status == 'cancelled_partially_filled':
            if status == 'filled' or status == 'cancelled_partially_filled':
                self.partially_filled_wait_start_time = None
                self.order_wait_start_time = None
                Trader.buy_prices_lock.acquire()
                Trader.logger.debug("Appending price %s to buy_prices" %
                                    (str(self.last_buy_price)))
                Trader.logger.debug("buy_prices: %s" % str(Trader.buy_prices))
                Trader.buy_prices.append(self.last_buy_price)
                Trader.logger.debug("buy_prices: %s" % str(Trader.buy_prices))
                Trader.buy_prices_lock.release()
                Trader.logger.debug("Releasing buying lock...")
                try:
                    Trader.buying_lock.release()
                except Exception as e:
                    Trader.logger.exception(e)
                else:
                    self.buying_lock_acquired = False
            self.order_id = -1
            Trader.analyzed_data_lock.acquire()
            sell_now = Trader.analyzed_data.sell_now
            Trader.analyzed_data_lock.release()

            if self.is_stoploss(sell_price):
                Trader.logger.info("Stop loss.")
                self.stoploss_triggered = True

            if not sell_now and not self.stoploss_triggered:
                Trader.logger.info("waiting for sell signal.")
                return

            if self.stoploss_triggered:
                loss_perc = 100 * (1 - sell_price / float(self.last_buy_price))
                if loss_perc <= STOPLOSS_PERCENTAGE and not sell_now:
                    Trader.logger.info("Stop loss: waiting for sell signal.")
                    return
                if loss_perc <= STOPLOSS_PERCENTAGE or loss_perc >= IMMEDIATELY_STOPLOSS_PERCENTAGE:
                    Trader.logger.info("Selling at %.2lf percent loss." %
                                       loss_perc)
                    quantity = self.calc_sell_quantity()
                else:
                    return
            elif self.is_profitable(sell_price):
                Trader.logger.info(
                    "The profit is %.2lf. Try to sell it. Least profitable_price is %.8lf."
                    % (self.calc_profit(sell_price), profitable_price))
            else:
                Trader.logger.info("Least profitable_price is %.8lf." %
                                   (profitable_price))
                return
            try:
                self.validate(quantity, sell_price)
                self.order_id = self.sell(quantity, sell_price)
            except Exception as e:
                Trader.logger.exception(e)
                if status == 'cancelled_partially_filled':
                    raise
                Trader.logger.error(
                    "Cannot sell. Please handle it manually. Exiting...")
                sys.exit(1)

        elif status == 'new' or status == 'partially_filled':
            if status == 'new':
                if not self.order_wait_start_time:
                    self.order_wait_start_time = time.time()
                if not self.timeout(self.order_wait_start_time,
                                    order_type='new'):
                    return

            if status == 'partially_filled':
                if not self.partially_filled_wait_start_time:
                    self.partially_filled_wait_start_time = time.time()
                if not self.timeout(self.partially_filled_wait_start_time):
                    Trader.logger.info("Waiting for order to be filled...")
                    return
                else:
                    Trader.logger.info("Waiting for filled order timed out.")

            price_range = self.calc_price_range(price=self.last_sell_price,
                                                side='sell')
            self.logger.debug(
                "SELL_ACTION: last_sell: %s - sell_price: %s - price_range: %s"
                %
                (str(self.last_sell_price), str(sell_price), str(price_range)))
            # cancel order that's not profitable anymore
            if self.last_sell_price < price_range[
                    0] or self.last_sell_price > price_range[1]:
                try:
                    self.cancel(self.order_id)
                except Exception as e:
                    Trader.logger.exception(e)
                    Trader.logger.info(
                        "Cannot cancel order #%s. Maybe it has already fully filled."
                        % str(self.order_id))

    def trade(self):
        """
        Trading logic
        """
        name = threading.currentThread().getName()
        self.logger.info("%s starting...", name)
        self.update_balance(name,
                            initial_amount=INITIAL_AMOUNT,
                            first_time=True)
        while True:
            # make a copy of exchange data
            Trader.exchange_data_lock.acquire()
            self.exchange_data = Trader.exchange_data
            Trader.exchange_data_lock.release()
            if self.order_id == 0:
                self.buy_action()
            elif self.order_id == -1:
                self.sell_action()
            else:
                Trader.db_lock.acquire()
                order_data = Trader.database.order_read(self.order_id)
                Trader.db_lock.release()
                if not order_data:
                    Trader.logger.info(
                        "Waiting for order data to be available... Sleeping for a while..."
                    )
                    time.sleep(CHECK_ORDER_WAIT_TIME)
                else:
                    order_data = DictMap(order_data)
                    if order_data.status == 'NEW' and order_data.side == 'BUY':
                        self.buy_action(status='new')
                    elif order_data.status == 'NEW' and order_data.side == 'SELL':
                        self.sell_action(status='new')
                    elif order_data.status == 'FILLED' and order_data.side == 'BUY':
                        self.update_balance(
                            name,
                            executed_quantity=order_data.executed_quantity,
                            price=order_data.price,
                            side='BUY')
                        self.sell_action(status='filled')
                    elif order_data.status == 'FILLED' and order_data.side == 'SELL':
                        self.update_balance(
                            name,
                            executed_quantity=order_data.executed_quantity,
                            price=order_data.price,
                            side='SELL')
                        self.buy_action(status='filled')
                    elif order_data.status == 'PARTIALLY_FILLED' and order_data.side == 'BUY':
                        self.buy_action(status='partially_filled')
                    elif order_data.status == 'PARTIALLY_FILLED' and order_data.side == 'SELL':
                        self.sell_action(status='partially_filled')
                    elif order_data.status == 'CANCELED':
                        #if the order was cancelled and executed_quantity is 0, handle it as a normal case
                        if float(order_data.executed_quantity) == 0.0:
                            if order_data.side == 'BUY':
                                self.buy_action()
                            else:
                                self.sell_action()
                        # buy all with the current amount
                        # if the amount is not enough, sell more
                        else:
                            self.update_balance(
                                name,
                                executed_quantity=order_data.executed_quantity,
                                price=order_data.price,
                                side=order_data.side)
                            Trader.db_lock.acquire()
                            current_amount = float(
                                Trader.database.trader_read(
                                    name, key='current_amount')['pairs']
                                ['current_amount'])
                            current_quantity = float(
                                Trader.database.trader_read(
                                    name, key='current_quantity')['pairs']
                                ['current_quantity'])
                            Trader.db_lock.release()
                            if current_quantity * float(
                                    order_data.price) > float(
                                        Trader.symbol_info.filters[2]
                                        ['minNotional']):
                                if order_data.side == 'BUY':
                                    self.sell_action(
                                        status='cancelled_partially_filled')
                                else:  # sell more when the selling order was partially filled
                                    self.sell_action()
                            else:
                                try:
                                    self.buy_action(
                                        status='cancelled_partially_filled')
                                except:
                                    Trader.logger.info(
                                        'Order was partially filled. Unable to buy or sell. Please handle it manually.'
                                    )
                                    Trader.logger.info('%s exits now...' %
                                                       name)
                                    sys.exit(1)
            # Only put an order to the queue if its orderId > 0
            if int(self.order_id) > 0:
                Trader.order_queue_lock.acquire()
                Trader.order_queue.put(self.order_id)
                Trader.order_queue_lock.release()

            time.sleep(TRADER_WAIT_TIME)
예제 #41
0
class Interface():
    def __init__(self, parent):
        self.window = Frame(parent)  # Main window frame initialized
        self.window.grid()
        self.container = Frame(
            self.window
        )  # Container window frame initialized - used to clear window
        self.container.grid()
        self.startup()
        self.database = Database("credentials.db")

    def clearWindow(self):
        self.container.grid_forget()
        self.container = Frame(self.window)
        self.container.grid()
        self.errMessage = Message(self.container,
                                  font=('MS', 10),
                                  fg='red',
                                  width="320")
        self.errMessage.config(justify="center")

    def startup(self):

        # Initialized widgets
        lblUsername = Label(self.container, text='Username:'******'MS', 10))
        lblPassword = Label(self.container, text='Password:'******'MS', 10))
        lblRepeat = Label(self.container,
                          text='Repeat Password:'******'MS', 10))
        lblCourse = Label(self.container, text='Your Course:', font=('MS', 10))
        lblOr = Label(self.container, text='or', font=('MS', 10))
        lblID = Label(self.container, text='Student ID:', font=('MS', 10))
        btnLogIn = Button(self.container, text='Log-In', font=('MS', 10))
        btnRegister = Button(self.container, text='Register', font=('MS', 10))
        btnOpenLogIn = Button(self.container,
                              text='Open log-in Form',
                              font=('MS', 10))
        btnOpenReg = Button(self.container,
                            text='Open Registration Form',
                            font=('MS', 10))
        self.errMessage = Message(self.container,
                                  font=('MS', 10),
                                  fg='red',
                                  width="320")
        self.entUsername = Entry(self.container)
        self.entPassword = Entry(self.container, show="*")
        self.entRepeat = Entry(self.container, show="*")
        self.entID = Entry(self.container)
        self.cmbCourse = ttk.Combobox(self.container,
                                      width=17,
                                      state="readonly")

        # Widget configuration
        lblUsername.grid(row=0, column=0, padx=10, pady=5, sticky=E)
        self.entUsername.grid(row=0, column=1, padx=10)
        lblPassword.grid(row=1, column=0, padx=10, pady=5, sticky=E)
        self.entPassword.grid(row=1, column=1)
        btnLogIn.grid(row=2, column=0, columnspan=2, pady=10)
        lblOr.grid(row=3, column=0, columnspan=2, pady=5)
        btnOpenReg.grid(row=4, column=0, columnspan=2, pady=10)
        self.cmbCourse['values'] = ["Computer Science"]
        self.errMessage.config(justify="center")

        def openRegistration():
            self.errMessage.grid_forget()
            btnLogIn.grid_forget()
            btnOpenReg.grid_forget()
            lblRepeat.grid(row=2, column=0, padx=10, pady=5, sticky=E)
            self.entRepeat.grid(row=2, column=1)
            lblID.grid(row=3, column=0, padx=10, pady=5, sticky=E)
            self.entID.grid(row=3, column=1)
            lblCourse.grid(row=4, column=0, padx=10, pady=5, sticky=E)
            self.cmbCourse.grid(row=4, column=1, padx=10)
            btnRegister.grid(row=5, column=0, columnspan=2, pady=10)
            lblOr.grid(row=6, column=0, columnspan=2, pady=5)
            btnOpenLogIn.grid(row=7, column=0, columnspan=2, pady=10)
            self.entUsername.delete(0, END)
            self.entPassword.delete(0, END)

        def openLogIn():
            self.errMessage.grid_forget()
            lblRepeat.grid_forget()
            self.entRepeat.grid_forget()
            btnRegister.grid_forget()
            btnOpenLogIn.grid_forget()
            lblCourse.grid_forget()
            self.cmbCourse.grid_forget()
            lblID.grid_forget()
            self.entID.grid_forget()
            btnLogIn.grid(row=2, column=0, columnspan=2, pady=10)
            lblOr.grid(row=3, column=0, columnspan=2, pady=5)
            btnOpenReg.grid(row=4, column=0, columnspan=2, pady=10)
            self.entUsername.delete(0, END)
            self.entPassword.delete(0, END)
            self.entRepeat.delete(0, END)
            self.entID.delete(0, END)
            self.entPassword.option_clear()

        def tryLogIn():
            if self.logIn():
                self.clearWindow()
                self.createMenu(self.entUsername.get())

        def tryRegister():
            if self.register():
                openLogIn()  # Go back to log-in

        # Widget actions
        btnLogIn['command'] = tryLogIn
        btnRegister['command'] = tryRegister
        btnOpenReg['command'] = openRegistration
        btnOpenLogIn['command'] = openLogIn

    # Function to check user credentials and proceed with logging in when 'log-in' button is pressed.
    # Performs checks on user input.
    def logIn(self):
        username = self.entUsername.get()
        password = self.entPassword.get()

        if len(username) == 0 or len(password) == 0:
            self.errMessage.grid(row=5, columnspan=2)
            self.errMessage.config(text="You must complete all login fields!")
            return False

        if len(password) < 8:
            self.errMessage.grid(row=5, columnspan=2)
            self.errMessage.config(text="Password is at least 8 characters!")
            return False

        if not self.database.getUser(username, password):
            self.errMessage.grid(row=5, columnspan=2)
            self.errMessage.config(text="Invalid username/password.")
            return False

        # User is now logged in
        return True

    # Function to register user when 'register' button is pressed. Performs checks on user input.
    def register(self):
        username = self.entUsername.get()
        password = self.entPassword.get()
        passwordRep = self.entRepeat.get()
        course = self.cmbCourse.get()
        id = self.entID.get()

        # Checks regarding registration fields are made here
        if len(username) == 0 or len(password) == 0 or len(
                passwordRep) == 0 or len(course) == 0 or len(id) == 0:
            self.errMessage.grid(row=8, columnspan=2)
            self.errMessage.config(
                text="You must complete all registration fields!")
            return False

        if self.database.getUsername(username):
            self.errMessage.grid(row=8, columnspan=2)
            self.errMessage.config(text="This username already exists!")
            return False

        if len(password) < 8:
            self.errMessage.grid(row=8, columnspan=2)
            self.errMessage.config(
                text="Password must be 8 character or more!")
            return False

        if password != passwordRep:
            self.errMessage.grid(row=8, columnspan=2)
            self.errMessage.config(text="Passwords do not match!")
            return False

        if len(id) > 8 or not re.findall(r'[Cc][0-9]{7}', id):
            self.errMessage.grid(row=8, columnspan=2)
            self.errMessage.config(text="Invalid Student ID.")
            return False

        # User is registered into the database here
        self.errMessage.grid_forget()
        self.database.addEntry(username, password, course, id)
        messagebox.showinfo(
            "Registered",
            "You have successfully registered! You can now log-in.")
        return True

    def createMenu(self, username):
        for row in self.database.getUserData(username):
            frmCourse = Frame(self.container)
            lblID = Label(self.container,
                          text="Student ID: " + row[2],
                          font=('MS', 10))
            lblCourse = Label(self.container,
                              text="Course: " + row[1],
                              font=('MS', 10))
            lblLesson = Label(frmCourse,
                              text="Choose lesson: ",
                              font=('MS', 10))
            lblOr = Label(frmCourse, text='or', font=('MS', 10))
            cmbCourse = ttk.Combobox(frmCourse, width=17, state="readonly")
            btnSelect = Button(frmCourse, text='Go to Lesson', font=('MS', 10))
            btnHistory = Button(frmCourse,
                                text='View History',
                                font=('MS', 10))

            cmbCourse['values'] = ["Lesson 1", "Lesson 2"]

            # DELETE ME
            def select():
                if len(cmbCourse.get()) == 0:
                    print("You must choose a lesson!")
                    self.errMessage.grid(row=3, columnspan=2)
                    self.errMessage.config(text="You must choose a lesson!")
                    return
                self.clearWindow()
                print("Open Lesson Menu")

            def history():
                self.clearWindow()
                print("Open History Menu")

            btnSelect['command'] = select
            btnHistory['command'] = history

            lblID.grid(row=0, column=0, columnspan=2, sticky=W, padx=5, pady=5)
            lblCourse.grid(row=1, column=0, columnspan=2, sticky=W, padx=5)
            frmCourse.grid(row=2, columnspan=2, pady=20, padx=5)
            lblLesson.grid(row=0, column=0, sticky=W, pady=5)
            cmbCourse.grid(row=0, column=1, sticky=W, pady=5)
            btnSelect.grid(row=1, columnspan=2, pady=5)
            lblOr.grid(row=3, column=0, columnspan=2, pady=10)
            btnHistory.grid(row=4, columnspan=2, pady=5)
예제 #42
0
파일: main.py 프로젝트: Nastya67/ForStudy5
    for el in elems:
        if el:
            res.append(el.replace("(", "").replace(")", "").replace(",", ""))
    if isPlayer == False:
        return [Player(int(res[0]), res[1], int(res[2]))]
    if isPlayer == True:
        return [Command(int(res[0]), res[1], res[2])]
    return None


def getCount(command: str):
    return [int(re.findall(r"(\d+)", command)[0])]


if __name__ == "__main__":
    db = Database()
    db.load()
    dict_create = {
        r"create player (\(\d+, \w+, \d+\), )*\(\d+, \w+, \d+\)": {
            "funk": db.add_player,
            "args": getPlayers
        },
        r"create command (\(\d+, \w+, \w+\), )*\(\d+, \w+, \w+\)": {
            "funk": db.add_command,
            "args": getCommands
        }
    }
    dict_delete = {
        r"delete player (\d+, )*\d+": {
            "funk": db.del_player,
            "args": getIds
예제 #43
0
 def update_user_level(self):
     hm_db = Database(self.id)
     hm_db.connect()
     return "\n<:worrysign10:531221748964786188> New level: **" + str(hm_db.update_level()) +\
            "** <:worrysign10:531221748964786188>"
예제 #44
0
def threadCode(values):

    conf = \
        {"nameOfTheExperiment": "../50_clients_1_threadTWICE",
         "placement": "us-west-2c",
         "databaseType": "m3.large",
         "clientInstances": (1, "m3.large"),
         "middlewareInstances": (1, "m3.large"),
         "databaseUsername": "******",
         "databasePassword": "******",
         "databaseName": "mepas",
         "databasePortNumber": 5432,
         "middlewarePortNumber": 6789,
         "runningTimeInSeconds": 600,
         "threadPoolSize": 1,
         "connectionPoolSize": 1,
         "totalClients": 2,
         "totalQueues": 2,
         "messageSize": 20,
         "mappings": [(0, 0)],
         "clientsData": [(2, 1)],
         "username": "******",

         "variable": "totalClients",
         "values": values}

    for variable in conf["values"]:

        conf[conf["variable"]] = variable
        conf["clientsData"][0] = (variable, 1)
        print conf["clientsData"]

        # you always need one database instance for every experiment
        database = instancesRetriever.createDatabase(conf["databaseType"])

        numberOfClientInstances = conf["clientInstances"][0]
        clientType = conf["clientInstances"][1]

        clientIPs = []
        clients = []
        for i in range(0, numberOfClientInstances):
            inst = instancesRetriever.createClient(clientType)
            clients.append(inst)
            clientIPs.append(
                (inst.ip_address, inst.private_ip_address, inst.instance_type))

        numberOfMiddlewareInstances = conf["middlewareInstances"][0]
        middlewareType = conf["middlewareInstances"][1]

        middlewareIPs = []
        middlewares = []
        for i in range(0, numberOfMiddlewareInstances):
            inst = instancesRetriever.createMiddleware(middlewareType)
            middlewares.append(inst)
            middlewareIPs.append(
                (inst.ip_address, inst.private_ip_address, inst.instance_type))

        databaseIP = (database.ip_address, database.private_ip_address)

        print "IPs of machines that are going to be used"
        print "Database"
        print databaseIP[0] + ": " + databaseIP[
            1] + ":" + database.instance_type
        print "Clients"
        for client in clientIPs:
            print client[0] + ": " + client[2]

        print "Middlewares"
        for middleware in middlewareIPs:
            print middleware[0] + ": " + middleware[2]

        # clean database

        auxiliaryFunctionsFilePath = "../../src/main/resources/auxiliary_functions.sql"
        basicFunctionsFilePath = "../../src/main/resources/read_committed_basic_functions.sql"

        print ">>> Going to clean and initialize database"
        db = Database(databaseIP[0], conf["databasePortNumber"],
                      conf["databaseName"], conf["databaseUsername"],
                      conf["databasePassword"])
        db.recreateDatabase()
        db.initializeDatabase(
            conf["totalClients"], conf["totalQueues"],
            [auxiliaryFunctionsFilePath, basicFunctionsFilePath])
        print ">>> Database was cleaned and initialized!"

        print ">>> Starting CPU, memory and network utilization logging in database"
        db.startLogging(conf["username"]
                        )  # start logging CPU, memory and network utilization
        print ">>> Database logging started"

        # transfer the JAR to the clients & middlewares
        print ">>> transferring executable JAR to clients & middlewares"
        for client in clientIPs:
            scpTo(jarFile, "", conf["username"], client[0])
            print "JAR moved to client with IP: " + client[0]

        for middleware in middlewareIPs:
            scpTo(jarFile, "", conf["username"], middleware[0])
            print "JAR moved to middleware with IP: " + middleware[0]
        print ">>> executable JAR was transferred to the clients & middlewares"

        middlewareInstances = []
        for middlewareIP in middlewareIPs:
            middleware = Middleware(conf["username"], middlewareIP[0],
                                    databaseIP[1], conf["databasePortNumber"],
                                    conf["databaseUsername"],
                                    conf["databasePassword"],
                                    conf["databaseName"],
                                    str(conf["threadPoolSize"]),
                                    str(conf["connectionPoolSize"]),
                                    str(conf["middlewarePortNumber"]))
            print middleware
            middlewareInstances.append(middleware)

        clientInstances = []
        i = 0
        for mapping in conf["mappings"]:
            privateIPOfCorrespondingMiddleware = middlewareIPs[mapping[1]][1]
            client = Client(conf["username"], clientIPs[mapping[0]][0],
                            privateIPOfCorrespondingMiddleware,
                            str(conf["middlewarePortNumber"]),
                            str(conf["clientsData"][i][0]),
                            str(conf["totalClients"]),
                            str(conf["totalQueues"]), str(conf["messageSize"]),
                            str(conf["clientsData"][i][1]),
                            str(conf["runningTimeInSeconds"]))
            clientInstances.append(client)

            i += 1

        # clean the clients & MW from old logs and get the ready for the current experiment
        # assumes file exists "~/logs" in the corresponding machines
        print ">>> going to clean clients ..."
        for client in clientInstances:
            client.clean()
            client.getReady()
        print ">>> clients were cleaned from previous experiments and are ready for the new ones"

        print ">>> going to clean middlewares ..."
        for middleware in middlewareInstances:
            middleware.clean()
            middleware.getReady()
        print ">>> middlewares were cleaned from previous experiments and are ready for the new ones"

        print ">>> middlewares are starting ..."
        for middleware in middlewareInstances:
            middleware.startLogging()
            middleware.start()
        print ">>> middlewares were started"

        now = datetime.datetime.now()
        print ">>> clients are starting ... (" + str(now) + ")"
        for client in clientInstances:
            client.startLogging()
            client.start()
        print ">>> clients were started"

        print ">>> waiting until all clients have finished ..."
        for client in clientInstances:
            while not client.isFinished():
                pass
            client.stopLogging()

        now = datetime.datetime.now()
        print ">>> clients have finished (" + str(now) + ")"

        print ">>> stopping middlewares ..."
        for middleware in middlewareInstances:
            middleware.stop()
            middleware.stopLogging()

        print ">>> middlewares were stopped"

        db.stopLogging(conf["username"])

        # create a directory for the point of the experiment
        experimentPointPath = createPath([conf["nameOfTheExperiment"]],
                                         str(variable))
        os.mkdir(experimentPointPath)

        # save given configuration in the experimentPointPath
        confFile = open(createPath([experimentPointPath], "configuration.csv"),
                        "w")
        w = csv.writer(confFile)
        for key, val in conf.items():
            w.writerow([key, val])
            confFile.flush()

        # gather results and put them back somewhere locally
        print ">>> getting log files from middlewares ..."
        instanceCounter = 1
        for middleware in middlewareIPs:
            localDirectoryResults = experimentPointPath + "/middlewareInstance" + str(
                instanceCounter)
            os.mkdir(localDirectoryResults)
            scpFrom("logs/*", localDirectoryResults, conf["username"],
                    middleware[0])
            instanceCounter += 1
        print ">>> log files from middlewares received"

        print ">>> getting log files from clients ..."
        instanceCounter = 1
        for client in clientIPs:
            localDirectoryResults = experimentPointPath + "/clientInstance" + str(
                instanceCounter)
            os.mkdir(localDirectoryResults)
            scpFrom("logs/*", localDirectoryResults, conf["username"],
                    client[0])
            instanceCounter += 1
        print ">>> log files from clients were received"

        print ">>> getting log files from database ..."
        localDirectoryResults = experimentPointPath + "/database"
        os.mkdir(localDirectoryResults)
        scpFrom("logs/*", localDirectoryResults, conf["username"],
                databaseIP[0])
        print ">>> log files from database received"

        instancesRetriever.terminateInstance(database)
        for client in clients:
            instancesRetriever.terminateInstance(client)

        for middleware in middlewares:
            instancesRetriever.terminateInstance(middleware)
예제 #45
0
    def toggle_user_peace_status(self):
        hm_db = Database(self.id)
        hm_db.connect()

        return hm_db.toggle_peace_status()
예제 #46
0
              YOUTUBE_API_VERSION,
              developerKey=DEVELOPER_KEY)

    try:
        video.youtube_search(y,
                             query="Вашингтон",
                             ChnlId="UCWwCM3cvQjiAecvkph7EyCQ")
        for vidId in video.id_list:
            video_comment_threads = comments.get_threads(y, vidId)
            for thread in video_comment_threads:
                comments.get(y, thread["id"])
            # break
        i = 0  # type: int
        #https://www.youtube.com/watch?v=8W7QkEokCz0

        ODB = Database("Ovechkin")

        ovi_names = [
            u"Алекс", u"Ови", u"Овечкин", u"Овца",
            u"Сан", u"Саш", u"великий", u"Великий",
            u"Барашкин", u"Капитан", u"Овц"
        ]
        while (i != len(comments.authors)):
            ODB.savetodb(comments.authors[i], comments.text[i], ovi_names)
            # print "qty="+i
            i += 1
        ODB.deinit()

    except HttpError, e:
        print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
예제 #47
0
 def find_user(self):
     hm_db = Database(self.id)
     hm_db.connect()
     return hm_db.find_acct()
예제 #48
0
        message = ""
        #Setting up Socket connection
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('0.0.0.0', self.port))

        while True:
            #Waiting for connection
            s.listen(10)
            print("Waiting for a connection...")
            connection, client_address = s.accept()

            #Accepting connection
            print('Connection Accepted from: ' + str(client_address[0]))
            message = connection.recv(1024).decode()
            print("Recieved message: " + message)

            #Send to Database
            self.database.writeRecord(message)

            #Write to file
            with open(self.path, 'a') as f:
                f.write(message + "\n")

            print("Message saved")
            message = ""


#Needs to be an Absolute Path to get proper saving functionality
d = Database("/Users/jd/Documents/Capstone/output.txt")
c = Consumer("/Users/jd/Documents/Capstone/output.txt", 6969, d)
c.consume()
예제 #49
0
 def delete_user(self):
     hm_db = Database(self.id)
     hm_db.connect()
     hm_db.delete_acct()
     return " Deleted account! <a:pepehands:485869482602922021>"
예제 #50
0
    def generate_content(self, df_rec):
        self.df_rec = df_rec
        pptcontent = {}  # dictionary to store all ppt content for a gene
        """Info fields of a gene"""
        Info_rec = self.df_rec[7]
        #Info_rec=variants_dataframe['INFO'][0]
        ''' generating dictionary of info fields '''
        self.Info_dict = self.generate_info_dict(Info_rec)
        """ 
        ###########################################################
        ##################### Generate PPT content ################
        ###########################################################
        """
        """ Presentation Line 1 """
        """ calling function het_homo for subject,mom and dad """
        try:
            sub_hh = str(self.het_homo(self.df_rec[9]))
        except:
            sub_hh = "NA"
        try:
            mom_hh = str(self.het_homo(self.df_rec[10]))
        except:
            mom_hh = "NA"
        try:
            dad_hh = str(self.het_homo(self.df_rec[11]))
        except:
            dad_hh = "NA"
        ''' generating key dictionary by parsing the drill file '''
        key_dictionary = self.generate_key_dictionary()
        ''' getting all necessary values from info dictionary by using 
        parsed dictionary keys from drill file fields '''
        try:
            NCBI_GENE = self.get_dict_value(key_dictionary['NCBI_gene'])
            CAVA_GENE = self.get_dict_value(key_dictionary['CAVA_GENE'])
            CAVA_CSN = self.get_dict_value(key_dictionary['CAVA_CSN'])
            CAVA_LOC = self.get_dict_value(key_dictionary['CAVA_LOC'])
            CAVA_IMPACT = self.get_dict_value(key_dictionary['CAVA_IMPACT'])
            Phenotype = self.get_dict_value(key_dictionary['OMIM_Phenotypes'])
            ExAC_AC = self.get_dict_value(key_dictionary['ExAC_AC'])
            ExAC_AN_Adj = self.get_dict_value(key_dictionary['ExAC_AN_Adj'])
            ExAC_AC_Hom = self.get_dict_value(key_dictionary['ExAC_AC_Hom'])
            ExAC_AF_popmax = self.get_dict_value(
                key_dictionary['ExAC_AF_POPMAX'])
            ExAc_popmax = self.get_dict_value(key_dictionary['ExAC_POPMAX'])
            gnomAD_AC = self.get_dict_value(key_dictionary['gnomAD_AC'])
            gnomAD_Ex_AN_raw = self.get_dict_value(
                key_dictionary['gnomAD_EX_AN_raw'])
            gnomAD_Ex_Hom = self.get_dict_value(
                key_dictionary['gnomAD_EX_Hom'])
            gnomAD_AF_popmax = self.get_dict_value(
                key_dictionary['gnomAD_AF_POPMAX'])
            gnomAD_EX_popmax = self.get_dict_value(
                key_dictionary['gnomAD_EX_POPMAX'])
            Clinvar_significance = self.get_dict_value(
                key_dictionary['Clinvar_significance'])
            Clinvar_measureset = self.get_dict_value(
                key_dictionary['Clinvar_measureset'])
            Clinvar_transcipt = self.get_dict_value(
                key_dictionary['Clinvar_transcript'])
            Clinvar_protein = self.get_dict_value(
                key_dictionary['Clinvar_protein'])
            HGMD_pub = self.get_dict_value(key_dictionary['HGMD_Pubmed'])
            HGMD_dna = self.get_dict_value(key_dictionary['HGMD_DNA'])
            #HGMD_gene=self.get_dict_value(key_dictionary['HGMD_GENE'])
            #HGMD_PROT=self.get_dict_value(key_dictionary['HGMD_PROT'])
            Sift = self.get_dict_value(key_dictionary['dbNSFP_Sift'])
            Polyphen = self.get_dict_value(key_dictionary['dbNSFP_Polyphen'])
            #Metalr=self.get_dict_value(key_dictionary['dbNSFP_Metalr'])
            Mutationtaster = self.get_dict_value(
                key_dictionary['dbNSFP_Mutationtaster'])
            #Vest3=self.get_dict_value(key_dictionary['dbNSFP_Vest3Score'])
            ensemble_id = self.get_dict_value(
                key_dictionary['HGNC_ensemble_id'])
            entrez_id = self.get_dict_value(key_dictionary['HGNC_entrez_id'])
            omim_id = self.get_dict_value(key_dictionary['HGNC_omim_id'])
            #ucsc_id=self.get_dict_value(key_dictionary['HGNC_ucsc_id'])
            #HGNC_location=self.get_dict_value(key_dictionary['HGNC_location'])
            uniprot_id = self.get_dict_value(
                key_dictionary['HGNC_uniprot_ids'])
            Phenotype_list = self.get_dict_value(key_dictionary['HPO_term'])
        except:
            raise Exception(
                "In valid keys ,Check drill_file_fields.txt in /config")

        if Clinvar_transcipt == Clinvar_protein == "NA":
            #warnings.warn(" WARNING !!!! : using CAVA Protein,transcript not clinvar ")
            tran = CAVA_CSN.split("_")[0]
            try:
                prot = CAVA_CSN.split("_")[1]
            except:
                prot = "NA"
        else:
            tran, prot = Clinvar_transcipt, Clinvar_protein

        location = CAVA_LOC

        if dad_hh == mom_hh == "NEG":
            pptcontent['Gene'] = str(NCBI_GENE + " , " + sub_hh + " , " +
                                     tran + " , " + prot + " , [DENOVO] " +
                                     " Dad is : " + dad_hh + " , " +
                                     "Mom is : " + mom_hh)
        else:
            pptcontent['Gene'] = str(NCBI_GENE + " , " + sub_hh + " , " +
                                     tran + " , " + prot + " , " +
                                     " Dad is : " + dad_hh + " , " +
                                     "Mom is : " + mom_hh)
        """ Presentation Line 2 """
        pptcontent['Disease'] = str(" & ".join(self.clean_pheno(Phenotype)))
        """ Presentation Line 3 """
        if ExAC_AC == ExAC_AN_Adj == ExAC_AC_Hom == ExAC_AF_popmax == ExAc_popmax == "NA":
            Exac_string = "ExAC => Not reported"
        else:
            Exac_string = str("ExAC =>  " + ExAC_AC + "/" + ExAC_AN_Adj +
                              " (" + ExAC_AC_Hom + " hom ;" +
                              self.clean_exac_val(ExAC_AF_popmax) + "% " +
                              ExAc_popmax + ")")
        if gnomAD_AC == gnomAD_Ex_AN_raw == gnomAD_Ex_Hom == gnomAD_AF_popmax == gnomAD_EX_popmax == "NA":
            gnomAD_string = "gnomAD => Not reported"
        else:
            gnomAD_string = str("gnomAD => " + gnomAD_AC + "/" +
                                gnomAD_Ex_AN_raw + " (" + gnomAD_Ex_Hom +
                                " hom;" +
                                self.clean_exac_val(gnomAD_AF_popmax) + "% " +
                                gnomAD_EX_popmax + ")")
        pptcontent['Exac'] = Exac_string + " , " + gnomAD_string
        """ Presentation Line 4 """
        if Clinvar_significance == Clinvar_measureset == HGMD_pub == HGMD_dna == "NA":
            pptcontent['Clinvar'] = str(
                "ClinVar => Not reported , HGMD => Not reported")
        elif Clinvar_significance == Clinvar_measureset == "NA":
            pptcontent['Clinvar'] = str("ClinVar => Not reported" +
                                        "  , HGMD => PMID: " + HGMD_pub +
                                        ", DNA: " + HGMD_dna)
        elif HGMD_pub == HGMD_dna == "NA":
            pptcontent['Clinvar'] = str("ClinVar => " + Clinvar_significance +
                                        " , ID: " + Clinvar_measureset +
                                        "  , HGMD => Not reported")
        else:
            pptcontent['Clinvar'] = str("ClinVar => " + Clinvar_significance +
                                        " , ID: " + Clinvar_measureset +
                                        "  , HGMD => PMID: " + HGMD_pub +
                                        ", DNA: " + HGMD_dna)
        """ Presentation Line 5 """
        pptcontent['In_silico'] = str("In silico  =>  SIFT : " + Sift +
                                      "  ,  Polyphen : " + Polyphen +
                                      " , Mutation Taster Pred : " +
                                      "".join(Mutationtaster) +
                                      "  ,  CAVA_IMPACT : " + CAVA_IMPACT)
        """ Presentation Line 6 """
        pptcontent['Loc'] = str("Location =>  " +
                                location)  #+" ,  Region => NA")
        """ URLS """
        #Cid="ENSG00000144554"
        #Entrez_id="2177"
        #Uniport_id="Q9BXW9"

        exac_url = str("http://exac.broadinstitute.org/gene/" + ensemble_id)
        ncbi_url = str("https://www.ncbi.nlm.nih.gov/gene/" + entrez_id)
        uniprot_url = str("http://www.uniprot.org/uniprot/" + uniprot_id)
        marrvel_url = str("http://marrvel.org/search/gene/" + CAVA_GENE)
        genecards_url = str(
            "http://www.genecards.org/cgi-bin/carddisp.pl?gene=" + CAVA_GENE)
        if Clinvar_measureset != "NA":
            clinvar_url = str(
                "https://www.ncbi.nlm.nih.gov/clinvar/variation/" +
                Clinvar_measureset)
            pptcontent['clinvar_url'] = clinvar_url
        else:
            pptcontent['clinvar_url'] = "NA"
        if HGMD_pub != "NA":
            hgmd_pub_url = str("http://www.ncbi.nlm.nih.gov/pubmed/?term=" +
                               HGMD_pub)
            pptcontent['hgmd_pub_url'] = hgmd_pub_url
        else:
            pptcontent['hgmd_pub_url'] = "NA"
        if omim_id != "NA":
            omim_url = str("https://www.omim.org/entry/" + omim_id +
                           "?search=" + omim_id + "&highlight=" + omim_id)
            pptcontent['omim_url'] = omim_url
        else:
            pptcontent['omim_url'] = "NA"
        '''
        ##########################################################
        ############# Searching DB for gene ######################
        ##########################################################
        '''
        #dirs=os.getcwd().split("\\")
        #home=str(dirs[0]+"\\"+dirs[1])
        db_path = os.path.join(self.database_path, "GENE_DB.db")
        db = Database(db_path)
        #rec=(("ANKRD2","NA","NA"),("FANCD2","NA","NA"),("RUNX1","NA","NA"),("NEFL","NA","NA"),("AMNCD1","NA","NA"),("NEFL2","NA","NA"),("NEFL7","NA","NA"))
        table_name = "Gene_table"
        table_cols = [
            "GENE_SYM:text:PRIMARY KEY", "Entrez_summary:text:",
            "Uniprot_summary:text:", "Exac_table:text:"
        ]
        db.create_table(table_name, table_cols)
        #db.insert_records(rec)
        gene_list = [str(i) for i in db.get_gene_list()]
        Cgene = NCBI_GENE
        if Cgene in gene_list:
            print " ===>    Gene found in Database \n"
            summaries = db.get_records(Cgene)
            entrez_summary = str(summaries[1])
            uniprot_summary = str(summaries[2])
            pptcontent['exac_table'] = str(summaries[3])
            #pptcontent['exac_table']="NA"
            db.close_db_connection()
        else:
            """web search for summary exac and entrez summary """
            print " ===>    Fetching gene details from web \n"
            wp = get_web_content(exac_url, ncbi_url, uniprot_url)
            pptcontent['exac_table'] = wp.exac_tab_vals()
            entrez_summary = wp.entrez_gene_summary()
            uniprot_summary = wp.uniprot_gene_summary()
            rec = (Cgene, entrez_summary, uniprot_summary,
                   pptcontent['exac_table'])
            db.insert_records(rec)
            db.db_commit()
            db.close_db_connection()
            print " ===>    Gene details added to DB \n"
        """ Presentation Line 7 """

        pptcontent['entrez_summary'] = str(
            "Entrez Gene Summary / (CAVA_GENE_ID : " + ensemble_id + ")  => " +
            entrez_summary)
        """ Presentation Line 8 """

        pptcontent['uniprot_summary'] = str("Uniprot Gene Summary =>  " +
                                            uniprot_summary)
        """ ADD neceassary URLs of sources """
        pptcontent['exac_url'] = exac_url
        pptcontent['ncbi_url'] = ncbi_url
        pptcontent['uniprot_url'] = uniprot_url
        pptcontent['marrvel_url'] = marrvel_url
        pptcontent['genecards_url'] = genecards_url
        """ adding phenotypes list to ppt content """

        #pheno_list="Bruising_susceptibility,Autosomal_dominant_inheritance,Thrombocytopenia"
        def clean_phenotypes(pheno_list):
            #pheno_list="Motor_delay,Hyporeflexia,Autosomal_dominant_inheritance,Decreased_motor_nerve_conduction_velocity,Areflexia,Myelin_outfoldings,Autosomal_recessive_inheritance,Pes_cavus,Onion_bulb_formation,Juvenile_onset,Segmental_peripheral_demyelination/remyelination,Distal_sensory_impairment,Clusters_of_axonal_regeneration,Heterogeneous,Variable_expressivity,Decreased_number_of_peripheral_myelinated_nerve_fibers,Distal_amyotrophy,Distal_muscle_weakness,Hammertoe,Steppage_gait,Ptosis,Scoliosis,Increased_connective_tissue,Hypotrophy_of_the_small_hand_muscles,Nemaline_bodies,Foot_dorsiflexor_weakness,High_palate,Facial_palsy,Split_hand,Ulnar_claw,Flexion_contracture"
            pheno_items = pheno_list.split(",")
            pheno_items = [re.sub("_", " ", p) for p in pheno_items]
            try:
                dom_recess = [
                    p for p in pheno_items if p.__contains__("dominant")
                    or p.__contains__("recessive")
                ]
                inheritance = [
                    dm for dm in dom_recess if dm.__contains__("Autosomal")
                ]
            except:
                inheritance = "NA"
            try:
                pheno_types = [p for p in pheno_items if p not in inheritance]
            except:
                pheno_types = "NA"
            ''' Inheritance Label '''
            inheritance = "".join(inheritance)
            recessive = inheritance.__contains__("recessive")
            dominant = inheritance.__contains__("dominant")
            if recessive and dominant:
                pptcontent['Inheritance'] = "AD/AR"
            elif dominant:
                pptcontent['Inheritance'] = "AD"
            elif recessive:
                pptcontent['Inheritance'] = "AR"
            else:
                pptcontent['Inheritance'] = "NA"

            pptcontent['phenotype_list'] = pheno_types
            #else:
            #   pptcontent['phenotype_list']=pheno_types[0:14]

        clean_phenotypes(Phenotype_list)
        """
        Capturing Screenshots (disabled) / un-comment below code chunk to enable screen shot capturing
        """
        #img_dir_comm=str("mkdir img")
        #os.popen(img_dir_comm)
        #Cgene="FANCD2"
        #home="h:/rp"
        #screen_shots(Cgene,home) ## triggering screenshot generation by calling screen_shots.py

        return pptcontent
예제 #51
0
    def get_user_peace_cooldown(self):
        hm_db = Database(self.id)
        hm_db.connect()

        return hm_db.get_peace_cooldown()
예제 #52
0
import PySimpleGUI as sg
from User import User
from Database import Database
from Validator import Validator

DB = Database()


class App:
    @staticmethod
    def init():
        message = sg.Text('', key='-TEXT-', size=(30, 2))

        layout = [[sg.Text('Username'), sg.InputText()],
                  [sg.Text('Password'),
                   sg.InputText(password_char='*')],
                  [sg.ReadButton('Register'),
                   sg.Cancel(), message]]

        window = sg.Window('Simple Registration App', layout)
        window.set_icon('icon.ico')
        while True:
            event, values = window.read()
            if event == 'Cancel' or event == None:
                break
            if values and values[0] and values[
                    1]:  # values[0] holds username, values[1] password
                if Validator.is_valid(values[1]):
                    new_user = User(values[0], values[1])
                    try:
                        new_user.add(DB)
예제 #53
0
    def __init__(self, esNueva=True, rowData=None):
        super(QtWidgets.QDialog, self).__init__()
        self.esNueva = esNueva
        self.rowData = rowData
        self.db = Database.getInstance()

        self.productores = self.db.getProductoresList()
        self.personas = self.db.getPersonasList()
        self.autos = self.db.getAutosList(
            None if esNueva else rowData['Auto_id'])
        self.gruposRiesgo = self.db.getGruposRiesgoList()

        self.resize(400, 367)
        self.verticalLayout = QtWidgets.QVBoxLayout(self)
        self.formLayout = QtWidgets.QFormLayout()
        self.productorLabel = QtWidgets.QLabel(self)
        self.productorLabel.setText("Productor")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole,
                                  self.productorLabel)
        self.productorComboBox = QtWidgets.QComboBox(self)
        for productor in self.productores:
            self.productorComboBox.addItem(
                f"{productor['apellido']}, {productor['nombre']}",
                userData=productor['legajo'])
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole,
                                  self.productorComboBox)
        self.conductorLabel = QtWidgets.QLabel(self)
        self.conductorLabel.setText("Conductor")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole,
                                  self.conductorLabel)
        self.conductorComboBox = QtWidgets.QComboBox(self)
        for persona in self.personas:
            self.conductorComboBox.addItem(
                f"{persona['apellido']}, {persona['nombre']}",
                userData=persona['dni'])
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole,
                                  self.conductorComboBox)
        self.autoLabel = QtWidgets.QLabel(self)
        self.autoLabel.setText("Auto")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole,
                                  self.autoLabel)
        self.autoComboBox = QtWidgets.QComboBox(self)
        for auto in self.autos:
            self.autoComboBox.addItem(
                f"id/patente: {auto['id']} - Modelo: {auto['marca']} {auto['nombre']}",
                userData=auto['id'])
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole,
                                  self.autoComboBox)
        self.addAuto = QtWidgets.QPushButton()
        self.addAuto.setText("Agregar Auto")
        self.formLayout.setWidget(3, 1, self.addAuto)
        self.grupoDeRiesgoLabel = QtWidgets.QLabel(self)
        self.grupoDeRiesgoLabel.setText("Grupo de Riesgo")
        self.formLayout.setWidget(4, QtWidgets.QFormLayout.LabelRole,
                                  self.grupoDeRiesgoLabel)
        self.GrupoDeRiesgoCombo = QtWidgets.QComboBox(self)
        for grupoRiesgo in self.gruposRiesgo:
            self.GrupoDeRiesgoCombo.addItem(f"{grupoRiesgo['descripcion']}",
                                            userData=grupoRiesgo['id'])
        self.formLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole,
                                  self.GrupoDeRiesgoCombo)
        self.franquiciaLabel = QtWidgets.QLabel(self)
        self.franquiciaLabel.setText("Franquicia")
        self.formLayout.setWidget(5, QtWidgets.QFormLayout.LabelRole,
                                  self.franquiciaLabel)
        self.franquiciaLineEdit = QtWidgets.QLineEdit(self)
        self.formLayout.setWidget(5, QtWidgets.QFormLayout.FieldRole,
                                  self.franquiciaLineEdit)
        self.validoDesdeLabel = QtWidgets.QLabel(self)
        self.validoDesdeLabel.setText("Válido desde")
        self.formLayout.setWidget(6, QtWidgets.QFormLayout.LabelRole,
                                  self.validoDesdeLabel)
        self.validoDesdeDateEdit = QtWidgets.QDateEdit(self)
        self.validoDesdeDateEdit.setDate(QtCore.QDate.currentDate())
        self.validoDesdeDateEdit.setCalendarPopup(True)
        self.validoDesdeDateEdit.setDisplayFormat("dd-MM-yyyy")
        self.formLayout.setWidget(6, QtWidgets.QFormLayout.FieldRole,
                                  self.validoDesdeDateEdit)

        self.primaLabel = QtWidgets.QLabel(self)
        self.primaLabel.setText("Prima")
        self.formLayout.setWidget(7, QtWidgets.QFormLayout.LabelRole,
                                  self.primaLabel)
        self.primaValue = QtWidgets.QLabel(self)
        self.formLayout.setWidget(7, QtWidgets.QFormLayout.FieldRole,
                                  self.primaValue)

        self.verticalLayout.addLayout(self.formLayout)
        self.buttonBox = QtWidgets.QDialogButtonBox(self)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel
                                          | QtWidgets.QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)

        self.error = QtWidgets.QLabel(self)
        self.verticalLayout.addWidget(self.error)

        self.buttonBox.accepted.connect(self.handleOK)
        self.buttonBox.rejected.connect(self.reject)
        QtCore.QMetaObject.connectSlotsByName(self)

        # signals
        self.conductorComboBox.currentIndexChanged.connect(
            self.actualizarPrima)
        self.autoComboBox.currentIndexChanged.connect(self.actualizarPrima)
        self.GrupoDeRiesgoCombo.currentIndexChanged.connect(
            self.actualizarPrima)
        self.franquiciaLineEdit.textChanged.connect(self.actualizarPrima)
        self.actualizarPrima()

        if (esNueva):
            self.dialogNuevaPoliza()
        else:
            if not rowData:
                self.reject()
            else:
                self.dialogEditarPoliza(rowData)
예제 #54
0
 def add_user(self):
     hm_db = Database(self.id)
     hm_db.connect()
     return " Made account!\nYour starting :moneybag: balance: **$" + str(
         hm_db.insert_acct()) + "**"
예제 #55
0
class AdminWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.table = QTableWidget(self)  # 添加表格对象
        self.database = Database('./data.db')
        self.check_list = []  # 保存所有的选择框
        self.show_password_flag = False  # 是否显示原密码
        self.select_all_flag = False  # 是否选择全部
        self.main_window = None
        self.set_ui()

    def set_main_window(self, widget):
        self.main_window = widget

    def set_ui(self):
        self.setWindowTitle("Management page")
        self.setFixedSize(1200, 900)  # 配合图片大小设定的值
        self.font = QFont("Consolas")
        self.setFont(self.font)
        self.setWindowIcon(QIcon("./IMG/python-logo.png"))  # 设置图标
        self.add_table()  # 添加数据表格
        self.get_all_user()  # add table 之后才有show
        self.add_line_edit()  # 添加输入框
        self.add_label()  # 添加标签
        self.add_button()  # 添加按钮并绑定事件

    # 添加数据表格
    def add_table(self):
        self.table.setFixedWidth(1020)  # 设置宽度
        self.table.setFixedHeight(600)  # 设置高度
        self.table.move(10, 30)  # 设置显示的位置
        self.table.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)  # 自动填充
        self.table.horizontalHeader().setFont(self.font)  # 设置一下字体
        # self.table.setSelectionMode(QAbstractItemView.SingleSelection)  # 只能单选
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)  # 只能选择整行
        self.table.setColumnCount(4)  # 设置列数
        self.table.setHorizontalHeaderLabels(
            ["Choice", "username", "password", 'created_time'])  # 设置首行
        self.table.setEditTriggers(
            QAbstractItemView.NoEditTriggers)  # 表格中的内容设置为无法修改
        self.table.verticalHeader().hide()  # 把序号隐藏
        self.table.setSortingEnabled(False)  # 自动排序

    # 获取所有的用户信息
    def get_all_user(self):
        data = self.database.read_table(
        )  # 从数据库中获取用户信息,用户信息以 username, password, created_time 形式返回
        for user in data:
            self.add_row(user[0], user[1], user[2])

    # 在表格上添加一行新的内容
    def add_row(self, username, password, created_time):
        row = self.table.rowCount()  # 表格的行数
        self.table.setRowCount(row + 1)  # 添加一行表格
        self.table.setItem(row, 1,
                           QTableWidgetItem(str(username)))  # 将用户信息插入到表格中
        self.table.setItem(row, 2, QTableWidgetItem(str(password)))
        self.table.setItem(row, 3, QTableWidgetItem(str(created_time)))
        # 设置复选框
        widget = QWidget()
        check = QCheckBox()
        self.check_list.append(check)  # 添加到复选框列表中
        check_lay = QHBoxLayout()
        check_lay.addWidget(check)
        check_lay.setAlignment(Qt.AlignCenter)
        widget.setLayout(check_lay)
        self.table.setCellWidget(row, 0, widget)

    def add_line_edit(self):
        self.username_edit = QLineEdit(self)
        self.username_edit.setFixedSize(240, 40)
        self.username_edit.move(760, 700)
        self.username_edit.setPlaceholderText('username')

        self.password_edit = QLineEdit(self)
        self.password_edit.setFixedSize(240, 40)
        self.password_edit.move(760, 760)
        self.password_edit.setPlaceholderText('password')
        self.password_edit.setEchoMode(QLineEdit.Password)

        # 更新密码的输入框
        self.update_username_edit = QLineEdit(self)
        self.update_username_edit.setFixedSize(240, 40)
        self.update_username_edit.move(160, 700)
        self.update_username_edit.setPlaceholderText('username')

        self.update_password_edit = QLineEdit(self)
        self.update_password_edit.setFixedSize(240, 40)
        self.update_password_edit.move(160, 760)
        self.update_password_edit.setPlaceholderText('new password')

    def show_password(self):
        if self.show_password_flag:  # 如果是真,隐藏密码
            self.password_edit.setEchoMode(QLineEdit.Password)
            self.show_password_flag = False
            self.show_password_button.setText('Show')
        else:  # 否则显示密码
            self.password_edit.setEchoMode(QLineEdit.Normal)
            self.show_password_flag = True
            self.show_password_button.setText("Hide")

    # 添加界面上的标签控件
    def add_label(self):
        self.username_label = QLabel(self)
        self.username_label.setFixedSize(160, 40)
        self.username_label.move(640, 700)
        self.username_label.setText('username')

        self.password_label = QLabel(self)
        self.password_label.setFixedSize(160, 40)
        self.password_label.move(640, 760)
        self.password_label.setText('password')

        # 更新密码的标签
        self.update_username_label = QLabel(self)
        self.update_username_label.setFixedSize(160, 40)
        self.update_username_label.move(40, 700)
        self.update_username_label.setText('username')

        self.update_password_label = QLabel(self)
        self.update_password_label.setFixedSize(160, 40)
        self.update_password_label.move(40, 760)
        self.update_password_label.setText('password')

    # 添加界面上的按钮控件
    def add_button(self):
        # 创建按钮对象
        self.delete_button = QPushButton(self)
        self.update_button = QPushButton(self)
        self.add_button_ = QPushButton(self)
        self.show_password_button = QPushButton(self)
        self.clear_button = QPushButton(self)
        self.select_all_button = QPushButton(self)
        self.refresh_button = QPushButton(self)
        self.main_window_button = QPushButton(self)

        # 设置按钮上的文本
        self.delete_button.setText("Delete")
        self.update_button.setText("Update")
        self.add_button_.setText("Add")
        self.show_password_button.setText("Show")
        self.clear_button.setText("Clear")
        self.select_all_button.setText("Select All")
        self.refresh_button.setText("Refresh")
        self.main_window_button.setText("Main window")

        # 在按钮上设置提示信息
        self.delete_button.setToolTip(
            "Delete the selected user, you can choose multiple users")
        self.clear_button.setToolTip(
            "Clear all the users, including the super user, but the super user will be "
            "created later by default")
        self.select_all_button.setToolTip(
            "Select all the users, including the super user")
        self.show_password_button.setToolTip("Show or hide the password")
        self.add_button_.setToolTip(
            "Add a new user with the username and password in the input box")
        self.update_button.setToolTip(
            "Update the password with the chosen username")
        self.refresh_button.setToolTip("Click here to refresh the table")
        self.main_window_button.setToolTip(
            "Click here and you will go to the user interface")

        # 控制位置
        self.delete_button.move(1040, 340)
        self.select_all_button.move(1040, 280)
        self.clear_button.move(1040, 400)
        self.refresh_button.move(1040, 460)

        self.update_button.move(430, 700)
        self.add_button_.move(1020, 700)
        self.show_password_button.move(1020, 750)

        self.main_window_button.move(500, 820)

        # 绑定事件
        self.delete_button.clicked.connect(self.delete_user)
        self.select_all_button.clicked.connect(self.select_all)
        self.clear_button.clicked.connect(self.clear)
        self.show_password_button.clicked.connect(self.show_password)
        self.add_button_.clicked.connect(self.add_user)
        self.update_button.clicked.connect(self.update_password)
        self.refresh_button.clicked.connect(self.refresh)
        self.main_window_button.clicked.connect(self.show_main_window)

        self.main_window_button.setFixedSize(200, 40)

    def show_main_window(self):
        self.main_window.show()

    def delete_user(self):
        choose_list = []
        for i in self.check_list:
            if i.isChecked():
                username = self.table.item(self.check_list.index(i), 1).text()
                if username == 'admin':
                    answer = QMessageBox.critical(
                        self, 'Error',
                        'You are going to delete the super user, but it will be created later with the default password',
                        QMessageBox.Yes | QMessageBox.Cancel,
                        QMessageBox.Cancel)
                    if answer == QMessageBox.Yes:
                        choose_list.append(i)
                    if answer == QMessageBox.Cancel:
                        return
                else:
                    choose_list.append(i)

        for i in choose_list:
            username = self.table.item(self.check_list.index(i), 1).text()
            self.database.delete_table_by_username(username)
            self.table.removeRow(self.check_list.index(i))
            self.check_list.remove(i)
        self.database.create_table()

    # 选择是否选择全部
    def select_all(self):
        try:
            if not self.select_all_flag:
                for check in self.check_list:
                    check.setCheckState(2)  # 设置为选择状态
                self.select_all_button.setText("Unselect")
                self.select_all_flag = True
            else:
                for check in self.check_list:
                    check.setCheckState(0)  # 设置为未选状态
                self.select_all_button.setText("Select All")
                self.select_all_flag = False
        except:  # 该错误是由于没有复选框引起
            pass

    # 一行一行的添加数据
    def add_user(self):
        username = self.username_edit.text()
        password = self.password_edit.text()
        if all((username, password)):
            flag = self.database.insert_table(username, password)
            if flag:
                QMessageBox.critical(
                    self, 'Error',
                    'Already exists the username {}, please use another username'
                    .format(username))
            else:
                self.add_row(username, password, self.database.get_time())
            self.username_edit.setText('')  # 清空输入的用户信息
            self.password_edit.setText('')
        else:
            QMessageBox.critical(self, 'Error', "Please fill in the blanks")

    # 清空所有的数据,包括数据库和表格中的数据
    def clear(self):
        self.table.clearContents()  # 清空表格的内容
        self.table.setRowCount(0)  # 将表格的行数重置为0
        self.database.clear()  # 清空数据库数据

    # 更新密码
    def update_password(self):
        username = self.update_username_edit.text()
        password = self.update_password_edit.text()
        if len(password) >= 6:
            self.database.update_table(username, password)
            self.change_table(username, password)
            self.update_password_edit.setText('')
            self.update_username_edit.setText('')
        else:
            QMessageBox.information(self, 'Error',
                                    'Password is too short, at least 6 words',
                                    QMessageBox.Yes, QMessageBox.Yes)

    # 更新表格
    def change_table(self, username, password):
        find_flag = False
        for row in range(self.table.rowCount()):
            username_find = self.table.item(row, 1).text()
            if username_find == username:
                self.table.item(row, 2).setText(password)
                find_flag = True
                break
        if not find_flag:  # 如果没有找到对应的用户名
            QMessageBox.information(
                self, 'prompt',
                'Can not find the username {}'.format(username))

    # 重新加载数据库并显示
    def refresh(self):
        self.table.clearContents()
        self.check_list.clear()
        self.table.setRowCount(0)
        self.database.create_table()
        self.get_all_user()
예제 #56
0
 def update_user_money(self, amount):
     hm_db = Database(self.id)
     hm_db.connect()
     return "Your new account balance: **$" + str(
         hm_db.update_money(amount)) + "**"
    def createUser(self, username=None, getAnotherUserData=False, email=None):

        db = Database()
        if db.connect():
            if email != None:
                #forget password
                sql = "SELECT * FROM `user` WHERE `email` = '" + str(
                    email) + "';"
                db.execute(sql)
                data = db.getCursor().fetchone()

                if data != None:
                    self.__usr = User(data=data,
                                      getAnotherUserData=getAnotherUserData)

            else:
                sql = "SELECT * FROM `user` WHERE `username` = '" + str(
                    username) + "';"
                db.execute(sql)
                data = db.getCursor().fetchone()

                if data != None:
                    self.__usr = User(data=data,
                                      getAnotherUserData=getAnotherUserData)

            db.close()
예제 #58
0
from Database import Database
from menu import Menu

Database.initialize()

menu = Menu()

menu.run_menu()
예제 #59
0
import xbmcgui
import xbmcaddon

import json
import threading
from datetime import datetime
import urllib
from DownloadUtils import DownloadUtils
from Database import Database

_MODE_BASICPLAY = 12
_MODE_ITEM_DETAILS = 17

# define our global download utils
downloadUtils = DownloadUtils()
db = Database()


class RandomInfoUpdaterThread(threading.Thread):

    logLevel = 0
    event = None
    exit = False

    def __init__(self, *args):
        addonSettings = xbmcaddon.Addon(id='plugin.video.xbmb3c')
        level = addonSettings.getSetting('logLevel')
        self.logLevel = 0
        if (level != None):
            self.logLevel = int(level)
예제 #60
0
# 用户数据相关
import pymysql
from Database import Database

database = Database()

_host = database.gethost()
_port = database.getport()
_sql_user = database.getuser()
_sql_password = database.getpassword()
_database = database.getdatabase()


# get username:string,password:string,useremail:string, return id
def register(login_name, username, password, useremail, bio):
    connection = pymysql.connect(_host, _port, _sql_user, _sql_password,
                                 _sql_password)
    # End
    try:
        with connection.cursor() as cursor:
            # Create a new record
            # TODO add sql line in here
            sql1 = "INSERT INTO `Auth` (`login_name`,`password`,`user_email`)  VALUES (%s, %s, %s)"
            cursor.execute(sql1, (login_name, password, useremail))
            sql2 = "INSERT INTO `User` (`user_name`, `bio`) VALUES (%s, %s)"
            cursor.execute(sql2, (username, bio))

        # !connection is not autocommit by default. So you must commit to save
        # your changes.
        connection.commit()
    except Exception as e: