Example #1
0
def credentials(save = None):
    clientId = config.get('clientId')
    clientSecret = config.get('clientSecret')
    if not clientId:
        clientId = DEFAULT_CLIENT_ID
        clientSecret = DEFAULT_CLIENT_SECRET

    refreshToken = config.get('refreshToken')
    if refreshToken:
        LOGGER.debug('Using stored refresh token...')

        return oauth2client.client.OAuth2Credentials(None, clientId,
                clientSecret, refreshToken, None,
                oauth2client.GOOGLE_TOKEN_URI, None)

    flow = oauth2client.client.OAuth2WebServerFlow(clientId, clientSecret,
            OAUTH_SCOPE, REDIRECT_URI,
            access_type = 'offline', approval_prompt = 'force')

    url = flow.step1_get_authorize_url()
    print 'Please open the following URL: '
    print url
    authorizationCode = raw_input('Copy and paste the authorization code: ').strip()

    LOGGER.debug('Requesting new refresh token...')
    credentials = flow.step2_exchange(authorizationCode)

    refreshToken = credentials.refresh_token
    print 'Refresh token: ' + refreshToken

    if utils.firstNonNone(save, False):
        config.set('refreshToken', refreshToken)
        config.save()

    return credentials
Example #2
0
def save_to_conf(module, src):
    def s(x):
        try:
            return src[module + "." + x][0]
        except:
            return None

    typ = r.ui.progs[module]
    conf = c.cfg[module]
    for j in [*typ]:
        if typ[j] == "label":
            pass
        if typ[j] == "action":
            pass
        if typ[j] == "multi":
            conf[j] = src[module + "." + j]
        elif typ[j] == "checkbox":
            if s(j) is not None:
                conf[j] = True
            else:
                conf[j] = False
        elif typ[j] == "number" or typ[j] == "range":
            try:
                conf[j] = int(s(j))
            except:
                conf[j] = 1
        else:
            conf[j] = str(s(j))
    config.save()
Example #3
0
	def onClose(self, evt):
		config.conf["upgrade"]["newLaptopKeyboardLayout"] = True
		try:
			config.save()
		except:
			pass
		self.EndModal(0)
def _append_data(analysis):
    """append source scores across subjects"""
    try:
        stcs, connectivity = load('score_source', subject='fsaverage',
                                  analysis=analysis['name'])
    except Exception:
        stcs = list()
        for meg_subject, subject in zip(range(1, 21), subjects_id):
            if subject in bad_mri:
                continue
            # load
            stc, _, _ = load('evoked_source', subject=meg_subject,
                             analysis=analysis['name'])
            morph = load('morph', subject=meg_subject)
            vertices_to = [np.arange(10242)] * 2
            # fix angle error scale
            if 'circAngle' in analysis['name']:
                stc._data /= 2.

            # apply morph
            stc_morph = morph_data_precomputed(subject, 'fsaverage', stc,
                                               vertices_to, morph)
            stcs.append(stc_morph.data)
        stcs = np.array(stcs)
        save([stcs, connectivity], 'score_source', subject='fsaverage',
             analysis=analysis['name'], overwrite=True, upload=True)
    return stcs, connectivity
Example #5
0
def _append_data(analysis):
    """append source scores across subjects"""
    try:
        stcs, connectivity = load('score_source',
                                  subject='fsaverage',
                                  analysis=analysis['name'])
    except Exception:
        stcs = list()
        for meg_subject, subject in zip(range(1, 21), subjects_id):
            if subject in bad_mri:
                continue
            # load
            stc, _, _ = load('evoked_source',
                             subject=meg_subject,
                             analysis=analysis['name'])
            morph = load('morph', subject=meg_subject)
            vertices_to = [np.arange(10242)] * 2
            # fix angle error scale
            if 'circAngle' in analysis['name']:
                stc._data /= 2.

            # apply morph
            stc_morph = morph_data_precomputed(subject, 'fsaverage', stc,
                                               vertices_to, morph)
            stcs.append(stc_morph.data)
        stcs = np.array(stcs)
        save([stcs, connectivity],
             'score_source',
             subject='fsaverage',
             analysis=analysis['name'],
             overwrite=True,
             upload=True)
    return stcs, connectivity
def save_scores(df):
    # attributes to save
    keep_cols = [
        "datetime",
        "season_week",
        "team1",
        "team2",
        "result",
        "pg_score1",
        "pg_score2",
        "elo_prob1",
        "carm-elo_prob1",
        "raptor_prob1",
    ]
    # my models
    keep_cols += [
        c for c in df.columns
        if c.startswith("result_") and c.endswith("prob1")
    ]
    #
    df_out = df[keep_cols].sort_values(["datetime", "team1"])
    df_out.loc[df_out.datetime >= config.get("date", "today"), "result"] = ""
    df_out = df_out.fillna("")
    # View today's games
    # df_out[df_out.datetime >= config.get('date', 'today')].head(20)
    save(df_out,
         dir="output",
         filename="all_scores",
         ext=".csv",
         main=True,
         date=False)
Example #7
0
def register(ctx, ip):
    """Register an authorized user on your bridge."""

    conf_file = ctx.obj["conf_file"]

    url = "http://%s/api" % ip
    payload = {"devicetype": "hue-client.py"}
    r = requests.post(url, json=payload)

    if r.status_code != 200:
        print("Could not communicate with %s. Check the IP, or run 'search'.")
        return
    else:
        print("Please press the button on your Hue bridge...")
        sys.stdout.write("Waiting...")
        for i in range(0, 31):
            sys.stdout.write(" %d" % (30 - i))
            sys.stdout.flush()
            r = requests.post(url, json=payload)
            json = r.json()

            if r.status_code == 200 and isinstance(json, list):
                if "success" in json[0] and "username" in json[0]["success"]:
                    username = json[0]["success"]["username"]
                    config.save({"ip": ip, "username": username}, conf_file)
                    print(" Bingo!")
                    print("\nRegistered user %s." % username)
                    break
                else:
                    sleep(1)
                    continue
Example #8
0
    def opt(self, cutoff, instates, prestates, C):
        instates, prestates = int(instates), int(prestates)
        config.lpcfg = LPCFG_Surrogate()
        self.smooth(self.get_length(cutoff, instates, prestates), C)
        config.save()

        from parsing import parser
        import multiprocessing as mp
        try:
            mp.set_start_method('fork')
        except RuntimeError:
            pass
        parser.parse_devset(config.test_file)

        import subprocess
        subprocess.Popen(['cd', 'parsing'])
        subprocess.Popen(['python3', 'parser.py'])
        subprocess.Popen(['cd', '..'])
        process = subprocess.Popen(['./evalb', '-p', 'new.prm', config.test_file, 'output/parse.txt'],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        output = str(stdout)
        i = output.find('FMeasure       =  ')
        return float(output[i + 18:i + 23])
Example #9
0
def process_data_files():
    #TODO: fix bug
    #new_config = get_new_new_config()
    #config.load()
    #config.config["modules"]["goagent"]["current_version"] = new_config["modules"]["goagent"]["current_version"]
    #config.config["modules"]["launcher"]["current_version"] = new_config["modules"]["launcher"]["current_version"]
    config.save()
Example #10
0
def quit():
    bulletmanager.shutdown()
    scriptmanager.shutdown()
    video.shutdown()
    pygame.quit()
    config.save("config.cfg")
    sys.exit(0)
def _stats(analysis):
    """2nd order stats across subjects"""

    # if already computed lets just load it
    ana_name = 'stats_' + analysis['name'] + '_vhp'
    if op.exists(paths('score', analysis=ana_name)):
        return load('score', analysis=ana_name)

    # gather scores across subjects
    scores = list()
    for subject in range(1, 21):
        kwargs = dict(subject=subject, analysis=analysis['name'] + '_vhp')
        fname = paths('score', **kwargs)
        if op.exists(fname):
            score, times = load(**kwargs)
        else:
            score, times = _decod(subject, analysis)
        scores.append(score)
    scores = np.array(scores)

    # compute stats across subjects
    p_values = stats(scores - analysis['chance'])
    diag_offdiag = scores - np.tile([np.diag(sc) for sc in scores],
                                    [len(times), 1, 1]).transpose(1, 0, 2)
    p_values_off = stats(diag_offdiag)

    # Save stats results
    out = dict(scores=scores, p_values=p_values, p_values_off=p_values_off,
               times=times, analysis=analysis)
    save(out, 'score',  analysis=ana_name)
    return out
Example #12
0
def process_data_files():
    # TODO: fix bug
    # new_config = get_new_new_config()
    # config.load()
    # config.config["modules"]["gae_proxy"]["current_version"] = new_config["modules"]["gae_proxy"]["current_version"]
    # config.config["modules"]["launcher"]["current_version"] = new_config["modules"]["launcher"]["current_version"]
    config.save()
Example #13
0
 def callback(self, event):
     try:
         if event.widget.cget("text") == "Browse":
             if self.opt == "get_seq": self.browse_get_seq()
             if self.opt == "lost": self.browse_get_seq()
             if self.opt == "errors": self.browse_errors()
             if self.opt == "graph": self.browse_graphics()
             if self.opt == "select": self.browse_select()
         if event.widget.cget("text") == "Execute":
             cfgn.save(self)
             qlibs.create_path(qlibs.get_datadir() + self.pop.get() + "/")
             if self.opt == "get_seq": self.get_seq()
             if self.opt == "lost": self.lost()
             if self.opt == "reverse": self.reverse()
             if self.opt == "quad_search": self.quad_search()
             if self.opt == "errors": self.errors()
             if self.opt == "dist": self.dist()
             if self.opt == "graph": self.graphics()
             if self.opt == "select": self.select()
             if self.opt == "intersect": self.intersections()
             messagebox.showinfo("Quad", "END!")
         if event.widget.cget("text") == "Confirm":
             cfgn.save(self)
     except:
         pass
     return
Example #14
0
    def req_config_handler(self):
        req = urlparse.urlparse(self.path).query
        reqs = urlparse.parse_qs(req, keep_blank_values=True)
        data = ''

        if reqs['cmd'] == ['get_config']:
            config.load()
            data = '{ "check_update": "%d" }' % (
                config.config["update"]["check_update"])
        elif reqs['cmd'] == ['set_config']:
            if reqs['check_update']:
                check_update = int(reqs['check_update'][0])
                if check_update != 0 and check_update != 1:
                    data = '{"res":"fail, check_update:%s"}' % check_update
                else:
                    config.config["update"]["check_update"] = int(check_update)
                    config.save()

                    data = '{"res":"success"}'
            else:
                data = '{"res":"fail"}'

        mimetype = 'text/plain'
        self.wfile.write(
            ('HTTP/1.1 200\r\nContent-Type: %s\r\nContent-Length: %s\r\n\r\n' %
             (mimetype, len(data))).encode())
        self.wfile.write(data)
def _analyze_toi(analysis):
    """Subscore each analysis as a function of the reported visibility"""
    ana_name = analysis['name'] + '-toi'

    # don't recompute if not necessary
    fname = paths('score', analysis=ana_name)
    if os.path.exists(fname):
        return load('score', analysis=ana_name)

    # gather data
    n_subject = 20
    scores = dict(visibility=np.zeros((n_subject, len(tois), 4)),
                  contrast=np.zeros((n_subject, len(tois), 3)))
    R = dict(visibility=np.zeros((n_subject, len(tois))),
             contrast=np.zeros((n_subject, len(tois))),)
    for s, subject in enumerate(subjects):
        gat, _, events_sel, events = load('decod', subject=subject,
                                          analysis=analysis['name'])
        events = events.iloc[events_sel].reset_index()
        for t, toi in enumerate(tois):
            # Average predictions on single trials across time points
            y_pred = _average_ypred_toi(gat, toi, analysis)
            # visibility
            for factor in ['visibility', 'contrast']:
                # subscore per condition (e.g. each visibility rating)
                scores[factor][s, t, :] = _subscore(y_pred, events,
                                                    analysis, factor)
                # correlate residuals with factor
                R[factor][s, t] = _subregress(y_pred, events,
                                              analysis, factor, True)

    save([scores, R], 'score', analysis=ana_name, overwrite=True, upload=True)
    return [scores, R]
Example #16
0
def set_template_config(request, collection_name, wiki_key):
    new_config = json.loads(request.body)

    conf_name = new_config["name"]
    conf_type = new_config["type"]

    collection = models.Collection.objects.get(name=collection_name)
    wiki = models.Wiki.objects.get(wiki_key=wiki_key)
    try:
        config = models.Template.objects.get(
            collection=collection,
            wiki=wiki,
            type=conf_type,
            name=conf_name,
        )
    except models.Template.DoesNotExist:
        # create if does not exist
        config = models.Template(
            collection=collection,
            wiki=wiki,
            type=conf_type,
            name=conf_name,
            # set as default if first template of this type
            is_default=not models.Template.objects.filter(
                collection__name=collection.name,
                wiki=wiki,
                type=conf_type,
            ).exists(),
        )

    config.template_file.save(f"{wiki_key}-{conf_name}",
                              ContentFile(new_config["template"]))
    config.save()

    return HttpResponse(status=200)
Example #17
0
def train():
    cleanup.cleanup()
    c.save(c.work_dir)

    data_loader = TextLoader(c.work_dir, c.batch_size, c.seq_length)
    with open(os.path.join(c.work_dir, 'chars_vocab.pkl'), 'wb') as f:
        cPickle.dump((data_loader.chars, data_loader.vocab), f)

    model = Model(c.rnn_size, c.num_layers, len(data_loader.chars), c.grad_clip, c.batch_size, c.seq_length)

    with tf.Session() as sess:
        tf.initialize_all_variables().run()
        saver = tf.train.Saver(tf.all_variables())
        for e in range(c.num_epochs):
            sess.run(tf.assign(model.lr, c.learning_rate * (c.decay_rate ** e)))
            data_loader.reset_batch_pointer()
            state = model.initial_state.eval()
            for b in range(data_loader.num_batches):
                start = time.time()
                x, y = data_loader.next_batch()
                feed = {model.input_data: x, model.targets: y, model.initial_state: state}
                train_loss, state, _ = sess.run([model.cost, model.final_state, model.train_op], feed)
                end = time.time()
                print("{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}"
                    .format(e * data_loader.num_batches + b,
                            c.num_epochs * data_loader.num_batches,
                            e, train_loss, end - start))
                if (e * data_loader.num_batches + b) % c.save_every == 0:
                    checkpoint_path = os.path.join(c.work_dir, 'model.ckpt')
                    saver.save(sess, checkpoint_path, global_step=e * data_loader.num_batches + b)
                    print("model saved to {}".format(checkpoint_path))
def _analyze_continuous(analysis):
    """Regress prediction error as a function of visibility and contrast for
    each time point"""
    ana_name = analysis['name'] + '-continuous'

    # don't recompute if not necessary
    fname = paths('score', analysis=ana_name)
    if os.path.exists(fname):
        return load('score', analysis=ana_name)

    # gather data
    n_subject = 20
    n_time = 151
    scores = dict(visibility=np.zeros((n_subject, n_time, 4)),
                  contrast=np.zeros((n_subject, n_time, 3)))
    R = dict(visibility=np.zeros((n_subject, n_time)),
             contrast=np.zeros((n_subject, n_time)),)
    for s, subject in enumerate(subjects):
        gat, _, events_sel, events = load('decod', subject=subject,
                                          analysis=analysis['name'])
        events = events.iloc[events_sel].reset_index()
        y_pred = np.transpose(get_diagonal_ypred(gat), [1, 0, 2])[..., 0]
        for factor in ['visibility', 'contrast']:
            # subscore per condition (e.g. each visibility rating)
            scores[factor][s, :, :] = _subscore(y_pred, events,
                                                analysis, factor)
            # correlate residuals with factor
            R[factor][s, :] = _subregress(y_pred, events,
                                          analysis, factor, True)

    times = gat.train_times_['times']
    save([scores, R, times], 'score', analysis=ana_name,
         overwrite=True, upload=True)
    return [scores, R, times]
def _stats(analysis):
    """2nd order stats across subjects"""

    # if already computed lets just load it
    ana_name = 'stats_' + analysis['name'] + '_vhp'
    if op.exists(paths('score', analysis=ana_name)):
        return load('score', analysis=ana_name)

    # gather scores across subjects
    scores = list()
    for subject in range(1, 21):
        kwargs = dict(subject=subject, analysis=analysis['name'] + '_vhp')
        fname = paths('score', **kwargs)
        if op.exists(fname):
            score, times = load(**kwargs)
        else:
            score, times = _decod(subject, analysis)
        scores.append(score)
    scores = np.array(scores)

    # compute stats across subjects
    p_values = stats(scores - analysis['chance'])
    diag_offdiag = scores - np.tile([np.diag(sc) for sc in scores],
                                    [len(times), 1, 1]).transpose(1, 0, 2)
    p_values_off = stats(diag_offdiag)

    # Save stats results
    out = dict(scores=scores,
               p_values=p_values,
               p_values_off=p_values_off,
               times=times,
               analysis=analysis)
    save(out, 'score', analysis=ana_name)
    return out
Example #20
0
def main():
    res = packitems(os.getcwd())
    res["HOST_MACHINE"] = socket.gethostname()

    import config
    config.save(res)
    return res
Example #21
0
def choose(chat, message, args, sender):
    if len(args) == 1:
        if args[0].lower() == '--listen':
            listeners.append(chat.Name)
            conf = config.config()
            config_operators = conf.get('mc_listens', [])
            if chat.Name in config_operators:
                chat.SendMessage("This chat is already listening to Minecraft service statuses.")
                return
            config_operators.append(chat.Name)
            conf['mc_listens'] = config_operators
            config.save(conf)
            return
        elif args[0].lower() == '--unlisten':
            conf = config.config()
            config_operators = conf.get('mc_listens', [])
            if chat.Name not in config_operators:
                chat.SendMessage("This chat is not currently listening to Minecraft service statuses.")
                return
            config_operators.remove(chat.Name)
            conf['mc_listens'] = config_operators
            config.save(conf)
            return
        else:
            service = args[0]
            if service in get_statuses():
                chat.SendMessage(format_status(service))
                return
            else:
                chat.SendMessage("Service not found.")
                return
    chat.SendMessage(format_status())
Example #22
0
def save_state(start_num, tag_index):
    config = model.Config.select().where(model.Config.name == "continue").limit(1).first()
    if config is None:
        model.Config.create(name="continue", value=json.dumps({ "start_num": start_num, "tag_index": tag_index }))
    else:
        config.value = json.dumps({ "start_num": start_num, "tag_index": tag_index })
        config.save()
Example #23
0
def main():
    df = df_with_538()
    df_scored = score_df(df)
    # Each of these functions is updating df
    df_scored2, df_acc = benchmark_model_accuracy(df_scored)
    # pandas groupby means
    _ = week_accuracies(df_scored2)

    df_records = all_records(df_scored2, freq=True)

    # Save out
    save_scores(df_scored)

    save(df_acc,
         dir="output",
         filename="acc_overall",
         ext=".csv",
         main=True,
         date=False)
    save(df_records,
         dir="output",
         filename="records",
         ext=".csv",
         main=True,
         date=False)
Example #24
0
def registerPress():
    addr: str = app.getEntry("Server Address")
    token: str = app.getEntry("Device-Token")
    uname = platform.uname()

    if addr != "" and token != "":
        if "http" not in addr:
            addr = "http://" + addr
        app.setLabel("info", "Trying to contact cmm server")
        registerRequest = req.post(addr + "/api/devices/register",
                                   json={
                                       "loginsecret": token,
                                       "name": uname.node,
                                       "os": uname.system,
                                       "osshort": uname.system[0:3],
                                       "arch": uname.machine,
                                       "mac": "Na"
                                   },
                                   verify=False)
        responseCode = registerRequest.status_code
        if responseCode <= 200 or responseCode >= 300:
            app.setLabel(
                "info",
                "Something went wrong, token probably invalid\nStatus code: " +
                str(responseCode))
        else:
            jsonData = json.loads(registerRequest.text)
            config.config["endpointURL"] = addr
            config.config["secret"] = jsonData["clientSecret"]
            config.config["uuid"] = jsonData["uuid"]
            config.save(config.config)
            app.setLabel("info", "Successfully registered device")
            app.hideSubWindow("Register this device")
    else:
        app.setLabel("info", "You have to specify everything")
Example #25
0
    def testConfig(self):
        logger.debug('-'*26 + '\n')
        logger.info('Running simple configuration test...')

        import config

        config.check()
        config.reload()
        configdata = str(config.get_config())

        config.set('testval', 1337)
        if not config.get('testval', None) is 1337:
            self.assertTrue(False)

        config.set('testval')
        if not config.get('testval', None) is None:
            self.assertTrue(False)

        config.save()
        config.reload()

        if not str(config.get_config()) == configdata:
            self.assertTrue(False)

        self.assertTrue(True)
 def on_main_window_delete_event(self, _widget, _event):
     self.conf.set('GUI', 'show_private_groups', str(self.show_private_groups))
     self.conf.set('GUI', 'show_system_groups', str(self.show_system_groups))
     visible_cols = [col.get_title() for col in self.users_tree.get_columns() if col.get_visible()]
     self.conf.set('GUI', 'visible_user_columns', ','.join(visible_cols))
     config.save()
     exit()
Example #27
0
def connect2ap(ssid=None, pw=None):
    """ If pw is None get the password from the config file 
        If pw is not None, write ssid,pw to the config file

        If ip is None in config file choose dhcp config
        else get ip. 
        If gw is None  it is assumed as 192.168.2.254, 
        If dns is None it is assumed as 192.168.2.254, 
        Deactivate the wlan, wait 1 second and activate with given ssid and pw
    """
    log.info("Connecting to ap %s", ssid)

    if not ssid:
        ssid = config.get("ssid", "xxxx")
    else:
        config.put("ssid", ssid)

    if not pw:
        pw = config.get(ssid, "geheim")
    else:
        config.put(ssid, pw)

    ip = config.get("wlan_ip")
    gw = config.get("wlan_gw", "192.168.2.254")
    dns = config.get("wlan_dns", "192.168.2.254")
    config.save()

    wlan.active(False)
    wlan.active(True)
    if ip:
        wconf = (ip, '255.255.255.0', gw, dns)
        wlan.ifconfig(wconf)
    wlan.connect(ssid, pw)
Example #28
0
def setup_config():
    if not os.path.exists(config._configfile):
        # this is the default config, it will be overwritten if a config file already exists. Else, it saves it
        conf_data = readstatic.read_static('default_config.json', ret_bin=False)
        config.set_config(json.loads(conf_data))

        config.save()

    config.reload()

    settings = 0b000
    if config.get('log.console.color', True):
        settings = settings | USE_ANSI
    if config.get('log.console.output', True):
        settings = settings | OUTPUT_TO_CONSOLE
    if config.get('log.file.output', True):
        settings = settings | OUTPUT_TO_FILE
    set_settings(settings)

    verbosity = str(config.get('log.verbosity', 'default')).lower().strip()
    if not verbosity in ['default', 'null', 'none', 'nil']:
        map = {
            str(LEVEL_DEBUG) : LEVEL_DEBUG,
            'verbose' : LEVEL_DEBUG,
            'debug' : LEVEL_DEBUG,
            str(LEVEL_INFO) : LEVEL_INFO,
            'info' : LEVEL_INFO,
            'information' : LEVEL_INFO,
            str(LEVEL_WARN) : LEVEL_WARN,
            'warn' : LEVEL_WARN,
            'warning' : LEVEL_WARN,
            'warnings' : LEVEL_WARN,
            str(LEVEL_ERROR) : LEVEL_ERROR,
            'err' : LEVEL_ERROR,
            'error' : LEVEL_ERROR,
            'errors' : LEVEL_ERROR,
            str(LEVEL_FATAL) : LEVEL_FATAL,
            'fatal' : LEVEL_FATAL,
            str(LEVEL_IMPORTANT) : LEVEL_IMPORTANT,
            'silent' : LEVEL_IMPORTANT,
            'quiet' : LEVEL_IMPORTANT,
            'important' : LEVEL_IMPORTANT
        }

        if verbosity in map:
            set_level(map[verbosity])
        else:
            logger.warn('Verbosity level %s is not valid, using default verbosity.' % verbosity)

    if type(config.get('client.webpassword')) is type(None):
        config.set('client.webpassword', base64.b16encode(os.urandom(32)).decode('utf-8'), savefile=True)
    if type(config.get('client.client.port')) is type(None):
        randomPort = netcontroller.get_open_port()
        config.set('client.client.port', randomPort, savefile=True)
    if type(config.get('client.public.port')) is type(None):
        randomPort = netcontroller.get_open_port()
        config.set('client.public.port', randomPort, savefile=True)
    if type(config.get('client.api_version')) is type(None):
        config.set('client.api_version', onionrvalues.API_VERSION, savefile=True)
Example #29
0
 def action_ok(self, event):
     if confirm_dialog(self):
         selected = []
         for element in self.selected_list_model.elements():
             selected.append(element)
         c.set_default('PLUGIN_LIST', selected)
         c.save()
     self.dispose()            
Example #30
0
def restart_pi():
    logger.info('Sending restart command to Raspberry Pi...')
    config.save()

    command = "/usr/bin/sudo /sbin/shutdown -r now"
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output = process.communicate()[0]
    print output
Example #31
0
	def onOk(self, evt):
		config.conf["keyboard"]["useCapsLockAsNVDAModifierKey"] = self.capsAsNVDAModifierCheckBox.IsChecked()
		config.conf["general"]["showWelcomeDialogAtStartup"] = self.showWelcomeDialogAtStartupCheckBox.IsChecked()
		try:
			config.save()
		except:
			pass
		self.Close()
Example #32
0
def generate_new_uuid():
    node_id = uuid.getnode()
    xx_net_uuid = str(uuid.uuid4())
    config.config["update"]["node_id"] = node_id
    config.config["update"]["uuid"] = xx_net_uuid
    logging.info("generate node_id:%s", node_id)
    logging.info("generate uuid:%s", xx_net_uuid)
    config.save()
Example #33
0
 def save(self):
     if self._config.last_saved is None:
         return self.saveAs()
     else:
         config.save(self._config.last_saved, self.values)
         self.undo.undo()  # unstack last change
         self.handleChanges(dirty=False)  # will stack current values
         return True
Example #34
0
 def set_rotation(self, rotation):
     platform = self.bookshelf.platform
     if platform.hasProperty('DISABLE_ROTATION') and platform.getProperty('DISABLE_ROTATION') == 'true':
         self.menu_item_rotation_0.selected = 1
     else:
         c.set_default('SCREEN_ROTATION', rotation)
         c.save()
         self.reconfigure()
def create_project(project_name, branch_base, branch_merge):
    config.main['projects'][project_name] = {
        'branches': {
            'base': branch_base or 'master',
            'merge': branch_merge or 'master'
        }
    }
    config.save()
Example #36
0
 def save(self):
   config.setValue("wine_paths", self._winePaths())
   config.setValue("default_wine_path", str(self.defaultWinePath.itemData(self.defaultWinePath.currentIndex()).toString()))
   config.setValue("allow_menu_entry_creation", self.allowMenuEntryCreation.isChecked())
   config.setValue("auto_import_shortcuts", self.autoImportShortcuts.isChecked())
   config.setValue("debug_line", str(self.debugLine.text()))
   config.setValue("architecture", str(self.architecture.currentText()))
   config.save()
Example #37
0
 def save():
     previous_mods = config.mods
     config.config_mods = ",".join(mods)
     config.mods = config.config_mods
     config.save()
     if config.mods != previous_mods:
         reload_all()
     return END_LOOP
Example #38
0
 def unhide_plugin(self, id):
     """ Unhide plugin with given id. This will unhide the plugin so queries
     return it again, and write this change to the config
     """
     self.__hidden_plugins.remove(id)
     config.set('plugin.hiddenplugins', list(self.__hidden_plugins))
     config.save()
     self.__hidden_changed()
Example #39
0
 async def lexicon(self, ctx, word):
     if ctx.author.name == ctx.channel.name or ctx.author.is_mod:
         config.channels[ctx.channel.name]["lexicon"] = word.lower()
         cf.save(config)
         msg = f'Lexicon changed to {word.lower()}'
     else:
         msg = f'Command can only be used by {ctx.channel.name} or moderators'
     await ctx.send(msg)
def finish_table_calib():
    # We've already picked the bound points for each image
    global depth
    boundpts = np.load('%s/config/boundpts.npy' % newest_folder)
    depth = np.load('%s/config/depth.npy' % newest_folder)

    config.bg = find_plane(depth, boundpts)
    config.save(newest_folder)
def finish_table_calib():
    # We've already picked the bound points for each image
    global depth
    boundpts = np.load('%s/config/boundpts.npy' % newest_folder)
    depth = np.load('%s/config/depth.npy' % newest_folder)

    config.bg = find_plane(depth, boundpts)
    config.save(newest_folder)
Example #42
0
def add_operator(new_op):
    conf = config.config()
    config_operators = conf.get('operators', [])
    if new_op in config_operators:
        return False
    config_operators.append(new_op)
    conf['operators'] = config_operators
    config.save(conf)
    return True
Example #43
0
	def onSaveConfigurationCommand(self,evt):
		if globalVars.appArgs.secure:
			queueHandler.queueFunction(queueHandler.eventQueue,ui.message,_("Cannot save configuration - NVDA in secure mode"))
			return
		try:
			config.save()
			queueHandler.queueFunction(queueHandler.eventQueue,ui.message,_("Configuration saved"))
		except:
			messageBox(_("Could not save configuration - probably read only file system"),_("Error"),wx.OK | wx.ICON_ERROR)
def _run(epochs, events, analysis):
    """Runs temporal generalization for a given subject and analysis"""
    print(subject, analysis['name'])

    # subselect the trials (e.g. exclude absent trials) with a
    # dataframe query defined in conditions.py
    query, condition = analysis['query'], analysis['condition']
    sel = range(len(events)) if query is None \
        else events.query(query).index
    sel = [ii for ii in sel if ~np.isnan(events[condition][sel][ii])]

    # The to-be-predicted value, for each trial:
    y = np.array(events[condition], dtype=np.float32)

    print analysis['name'], np.unique(y[sel]), len(sel)

    # Abort if there is no trial
    if len(sel) == 0:
        return

    # Apply analysis
    gat = GeneralizationAcrossTime(clf=analysis['clf'],
                                   cv=analysis['cv'],
                                   scorer=analysis['scorer'],
                                   n_jobs=-1)
    print(subject, analysis['name'], 'fit')
    gat.fit(epochs[sel], y=y[sel])
    print(subject, analysis['name'], 'score')
    score = gat.score(epochs[sel], y=y[sel])
    print(subject, analysis['name'], 'save')

    # save space
    if analysis['name'] not in ['probe_phase', 'target_circAngle']:
        # we'll need the estimator trained on the probe_phase and to generalize
        # to the target phase and prove that there is a significant signal.
        gat.estimators_ = None
    if analysis['name'] not in [
            'target_present', 'target_circAngle', 'probe_circAngle'
    ]:
        # We need these individual prediction to control for the correlation
        # between target and probe angle.
        gat.y_pred_ = None

    # Save analysis
    save([gat, analysis, sel, events],
         'decod',
         subject=subject,
         analysis=analysis['name'],
         overwrite=True,
         upload=True)
    save([score, epochs.times],
         'score',
         subject=subject,
         analysis=analysis['name'],
         overwrite=True,
         upload=True)
    return
Example #45
0
 def add_show(self):
     dlg = AddShowDialog(self)
     dlg.exec_()
     if dlg.result() == QDialog.Accepted:
         show = dlg.show_name
         if show in self.shows: return 
         self.shows.append(show)
         self.updateListWidget()
         config.save(self.shows)
Example #46
0
File: mcpil.py Project: dw5/MCPIL
def save():
    global current_config, current_render_distance, current_username, current_features, current_hide_launcher
    current_config['general']['render-distance'] = current_render_distance.get()
    current_config['general']['username'] = current_username.get()
    current_config['general']['custom-features'] = current_features.copy()
    current_config['general']['hide-launcher'] = bool(current_hide_launcher.get())
    current_config['server']['ip'] = current_ip.get()
    current_config['server']['port'] = current_port.get()
    config.save(current_config)
Example #47
0
 def put(self, key):
     CONFIG = config.load()
     if key in CONFIG:
         print(request.form['data'])
         CONFIG[key] = json.loads(request.form['data'])
         config.save(CONFIG)
         return {"result": "ok"}, 201
     else:
         return {"result": "key " + key + " not found"}, 404
Example #48
0
def remove_operator(remove_op):
    conf = config.config()
    config_operators = conf.get('operators', [])
    if remove_op not in config_operators:
        return False
    config_operators.remove(remove_op)
    conf['operators'] = config_operators
    config.save(conf)
    return True
Example #49
0
 def on_continue_clicked(self, _widget):
     self.dlg.hide()
     config.PARSER.set('GUI', 'requests_checked_groups',
                       ','.join([r[1] for r in self.groups_list if r[0]]))
     config.PARSER.set('GUI', 'requests_checked_roles',
                       ','.join([r[1] for r in self.roles_list if r[0]]))
     config.save()
     start_server(self.system, self.get_selected_groups(),
                  self.get_selected_roles())
Example #50
0
 def hide_plugin(self, id):
     """ Hide plugin with given id. This will hide the plugin so queries do
     not return it anymore, and write this change to the config.
     Note that config will then emit a signal
     """
     self.__hidden_plugins.add(id)
     config.set('plugin.hiddenplugins', list(self.__hidden_plugins))
     config.save()
     self.__hidden_changed()
Example #51
0
 def on_close(self, event):
  """Try and stop the reactor."""
  functions.output('Goodbye', process = False)
  try:
   application.log_object.flush()
   config.save()
   reactor.stop()
  except Exception as e:
   logger.exception(e)
  event.Skip()
Example #52
0
 def action_ok(self, event):
     language = self.language.get_selection()
     encoding = self.encoding.get_selection()
     para_start = self.para_start.get_selection()
     if confirm_dialog_no_restart(self):
         c.set_default('DEFAULT_TEXT_LANGUAGE', language)
         c.set_default('DEFAULT_TEXT_ENCODING', encoding)
         c.set_default('DEFAULT_PARAGRAPH_START', para_start)
         c.save()
     self.dispose()            
Example #53
0
 def action_ok(self, event):
     make_folder = self.make_folder.selected
     if confirm_dialog(self):
         c.set_default('MAKE_FOLDER', make_folder)
         c.set_default('DEFAULT_OPEN_DIRECTORY', self.open_file_dir)
         c.set_default('DEFAULT_SAVE_DIRECTORY', self.save_file_dir)
         c.set_default('LOCALE', self.language.get_selection())
         c.set_default('MIDLET_LOCALE', self.midlet_language.get_selection())
         c.save()
     self.dispose()            
def _epoch_raw(subject, block, overwrite=False):
    """high pass filter raw data, make consistent channels and epoch."""

    # Checks if preprocessing has already been done
    epo_fname = paths('epo_block', subject=subject, block=block)
    if op.exists(epo_fname) and not overwrite:
        return
    print(subject, block)

    # Load raw data
    raw = load('sss', subject=subject, block=block, preload=True)

    # Explicit picking of channel to ensure same channels across subjects
    picks = ['STI101', 'EEG060', 'EOG061', 'EOG062', 'ECG063', 'EEG064',
             'MISC004']

    # Potentially add forgotten channels
    ch_type = dict(STI='stim', EEG='eeg', EOG='eog', ECG='ecg',
                   MIS='misc')
    missing_chans = list()
    for channel in picks:
        if channel not in raw.ch_names:
            missing_chans.append(channel)
    if missing_chans:
        info = create_info(missing_chans, raw.info['sfreq'],
                           [ch_type[ch[:3]] for ch in missing_chans])
        raw.add_channels([RawArray(
            np.zeros((len(missing_chans), raw.n_times)), info,
            raw.first_samp)], force_update_info=True)

    # Select same channels order across subjects
    picks = [np.where(np.array(raw.ch_names) == ch)[0][0] for ch in picks]
    picks = np.r_[np.arange(306), picks]

    # high pass filtering
    raw.filter(.1, None, l_trans_bandwidth=.05, filter_length='30s',
               n_jobs=1)

    # Ensure same sampling rate
    if raw.info['sfreq'] != 1000.0:
        raw.resample(1000.0)

    # Select events
    events = find_events(raw, stim_channel='STI101', shortest_event=1)
    sel = np.where(events[:, 2] <= 255)[0]
    events = events[sel, :]

    # Compensate for delay (as measured manually with photodiod
    events[1, :] += .050 * raw.info['sfreq']

    # Epoch continuous data
    epochs = Epochs(raw, events, reject=None, tmin=-.600, tmax=1.8,
                    picks=picks, baseline=None)
    save(epochs, 'epo_block', subject=subject, block=block, overwrite=True,
         upload=False)
Example #55
0
 def modify_login(self):
     login = input_string([4235, 4236], "^[a-zA-Z0-9]$") # type your new
                                     # login ; use alphanumeric characters
     if login == None:
         voice.alert([4238]) # current login kept
     elif (len(login) < 1) or (len(login) > 20):
         voice.alert([4237, 4238]) # incorrect login ; current login kept
     else:
         voice.alert([4239, login]) # new login:
         config.login = login
         config.save()
Example #56
0
def modify_login():
    login = input_string(mp.ENTER_NEW_LOGIN + mp.USE_LETTERS_AND_NUMBERS_ONLY,
                         "^[a-zA-Z0-9]$")
    if login == None:
        voice.alert(mp.CURRENT_LOGIN_KEPT)
    elif (len(login) < 1) or (len(login) > 20):
        voice.alert(mp.BAD_LOGIN + mp.CURRENT_LOGIN_KEPT)
    else:
        voice.alert(mp.NEW_LOGIN + [login])
        config.login = login
        config.save()
Example #57
0
 def reconfigure(self):
     self.bookshelf.configure()
     if self.bookshelf.platform.hasProperty('DISABLE_ROTATION') and self.bookshelf.platform.getProperty('DISABLE_ROTATION') == 'true':
         c.set_default('SCREEN_ROTATION', 0)
         c.save()
         self.bookshelf.configure()
     self.set_title()
     for i in range(self.tabbed_pane.tabCount):
         bookView = self.tabbed_pane.getComponentAt(i)    
         # re-render every loaded book
         bookView.action_preview(None)