Ejemplo n.º 1
0
def get_token(force_creation=False):
    """
    Returns a valid oauth token. Creates a new one if the old token is expired.

    Parameters:
    -----------
    force_creation [optional]bool
        Enforces the creation even if the old token is valid.

    Returns:
    --------
    bool
        Getting the token was successful.
    string
        A valid token or an error message.
    """
    if conf.is_token_expired() or force_creation:
        response = api_token()
        if not response.has_error():
            content = json.loads(response.response)
            Configs.access_token = content['access_token']
            Configs.expires = time.time() + content['expires_in']
            conf.save()
            return True, Configs.access_token
        else:
            if response.error_description == "":
                return False, response.error_text
            else:
                return False, "{0} - {1}".format(response.error_text,
                                                 response.error_description)
    else:
        return True, Configs.access_token
Ejemplo n.º 2
0
def report_error(text):
    """Reports the error, if error reporting is enabled and below limit."""
    if conf.ErrorReportsAutomatic:
        # Set severe constraints on error sending to avoid creating
        # a busy idiot.
        today = datetime.date.today().strftime("%Y%m%d")
        conf.ErrorsReportedOnDay = conf.ErrorsReportedOnDay or {}
        reports_today = conf.ErrorsReportedOnDay.get(today, 0)
        text_hashed = "%s\n\n%s" % (conf.Version, text)
        sha1 = hashlib.sha1(text_hashed.encode("latin1", errors="ignore"))
        hash = sha1.hexdigest()
        if hash not in conf.ErrorReportHashes \
        and reports_today < conf.ErrorReportsPerDay:
            reports_today += 1
            conf.ErrorReportHashes.append(hash)
            conf.ErrorsReportedOnDay[today] = reports_today
            # Keep configuration in reasonable size
            if len(conf.ErrorReportHashes) > conf.ErrorsStoredMax:
                conf.ErrorReportHashes = \
                    conf.ErrorReportHashes[-conf.ErrorHashesMax:]
            if len(conf.ErrorsReportedOnDay) > conf.ErrorsStoredMax:
                days = sorted(conf.ErrorsReportedOnDay.keys())
                # Prune older days from dictionary
                for day in days[:len(days) - conf.ErrorsStoredMax]:
                    del conf.ErrorsReportedOnDay[day]
            conf.save()
            send_report(text, "error")
Ejemplo n.º 3
0
    def toggle(self, category):
        if category not in conf.InputFlags: return

        # Event input (mouse|keyboard), None if category itself is input
        input = next((k for k, vv in conf.InputEvents.items() if category in vv), None)
        attr = conf.InputFlags[category]
        on = not getattr(conf, attr)
        if input and not getattr(conf, conf.InputFlags[input]): # Event input itself off
            on = True # Force on regardless of event flag current state
            # Set other input events off, as only a single one was explicitly enabled
            for c, flag in ((c, conf.InputFlags[c]) for c in conf.InputEvents[input]):
                setattr(conf, flag, False)
        setattr(conf, attr, on)

        # Toggle input on when turning event category on
        if input and on: setattr(conf, conf.InputFlags[input], True)
        elif not any(getattr(conf, conf.InputFlags.get(c), False)
                     for c in conf.InputEvents[input or category]): # Not any event on
            if not input and on: # Turning input on
                # Toggle all input events on since all were off
                for c in conf.InputEvents[category]:
                    setattr(conf, conf.InputFlags[c], True)
            elif input and not on: # Turning single event off
                # Toggle entire input off since all input events are now off
                setattr(conf, conf.InputFlags[input], False)

        conf.save()
        q = self.listenerqueue or self.initialqueue
        q.put("%s %s" % ("start" if on else "stop", category))
Ejemplo n.º 4
0
 def on_exit(self, event):
     """Handler on application exit, saves configuration.
     """
     do_exit = True
     if do_exit:
         conf.save()
         self.Destroy()
Ejemplo n.º 5
0
 def on_exit(self, event):
     """
     Handler on application exit, asks about unsaved changes, if any.
     """
     do_exit = True
     if do_exit:
         conf.save()
         self.Destroy()
Ejemplo n.º 6
0
 def on_exit(self, event):
     """
     Handler on application exit, asks about unsaved changes, if any.
     """
     do_exit = True
     if do_exit:
         conf.save()
         self.Destroy()
Ejemplo n.º 7
0
 def toggle(self, input):
     if "mouse" == input:
         on = conf.MouseEnabled = not conf.MouseEnabled
     elif "keyboard" == input:
         on = conf.KeyboardEnabled = not conf.KeyboardEnabled
     conf.save()
     if self.listenerqueue:
         self.listenerqueue.put("%s_%s" %
                                (input, "start" if on else "stop"))
Ejemplo n.º 8
0
def start(ask_serverurl=True, ask_username=True, ask_password=True, ask_oauth2=True):
    """
    Interactive configuration.
    """
    conf.load_or_create()

    serverurl = conf.get_config('serverurl')
    username = conf.get_config('username')
    password = conf.get_config('password')
    client = conf.get_config('client')
    secret = conf.get_config('secret')

    if ask_serverurl or serverurl == "":
        serverurl = __serverurl(serverurl == "")
    if ask_username or username == "":
        username = __username(username == "")
    if ask_password or password == "":
        password = __password(password == "")
    if ask_oauth2 or client == "" or secret == "":
        client = __client(client == "")
        secret = __secret(secret == "")

    if serverurl != "":
        conf.set_config('serverurl', serverurl)
    if username != "":
        conf.set_config('username', username)
    if password != "":
        conf.set_config('password', password)
    if client != "":
        conf.set_config('client', client)
    if secret != "":
        conf.set_config('secret', secret)

    # username/password and client/secret check
    testresponse = api.api_token()
    if testresponse.has_error():
        conf.save()
        if testresponse.error == api.Error.http_bad_request:
            print(testresponse.error_description)
            if testresponse.error_text == "invalid_grant":
                start(ask_serverurl=False, ask_oauth2=False)
                return
            elif testresponse.error_text == "invalid_client":
                start(ask_serverurl=False, ask_username=False, ask_password=False)
                return
        print("An unknown error occured on the server side. Please try again later.")
        print()
        exit(-1)

    print()
    if conf.save():
        print("The config was saved successfully.")
    else:
        print("An error occured while saving the configuration. Please try again.")
        print()
        exit(-1)
Ejemplo n.º 9
0
 def on_exit(self, event):
     """Handler on application exit, saves configuration."""
     conf.LastText = self.edit_text.Value
     conf.LastLanguage = conf.Languages[self.list_lang.Selection][0]
     if not self.mediactrl.Tell() < 0:  # Nothing loaded and 0 volume if -1
         conf.LastVolume = round(self.mediactrl.GetVolume(), 2)
     conf.WindowPosition = self.Position[:]
     conf.WindowSize = [-1, -1] if self.IsMaximized() else self.Size[:]
     conf.save()
     event.Skip()
Ejemplo n.º 10
0
 def save_last_command(self):
     """
     Saves the last console command in conf, minus the commands given via
     run_console().
     """
     h = [x for x in self.console.history if x not in self.console_commands]
     history = h[: conf.MaxConsoleHistory][::-1]
     if history != conf.ConsoleHistoryCommands:
         conf.ConsoleHistoryCommands[:] = history
         conf.save()
Ejemplo n.º 11
0
 def save_last_command(self):
     """
     Saves the last console command in conf, minus the commands given via
     run_console().
     """
     h = [x for x in self.console.history if x not in self.console_commands]
     history = h[:conf.MaxConsoleHistory][::-1]
     if history != conf.ConsoleHistoryCommands:
         conf.ConsoleHistoryCommands[:] = history
         conf.save()
Ejemplo n.º 12
0
 def on_exit(self, event):
     """Handler on application exit, saves configuration."""
     conf.LastText = self.edit_text.Value
     conf.LastLanguage = conf.Languages[self.list_lang.Selection][0]
     if not self.mediactrl.Tell() < 0: # Nothing loaded and 0 volume if -1
         conf.LastVolume = round(self.mediactrl.GetVolume(), 2)
     conf.WindowPosition = self.Position[:]
     conf.WindowSize = [-1, -1] if self.IsMaximized() else self.Size[:]
     conf.save()
     event.Skip()
Ejemplo n.º 13
0
def onCommandNick(e):
    default_nick = irc.default_nicks()[0]
    if 't' not in e.switches and e.network.me == default_nick:
        conf['nick'] = e.args[0]
        import conf as _conf
        _conf.save()
        for network in set(w.network for w in core.manager):
            if network.me == default_nick:
                change_nick(network, e.args[0])
    else:
        change_nick(e.network, e.args[0])
Ejemplo n.º 14
0
def report_error(text):
    """Reports the error if unknown, reporting enabled and below daily limit."""
    if not conf.ErrorReportsAutomatic:
        return

    # Avoid reporting externally caused errors.
    SKIP_ERRORS = [
        "DatabaseError: database disk image is malformed",
        "OperationalError: attempt to write a readonly database",
        "OperationalError: database is locked",
        "OperationalError: disk I/O error",
        "OperationalError: unable to open database file",
        "SkypeAPIError: Skype attach timeout"
    ]
    if any(x for x in SKIP_ERRORS if x in text):
        return

    # Set severe constraints on error sending to avoid creating a busy idiot.
    today = datetime.date.today().strftime("%Y%m%d")
    conf.ErrorsReportedOnDay = conf.ErrorsReportedOnDay or {}
    sent_today = conf.ErrorsReportedOnDay.get(today, 0)
    text_hashed = "%s\n\n%s" % (conf.Version, text)
    sha1 = hashlib.sha1(text_hashed.encode("latin1", errors="ignore"))
    hash = sha1.hexdigest()
    if hash in conf.ErrorReportHashes or sent_today >= conf.ErrorReportsPerDay:
        return

    conf.ErrorReportHashes.append(hash)
    conf.ErrorsReportedOnDay[today] = sent_today + 1
    # Keep configuration in reasonable size
    if len(conf.ErrorReportHashes) > conf.ErrorsStoredMax:
        conf.ErrorReportHashes = conf.ErrorReportHashes[-conf.ErrorsStoredMax:]
    if len(conf.ErrorsReportedOnDay) > conf.ErrorsStoredMax:
        days = sorted(conf.ErrorsReportedOnDay.keys())
        for day in days[:len(days) - conf.ErrorsStoredMax]:
            del conf.ErrorsReportedOnDay[day]  # Prune older days from log
    conf.save()
    send_report(text, "error")
Ejemplo n.º 15
0
def report_error(text):
    """Reports the error if unknown, reporting enabled and below daily limit."""
    if not conf.ErrorReportsAutomatic:
        return

    # Avoid reporting externally caused errors.
    SKIP_ERRORS = ["DatabaseError: database disk image is malformed",
                   "OperationalError: attempt to write a readonly database",
                   "OperationalError: database is locked",
                   "OperationalError: disk I/O error",
                   "OperationalError: unable to open database file",
                   "SkypeAPIError: Skype attach timeout"]
    if any(x for x in SKIP_ERRORS if x in text):
        return

    # Set severe constraints on error sending to avoid creating a busy idiot.
    today = datetime.date.today().strftime("%Y%m%d")
    conf.ErrorsReportedOnDay = conf.ErrorsReportedOnDay or {}
    sent_today = conf.ErrorsReportedOnDay.get(today, 0)
    text_hashed = "%s\n\n%s" % (conf.Version, text)
    sha1 = hashlib.sha1(text_hashed.encode("latin1", errors="ignore"))
    hash = sha1.hexdigest()
    if hash in conf.ErrorReportHashes or sent_today >= conf.ErrorReportsPerDay:
        return

    conf.ErrorReportHashes.append(hash)
    conf.ErrorsReportedOnDay[today] = sent_today + 1
    # Keep configuration in reasonable size
    if len(conf.ErrorReportHashes) > conf.ErrorsStoredMax:
        conf.ErrorReportHashes = conf.ErrorReportHashes[-conf.ErrorsStoredMax:]
    if len(conf.ErrorsReportedOnDay) > conf.ErrorsStoredMax:
        days = sorted(conf.ErrorsReportedOnDay.keys())
        for day in days[:len(days) - conf.ErrorsStoredMax]:
            del conf.ErrorsReportedOnDay[day] # Prune older days from log
    conf.save()
    send_report(text, "error")
Ejemplo n.º 16
0
 def save_last_command(self):
     """Saves the last console command in conf."""
     history = self.console.history[:conf.ConsoleHistoryMax][::-1]
     if history != conf.ConsoleHistoryCommands:
         conf.ConsoleHistoryCommands[:] = history
         conf.save()
Ejemplo n.º 17
0
 def on_saveConf(self):
     conf.set_ff(self.toFFparam())
     conf.save()
Ejemplo n.º 18
0
 def save_last_command(self):
     """Saves the last console command in conf."""
     history = self.console.history[:conf.ConsoleHistoryMax][::-1]
     if history != conf.ConsoleHistoryCommands:
         conf.ConsoleHistoryCommands[:] = history
         conf.save()
Ejemplo n.º 19
0
 def on_exit(self, event):
     """Handler on application exit, saves configuration."""
     do_exit = True
     if do_exit:
         conf.save()
         self.Destroy()
Ejemplo n.º 20
0
    for jj, T in enumerate(mesh.elements):
        baryCenter[jj] = np.sum(mesh.vertices[T], axis=0) / 3.
    return baryCenter


if __name__ == "__main__":
    from mesh import RegMesh2D
    import conf
    mesh = RegMesh2D(conf.delta, 48)

    # Write
    print("\n h: ", mesh.h)
    conf.data["h"].append(mesh.h)
    conf.data["nV_Omega"].append(mesh.nV_Omega)
    mesh.save("data")
    conf.save("data")

    # Run METIS
    # (Führt C++ Code aus, nämlich die main() Funktion in comparecodes.cpp.
    # Da ist eigentlich nur die Funktion readConfiguration() interessant dort wird am Ende METIS aufgerufen.
    # Das Ergebnis wird in eine File gespeichert: data/result.partition)
    #                         v Anzahl der Subdomains
    os.system("./CompareCodes 6")

    # Read
    filter = np.array(
        assemble.read_arma_mat("data/result.partition").flatten(),
        dtype=np.int)
    adjacency = np.array(assemble.read_arma_mat("data/result.dual").flatten(),
                         dtype=np.int).reshape((13, mesh.nE)).T
    interaction = assemble.read_arma_spMat("data/result.interaction")
Ejemplo n.º 21
0
def save_config(*args):
    conf.save(config)
    set_status_message("Config saved.")
Ejemplo n.º 22
0
def main():
    import conf
    err_ = None
    pp = PdfPages(conf.fnames["triPlot.pdf"])
    for n in conf.N:
        mesh=RegMesh2D(conf.delta, n, ufunc=conf.u_exact, ansatz=conf.ansatz)
        print("\n h: ", mesh.h)
        conf.data["h"].append(mesh.h)
        conf.data["nV_Omega"].append(mesh.nV_Omega)
        mesh.save("data")
        conf.save("data")

        tg = assemble.tensorgauss(4)
        # Assembly ------------------------------------------------------------------------
        start = time()
        A, f = assemble.assemble(mesh, conf.py_Px, conf.py_Py, conf.dx, conf.dy, conf.delta,
                                 model_kernel=conf.model_kernel,
                                 model_f=conf.model_f,
                                 integration_method=conf.integration_method,
                                 is_PlacePointOnCap=conf.is_PlacePointOnCap,
                                 compute="systemforcing",
                                 tensorGaussDegree=conf.tensorGaussDegree)

        conf.data["Assembly Time"].append(time() - start)

        A_O = A[:, :mesh.K_Omega]
        A_I = A[:, mesh.K_Omega:]

        if conf.ansatz == "CG":
            g = np.apply_along_axis(conf.u_exact, 1, mesh.vertices[mesh.nV_Omega:])
        else:
            g = np.zeros(((mesh.K - mesh.K_Omega) // mesh.outdim, mesh.outdim))
            for i, E in enumerate(mesh.elements[mesh.nE_Omega:]):
                for ii, Vdx in enumerate(E):
                    vert = mesh.vertices[Vdx]
                    g[3*i + ii] = conf.u_exact(vert)
        f -= A_I @ g.ravel()

        # Solve ---------------------------------------------------------------------------
        print("Solve...")
        #mesh.write_ud(np.linalg.solve(A_O, f), conf.u_exact)
        x = cg(A_O, f, f)[0].reshape((-1, mesh.outdim))
        #print("CG Solve:\nIterations: ", solution["its"], "\tError: ", solution["res"])
        mesh.write_ud(x, conf.u_exact)

        # Some random quick Check....
        #filter = np.array(assemble.read_arma_mat("data/result.fd").flatten(), dtype=bool)
        #plt.scatter(mesh.vertices[filter][:,0], mesh.vertices[filter][:,1])
        #plt.scatter(mesh.vertices[np.invert(filter)][:,0], mesh.vertices[np.invert(filter)][:,1])
        #plt.show()

        # Refine to N_fine ----------------------------------------------------------------
        mesh.plot_ud(pp)
        mesh = RegMesh2D(conf.delta, conf.N_fine, ufunc=conf.u_exact, coarseMesh=mesh,
                         is_constructAdjaciencyGraph=False, ansatz=conf.ansatz)

        # Evaluate L2 Error ---------------------------------------------------------------
        u_diff = (mesh.u_exact - mesh.ud)[:mesh.K_Omega]
        Mu_udiff = assemble.evaluateMass(mesh, u_diff, conf.py_Px, conf.dx)
        err = np.sqrt(u_diff.ravel() @ Mu_udiff)

        # Print Rates ---------------------------------------------------------------------
        print("L2 Error: ", err)
        conf.data["L2 Error"].append(err)
        if err_ is not None:
            rate = np.log2(err_/err)
            print("Rate: \t",  rate)
            conf.data["Rates"].append(rate)
        else:
            conf.data["Rates"].append(0)
        err_ = err
    pp.close()

    return conf.data