Import volumes

    SOURCE must be a json file and must follow the same structure used in `libreant-db export`.
    Pass - to read from standard input.
425531
def import_volumes(source, ignore_conflicts, yes):
    '''
    '''
    volumes = json.load(source)
    tot = len(volumes)
    if not yes:
        click.confirm("Are you sure you want to import {} volumes into index '{}'".format(tot, arc._config['ES_INDEXNAME']))
    conflicts=0
    with click.progressbar(volumes, label='adding volumes') as bar:
        for v in bar:
            try:
                arc.import_volume(v)
            except ConflictException as ce:
                if not ignore_conflicts:
                    die(str(ce))
                conflicts += 1
            except Exception as e:
                if conf.get('DEBUG', False):
                    raise
                else:
                    die(str(e))

    if conflicts > 0:
        click.echo("{} volumes has been skipped beacause of a conflict".format(conflicts))
233829
def load_json(filename: str) -> Union[List, Dict]:
    
    try:
        with open(filename, encoding='utf-8') as fdesc:
            return json.loads(fdesc.read())
    except FileNotFoundError:
        # This is not a fatal error
        _LOGGER.debug('JSON file not found: %s', filename)
    except ValueError as error:
        _LOGGER.exception('Could not parse JSON content: %s', filename)
        raise PytradfriError(error)
    except OSError as error:
        _LOGGER.exception('JSON file reading failed: %s', filename)
        raise PytradfriError(error)
    return {}
1025215
def import_from_dict(session, data, sync=[]):
    """"""
    if isinstance(data, dict):
        logging.info('Importing %d %s',
                     len(data.get(DATABASES_KEY, [])),
                     DATABASES_KEY)
        for database in data.get(DATABASES_KEY, []):
            Database.import_from_dict(session, database, sync=sync)

        logging.info('Importing %d %s',
                     len(data.get(DRUID_CLUSTERS_KEY, [])),
                     DRUID_CLUSTERS_KEY)
        for datasource in data.get(DRUID_CLUSTERS_KEY, []):
            DruidCluster.import_from_dict(session, datasource, sync=sync)
        session.commit()
    else:
        logging.info('Supplied object is not a dictionary.')
321781
def to_json(self, path: Optional[str] = None, **kwargs) -> str:
        
        from .io import save_json
        return save_json(self, path, **kwargs)
891475
function checkImport(jsonImport, importType) {
        if (!jsonImport) {
            return 'Import should always be a valid JSON object!';
        }

        switch (importType) {
            case CONSTANTS.EXPORT_TYPE_PROJECT:
                if (jsonImport._metadata && jsonImport._metadata.type) {
                    if (jsonImport._metadata.type !== CONSTANTS.EXPORT_TYPE_PROJECT) {
                        return 'Import is of type \'' + CONSTANTS.EXPORT_TYPE_LIBRARY + '\' and not of \'' +
                            CONSTANTS.EXPORT_TYPE_PROJECT + '\'!';
                    }
                } else if (jsonImport.root && typeof jsonImport.root.path === 'string') {
                    if (jsonImport.root.path !== '') {
                        return 'Import is of type \'' + CONSTANTS.EXPORT_TYPE_LIBRARY + '\' and not of \'' +
                            CONSTANTS.EXPORT_TYPE_PROJECT + '\'!';
                    }
                } else {
                    return 'Import data is probably incomplete and should not be used!';
                }
                break;
            case CONSTANTS.EXPORT_TYPE_LIBRARY:
                if (jsonImport._metadata && jsonImport._metadata.type) {
                    if (jsonImport._metadata.type !== CONSTANTS.EXPORT_TYPE_LIBRARY) {
                        return 'Import is of type \'' + CONSTANTS.EXPORT_TYPE_PROJECT + '\' and not of \'' +
                            CONSTANTS.EXPORT_TYPE_LIBRARY + '\'!';
                    }
                } else if (jsonImport.root && typeof jsonImport.root.path === 'string') {
                    if (jsonImport.root.path === '') {
                        return 'Import is of type \'' + CONSTANTS.EXPORT_TYPE_PROJECT + '\' and not of \'' +
                            CONSTANTS.EXPORT_TYPE_LIBRARY + '\'!';
                    }
                } else {
                    return 'Import data is probably incomplete and should not be used!';
                }
                break;
            default:
                return 'Invalid type, cannot checked!';
        }

        return null;
    }
3144
function fromJson(collection, collectionPath, next) {

  var docsBulk = [];
  var docs = fs.readdirSync(collectionPath);
  var last = ~~docs.length, counter = 0;
  if (last === 0) {
    return next(null);
  }

  docs.forEach(function(docName) {

    var doc, data;
    try {
      data = fs.readFileSync(collectionPath + docName);
    } catch (err) {
      return last === ++counter ? next(null) : null;
    }
    try {
      doc = JSON.parse(data);
    } catch (err) {
      return last === ++counter ? next(err) : error(err);
    }

    docsBulk.push({
      insertOne: {
        document: doc
      }
    });

    return last === ++counter ? collection.bulkWrite(docsBulk, next) : null;
  });
}
1336793
def get_source_import(self):
        
        import_header = {"Accept": Consts.mediaTypeImportPreview}
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/import",
            headers=import_header,
        )
        if not data:
            return None
        else:
            return github.SourceImport.SourceImport(self._requester, headers, data, completed=True)
175778
def _get_importer(input_file):
    """"""
    __, ext = os.path.splitext(input_file)
    ext = ext.lower()

    if "ostriz" in input_file:
        from dump2polarion.results import ostriztools

        importer = ostriztools.import_ostriz
    elif ext == ".xml":
        # expect junit-report from pytest
        from dump2polarion.results import junittools

        importer = junittools.import_junit
    elif ext == ".csv":
        from dump2polarion.results import csvtools

        importer = csvtools.import_csv
    elif ext in dbtools.SQLITE_EXT:
        importer = dbtools.import_sqlite
    elif ext == ".json":
        from dump2polarion.results import jsontools

        importer = jsontools.import_json
    else:
        raise Dump2PolarionException("Cannot recognize type of input data, add file extension.")

    return importer
75406
def read_json (self, mode='rt', **kwargs):
        
        import json

        with self.open (mode=mode) as f:
            return json.load (f, **kwargs)
582792
def fromJSON(value):
        """"""
        if isinstance(value, str):
            value = json.loads(value)
        elif isinstance(value, dict): pass
        else:
            raise AttributeError("Invalid input")
        return Extension(typeName=value['typeName'],
                         capabilities=value['capabilities'],
                         enabled=value['enabled'] == "true",
                         maxUploadFileSize=value['maxUploadFileSize'],
                         allowedUploadFileType=value['allowedUploadFileTypes'],
                         properties=value['properties'])
843191
def import_model(self, source):
        """"""
        model = super(StrictImporter, self).import_model(source)

        # Translate entries into dict-based entries.
        sbml.convert_model_entries(
            model, convert_id=lambda entry: entry.id,
            translate_compartment=self._translate_compartment,
            translate_compound=self._translate_compound,
            translate_reaction=self._translate_reaction)

        return model
1372297
def from_json(cls, json_doc):
        """"""
        try:
            d = json.load(json_doc)
        except AttributeError:  # catch the read() error
            d = json.loads(json_doc)

        return cls.from_dict(d)
920488
def load(filename):
  '''  '''
  global _DICTIONARY
  try:
    json_file = filename + '.json'
    with open(os.path.join(_DEFAULT_DIR, json_file), 'rb') as f:
      _DICTIONARY = json.load(f)
  except IOError:
    raise IOError('Language file not found. Make sure that your ',
                  'translation file is in the languages directory, ')
766050
function createJsonFileDiscoverProvider(hostsFile) {
    var fs = require('fs');

    return function jsonFileProvider(callback) {
        fs.readFile(hostsFile, function onFileRead(err, data) {
            if (err) {
                callback(err);
                return;
            }

            var hosts;
            try {
                hosts = JSON.parse(data.toString());
            } catch (e) {
                callback(e);
                return;
            }
            callback(null, hosts);
            return;
        });
    };
}
1357143
function bemJsonLoader(source) {
  // Evaluate raw BemJson
  const bemJson = nodeEval(source) || '';

  // Validate BemJson for errors
  const self = this;
  validateBemJson(bemJson, this.resourcePath).forEach((e) => {
    self.emitWarning(e);
  });

  // Convert BemJson to BemDecl
  let bemDecl;
  try {
    bemDecl = bemjsonToDecl.convert(bemJson) || [];
  } catch (e) {
    throw new Error('BemJson to BemDecl error: ' + e.message + '. File: ' +
      this.resourcePath);
  }

  // Validate BemDecl for errors
  validateBemDecl(bemDecl, this.resourcePath).forEach((e) => {
    self.emitWarning(e);
  });

  return 'module.exports = ' + JSON.stringify(bemDecl, null, 2) + ';';
}
1242158
def load_json(data=None, path=None, name='NT'):
    
    if data and not path:
        return mapper(json.loads(data), _nt_name=name)
    if path and not data:
        return mapper(json.load(path), _nt_name=name)
    if data and path:
        raise ValueError('expected one source and received two')
368577
def _load(self):
        
        if self.dbfile is not None:
            with open(self.dbfile, 'r') as f:
                self._db = json.loads(f.read())
        else:
            self._db = {}