Imports a DFA from a JSON file.

    :param str input_file: path + filename to json file;
    :return: *(dict)* representing a DFA.
776545
def dfa_json_importer(input_file: str) -> dict:
    
    file = open(input_file)
    json_file = json.load(file)

    transitions = {}  # key [state ∈ states, action ∈ alphabet]
    #                   value [arriving state ∈ states]
    for (origin, action, destination) in json_file['transitions']:
        transitions[origin, action] = destination

    dfa = {
        'alphabet': set(json_file['alphabet']),
        'states': set(json_file['states']),
        'initial_state': json_file['initial_state'],
        'accepting_states': set(json_file['accepting_states']),
        'transitions': transitions
    }
    return dfa
1356942
def import_file_object(filename):
    
    try:
        handle = open(filename, 'r')
        file_obj = handle.read()
        dict_obj = json.loads(file_obj)

    except IOError as e:
        logger.critical(
            'import_file_object: %s error opening %s' % (str(e), str(filename))
        )
        raise e
    except ValueError:
        logger.info(
            '%s: import_file_object: %s not json. file object returned' %
            (inspect.stack()[0][3], str(filename))
        )
        return file_obj    # reg file, not valid json
    return dict_obj
307247
def parse(input_: Union[str, FileStream], default_base: Optional[str]=None) -> Optional[Schema]:
    

    # Step 1: Tokenize the input stream
    error_listener = ParseErrorListener()
    if not isinstance(input_, FileStream):
        input_ = InputStream(input_)
    lexer = ShExDocLexer(input_)
    lexer.addErrorListener(error_listener)
    tokens = CommonTokenStream(lexer)
    tokens.fill()
    if error_listener.n_errors:         # Lexer prints errors directly
        return None

    # Step 2: Generate the parse tree
    parser = ShExDocParser(tokens)
    parser.addErrorListener(error_listener)
    parse_tree = parser.shExDoc()
    if error_listener.n_errors:
        print('\n'.join(error_listener.errors), file=sys.stderr)
        return None

    # Step 3: Transform the results the results
    parser = ShexDocParser(default_base=default_base)
    parser.visit(parse_tree)

    return parser.context.schema
148252
def add_input_stream(self, datastream, data_type, options, data):
        

        url = self.get_add_input_data_url(datastream, options)
        form_data = {
            'files': {
                'data': (
                    Utils.random_string(10)+('.json' if data_type == 'json' else '.csv'),
                    data,
                    'text/plain;charset=UTF-8',
                    {'Expires': '0'}
                )
            }
        }
        response = self.http.upstream(url, form_data)
        return response
1103016
def set_from_file(file_name):
    
    if type(file_name) != str:
        raise TypeError('file_name must be str')
    global _config_file_name
    _config_file_name = file_name
    # Try to open the file and get the json data into a dictionary
    with open(file_name, "r") as file:
        data = yaml.load(file)
    # each value found will overwrite the same value in the config
    _list_merge(data, _config)
764588
def json_decode_file(filename):
    
    seq = open(filename).read()
    # The JSON standard has no comments syntax. We have to remove them
    # before feeding python's JSON parser
    seq = json_remove_comments(seq)
    # Parse all the unicode stuff to utf-8
    return json_unicode_to_utf8(json.loads(seq))
658418
def from_file(cls, db_file=ALL_SETS_PATH):
        
        if callable(getattr(db_file, 'read', None)):
            return cls(json.load(db_file))

        with io.open(db_file, encoding='utf8') as inp:
            return cls(json.load(inp))
723057
def dump_dict(dict_input, indent=4):
    

    dict_work = dict(dict_input)
    """
    for key, value in six.iteritems(dict_input):
        if any([f(value) for f in (is_float, isDict, is_list_or_tuple)]):
            dict_work[key] = value
            continue

        try:
            dict_work[key] = str(value)
        except:
            dict_work[key] = str(type(value))

        dict_work[key] = _convert_dump_dict(value)
    """

    try:
        import json
        return json.dumps(dict_work, sort_keys=True, indent=indent)
    except ImportError:
        pass

    try:
        import simplejson as json
        return json.dumps(dict_work, sort_keys=True, indent=indent)
    except ImportError:
        pass

    try:
        import pprint
        return pprint.pformat(dict_work, indent=indent)
    except ImportError:
        pass

    return str(dict_work)
223447
def import_from_json(filename_or_fobj, encoding="utf-8", *args, **kwargs):
    

    source = Source.from_file(filename_or_fobj, mode="rb", plugin_name="json", encoding=encoding)

    json_obj = json.load(source.fobj, encoding=source.encoding)
    field_names = list(json_obj[0].keys())
    table_rows = [[item[key] for key in field_names] for item in json_obj]

    meta = {"imported_from": "json", "source": source}
    return create_table([field_names] + table_rows, meta=meta, *args, **kwargs)
185469
def from_file(cls, config_path=None, *args, **kwargs):
        

        config_reader = kaptan.Kaptan()

        config = {}

        if config_path:
            if not os.path.exists(config_path):
                raise exc.CihaiException(
                    '{0} does not exist.'.format(os.path.abspath(config_path))
                )
            if not any(
                config_path.endswith(ext) for ext in ('json', 'yml', 'yaml', 'ini')
            ):
                raise exc.CihaiException(
                    '{0} does not have a yaml,yml,json,ini extend.'.format(
                        os.path.abspath(config_path)
                    )
                )
            else:
                custom_config = config_reader.import_config(config_path).get()
                config = merge_dict(config, custom_config)

        return cls(config)
304507
def read_dict_from_file(file_path):
    
    with open(file_path) as file:
        lines = file.read().splitlines()

    obj = {}
    for line in lines:
        key, value = line.split(':', maxsplit=1)
        obj[key] = eval(value)

    return obj
485925
def _read_from_json(self, file):
        

        try:
            with io.open(os.path.join(self._PATH, file), encoding="utf8") as f:
                return {u["id"]: u for u in json.load(f)}
        except IOError:
            return {}
515227
def read_pkginfo(filename):
    
    COMMENT_CHAR = '#'
    OPTION_CHAR =  '='
    options = {}
    f = open(filename)
    for line in f:
        if COMMENT_CHAR in line:
            line, comment = line.split(COMMENT_CHAR, 1)
        if OPTION_CHAR in line:
            option, value = line.split(OPTION_CHAR, 1)
            option = option.strip()
            value = value.strip()
            options[option] = value
    f.close()
    return options
569786
def parser(input_file_path='config.json'):
    '''
    
    '''

    # --- Read .json file
    try:
        with open(input_file_path, 'r') as config_file:
            config_new = json.load(config_file)
            config_file.close()
    except:
        raise Exception('Config file "'+input_file_path+'" not loaded properly. Please check it an try again.')

    import copy
    options = update_config(config_new, copy.deepcopy(default_config))

    return options
328711
def load_input():
    
    file = open(_input_file, 'r')
    result = json.loads(file.read().strip('\0').strip())
    file.close()
    return result
728983
def load_elements(self, filename):
        
        input_data = load_b26_file(filename)
        if isinstance(input_data, dict) and self.elements_type in input_data:
            return input_data[self.elements_type]
        else:
            return {}
1079831
def load(cls, file_path):
        

        # convert back to numpy
        data = helper.read_json(file_path)
        return Concise.from_dict(data)