def hists_core_distance_vs_time():
    plt.figure()

    sim = data.root.showers.E_1PeV.zenith_0
    electrons = sim.electrons

    bins = np.logspace(0, 2, 5)
    for low, high in zip(bins[:-1], bins[1:]):
        sel = electrons.readWhere(
            '(low < core_distance) & (core_distance <= high)')
        arrival_time = sel[:]['arrival_time']
        plt.hist(arrival_time,
                 bins=np.logspace(-2, 3, 50),
                 histtype='step',
                 label="%.2f <= log10(R) < %.2f" %
                 (np.log10(low), np.log10(high)))

    plt.xscale('log')

    plt.xlabel("Arrival Time [ns]")
    plt.ylabel("Count")
    plt.legend(loc='upper left')

    utils.title("Shower front timing structure")
    utils.saveplot()
Пример #2
0
def median_core_distance_vs_time():
    plt.figure()
    plot_and_fit_statistic(lambda a: scoreatpercentile(a, 25))
    plot_and_fit_statistic(lambda a: scoreatpercentile(a, 75))

    utils.title("Shower front timing structure (25, 75 %)")
    utils.saveplot()
    plt.xlabel("Core distance [m]")
    plt.ylabel("Median arrival time [ns]")
    legend(loc='lower right')
Пример #3
0
def median_core_distance_vs_time():
    plt.figure()
    plot_and_fit_statistic(lambda a: scoreatpercentile(a, 25))
    plot_and_fit_statistic(lambda a: scoreatpercentile(a, 75))

    utils.title("Shower front timing structure (25, 75 %)")
    utils.saveplot()
    plt.xlabel("Core distance [m]")
    plt.ylabel("Median arrival time [ns]")
    legend(loc='lower right')
Пример #4
0
def scatterplot_core_distance_vs_time():
    plt.figure()

    sim = data.root.showers.E_1PeV.zenith_0
    electrons = sim.electrons

    plt.loglog(electrons[:]['core_distance'], electrons[:]['arrival_time'], ',')
    plt.xlim(1e0, 1e2)
    plt.ylim(1e-3, 1e3)

    plt.xlabel("Core distance [m]")
    plt.ylabel("Arrival time [ns]")

    utils.title("Shower front timing structure")
    utils.saveplot()
Пример #5
0
def scatterplot_core_distance_vs_time():
    plt.figure()

    sim = data.root.showers.E_1PeV.zenith_0
    electrons = sim.electrons

    plt.loglog(electrons[:]['core_distance'], electrons[:]['arrival_time'], ',')
    plt.xlim(1e0, 1e2)
    plt.ylim(1e-3, 1e3)

    plt.xlabel("Core distance [m]")
    plt.ylabel("Arrival time [ns]")

    utils.title("Shower front timing structure")
    utils.saveplot()
Пример #6
0
def main_loop():
    # Use only colors in the format of #RRGGBB
    MyAmber = {
        "BACKGROUND": "#ebb41c",
        "TEXT": "#000000",
        "INPUT": "#FDFFF7",
        "TEXT_INPUT": "#000000",
        "SCROLL": "#FDFFF7",
        "BUTTON": ("#000000", "#fdcb52"),
        "PROGRESS": ('#000000', '#000000'),
        "BORDER": 1,
        "SLIDER_DEPTH": 0,
        "PROGRESS_DEPTH": 0,
    }

    # Add your dictionary to the PySimpleGUI themes
    sg.theme_add_new('MyAmber', MyAmber)

    # Switch your theme to use the newly added one
    sg.theme('My Amber')

    if not sg.UserSettings()['-setup-']:
        company.Company.init_companies()
    while True:
        try:
            if menus():
                break
        except Exception as e:
            print(utils.title() + "\n" + str(e) + "\n" +
                  traceback.format_exc())
            print("Fataler Fehler - angehalten.")
            while True:
                pass
Пример #7
0
def hists_core_distance_vs_time():
    plt.figure()

    sim = data.root.showers.E_1PeV.zenith_0
    electrons = sim.electrons

    bins = np.logspace(0, 2, 5)
    for low, high in zip(bins[:-1], bins[1:]):
        sel = electrons.read_where('(low < core_distance) & (core_distance <= high)')
        arrival_time = sel[:]['arrival_time']
        plt.hist(arrival_time, bins=np.logspace(-2, 3, 50), histtype='step',
                 label="%.2f <= log10(R) < %.2f" % (np.log10(low),
                                                    np.log10(high)))

    plt.xscale('log')

    plt.xlabel("Arrival Time [ns]")
    plt.ylabel("Count")
    plt.legend(loc='upper left')

    utils.title("Shower front timing structure")
    utils.saveplot()
Пример #8
0
def AES():
    while True:
        title('AES Encryption / Decryption', fillchar='-')
        [print() for i in range(5)]
        print('Do you want to...')
        print('1. Encrypt a file')
        print('2. Decrypt a file')
        print('3. Exit')
        print('_' * utils.get_terminal_size()[0])
        print()
        action = input('>> ').lower()
        if action in ['1', 'encrypt', 'e']:
            title('AES Encryption / Decryption', fillchar='-')
            print()
            print()
            print('Please select a file in the dialog box.')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Choose a file to encrypt...')
            password = getpass('Enter password for file: ').encode('utf-8')
            print('Choose the name for the encrypted file.')
            outfilename = asksaveasfilename(
                initialdir=cwd,
                title='Choose the name for the encrypted file...')
            chunksize = input('Enter encryption chunksize: ') or 64 * 1024
            if chunksize:
                chunksize = int(chunksize)
            aes.encrypt(password, filename, outfilename, chunksize)

        elif action in ['2', 'decrypt', 'd']:
            title('AES Encryption / Decryption', fillchar='-')
            print()
            print()
            print('Please select a file in the dialog box.')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Choose a file to decrypt...')
            password = getpass('Enter password to decrpyt file: ').encode(
                'utf-8')
            print('Choose the name for the output file.')
            outfilename = asksaveasfilename(
                initialdir=cwd,
                title='Choose the name for the decrypted file...')
            chunksize = input('Enter decryption chunksize: ') or 24 * 1024
            if chunksize:
                chunksize = int(chunksize)

            aes.decrypt(password, filename, outfilename, chunksize)

        elif action in ['3', 'exit', 'quit', 'q']:
            exit(0)

        else:
            clear()
            _tmp = input('That is not an action.')
Пример #9
0
#!/usr/bin/env python

# General libs
import re
import json
import os
import sys

# Tool libs
from utils import run, sanitize
import utils
import conf
from objects import GameAchievement


utils.title('ACHIEVEMENTS')

###
#   GLOBALS
###
ITEMS = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for java files...")
#utils.sub("Keywords: %s" % ', '.join(conf.ACHIEVEMENTS_JAVA_KEYWORDS))
for keyword in conf.ACHIEVEMENTS_JAVA_KEYWORDS:
    cmd = run('grep \'%s\' ./classes/*' % keyword)
    for result in cmd:
        if result and result is not '':
Пример #10
0
import utils
import ranker
from pprint import pprint
import statistics

repetitions = 10
set_size = 1000

for version in [0, 1]:
    utils.title('version {}'.format(version))
    print(f'ranking sets of {set_size} trips ({repetitions} reps)')
    ranking_function = lambda x: ranker.rank_elements(x, version=version)
    info = utils.profile_ranker(ranking_function,
                                set_size=set_size,
                                repetitions=repetitions)
    print('average number of base function calls {}'.format(
        statistics.mean([run['rank_call_count'] for run in info])))
Пример #11
0
def run(path):
    project = Project(path)

    issues_grouped_by_type = project.group_issues_by_type(project.issues)
    issues_grouped_by_status = project.group_issues_by_status(project.issues)

    # Level of detail
    for issue_type, issue_type_list in issues_grouped_by_type.items():
        title('%s (%s)' % (issue_type, len(issue_type_list)))

        average_description_size = round(
            mean([
                issue.get_size_of_description() for issue in issue_type_list
            ]), 2)
        average_acceptance_criteria_size = round(
            mean([
                issue.get_size_of_acceptance_criteria()
                for issue in issue_type_list
            ]), 2)
        average_how_to_test_size = round(
            mean([
                issue.get_size_of_how_to_test() for issue in issue_type_list
            ]), 2)

        print('Average description size: %s lines' % average_description_size)
        print('Average acceptance criteria size: %s lines' %
              average_acceptance_criteria_size)
        print('Average how to test size: %s lines' % average_how_to_test_size)

    # Type and status distribution
    title('Issue distribution by status (overall)')
    issue_status_distribution = {
        issue_type: len(issue_type_list)
        for issue_type, issue_type_list in issues_grouped_by_status.items()
    }
    for issue, count in issue_status_distribution.items():
        print('- %s: %s' % (issue, count))

    title('Issue distribution by type and status')
    for issue_type, issue_type_list in issues_grouped_by_type.items():
        print('+ %s: %s' % (issue_type, len(issue_type_list)))
        issue_type_status_distribution = project.group_issues_by_status(
            issue_type_list)
        for issue, count in issue_type_status_distribution.items():
            print(' - %s: %s' % (issue, len(count)))

    # Activity distribution by status
    description_updates = Counter()
    acceptance_criteria_updates = Counter()
    how_to_test_updates = Counter()
    comments = Counter()

    for issue in project.issues:
        description_updates += Counter(
            issue.get_description_update_by_status_distribution())
        acceptance_criteria_updates += Counter(
            issue.get_acceptance_criteria_update_by_status_distribution())
        how_to_test_updates += Counter(
            issue.get_how_to_test_update_by_status_distribution())
        comments += Counter(issue.get_comments_by_status_distribution())

    # Update distribution
    title('Number of updates in status')

    def display_updates(title, counter):
        print('+ %s' % title)
        for k, v in dict(counter).items():
            print(' - %s: %s' % (k, v))

    display_updates('Description', description_updates)
    display_updates('Acceptance criteria', acceptance_criteria_updates)
    display_updates('How to test', how_to_test_updates)
    display_updates('Comments', comments)

    # Time distribution

    # Filter only issues that have been through 'Todo', meaning they were ready to be dragged into 'In Progress'
    issues = [
        issue for issue in project.issues if 'Todo' in issue.get_status_flow()
    ]
    issues_grouped_by_type = project.group_issues_by_type(issues)

    title('Average time spent in status')
    for issue_type, issue_type_list in issues_grouped_by_type.items():
        status_date_distributions = [
            issue.get_status_date_distribution() for issue in issue_type_list
        ]
        dd = defaultdict(list)
        for d in status_date_distributions:
            for key, value in d.items():
                dd[key].append(value)

        print('+ %s' % issue_type)
        for key, value in project.sort_issue_status(dd).items():
            print(' - %s: %s' % (key, seconds_to_human(round(mean(value), 2))))
Пример #12
0
#!/usr/bin/env python

# General libs
from os import listdir, environ
from os.path import isfile, join
from sys import path
import json
from PIL import Image

# Tool libs
import utils
import conf
from objects import GameTexture

utils.title("TEXTURES")

if conf.SAVE:
    path.append('../../minecraftcodex')
    environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    from database.models import Texture

TEXTURES = []

# Old textures for final count
try:
    OLD_TEXTURES = json.loads(open('textures.json').read())
except:
    OLD_TEXTURES = {}
    OLD_TEXTURES['list'] = []

Пример #13
0
#!/usr/bin/env python

# General libs
import re
import json
import os
import sys

# Tool libs
import utils
import conf
from objects import GameItem


utils.title("ITEMS")

if conf.SAVE:
    sys.path.append('../../minecraftcodex')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    from database.models import Item, Texture

###
#   GLOBALS
###
ITEMS = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for java files: ")
#utils.sub("Keywords: %s" % ', '.join(conf.ITEMS_JAVA_KEYWORDS), end='\n')
Пример #14
0
#!/usr/bin/env python

# General libs
import re
import json
import os
import sys

# Tool libs
from utils import run, sanitize
import utils
import conf
from objects import GameMob

utils.title('MOS')

if conf.SAVE:
    sys.path.append('../../minecraftcodex')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    #from database.models import Achievement

###
#   GLOBALS
###
ITEMS = []
ITEMS_STR = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for java files...")
Пример #15
0
#!/usr/bin/env python

# General libs
import re
import json
import os
import sys

# Tool libs
from utils import run, sanitize
import utils
import conf
from objects import GameAchievement

utils.title('ACHIEVEMENTS')

if conf.SAVE:
    sys.path.append('../../minecraftcodex')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    from database.models import Achievement

###
#   GLOBALS
###
ITEMS = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for java files...")
#utils.sub("Keywords: %s" % ', '.join(conf.ACHIEVEMENTS_JAVA_KEYWORDS))
Пример #16
0
def RSA(action):
    if action == '2':
        title('RSA keygen', fillchar='-')
        print()
        print()
        print('Select directory for the keys.')
        Tk().withdraw()
        while True:
            outfolder = askdirectory(
                initialdir=cwd, title='Select directory to save keys in...')
            if not outfolder:
                print('Please choose a directory.')
            else:
                if not os.path.exists(outfolder):
                    os.makedirs(outfolder, exist_ok=True)
                break

        bits = int(input('Size of the key (default is 2048): ') or 2048)
        rsa.generate(bits, outfolder)

    elif action == '3':
        title('RSA Encryption / Decryption', fillchar='-')
        [print() for i in range(5)]
        print('Do you want to...')
        print('1. Encrypt a file')
        print('2. Decrypt a file')
        print('3. Exit')
        print('_' * utils.get_terminal_size()[0])
        print()
        action = input('>> ').lower()
        if action == '1':
            title('RSA Encryption / Decryption', fillchar='-')
            print()
            print()
            print('Select a file to encrypt in the dialog box.')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Choose a file to encrypt...')
            print(filename)
            filedir = os.path.dirname(filename)
            print('Select the public key to encrypt the file with.')
            Tk().withdraw()
            keypath = askopenfilename(initialdir=cwd,
                                      title='Choose a public key...')
            print(keypath)
            keydir = os.path.dirname(keypath)
            print('Select the name for the encrypted file.')
            Tk().withdraw()
            outfile = asksaveasfilename(initialdir=filedir, title='Save as...')
            print('Select the name for the encrypted key.')
            Tk().withdraw()
            outkeyfile = asksaveasfilename(initialdir=filedir,
                                           title='Save as...')
            print(outfile)
            chunksize = input(
                'Select chunksize (leave empty for default): ') or 64 * 1024
            rsa.encrypt(keypath, filename, outfile, outkeyfile, chunksize)

        elif action == '2':
            title('RSA Encryption / Decryption', fillchar='-')
            print()
            print()
            print('Select a file to decrypt in the dialog box.')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Choose a file to decrypt...')
            print(filename)
            filedir = os.path.dirname(filename)
            print('Select the private key to decrypt the file with.')
            Tk().withdraw()
            keypath = askopenfilename(initialdir=cwd,
                                      title='Choose a private key...')
            print(keypath)
            keydir = os.path.dirname(keypath)
            print('Select the encrypted key file used to encrypt the file.')
            Tk().withdraw()
            keyfilepath = askopenfilename(
                initialdir=filedir, title='Choose the encrypted key file...')
            print(keyfilepath)
            print('Select the name for the decrypted file.')
            Tk().withdraw()
            outfile = asksaveasfilename(initialdir=filedir, title='Save as...')
            print(outfile)
            chunksize = input(
                'Select chunksize (leave empty for default): ') or 24 * 1024
            rsa.decrypt(keypath, filename, keyfilepath, outfile, chunksize)

        elif action == '3':
            exit(0)

    elif action == '4':
        title('RSA Signature / verification', fillchar='-')
        [print() for i in range(5)]
        print('Do you want to...')
        print('1. Sign a file')
        print('2. Verify a file')
        print('3. Exit')
        print('_' * utils.get_terminal_size()[0])
        print()
        action = input('>> ').lower()

        if action == '1':
            title('RSA Signature / verification', fillchar='-')
            print()
            print()
            print('Select file to sign...')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Select file to sign...')
            print(filename)
            filedir = os.path.dirname(filedir)
            print('Select private key...')
            Tk().withdraw()
            privKey = askopenfilename(initialdir=cwd,
                                      title='Select private key...')
            print(privKey)
            print('Select name for signature file...')
            signature = asksaveasfilename(
                initialdir=filedir,
                title='Select signature filename...') or None
            print(signature)
            sign(filename, privKey, signature)

        elif action == '2':
            title('RSA Signature / verification', fillchar='-')
            print()
            print()
            print('Select file to verify...')
            Tk().withdraw()
            filename = askopenfilename(initialdir=cwd,
                                       title='Select file to verify...')
            print(filename)
            filedir = os.path.dirname(filename)
            print('Select public key...')
            Tk().withdraw()
            pubKey = askopenfilename(initialdir=cwd,
                                     title='Select public key...')
            print(pubKey)
            print('Select signature file...')
            signature = askopenfilename(initialdir=filedir,
                                        title='Select signature file...')
            print(signature)
            valid = verify(filename, signature, pubKey)
            if valid:
                print(
                    'Success! Signature and hash are the same, so the file has not been tampered with.'
                )
                _tmp = input('Press enter to continue...')
            elif not valid:
                clear()
                print('FILE AUTHENTICITY COULD NOT BE VERIFIED!')
                print(
                    'Do not trust the file or its sender. Did you use the correct public key?'
                )
                print(
                    'Error: Verification failed. Authenticity of file could not be verified.'
                )

        elif action == '3':
            pass

    else:
        TypeError('invalid action: \'%s\' in RSA()')
Пример #17
0
def event_handler(event, window):
    settings = sg.UserSettings()
    show_company_data = False
    if event in (sg.WIN_CLOSED, 'Exit'):
        return "exit"
    if event in company.Company.all():
        settings['-company-'] = event
        company.Company.current_load_data()
        return "outer"
    #print(event, values)
    elif event == 'Über':
        print()
        print('ERPNext Client für Solidarische Ökonomie Bremen',
              'Version ' + VERSION)
    elif event == 'Hilfe Server':
        print()
        print('Anleitung für Einstellungen ERPNext-Server:')
        print(
            '- Adresse des ERPNext-Servers: z.B. https://erpnext.cafesunshine.de'
        )
        print(
            '- API-Schlüssel und -Geheimnis bekommt man im ERPNext-Webclient')
        print('- (d.h. im Browser unter eben jener Adresse)')
        print('  - unter Einstellungen - My Settings')
        print('  - API-Zugriff (ganz unten auf der Seite)')
        print('  - dann "Schlüssel generieren" anklicken')
        print('  - das API-Geheimnis wird nur einmal angezeigt!')
        print('  - der API-Schlüssel wird stets angezeigt')
        print('- Diese Daten hier unter "Einstellungen" eingeben.')
    elif event == 'Hilfe Banktransaktionen':
        print()
        print('Das Datum des letzten Kontoauszugs wird angezeigt')
        print(
            'Im Homebanking die Banktransaktionen seit diesem Datum herunterladen und als csv-Datein speichern'
        )
        print(
            '- Doppelungen werden erkannt, also lieber einen zu großen statt zu kleinen Zeitraum wählen'
        )
        print('Dann hier unter Einlesen - Kontoauszug die csv-Datei hochladen')
        print(
            'Danach unter Bearbeiten - Banktransaktionen die Banktransaktionen zuordnen'
        )
        print(
            'Jeder Banktransaktion muss ein ERPNext-Buchungskonto oder eine offene Rechnung zugeordnet werden'
        )
        print(
            '- Dadurch entsteht ein ERPNext-Buchungssatz oder eine ERPNext-Zahlung'
        )
        print(
            '- Man kann die Bearbeitung einer Banktransaktion auch abbrechen und mit der nächsten weitermachen'
        )
        print(
            '  - Die Banktransaktion bleibt dann offen und kann später bearbeitet werden'
        )
        print(
            'Schließlich müssen die ERPNext-Buchungssätze und ERPNext-Zahlungen noch gebucht werden'
        )
        print(
            '-> Das geht unter Anzeigen - Buchungssätze bzw. Anzeigen - Zahlungen, oder auf der ERPNext-Seite'
        )
    elif event == 'Hilfe Rechnungen':
        print()
        print('Einlesen von Einkaufsrechnungen:')
        suppliers = ", ".join(
            purchase_invoice.PurchaseInvoice.suppliers.keys())
        print(
            'Derzeit können Rechnungen von folgenden Lieferanten eingelesen werden: '
            + suppliers)
        print(
            '(Für andere Lieferanten bitte im ERPNext-Webclient manuell eine Rechnung anlegen. Die Liste der hier möglichen Lieferanten kann ggf. erweitert werden.)'
        )
        print('Das Einlesen einer Rechnung geht hier wie folgt:')
        print(
            '- Unter Einlesen - Einkaufsrechnung das PDF hochladen (bitte keinen Scan einer Rechnung und keine Auftragsbestätigung!)'
        )
        print('- oder unter Einlesen - Einkaufsrechnung Balkonmodule')
        print('Bei Balkonmodul-Rechnungen wird das Lager aktualisiert, d.h.:')
        print(
            '- Für jeden Rechnungenartikel muss ein ERPNext-Artikel gefunden werden'
        )
        print(
            '- Es kann auch ein neuer ERPNext-Artikel angelegt werden, mit den Daten aus der Rechnung'
        )
        print('- Ggf. muss der Preis angepasst werden')
        print(
            'Für alle Rechnungen (ob Balkonmodul oder nicht) wird schließlich die Einkaufsrechnungen in ERPNext hochgeladen.'
        )
        print('Dort muss sie noch geprüft und gebucht werden')
    elif event == 'Hilfe Buchen':
        print()
        print(
            'In ERPNext werden Dokumente wie Rechnungen, Buchungssätze und Zahlungen zunächst als Entwurf gespeichert.'
        )
        print(
            'Im Entwurfsstadium kann ein Dokument noch bearbeitet oder auch gelöscht werden.'
        )
        print(
            'Schließlich muss das Dokument gebucht werden. Nur dann wird es für die Abrechnung wirksam.'
        )
        print(
            'Ein einmal gebuchtes Dokument bleibt für immer im System. Es kann nicht mehr bearbeitet werden. Das ist gesetzlich so vorgeschrieben.'
        )
        print(
            'Es kann allerdings abgebrochen und abgeändert werden. Dadurch entsteht ein neues Dokument (eine Kopie).'
        )
        print(
            'Das alte Dokument bleibt aber als abgebrochenes Dokument im System.'
        )
    elif event == 'ERPNext-Server':
        layout = [[sg.Text('Adresse des ERPNext-Servers')],
                  [sg.Input(default_text=settings['-server-'])],
                  [sg.Text('API-Schlüssel für Server-API')],
                  [sg.Input(default_text=settings['-key-'])],
                  [sg.Text('API-Geheimnis für Server-API')],
                  [sg.Input(default_text=settings['-secret-'])],
                  [sg.Button('Testen')]]
        window1 = sg.Window("ERPNext-Server-Einstellungen",
                            layout,
                            finalize=True)
        window1.bring_to_front()
        event, values = window1.read()
        if values:
            if len(values) > 0 and values[0]:
                settings['-server-'] = values[0]
            if len(values) > 1 and values[1]:
                settings['-key-'] = values[1]
            if len(values) > 2 and values[2]:
                settings['-secret-'] = values[2]
            window1.close()
            if "http:" in settings['-server-']:
                settings['-server-'] = settings['-server-'].replace(
                    'http', 'https')
            print()
            print("Teste API ...")
            result = api_wrapper(Api.initialize)
            if result['err_msg'] or result['exception']:
                if result['err_msg']:
                    print(result['err_msg'])
                elif result['exception']:
                    print(result['exception'])
                print("API-Test fehlgeschlagen!")
                settings['-setup-'] = True
            else:
                print("API-Test erfolgreich!")
                settings['-setup-'] = False
                initial_loads()
                window.close()
                return "outer"
    elif event == 'Update':
        print()
        print("Aktualisiere dieses Programm...")
        tmp = tempfile.mktemp()
        os.system("cd {}; git pull --rebase > {} 2>&1".format(
            settings['-folder-'], tmp))
        f = open(tmp, 'r')
        print(f.read())
        f.close()
        print("Bitte Programm neu starten.")
    elif event == 'Sofort buchen':
        c = checkbox_input(
            'Buchungseinstellungen',
            'Ein Dokument muss gebucht werden, um für die Abrechnung wirksam zu werden.\nEin einmal gebuchtes Dokument bleibt für immer im System. Es kann nicht mehr bearbeitet werden. Das ist gesetzlich so vorgeschrieben.\nBei einer Einkaufsrechnung wird in jedem Fall gefragt, ob diese gebucht werden soll.',
            'Alle Dokumente immer gleich einbuchen',
            default=settings['-buchen-'])
        if c is not None:
            settings['-buchen-'] = c
    elif settings['-setup-']:
        print()
        print("Bitte erst ERPNext-Server einstellen (unter Einstellungen)")
        return "inner"
    elif event == 'Daten neu laden':
        company.Company.clear_companies()
        bank.BankAccount.clear_baccounts()
        initial_loads()
        show_company_data = True
    elif event == 'Kontoauszug':
        filename = utils.get_file('Kontoauszug als csv')
        if filename:
            print()
            print("Lese {} ein ...".format(filename))
            b = bank.BankStatement.process_file(filename)
            if b:
                comp = b.baccount.company.name
                if settings['-company-'] != comp:
                    print("Kontoauszug ist für " + comp)
                settings['-company-'] = comp
                show_company_data = True
                print("{} Banktransaktionen eingelesen, davon {} neu".\
                      format(len(b.entries),len(b.transactions)))
            else:
                print("Konnte keinen Kontoauszug einlesen")
    elif event == 'Einkaufsrechnung':
        if purchase_inv(False):
            show_company_data = True
    elif event == 'Einkaufsrechnung Balkonmodule':
        if purchase_inv(True):
            show_company_data = True
    elif event == 'Banktransaktionen bearbeiten':
        comp = company.Company.get_company(settings['-company-'])
        if comp:
            comp.reconciliate_all()
            show_company_data = True
    elif event == 'Buchungssätze':
        keys = [
            'posting_date', 'account', 'caccount', 'total_debit', 'user_remark'
        ]
        headings = [
            'Datum', 'Buchungskonto', 'Gegenkonto', 'Betrag', 'Bemerkung'
        ]
        while True:
            comp = company.Company.get_company(settings['-company-'])
            jes = comp.open_journal_entries()
            jes1 = []
            for j in jes:
                j1 = gui_api_wrapper(Api.api.get_doc, 'Journal Entry',
                                     j['name'])
                j1['account'] = j1['accounts'][0]['account']
                j1['caccount'] = j1['accounts'][1]['account']
                jes1.append(j1)
            title = "Buchungssätze"
            tbl = table.Table(jes1,
                              keys,
                              headings,
                              title,
                              enable_events=True,
                              display_row_numbers=True)
            ix = tbl.display()
            if ix is False:
                break
            je = jes[ix]
            details = utils.format_entry(jes1[ix], keys, headings)
            choice = easygui.buttonbox("Buchungssatz {}\n{} ".\
                                           format(je['name'],details),
                                       "Buchungssatz",
                                       ["Buchen","Löschen","Nichts tun"])
            if choice == "Buchen":
                bank.BankTransaction.submit_entry(je['name'])
                show_company_data = True
            elif choice == "Löschen":
                bank.BankTransaction.delete_entry(je['name'])
                show_company_data = True
    elif event == 'Zahlungen':
        while True:
            keys = ['posting_date', 'paid_amount', 'party', 'reference_no']
            headings = ['Datum', 'Betrag', 'Gezahlt an', 'Referenz.']
            comp = company.Company.get_company(settings['-company-'])
            pes = comp.open_payment_entries()
            title = "Zahlungen"
            tbl = table.Table(pes,
                              keys,
                              headings,
                              title,
                              enable_events=True,
                              display_row_numbers=True)
            ix = tbl.display()
            if ix is False:
                break
            pe = pes[ix]
            details = utils.format_entry(pe, keys, headings)
            choice = easygui.buttonbox("Zahlung {}\n{} ".\
                                           format(pe['name'],details),
                                       "Zahlung",
                                       ["Buchen","Löschen","Nichts tun"])
            if choice == "Buchen":
                bank.BankTransaction.submit_entry(pe['name'], is_journal=False)
                show_company_data = True
            elif choice == "Löschen":
                bank.BankTransaction.delete_entry(pe['name'], is_journal=False)
                show_company_data = True
    elif event in ['Einkaufsrechnungen', 'Verkaufsrechnungen']:
        while True:
            keys = [
                'posting_date', 'outstanding_amount', 'bill_no', 'status',
                'account', 'supplier', 'title'
            ]
            headings = [
                'Datum', 'Ausstehend', 'Rechungsnr.', 'Status',
                'Buchungskonto', 'Lieferant', 'Titel'
            ]
            comp = company.Company.get_company(settings['-company-'])
            if event == 'Einkaufsrechnungen':
                inv_type = 'Purchase Invoice'
            else:
                inv_type = 'Sales Invoice'
            invs = comp.get_open_invoices_of_type(inv_type)
            inv_docs = []
            bt_dict = defaultdict(list)
            for i in range(len(invs)):
                name = invs[i].name
                inv_doc = gui_api_wrapper(Api.api.get_doc, inv_type, name)
                if not 'bill_no' in inv_doc:
                    inv_doc['bill_no'] = name
                accounts = list(
                    set(map(lambda i: i['expense_account'], inv_doc['items'])))
                inv_doc['account'] = accounts[0]
                if len(accounts) > 1:
                    inv_doc['account'] + " + weitere"
                total = inv_doc['grand_total']
                if inv_type == 'Purchase Invoice':
                    total = -total
                bt = bank.BankTransaction.find_bank_transaction(\
                       comp.name,total,
                       inv_doc['bill_no'] if 'bill_no' in inv_doc else "")
                if bt:
                    ref = None
                    if 'customer' in inv_doc:
                        ref = inv_doc['customer']
                    if 'supplier' in inv_doc:
                        ref = inv_doc['supplier']
                    if ref:
                        inv_doc['similarity'] = \
                            utils.similar(bt.description.lower(),
                                          ref.lower())
                        bt_dict[bt.name].append((i, inv_doc['similarity']))
                        inv_doc['bt'] = bt
                        inv_doc['btname'] = bt.name
                inv_doc['disabled'] = not (bt or inv_doc['status'] == 'Draft')
                inv_docs.append(inv_doc)
            # handle duplicate bank transactions, use best matching invoice
            for bt, entries in bt_dict.items():
                entries.sort(key=lambda e: e[1], reverse=True)
                for (i, s) in entries[1:]:
                    del inv_docs[i]['bt']
                    del inv_docs[i]['btname']
            tbl = table.Table(inv_docs,
                              keys + ['btname'],
                              headings + ['Bank'],
                              event,
                              enable_events=True,
                              display_row_numbers=True)
            ix = tbl.display()
            if ix is False:
                break
            inv_doc = inv_docs[ix]
            details = utils.format_entry(inv_doc, keys, headings)
            msg = "{} {}\n{} ".\
                      format(event[:-2],inv_doc['name'],details)
            choices = [
                "Buchen", "Löschen", "Buchungskonto bearbeiten", "Nichts tun"
            ]
            if 'bt' in inv_doc:
                bt = inv_doc['bt']
                msg += "\n\nZugehörige Bank-Transaktion gefunden: {}\n".\
                         format(bt.description)
                choices[0] = "Sofort buchen und zahlen"
            if bt or inv_doc['status'] == 'Draft':
                choice = easygui.buttonbox(msg, event[:-2], choices)
                #print(choice)
                if choice == "Buchen" or choice == "Sofort buchen und zahlen":
                    gui_api_wrapper(Api.submit_doc, inv_type, inv_doc['name'])
                    show_company_data = True
                    if choice == "Sofort buchen und zahlen":
                        inv = Invoice(inv_doc, inv_type == 'Sales Invoice')
                        inv.payment(bt)
                elif choice == "Löschen":
                    gui_api_wrapper(Api.api.delete, inv_type, inv_doc['name'])
                    show_company_data = True
                elif choice == "Buchungskonto bearbeiten":
                    if inv_doc['account'][-10:] != ' + weitere':
                        title = "Buchungskonto ändern"
                        msg = "Bitte ein Buchungskonto auswählen"
                        accounts = comp.leaf_accounts_for_credit
                        account_names = [acc['name'] for acc in accounts]
                        account_names.remove(inv_doc['account'])
                        texts = [inv_doc['account']] + account_names
                        account = easygui.choicebox(msg, title, texts)
                        del inv_doc['account']
                        nitems = []
                        for item in inv_doc['items']:
                            item['expense_account'] = account
                            nitems.append(item)
                        inv_doc['items'] = nitems
                        gui_api_wrapper(Api.api.update, inv_doc)
    elif event == 'Banktransaktionen':
        keys = ['date', 'amount', 'description']
        headings = ['Datum', 'Betrag', 'Bemerkung']
        comp = company.Company.get_company(settings['-company-'])
        while True:
            bts = comp.open_bank_transactions()
            for bt in bts:
                bt['amount'] = bt['unallocated_amount'] * np.sign(
                    bt['deposit'] - bt['withdrawal'])
            title = "Banktransaktionen"
            tbl = table.Table(bts,
                              keys,
                              headings,
                              title,
                              enable_events=True,
                              max_col_width=120,
                              display_row_numbers=True)
            ix = tbl.display()
            if ix is False:
                break
            comp.reconciliate(bts[ix])
            show_company_data = True
    elif event in bank.BankAccount.get_baccount_names():
        keys = ['date', 'open', 'amount', 'balance', 'description']
        headings = ['Datum', 'Offen', 'Betrag', 'Stand', 'Bemerkung']
        while True:
            bts = gui_api_wrapper(Api.api.get_list,
                                  'Bank Transaction',
                                  filters={
                                      'bank_account': event,
                                      'status': ['!=', 'Cancelled']
                                  },
                                  order_by='date asc',
                                  limit_page_length=LIMIT)
            balance = 0.0
            for bt in bts:
                bt['amount'] = bt['deposit'] - bt['withdrawal']
                balance += bt['amount']
                bt['balance'] = balance
                bt['disabled'] = (bt['status'] == 'Reconciled')
                if bt['disabled']:
                    bt['open'] = ''
                else:
                    bt['open'] = '*'
            bts.reverse()
            title = "Banktransaktionen für " + event
            tbl = table.Table(bts,
                              keys,
                              headings,
                              title,
                              enable_events=True,
                              max_col_width=120,
                              display_row_numbers=True)
            ix = tbl.display()
            if ix is False:
                break
            comp = company.Company.get_company(settings['-company-'])
            comp.reconciliate(bts[ix])
            show_company_data = True
    elif event in [
            'Abrechnung', 'Quartalsabrechnung', 'Monatsabrechnung', 'Bilanz'
    ]:
        comp = settings['-company-']
        if event == 'Abrechnung':
            consolidated = True
            periodicity = 'Yearly'
        elif event == 'Quartalsabrechnung':
            consolidated = False
            periodicity = 'Quarterly'
        elif event == 'Monatsabrechnung':
            consolidated = False
            periodicity = 'Monthly'
        else:
            consolidated = False
            periodicity = None
        balance = event == 'Bilanz'
        tbl = report.build_report(comp,
                                  consolidated=consolidated,
                                  balance=balance,
                                  periodicity=periodicity)
        # in PDF, always also display balance
        if event != 'Bilanz':
            child = report.build_report(comp, consolidated=False, balance=True)
            tbl.child = child
            tbl.child_title = " mit Bilanz"
        while True:
            ix = tbl.display()
            if ix is False:
                break
            account = tbl.entries[ix]['account']
            tbl1 = report.general_ledger(comp, account)
            if tbl1:
                tbl1.display()
    elif event in ['Chancen', 'Chancen Balkon']:
        tbl = report.opportunities(settings['-company-'],
                                   event == 'Chancen Balkon')
        tbl.display()
    if show_company_data:
        print()
        show_data()
        window.set_title(utils.title())
        show_company_data = False
    return "inner"
Пример #18
0
def menus():
    settings = sg.UserSettings()

    sg.set_options(element_padding=(0, 0))

    # ------ Menu Definition ------ #
    menu_def = [
        [
            '&Einlesen',
            [
                '&Kontoauszug', '&Einkaufsrechnung',
                '&Einkaufsrechnung Balkonmodule'
            ]
        ],
        ['&Bearbeiten', ['Banktransaktionen bearbeiten']],
        [
            '&Anzeigen',
            [
                'Buchungssätze', 'Zahlungen', 'Einkaufsrechnungen',
                'Verkaufsrechnungen', 'Banktransaktionen'
            ]
        ],
        ['Bankkonten', bank.BankAccount.get_baccount_names()],
        [
            'Berichte',
            [
                'Abrechnung', 'Quartalsabrechnung', 'Monatsabrechnung',
                'Bilanz', 'Chancen', 'Chancen Balkon'
            ]
        ],
        ['Bereich', company.Company.all()],
        [
            '&Einstellungen',
            ['Daten neu laden', 'Sofort buchen', '&ERPNext-Server', 'Update']
        ],
        [
            '&Hilfe',
            [
                'Hilfe Server', 'Hilfe Banktransaktionen', 'Hilfe Rechnungen',
                'Hilfe Buchen', 'Über'
            ]
        ],
    ]

    # ------ GUI Defintion ------ #
    layout = [
        [sg.Menu(menu_def, tearoff=False, pad=(200, 1))],
        [sg.Output(size=(130, 30))],
    ]
    company_name = settings['-company-']
    if not company_name:
        company_name = "... <Bitte erst Server-Einstellungen setzen>"
    window = sg.Window(utils.title(),
                       layout,
                       default_element_size=(12, 1),
                       default_button_element_size=(12, 1),
                       finalize=True)

    # ------ Loop & Process button menu choices ------ #
    window.bring_to_front()
    initial_loads()
    show_data()
    while True:
        event, values = window.read()
        try:
            res = event_handler(event, window)
        except Exception as e:
            res = utils.title() + "\n" + str(e) + "\n" + traceback.format_exc()
        if res == "exit":
            window.close()
            return True
        elif res == "outer":
            window.close()
            return False
        elif res != "inner":
            print(res)
Пример #19
0
# TODO

# General libs
import re
import json
import os
import sys

# Tool libs
from utils import run, sanitize
import utils
import conf
from objects import GameMob


utils.title('MOBS')


###
#   GLOBALS
###
ITEMS = []
ITEMS_STR = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for java files...")
#utils.sub("Keywords: %s" % ', '.join(conf.ACHIEVEMENTS_JAVA_KEYWORDS))
for keyword in conf.MOBS_JAVA_KEYWORDS:
    cmd = run("grep '%s' ./classes/*" % keyword)
Пример #20
0
#!/usr/bin/env python

# General libs
import re
import json
import os
import sys

# Tool libs
import utils
import conf
from objects import GameBlock


utils.title('BLOCKS')
if conf.SAVE:
    sys.path.append('../../minecraftcodex')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    from database.models import Block, Texture

###
#   GLOBALS
###
BLOCKS = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for java files...")
#utils.sub("Keywords: %s" % ', '.join(conf.BLOCKS_JAVA_KEYWORDS), end='\n')
for keyword in conf.BLOCKS_JAVA_KEYWORDS:
Пример #21
0
            prediction = cv2.resize(prediction, (500,500))
            cv2.imshow('Frame', frame)
            visualise = frame.copy()
            visualise[:,:,0] = prediction*255.0
            # print(visualise)
            cv2.imshow('Learned', visualise)
            cv2.imshow('prediction', prediction)
            if cv2.waitKey(1) & 0xFF == ord('s'):
                print('Choose option:\n1. Train\n2. No Train')
                input_choice = int(input())
                if input_choice == 1:
                    train = True
                else:
                    train = False



    print("Video stream ended")
    return 1


if __name__ == "__main__" :
    utils.title("Online Traffic Segmentation")
    print("Choose:\n 1. Run(Default)\n 2. Train from Scratch")
    inp = int(input())

    if inp == 2:
        main(train = True)

    main()
Пример #22
0
#!/usr/bin/env python

# General libs
import re
import json
import os
import sys

# Tool libs
from utils import run, sanitize
import utils
import conf
from objects import GameMob


utils.title('MOS')

if conf.SAVE:
    sys.path.append('../../minecraftcodex')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    #from database.models import Achievement

###
#   GLOBALS
###
ITEMS = []
ITEMS_STR = []

###
#   LOOK FOR CORRECT JAVA FILES
###
Пример #23
0
    else:
        TypeError('invalid action: \'%s\' in RSA()')


parser = argparse.ArgumentParser(description="AES and RSA cryptography tools")
parser.add_argument(
    '--debug',
    help="Wait for debugger to attach on port (default is 3000)",
    dest='port',
    default=None,
    const='5768',
    nargs='?',
    type=int)
args = parser.parse_args()

title('Crypto 2.0!')
[print() for i in range(5)]
print('What do you want to do?')
print("1. Encrypt/decrypt a file with AES")
print("2. Generate RSA keys")
print("3. Encrypt/decrypt a file with RSA")
print('4. Sign a file using RSA')
print()
print('Type the number corresponding to the desired action.')
print('Type q, quit or ctrl-c to quit.')
if args.port:
    print('Port is %s' % args.port)
print('_' * utils.get_terminal_size()[0])
print()
try:
    action = input('> ').lower()
Пример #24
0
#!/usr/bin/env python

# General libs
import re
import json
import os
import sys

# Tool libs
import utils
import conf
from objects import GameLanguage


utils.title('LANGUAGES')
if conf.SAVE:
    sys.path.append('../../minecraftcodex')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'local_settings'
    from database.models import Language, LanguageString

###
#   GLOBALS
###
STRINGS = []
LANGUAGES = []
LANGUAGES_STR = []

###
#   LOOK FOR CORRECT JAVA FILES
###
utils.sub("Looking for languages files:")