示例#1
0
 def run(self, dispatcher, tracker, domain):
     collection = Database('kb', 'ReqPendientes').collection
     matricula = 20121917
     if matricula:
         query = {"matricula": matricula, 'matricula': {'$exists': True}}
         projection = {
             "matricula": 1,
             "codTema": 1,
             "nombre": 1,
             "creditos": 1
         }
         result = collection.find(query, projection=projection)
         requisitos = [(doc["codTema"], doc["nombre"], doc["creditos"])
                       for doc in result]
         dispatcher.utter_template("utter_requisitos_pendientes",
                                   tracker,
                                   requisitos=requisitos)
     return []
示例#2
0
def make_db(fname,
            skiplines='#',
            readonly=True,
            requiredattrs=('st_dist', 'pl_name', 'st_teff', 'pl_orbeccen',
                           'pl_disc', 'pl_orbper', 'pl_masse', 'st_mass')):
    '''Read in a database from the given file, skipping lines beginning with
    'skiplines'. Checks that the db entries have all attributes in 'requiredattrs'.'''
    db = Database()
    # Needs to be opened in binary mode (on Windows).
    with open(fname, 'rb') as finput:
        db.read_from_csv(
            (line for line in finput if not line.startswith(skiplines)),
            readonly=readonly)
    missingattrs = set(requiredattrs).difference(set(db.Entry.attributes()))
    if missingattrs:
        raise Exception('File ' + fname + ' is missing columns ' +
                        str(list(missingattrs)) + '!')
    return db
示例#3
0
    def run(self, dispatcher, tracker, domain):
        collection = Database('kb', 'CondicionAcademica').collection
        matricula = 20121917
        if matricula:
            query = {"matricula": matricula, 'matricula': {'$exists': True}}
            projection = {
                "condicionAcadActual": 1,
            }
            result = collection.find_one(query, projection=projection)
            if result:
                dispatcher.utter_template(
                    "utter_condicion_academica",
                    tracker,
                    condicion=result['condicionAcadActual'])
            else:
                dispatcher.utter_message("Error interno")

        return []
示例#4
0
 def insere_bibliotecario(self):
     database = Database()
     bibliotecarios = database.db.bibliotecarios
     # dicionário que armazenará os dados da classe e os inserirá no banco.
     bib_inserir = {
         "nome": self.nome,
         "idade": self.idade,
         "cpf": self.cpf,
         "usuario": self.usuario,
         "senha": self.senha
     }
     # inserção no banco de dados.
     try:
         result = bibliotecarios.insert_one(bib_inserir).inserted_id
         print(result)
         return True if result else False
     except ConnectionError:
         print('Servidor indisponível.')
示例#5
0
    def __init__(self):
        ''' Initialization code '''
        self.busy = False
        self.masterMode = False

        #Initialize system components
        self.rfidReader = RFIDReader()
        self.keypad = Keypad()
        self.lcd = LCD()
        self.doorLatch = DoorLatch()
        self.database = Database()

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.server_address = ('192.168.43.206', 8888)
        self.socket.bind(self.server_address)

        self.correct_pin = self.database.getCorrectPin()
        self.entered_pin = ""
示例#6
0
    def Get_ques_ans(self):
        try:
            page = requests.get(
                self.url
            )  # Send request to site for getting source code of their webpage

            if page.status_code == 200:  # To check if it has successfully recieved the source
                # code or particular webpage is present
                content = BeautifulSoup(page.content, "html.parser")
                # Question extraction...................................

                question = []
                for temp in content.find_all("div",
                                             class_="question_text_edit"):
                    temp = temp.get_text()
                    temp = str(temp)
                    temp = temp.lower()
                    question.append(temp)
                # Answers extraction......................................

                answers = []
                for temp in content(
                        "span",
                        class_="rendered_qtext"):  # extract the contents
                    temp = temp.get_text()
                    answers.append(temp)

                for temp in content.find_all("div",
                                             class_="ui_qtext_expanded"):
                    temp = temp.get_text()
                    answers.append(temp)

                db = Database()
                db.StoreToDatabase(question, answers, self.url, 1)

            else:
                print("Cannot connect to website due to " +
                      str(page.status_code) + " error from Quora Site")
                exit(-1)

        except Exception as error:
            print(error)
            print("Something went wrong try again later (Quora Site)")
            exit(-1)
示例#7
0
    def do_submit(self):

        # 输入信息校验
        B_ISBN = self.B_ISBN.text()
        Bs_id = self.Bs_id.text()

        if len(B_ISBN.strip()) < 1:
            self.msg.setText("ISBN不能为空!")
            return

        if len(Bs_id.strip()) < 1:
            self.msg.setText("图书编号不能为空!")
            return

        # 准备登记库存信息SQL
        now_time = datetime.datetime.now()
        Put_in_date = now_time.strftime('%Y-%m-%d')
        Bstate = "在馆"

        sql_str1 = "insert into bookstock (B_ISBN, Bs_id, Put_in_date, Bstate) " \
                  "values ('%s', '%s', '%s', '%s');" % (B_ISBN, Bs_id, Put_in_date, Bstate)

        # 准备登记出入库信息SQL
        sR_id = now_time.strftime('%Y%m%d%H%M%S%f')  # 流水编号
        C_id = Global.C_ID  # 员工号
        S_action = "入库"  # 动作
        Sdate = Put_in_date

        sql_str2 = "insert into stock_regist (sR_id, Bs_id, C_id, S_action, Sdate) " \
                   "values ('%s', '%s', '%s', '%s', '%s');" % (sR_id, Bs_id, C_id, S_action, Sdate)

        # 执行SQL
        db = Database()
        try:
            db.update(sql_str1)
            db.update(sql_str2)
        except Exception as e:
            self.msg.setText("入库失败!{}".format(str(e)))
            return

        # SQL执行成功
        self.hide()
        self.clear()
        QtWidgets.QMessageBox.information(self, "提示", "入库成功!", QtWidgets.QMessageBox.Yes)
示例#8
0
    def updateContact(self):
        db = Database()

        try:
            c = db.conexao.cursor()

            c.execute(
                """
            UPDATE contacts
            SET name = (?), number = (?), email = (?)
            WHERE id = (?)""",
                (self.name, self.number, self.email, self.idContact))

            db.conexao.commit()
            c.close()

            return "Contact succesfuly updated."
        except:
            return "Something went wrong."
示例#9
0
class FileHandler:

    filename = "input/data.in"
    resultfile = "result.out"
    db = Database()

    def __init__(self, database_obj, filename_arg):
        self.filename = filename_arg
        self.db = database_obj
        pass

    # remove new line characters and trims the line
    def streamline(self, input):
        return input.strip()

    def read_File(self):

        line_no = 0
        try:
            with open(self.filename) as file:
                for line in file:
                    line = self.streamline(line)
                    self.db.validate_and_add(line, line_no)
                    line_no = line_no + 1
        except Exception as e:
            print e
            sys.exit(0)

        pass

    def jsonDump(self):
        json_dict = {}
        json_dict["errors"] = self.db.errors

        json_dict["entries"] = self.db.directory

        try:
            with open(self.resultfile, 'w') as fp:
                json.dump(json_dict, fp, indent=2, sort_keys=True)
        except Exception as e:
            print e
            sys.exit(0)
        pass
示例#10
0
 def onSave(self):
     print("save")
     # setup db connection
     sqlite = Database()
     # check if there is record in db or not. if number of records is 0, then insert. otherwise update the existing records
     sql = 'delete from networkinfo'
     sqlite.executeDB(sql)
     i = 0
     for item, value in self.networkInfo.items():
         if self.radioButtonPub[i].state == True:
             sql = 'insert into networkinfo (networkName, subnet, networkType) values ("' + (str)(item) + \
                       '", "' + (str)(value) + \
                       '", "'+'Public")'
         else:
             sql = 'insert into networkinfo (networkName, subnet, networkType) values ("' + (str)(item) + \
                   '", "' + (str)(value) + \
                   '", "' + 'Private")'
         sqlite.executeDB(sql)
     sqlite.closeConn()
示例#11
0
    def __init__(self, site=None, site_id=None, db=None):
        self.__resources = []

        with open(CONFIG_FILE, 'r') as data_file:
            jsonObj = json.load(data_file)

        if site_id != None:
            self.__siteId = site_id

        if site != None:
            self.__siteId = site[0]
            self.__name = site[1]
            self.__description = site[2]
            self.__contact = site[3]
            self.__location = site[4]
            self.__pragma_boot_path = site[5]
            self.__pragma_boot_version = site[6]
            self.__python_path = site[7]
            self.__temp_dir = site[8]
            self.__username = site[9]
            self.__deployment_type = site[10]
            self.__site_hostname = site[11]
            self.__latitude = site[12]
            self.__longitude = site[13]

            if db == None:
                db = Database()
                db.connect()

            for i in range(0, len(jsonObj['RESOURCES'])):
                self.addResource(
                    db,
                    Resource(siteId=self.__siteId,
                             typ=jsonObj['RESOURCES'][i]['parameter'],
                             total=site[14 + i]))

        self.__image_types = []
        self.__connection_types = []
        self.__setConnectionType()
        self.__setImageType()

        self.__beginAvailable = None
        self.__endAvailable = None
示例#12
0
def homePage():
    hash_key = "0"
    filename = "images/template.png"
    if request.method == 'POST':
        try:
            db = Database(db_path)
            hash_key, photo_path = db.selectLast()
            img = Image.open(photo_path)
            img.save("./static/images/car_image.png", "PNG")
            filename = 'images/car_image.png'
            # photo_path = photo_path.replace("\\", "/")
        except:
            print("Couldn't connect to database or load image")

        first_two = hash_key[:2]
        last_two = hash_key[-2:]
        hash_key = hash_key

    return render_template("index.html", hash_key=hash_key, filename=filename)
示例#13
0
    def __init__(self, parent, controller, pages):
        tk.Frame.__init__(self, parent)

        self.database = Database()
        self.label1 = tk.Label(self)
        self.label1.configure(text='Enter the id of the patient to  delete')
        self.label1.pack(padx='20', pady='40', side='top')

        self.backButton = tk.Button(
            self, command=lambda: controller.show_frame(Choices))
        self.backButton.pack(side='top')

        self.patientIdEntry = tk.Entry(self)
        self.IdEntry = tk.StringVar()
        self.patientIdEntry.configure(textvariable=self.IdEntry)
        self.patientIdEntry.pack(side='top')
        self.button2 = tk.Button(self, command=self.deletePatient)
        self.button2.configure(height='2', text='Delete', width='6')
        self.button2.pack(pady='30', side='top')
示例#14
0
def infer(img):
    db = Database()
    db.connect_db()

    result = db.where('status', 'is_my_model=0')
    if (len(result) > 0):
        classifierModel = fileDir + "/batch-represent/models/openface/celeb-classifier.nn4.small2.v1.pkl"
    else:
        classifierModel = fileDir + "/batch-represent/reps/classifier.pkl"

    with open(classifierModel, 'rb') as f:
        if sys.version_info[0] < 3:
            (le, clf) = pickle.load(f)
        else:
            (le, clf) = pickle.load(f, encoding='latin1')

    alignedFace = preProcess(img, True)

    scriptPath = '/home/hamid/CP/final project/faceRecognition-backend/image_processing_core/batch-represent/src/main.lua'
    dataPath = '/home/hamid/CP/final project/faceRecognition-backend/uploads/preprocessed'
    returned_output = subprocess.check_output(
        ['luajit', scriptPath, '-outDir', 'out', '-data', dataPath, '-infer'])

    rep = confineVectorData(returned_output)
    rep = np.asarray(rep, dtype=np.float32)

    # rep = net.forward(alignedFace)
    # # TODO what is it for?
    # reshapedRep = rep.reshape(1, -1)

    print(rep)

    predictions = clf.predict_proba(rep).ravel()
    maxI = np.argmax(predictions)
    person = le.inverse_transform(maxI)
    confidence = predictions[maxI]

    # print ("RESULT__d-prsn__" + person.decode('utf-8') + "__d-conf__{:.2f}".format(confidence))
    print("RESULT__d-prsn__" + person + "__d-conf__{:.2f}".format(confidence))

    if isinstance(clf, GMM):
        dist = np.linalg.norm(rep - clf.means_[maxI])
        print("  + Distance from the mean: {}".format(dist))
def step3_generate_minute_data():

    db = Database()
    available_currency_list = db.get_available_currency_list()

    for currency in available_currency_list:
        count = 0
        print currency
        for day in db.db[currency].find():
            count = count + 1
            #if not ("minute_price_high" in day):
            date = str(day["date"])
            minute_dict = [{
                "minute_count": index,
                "first": 0,
                "high": 0,
                "low": 9999,
                "last": 0,
                "tick_count": 0,
                "seconds_data": []
            } for index in range(0, 1440)]
            for tick in day["timeline"]:
                current_minute = (tick["unix_time"] - day["unix_time"]) / 60
                if current_minute >= 1440:
                    continue
                if tick["price"] > minute_dict[current_minute]["high"]:
                    minute_dict[current_minute]["high"] = tick["price"]
                if tick["price"] < minute_dict[current_minute]["low"]:
                    minute_dict[current_minute]["low"] = tick["price"]
                if minute_dict[current_minute]["first"] == 0:
                    minute_dict[current_minute]["first"] = tick["price"]
                minute_dict[current_minute]["last"] = tick["price"]
                minute_dict[current_minute]["tick_count"] = minute_dict[
                    current_minute]["tick_count"] + 1
                minute_dict[current_minute]["seconds_data"].append({
                    "price":
                    tick["price"],
                    "unix_time":
                    tick["unix_time"]
                })
            day["minute_price"] = minute_dict
            db.db[currency].update({"date": day["date"]}, day, False)
            print count
示例#16
0
def getWindows(room):
    db = Database()
    cursor = db.getCursor()
    windows = []
    cursor.execute(
        '''
	SELECT 
		name as name,
		ipaddress as ipaddress,
		upcommand as upcommand,
		downcommand as downcommand,
		stopcommand as stopcommand
	FROM window
	WHERE room_id=:room_id
	''', {'room_id': room.getId()})
    for row in cursor:
        windows.append(Window(row, room))

    return windows
示例#17
0
    def __init__(self, config, version):
        self.configuration = config
        self.memory = {}
        self.memory['nick'] = config['nick']
        self.version = version

        # A place to keep track of the plugins with various bot functions
        # Keys are each function, values are the name of the plugins with that function
        function_list = [
            'action', 'connectionMade', 'kickedFrom', 'names', 'signedOn',
            'joined', 'on_ctcp', 'userJoined', 'userKicked', 'modeChanged',
            'userRenamed', 'userLeft', 'privmsg', 'userQuit', 'topicUpdated'
        ]

        self.users = UserDatabase(self, User, 'users/')
        self.groups = Database(self, Group, 'groups/')
        self.channels = ChannelDatabase(self, Channel)
        self.plugins = PluginDatabase(self, function_list)
        self.plugins.loadAll()
示例#18
0
 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()
示例#19
0
 def NeedToRebuildPackage(self, username, projectname, packagename,
                          branchname, distro, release, arch):
     result = True
     con = Database(self.config)
     cursor = con.execute(
         "SELECT * FROM package WHERE username = ? AND projectname = ? AND packagename = ? AND branchname = ?",
         (username, projectname, packagename, branchname))
     row = cursor.fetchone()
     if row is not None:
         packageid = row['id']
         stmt = "SELECT dirty FROM packagebuildstatus WHERE packageid = ? AND distro = ? AND release = ? AND arch = ? AND dirty = 0"
         cursor = con.execute(stmt, (packageid, distro, release, arch))
         row = cursor.fetchone()
         if row is not None:
             print(" no need to rebuild " + packagename + " " +
                   str(packageid))
             result = False
     con.close()
     return result
示例#20
0
    def __init__(self, password):
        super(LoginForm, self).__init__()

        self.username = QLineEdit(self)
        self.password = QLineEdit(self)
        login_btn = QPushButton('Login')
        create_accnt_btn = QPushButton('Create Account')

        mainlayout = QFormLayout()
        mainlayout.addRow(QLabel('Username:'******'Password:'******'root', root_passwd, 'usersdb')
示例#21
0
    def run(self, dispatcher, tracker, domain):
        collection = Database('kb', 'Calificaciones').collection
        letra = str(tracker.get_slot('calificacion')).upper()
        matricula = int(tracker.get_slot('matricula'))
        if matricula and letra:
            query = {
                "matricula": matricula,
                "calificacion": letra,
            }
            projection = {
                "calificacion": 1,
            }
            result = collection.find(query, projection=projection).count()
            if result:
                dispatcher.utter_message("Usted ha obtenido {0}".format(result))
            else:
                dispatcher.utter_message("Usted no ha obtenido ninguna")

        return []
示例#22
0
 def leaveGroup(self, email):
     db = Database()
     flag = self.showMyGroups(email)
     if (flag == False):
         return
     print("|---------------------------------|")
     print("         Leaving group             ")
     print("|---------------------------------|")
     group = input("\n Enter the name of the group you want to leave : ")
     if group in db.my_groups(email):
         db.leave_group(group, email)
         clear()
         print("|---------------------------------|")
         print("     You have left the group ")
         print("|---------------------------------|")
     else:
         print("|---------------------------------|")
         print("      Not a valid group name           ")
         print("|---------------------------------|")
示例#23
0
def deleteWord():
    check = False
    if(request.method=='POST'):
       try:
            id_word = request.form['idword']
            thaiword = request.form['thaiword']
            userID = request.form['userID']
            print(id_word)
            print(thaiword)
            print(userID)

            dd = Database()
            dd.deleteWord(userID,id_word,thaiword)
            check = True
       except Exception as e:
            print(e)
            print("error in delete funtion deleteword")
            return jsonify({'state': False})
    return jsonify({'state':check})
示例#24
0
def main(auto):
    os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (500, 30)
    _ = (Map1, Map2, Map3, Map4)
    walls, trophies, parkings, crosswalks, traffic_signs, car = Map1
    lidar = LiDAR()
    control = Control()
    database = Database(lidar, control, car)
    # Get LiDAR data, Set Control data
    brain = Brain(database)
    # Get Control data Set LiDAR data
    game = Game(walls, trophies, parkings, crosswalks, traffic_signs, car,
                database)
    if auto:
        brain_thread = threading.Thread(target=brain.run, )
        brain_thread.start()
    game.run(auto=auto)
    pygame.quit()

    return 0
示例#25
0
    def do_submit(self):

        # 输入信息校验
        Bs_id = self.Bs_id.text()
        if len(Bs_id.strip()) < 1:
            self.msg.setText("图书编号不能为空!")
            return

        # 查询是否有该图书
        sql_str = "select * from bookstock where Bs_id = '%s';" % Bs_id
        db = Database()
        book = db.query(sql_str).fetchone()
        if book is None:
            QtWidgets.QMessageBox.information(self, "提示", "不存在该编号的图书!",
                                              QtWidgets.QMessageBox.Yes)
            return

        # 准备删除登记库存信息SQL
        sql_str1 = "delete from bookstock where Bs_id = '%s';" % Bs_id

        # 准备登记出入库信息SQL
        now_time = datetime.datetime.now()
        sR_id = now_time.strftime('%Y%m%d%H%M%S%f')  # 流水编号
        C_id = Global.C_ID  # 员工号
        S_action = "出库"  # 动作
        Sdate = now_time.strftime('%Y-%m-%d')

        sql_str2 = "insert into stock_regist (sR_id, Bs_id, C_id, S_action, Sdate) " \
                   "values ('%s', '%s', '%s', '%s', '%s');" % (sR_id, Bs_id, C_id, S_action, Sdate)

        # 执行SQL
        try:
            db.update(sql_str1)
            db.update(sql_str2)
        except Exception as e:
            self.msg.setText("出库失败!{}".format(str(e)))
            return

        # SQL执行成功
        self.hide()
        self.clear()
        QtWidgets.QMessageBox.information(self, "提示", "出库成功!",
                                          QtWidgets.QMessageBox.Yes)
示例#26
0
def change_master_password():
    db = Database()
    new_master_password = "******"
    confirm_new_master_password = "******"
    try:
        while (new_master_password != confirm_new_master_password):
            print_header("Changing Master Password")
            new_master_password = input("Input the new master password:"******"Confirm the new master password:"******"The passwords do not correspond. Retry")
                continue
    except (KeyboardInterrupt, EOFError) as e:
        os.system("clear")
        print_error("Aborted")
        return 1
    db.update_masterpassword(new_master_password)
    return new_master_password
示例#27
0
 def test_BasicAuthentication(self):
     db = Database()
     db.Initialize()
     username = '******'
     password = '******'
     authentications = [BasicAuthentication(username, password)]
     reqp = RequestParameter(db, authentications)
     http_method = 'GET'
     endpoint = 'test'
     params = reqp.Get(http_method, endpoint)
     print(params)
     self.assertTrue('headers' in params)
     self.assertTrue('Time-Zone' in params['headers'])
     self.assertTrue('Accept' in params['headers'])
     self.assertEqual(params['headers']['Time-Zone'], 'Asia/Tokyo')
     self.assertEqual(params['headers']['Accept'],
                      'application/vnd.github.v3+json')
     self.assertTrue('auth' in params)
     self.assertEqual(params['auth'], (username, password))
示例#28
0
 def run(self, dispatcher, tracker, domain):
     collection = Database('kb', 'ReqCursados').collection
     matricula = int(tracker.get_slot("matricula"))
     if matricula:
         query = {"matricula": matricula, 'matricula': {'$exists': True}}
         projection = {
             "matricula": 1,
             "asignatura": 1,
             "nombre": 1,
             "creditos": 1,
             "calificacion": 1
         }
         result = collection.find(query, projection=projection)
         requisitos = [(doc["asignatura"], doc["nombre"], doc["creditos"],
                        doc["calificacion"]) for doc in result]
         dispatcher.utter_template("utter_requisitos_cursados",
                                   tracker,
                                   requisitos=requisitos)
     return []
示例#29
0
    def store(self, DeleteLogAfterDays, KeepMinimumLogs, logpath):
        if self.buildid != -1:
            # store buffered lines to the database
            con = Database(self.config)
            stmt = "INSERT INTO log(buildid, line) VALUES(?,?)"
            for line in self.linebuffer:
                con.execute(stmt, (self.buildid, line))
            self.linebuffer = []
            con.commit()
            con.close()

        LogPath = self.logspath + "/" + logpath
        if not os.path.exists(LogPath):
            os.makedirs(LogPath)
        buildnumber = 0
        MaximumAgeInSeconds = time.time() - (DeleteLogAfterDays * 24 * 60 * 60)
        logfiles = []
        for file in os.listdir(LogPath):
            if file.endswith(".log"):
                logfiles.append(file)
                oldnumber = int(file[6:-4])
                if oldnumber >= buildnumber:
                    buildnumber = oldnumber + 1
        logfiles = sorted(logfiles)
        if len(logfiles) > KeepMinimumLogs:
            for i in range(1, len(logfiles) - KeepMinimumLogs):
                file = logfiles[i - 1]
                # delete older logs, depending on DeleteLogAfterDays
                if os.path.getmtime(LogPath + "/" +
                                    file) < MaximumAgeInSeconds:
                    os.unlink(LogPath + "/" + file)
        LogFilePath = LogPath + "/build-" + (
            str(buildnumber).zfill(6)) + ".log"
        self.print("This build took about " +
                   str(int((time.time() - self.starttime) / 60)) + " minutes")
        try:
            with open(LogFilePath, 'ab') as f:
                f.write(self.get().encode('utf8'))
        except:
            print("Unexpected error:", sys.exc_info())
        sys.stdout.flush()

        return buildnumber
示例#30
0
def expenses():  #function that will run when homepage starts
    msg = ""
    if request.method == "POST":
        db = Database()
        db.create_table()
        name = request.form.get('item')
        price = request.form.get('price')
        status = db.add(name, price)
        records = db.view()
        if status:
            msg = "saved succesfully"
        else:
            msg = "error saving data"

        for data in request.form.items():
            print(data)

    print(records)
    return render_template('expense.html')