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')
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()
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
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)
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)
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, "/")
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)
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 __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 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)
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)
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 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
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()
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
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)
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)
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)
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()
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 __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
def list_games(player_id): persistence = Persistence(db) game_summary = persistence.list_games(player_id) return json.dumps(game_summary)
def list_all_games(): persistence = Persistence(db) game_summary = persistence.list_games(None) return json.dumps(game_summary)
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 __init__(self, persist=None): '''Creates a persistence instance if one is provided.''' if not persist: self._persist = Persistence() else: self._persist = persist
def get_persistence(name="./tsdl.sqlite3") -> Persistence: return Persistence(name)
def get_records(): data = Persistence().get_gateway_records() return jsonify(data)
import unittest from stub_quiz import Quiz, Question, MultipleChoice from take_quiz import QuizInProgress, TakingQuiz from persistence import Persistence storage = Persistence() q = Quiz(3) c1 = MultipleChoice("question1", "one", ["one", "two", "three", "nine"]) c2 = MultipleChoice("question2", "two", ["one", "two", "three", "four"]) c3 = MultipleChoice("question3", "three", ["one", "six", "three", "four"]) c4 = MultipleChoice("question4", "four", ["five", "two", "three", "four"]) c5 = MultipleChoice("question4", "four", ["five", "two", "three", "four"]) c1.set_quest_id(1) c2.set_quest_id(2) c3.set_quest_id(3) c4.set_quest_id(4) c5.set_quest_id(5) mylist = [] mylist.append(c1) mylist.append(c2) mylist.append(c3) mylist.append(c4) mylist.append(c5) for i in mylist: q.addQuest(i) qp = QuizInProgress() qp.setQuizId("1111") tq = TakingQuiz(qp) class TestTakingQuiz(unittest.TestCase): def test_submit(self):
from flask import request, jsonify, Flask import json from flask_cors import CORS from persistence import Persistence persistence = Persistence() app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/get_by_name', methods=["POST"]) def get_by_name(): data = json.loads(request.data) first_name = data['first_name'] last_name = data['last_name'] return persistence.get_by_name(first_name, last_name) @app.route('/get_by_city', methods=["POST"]) def get_by_city(): data = json.loads(request.data) city = data['city'] return persistence.get_by_city(city)
if time_ago < 60: return str(int(round(time_ago))) + " seconds" time_ago = time_ago / 60 if time_ago < 60: return str(int(round(time_ago))) + " minutes" time_ago = time_ago / 60 if time_ago / 60 < 24: return str(int(round(time_ago))) + " hours" time_ago = time_ago / 24 if time_ago < 12: return str(int(round(time_ago))) + " months" time_ago = time_ago / 12 return str(int(round(time_ago))) + " years" if __name__ == '__main__': repository = Persistence(os.environ['DB_PATH'], logging.getLogger(__name__)) repository.init_db( [User.get_table_creation(), Contribution.get_table_creation(), UserContributionVoted.get_table_creation(), Comment.get_table_creation(), UserCommentVoted.get_table_creation()]) basicConfig(filename=os.environ['LOG'], level=INFO) app.config.update(TEMPLATES_AUTO_RELOAD=True) app.run(host=str(os.environ['HOST']), port=int(os.environ['PORT']), threaded=True)