Example #1
0
 def __init__(self, persist=None):
     '''Create a Authentication instance, and sees if you are currently in a
     persistence environment or not.'''
     if not persist:
         self._persist = Persistence()
     else:
         self._persist = persist
Example #2
0
def new(type):
    """Create a new game.

       type -- The type of game (PvP, or type of AI.)
    """

    white_player_id = 1  # str(uuid.uuid1())
    black_player_id = 2  # str(uuid.uuid1())

    board = Board()

    persistence = Persistence(db)
    game_id = persistence.save_new_game(white_player_id, black_player_id,
                                        pickle.dumps(board))

    resp = {
        u'board': board.display_json(),
        u'board_serialized': repr(board),
        u'turn': board.turns_taken,
        u'player': board.current_player,
        u'game_id': game_id,
        u'white_player': white_player_id,
        u'black_player': black_player_id,
        u'moves': board.display_previous_moves(),
        u'winner': board.winner,
        u'status_code': u'NEW_GAME',
        u'status_message': u'New Game Created.',
    }

    return json.dumps(resp)
Example #3
0
    def run(self):
        main_config = Config(self.main_config_file)
        main_module = main_config.get_module()
        if not main_module:
            print "Error parsing main configuration file %s"\
                % self.main_config_file
            return False

        modules_configs = self._get_modules_configs(self.modules_dir)
        cron_manager = CronManager(main_module.executor,
                                   main_module.crons_path,
                                   main_module.crons_prefix)
        persistence = Persistence(main_module.persistence_file)

        # Identify new modules added
        new_modules = presistence.filter_old(modules_configs)
        old_modules = list(set(modules_configs) - set(new_modules))

        # Clean persistence by deleting the modules removed
        deleted_modules = persistence.clean(old_modules)

        # For those deleted from the persistence, remove the cron
        for module_config in deleted_modules:
            config = Config(module_config)
            module = config.get_module()
            if module:
                cron_manager.delete(module)

        # Add new modules to persistence and load their crons
        for module_config in new_modules:
            config = Config(module_config)
            module = config.get_module()
            if module:
                cron_manager.load(module)
                persistence.store(module)
Example #4
0
def new(type):
    """Create a new game.

       type -- The type of game (PvP, or type of AI.)
    """

    white_player_id = 1  # str(uuid.uuid1())
    black_player_id = 2  # str(uuid.uuid1())

    board = Board()

    persistence = Persistence(db)
    game_id = persistence.save_new_game(white_player_id, black_player_id, pickle.dumps(board))

    resp = {
        u'board': board.display_json(),
        u'board_serialized': repr(board),
        u'turn': board.turns_taken,
        u'player': board.current_player,
        u'game_id': game_id,
        u'white_player': white_player_id,
        u'black_player': black_player_id,
        u'moves': board.display_previous_moves(),
        u'winner': board.winner,
        u'status_code': u'NEW_GAME',
        u'status_message': u'New Game Created.',
    }

    return json.dumps(resp)
Example #5
0
    def test_persistence_init_fail(self):
        test_persist = Persistence('foo')

        with self.assertRaises(
                OSError,
                msg=
                'Should throw OSError on trying to create two references to one shelve'
        ):
            Persistence('foo')
Example #6
0
def ensure_file(bot: Bot, persistence: Persistence, file_id: str) -> dict:
    f_key = f"file:{file_id}"
    file_data = persistence.get_last(f_key)
    if file_data is None:
        print(f"Retrieving file {file_id}")
        file = bot.get_file(file_id=file_id)
        file_data = file.to_dict()
        persistence.add(f_key, file_data)
    return file_data
Example #7
0
    def __init__(self):
        # Persistence
        super().__init__()
        self.__current_jsons = defaultdict(dict)
        if config["crawler"] == "xlsx":
            self.__info_getter = XLSXCrawler()
        elif config["crawler"] == "gspread":
            self.__info_getter = GSpreadCrawler()
        elif config["crawler"] == "gspread2":
            self.__info_getter = GSpreadCrawler2()

        self.persistence = Persistence()
Example #8
0
def move_piece(game_id, from_, to_):
    """

    """
    persistence = Persistence(db)
    game = persistence.load_game(game_id)
    if (game is not None):
        try:
            board = pickle.loads(game.board)
            board.move_piece(from_, to_)
            persistence.update_game(game_id, pickle.dumps(board), board.winner)

            resp = {
                u'board':
                board.display_json(),
                u'board_serialized':
                repr(board),
                u'turn':
                board.turns_taken,
                u'player':
                board.current_player,
                u'game_id':
                game_id,
                u'white_player':
                game.white_player_id,
                u'black_player':
                game.black_player_id,
                u'winner':
                board.winner,
                u'moves':
                board.display_previous_moves(),
                u'promotable_pieces':
                [p.name for p in board.promotable_pieces()],
                u'status_code':
                u'UPDATED',
                # TODO: Update to used previous_move property and {piece}
                u'status_message':
                u'Piece moved from {from_} to {to_}'.format(from_=from_,
                                                            to_=to_)
            }
        except IllegalMoveException:
            #TODO: Prepare an error message
            resp = {'board': None, 'turn': None, 'error': 'Invalid move'}
    else:
        #TODO: Prepare an error message
        resp = {
            'board': None,
            'turn': None,
            'error': 'Could not find chess game for current player.'
        }

    return json.dumps(resp)
Example #9
0
def detail_report(id: int):
    """
    Print a detailed report.
    
    This will fetch a specific activity from the database, then provide a detailed
    report for it.
    """

    # Load the peak data.
    db = Persistence()
    if not (activity := db.load_by_id(id)):
        print(f"Cannot find activity #{id}")
        return
Example #10
0
def detail_plot_report(id: int):
    """
    Plot the result of an activity.
    
    This will fetch a specific activity from the database, then plot its power
    and heart rate data.
    """

    # Load the peak data.
    db = Persistence()
    if not (activity := db.load_by_id(id)):
        print(f"Cannot find activity #{id}")
        return
    def __init__(self, quizname, num_of_attempts):
        '''This method initializes a new Quiz object with the basic
        attributes, a name and the number of alloted attempts. This is
        done by calling the Quiz class in structure.py, and giving it the
        quizname and num_of-attempts attributes in this method. It then
        creates a self.quiz variable that will be used to refer to the
        quiz in further methods. As well, an instance of persistance is
        created to store the quiz.

        quizname: String
        num_of_attempts: Int
        '''
        self.quiz = Quiz(quizname, num_of_attempts)
        self.question_bank = QuestionBank()
        self.persist = Persistence()
Example #12
0
def delete_topic(id):
    topic = Topic.query.filter_by(id=id).first()
    if topic is not None:
        if request.method == 'POST':
            try:
                devices = Device.query.with_parent(topic)
                for device in devices:
                    print(topic.topic)
                    delete = Persistence().delete_device_topic(device,topic)
                    if not delete:
                        flash("Problems deleting topic from the device")
                        return render_template('topics/delete.html',device=device)

                #Delete the database register
                db.session.delete(topic)
                db.session.commit()
                flash("The topic was removed")
                return redirect(url_for('topic.topic_index'))

            except Exception as e:
                print(e)
                flash("DB Deleted Failed - %s".format(e))
    else:
        flash("Topic Not Found")

    return render_template('topics/delete.html',topic=topic)
Example #13
0
async def main():
    bot = commands.Bot(command_prefix=commands.when_mentioned_or("?"), description="Another random discord bot")
    with open('auth.json') as jf:
        data = json.loads(jf.read())
        bot.key_dis = data['discord']
        bot.key_yt = data['youtube']
        bot.key_azure = data['azure']
    bot.resources = "resources/"
    bot.get_images = utility.get_images
    bot.db = Persistence()
    bot.var = {}

    @bot.event
    async def on_ready():
        for g in bot.guilds:
            bot.var[g.id] = {}
        print("rdy")

    bot.add_cog(Cat(bot))
    bot.add_cog(Image(bot))
    #bot.add_cog(Filter(bot))
    bot.add_cog(Various(bot))
    bot.add_cog(Audio(bot))
    bot.add_cog(Anime(bot))

    try:
        await bot.start(bot.key_dis)
    except KeyboardInterrupt:
        await bot.db.close()
        await bot.logout()
Example #14
0
def start_service():
    config = CleanerConfig()
    persistence = Persistence(config)
    cherrypy.tree.mount(root=DBInstanceRestful(config, persistence),
                        script_name="/dbinstance")
    cherrypy.tree.mount(root=DBReplicaRestful(config, persistence),
                        script_name="/dbreplica")
    cherrypy.quickstart(None, "/")
Example #15
0
def power_report():
    """
    Print a power report.
    
    This will fetch activities from the database, then:
    
    - Find the maximum for each power peak (e.g., max 5 seconds, 30 seconds, etc).
    - Print the activity data for each activity, sorted in date order with a break
      between each week.
    - Print the maximum we found for each power peak as a final summary.
    """

    # Load the activity data.
    db = Persistence()
    if not (activities := db.load_all()):
        print("No data to report on")
        return
Example #16
0
def get_gathered_set_names(persistence: Persistence):
    sets = set()
    for gs in persistence.list("gathered_stickers"):
        if isinstance(gs, str):
            gs = json.loads(gs)
        set_name = gs.get("set_name")
        if set_name:
            sets.add(set_name)
    return sets
Example #17
0
def start_service(): 
    persistence = Persistence()
    cherrypy.tree.mount(root=UserController(persistence), 
                        script_name="/user")
    cherrypy.tree.mount(root=RewardUserController(persistence), 
                        script_name="/reward")
    root_conf = {'/': {'tools.staticdir.on': True,
                       'tools.staticdir.dir': '%s/static' % home_path(),
                       'tools.staticdir.index': 'lottery.html'}}
    cherrypy.quickstart(None, "/", config=root_conf)         
Example #18
0
def move_piece(game_id, from_, to_):
    """

    """
    persistence = Persistence(db)
    game = persistence.load_game(game_id)
    if (game is not None):
        try:
            board = pickle.loads(game.board)
            board.move_piece(from_, to_)
            persistence.update_game(game_id, pickle.dumps(board), board.winner)

            resp = {
                u'board': board.display_json(),
                u'board_serialized': repr(board),
                u'turn': board.turns_taken,
                u'player': board.current_player,
                u'game_id': game_id,
                u'white_player': game.white_player_id,
                u'black_player': game.black_player_id,
                u'winner': board.winner,
                u'moves': board.display_previous_moves(),
                u'promotable_pieces': [p.name for p in board.promotable_pieces()],
                u'status_code': u'UPDATED',
                # TODO: Update to used previous_move property and {piece}
                u'status_message': u'Piece moved from {from_} to {to_}'.format(from_=from_, to_=to_)
            }
        except IllegalMoveException:
            #TODO: Prepare an error message
            resp = {
                'board': None,
                'turn': None,
                'error': 'Invalid move'
            }
    else:
        #TODO: Prepare an error message
        resp = {
            'board': None,
            'turn': None,
            'error': 'Could not find chess game for current player.'
        }

    return json.dumps(resp)
Example #19
0
 def __init__(self, name, path, database_path):
     #TODO: it is better if we override __new__ method in Project class instead of receive None args
     if name != None and database_path != None:  #new project called
         if name[:-4] != '.nav':
             name += '.nav'
         self.name = name
         self.path = path
         self.database_path = database_path
         self.adjacency_matrices = []
         self.neighbourhood_matrices = []
         self.analysis = []
         self.state = 'new'
         self.persistence = Persistence()
         self.save_file('w')
         self.bio_handler = BioHandler(database_path)
         self.save_project()
     else:  #open project called
         self.path = path
         self.persistence = Persistence()
Example #20
0
 def __init__(self, name, path, database_path):
     #TODO: it is better if we override __new__ method in Project class instead of receive None args
     if name != None and database_path != None: #new project called
         if name[:-4] != '.nav':
             name += '.nav'
         self.name = name
         self.path = path
         self.database_path = database_path
         self.adjacency_matrices = []
         self.neighbourhood_matrices = []
         self.analysis = []
         self.state = 'new'
         self.persistence = Persistence()
         self.save_file('w')
         self.bio_handler = BioHandler(database_path)
         self.save_project()
     else: #open project called
         self.path = path
         self.persistence = Persistence()
Example #21
0
def game(game_id):
    """ Returns the chess board for the game specified"""
    persistence = Persistence(db)
    game = persistence.load_game(game_id)
    board = pickle.loads(game.board)

    resp = {
        u'board': board.display_json(),
        u'board_serialized': repr(board),
        u'turn': board.turns_taken,
        u'player': board.current_player,
        u'game_id': game_id,
        u'white_player': game.white_player_id,
        u'black_player': game.black_player_id,
        u'winner': board.winner,
        u'moves': board.display_previous_moves(),
        u'promotable_pieces': [p.name for p in board.promotable_pieces()]
    }

    return json.dumps(resp)
Example #22
0
def game(game_id):
    """ Returns the chess board for the game specified"""
    persistence = Persistence(db)
    game = persistence.load_game(game_id)
    board = pickle.loads(game.board)

    resp = {
        u'board': board.display_json(),
        u'board_serialized': repr(board),
        u'turn': board.turns_taken,
        u'player': board.current_player,
        u'game_id': game_id,
        u'white_player': game.white_player_id,
        u'black_player': game.black_player_id,
        u'winner': board.winner,
        u'moves': board.display_previous_moves(),
        u'promotable_pieces': [p.name for p in board.promotable_pieces()]
    }

    return json.dumps(resp)
Example #23
0
class CovidUpdater(threading.Thread):
    def __init__(self):
        # Persistence
        super().__init__()
        self.__current_jsons = defaultdict(dict)
        if config["crawler"] == "xlsx":
            self.__info_getter = XLSXCrawler()
        elif config["crawler"] == "gspread":
            self.__info_getter = GSpreadCrawler()
        elif config["crawler"] == "gspread2":
            self.__info_getter = GSpreadCrawler2()

        self.persistence = Persistence()

    def update_all(self):
        for table in SHEET_DATA.keys():
            final_json = self.__info_getter.get_worksheet_data(table)
            diff_result = dictdiffer.diff(self.__current_jsons[table],
                                          final_json,
                                          dot_notation=False)
            list_diff_result = list(diff_result)
            if len(list_diff_result) > 0:
                self.__current_jsons[table] = final_json
                with app.test_request_context():
                    update(list_diff_result)
                logging.info(list_diff_result)
                with open(os.path.join(CURRENT_DIR, 'data_' + table + '.json'),
                          'w') as outfile:
                    json.dump(final_json, outfile, indent=4)
                    self.persistence.insert(final_json)
                with open(
                        os.path.join(CURRENT_DIR,
                                     'last_update_' + table + '.json'),
                        'w') as outfile:
                    json.dump(list_diff_result, outfile, indent=4)

    def run(self):
        while (True):
            logging.info("compute")
            self.update_all()
            time.sleep(30)
Example #24
0
    def update_items():
        Cache.lock_items.acquire()

        items_to_insert = []
        items_to_edit = []
        items_to_delete = []

        for i in Cache.list_items.values():
            aux = {'id': i.id, 'index': i.index, 'file_path': i.file_path, 'description': i.description}
            if i.status == 1:
                items_to_insert.append(aux)
            elif i.status == 2:
                items_to_edit.append(aux)
            elif i.status == 3:
                items_to_delete.append(aux)
        
        Persistence.update_items(items_to_insert, items_to_edit, items_to_delete)
        
        Cache.list_items.clear()
        Cache.get_items_from_db()
        Cache.lock_items.release()
Example #25
0
 def get_items_from_db():
     Cache.lock_items.acquire()
     try: 
         r = Persistence.get_items()
         for i in range(len(r)):
             new_item = Item(r[i]['description'], r[i]['file_path'], r [i]['index'], r[i]['id'], 0)
             Cache.add_item(new_item.id, new_item)
     except Exception as e:
         print(str(e))
         
     Cache.needs_update = False
     Cache.lock_items.release()
Example #26
0
class Manager(object):

    def __init__(self):
        self._user = None
        self._persistence = Persistence()

    @property
    def user(self):
        return self._user

    def createUser(self, name, password):
        self._user = User(name, password)

    def save(self):
        self._persistence.save(self._user)

    def load(self):
        try:
            self._user = self._persistence.load()
        except:
            print 'No user existing.'
    def __init__(self, passGrade: int, quiz: Quiz, questionSet: QuestionBank,
                 students: Class, weight: int):
        '''
        The method to initialize the class. Upon being initialized, it sets up the persistence
        service, and grabs the quiz you'd like to edit, as well as the question set you'd like to access, and the class of students
        who's quiz you're editing. It also initializes an empty list, changeLog, which is used in every method to provide a list of
        'notes' of changes you've made so other professors or assistants can look at them and see recent changes.

        passGrade: int
        quiz : Quiz
        questionSet: QuestionBank
        students : Class
        weight: int
        '''
        self.passGrade = 50
        self.changeLog = []
        self.weight = 5
        self.persist = Persistence()
        self.quiz = self.persist.retrieve(Quiz, quiz)
        self.questionSet = self.persist.retrieve(QuestionBank, questionSet)
        self.students = self.persist.retrieve(Class, students)
Example #28
0
def promote_piece(game_id, piece_code):
    persistence = Persistence(db)
    game = persistence.load_game(game_id)
    if (game is not None):
        try:
            board = pickle.loads(game.board)
            piece = PieceFactory.create(piece_code)
            board.promote_pawn(piece)
            persistence.update_game(game_id, pickle.dumps(board), board.winner)

            resp = {
                u'board': board.display_json(),
                u'turn': board.turns_taken,
                u'player': board.current_player,
                u'game_id': game_id,
                u'white_player': game.white_player_id,
                u'black_player': game.black_player_id,
                u'winner': board.winner,
                u'moves': board.display_previous_moves(),
                u'promotable_pieces': [p.name for p in board.promotable_pieces()],
                u'status_code': u'UPDATED',
                # TODO: Update to used previous_move property and {piece}
                u'status_message': u'Pawn promoted to {piece}'.format(piece=piece)
            }
        except IllegalMoveException:
            #TODO: Prepare an error message
            resp = {
                'board': None,
                'turn': None,
                'error': 'Invalid move'
            }
    else:
        #TODO: Prepare an error message
        resp = {
            'board': None,
            'turn': None,
            'error': 'Could not find chess game for current player.'
        }

    return json.dumps(resp)
def run(args):
    logging.info('Starting bot')

    config = BotConfig(args.config)
    logging.info('Will use next config parameters:\n%s' % config)

    global global_broker
    global_broker = TransmissionBroker(config, Persistence(config.persistence_file))

    global global_updater
    global_updater = Updater(token=config.token)
    dispatcher = global_updater.dispatcher
    dispatcher.add_error_handler(telegram_error)

    list_handler = CommandHandler('list', list_command)
    dispatcher.add_handler(list_handler)

    add_handler = CommandHandler('add', add_command)
    dispatcher.add_handler(add_handler)

    stop_handler = CommandHandler('stop', stop_command)
    dispatcher.add_handler(stop_handler)


    remove_handler = CommandHandler('remove', remove_command)
    dispatcher.add_handler(remove_handler)

    help_handler = CommandHandler('help', help_command)
    dispatcher.add_handler(help_handler)

    start_handler = CommandHandler('start', start_command)
    dispatcher.add_handler(start_handler)

    secret_handler = CommandHandler('secret', secret_command)
    dispatcher.add_handler(secret_handler)
    
    os_handler = CommandHandler('uname', os_command)
    dispatcher.add_handler(os_handler)

    unknown_handler = MessageHandler([Filters.command], help_command)
    dispatcher.add_handler(unknown_handler)
	
    global_updater.start_polling()

    global global_error_exit
    global_updater.is_idle = True
    while global_updater.is_idle:
        if global_error_exit:
            global_updater.stop()
            sys.exit(1)

        time.sleep(0.1)
Example #30
0
    def __init__(self):
        self.persistence = Persistence()
        self.matrix_ctrl = MatrixController()
        signal.signal(signal.SIGINT, self.sigint_handler)

        self.sender = "*****@*****.**"
        self.pwd = "weatherapp"

        while True:
            username = self.matrix_ctrl.get_username()
            if username == MatrixController.USER_EXIT:
                self.matrix_ctrl.exit()
                break
            pattern = self.matrix_ctrl.get_input_pattern()
            pattern = self.pattern_to_string(pattern)
            try:
                self.user_logged = self.persistence.login(username, pattern)
            except Exception as error:
                self.matrix_ctrl.display_error(error)
            else:
                self.matrix_ctrl.display_success(self.user_logged)
                self.record_weather()
Example #31
0
def promote_piece(game_id, piece_code):
    persistence = Persistence(db)
    game = persistence.load_game(game_id)
    if (game is not None):
        try:
            board = pickle.loads(game.board)
            piece = PieceFactory.create(piece_code)
            board.promote_pawn(piece)
            persistence.update_game(game_id, pickle.dumps(board), board.winner)

            resp = {
                u'board': board.display_json(),
                u'turn': board.turns_taken,
                u'player': board.current_player,
                u'game_id': game_id,
                u'white_player': game.white_player_id,
                u'black_player': game.black_player_id,
                u'winner': board.winner,
                u'moves': board.display_previous_moves(),
                u'promotable_pieces':
                [p.name for p in board.promotable_pieces()],
                u'status_code': u'UPDATED',
                # TODO: Update to used previous_move property and {piece}
                u'status_message':
                u'Pawn promoted to {piece}'.format(piece=piece)
            }
        except IllegalMoveException:
            #TODO: Prepare an error message
            resp = {'board': None, 'turn': None, 'error': 'Invalid move'}
    else:
        #TODO: Prepare an error message
        resp = {
            'board': None,
            'turn': None,
            'error': 'Could not find chess game for current player.'
        }

    return json.dumps(resp)
class PersistenceManager:
    def __init__(self, path, log):
        self.last_request = time.time() - CACHE_TIME
        self.log = log
        self.twitterAPI = TwitterAPI()
        self.repository = Persistence(path, logging.getLogger(__name__))
        self.repository.init_db()

    def list(self):
        if (time.time() - self.last_request) >= CACHE_TIME:

            t = TwitterAPI()
            active = t.get_active_tweets("#riverguard", "36.528580",
                                         "-6.213026", RADIUS)["statuses"]
            passive = t.get_passive_tweets("36.528580", "-6.213026",
                                           RADIUS)["statuses"]
            passive = t.extract_image_tweets(passive)[:15]

            v = VisionAPI()
            passive = v.tag_images(passive)
            relevant_tags = ["waste", "algae", "fish", "water", "litter"]
            passive = self.filter_non_relevant_tweets(passive, relevant_tags)

            tweets = active + passive

            self.log.info('getting tweets from twitter')
            for tweet in tweets:
                self.repository.create(tweet)
            self.last_request = time.time()
        return self.repository.list()

    def filter_non_relevant_tweets(self, tweets, relevant_tags):
        filtered_tweets = []
        for tweet in tweets:
            tags = [tag["Label"] for tag in tweet["tags"]]
            if set(relevant_tags) & set(tags):
                filtered_tweets.append(tweet)
        return filtered_tweets
Example #33
0
    def start(self):
        Persistence.load_from_disk(self.active_chain, self.utxo_set)

        server = ThreadedTCPServer(
            ("0.0.0.0", Params.PORT_CURRENT),
            TCPHandler,
            self.active_chain,
            self.side_branches,
            self.orphan_blocks,
            self.utxo_set,
            self.mempool,
            self.peerManager,
            self.mine_interrupt,
            self.ibd_done,
            self.chain_lock,
            self.peers_lock,
        )

        # This is a single server without initializing block download from other peers.
        # So set ibd_done and let this listening server run.
        self.ibd_done.set()

        server.serve_forever()
Example #34
0
    def __init__(self, name, new=True):
        self.players = {}
        self.ladder_filename = name

        self.file = Persistence(self.ladder_folder, self.ladder_filename,
                                self.ladder)
        players = self.file.read()

        # file not found or empty load some default data for testing
        if not players and not new:
            self.players['Ash'] = Player('Ash')
            self.players['Matt'] = Player('Matt')
            self.players['Mike'] = Player('Dan')
            self.players['Dan'] = Player('Dan')
            self.players['Emily'] = Player('Emily')
            players = ['Ash', 'Matt', 'Mike', 'Dan', 'Emily']
            self.save()

        if players:
            for player in players:
                player_object = Player(player)
                self.ladder.append(player_object)
                self.players[player] = player_object
class TestPersistence(unittest.TestCase):
    def setUp(self) -> None:
        self.path = os.path.dirname(os.path.realpath(__file__))
        self.name = "test_file"
        self.persistence = Persistence(self.path, self.name)

    def tearDown(self) -> None:
        os.remove(self.persistence.path())

    def test_exists(self) -> None:
        self.assertTrue(self.persistence.exists())

    def test_path(self) -> None:
        expected = f"{self.path}/{self.name}.yaml"
        actual = self.persistence.path()
        self.assertEqual(expected, actual)

    def test_reset(self) -> None:
        with open(self.persistence.path(), "w") as f:
            f.write("My best joke!")
        self.persistence.reset()
        with open(self.persistence.path(), "r") as f:
            self.assertEqual("---", f.read())
Example #36
0
def main():
    # Collect command line arguments
    # Expecting 4 input values:
    # 1. Database server
    # 2. Login
    # 3. Password
    # 4. Load Manager table id
    adm_sp_value = ADMSharepointValue()

    i = 1
    for arg in sys.argv[1:]:
        if i == 1:
            adm_sp_value.database_server = arg
        if i == 2:
            adm_sp_value.login = arg
        if i == 3:
            adm_sp_value.password = arg
        if i == 4:
            adm_sp_value.load_manager_id = arg

        i += 1

    print(adm_sp_value)

    # Step 1: Populate sharepoint details from ADM
    persistence = Persistence(adm_sp_value)
    sharepoint_value = persistence.fetch_sharepoint_attributes()
    print(sharepoint_value)

    if sharepoint_value is not None:
        adm_sp_value.sharepoint_value = sharepoint_value
        # Step 2: Populate load manager attributes
        persistence.fetch_load_manager_attributes()
        print(adm_sp_value)

        # Step 3: Fetch active target report details
        target_report_values = persistence.fetch_target_report_attributes()
        print("Target Report Values: " + str(target_report_values))
        adm_sp_value.target_report_values = target_report_values

        # Step 4: Upload files to sharepoint.
        __upload_target_reports(adm_sp_value)
Example #37
0
 def __init__(self):
     self._user = None
     self._persistence = Persistence()
Example #38
0
        def mine_forever():
            logger.info(f'thread for mining is started....')

            def broadcast_new_mined_block(block_to_broadcast):
                peers = self.peerManager.getPeers()
                for _peer in peers:
                    ret = Utils.send_to_peer(
                        Message(Actions.BlockRev, block_to_broadcast,
                                Params.PORT_CURRENT), _peer)
                    if ret == 1:
                        if _peer in peers:
                            with self.peers_lock:
                                #self.peerManager.remove(_peer)
                                self.peerManager.block(_peer)

                    elif ret != 0:
                        with self.peers_lock:
                            self.peerManager.addLog(_peer, 1)
                    else:
                        with self.peers_lock:
                            self.peerManager.addLog(_peer, 0)

            while True:

                try:
                    block = self.assemble_and_solve_block()

                    if block:

                        threading.Thread(
                            target=broadcast_new_mined_block,
                            args=(copy.deepcopy(block), )).start()
                        #ret_outside_chain = False
                        with self.chain_lock:
                            #chain_use_id = [str(number).split('.')[0] + '.' + str(number).split('.')[1][:5] for number in [random.random()]][0]
                            #logger.info(f'####### into chain_lock: {chain_use_id} of mine_forever')

                            chain_idx  = TCPHandler.check_block_place(block, self.active_chain, self.utxo_set, \
                                                                      self.mempool, self.side_branches)

                            ret_outside_lock = False
                            if chain_idx is not None and chain_idx >= 0:
                                ret_outside_lock = TCPHandler.do_connect_block_and_after(block, chain_idx, self.active_chain, \
                                                                      self.side_branches, self.mempool, \
                                                               self.utxo_set, self.mine_interrupt)
                            #logger.info(f'####### out of chain_lock: {chain_use_id} of mine_forever')
                        if ret_outside_lock is True:
                            if len(self.active_chain.chain
                                   ) % Params.SAVE_PER_SIZE == 0 or len(
                                       self.active_chain.chain) <= 5:
                                Persistence.save_to_disk(self.active_chain)

                        if chain_idx is not None and chain_idx >= 0:
                            pass
                        elif chain_idx is None:
                            logger.info(
                                f'mined already seen block {block.id}, just discard it and go'
                            )
                        elif chain_idx == -2:
                            logger.info(
                                f"mined an orphan block {block.id}, just discard it and go"
                            )
                        elif chain_idx == -1:
                            logger.info(
                                f'a mined block {block.id} but failed validation'
                            )
                        else:
                            logger.info(
                                f'unwanted result of check block place')
                except:
                    pass
Example #39
0
File: raisin.py Project: fpt/py-rss
 def initialize(self):
     self.pers = Persistence.start(self.mongo_url).proxy()
Example #40
0
def list_all_games():
    persistence = Persistence(db)
    game_summary = persistence.list_games(None)
    return json.dumps(game_summary)
Example #41
0
def list_games(player_id):
    persistence = Persistence(db)
    game_summary = persistence.list_games(player_id)
    return json.dumps(game_summary)
Example #42
0
    parser.add_argument("--force", "-f", action='store_const', const=True, default=False, 
                        help="if the update action is going to be forced")

    parser.add_argument("--create-virtual-contest", "-v", nargs="*", 
                        help="creates a virtual contest")
    parser.add_argument("--title",
                        help="title of the contest to create")
    parser.add_argument("--description", 
                        help="description of the contest to create")
    parser.add_argument("--start-date", default="15", 
                        help="sets the contest start date in format '%s', if integer given start date is X minutes from now" % TIME_FORMAT)
    parser.add_argument("--duration", type=int, default=300, 
                        help="sets the contest duration")
    args = parser.parse_args()
    
    persistence = Persistence()
    try:
        if args.update_users is not None:
            if "*" in args.update_users:
                updateUsers([], args.top, args.force)
            else:
                updateUsers(args.update_users, args.top, args.force)
        elif args.update_problems:
            updateProblems(args.force)
        elif args.update_contests is not None:
            if "*" in args.update_contests:
                updateContests([], args.force)
            else:
                updateContests(args.update_contests, args.force)
        elif args.show_users is not None:
            showUsers(args.show_users)
Example #43
0
 def __init__(self):
     self._persistence = Persistence()
     self._clients = list()
     self._isConnected = False
Example #44
0
class Project:
    '''
    name
    description
    path
    database_path
    database_date
    Persistence 1
    BioHandler 1
    SimilarityMatrix 1
    AdjacencyMatrix *
    NeighbourhoodMatrix *
    '''
    
    def __init__(self, name, path, database_path):
        #TODO: it is better if we override __new__ method in Project class instead of receive None args
        if name != None and database_path != None: #new project called
            if name[:-4] != '.nav':
                name += '.nav'
            self.name = name
            self.path = path
            self.database_path = database_path
            self.adjacency_matrices = []
            self.neighbourhood_matrices = []
            self.analysis = []
            self.state = 'new'
            self.persistence = Persistence()
            self.save_file('w')
            self.bio_handler = BioHandler(database_path)
            self.save_project()
        else: #open project called
            self.path = path
            self.persistence = Persistence()
        
    def save_file(self, mode):
        return self.persistence.save_project_file(self, mode)
        
    def save_project(self):
        self.persistence.update_data(self)
        
    def load_data(self):
        return self.persistence.load_project_data(self)
    
    def end(self):
        self.persistence.update_data(self)
        
    def get_sequences(self):
        return self.bio_handler.get_sequences()
        
    def get_adjacency_matrices(self):
        adj_matrices = {}
        for matrix in self.adjacency_matrices:
            adj_matrices[matrix.threshold] = matrix
            
        return adj_matrices
        
    def get_neighbourhood_matrices(self):
        nbh_matrices = {}
        for matrix in self.neighbourhood_matrices:
            nbh_matrices[matrix.threshold] = matrix
            
        return nbh_matrices
        
    def generate_adjacency_matrices(self, adj_matrix_gen):
        if adj_matrix_gen:
            for threshold in range(adj_matrix_gen['begin'], adj_matrix_gen['end'] + 1):
                adj_matrix = AdjacencyMatrix(self.similarity_matrix, threshold)
                adj = self.get_adjacency_matrix(adj_matrix.threshold)
                if adj:
                    self.adjacency_matrices.remove(adj)
                self.adjacency_matrices.append(adj_matrix)
                
    def generate_neighbourhood_matrices(self, nbh_matrix_gen):
        if nbh_matrix_gen:
            for threshold in range(nbh_matrix_gen['begin'], nbh_matrix_gen['end'] + 1):
                nbh_matrix = NeighbourhoodMatrix(self.similarity_matrix, threshold)
                if nbh_matrix_gen['rearrange']:
                    #TODO
                    #pass matrix and call minener
                    #receive new matrix and list with new order
                    #call method to rearrange nbh_matrix
                    pass
                nbh = self.get_neighbourhood_matrix(nbh_matrix.threshold)
                if nbh:
                    self.neighbourhood_matrices.remove(nbh)
                self.neighbourhood_matrices.append(nbh_matrix)
                
    def get_adjacency_matrix(self, threshold):
        for matrix in self.adjacency_matrices:
            if matrix.threshold == threshold:
                return matrix
        return None
        
    def get_neighbourhood_matrix(self, threshold):
        for matrix in self.neighbourhood_matrices:
            if matrix.threshold == threshold:
                return matrix
        return None
        
    def analyse_thresholds(self, analysis_type):
        if analysis_type == 'distance':
            th_analysis = Distance()
            distance_data = None
            if len(self.neighbourhood_matrices) == 101:
                distance_data = th_analysis.do_analysis(self.similarity_matrix, self.neighbourhood_matrices)
                self.analysis.append(th_analysis)
            else:
                print len(self.neighbourhood_matrices)
            
            self.state = 'threshold'
            return distance_data
            
    def get_clustering_analysis(self, threshold):
        for analysis in self.analysis:
            if isinstance(analysis, Clustering) and analysis.threshold == threshold:
                return analysis
                
        return None
            
    def clusterize(self, threshold, method):
        if method == 'newmangirvan':
            clus_analysis = NewmanGirvan()
            nbh_matrix = self.get_neighbourhood_matrix(threshold)
            clus_analysis.clusterize(nbh_matrix)
            old_clus_analysis = self.get_clustering_analysis(threshold)
            if old_clus_analysis:
                self.analysis.remove(old_clus_analysis)
            self.analysis.append(clus_analysis)
        
    def generate_similarities(self, sequences):
        self.similarity_matrix = self.bio_handler.generate_similarities(sequences)
        self.state = 'similarity_matrix'
        return True
Example #45
0
class Manager(object):

    def __init__(self):
        self._persistence = Persistence()
        self._clients = list()
        self._isConnected = False

    def auth(self):
        if self._isConnected is True:
            print 'FOP 100 - OK'
            return 1
        else:
            print 'FOP 200 - Unauthorized'
            return 0

    def createAccount(self, id, name, password):
        if self.auth():
            account = Account(id)
            client = Client(name, account, password)
            self._clients.append(client)
            return client

    def connectAccount(self, id, password):
        for c in self._clients:
            if c.id == id:
                if c.password == password:
                    self._isConnected = True
                    print 'FOP 100 - OK'
                    return c
                else:
                    print 'FOP 200 - Unauthorized'
                    return None
            
    def lookForClientByID(self, id):
        if self.auth():
            for c in self._clients:
                if c.id == id:
                    print 'FOP 100 - OK'
                    return c
            return None


    def lookForClientByName(self, name):
        if self.auth():
            for c in self._clients:
                if c.name == name:
                    print 'FOP 100 - OK'
                    return c
            return None


    def removeClient(self, name):
        if self.auth():
            c = self.lookForClientByName(name)
            self._clients.remove(c)

    def removeClient(self, id):
        if self.auth():
            c = self.lookForClientByID(id)
            self._clients.remove(c)

    def listClients(self):
        if self.auth():
            for c in self._clients:
                print c.toDict()

    def genReport(self):
        if self.auth():
            reports = list()
            for c in self._clients:
                reports.append(c.genReport())
            return reports

    def save(self):
        self._persistence.save(self._clients)

    def refresh(self):
        self._persistence = Persistence()
        self.load()

    def load(self):
        try:
            self._clients = self._persistence.load()
        except:
            print 'No clients existing.'
            print 'Please define a starting account.'
            id = int(raw_input("Please enter an ID: "))
            name = str(raw_input("Please enter a name: "))
            password = str(raw_input("Please enter a password: "******"Account created."
Example #46
0
 def refresh(self):
     self._persistence = Persistence()
     self.load()