def __init__(self): # Set up all the logging self.logger = logging.getLogger('TweGeT') logging.basicConfig( level=logging.DEBUG, format=u'%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') handler = logging.StreamHandler(sys.stderr) handler.setLevel(logging.CRITICAL) formatter = logging.Formatter( u'%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') fhandler = logging.FileHandler("twet.log", 'w', 'utf-8') fhandler.setFormatter(formatter) handler.setFormatter(formatter) self.logger.addHandler(handler) self.logger.addHandler(fhandler) self.log_queue = Queue() self.queue_handler = QueueHandler(self.log_queue) self.logger.addHandler(self.queue_handler) self.settings_manager = SettingsManager() if self.system_type == WINDOWS: self.which_command = "where" self.shell = True self.cmd_extension = self.WINDOWS_CMD_EXT if self.system_type == DARWIN: self.icon_type = ("Iconset", "*.icns")
def update_alarm(): settings_manager = SettingsManager() settings = settings_manager.get_settings() # print request.form day_map = { 'sunday_time': '0', 'monday_time': '1', 'tuesday_time': '2', 'wednesday_time': '3', 'thursday_time': '4', 'friday_time': '5', 'saturday_time': '6', } form_day_name = request.form['day'] alarms = settings['settings']['alarms'] if form_day_name in day_map: weekday_number = day_map[form_day_name] alarms[weekday_number]['time'] = request.form['alarm_time'] settings['settings']['alarms'] = alarms settings_manager.set_settings(settings) return "";
def main(): # create the Application app = QtWidgets.QApplication(sys.argv) # create the event loop event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # Create the Gui main_window = MainWindow() # plugins to include different websites (and listeners?) plugin_manager = PluginManager() plugin_manager.register_main_window(main_window) # User Settings settings_manager = SettingsManager() settings_manager.register_main_window(main_window) settings_manager.register_plugin_manager(plugin_manager) main_window.show() try: event_loop.run_forever() except KeyboardInterrupt: pass app.deleteLater() plugin_manager.terminate_plugins() event_loop.close() sys.exit()
def __init__(self): QtCore.QObject.__init__(self) self.comic = None self.settings_manager = SettingsManager() self.rotate_angle = 0 self.scroll_area_size = None self.fit_type = self.load_view_adjust(MainWindowModel._ORIGINAL_FIT) self.current_directory = self.load_current_directory() ext_list = ["*.cbr", "*.cbz", "*.rar", "*.zip", "*.tar", "*.cbt"] self.path_file_filter = PathFileFilter(ext_list)
def test_get_config(self): with tempfile.TemporaryDirectory() as dname: print(dname) # /tmp/tmpl2cvqpq5 test_yaml = os.path.join(dname, "test.yaml") with open(test_yaml, "w") as f: yaml.dump(self.sample_config(), f) conf = SettingsManager() conf.load(test_yaml) assert conf.input_file_path == 'input' assert conf.template_file_path == 'template' assert conf.save_directory == 'save' assert conf.save_file_name == 'file'
def __init__(self): QtCore.QObject.__init__(self) self.comic = None self.settings_manager = SettingsManager() self.rotate_angle = 0 self.scroll_area_size = None self.fit_type = self.load_view_adjust(MainWindowModel._ORIGINAL_FIT) self.current_directory = self.load_current_directory() ext_list = ["*.cbr", "*.cbz", "*.rar", "*.zip", "*.tar", "*.cbt"] self.path_file_filter = PathFileFilter(ext_list)
def main(): config_file_path = os.path.join(os.path.dirname(sys.argv[0]), "config.yaml") conf = SettingsManager() conf.load(config_file_path) target = open(conf.target_file_path, "rb") reader = PyPDF2.PdfFileReader(target) writer = PyPDF2.PdfFileWriter() print("対象PDF:{0}".format(conf.target_file_path)) print("出力ファイルパス:{0}".format(conf.out_file_path)) print("回転角度:{0}度".format(conf.rotate)) for page in range(reader.numPages): obj = reader.getPage(page) obj.rotateClockwise(conf.rotate) # 回転させる writer.addPage(obj) outfile = open(conf.out_file_path, "wb") writer.write(outfile) outfile.close() target.close()
def main(): # create the Application app = QtWidgets.QApplication(sys.argv) # create the event loop event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # Create the Gui main_window = MainWindow() # plugins to include different websites (and listeners?) plugin_manager = PluginManager() plugin_manager.register_main_window(main_window) # User Settings settings_manager = SettingsManager() settings_manager.register_main_window(main_window) settings_manager.register_plugin_manager(plugin_manager) # listeners handeled separatly for now listener_interface = pluginmanager.PluginInterface() listener_interface.collect_plugins(plugins) listener_list = listener_interface.get_instances() # flake8: noqa # main_window.central_widget.message_area.listeners = listener_list main_window.show() try: event_loop.run_forever() except KeyboardInterrupt: pass app.deleteLater() plugin_manager.terminate_plugins() event_loop.close() sys.exit()
def __init__(self, *args, **kwargs): def settings_save_callback(*args, **kwargs): self.rtorrent.open(self.cfg.get("DEFAULT",'rTorrent URL')) self.cfg = SettingsManager(APP_NAME+'.cfg', { 'rtorrent url': 'http://localhost/RPC2', 'remote root': '/' }, settings_save_callback) self.rtorrent = xmlrpcdaemon.XMLRPCDaemon( # Can't shorten this one! self.cfg.get("rTorrent URL")) self.rtorrent.start() wx.App.__init__(self, *args, **kwargs) self.updater = UpdateScheduler(self) self.updater.start() self.Bind(wx.EVT_ACTIVATE_APP, self.activate)
def __init__(self, signal_want_tv_window=None): super(TVMainWindow, self).__init__() # use this when embedded in tv_browser if signal_want_tv_window: signal_want_tv_window.connect(self.show_window) # user's preferred TV file path self.preferred_tv_dir = os.path.expanduser("~") # user's preferred JPG graph path self.preferred_graph_dir = os.path.expanduser("~") # settings manager self.settings_manager = SettingsManager() # data manager self.tv_data_manager = TVDataManager( settings, self.settings_manager.signal_settings_changed) # scale manager self.tv_scale_manager = TVScaleManager() # main window self.w = QMainWindow() # main window decoration self.w.setGeometry(0, 0, 950, 900) self.w.setWindowTitle("Texture Vector Similarity Version %s" % VERSION) self.w.setWindowIcon(QIcon(window_icon)) # the graph main widget self.tv_graph_widget = TVGraphWidget( self.tv_data_manager.signal_data_loaded, self.tv_scale_manager.signal_tv_scale_changed) # the graph self.w.setCentralWidget(self.tv_graph_widget.view) # actions self.define_actions() # sketch checkbox self.tv_sketch_cb = TVSketchCB(self.tv_data_manager) # toolbar self.add_toolbar()
def initialize_settings(): #create instance of settings manager settings = SettingsManager("settings.json") #initialize settings #debug settings.add_setting("debug", "Display extra debuging output on screen?", "False", ("True", "False")) #orientation orientation_setting_description = "This flips the map and the tokens so they are facing players\n" orientation_setting_description += "that are sitting across from the dm.\n" orientation_setting_description += "It also displays messages on all 4 sides of the screen facing outward,\n" orientation_setting_description += "instead of just one at the bottom." settings.add_setting("table_top_orientation", orientation_setting_description, "False", ("True", "False")) #return the settings manager return settings
def save_ui_info(self): settings = SettingsManager(CONFIG_FILE) settings.save(self.ui.load_path_edit) settings.save(self.ui.override_velocity_edit)
def save_ui_info(self): settings = SettingsManager(CONFIG_FILE) settings.save(self.ui.root_dir_edit) settings.save(self.ui.title_edit) settings.save(self.ui.description_edit) settings.save(self.ui.command_option_edit) settings.save(self.ui.can_device_edit) settings.save(self.ui.candump_checkbox)
def load_ui_info(self): settings = SettingsManager(CONFIG_FILE) settings.load(self.ui.root_dir_edit) settings.load(self.ui.title_edit) settings.load(self.ui.description_edit) settings.load(self.ui.command_option_edit) settings.load(self.ui.can_device_edit) settings.load(self.ui.candump_checkbox) # Set default value if self.ui.can_device_edit.text() == '': self.ui.can_device_edit.setText('can0') self.ui.candump_checkbox.setEnabled(self.found_candump)
def get_settings_path(): path = Utility.get_dir_name(SettingsManager().settings.fileName()) return path + u'/bookmark.db'
class MainWindowModel(QtCore.QObject): _ORIGINAL_FIT = 'action_original_fit' _VERTICAL_FIT = 'action_vertical_fit' _HORIZONTAL_FIT = 'action_horizontal_fit' _BEST_FIT = 'action_best_fit' load_progress = QtCore.Signal(int) load_done = QtCore.Signal() def __init__(self): QtCore.QObject.__init__(self) self.comic = None self.settings_manager = SettingsManager() self.rotate_angle = 0 self.scroll_area_size = None self.fit_type = self.load_view_adjust(MainWindowModel._ORIGINAL_FIT) self.current_directory = self.load_current_directory() ext_list = ["*.cbr", "*.cbz", "*.rar", "*.zip", "*.tar", "*.cbt"] self.path_file_filter = PathFileFilter(ext_list) def save_recent_files(self, recent_files_list): self.settings_manager.save_recent_files(recent_files_list) def load_recent_files(self): return self.settings_manager.load_recent_files() def save_view_adjust(self, object_name): self.settings_manager.save_view_adjust(object_name) def load_view_adjust(self, default_object_name): return self.settings_manager.load_view_adjust(default_object_name) def save_current_directory(self, current_directory): self.settings_manager.save_current_directory(current_directory) def load_current_directory(self): return self.settings_manager.load_current_directory() def load(self, filename, initial_page=0): image_extensions = [ '.bmp', '.jpg', '.jpeg', '.gif', '.png', '.pbm', '.pgm', '.ppm', '.tiff', '.xbm', '.xpm', '.webp' ] ld = LoaderFactory.create_loader(Utility.get_file_extension(filename), set(image_extensions)) ld.progress.connect(self.load_progressbar_value) try: ld.load(filename) except NoDataFindException as excp: # Caso nao exista nenhuma imagem, carregamos a imagem indicando # erro from page import Page print excp.message q_file = QtCore.QFile(":/icons/notCover.png") q_file.open(QtCore.QIODevice.ReadOnly) ld.data.append(Page(q_file.readAll(), 'exit_red_1.png', 0)) self.comic = Comic(Utility.get_base_name(filename), Utility.get_dir_name(filename), initial_page) self.comic.pages = ld.data self.current_directory = Utility.get_dir_name(filename) self.path_file_filter.parse(filename) def save_current_page_image(self, file_name): self.get_current_page().save(file_name) def next_page(self): if self.comic: self.comic.go_next_page() def previous_page(self): if self.comic: self.comic.go_previous_page() def first_page(self): if self.comic: self.comic.go_first_page() def last_page(self): if self.comic: self.comic.go_last_page() def next_comic(self): return self.path_file_filter.next_path.decode('utf-8') def previous_comic(self): return self.path_file_filter.previous_path.decode('utf-8') def rotate_left(self): self.rotate_angle = (self.rotate_angle - 90) % 360 def rotate_right(self): self.rotate_angle = (self.rotate_angle + 90) % 360 def get_comic_name(self): return self.comic.name if self.comic else '' def get_comic_title(self): return self.comic.name + ' - Pynocchio Comic Reader' def get_current_page(self): if self.comic: pix_map = self.comic.get_current_page().pixmap pix_map = self._rotate_page(pix_map) pix_map = self._resize_page(pix_map) return pix_map return None def get_current_page_title(self): return self.comic.get_current_page_title() if self.comic else '' def set_current_page_index(self, idx): if self.comic: self.comic.set_current_page_index(idx) def get_current_page_index(self): return self.comic.current_page_index if self.comic else -1 def is_first_page(self): if self.comic and self.comic.current_page_index == 0: return True return False def is_last_page(self): if self.comic and self.comic.current_page_index + 1 == \ self.comic.get_number_of_pages(): return True return False def is_firts_comic(self): return self.path_file_filter.is_first_file() def is_last_comic(self): return self.path_file_filter.is_last_file() def _rotate_page(self, pix_map): if self.rotate_angle != 0: trans = QtGui.QTransform().rotate(self.rotate_angle) pix_map = QtGui.QPixmap(pix_map.transformed(trans)) return pix_map def _resize_page(self, pix_map): if self.fit_type == MainWindowModel._VERTICAL_FIT: pix_map = pix_map.scaledToHeight(self.scroll_area_size.height(), QtCore.Qt.SmoothTransformation) elif self.fit_type == MainWindowModel._HORIZONTAL_FIT: pix_map = pix_map.scaledToWidth(self.scroll_area_size.width(), QtCore.Qt.SmoothTransformation) elif self.fit_type == MainWindowModel._BEST_FIT: pix_map = pix_map.scaledToWidth( self.scroll_area_size.width() * 0.8, QtCore.Qt.SmoothTransformation) return pix_map def original_fit(self): self.fit_type = MainWindowModel._ORIGINAL_FIT def vertical_fit(self): self.fit_type = MainWindowModel._VERTICAL_FIT def horizontal_fit(self): self.fit_type = MainWindowModel._HORIZONTAL_FIT def best_fit(self): self.fit_type = MainWindowModel._BEST_FIT @QtCore.Slot(int) def load_progressbar_value(self, percent): self.load_progress.emit(percent) @QtCore.Slot() def load_progressbar_done(self): self.load_done.emit() def save_settings(self): self.save_view_adjust(self.fit_type) self.save_current_directory(self.current_directory) @staticmethod def get_bookmark_list(n): BookmarkManager.connect() bookmark_list = BookmarkManager.get_bookmarks(n) BookmarkManager.close() return bookmark_list def is_bookmark(self): BookmarkManager.connect() is_bookmark = BookmarkManager.is_bookmark(self.comic.get_path()) BookmarkManager.close() return is_bookmark @staticmethod def get_bookmark_from_path(path): BookmarkManager.connect() bk = BookmarkManager.get_bookmark_by_path(path) BookmarkManager.close() return bk def add_bookmark(self): if self.comic: BookmarkManager.connect() BookmarkManager.add_bookmark(self.comic.name, self.comic.get_path(), self.comic.get_current_page_number(), self.comic.get_current_page().data) BookmarkManager.close() def remove_bookmark(self): if self.comic: BookmarkManager.connect() BookmarkManager.remove_bookmark(self.comic.get_path()) BookmarkManager.close()
class Core: log_queue = None logger = None queue_handler = None settings_manager = None icon_type = ("Icon files", "*.ico") ON_POSIX = 'posix' in sys.builtin_module_names LIB_DICT_NAME = "libs" PROJECT_DICT_NAME = "project" AUTHOR_DICT_NAME = "author" UPDATED_TIME_KEY = "last_updated_at" BUILD_DIR_KEY = "build_directory" libs = {NPM_LOCATION: "", NPX_LOCATION: "", TWEEGO_LOCATION: ""} project = { PROJ_NAME: "", PROJ_DIR: "", PROJ_HTML: "", PROJ_PARENT_DIR: "", PROJ_BUILD_DIR: "", PROJ_VERSION: "1.0.0", PROJ_DIMS_HEIGHT: "600", PROJ_DIMS_WIDTH: "800", PROJ_ICON_LOCATION: "", PROJ_KEYWORDS: "", PROJ_LAST_UPDATED: "" } author = { AUTHOR_NAME: "Your Name", AUTHOR_EMAIL: "", AUTHOR_REPO: "", } # I cannot find a nicer way of doing this without installing additional packages processes = [] entry_size = (20, 1) system_type = platform.system() # System dependent variables which_command = "which" shell = False lock = threading.Lock() cmd_extension = "" WINDOWS_CMD_EXT = ".cmd" def __init__(self): # Set up all the logging self.logger = logging.getLogger('TweGeT') logging.basicConfig( level=logging.DEBUG, format=u'%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') handler = logging.StreamHandler(sys.stderr) handler.setLevel(logging.CRITICAL) formatter = logging.Formatter( u'%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') fhandler = logging.FileHandler("twet.log", 'w', 'utf-8') fhandler.setFormatter(formatter) handler.setFormatter(formatter) self.logger.addHandler(handler) self.logger.addHandler(fhandler) self.log_queue = Queue() self.queue_handler = QueueHandler(self.log_queue) self.logger.addHandler(self.queue_handler) self.settings_manager = SettingsManager() if self.system_type == WINDOWS: self.which_command = "where" self.shell = True self.cmd_extension = self.WINDOWS_CMD_EXT if self.system_type == DARWIN: self.icon_type = ("Iconset", "*.icns") def enqueue_output(self, out, queue): for line in iter(out.readline, b''): string = str(line, encoding="utf-8") try: self.logger.info(string) except: string = line self.logger.info(string) out.close() self.lock.release() def get_bin_path(self, app_name): try: proc = self.test_existence(app_name) location = proc.split("\n")[0].strip() return location except AssertionError: return None # We have a result, now grab the first line of output # Windows note: the first location returned /tends/ to be the binary itself def run_command_with_output(self, commands, cwd=None): process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=False, bufsize=0, text=None, cwd=cwd) self.processes.append(process) t = Thread(target=self.enqueue_output, args=(process.stdout, self.log_queue)) self.lock.acquire(blocking=False) t.start() # Warning: Blocking def run_command_store_output(self, commands, cwd=None): process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, bufsize=0, text=None, cwd=cwd) output = "" for line in iter(process.stdout.readline, b''): output += str(line, encoding="utf-8") process.stdout.close() return output def find_dependencies(self): res = self.get_bin_path( NPM) if not None else self.settings_manager.find_setting(NPM) if res == "": self.logger.info( "NPM cannot be found. It is likely not installed. Please visit https://www.npmjs.com/get-npm to install" ) self.libs[NPM_LOCATION] = res res = self.get_bin_path( NPX) if not None else self.settings_manager.find_setting(NPX) if res == "": self.logger.info( "NPX cannot be found. It is likely not installed. Please visit https://www.npmjs.com/get-npm to install" ) self.libs[NPX_LOCATION] = res res = self.get_bin_path( TWEEGO) if not None else self.settings_manager.find_setting(TWEEGO) if res == "": self.logger.info( "Tweego cannot be found. Either locate its executable or install from https://www.motoslave.net/tweego/" ) self.libs[TWEEGO_LOCATION] = res # TODO Still need to test for StoryFormats def test_existence(self, app_name): the_process = subprocess.run([self.which_command, app_name], universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=self.shell) assert (the_process.stderr == '') return the_process.stdout def create_lock_file(self, path): publish_time_stamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') build_dir = str(path) # Build the data before writing it to file data = { self.UPDATED_TIME_KEY: publish_time_stamp, self.BUILD_DIR_KEY: build_dir, self.AUTHOR_DICT_NAME: self.author, self.LIB_DICT_NAME: self.libs, self.PROJECT_DICT_NAME: self.project } with open(path.joinpath(DETAILS_FILE_NAME), 'w', encoding="utf-8") as f: json.dump(data, fp=f, ensure_ascii=False, indent=4, sort_keys=True) def load_lock_file(self, path): # returns a tuple of the dictionaries # This method ensures that dictionary structure won't be affected with open(path, 'r', encoding="utf-8") as f: data = json.load(f) self.libs = data[self.LIB_DICT_NAME] self.project = data[self.PROJECT_DICT_NAME] self.author = data[self.AUTHOR_DICT_NAME] def update_package_json(self, path): data = None with open(path, 'r', encoding="utf-8") as f: data = json.load(f) # keywords = data["keywords"] data["keywords"] = self.project[PROJ_KEYWORDS].split(",") data["author"]["name"] = self.author[AUTHOR_NAME] data["author"]["email"] = self.author[AUTHOR_EMAIL] data["repository"] = self.author[AUTHOR_EMAIL] data["version"] = self.project[PROJ_VERSION] data["config"]["forge"]["packagerConfig"] = {"icon": "icon"} with open(path, 'w', encoding="utf-8") as f: json.dump(data, fp=f, indent=4) def terminate_processes(self): # this == ugly but it'll work until I improve it self.logger.info("Ending other tasks") for p in self.processes: if p.returncode is None: p.terminate() self.logger.info("All tasks finished, can safely close now.") def replace_js_parameters(self, path): js = None with open(resource_path(INDEX_JS_TEMPLATE_PATH), 'r') as f: js = f.read() js = js.replace(JS_HEIGHT_KEY, self.project[PROJ_DIMS_HEIGHT]).replace( JS_WIDTH_KEY, self.project[PROJ_DIMS_WIDTH]) with open(path, 'w') as f: f.write(js) def write_settings(self): self.settings_manager.write_out_settings(self.libs) def read_settings(self): m, x, t = self.settings_manager.read_in_settings() if m is None and x is None and t is None: return if self.libs[NPM_LOCATION] == "": self.libs[NPM_LOCATION] = m if self.libs[NPX_LOCATION] == "": self.libs[NPX_LOCATION] = x if self.libs[TWEEGO_LOCATION] == "": self.libs[TWEEGO_LOCATION] = t
from settings_manager import SettingsManager, SettingsManagerFrame import tkinter as tk from tkinter import ttk s = SettingsManager("settings.json") s.add_setting("debug", "should the application produce extra debugging output?", "False", ("True", "False")) s.add_setting("width", "width? i dont know how to do ranges", "640", ("range", "100", "1000")) s.add_setting("height", "description for height", "480", ("range", "100", "1000")) s.add_setting("test", "a test setting.\nthis description has a new line in it", "abc", ("abc", "123", "456", "789")) s.add_setting( "test2", "just adding another setting\nto see if adding a new one works after\neverythuing is in place", "abc", ("abc", "123", "456", "789")) #s.print_test() root = tk.Tk() frame = SettingsManagerFrame(root, s) frame.pack() root.mainloop()
class MainWindowModel(QtCore.QObject): _ORIGINAL_FIT = 'action_original_fit' _VERTICAL_FIT = 'action_vertical_fit' _HORIZONTAL_FIT = 'action_horizontal_fit' _BEST_FIT = 'action_best_fit' load_progress = QtCore.Signal(int) load_done = QtCore.Signal() def __init__(self): QtCore.QObject.__init__(self) self.comic = None self.settings_manager = SettingsManager() self.rotate_angle = 0 self.scroll_area_size = None self.fit_type = self.load_view_adjust(MainWindowModel._ORIGINAL_FIT) self.current_directory = self.load_current_directory() ext_list = ["*.cbr", "*.cbz", "*.rar", "*.zip", "*.tar", "*.cbt"] self.path_file_filter = PathFileFilter(ext_list) def save_recent_files(self, recent_files_list): self.settings_manager.save_recent_files(recent_files_list) def load_recent_files(self): return self.settings_manager.load_recent_files() def save_view_adjust(self, object_name): self.settings_manager.save_view_adjust(object_name) def load_view_adjust(self, default_object_name): return self.settings_manager.load_view_adjust(default_object_name) def save_current_directory(self, current_directory): self.settings_manager.save_current_directory(current_directory) def load_current_directory(self): return self.settings_manager.load_current_directory() def load(self, filename, initial_page=0): image_extensions = ['.bmp', '.jpg', '.jpeg', '.gif', '.png', '.pbm', '.pgm', '.ppm', '.tiff', '.xbm', '.xpm', '.webp'] loader = LoaderFactory.create_loader( Utility.get_file_extension(filename), set(image_extensions)) loader.progress.connect(self.load_progressbar_value) try: loader.load(filename) except NoDataFindException as excp: # Caso nao exista nenhuma imagem, carregamos a imagem indicando # erro from page import Page print excp.message q_file = QtCore.QFile(":/icons/notCover.png") q_file.open(QtCore.QIODevice.ReadOnly) loader.data.append(Page(q_file.readAll(), 'exit_red_1.png', 0)) self.comic = Comic(Utility.get_base_name(filename), Utility.get_dir_name(filename), initial_page) self.comic.pages = loader.data self.current_directory = Utility.get_dir_name(filename) self.path_file_filter.parse(filename) def save_current_page_image(self, file_name): self.get_current_page().save(file_name) def next_page(self): if self.comic: self.comic.go_next_page() def previous_page(self): if self.comic: self.comic.go_previous_page() def first_page(self): if self.comic: self.comic.go_first_page() def last_page(self): if self.comic: self.comic.go_last_page() def next_comic(self): return self.path_file_filter.next_path.decode('utf-8') def previous_comic(self): return self.path_file_filter.previous_path.decode('utf-8') def rotate_left(self): self.rotate_angle = (self.rotate_angle - 90) % 360 def rotate_right(self): self.rotate_angle = (self.rotate_angle + 90) % 360 def get_comic_name(self): return self.comic.name if self.comic else '' def get_comic_title(self): return self.comic.name + ' - Pynocchio Comic Reader' def get_current_page(self): if self.comic: pix_map = self.comic.get_current_page().pixmap pix_map = self._rotate_page(pix_map) pix_map = self._resize_page(pix_map) return pix_map return None def get_current_page_title(self): return self.comic.get_current_page_title() if self.comic else '' def set_current_page_index(self, idx): if self.comic: self.comic.set_current_page_index(idx) def get_current_page_index(self): return self.comic.current_page_index if self.comic else -1 def is_first_page(self): if self.comic and self.comic.current_page_index == 0: return True return False def is_last_page(self): if self.comic and self.comic.current_page_index + 1 == \ self.comic.get_number_of_pages(): return True return False def is_firts_comic(self): return self.path_file_filter.is_first_file() def is_last_comic(self): return self.path_file_filter.is_last_file() def _rotate_page(self, pix_map): if self.rotate_angle != 0: trans = QtGui.QTransform().rotate(self.rotate_angle) pix_map = QtGui.QPixmap(pix_map.transformed(trans)) return pix_map def _resize_page(self, pix_map): if self.fit_type == MainWindowModel._VERTICAL_FIT: pix_map = pix_map.scaledToHeight( self.scroll_area_size.height(), QtCore.Qt.SmoothTransformation) elif self.fit_type == MainWindowModel._HORIZONTAL_FIT: pix_map = pix_map.scaledToWidth( self.scroll_area_size.width(), QtCore.Qt.SmoothTransformation) elif self.fit_type == MainWindowModel._BEST_FIT: pix_map = pix_map.scaledToWidth( self.scroll_area_size.width() * 0.8, QtCore.Qt.SmoothTransformation) return pix_map def original_fit(self): self.fit_type = MainWindowModel._ORIGINAL_FIT def vertical_fit(self): self.fit_type = MainWindowModel._VERTICAL_FIT def horizontal_fit(self): self.fit_type = MainWindowModel._HORIZONTAL_FIT def best_fit(self): self.fit_type = MainWindowModel._BEST_FIT @QtCore.Slot(int) def load_progressbar_value(self, percent): self.load_progress.emit(percent) @QtCore.Slot() def load_progressbar_done(self): self.load_done.emit() def save_settings(self): self.save_view_adjust(self.fit_type) self.save_current_directory(self.current_directory) @staticmethod def get_bookmark_list(qty): BookmarkManager.connect() bookmark_list = BookmarkManager.get_bookmarks(qty) BookmarkManager.close() return bookmark_list def is_bookmark(self): BookmarkManager.connect() is_bookmark = BookmarkManager.is_bookmark(self.comic.get_path()) BookmarkManager.close() return is_bookmark @staticmethod def get_bookmark_from_path(path): BookmarkManager.connect() bookmark = BookmarkManager.get_bookmark_by_path(path) BookmarkManager.close() return bookmark def add_bookmark(self): if self.comic: BookmarkManager.connect() BookmarkManager.add_bookmark(self.comic.name, self.comic.get_path(), self.comic.get_current_page_number(), self.comic.get_current_page().data) BookmarkManager.close() def remove_bookmark(self): if self.comic: BookmarkManager.connect() BookmarkManager.remove_bookmark(self.comic.get_path()) BookmarkManager.close()
from settings_manager import SettingsManager my_settings = SettingsManager() settings = my_settings.get_settings() print settings # my_settings.set_settings(settings)
def get_settings(): settings_manager = SettingsManager() return jsonify(settings_manager.get_settings())
def main(): config_file_path = os.path.join(os.path.dirname(__file__), 'config.yaml') conf = SettingsManager() conf.load(config_file_path) report_instance = ReportInsured(conf) report_instance.generate()
import asyncio from os import name import discord from discord.activity import Activity from discord.embeds import Embed from discord.enums import ActivityType from discord.permissions import Permissions from typing import Deque, Union, Tuple from dotenv import load_dotenv from collections import deque from settings_manager import SettingsManager load_dotenv() TOKEN=os.getenv("TOKEN") client = discord.Client() o = True sm = SettingsManager() str_or_None = Union[str, None] lis: Deque[Tuple[str_or_None, str_or_None]] = deque([(None,None)]*100, maxlen=100) def get_role(guild, name) -> discord.Role: tc = discord.utils.find(lambda g: g.name==name, guild.roles) return tc def get_channel(guild, id): tc = discord.utils.find(lambda g: g.id==id, guild.channels) return tc @client.event async def on_ready(): print("-\n".join(x.name for x in client.guilds))
def save_ui_info(self): settings = SettingsManager(CONFIG_FILE) settings.save(self.ui.save_path_edit)
class wrtcApp(wx.App): def __init__(self, *args, **kwargs): def settings_save_callback(*args, **kwargs): self.rtorrent.open(self.cfg.get("DEFAULT",'rTorrent URL')) self.cfg = SettingsManager(APP_NAME+'.cfg', { 'rtorrent url': 'http://localhost/RPC2', 'remote root': '/' }, settings_save_callback) self.rtorrent = xmlrpcdaemon.XMLRPCDaemon( # Can't shorten this one! self.cfg.get("rTorrent URL")) self.rtorrent.start() wx.App.__init__(self, *args, **kwargs) self.updater = UpdateScheduler(self) self.updater.start() self.Bind(wx.EVT_ACTIVATE_APP, self.activate) def OnInit(self): self.frame = MainWindow(None, wx.ID_ANY, APP_NAME+" - wxPython rTorrent client") self.frame.Show() if len(sys.argv) > 1 and os.path.isfile(sys.argv[1]): self.load_torrent(filename=sys.argv[1]) return True def raise_frame(self): try: self.frame.Raise() except: pass def activate(self, evt): if evt.GetActive(): self.raise_frame() evt.Skip() def MacOpenFile(self, filename): self.load_torrent(filename=filename) def MacReopenApp(self, *args, **kwargs): self.raise_frame() def load_torrent(self,e=None,filename=None): dlg = LoadTorrentDialog(self.cfg.get('remote root')) if filename: dlg.filepath.SetValue(filename) if dlg.ShowModal() == wx.ID_OK: self.send_torrent(dlg) dlg.Destroy() def send_torrent(self, dlg): start = dlg.start_immediate.GetValue() dest = dlg.browser.GetPyData(dlg.browser.GetSelection())['path'] if dlg.filepath.GetValue() != '': torrent_file = open(dlg.filepath.GetValue(),'rb') elif dlg.url.GetValue() != '': import urllib2 torrent_file = urllib2.urlopen(dlg.url.GetValue()) torrent_data = torrent_file.read() torrent_file.close() infohash = make_hash(torrent_data) torrent_data = Binary(torrent_data) def dest_callback(rv): def start_callback(rv): if start: self.rtorrent.put(('d.start', infohash)) self.rtorrent.put(('d.set_directory', (infohash, dest), start_callback)) self.rtorrent.put(('load_raw', torrent_data, dest_callback))