Пример #1
0
def read_config(config_file=CONFIG_FILE):
    try:
        p = ConfigParser.SafeConfigParser()
    except AttributeError:
        p = ConfigParser()
    p.read(config_file)
    return p
    def load_conf(self, filename):
        config = ConfigParser.SafeConfigParser()
        try:
            config.read(filename)
            sections = config.sections()
            if len(sections):
                device = DeviceGPS()
                device.name = sections[0]
                device.type = config.getint(sections[0], 'type')
                device.resource = config.get(sections[0], 'resource')
                if device.type == DeviceGPS.NMEA_SERIAL:
                    if config.has_option(sections[0], 'baud'):
                        device.baud = config.getint(sections[0], 'baud')
                    if config.has_option(sections[0], 'bits'):
                        device.bytes = config.getint(sections[0], 'bits')
                    if config.has_option(sections[0], 'parity'):
                        device.parity = config.get(sections[0], 'parity')
                    if config.has_option(sections[0], 'stops'):
                        device.stops = config.getint(sections[0], 'stops')
                    if config.has_option(sections[0], 'soft'):
                        device.soft = config.getboolean(sections[0], 'soft')

                self.devicesGps.append(device)
                return self.__check_conf_serial(device)

        except ConfigParser.Error as e1:
            return str(e1)
        except ValueError as e2:
            return str(e2)
Пример #3
0
def autoconfigure():
    ''' Perform timing experiments on current hardware to assess which
         of various implementations is the fastest for each key routine
    '''
    config = ConfigParser.SafeConfigParser()
    config.optionxform = str
    config.read(cfgfilepath)
    methodNames = ['inplaceExpAndNormalizeRows', 'calcRlogR', 'calcRlogRdotv']
    for mName in methodNames:
        if mName == 'inplaceExpAndNormalizeRows':
            expectedGainFactor = _runTiming_inplaceExpAndNormalizeRows()
        elif mName == 'calcRlogR':
            expectedGainFactor = runTiming_calcRlogR()
        elif mName == 'calcRlogRdotv':
            expectedGainFactor = runTiming_calcRlogRdotv()
        print(mName, end=' ')
        if expectedGainFactor > 1.05:
            config.set('LibraryPrefs', mName, 'numexpr')
            print("numexpr preferred: %.2f X faster" % (expectedGainFactor))
        else:
            config.set('LibraryPrefs', mName, 'numpy')
            print("numpy preferred: %.2f X faster" % (expectedGainFactor))
        with open(cfgfilepath, 'w') as f:
            config.write(f)
    LoadConfig()
Пример #4
0
def parse_config():
    conf_parser = argparse.ArgumentParser(description=__doc__, add_help=False,
                                          formatter_class=argparse.RawDescriptionHelpFormatter)

    conf_parser.add_argument("-c", "--config",
                             help="""Config file with defaults. Command line parameters will override those given in the config file. Options to selfspy goes in the "[Defaults]" section, followed by [argument]=[value] on each line. Options specific to selfstats should be in the "[Selfstats]" section, though "password" and "data-dir" are still read from "[Defaults]".""", metavar="FILE")
    args, remaining_argv = conf_parser.parse_known_args()

    defaults = {}
    if args.config:
        if not os.path.exists(args.config):
            raise  EnvironmentError("Config file %s doesn't exist." % args.config)
        config = ConfigParser.SafeConfigParser()
        config.read([args.config])
        defaults = dict(config.items('Defaults') + config.items("Selfstats"))

    parser = argparse.ArgumentParser(description="""Calculate statistics on selfspy data. Per default it will show non-text information that matches the filter. Adding '-s' means also show text. Adding any of the summary options will show those summaries over the given filter instead of the listing. Multiple summary options can be given to print(several summaries over the same filter. If you give arguments that need to access text / keystrokes, you will be asked for the decryption password.""", epilog="""See the README file or http://gurgeh.github.com/selfspy for examples.""", parents=[conf_parser])
    parser.set_defaults(**defaults)
    parser.add_argument('-p', '--password', help='Decryption password. Only needed if selfstats needs to access text / keystrokes data. If your database in not encrypted, specify -p="" here. If you don\'t specify a password in the command line arguments or in a config file, and the statistics you ask for require a password, a dialog will pop up asking for the password. If you give your password on the command line, remember that it will most likely be stored in plain text in your shell history.')
    parser.add_argument('-d', '--data-dir', help='Data directory for selfspy, where the database is stored. Remember that Selfspy must have read/write access. Default is %s' % cfg.DATA_DIR, default=cfg.DATA_DIR)

    parser.add_argument('-s', '--showtext', action='store_true', help='Also show the text column. This switch is ignored if at least one of the summary options are used. Requires password.')

    parser.add_argument('-D', '--date', nargs='+', help='Which date to start the listing or summarizing from. If only one argument is given (--date 13) it is interpreted as the closest date in the past on that day. If two arguments are given (--date 03 13) it is interpreted as the closest date in the past on that month and that day, in that order. If three arguments are given (--date 2012 03 13) it is interpreted as YYYY MM DD')
    parser.add_argument('-C', '--clock', type=str, help='Time to start the listing or summarizing from. Given in 24 hour format as --clock 13:25. If no --date is given, interpret the time as today if that results in sometimes in the past, otherwise as yesterday.')

    parser.add_argument('-i', '--id', type=int, help='Which row ID to start the listing or summarizing from. If --date and/or --clock is given, this option is ignored.')

    parser.add_argument('-b', '--back', nargs='+', type=str, help='--back <period> [<unit>] Start the listing or summary this much back in time. Use this as an alternative to --date, --clock and --id. If any of those are given, this option is ignored. <unit> is either "s" (seconds), "m" (minutes), "h" (hours), "d" (days) or "w" (weeks). If no unit is given, it is assumed to be hours.')

    parser.add_argument('-l', '--limit', help='--limit <period> [<unit>]. If the start is given in --date/--clock, the limit is a time period given by <unit>. <unit> is either "s" (seconds), "m" (minutes), "h" (hours), "d" (days) or "w" (weeks). If no unit is given, it is assumed to be hours. If the start is given with --id, limit has no unit and means that the maximum row ID is --id + --limit.', nargs='+', type=str)

    parser.add_argument('-m', '--min-keys', type=int, metavar='nr', help='Only allow entries with at least <nr> keystrokes')

    parser.add_argument('-T', '--title', type=str, metavar='regexp', help='Only allow entries where a search for this <regexp> in the window title matches something. All regular expressions are case insensitive.')
    parser.add_argument('-P', '--process', type=str, metavar='regexp', help='Only allow entries where a search for this <regexp> in the process matches something.')
    parser.add_argument('-B', '--body', type=str, metavar='regexp', help='Only allow entries where a search for this <regexp> in the body matches something. Do not use this filter when summarizing ratios or activity, as it has no effect on mouse clicks. Requires password.')

    parser.add_argument('--clicks', action='store_true', help='Summarize number of mouse button clicks for all buttons.')

    parser.add_argument('--key-freqs', action='store_true', help='Summarize a table of absolute and relative number of keystrokes for each used key during the time period. Requires password.')

    parser.add_argument('--human-readable', action='store_true', help='This modifies the --body entry and honors backspace.')
    parser.add_argument('--active', type=int, metavar='seconds', nargs='?', const=ACTIVE_SECONDS, help='Summarize total time spent active during the period. The optional argument gives how many seconds after each mouse click (including scroll up or down) or keystroke that you are considered active. Default is %d.' % ACTIVE_SECONDS)

    parser.add_argument('--ratios', type=int, metavar='seconds', nargs='?', const=ACTIVE_SECONDS, help='Summarize the ratio between different metrics in the given period. "Clicks" will not include up or down scrolling. The optional argument is the "seconds" cutoff for calculating active use, like --active.')

    parser.add_argument('--periods', type=int, metavar='seconds', nargs='?', const=ACTIVE_SECONDS, help='List active time periods. Optional argument works same as for --active.')

    parser.add_argument('--pactive', type=int, metavar='seconds', nargs='?', const=ACTIVE_SECONDS, help='List processes, sorted by time spent active in them. Optional argument works same as for --active.')
    parser.add_argument('--tactive', type=int, metavar='seconds', nargs='?', const=ACTIVE_SECONDS, help='List window titles, sorted by time spent active in them. Optional argument works same as for --active.')

    parser.add_argument('--pkeys', action='store_true', help='List processes sorted by number of keystrokes.')
    parser.add_argument('--tkeys', action='store_true', help='List window titles sorted by number of keystrokes.')

    return parser.parse_args()
Пример #5
0
    def __init__(self, config_path):
        """Create an instance of the main video looper application class. Must
        pass path to a valid video looper ini configuration file.
        """

        self.hostname = socket.gethostname()
        self.ip = socket.gethostbyname(self.hostname)
        print("Your Computer Name is:" + self.hostname)
        print("Your Computer IP Address is:" + self.ip)

        # Load the configuration.
        self._config = ConfigParser.SafeConfigParser()
        if len(self._config.read(config_path)) == 0:
            raise RuntimeError(
                'Failed to find configuration file at {0}, is the application properly installed?'
                .format(config_path))
        self._console_output = self._config.getboolean('video_looper',
                                                       'console_output')
        self._interrupt_on_new = self._config.getboolean(
            'video_looper', 'interrupt_on_new')
        self._waiting_to_build_playlist = True
        # Load configured video player and file reader modules.
        self._player = self._load_player()
        self._reader = self._load_file_reader()
        # Load other configuration values.
        self._osd = self._config.getboolean('video_looper', 'osd')
        self._is_random = self._config.getboolean('video_looper', 'is_random')
        # Parse string of 3 comma separated values like "255, 255, 255" into
        # list of ints for colors.
        self._bgcolor = map(
            int,
            self._config.get('video_looper', 'bgcolor').translate(None,
                                                                  ',').split())
        self._fgcolor = map(
            int,
            self._config.get('video_looper', 'fgcolor').translate(None,
                                                                  ',').split())
        # Load sound volume file name value
        self._sound_vol_file = self._config.get('omxplayer', 'sound_vol_file')
        # default value to 0 millibels (omxplayer)
        self._sound_vol = 0
        # Initialize pygame and display a blank screen.
        pygame.display.init()
        pygame.font.init()
        pygame.mouse.set_visible(False)
        size = (pygame.display.Info().current_w,
                pygame.display.Info().current_h)
        self._screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
        self._blank_screen()
        # Set other static internal state.
        self._extensions = self._player.supported_extensions()
        self._small_font = pygame.font.Font(None, 50)
        self._big_font = pygame.font.Font(None, 250)
        self._running = True
    def _loadConfigFile(self):
        if os.path.exists(self.pathConfig) == False:
            raise IOError("Config file does not exist. System ends")

        if six.PY2:
            config = ConfigParser.SafeConfigParser()
        else:
            config = ConfigParser(allow_no_value=True)

        config.read(self.pathConfig)
        if six.PY2:
            self.posRemained = config.get(
                'POS', 'pos_remained').decode('utf-8').split(u',')
        else:
            self.posRemained = config.get('POS', 'pos_remained').split(',')

        self.stopLowLimit = int(
            config.get('stopWordSetting', 'low_frequency_limit'))
        self.stopHighLimit = float(
            config.get('stopWordSetting', 'high_ratio_limit'))

        self.nIter = int(config.get('ldaConfig', 'n_iteration'))
        self.randomState = int(config.get('ldaConfig', 'random_state'))
Пример #7
0
    def __load_model_conf(self):
        """
        to doc
        """

        CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))
        user_config = ConfigParser.SafeConfigParser()
        user_config.read(os.path.join(CURRENT_PATH, 'config', 'config.cfg'))

        self.__normalize = user_config.get_boolean('data', 'normalize')
        self.__threshold = user_config.get('data', 'out_threshold')
        self.__workers = user_config.get('data', 'workers')
        self.__model_name = user_config.get('model', 'model_name')
        self.__scale = user_config.get('model', 'scale')
        self.__input_channels = user_config.get('model', 'input_channels')
        self.__step = (user_config.get('model', 'test_step'),
                       user_config.get('model', 'test_step'),
                       user_config.get('model', 'test_step'))
        self.__patch_shape = (user_config.get('model', 'patch_shape'),
                              user_config.get('model', 'patch_shape'),
                              user_config.get('model', 'patch_shape'))
        self.__use_gpu = user_config.get_boolean('model', 'use_gpu')
        self.__gpu_number = [user_config.get('model', 'gpu_number')]
        'q_bumper_alpha': 1,  # Rescale advantage normalization by alpha
        'trajectory_distance': 'timestep',
        'q_threshold': 0.1,  # Have to be at least 90% of optimal
        'exploration_fraction': 0.9,
        'exploration_final_eps': 0.02,
        'exploration_final_lr': 0.02,
        'env_name': 'CliffWalking-treasure100-v0',
        'max_processes': None,
        'optimal_agent_training_timesteps': int(4e5),
        #'optimal_agent_smoothing_timesteps': int(4e5),
        'optimal_agent_smoothing_timesteps': None,
        'gamma': None,
    }

    if args.conf_file:
        config = ConfigParser.SafeConfigParser()
        config.read([args.conf_file])
        arg_defaults.update(dict(config.items("Defaults")))

    parser = argparse.ArgumentParser(
        parents=[conf_parser]
    )
    parser.set_defaults(**arg_defaults)
    parser.add_argument(
        '--env_name',
        choices=[
            'CliffWalking-treasure100-v0',
            'CliffWalking-nocliff-treasure100-v0',
            'CliffWalking-nocliff-treasure100-v0',
            'LunarLander-v2',
            'LunarLanderFixed-v2',
Пример #9
0
def parse_config():
    conf_parser = argparse.ArgumentParser(
        description=__doc__,
        add_help=False,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    conf_parser.add_argument(
        "-c",
        "--config",
        help=
        "Config file with defaults. Command line parameters will override those given in the config file. The config file must start with a \"[Defaults]\" section, followed by [argument]=[value] on each line.",
        metavar="FILE")
    args, remaining_argv = conf_parser.parse_known_args()

    defaults = {}
    if args.config:
        if not os.path.exists(args.config):
            raise EnvironmentError("Config file %s doesn't exist." %
                                   args.config)
        config = ConfigParser.SafeConfigParser()
        config.read([args.config])
        defaults = dict(config.items('Defaults'))
    else:
        if os.path.exists(os.path.expanduser('~/.selfspy/selfspy.conf')):
            config = ConfigParser.SafeConfigParser()
            config.read([os.path.expanduser('~/.selfspy/selfspy.conf')])
            defaults = dict(config.items('Defaults'))

    parser = argparse.ArgumentParser(
        description=
        'Monitor your computer activities and store them in an encrypted database for later analysis or disaster recovery.',
        parents=[conf_parser])
    parser.set_defaults(**defaults)
    parser.add_argument(
        '-p',
        '--password',
        help=
        'Encryption password. If you want to keep your database unencrypted, specify -p "" here. If you don\'t specify a password in the command line arguments or in a config file, a dialog will pop up, asking for the password. The most secure is to not use either command line or config file but instead type it in on startup.'
    )
    parser.add_argument(
        '-d',
        '--data-dir',
        help=
        'Data directory for selfspy, where the database is stored. Remember that Selfspy must have read/write access. Default is %s'
        % cfg.DATA_DIR,
        default=cfg.DATA_DIR)

    parser.add_argument(
        '-n',
        '--no-text',
        action='store_true',
        help=
        'Do not store what you type. This will make your database smaller and less sensitive to security breaches. Process name, window titles, window geometry, mouse clicks, number of keys pressed and key timings will still be stored, but not the actual letters. Key timings are stored to enable activity calculation in selfstats. If this switch is used, you will never be asked for password.'
    )
    parser.add_argument(
        '-r',
        '--no-repeat',
        action='store_true',
        help='Do not store special characters as repeated characters.')

    parser.add_argument(
        '--change-password',
        action="store_true",
        help='Change the password used to encrypt the keys columns and exit.')
    parser.add_argument('-v',
                        '--verbose',
                        action="count",
                        help="verbose \
            level... repeat up to three times.")

    return parser.parse_args()