def __init__(self): super(Controller, self).__init__() self.daemon = True self.exit_event = threading.Event() #self.plugins = plugins.load_all() self.buttons = buttons.ButtonReader(config.BUTTONS_EVDEV_FILE) self.buttons.register(self.buttons_callback) self.buttons.start() self.queue = Queue.Queue() self.queue_do = Queue.Queue() dummy_parameter = "dummy_parameter" self.sensors = sensors.SensorReader(dummy_parameter) self.sensors.register(self.sensors_callback) self.sensors.start() self.queue_sensors = Queue.Queue() self.folder_index = -1 self.folders = config.MUSIC_FOLDERS self.mpd = mpd.MPDClient() self.mpd.connect('127.0.0.1', 6600) self.led = leds.LED(config.LED_NAME) self.updater = updater.Updater() self.justBooted() self.saved_song = 0 self.saved_time = 0
def is_updated(self): """ Checks that cnchi version is, at least, latest stable """ if not self.updater: # Only call updater once self.updater = updater.Updater( local_cnchi_version=info.CNCHI_VERSION) return not self.updater.is_remote_version_newer()
def getUpdateFileName(self): try: fn = QFileDialog.getOpenFileName(self, 'Open file', os.getcwd(), "Zip file (*.zip)") self.updaterLoc = fn[0] except: #print("No file selected.") pass if self.updaterLoc != None: self.ui.pathField.setText(self.updaterLoc) self.updater = updater_.Updater(self.updaterLoc) self.ui.pathField.setText(self.updaterLoc)
def run_update(self): try: self.updater = updater.Updater(self.id, self.api, self.set_status) self.set_status('starting update...') self.updater.ping_server('starting') self.updater.load_config() with open('data.json') as data_file: self.settings = json.load(data_file) if self.settings['Success'] == False: self.set_status('bad json file...') self.updater.ping_server('Error or no content') self.updater.sync_content() except Exception as ex: self.set_status('error: %s' % ex)
def init_thus(): """ This function initialises Thus """ # Command line options global cmd_line if not check_gtk_version(): sys.exit(1) # Command line options global cmd_line cmd_line = parse_options() #setup_logging() if cmd_line.update is not None: force = False if cmd_line.update == 2: force = True upd = updater.Updater(force) if upd.update(): # Remove /tmp/.setup-running to be able to run another # instance of Thus remove_temp_files() if force: # Remove -uu option new_argv = [] for argv in sys.argv: if argv != "-uu": new_argv.append(argv) else: new_argv = sys.argv print("Program updated! Restarting...") # Run another instance of Thus (which will be the new version) os.execl(sys.executable, *([sys.executable] + new_argv)) sys.exit(0) # Drop root privileges misc.drop_privileges() # Start Gdk stuff and main window app GObject.threads_init() myapp = Main() Gtk.main()
def update_cnchi(): force = False if cmd_line.update == 2: force = True upd = updater.Updater(force) if upd.update(): remove_temp_files() if force: # Remove -uu option new_argv = [] for argv in sys.argv: if argv != "-uu": new_argv.append(argv) else: new_argv = sys.argv print(_("Program updated! Restarting...")) # Run another instance of Cnchi (which will be the new version) os.execl(sys.executable, *([sys.executable] + new_argv)) sys.exit(0)
def updateFirmware(self): self.updaterLoc = self.ui.pathField.text() if self.updaterLoc != None: self.updater = updater_.Updater(self.updaterLoc) stat = self.updater.validateApp() msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setStandardButtons(QMessageBox.Ok) if stat == 1: self.updater.updateApp() msg.setText("Linguis is updated to version " + str(self.updater.updater_ver)) msg.setWindowTitle("Updated.") elif stat == 0: msg.setText("Linguis is already in the latest version.") msg.setWindowTitle("Not updated.") else: msg.setText("Invalid installer package") msg.setWindowTitle("Not updated.") msg.exec_()
def update_cnchi(): """ Runs updater function to update cnchi to the latest version if necessary """ upd = updater.Updater(force_update=cmd_line.update) if upd.update(): #remove_temp_files() if cmd_line.update: # Remove -uu and --update options from new call new_argv = [] for argv in sys.argv: if argv != "-uu" and argv != "--update": new_argv.append(argv) else: new_argv = sys.argv print(_("Program updated! Restarting...")) # Run another instance of Cnchi (which will be the new version) with misc.raised_privileges(): os.execl(sys.executable, *([sys.executable] + new_argv)) sys.exit(0)
def __init__(self): config.Config.instance().set_app_pointer(self) self.logger = log.create_logger('', log.LOG_FILE) self.logger.info("Starting 3DPrinterOS client. Version %s_%s" % (version.version, version.build)) self.logger.info('Operating system: ' + platform.system() + ' ' + platform.release()) signal.signal(signal.SIGINT, self.intercept_signal) signal.signal(signal.SIGTERM, self.intercept_signal) self.detected_printers = [] self.network_printers = [] self.printer_interfaces = [] self.virtual_printer_enabled = False self.network_detect_flag = False self.stop_flag = False self.closing_status = [] self.rights_checker_waiter = rights.RightsCheckerWaiter(self) self.conveyor_kill_waiter = makerware_utils.ConveyorKillWaiter(self) self.network_connection_checker = http_client.NetworkConnectionChecker( self) self.init_interface() self.rights_checker_waiter.wait() self.conveyor_kill_waiter.wait() self.network_connection_checker.wait() self.updater = updater.Updater() self.user_login = user_login.UserLogin(self) self.user_login.wait() if self.user_login.user_token and hasattr(self.user_login, "profiles"): config.Config.instance().set_profiles(self.user_login.profiles) self.virtual_printer_enabled = config.get_settings( )['virtual_printer']['enabled'] self.tray_controller = tray_controller.TrayController() self.camera_controller = camera_controller.CameraController(self.user_login.user_token,\ self.user_login.http_client.mac) self.cloud_sync_controller = cloud_sync_controller.CloudSyncController( ) else: self.logger.error( "Can't retrieve user login or printer profiles. Exiting...") self.quit()
def update_thus(): """ Runs updater function to update thus to the latest version if necessary """ upd = updater.Updater(force_update=cmd_line.update) if upd.update(): logging.info(_("Program updated! Restarting...")) misc.remove_temp_files() if cmd_line.update: # Remove -u and --update options from new call new_argv = [] for argv in sys.argv: if argv != "-u" and argv != "--update": new_argv.append(argv) else: new_argv = sys.argv # Do not try to update again now new_argv.append("--disable-update") # Run another instance of Thus (which will be the new version) with misc.raised_privileges(): os.execl(sys.executable, *([sys.executable] + new_argv)) sys.exit(0)
def __init__(self): self.set_reboot_flag(False) self.logger = log.create_logger("app", log.LOG_FILE) self.logger.info("Starting 3DPrinterOS client. Version %s_%s" % (version.version, version.build)) self.logger.info('Operating system: ' + platform.system() + ' ' + platform.release()) self.time_stamp() signal.signal(signal.SIGINT, self.intercept_signal) signal.signal(signal.SIGTERM, self.intercept_signal) self.detected_printers = [] self.printer_interfaces = [] self.stop_flag = False self.updater = updater.Updater() self.rights_checker_and_waiter = rights.RightsCheckerAndWaiter(self) self.user_login = user_login.UserLogin(self) self.init_interface() self.rights_checker_and_waiter.wait() if self.user_login.wait_for_login(): config.Config.instance().set_profiles(self.user_login.profiles) if config.get_settings()["camera"]["enabled"]: self.camera_controller = camera_controller.CameraController() self.cloud_sync_controller = cloud_sync_controller.CloudSyncController( )
if __name__ == '__main__': config.CLIENT = subprocess.Popen([sys.executable, 'client.py']) pygame.init() screen = pygame.display.set_mode(SIZE) pygame.display.set_caption('Epic Tetris') pygame.event.set_allowed([ pygame.QUIT, pygame.MOUSEBUTTONDOWN, pygame.MOUSEMOTION, pygame.KEYDOWN, ]) config.FONT = pygame.font.Font(None, 40) config.WINDOW = eval( open(gsp('interface.interface'), 'r', encoding='utf8').read()) config.UPDATER = updater.Updater() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: shutdown() elif event.type == pygame.MOUSEBUTTONDOWN: config.WINDOW.mouse_down(event.pos) elif event.type == pygame.MOUSEMOTION: config.WINDOW.mouse_motion(event.pos) elif event.type == pygame.KEYDOWN: config.WINDOW.key_down(event.key) config.UPDATER.update() screen.fill(BACKGROUND) config.WINDOW.show(screen) pygame.display.flip() time.sleep(1 / FPS)
def main(): parser = argparse.ArgumentParser(description='Chainer example: MNIST') parser.add_argument('--batchsize', '-b', type=int, default=256, help='Number of images in each mini-batch') parser.add_argument('--batchsize2', '-b2', type=int, default=64, help='Number of images in each mini-batch') parser.add_argument('--data_type', '-d', type=str, default='LSHTC1') parser.add_argument('--model_type', '-m', type=str, default='DocModel') parser.add_argument('--model_path', '-mp', type=str, default='./models/ResNet50_model_500.npz') parser.add_argument('--gpu', '-g', type=int, default=-1) parser.add_argument('--cluster', '-c', type=int, default=100) parser.add_argument('--weight_decay', '-w', type=float, default=0.0000) parser.add_argument('--unit', '-u', type=int, default=300) parser.add_argument('--alpha', '-a', type=float, default=0.005) parser.add_argument('--epoch', '-e', type=int, default=10) parser.add_argument('--epoch2', '-e2', type=int, default=10) parser.add_argument('--mu', '-mu', type=float, default=30.0) parser.add_argument('--out', '-o', type=str, default='results') parser.add_argument('--train_file', '-train_f', type=str, default='dataset/LSHTC1/LSHTC1_selected03.train') parser.add_argument('--test_file', '-test_f', type=str, default='dataset/LSHTC1/LSHTC1_selected03.test') parser.add_argument('--train_instance', '-train_i', type=str, default='PDSparse/examples/LSHTC1/LSHTC1.train') parser.add_argument('--train_label', '-train_l', type=str, default='PDSparse/examples/LSHTC1/LSHTC1.train') parser.add_argument('--test_instance', '-test_i', type=str, default='PDSparse/examples/LSHTC1/LSHTC1.train') parser.add_argument('--test_label', '-test_l', type=str, default='PDSparse/examples/LSHTC1/LSHTC1.train') parser.add_argument('--seed', '-s', type=int, default=0) parser.add_argument('--resume', '-r', default='', help='resume the training from snapshot') parser.add_argument('--resume2', '-r2', default='', help='resume the training from snapshot') parser.add_argument('--optimizer', '-op', type=str, default='Adam') parser.add_argument('--optimizer2', '-op2', type=str, default='Adam') parser.add_argument('--initial_lr', type=float, default=0.05) parser.add_argument('--lr_decay_rate', type=float, default=0.5) parser.add_argument('--lr_decay_epoch', type=float, default=25) parser.add_argument('--random', action='store_true', default=False, help='Use random assignment or not') parser.add_argument('--valid', '--v', action='store_true', help='Use random assignment or not') args = parser.parse_args() random.seed(args.seed) np.random.seed(args.seed) gpu = args.gpu data_type = args.data_type model_type = args.model_type num_clusters = args.cluster initial_lr = args.initial_lr lr_decay_rate = args.lr_decay_rate lr_decay_epoch = args.lr_decay_epoch opt1 = args.optimizer opt2 = args.optimizer2 model_path = args.model_path rand_assign = args.random train_file = args.train_file test_file = args.test_file unit = args.unit alpha = args.alpha sparse = False ndim = 1 n_in = None train_transform = None test_transform = None if data_type == 'toy': model = network.LinearModel(2, 2) num_classes = 4 elif data_type == 'mnist': num_classes = 10 if model_type == 'linear': model = network.LinearModel(784, num_clusters) elif model_type == 'DNN': model = network.MLP(1000, num_clusters) elif model_type == 'CNN': ndim = 3 model = network.CNN(num_clusters) else: raise ValueError elif data_type == 'cifar100': num_classes = 100 train_transform = partial(dataset.transform, mean=0.0, std=1.0, train=True) test_transform = partial(dataset.transform, mean=0.0, std=1.0, train=False) if model_type == 'Resnet50': model = network.ResNet50(num_clusters) n_in = 2048 load_npz(model_path, model, not_load_list=['fc7']) elif model_type == 'VGG': model = network.VGG(num_clusters) n_in = 1024 load_npz(model_path, model, not_load_list=['fc6']) else: raise ValueError elif data_type == 'LSHTC1': sparse = True num_classes = None if model_type == 'DocModel': model = network.DocModel(n_in=1024, n_mid=unit, n_out=num_clusters) elif model_type == 'DocModel2': model = network.DocModel2(n_in=1024, n_mid=unit, n_out=num_clusters) elif model_type == 'linear': model = network.LinearModel(n_in=92586, n_out=num_clusters) else: raise ValueError elif data_type == 'Dmoz': sparse = True num_classes = None if model_type == 'DocModel': model = network.DocModel(n_in=561127, n_mid=unit, n_out=num_clusters) elif model_type == 'linear': model = network.LinearModel(n_in=1024, n_out=num_clusters) else: raise ValueError else: num_classes = 10 if model_type == 'Resnet50': model = network.ResNet50(num_clusters) elif model_type == 'Resnet101': model = network.ResNet101(num_clusters) elif model_type == 'VGG': model = network.VGG(num_clusters) elif model_type == 'CNN': model = network.CNN(num_clusters) else: raise ValueError if gpu >= 0: # Make a specified GPU current chainer.backends.cuda.get_device_from_id(gpu).use() model.to_gpu() # Copy the model to the GPU (train_instances, train_labels), (test_instances, test_labels), num_classes \ = load_data(data_type, ndim, train_file, test_file) if rand_assign: assignment, count_classes = random_assignment(num_clusters, num_classes) else: if opt1 == 'Adam': optimizer = chainer.optimizers.Adam(alpha=alpha) else: optimizer = chainer.optimizers.SGD(lr=alpha) optimizer.setup(model) train = Dataset(*(train_instances, train_labels), sparse) test = Dataset(*(test_instances, test_labels), sparse) train_iter = chainer.iterators.SerialIterator( train, batch_size=args.batchsize) train_updater = Updater(model, train, train_iter, optimizer, num_clusters=num_clusters, device=gpu, mu=args.mu) trainer = training.Trainer(train_updater, (args.epoch, 'epoch'), out=args.out) trainer.extend(extensions.LogReport(trigger=(1, 'epoch'))) trainer.extend( extensions.PrintReport([ 'epoch', 'iteration', 'main/loss', 'main/loss_cc', 'main/loss_mut_info', 'main/H_Y', 'main/H_YX', 'elapsed_time' ])) trainer.extend(extensions.snapshot(), trigger=(5, 'epoch')) if args.resume: chainer.serializers.load_npz(args.resume, trainer) trainer.run() """ end clustering """ """ res, ss = check_cluster(model, train, num_classes, num_clusters, device=gpu) res_sum = tuple(0 for _ in range(num_clusters)) for i in range(num_classes): res_sum = tuple(res_sum[j] + res[i][j] for j in range(num_clusters)) print(res, res_sum, ss) """ """ res, ss = check_cluster(model, test, num_classes, num_clusters, device=gpu) res_sum = tuple(0 for _ in range(num_clusters)) for i in range(num_classes): res_sum = tuple(res_sum[j] + res[i][j] for j in range(num_clusters)) """ cluster_label = separate.det_cluster(model, train, num_classes, batchsize=128, device=gpu, sparse=sparse) assignment, count_classes = separate.assign(cluster_label, num_classes, num_clusters) del optimizer del train_iter del train_updater del trainer del train del test print(count_classes) """ start classification """ model = h_net.HierarchicalNetwork(model, num_clusters, count_classes, n_in=n_in) if opt2 == 'Adam': optimizer2 = chainer.optimizers.Adam(alpha=initial_lr) elif opt2 == 'SGD': optimizer2 = chainer.optimizers.SGD(lr=initial_lr) else: optimizer2 = chainer.optimizers.MomentumSGD(lr=initial_lr) optimizer2.setup(model) if args.weight_decay > 0: optimizer2.add_hook(chainer.optimizer.WeightDecay(args.weight_decay)) if gpu >= 0: # Make a specified GPU current chainer.backends.cuda.get_device_from_id(gpu).use() model.to_gpu() # Copy the model to the GPU train = dataset.Dataset(train_instances, train_labels, assignment, _transform=train_transform, sparse=sparse) test = dataset.Dataset(test_instances, test_labels, assignment, _transform=test_transform, sparse=sparse) train_iter = chainer.iterators.SerialIterator(train, batch_size=args.batchsize2) test_iter = chainer.iterators.SerialIterator(test, batch_size=1, repeat=False) train_updater = updater.Updater(model, train, train_iter, optimizer2, num_clusters, device=gpu) trainer = training.Trainer(train_updater, (args.epoch2, 'epoch'), args.out) acc = accuracy.Accuracy(model, assignment, num_clusters) trainer.extend(extensions.Evaluator(test_iter, acc, device=gpu)) """ trainer.extend( extensions.snapshot(filename='snapshot_iter_{.updater.iteration}.npz'), trigger=(20, 'epoch')) """ trainer.extend(extensions.LogReport(trigger=(1, 'epoch'))) trainer.extend( extensions.PrintReport([ 'epoch', 'main/loss', 'main/loss_cluster', 'main/loss_class', 'validation/main/accuracy', 'validation/main/cluster_accuracy', 'validation/main/loss', 'elapsed_time' ])) if opt2 != 'Adam': trainer.extend(extensions.ExponentialShift('lr', lr_decay_rate), trigger=(lr_decay_epoch, 'epoch')) if args.resume2: chainer.serializers.load_npz(args.resume2, trainer) trainer.run()
import time import updater import logs if __name__ == "__main__": time.sleep(60) module = updater.Updater() while True: try: module.update() module.download() except Exception as e: logs.error_logger.info(f"[error] {e}") time.sleep(600)
def CtMnUpdateChannels(self, selectedIndex): updaterWindow = updater.Updater(config.updaterSkin, config.rootDir, config.skinFolder) updaterWindow.doModal() del updaterWindow
def __init__(self, config_file): log.debug("initializing repository from %s", config_file) pars = parser.XBMCAddonXMLParser(config_file) repo_dict = pars.parse() self.id = repo_dict['id'] self.name = repo_dict['name'] self.author = repo_dict['author'] self.version = repo_dict['version'] self.description = repo_dict['description'] # every repository should have its update xml, to check versions and update/download addons self.update_xml_url = repo_dict['repo_addons_url'] self.update_datadir_url = repo_dict['repo_datadir_url'] self.path = os.path.dirname(config_file) self.addons_path = self.path #os.path.join(self.path, "addons") # addon.xml which describes addon self.addon_xml_relpath = 'addon.xml' # icon for addon size 256x256 self.addon_icon_relpath = 'icon.png' self.addon_resources_relpath = 'resources' # default language,settings and libraries path of addon self.addon_languages_relpath = self.addon_resources_relpath + '/language' self.addon_settings_relpath = self.addon_resources_relpath + '/settings.xml' self.addon_libraries_relpath = self.addon_resources_relpath + '/lib' self._addons = {} #create updater for repository self._updater = updater.Updater( self, os.path.join(config.plugins.archivCZSK.tmpPath.value, self.id)) # load installed addons in repository for addon_dir in os.listdir(self.addons_path): addon_path = os.path.join(self.addons_path, addon_dir) if os.path.isfile(addon_path): continue addon_info = AddonInfo( os.path.join(addon_path, self.addon_xml_relpath)) if addon_info.type not in Repository.SUPPORTED_ADDONS: raise Exception( "%s '%s' addon not in supported type of addons %s " % (self, addon_info.type, Repository.SUPPORTED_ADDONS)) if addon_info.type == 'video': try: tmp = os.path.join(addon_path, addon_info.script) if not os.path.isfile(tmp): raise Exception( "Invalid addon %s. Script file missing %s" % (addon_info.name, tmp)) addon = VideoAddon(addon_info, self) except Exception: traceback.print_exc() log.logError( "Load video addon %s failed, skipping...\n%s" % (addon_dir, traceback.format_exc())) #log.error("%s cannot load video addon %s, skipping.." , self, addon_dir) continue else: archivczsk.ArchivCZSK.add_addon(addon) self.add_addon(addon) elif addon_info.type == 'tools': # load tools addons try: tools = ToolsAddon(addon_info, self) except Exception: traceback.print_exc() log.error("%s cannot load tools addon %s, skipping..", self, addon_dir) continue else: archivczsk.ArchivCZSK.add_addon(tools) self.add_addon(tools) log.debug("%s successfully loaded", self)
break except: print 'Use the format YYYY/mm/dd' fitbit_creds = dict() fitbit_creds['username'] = raw_input('Fitbit Username: '******'password'] = getpass() garmin_creds = dict() garmin_creds['username'] = raw_input('Garmin Username: '******'password'] = getpass() fitbit_creds = models.FitbitCredentials(**fitbit_creds) garmin_creds = models.ServiceCredentials(**garmin_creds) account = models.Account(nickname=nickname, fitbit_creds=fitbit_creds, garmin_creds=garmin_creds, start_date=start_date) account.save() elif args.action == 'update': for account in models.Account.objects: log.debug('Processing account %s' % account.nickname) upd = updater.Updater(account) upd.update() elif args.action == 'deleteDani': account = models.Account.objects.get(nickname='dani') with garmin.GarminClient(account) as garmin_client: garmin_client.delete_all_weights() account.latest_fitbit = {} account.save()
#!/usr/bin/python3 import tempstation import updater import threading import sys if __name__ == "__main__": """ These three objects have infinite loop to do their jobs - using threads to run them nicely. There is always an option to run every obj in "solo" mode. """ publisher = tempstation.TempstationPublisher() subscriber = tempstation.TempstationSubscriber() updater = updater.Updater() pub_thread = threading.Thread( target=publisher.continuous_publishing, kwargs={"period": 300}) # 300 seconds ~ 5 minutes request for temp and hum sub_thread = threading.Thread( target=subscriber.run ) # subscribing to tempstation-related topics and save the data to InfluxDB update_thread = threading.Thread(target=updater.run) # Updating website try: pub_thread.start() sub_thread.start() update_thread.start() except: # NOTE: Catch only needed exceptions sys.stderr.write("Threads failed.")
argv = sys.argv[1:] try: opts, args = getopt.getopt(argv, "adlup:", ["aria2", "debug", "alongside" "update", "packages"]) except getopt.GetoptError as e: print(str(e)) sys.exit(2) for opt, arg in opts: if opt in ('-d', '--debug'): log._debug = True log.debug("Debug mode on") elif opt in ('-u', '--update'): upd = updater.Updater() if upd.update(): print("Program updated! Restarting...") os.execl(sys.executable, *([sys.executable] + sys.argv)) elif opt in ('-p', '--packages'): _alternate_package_list = arg elif opt in ('-a', '--aria2'): _use_aria2 = True elif opt in ('-l', '--alongisde'): _enable_alongside = True else: assert False, "unhandled option" GObject.threads_init() Gdk.threads_init()