How to use the mpf.core.utility_functions.Util function in mpf

To help you get started, we’ve selected a few mpf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github missionpinball / mpf / mpf / core / config_processor.py View on Github external
config = FileManager.load(filename, expected_version_str, True)
        subfiles = []

        if not config:
            return dict(), []

        self.log.info('Loading config: %s', filename)

        if config_type in ("machine", "mode"):
            self._check_sections(config, config_type, filename, ignore_unknown_sections)

        try:
            if 'config' in config:
                path = os.path.split(filename)[0]

                for file in Util.string_to_list(config['config']):
                    full_file = os.path.join(path, file)
                    subfiles.append(full_file)
                    subconfig, subsubfiles = self._load_config_file_and_return_loaded_files(full_file, config_type)
                    subfiles.extend(subsubfiles)
                    config = Util.dict_merge(config, subconfig)
            return config, subfiles
        except TypeError:
            return dict(), []
github missionpinball / mpf / mpf / config_players / event_player.py View on Github external
def play(self, settings, context, calling_context, priority=0, **kwargs):
        """Post (delayed) events."""
        del kwargs
        for event, s in settings.items():
            s = deepcopy(s)
            if '|' in event:
                event, delay = event.split("|")
                delay = Util.string_to_ms(delay)
                self.delay.add(callback=self._post_event, ms=delay,
                               event=event, s=s)
            elif ':' in event:
                event, delay = event.split(":")
                delay = Util.string_to_ms(delay)
                self.delay.add(callback=self._post_event, ms=delay,
                               event=event, s=s)
            else:
                self._post_event(event, s)
github missionpinball / mpf-mc / mpfmc / commands / mc.py View on Github external
const='virtual', help=argparse.SUPPRESS)

        parser.add_argument("--vpx",
                            action="store_const", dest="force_platform",
                            const='virtual_pinball', help=argparse.SUPPRESS)

        parser.add_argument("-X",
                            action="store_const", dest="force_platform",
                            const='smart_virtual', help=argparse.SUPPRESS)

        parser.add_argument("--no-sound",
                            action="store_true", dest="no_sound", default=False)

        args = parser.parse_args(args)

        args.configfile = Util.string_to_event_list(args.configfile)

        # Configure logging. Creates a logfile and logs to the console.
        # Formatting options are documented here:
        # https://docs.python.org/2.7/library/logging.html#logrecord-attributes

        try:
            os.makedirs(os.path.join(machine_path, 'logs'))
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise

        if args.mc_logfile:
            args.logfile = args.mc_logfile

        full_logfile_path = os.path.join(machine_path, args.logfile)
github missionpinball / mpf / mpf / core / config_validator.py View on Github external
if item == 'item not in config!@#':
            if default == 'default required!@#':
                raise ValueError('Required setting missing from config file. '
                                 'Run with verbose logging and look for the last '
                                 'ConfigProcessor entry above this line to see where the '
                                 'problem is. {} {}'.format(spec,
                                                            validation_failure_info))
            else:
                item = default

        if item_type == 'single':
            return self.validate_item(item, validation,
                                      validation_failure_info)

        elif item_type == 'list':
            item_list = Util.string_to_list(item)

            new_list = list()

            for i in item_list:
                new_list.append(self.validate_item(i, validation, validation_failure_info))

            return new_list

        elif item_type == 'set':
            item_set = set(Util.string_to_list(item))

            new_set = set()

            for i in item_set:
                new_set.add(self.validate_item(i, validation, validation_failure_info))
github missionpinball / mpf / mpf / core / utility_functions.py View on Github external
a decibel value (-inf to 0.0) into a gain value (0.0 to 1.0).

        Args:
            gain_string: The string to convert to a gain value

        Returns:
            Float containing a gain value (0.0 to 1.0)
        """
        gain_string = str(gain_string).lower()

        if gain_string.startswith('-inf'):
            return 0.0

        if gain_string.endswith('db'):
            gain_string = ''.join(i for i in gain_string if not i.isalpha())
            return min(max(Util.db_to_gain(float(gain_string)), 0.0), 1.0)

        try:
            return min(max(float(gain_string), 0.0), 1.0)
        except (TypeError, ValueError):
            return 1.0
github missionpinball / mpf / mpf / core / utility_functions.py View on Github external
# log.info("Dict Merge incoming A %s", a)
        # log.info("Dict Merge incoming B %s", b)
        if not isinstance(b, dict):
            return b
        result = deepcopy(a)
        for k, v in b.items():
            if v is None:
                continue
            if isinstance(v, dict) and '_overwrite' in v:
                result[k] = v
                del result[k]['_overwrite']
            elif isinstance(v, dict) and '_delete' in v:
                if k in result:
                    del result[k]
            elif k in result and isinstance(result[k], dict):
                result[k] = Util.dict_merge(result[k], v)
            elif k in result and isinstance(result[k], list):
                if isinstance(v, dict) and v[0] == dict(_overwrite=True):
                    result[k] = v[1:]
                elif isinstance(v, list) and combine_lists:
                    result[k].extend(v)
                else:
                    result[k] = deepcopy(v)
            else:
                result[k] = deepcopy(v)
        # log.info("Dict Merge result: %s", result)
        return result
github missionpinball / mpf / mpf / core / utility_functions.py View on Github external
    @staticmethod
    def bin_str_to_hex_str(source_int_str: str, num_chars: int) -> str:
        """Convert binary string to hex string."""
        return Util.normalize_hex_string('%0X' % int(source_int_str, 2),
                                         num_chars)
github missionpinball / mpf / mpf / config_players / random_event_player.py View on Github external
def get_express_config(self, value):
        """Parse express config."""
        return {"events": self.get_list_config(Util.string_to_list(value))}