Ejemplo n.º 1
0
    def setUp(self):
        rid = '60754-10'
        config = ConfigParser()
        p = '/Users/ross/Sandbox/pychron_validation_data.cfg'
        config.read(p)

        signals = [list(map(float, x.split(','))) for x in [config.get('Signals-{}'.format(rid), k)
                        for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']]]

        blanks = [list(map(float, x.split(','))) for x in [config.get('Blanks-{}'.format(rid), k)
                        for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']]]

        irradinfo = [list(map(float, x.split(','))) for x in [config.get('irrad-{}'.format(rid), k) for k in ['k4039', 'k3839', 'ca3937', 'ca3837', 'ca3637', 'cl3638']]]

        j = config.get('irrad-{}'.format(rid), 'j')
        j = [float(x) for x in j.split(',')]
        baselines = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
        backgrounds = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]

        ar37df = config.getfloat('irrad-{}'.format(rid), 'ar37df')
        t = math.log(ar37df) / (constants.lambda_37.nominal_value * 365.25)
        irradinfo.append(t)

        # load results
        r = 'results-{}'.format(rid)
        self.age = config.getfloat(r, 'age')
        self.rad4039 = config.getfloat(r, 'rad4039')
        self.ca37k39 = config.getfloat(r, 'ca37k39')


        self.age_dict = calculate_arar_age(signals, baselines, blanks, backgrounds, j, irradinfo,
                               )
Ejemplo n.º 2
0
    def get_ic_factor(self, det):
        # storing ic_factor in preferences causing issues
        # ic_factor stored in detectors.cfg

        p = os.path.join(paths.spectrometer_dir, 'detectors.cfg')
        # factors=None
        ic = 1, 0
        if os.path.isfile(p):
            c = ConfigParser()
            c.read(p)
            det = det.lower()
            for si in c.sections():
                if si.lower() == det:
                    v, e = 1, 0
                    if c.has_option(si, 'ic_factor'):
                        v = c.getfloat(si, 'ic_factor')
                    if c.has_option(si, 'ic_factor_err'):
                        e = c.getfloat(si, 'ic_factor_err')
                    ic = v, e
                    break
        else:
            self.debug('no detector file {}. cannot retrieve ic_factor'.format(p))

        r = ufloat(*ic)
        return r
Ejemplo n.º 3
0
    def setUp(self):
        rid = '60754-10'
        config = ConfigParser()
        p = '/Users/ross/Sandbox/pychron_validation_data.cfg'
        config.read(p)

        signals = [
            list(map(float, x.split(','))) for x in [
                config.get('Signals-{}'.format(rid), k)
                for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']
            ]
        ]

        blanks = [
            list(map(float, x.split(','))) for x in [
                config.get('Blanks-{}'.format(rid), k)
                for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']
            ]
        ]

        irradinfo = [
            list(map(float, x.split(','))) for x in [
                config.get('irrad-{}'.format(rid), k) for k in
                ['k4039', 'k3839', 'ca3937', 'ca3837', 'ca3637', 'cl3638']
            ]
        ]

        j = config.get('irrad-{}'.format(rid), 'j')
        j = [float(x) for x in j.split(',')]
        baselines = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
        backgrounds = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]

        ar37df = config.getfloat('irrad-{}'.format(rid), 'ar37df')
        t = math.log(ar37df) / (constants.lambda_37.nominal_value * 365.25)
        irradinfo.append(t)

        # load results
        r = 'results-{}'.format(rid)
        self.age = config.getfloat(r, 'age')
        self.rad4039 = config.getfloat(r, 'rad4039')
        self.ca37k39 = config.getfloat(r, 'ca37k39')

        self.age_dict = calculate_arar_age(
            signals,
            baselines,
            blanks,
            backgrounds,
            j,
            irradinfo,
        )
Ejemplo n.º 4
0
    def test_partial_dict(self):
        name = self.make_empty_temp_file()
        to_config_file(name, "section.name", {"port_queue_dt": 1.})

        self.assertTrue(os.path.isfile(name))

        config = ConfigParser()
        config.read(name)
        self.assertTrue(config.has_section("section.name"))
        self.assertSetEqual(_VALID_KEYS, set(config.options("section.name")))
        self.assertEqual(1., config.getfloat("section.name", "port_queue_dt"))
    def test_partial_dict(self):
        name = self.make_empty_temp_file()
        to_config_file(name, "section.name", {"port_queue_dt": 1.})

        self.assertTrue(os.path.isfile(name))

        config = ConfigParser()
        config.read(name)
        self.assertTrue(config.has_section("section.name"))
        self.assertSetEqual(_VALID_KEYS, set(config.options("section.name")))
        self.assertEqual(1., config.getfloat("section.name", "port_queue_dt"))
Ejemplo n.º 6
0
    def __init__(self, config_file):
        config = ConfigParser(allow_no_value=True)
        config.read(config_file)

        self.serial = {
            "port": config.get('device', 'port'),
            "baudrate": config.getint('device', 'baudrate'),
            "parity": config.get('device', 'parity'),
            "bytesize": config.getint('device', 'bytesize'),
            "stopbits": config.getint('device', 'stopbits'),
            "timeout": config.getfloat('device', 'timeout'),
            "interCharTimeout": config.getfloat('device', 'char_delay'),
        }

        self.serial_char_delay = self.serial["interCharTimeout"]

        self.storage_dir = config.get("storage", "dir")

        self.sdb_enabled = config.has_section("simpledb")

        if self.sdb_enabled:
            self.sdb_domain = config.get("simpledb", "domain")

        if config.has_section("aws"):
            self.aws_access_key_id = config.get("aws", "access_key_id")
            self.aws_secret_access_key = config.get("aws", "secret_access_key")
            self.aws_region = config.get("aws", "region")

        self.station_id = config.get("site", "station_id")

        self.mail_enabled = config.has_section("mail")
        if self.mail_enabled:
            self.mail_host = config.get("mail", "host") or "localhost"
            self.mail_port = config.getint(
                "mail", "port") if config.has_option("mail", "port") else 587
            self.mail_username = config.get("mail", "username")
            self.mail_password = config.get("mail", "password")
            self.mail_to = config.get("mail", "to")
Ejemplo n.º 7
0
    def test_ignore_extra_params(self):
        name = self.make_empty_temp_file()
        to_config_file(
            name, "section.name", {"invalid_parameter": "empty", "port_queue_dt": 1.2}
        )

        self.assertTrue(os.path.isfile(name))

        config = ConfigParser()
        config.read(name)
        self.assertTrue(config.has_section("section.name"))
        self.assertSetEqual(_VALID_KEYS, set(config.options("section.name")))
        self.assertEqual(1.2, config.getfloat("section.name", "port_queue_dt"))
        self.assertFalse(config.has_option("section.name", "invalid_parameter"))
    def test_ignore_extra_params(self):
        name = self.make_empty_temp_file()
        to_config_file(name, "section.name", {
            "invalid_parameter": "empty",
            "port_queue_dt": 1.2
        })

        self.assertTrue(os.path.isfile(name))

        config = ConfigParser()
        config.read(name)
        self.assertTrue(config.has_section("section.name"))
        self.assertSetEqual(_VALID_KEYS, set(config.options("section.name")))
        self.assertEqual(1.2, config.getfloat("section.name", "port_queue_dt"))
        self.assertFalse(config.has_option("section.name",
                                           "invalid_parameter"))
Ejemplo n.º 9
0
    def load(self):
        cfp = ConfigParser()
        # p = os.path.join(paths.spectrometer_dir, 'config.cfg')
        p = get_spectrometer_config_path()
        cfp.read(p)
        gs = []
        for section in cfp.sections():
            g = SpectrometerParametersGroup(name=section)
            ps = []
            for pp in cfp.options(section):
                v = cfp.getfloat(section, pp)
                ps.append(Parameter(name=pp, value=v))

            g.parameters = ps
            gs.append(g)

        self.groups = gs
Ejemplo n.º 10
0
    def load(self):
        cfp = ConfigParser()
        # p = os.path.join(paths.spectrometer_dir, 'config.cfg')
        p = get_spectrometer_config_path()
        cfp.read(p)
        gs = []
        for section in cfp.sections():
            g = SpectrometerParametersGroup(name=section)
            ps = []
            for pp in cfp.options(section):
                v = cfp.getfloat(section, pp)
                ps.append(Parameter(name=pp, value=v))

            g.parameters = ps
            gs.append(g)

        self.groups = gs
Ejemplo n.º 11
0
def loadini(struct, configfile):
    """Loads .ini configuration file and stores its values in struct"""

    config_path = os.path.expanduser(configfile)

    config = ConfigParser()
    defaults = {
        'general': {
            'arg_spec': True,
            'auto_display_list': True,
            'color_scheme': 'default',
            'complete_magic_methods': True,
            'autocomplete_mode': default_completion,
            'dedent_after': 1,
            'flush_output': True,
            'highlight_show_source': True,
            'hist_file': '~/.pythonhist',
            'hist_length': 100,
            'hist_duplicates': True,
            'paste_time': 0.02,
            'single_undo_time': 1.0,
            'syntax': True,
            'tab_length': 4,
            'pastebin_confirm': True,
            'pastebin_url': 'https://bpaste.net/json/new',
            'pastebin_show_url': 'https://bpaste.net/show/$paste_id',
            'pastebin_removal_url': 'https://bpaste.net/remove/$removal_id',
            'pastebin_expiry': '1week',
            'pastebin_helper': '',
            'save_append_py': False,
            'editor': os.environ.get('VISUAL', os.environ.get('EDITOR', 'vi')),
            'unicode_box': True
        },
        'keyboard': {
            'backspace': 'C-h',
            'left': 'C-b',
            'right': 'C-f',
            'beginning_of_line': 'C-a',
            'end_of_line': 'C-e',
            'transpose_chars': 'C-t',
            'clear_line': 'C-u',
            'clear_screen': 'C-l',
            'clear_word': 'C-w',
            'cut_to_buffer': 'C-k',
            'delete': 'C-d',
            'down_one_line': 'C-n',
            'exit': '',
            'external_editor': 'F7',
            'edit_config': 'F3',
            'edit_current_block': 'C-x',
            'help': 'F1',
            'last_output': 'F9',
            'copy_clipboard': 'F10',
            'pastebin': 'F8',
            'save': 'C-s',
            'show_source': 'F2',
            'suspend': 'C-z',
            'toggle_file_watch': 'F5',
            'undo': 'C-r',
            'reimport': 'F6',
            'search': 'C-o',
            'up_one_line': 'C-p',
            'yank_from_buffer': 'C-y'},
        'cli': {
            'suggestion_width': 0.8,
            'trim_prompts': False,
        },
        'curtsies': {
            'list_above': False,
            'right_arrow_completion': True,
        }}

    default_keys_to_commands = dict((value, key) for (key, value)
                                    in iteritems(defaults['keyboard']))

    fill_config_with_default_values(config, defaults)
    if not config.read(config_path):
        # No config file. If the user has it in the old place then complain
        if os.path.isfile(os.path.expanduser('~/.bpython.ini')):
            sys.stderr.write("Error: It seems that you have a config file at "
                             "~/.bpython.ini. Please move your config file to "
                             "%s\n" % default_config_path())
            sys.exit(1)

    def get_key_no_doublebind(command):
        default_commands_to_keys = defaults['keyboard']
        requested_key = config.get('keyboard', command)

        try:
            default_command = default_keys_to_commands[requested_key]

            if (default_commands_to_keys[default_command] ==
                    config.get('keyboard', default_command)):
                setattr(struct, '%s_key' % default_command, '')
        except KeyError:
            pass

        return requested_key

    struct.config_path = config_path

    struct.dedent_after = config.getint('general', 'dedent_after')
    struct.tab_length = config.getint('general', 'tab_length')
    struct.auto_display_list = config.getboolean('general',
                                                 'auto_display_list')
    struct.syntax = config.getboolean('general', 'syntax')
    struct.arg_spec = config.getboolean('general', 'arg_spec')
    struct.paste_time = config.getfloat('general', 'paste_time')
    struct.single_undo_time = config.getfloat('general', 'single_undo_time')
    struct.highlight_show_source = config.getboolean('general',
                                                     'highlight_show_source')
    struct.hist_file = config.get('general', 'hist_file')
    struct.editor = config.get('general', 'editor')
    struct.hist_length = config.getint('general', 'hist_length')
    struct.hist_duplicates = config.getboolean('general', 'hist_duplicates')
    struct.flush_output = config.getboolean('general', 'flush_output')

    struct.pastebin_key = get_key_no_doublebind('pastebin')
    struct.copy_clipboard_key = get_key_no_doublebind('copy_clipboard')
    struct.save_key = get_key_no_doublebind('save')
    struct.search_key = get_key_no_doublebind('search')
    struct.show_source_key = get_key_no_doublebind('show_source')
    struct.suspend_key = get_key_no_doublebind('suspend')
    struct.toggle_file_watch_key = get_key_no_doublebind('toggle_file_watch')
    struct.undo_key = get_key_no_doublebind('undo')
    struct.reimport_key = get_key_no_doublebind('reimport')
    struct.up_one_line_key = get_key_no_doublebind('up_one_line')
    struct.down_one_line_key = get_key_no_doublebind('down_one_line')
    struct.cut_to_buffer_key = get_key_no_doublebind('cut_to_buffer')
    struct.yank_from_buffer_key = get_key_no_doublebind('yank_from_buffer')
    struct.clear_word_key = get_key_no_doublebind('clear_word')
    struct.backspace_key = get_key_no_doublebind('backspace')
    struct.clear_line_key = get_key_no_doublebind('clear_line')
    struct.clear_screen_key = get_key_no_doublebind('clear_screen')
    struct.delete_key = get_key_no_doublebind('delete')

    struct.left_key = get_key_no_doublebind('left')
    struct.right_key = get_key_no_doublebind('right')
    struct.end_of_line_key = get_key_no_doublebind('end_of_line')
    struct.beginning_of_line_key = get_key_no_doublebind('beginning_of_line')
    struct.transpose_chars_key = get_key_no_doublebind('transpose_chars')
    struct.clear_line_key = get_key_no_doublebind('clear_line')
    struct.clear_screen_key = get_key_no_doublebind('clear_screen')
    struct.exit_key = get_key_no_doublebind('exit')
    struct.last_output_key = get_key_no_doublebind('last_output')
    struct.edit_config_key = get_key_no_doublebind('edit_config')
    struct.edit_current_block_key = get_key_no_doublebind('edit_current_block')
    struct.external_editor_key = get_key_no_doublebind('external_editor')
    struct.help_key = get_key_no_doublebind('help')

    struct.pastebin_confirm = config.getboolean('general', 'pastebin_confirm')
    struct.pastebin_url = config.get('general', 'pastebin_url')
    struct.pastebin_show_url = config.get('general', 'pastebin_show_url')
    struct.pastebin_removal_url = config.get('general', 'pastebin_removal_url')
    struct.pastebin_expiry = config.get('general', 'pastebin_expiry')
    struct.pastebin_helper = config.get('general', 'pastebin_helper')

    struct.cli_suggestion_width = config.getfloat('cli',
                                                  'suggestion_width')
    struct.cli_trim_prompts = config.getboolean('cli',
                                                'trim_prompts')

    struct.complete_magic_methods = config.getboolean('general',
                                                      'complete_magic_methods')
    struct.autocomplete_mode = config.get('general', 'autocomplete_mode')
    struct.save_append_py = config.getboolean('general', 'save_append_py')

    struct.curtsies_list_above = config.getboolean('curtsies', 'list_above')
    struct.curtsies_right_arrow_completion = \
        config.getboolean('curtsies', 'right_arrow_completion')

    color_scheme_name = config.get('general', 'color_scheme')

    default_colors = {
        'keyword': 'y',
        'name': 'c',
        'comment': 'b',
        'string': 'm',
        'error': 'r',
        'number': 'G',
        'operator': 'Y',
        'punctuation': 'y',
        'token': 'C',
        'background': 'd',
        'output': 'w',
        'main': 'c',
        'paren': 'R',
        'prompt': 'c',
        'prompt_more': 'g',
        'right_arrow_suggestion': 'K',
    }

    if color_scheme_name == 'default':
        struct.color_scheme = default_colors
    else:
        struct.color_scheme = dict()

        theme_filename = color_scheme_name + '.theme'
        path = os.path.expanduser(os.path.join(get_config_home(),
                                               theme_filename))
        try:
            load_theme(struct, path, struct.color_scheme, default_colors)
        except EnvironmentError:
            sys.stderr.write("Could not load theme '%s'.\n" %
                             (color_scheme_name, ))
            sys.exit(1)

    # checks for valid key configuration this part still sucks
    for key in (struct.pastebin_key, struct.save_key):
        key_dispatch[key]

    # expand path of history file
    struct.hist_file = os.path.expanduser(struct.hist_file)

    # verify completion mode
    if struct.autocomplete_mode not in bpython.autocomplete.ALL_MODES:
        struct.autocomplete_mode = default_completion

    # set box drawing characters
    if config.getboolean('general', 'unicode_box') and supports_box_chars():
        struct.left_border = u'│'
        struct.right_border = u'│'
        struct.top_border = u'─'
        struct.bottom_border = u'─'
        struct.left_bottom_corner = u'└'
        struct.right_bottom_corner = u'┘'
        struct.left_top_corner = u'┌'
        struct.right_top_corner = u'┐'
    else:
        struct.left_border = u'|'
        struct.right_border = u'|'
        struct.top_border = u'-'
        struct.bottom_border = u'-'
        struct.left_bottom_corner = u'+'
        struct.right_bottom_corner = u'+'
        struct.left_top_corner = u'+'
        struct.right_top_corner = u'+'
Ejemplo n.º 12
0
def loadini(struct, configfile):
    """Loads .ini configuration file and stores its values in struct"""

    config_path = os.path.expanduser(configfile)

    config = ConfigParser()
    defaults = {
        "general": {
            "arg_spec": True,
            "auto_display_list": True,
            "autocomplete_mode": default_completion,
            "color_scheme": "default",
            "complete_magic_methods": True,
            "dedent_after": 1,
            "default_autoreload": False,
            "editor": os.environ.get("VISUAL", os.environ.get("EDITOR", "vi")),
            "flush_output": True,
            "highlight_show_source": True,
            "hist_duplicates": True,
            "hist_file": "~/.pythonhist",
            "hist_length": 1000,
            "paste_time": 0.02,
            "pastebin_confirm": True,
            "pastebin_expiry": "1week",
            "pastebin_helper": "",
            "pastebin_url": "https://bpaste.net",
            "save_append_py": False,
            "single_undo_time": 1.0,
            "syntax": True,
            "tab_length": 4,
            "unicode_box": True,
        },
        "keyboard": {
            "backspace": "C-h",
            "beginning_of_line": "C-a",
            "clear_line": "C-u",
            "clear_screen": "C-l",
            "clear_word": "C-w",
            "copy_clipboard": "F10",
            "cut_to_buffer": "C-k",
            "delete": "C-d",
            "down_one_line": "C-n",
            "edit_config": "F3",
            "edit_current_block": "C-x",
            "end_of_line": "C-e",
            "exit": "",
            "external_editor": "F7",
            "help": "F1",
            "incremental_search": "M-s",
            "last_output": "F9",
            "left": "C-b",
            "pastebin": "F8",
            "reimport": "F6",
            "reverse_incremental_search": "M-r",
            "right": "C-f",
            "save": "C-s",
            "search": "C-o",
            "show_source": "F2",
            "suspend": "C-z",
            "toggle_file_watch": "F5",
            "transpose_chars": "C-t",
            "undo": "C-r",
            "up_one_line": "C-p",
            "yank_from_buffer": "C-y",
        },
        "cli": {
            "suggestion_width": 0.8,
            "trim_prompts": False,
        },
        "curtsies": {
            "list_above": False,
            "right_arrow_completion": True,
        },
    }

    default_keys_to_commands = dict(
        (value, key) for (key, value) in iteritems(defaults["keyboard"]))

    fill_config_with_default_values(config, defaults)
    try:
        if not config.read(config_path):
            # No config file. If the user has it in the old place then complain
            if os.path.isfile(os.path.expanduser("~/.bpython.ini")):
                sys.stderr.write(
                    "Error: It seems that you have a config file at "
                    "~/.bpython.ini. Please move your config file to "
                    "%s\n" % default_config_path())
                sys.exit(1)
    except UnicodeDecodeError as e:
        sys.stderr.write(
            "Error: Unable to parse config file at '{}' due to an "
            "encoding issue. Please make sure to fix the encoding "
            "of the file or remove it and then try again.\n".format(
                config_path))
        sys.exit(1)

    def get_key_no_doublebind(command):
        default_commands_to_keys = defaults["keyboard"]
        requested_key = config.get("keyboard", command)

        try:
            default_command = default_keys_to_commands[requested_key]

            if default_commands_to_keys[default_command] == config.get(
                    "keyboard", default_command):
                setattr(struct, "%s_key" % default_command, "")
        except KeyError:
            pass

        return requested_key

    struct.config_path = config_path

    struct.dedent_after = config.getint("general", "dedent_after")
    struct.tab_length = config.getint("general", "tab_length")
    struct.auto_display_list = config.getboolean("general",
                                                 "auto_display_list")
    struct.syntax = config.getboolean("general", "syntax")
    struct.arg_spec = config.getboolean("general", "arg_spec")
    struct.paste_time = config.getfloat("general", "paste_time")
    struct.single_undo_time = config.getfloat("general", "single_undo_time")
    struct.highlight_show_source = config.getboolean("general",
                                                     "highlight_show_source")
    struct.hist_file = config.get("general", "hist_file")
    struct.editor = config.get("general", "editor")
    struct.hist_length = config.getint("general", "hist_length")
    struct.hist_duplicates = config.getboolean("general", "hist_duplicates")
    struct.flush_output = config.getboolean("general", "flush_output")
    struct.default_autoreload = config.getboolean("general",
                                                  "default_autoreload")

    struct.pastebin_key = get_key_no_doublebind("pastebin")
    struct.copy_clipboard_key = get_key_no_doublebind("copy_clipboard")
    struct.save_key = get_key_no_doublebind("save")
    struct.search_key = get_key_no_doublebind("search")
    struct.show_source_key = get_key_no_doublebind("show_source")
    struct.suspend_key = get_key_no_doublebind("suspend")
    struct.toggle_file_watch_key = get_key_no_doublebind("toggle_file_watch")
    struct.undo_key = get_key_no_doublebind("undo")
    struct.reimport_key = get_key_no_doublebind("reimport")
    struct.reverse_incremental_search_key = get_key_no_doublebind(
        "reverse_incremental_search")
    struct.incremental_search_key = get_key_no_doublebind("incremental_search")
    struct.up_one_line_key = get_key_no_doublebind("up_one_line")
    struct.down_one_line_key = get_key_no_doublebind("down_one_line")
    struct.cut_to_buffer_key = get_key_no_doublebind("cut_to_buffer")
    struct.yank_from_buffer_key = get_key_no_doublebind("yank_from_buffer")
    struct.clear_word_key = get_key_no_doublebind("clear_word")
    struct.backspace_key = get_key_no_doublebind("backspace")
    struct.clear_line_key = get_key_no_doublebind("clear_line")
    struct.clear_screen_key = get_key_no_doublebind("clear_screen")
    struct.delete_key = get_key_no_doublebind("delete")

    struct.left_key = get_key_no_doublebind("left")
    struct.right_key = get_key_no_doublebind("right")
    struct.end_of_line_key = get_key_no_doublebind("end_of_line")
    struct.beginning_of_line_key = get_key_no_doublebind("beginning_of_line")
    struct.transpose_chars_key = get_key_no_doublebind("transpose_chars")
    struct.exit_key = get_key_no_doublebind("exit")
    struct.last_output_key = get_key_no_doublebind("last_output")
    struct.edit_config_key = get_key_no_doublebind("edit_config")
    struct.edit_current_block_key = get_key_no_doublebind("edit_current_block")
    struct.external_editor_key = get_key_no_doublebind("external_editor")
    struct.help_key = get_key_no_doublebind("help")

    struct.pastebin_confirm = config.getboolean("general", "pastebin_confirm")
    struct.pastebin_url = config.get("general", "pastebin_url")
    struct.pastebin_expiry = config.get("general", "pastebin_expiry")
    struct.pastebin_helper = config.get("general", "pastebin_helper")

    struct.cli_suggestion_width = config.getfloat("cli", "suggestion_width")
    struct.cli_trim_prompts = config.getboolean("cli", "trim_prompts")

    struct.complete_magic_methods = config.getboolean(
        "general", "complete_magic_methods")
    struct.autocomplete_mode = config.get("general", "autocomplete_mode")
    struct.save_append_py = config.getboolean("general", "save_append_py")

    struct.curtsies_list_above = config.getboolean("curtsies", "list_above")
    struct.curtsies_right_arrow_completion = config.getboolean(
        "curtsies", "right_arrow_completion")

    color_scheme_name = config.get("general", "color_scheme")

    default_colors = {
        "keyword": "y",
        "name": "c",
        "comment": "b",
        "string": "m",
        "error": "r",
        "number": "G",
        "operator": "Y",
        "punctuation": "y",
        "token": "C",
        "background": "d",
        "output": "w",
        "main": "c",
        "paren": "R",
        "prompt": "c",
        "prompt_more": "g",
        "right_arrow_suggestion": "K",
    }

    if color_scheme_name == "default":
        struct.color_scheme = default_colors
    else:
        struct.color_scheme = dict()

        theme_filename = color_scheme_name + ".theme"
        path = os.path.expanduser(
            os.path.join(get_config_home(), theme_filename))
        try:
            load_theme(struct, path, struct.color_scheme, default_colors)
        except EnvironmentError:
            sys.stderr.write("Could not load theme '%s'.\n" %
                             (color_scheme_name, ))
            sys.exit(1)

    # expand path of history file
    struct.hist_file = os.path.expanduser(struct.hist_file)

    # verify completion mode
    if struct.autocomplete_mode not in ALL_MODES:
        struct.autocomplete_mode = default_completion

    # set box drawing characters
    if config.getboolean("general", "unicode_box") and supports_box_chars():
        struct.left_border = "│"
        struct.right_border = "│"
        struct.top_border = "─"
        struct.bottom_border = "─"
        struct.left_bottom_corner = "└"
        struct.right_bottom_corner = "┘"
        struct.left_top_corner = "┌"
        struct.right_top_corner = "┐"
    else:
        struct.left_border = "|"
        struct.right_border = "|"
        struct.top_border = "-"
        struct.bottom_border = "-"
        struct.left_bottom_corner = "+"
        struct.right_bottom_corner = "+"
        struct.left_top_corner = "+"
        struct.right_top_corner = "+"
Ejemplo n.º 13
0
def read_config(filenames=SEARCH_PATH):
    """Attempt to read local configuration files to determine spalloc client
    settings.

    Parameters
    ----------
    filenames : [str, ...]
        Filenames to attempt to read. Later config file have higher priority.

    Returns
    -------
    dict
        The configuration loaded.
    """
    parser = ConfigParser()

    # Set default config values (NB: No read_dict in Python 2.7)
    parser.add_section("spalloc")
    for key, value in iteritems({"port": "22244",
                                 "keepalive": "60.0",
                                 "reconnect_delay": "5.0",
                                 "timeout": "5.0",
                                 "machine": "None",
                                 "tags": "None",
                                 "min_ratio": "0.333",
                                 "max_dead_boards": "0",
                                 "max_dead_links": "None",
                                 "require_torus": "False"}):
        parser.set("spalloc", key, value)

    # Attempt to read from each possible file location in turn
    for filename in filenames:
        try:
            with open(filename, "r") as f:
                parser.readfp(f, filename)
        except (IOError, OSError):
            # File did not exist, keep trying
            pass

    cfg = {}

    try:
        cfg["hostname"] = parser.get("spalloc", "hostname")
    except NoOptionError:
        cfg["hostname"] = None

    cfg["port"] = parser.getint("spalloc", "port")

    try:
        cfg["owner"] = parser.get("spalloc", "owner")
    except NoOptionError:
        cfg["owner"] = None

    if parser.get("spalloc", "keepalive") == "None":
        cfg["keepalive"] = None
    else:
        cfg["keepalive"] = parser.getfloat("spalloc", "keepalive")

    cfg["reconnect_delay"] = parser.getfloat("spalloc", "reconnect_delay")

    if parser.get("spalloc", "timeout") == "None":
        cfg["timeout"] = None
    else:
        cfg["timeout"] = parser.getfloat("spalloc", "timeout")

    if parser.get("spalloc", "machine") == "None":
        cfg["machine"] = None
    else:
        cfg["machine"] = parser.get("spalloc", "machine")

    if parser.get("spalloc", "tags") == "None":
        cfg["tags"] = None
    else:
        cfg["tags"] = list(map(str.strip,
                               parser.get("spalloc", "tags").split(",")))

    cfg["min_ratio"] = parser.getfloat("spalloc", "min_ratio")

    if parser.get("spalloc", "max_dead_boards") == "None":
        cfg["max_dead_boards"] = None
    else:
        cfg["max_dead_boards"] = parser.getint("spalloc", "max_dead_boards")

    if parser.get("spalloc", "max_dead_links") == "None":
        cfg["max_dead_links"] = None
    else:
        cfg["max_dead_links"] = parser.getint("spalloc", "max_dead_links")

    cfg["require_torus"] = parser.getboolean("spalloc", "require_torus")

    return cfg
def loadini(struct, configfile):
    """Loads .ini configuration file and stores its values in struct"""

    config_path = os.path.expanduser(configfile)

    config = ConfigParser()
    defaults = {
        'general': {
            'arg_spec': True,
            'auto_display_list': True,
            'autocomplete_mode': default_completion,
            'color_scheme': 'default',
            'complete_magic_methods': True,
            'dedent_after': 1,
            'editor': os.environ.get('VISUAL', os.environ.get('EDITOR', 'vi')),
            'flush_output': True,
            'highlight_show_source': True,
            'hist_duplicates': True,
            'hist_file': '~/.pythonhist',
            'hist_length': 100,
            'paste_time': 0.02,
            'pastebin_confirm': True,
            'pastebin_expiry': '1week',
            'pastebin_helper': '',
            'pastebin_removal_url': 'https://bpaste.net/remove/$removal_id',
            'pastebin_show_url': 'https://bpaste.net/show/$paste_id',
            'pastebin_url': 'https://bpaste.net/json/new',
            'save_append_py': False,
            'single_undo_time': 1.0,
            'syntax': True,
            'tab_length': 4,
            'unicode_box': True
        },
        'keyboard': {
            'backspace': 'C-h',
            'beginning_of_line': 'C-a',
            'clear_line': 'C-u',
            'clear_screen': 'C-l',
            'clear_word': 'C-w',
            'copy_clipboard': 'F10',
            'cut_to_buffer': 'C-k',
            'delete': 'C-d',
            'down_one_line': 'C-n',
            'edit_config': 'F3',
            'edit_current_block': 'C-x',
            'end_of_line': 'C-e',
            'exit': '',
            'external_editor': 'F7',
            'help': 'F1',
            'last_output': 'F9',
            'left': 'C-b',
            'pastebin': 'F8',
            'reimport': 'F6',
            'right': 'C-f',
            'save': 'C-s',
            'search': 'C-o',
            'show_source': 'F2',
            'suspend': 'C-z',
            'toggle_file_watch': 'F5',
            'transpose_chars': 'C-t',
            'undo': 'C-r',
            'up_one_line': 'C-p',
            'yank_from_buffer': 'C-y'
        },
        'cli': {
            'suggestion_width': 0.8,
            'trim_prompts': False,
        },
        'curtsies': {
            'list_above': False,
            'right_arrow_completion': True,
        }}

    default_keys_to_commands = dict((value, key) for (key, value)
                                    in iteritems(defaults['keyboard']))

    fill_config_with_default_values(config, defaults)
    if not config.read(config_path):
        # No config file. If the user has it in the old place then complain
        if os.path.isfile(os.path.expanduser('~/.bpython.ini')):
            sys.stderr.write("Error: It seems that you have a config file at "
                             "~/.bpython.ini. Please move your config file to "
                             "%s\n" % default_config_path())
            sys.exit(1)

    def get_key_no_doublebind(command):
        default_commands_to_keys = defaults['keyboard']
        requested_key = config.get('keyboard', command)

        try:
            default_command = default_keys_to_commands[requested_key]

            if (default_commands_to_keys[default_command] ==
                    config.get('keyboard', default_command)):
                setattr(struct, '%s_key' % default_command, '')
        except KeyError:
            pass

        return requested_key

    struct.config_path = config_path

    struct.dedent_after = config.getint('general', 'dedent_after')
    struct.tab_length = config.getint('general', 'tab_length')
    struct.auto_display_list = config.getboolean('general',
                                                 'auto_display_list')
    struct.syntax = config.getboolean('general', 'syntax')
    struct.arg_spec = config.getboolean('general', 'arg_spec')
    struct.paste_time = config.getfloat('general', 'paste_time')
    struct.single_undo_time = config.getfloat('general', 'single_undo_time')
    struct.highlight_show_source = config.getboolean('general',
                                                     'highlight_show_source')
    struct.hist_file = config.get('general', 'hist_file')
    struct.editor = config.get('general', 'editor')
    struct.hist_length = config.getint('general', 'hist_length')
    struct.hist_duplicates = config.getboolean('general', 'hist_duplicates')
    struct.flush_output = config.getboolean('general', 'flush_output')

    struct.pastebin_key = get_key_no_doublebind('pastebin')
    struct.copy_clipboard_key = get_key_no_doublebind('copy_clipboard')
    struct.save_key = get_key_no_doublebind('save')
    struct.search_key = get_key_no_doublebind('search')
    struct.show_source_key = get_key_no_doublebind('show_source')
    struct.suspend_key = get_key_no_doublebind('suspend')
    struct.toggle_file_watch_key = get_key_no_doublebind('toggle_file_watch')
    struct.undo_key = get_key_no_doublebind('undo')
    struct.reimport_key = get_key_no_doublebind('reimport')
    struct.up_one_line_key = get_key_no_doublebind('up_one_line')
    struct.down_one_line_key = get_key_no_doublebind('down_one_line')
    struct.cut_to_buffer_key = get_key_no_doublebind('cut_to_buffer')
    struct.yank_from_buffer_key = get_key_no_doublebind('yank_from_buffer')
    struct.clear_word_key = get_key_no_doublebind('clear_word')
    struct.backspace_key = get_key_no_doublebind('backspace')
    struct.clear_line_key = get_key_no_doublebind('clear_line')
    struct.clear_screen_key = get_key_no_doublebind('clear_screen')
    struct.delete_key = get_key_no_doublebind('delete')

    struct.left_key = get_key_no_doublebind('left')
    struct.right_key = get_key_no_doublebind('right')
    struct.end_of_line_key = get_key_no_doublebind('end_of_line')
    struct.beginning_of_line_key = get_key_no_doublebind('beginning_of_line')
    struct.transpose_chars_key = get_key_no_doublebind('transpose_chars')
    struct.clear_line_key = get_key_no_doublebind('clear_line')
    struct.clear_screen_key = get_key_no_doublebind('clear_screen')
    struct.exit_key = get_key_no_doublebind('exit')
    struct.last_output_key = get_key_no_doublebind('last_output')
    struct.edit_config_key = get_key_no_doublebind('edit_config')
    struct.edit_current_block_key = get_key_no_doublebind('edit_current_block')
    struct.external_editor_key = get_key_no_doublebind('external_editor')
    struct.help_key = get_key_no_doublebind('help')

    struct.pastebin_confirm = config.getboolean('general', 'pastebin_confirm')
    struct.pastebin_url = config.get('general', 'pastebin_url')
    struct.pastebin_show_url = config.get('general', 'pastebin_show_url')
    struct.pastebin_removal_url = config.get('general', 'pastebin_removal_url')
    struct.pastebin_expiry = config.get('general', 'pastebin_expiry')
    struct.pastebin_helper = config.get('general', 'pastebin_helper')

    struct.cli_suggestion_width = config.getfloat('cli',
                                                  'suggestion_width')
    struct.cli_trim_prompts = config.getboolean('cli',
                                                'trim_prompts')

    struct.complete_magic_methods = config.getboolean('general',
                                                      'complete_magic_methods')
    struct.autocomplete_mode = config.get('general', 'autocomplete_mode')
    struct.save_append_py = config.getboolean('general', 'save_append_py')

    struct.curtsies_list_above = config.getboolean('curtsies', 'list_above')
    struct.curtsies_right_arrow_completion = \
        config.getboolean('curtsies', 'right_arrow_completion')

    color_scheme_name = config.get('general', 'color_scheme')

    default_colors = {
        'keyword': 'y',
        'name': 'c',
        'comment': 'b',
        'string': 'm',
        'error': 'r',
        'number': 'G',
        'operator': 'Y',
        'punctuation': 'y',
        'token': 'C',
        'background': 'd',
        'output': 'w',
        'main': 'c',
        'paren': 'R',
        'prompt': 'c',
        'prompt_more': 'g',
        'right_arrow_suggestion': 'K',
    }

    if color_scheme_name == 'default':
        struct.color_scheme = default_colors
    else:
        struct.color_scheme = dict()

        theme_filename = color_scheme_name + '.theme'
        path = os.path.expanduser(os.path.join(get_config_home(),
                                               theme_filename))
        try:
            load_theme(struct, path, struct.color_scheme, default_colors)
        except EnvironmentError:
            sys.stderr.write("Could not load theme '%s'.\n" %
                             (color_scheme_name, ))
            sys.exit(1)

    # checks for valid key configuration this part still sucks
    for key in (struct.pastebin_key, struct.save_key):
        key_dispatch[key]

    # expand path of history file
    struct.hist_file = os.path.expanduser(struct.hist_file)

    # verify completion mode
    if struct.autocomplete_mode not in bpython.autocomplete.ALL_MODES:
        struct.autocomplete_mode = default_completion

    # set box drawing characters
    if config.getboolean('general', 'unicode_box') and supports_box_chars():
        struct.left_border = u'│'
        struct.right_border = u'│'
        struct.top_border = u'─'
        struct.bottom_border = u'─'
        struct.left_bottom_corner = u'└'
        struct.right_bottom_corner = u'┘'
        struct.left_top_corner = u'┌'
        struct.right_top_corner = u'┐'
    else:
        struct.left_border = u'|'
        struct.right_border = u'|'
        struct.top_border = u'-'
        struct.bottom_border = u'-'
        struct.left_bottom_corner = u'+'
        struct.right_bottom_corner = u'+'
        struct.left_top_corner = u'+'
        struct.right_top_corner = u'+'
Ejemplo n.º 15
0
    def auth(self, username, password, nat=None, mtu=None, callback=None):
        """
        Login to AniDB UDP API

        parameters:
        username - your anidb username
        password - your anidb password
        nat     - if this is 1, response will have "address" in attributes with your "ip:port" (default:0)
        mtu     - maximum transmission unit (max packet size) (default: 1400)

        """

        # disabled, this code doesn't work with renovations
        # logging.debug("ok1")
        # if self.keepAlive:
        #     logging.debug("ok2")
        #     self._username = username
        #     self._password = password
        #     if self.is_alive() == False:
        #         logging.debug("You wanted to keep this thing alive!")
        #         if self._iamALIVE == False:
        #             logging.info("Starting thread now...")
        #             self.start()
        #             self._iamALIVE = True
        #         else:
        #             logging.info("not starting thread seems like it is already running. this must be a _reAuthenticate")
        config = ConfigParser()
        config.read(self.SessionFile)
        needauth = False

        try:
            if config.getboolean('DEFAULT', 'loggedin'):
                self.lastCommandTime = config.getfloat('DEFAULT', 'lastcommandtime')
                timeelapsed = time() - self.lastCommandTime
                timeoutduration = timedelta(minutes=30).seconds
                if timeelapsed < timeoutduration:
                    # we are logged in and within timeout so set up session key and assume valid
                    self.link.session = config.get('DEFAULT', 'sessionkey')
                else:
                    needauth = True
            else:
                needauth = True
        except:
            needauth = True

        if needauth:
            self.lastAuth = time()
            logging.debug('No valid session, so authenticating')
            try:
                self.handle(AuthCommand(username, password, 3, self.clientname, self.clientver, nat, 1, 'utf8', mtu), callback)
            except Exception as e:
                logging.debug('Auth command with exception %s', e)
                # we force a config file with logged out to ensure a known state if an exception occurs, forcing us to log in again
                config['DEFAULT'] = {'loggedin': 'yes', 'sessionkey': self.link.session, 'exception': str(e),
                                     'lastcommandtime': repr(time())}
                with open(self.SessionFile, 'w') as configfile:
                    config.write(configfile)
                return e
            logging.debug('Successfully authenticated and recording session details')
            config['DEFAULT'] = {'loggedin': 'yes', 'sessionkey': self.link.session, 'lastcommandtime': repr(time())}
            with open(self.SessionFile, 'w') as configfile:
                config.write(configfile)
        return