Пример #1
0
def main():
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-l',
                       '--list',
                       help='Lists all scans in database.',
                       action='store_true')
    group.add_argument('-st',
                       '--stats',
                       help='Lists stats about database contents.',
                       action='store_true')
    group.add_argument('-sc',
                       '--scan',
                       help='Scan a location and add to the database.',
                       type=str)
    group.add_argument(
        '-qs',
        '--quickscan',
        help='Scan a location ignoring hashes and add to the database.',
        type=str)
    parser.add_argument('-v', '--version', action='version', version='0.0.1')
    parser.add_argument("database",
                        help="Location of the database (Default files.db).",
                        type=str)

    args = parser.parse_args()

    if args.database:
        file_database = database.DataBase(args.database + '.db')
    else:
        file_database = database.DataBase('files.db')

    if args.scan:
        file_database.add_scan(args.scan)
        scan_id = file_database.get_last_scan_id()
        for root, dirnames, files in os.walk(args.scan):
            for file in files:
                file_data = file_metadata.FileMetadata(root, file)
                file_database.add_file(file_data, scan_id)
        cont = file_database.print_all()
        print_table(cont)
        file_database.dissconect()
    elif args.quickscan:
        file_database.add_quick_scan(args.quickscan)
        scan_id = file_database.get_last_scan_id()
        for root, dirnames, files in os.walk(args.quickscan):
            for file in files:
                file_data = file_metadata.FileMetadata(root, file, quick=True)
                file_database.add_quick_file(file_data, scan_id)
        cont = file_database.print_all()
        print_table(cont)
        file_database.dissconect()
    elif args.list:
        cont = file_database.list_scans()
        print_table(cont)
        file_database.dissconect()
    elif args.stats:
        cont = file_database.show_stats()
        print_table(cont)
        file_database.dissconect()
Пример #2
0
def check_balance_repleh():
    date_today = get_datetime_today()[-2:]
    date_month = database.DataBase().get_data_balance_old()
    print(date_month)
    print(date_today)
    if int(date_month) == int(date_today):
        print('WEa')
        database.DataBase().replenishment_balance()
Пример #3
0
    def test_one(self):

        db = database.DataBase()
        db.removeAll()

        assert len(db.constraint) == 0
        assert len(db.listRu) == 0
Пример #4
0
    def run(self):
        '''
        Every CONSIDER_DIED_MINS minutes it checks in database if there are controllers
        which didn't send its corresponding keep alive message.
        It wakes up every EXIT_CHECK_TIME seconds to see if the main thread ask it to finish. 
        '''

        #First of all, the database should be connected by the execution of this thread
        self.dataBase = database.DataBase(DB_HOST, DB_USER, DB_PASSWD,
                                          DB_DATABASE, self)

        while True:
            #Blocking until EXIT_CHECK_TIME expires
            time.sleep(EXIT_CHECK_TIME)
            self.checkExit()

            if self.iteration >= self.ITERATIONS:
                logMsg = 'Checking controller alivnesses.'
                self.logger.debug(logMsg)
                deadCtrllers = self.dataBase.setCtrllersNotReachable()
                for deadCtrller in deadCtrllers:
                    self.toRtEventQueue.put(deadCtrller)
                self.iteration = 0
            else:
                self.iteration += 1
Пример #5
0
def check_to_balance() -> BalanceMessage:  # checking from db balance user
    try:
        answer_balance = database.DataBase().check_balance()
        return BalanceMessage(month=answer_balance[1], )

    except:
        pass
Пример #6
0
def add_budjet_month(price_month: int) -> MessageUser:  # add to db budjet user
    try:
        database.DataBase().insert_budjet(price_month)

        return MessageUser(message='Бюджет на месяц успешно изменен')
    except:
        pass
Пример #7
0
def delete_all() -> MessageUser:  # truncate table from  db
    try:
        database.DataBase().delete_all()
        return MessageUser(message='Все данные о покупках удалены')

    except:
        return MessageUser(message='Произошла ошибка')
Пример #8
0
def main():
    try:
        args = parse_args()
        if args.about:
            print(get_about_info())
            return
        dbpath = args.path if args.path else DB_PATH
        db = database.DataBase(dbpath)
        public_id = db.get_public_id()
        set_output_path('%s/%s/' % (get_output_path(), public_id))
        if not os.path.isdir(get_output_path()):
            os.makedirs(get_output_path())
        if args.clear_output: #clean output contents
            files = glob.glob('%s/*' % (get_output_path()))
            for f in files:
                os.remove(f)
        common.common_data(db)
        common.alltop_data(db, 10)
        common.zero_data(db)
        common.authors_data(db)
        attachments.attachments_data(db)
        attachments.polls_info(db, 20)
        text_parse.popular_words(db, 200)
        text_parse.get_topics(db)
        timing.drawplots(db)
    except BaseException as e:
        print(e)
        traceback.print_exc()
        exit(1)
Пример #9
0
    def __init__(self):
        # super(myWindow, self).__init__()
        self.ui = uic.loadUi(os.path.join(uiFilePath, 'test.ui'))

        self.ui.allButton.pressed.connect(self.allBtnClick)
        self.ui.serialNoButton.pressed.connect(self.slNoBtnClick)
        self.ui.itemTypeButton.pressed.connect(self.itBtnClick)
        self.ui.locationButton.pressed.connect(self.locBtnClick)
        self.ui.userButton.pressed.connect(self.usrBtnClick)

        # self.ui.searchButton.clicked.connect(self.search)
        self.ui.comboBox.currentIndexChanged.connect(self.search)

        if user in authUsers:
            self.ui.addButton.clicked.connect(self.add)
            self.ui.updateButton.clicked.connect(self.update)
            self.ui.logButton.clicked.connect(self.log)

        self.ui.setWindowTitle('GRANTHA')
        self.ui.setWindowIcon(QtGui.QIcon('granthaLogo.png'))

        self.ui.tableWidget.customContextMenuRequested.connect(
            self.viewParentPopUp)

        self.center()
        self.ui.show()

        self.db = database.DataBase()
Пример #10
0
 def __init__(self, sys_path: str = "", time_delta_hour: int = 3, base_name: str = "Default"):
     # инициализация времени и часового пояса
     self.time_delta_hour = time_delta_hour
     self.time_delta = datetime.timedelta(hours=self.time_delta_hour, minutes=0)
     # инициализация системной папки
     self.sys_path = sys_path
     # виды полей для ответа
     self.ANS_PEER_ID = "peer_id"
     self.ANS_MESSAGE = "message"
     self.AMS_RAND_ID = "random_id"
     self.ANS_KEYBOARD = "keyboard"
     self.ANS_ATTACHMENT = "attachment"
     # виды клавиатур
     self.KBRD_MENU = "menu"
     self.KBRD_TIMETABLE = "timetable"
     self.KBRD_ACC_PLAN = "academic_plan"
     self.KBRD_SETTINGS = "settings"
     self.KBRD_MORNING_M = "morning_mailing"
     self.KBRD_EVENING_M = "evening_mailing"
     self.KBRD_EMPTY = "empty"
     # модуль расписания
     self.timetale = timetable.Timetable(self.sys_path, self.time_delta_hour)
     # модуль клавиатур
     self.keyboards = keyboard.KeyBoard()
     # инициализация клавиатур
     self._init_keyboards()
     # база данных
     self.base_name = base_name
     self.database = database.DataBase(sys_path, self.base_name)
Пример #11
0
    def run(self):
        '''
        '''
        self.dataBase = database.DataBase(DB_FILE)

        for eventIds, toReSendEvents in self.dataBase.getNEvents(RE_SEND_EVTS_QUANT):
            eventsSent = False
            while not eventsSent:
                self.netMngr.reSendEvents(toReSendEvents)
                try:
                    eventsResponse = self.netToReSnd.get(timeout=WAIT_RESP_TIME)
                    if eventsResponse == 'OK':
                        self.logger.debug('The server confirms the reception of the events.')
                        self.dataBase.delEvents(eventIds)
                        eventsSent = True
                    else:
                        self.logger.warning('The server could not save the events correctly.')
                        raise queue.Empty
                except queue.Empty:
                    logMsg = ("Sleeping for {} secs to retry sending events."
                              "".format(self.REAL_RE_SEND_TIME)
                             )
                    self.logger.info(logMsg) 
                    for i in range(self.SLEEP_TURNS):
                        self.checkExit()
                        time.sleep(EXIT_CHECK_TIME)

        self.resenderAlive.clear()
        sys.exit(self.exitCode)
Пример #12
0
 def __init__(self, api_token: str = "", group_id: int = 0, sys_path: str = "", base_name: str = "Default",
              server_name: str = "Empty", time_delta_hour: int = 3):
     # инициализируем часовой пояс
     self.time_delta_hour = time_delta_hour
     self.time_delta = datetime.timedelta(hours=self.time_delta_hour, minutes=0)
     # Даем серверу имя
     self.server_name = server_name
     # запоминаем id группы
     self.group_id = group_id
     # создаем папку сервера
     self.folder_path = sys_path + "\\" + server_name
     if not os.path.exists(self.folder_path):
         os.makedirs(self.folder_path)
     # --------------------------------------------------------------------------------------------------------------
     # Для Long Poll
     self.vk = vk_api.VkApi(token=api_token)
     # Для использования Long Poll API
     self.long_poll = VkBotLongPoll(self.vk, group_id)
     # Для вызова методов vk_api
     self.vk_api = self.vk.get_api()
     # --------------------------------------------------------------------------------------------------------------
     # инициализация базы данных
     self.base_name = base_name
     self.database = database.DataBase(self.folder_path, self.base_name)
     # --------------------------------------------------------------------------------------------------------------
     # инициализация класса, обрабатывающего команды
     self.command_hm = command_headman.Command_headman(self.folder_path, self.time_delta_hour, self.base_name)
     self.command = command.Command(self.folder_path, self.time_delta_hour, self.base_name)
     self.log = logining.Logining(self.folder_path, self.time_delta_hour)
Пример #13
0
    def add_purchase(self):
        self.debt = int(self.price) // (len(self.names) + 1)

        db = database.DataBase()
        db.connect('purchases')

        for i in self.names:
            db.db_command(
                'INSERT INTO purchases VALUES ("{}", "{}", "{}", "{}", "{}")'.
                format(self.user_name, self.item, self.price, i, self.debt))

        try:
            answer = Bookkeeper.send_message('collector')
            random_num = str(randint(0, len(answer) - 1))

            [
                bot.send_message(
                    i, answer[random_num].format(self.user_name, self.item,
                                                 self.price, self.debt))
                for i in self.names
            ]

            [
                bot.send_message(
                    i,
                    Bookkeeper.send_message('table').format(
                        self.user_name, self.item, self.price, self.debt,
                        self.phone)) for i in self.names
            ]

        except telebot.apihelper.ApiException:
            pass

        db.disconnect()
Пример #14
0
 def __init__(self):
     super(GUI_window, self).__init__()
     self.prompt = None  #for selecting things
     self.data = db.DataBase()  #stores the data to be plotted
     self.version = 0x050  #Should be equal to version in header comment (without periods)
     self.objectCounter = 0
     self.initUI()
Пример #15
0
	def __init__(self, options, daemon_url):
		"""
		Setup objects:

		  Methods

		  WorkSpaces

		"""
		self.config = configfile.get_config(options.config, verbose=False)
		self.debug = options.debug
		self.daemon_url = daemon_url
		# check config file
		configfile.sanity_check(self.config)
		self._update_methods()
		self.target_workdir = self.config['target_workdir']
		self.source_workdirs = {self.target_workdir} | self.config.get('source_workdirs', set())
		self.workspaces = {}
		for name, data in self.config['workdir'].items():
			if name in self.source_workdirs:
				path   = data[0]
				slices = data[1]
				self.workspaces[name] = workspace.WorkSpace(name, path, slices)
		undefined_workdirs = self.source_workdirs - set(self.workspaces)
		if undefined_workdirs:
			print('\nERROR:  Workdir(s) missing definition: ' + ', '.join('\"' + x + '\"' for x in undefined_workdirs) + '.')
			exit(1)
		check_slices = set(self.workspaces[name].slices for name in self.workspaces)
		if len(check_slices) > 1:
			print('\nERROR:  Not all workdirs have the same number of slices!')
			exit(1)
		put_workspaces({k: v.path for k, v in self.workspaces.items()})
		self.DataBase = database.DataBase(self)
		self.update_database()
		self.broken = False
Пример #16
0
 def thread_func(self):
     # Debug
     self.DB = database.DataBase()
     print("Thread criada para cliente:", self.conAddr)
     while True:
         try:
             data = self.conSock.recv(1024)
         except:
             if self.user is not None:
                 print("Closing thread for user " + self.user.login)
             else:
                 print("Closing thread without user")
             self.DB.closeDB()
             self.conSock.close()
             return None
         if (len(data) < 1): continue
         data = data.decode()
         # Debug
         print("Mensagem recebida de", self.conAddr, ":", data)
         c = self.check_command(data)
         if (c == -1):
             print("Closing connection to", self.conAddr)
             self.DB.closeDB()
             self.conSock.close()
             break
         self.execute(c, data)
Пример #17
0
def replenishment_balance_date(data_balance):  # return data_balance next month
    database.DataBase().insert_data_balance(data_balance)
    date_today = get_datetime_today()[:5]
    cnt_month = int(get_datetime_today()[5:7]) + 1  # new month
    result = str(date_today) + '0' + str(cnt_month) + '-' + str(
        data_balance)  # new format data
    return result
Пример #18
0
def room_book():
    db = database.DataBase('./data.db')
    params = request.json
    print(params)
    ret = db.BookRoom(params['team'], params['room'], params['date'],
                      params['reason'])
    code = 200 if ret else 500
    return jsonify({'status': code}), code
Пример #19
0
    def add_to_db(self):

        db = DB.DataBase(DB.path)

        with db.Session() as session:
            self.add_annual_report_to_db(session)
            self.add_auditors_to_db(session)
            self.add_kams_and_kam_tags_to_db(session)
Пример #20
0
 def deleter(self):
     db = database.DataBase()
     db.connect('purchases')
     for i in self.names:
         db.db_command(
             'DELETE FROM purchases WHERE item = "{}" AND debtor_id = "{}"'.
             format(self.item, i))
     db.disconnect()
Пример #21
0
 def find_id(self, user_name):
     db = database.DataBase()
     db.connect('users')
     db.db_command(
         'SELECT user_id FROM users WHERE name LIKE "{}"'.format(user_name))
     self.db_feedback = db.feedback
     [self.names.append(i[0]) for i in self.db_feedback]
     db.disconnect()
Пример #22
0
def getKey(json, user):
    """Get key from user."""
    if not user:
        """In here we need to connect to the WS, pass parameters and get a new key"""
        key = "X86NOH6II01P7R24"  # Tests
    else:
        db = database.DataBase()
        key = db.returnKey(json)
    return key
Пример #23
0
 def other_users(self):
     db = database.DataBase()
     db.connect('users')
     db.db_command(
         'SELECT user_id FROM users WHERE user_id NOT LIKE "{}"'.format(
             self.user_id))
     self.db_feedback = db.feedback
     [self.names.append(i[0]) for i in self.db_feedback]
     db.disconnect()
Пример #24
0
def teacher_login():
    params = request.json
    db = database.DataBase('./data.db')
    info = db.GetTeacherInfo(params['name'])
    if info:
        if info[2] == params['password']:
            log(params['name'] + ' has logined')
            return jsonify({'status': 200}), 200
    return jsonify({'status': 500}), 500
Пример #25
0
 def is_register(self):
     db = database.DataBase()
     db.connect('users')
     db.db_command(
         'SELECT name, phone FROM users WHERE user_id LIKE "{}"'.format(
             self.user_id))
     self.db_feedback = [i for i in db.feedback]
     self.user_name = self.db_feedback[0][0]
     self.phone = self.db_feedback[0][1]
     db.disconnect()
Пример #26
0
def out_expenses() -> List[MessageExpense]:  # return last expenses default :10
    data_all = []
    try:
        tuple_expenses = database.DataBase().fetchall()
        for i in tuple_expenses:
            data_all.append(MessageExpense(name=i[0], amount=i[1], date=i[2]))
        return data_all

    except Exception as e:
        print(e)
Пример #27
0
    def __init__(self):
        print "Generating Key...\n"
        self._key = Key()

        self.database = database.DataBase()

        self.baseLink = 'http://www.primewire.ag/'
        self.searchLink = '?search_keywords='
        self.keyLink = '&key='
        self.key = self._key.key
        self.sectionLink = '&search_section='
        self.debug = False
Пример #28
0
    def finder(self):
        db = database.DataBase()
        db.connect('users')
        db.db_command(
            'SELECT name, phone FROM users WHERE user_id NOT LIKE "{}"'.format(
                self.user_id))

        self.db_feedback = [i for i in db.feedback]
        for i in self.db_feedback:
            self.people += '• {} - {}\n'.format(i[0], i[1])

        db.disconnect()
Пример #29
0
 def PUT(self):
     path = 'tmp'
     for root, dirs, files in os.walk(path):
         for file in files:
             path = os.path.join(path, file)
             os.remove(path)
     bc = stocks.BhavCopy()
     bc.download_zip()
     red = database.DataBase()
     red.delete_all()
     red.load_csv_to_db()
     return self.common()
Пример #30
0
    def __init__(self, parent, title, pos, size=(300, 250)):
        wx.Frame.__init__(self, parent, -1, title, pos, size)
        self.pheno = None
        self.make_panels()
        if db_loaded:
            self.db = database.DataBase()
        else:
            self.db = None

        self.playing = False
        self.Bind(wx.EVT_IDLE, self.monit)
        self.editor = None