Take a snapshot of all the supplied models and generate a diff report.

    MODELS: List of paths to two or more model files.
483259
def diff(models, filename, pytest_args, exclusive, skip, solver,
         experimental, custom_tests, custom_config):
    
    if not any(a.startswith("--tb") for a in pytest_args):
        pytest_args = ["--tb", "no"] + pytest_args
    # Add further directories to search for tests.
    pytest_args.extend(custom_tests)
    config = ReportConfiguration.load()
    # Update the default test configuration with custom ones (if any).
    for custom in custom_config:
        config.merge(ReportConfiguration.load(custom))
    # Build the diff report specific data structure
    diff_results = dict()
    model_and_model_ver_tuple = list()
    for model_path in models:
        try:
            model_filename = os.path.basename(model_path)
            diff_results.setdefault(model_filename, dict())
            model, model_ver, notifications = api.validate_model(model_path)
            if model is None:
                head, tail = os.path.split(filename)
                report_path = os.path.join(
                    head, '{}_structural_report.html'.format(model_filename))
                api.validation_report(
                    model_path, notifications, report_path)
                LOGGER.critical(
                    "The model {} could not be loaded due to SBML errors "
                    "reported in {}.".format(model_filename, report_path))
                continue
            model.solver = solver
            model_and_model_ver_tuple.append((model, model_ver))
        except (IOError, SBMLError):
            LOGGER.debug(exc_info=True)
            LOGGER.warning("An error occurred while loading the model '%s'. "
                           "Skipping.", model_filename)
    # Abort the diff report unless at least two models can be loaded
    # successfully.
    if len(model_and_model_ver_tuple) < 2:
        LOGGER.critical(
            "Out of the %d provided models only %d could be loaded. Please, "
            "check if the models that could not be loaded are valid SBML. "
            "Aborting.",
            len(models), len(model_and_model_ver_tuple))
        sys.exit(1)
    # Running pytest in individual processes to avoid interference
    partial_test_diff = partial(_test_diff, pytest_args=pytest_args,
                                skip=skip, exclusive=exclusive,
                                experimental=experimental)
    pool = Pool(min(len(models), cpu_count()))
    results = pool.map(partial_test_diff, model_and_model_ver_tuple)

    for model_path, result in zip(models, results):
        model_filename = os.path.basename(model_path)
        diff_results[model_filename] = result

    with open(filename, "w", encoding="utf-8") as file_handle:
        LOGGER.info("Writing diff report to '%s'.", filename)
        file_handle.write(api.diff_report(diff_results, config))
818769
def list_models(args: argparse.Namespace):
    
    try:
        git_index = GitIndex(remote=args.index_repo, username=args.username,
                             password=args.password, cache=args.cache, log_level=args.log_level)
    except ValueError:
        return 1
    for model_type, models in git_index.models.items():
        print(model_type)
        default = git_index.meta[model_type]["default"]
        for uuid, model in sorted(models.items(),
                                  key=lambda m: parse_datetime(m[1]["created_at"]),
                                  reverse=True):
            print("  %s %s" % ("*" if default == uuid else " ", uuid),
                  model["created_at"])
134867
def model_results(self) -> str:
        
        with open(os.path.join(self.directory, "model.results")) as f:
            return f.read()
528485
def _load_outcome_models(self):
        
        self.outcomes = []
        for outcome in self.state.outcomes.values():
            self._add_model(self.outcomes, outcome, OutcomeModel)
231094
function modelsToTypes(models) {
  let typeMap = models.filter(model => {
    if (_typeMap[model.modelName]) return false;
    return true;
  }).reduce((map, model) => {
    return (0, _assign2.default)(map, { [model.modelName]: toType(model) });
  }, {});
  _typeMap = (0, _assign2.default)(_typeMap, typeMap);

  // Deal with ref after all types are defined
  (0, _entries2.default)(typeMap).forEach(_ref => {
    var _ref2 = (0, _slicedToArray3.default)(_ref, 2);

    let modelName = _ref2[0];
    let type = _ref2[1];

    const originFileds = type._typeConfig.fields();
    const newTypeFileds = (0, _entries2.default)(originFileds).map(_ref3 => {
      var _ref4 = (0, _slicedToArray3.default)(_ref3, 2);

      let path = _ref4[0];
      let pathValue = _ref4[1];

      let newPathValue = (0, _assign2.default)({}, pathValue);
      if (newPathValue.ref) {
        const ref = newPathValue.ref;
        if (!_typeMap[ref]) throw TypeError(`${ref} is not a model`);
        const model = models.find(m => m.modelName === ref);
        const refModelType = _typeMap[ref];
        if (newPathValue.type instanceof _graphql.GraphQLList) {
          newPathValue = (0, _assign2.default)({}, newPathValue, {
            type: new _graphql.GraphQLList(refModelType),
            resolve: (() => {
              var _ref5 = (0, _asyncToGenerator3.default)(function* (instance) {
                // TODO: args filter
                return yield model.find({ _id: { $in: instance[path] } });
              });

              return function resolve(_x) {
                return _ref5.apply(this, arguments);
              };
            })()
          });
        } else {
          newPathValue = (0, _assign2.default)({}, newPathValue, {
            type: refModelType,
            resolve: (() => {
              var _ref6 = (0, _asyncToGenerator3.default)(function* (instance) {
                return yield model.findById(instance[path]);
              });

              return function resolve(_x2) {
                return _ref6.apply(this, arguments);
              };
            })()
          });
        }
      }
      return { [path]: newPathValue };
    }).reduce((typeField, path) => (0, _assign2.default)(typeField, path), {});

    typeMap[modelName]._typeConfig.fields = () => newTypeFileds;
  });

  _typeMap = (0, _assign2.default)(_typeMap, typeMap);
  return _typeMap;
}
30415
def _print_split_model(self, path, apps_models):
        
        for app, models in apps_models:
            for model in models:
                model_name = model().title
                if self._has_extension(path):
                    model_path = re.sub(r'^(.*)[.](\w+)$', r'\1.%s.%s.\2' % (app, model_name), path)
                else:
                    model_path = '%s.%s.%s.puml' % (path, app, model_name)
                self._print_single_file(model_path, [(app, [model])])
17943
def dicom_diff(file1, file2):
    

    datasets = compressed_dicom.read_file(file1), compressed_dicom.read_file(file2)

    rep = []

    for dataset in datasets:
        lines = (str(dataset.file_meta)+"\n"+str(dataset)).split('\n')
        lines = [line + '\n' for line in lines]  # add the newline to the end
        rep.append(lines)

    diff = difflib.Differ()
    for line in diff.compare(rep[0], rep[1]):
        if (line[0] == '+') or (line[0] == '-'):
            sys.stdout.write(line)
864780
def _models_generator():
    

    for app in apps.get_app_configs():
        for model in app.get_models():
            yield (str(model._meta.verbose_name).lower(), model)
            yield (str(model._meta.verbose_name_plural).lower(), model)
10483
private static void calculateDifferences(ModelDiff diff) {
        Class<?> modelClass = diff.getBefore().getClass();
        for (Field field : modelClass.getDeclaredFields()) {
            if (field.getName().equals(ModelUtils.MODEL_TAIL_FIELD_NAME)) {
                continue;
            }
            try {
                Object before = FieldUtils.readField(field, diff.getBefore(), true);
                Object after = FieldUtils.readField(field, diff.getAfter(), true);
                if (!Objects.equal(before, after)) {
                    diff.addDifference(field, before, after);
                }
            } catch (IllegalAccessException e) {
                LOGGER.warn("Skipped field '{}' because of illegal access to it", field.getName(), e);
            }
        }
    }
1075379
def diff(ctx, files, metrics, all, detail):
    """"""
    config = ctx.obj["CONFIG"]

    if not exists(config):
        handle_no_cache(ctx)

    if not metrics:
        metrics = get_default_metrics(config)
        logger.info(f"Using default metrics {metrics}")
    else:
        metrics = metrics.split(",")
        logger.info(f"Using specified metrics {metrics}")

    from wily.commands.diff import diff

    logger.debug(f"Running diff on {files} for metric {metrics}")
    diff(
        config=config, files=files, metrics=metrics, changes_only=not all, detail=detail
    )
1316764
def join(cls, diffs: Iterable['DBDiff']) -> 'DBDiff':
        
        tracker = DBDiffTracker()
        for diff in diffs:
            diff.apply_to(tracker)
        return tracker.diff()
229438
def models(self):
        '''
        
        '''
        model_dict = self._build_all_dependencies()
        while True:
            model = self._get_model_without_dependencies(model_dict)
            if not model:
                break
            yield (model, self._models().get(model))
408140
def build_model_classes(metadata):
    """"""
    i = importlib.import_module(metadata)
    env = get_jinja_env()
    model_template = env.get_template('model.py.jinja2')
    for model in i.models:
        with open(model_path(model.name.lower()), 'w') as t:
            t.write(model_template.render(model_md=model))
1191872
def _write_models_step(self, model, field=None):
    

    model = get_model(model)
    data = guess_types(self.hashes)

    try:
        func = _WRITE_MODEL[model]
    except KeyError:
        func = partial(write_models, model)

    func(data, field)
156920
def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None):
    
    with open(from_file) as from_stream:
        with open(to_file) as to_stream:
            from_records = records.load(from_stream, sep=sep)
            to_records = records.load(to_stream, sep=sep)
            return patch.create(from_records, to_records, index_columns,
                                ignore_columns=ignored_columns)
1216343
def get_diff(self, other_mapping):
        
        result = MultiField(name=self.name)
        new_fields = set(self.fields.keys())
        if not isinstance(other_mapping, MultiField):
            n_mapping = MultiField(name=self.name)
            n_mapping.add_fields([other_mapping])
            other_mapping = n_mapping

        old_fields = set(other_mapping.fields.keys())
        #we propagate new fields
        added = new_fields - old_fields
        if added:
            result.add_fields([(add, self.fields[add]) for add in added])
            #TODO: raise in field changed
        if len(result.fields) > 0:
            return result
        return None
901389
def diff_snapshots(self,snapshot_a,snapshot_b,save = True, diff=None):

        

        file_revisions_a = snapshot_a.file_revisions
        file_revisions_b = snapshot_b.file_revisions

        file_revisions_diff = diff_objects(file_revisions_a,
                                           file_revisions_b,
                                           file_revision_key,
                                           file_revision_comparator)

        #We just generate code objects and issues
        #for the modified file revisions, to save time when diffing.

        logger.debug("Generating list of modified file revisions...")
        modified_file_revisions_by_path = {}
        for fr_type in ('modified','added','deleted'):
            for fr in file_revisions_diff[fr_type]:
                if not fr.path in modified_file_revisions_by_path:
                    modified_file_revisions_by_path[fr.path] = fr

        logger.debug("Generating list of modified issues...")

        modified_file_revisions_a = [fr for fr in file_revisions_a
                                     if fr.path in modified_file_revisions_by_path]
        modified_file_revisions_b = [fr for fr in file_revisions_b
                                     if fr.path in modified_file_revisions_by_path]

        if modified_file_revisions_a:
            #to do: check the file revisions chunk-wise to avoid DB query errors
            issue_occurrences_a = self.project.backend.filter(IssueOccurrence,
                                         {
                                            'file_revision' : {'$in' : modified_file_revisions_a}
                                         },
                                      include = ('file_revision','issue'))
        else:
            issue_occurrences_a = []

        if modified_file_revisions_b:
            #to do: check the file revisions chunk-wise to avoid DB query errors
            issue_occurrences_b = self.project.backend.filter(IssueOccurrence,
                                           {
                                            'file_revision' : {'$in' : modified_file_revisions_b}
                                            },
                                      include = ('file_revision','issue'))
        else:
            issue_occurrences_b = []

        logger.debug("Diffing issues (%d in A, %d in B)" % (len(issue_occurrences_a),
                                                           len(issue_occurrences_b)))


        issue_occurrences_diff = diff_objects(issue_occurrences_a,
                                              issue_occurrences_b,
                                              issue_occurrence_key,
                                              issue_occurrence_comparator)

        logger.debug("Diffing summary...")
        summary_diff = self.diff_summaries(snapshot_a,snapshot_b)

        if diff is None:
            diff = Diff({'summary' : summary_diff,
                        'snapshot_a' : snapshot_a,
                        'project' : self.project,
                        'configuration' : self.project.configuration,
                        'snapshot_b' : snapshot_b})
            #we generate the hash value for this diff
            hasher = Hasher()
            hasher.add(diff.snapshot_a.hash)
            hasher.add(diff.snapshot_b.hash)
            diff.hash = hasher.digest.hexdigest()
        elif save:
            with self.project.backend.transaction():
                self.project.backend.filter(DiffFileRevision,{'diff' : diff}).delete()
                self.project.backend.filter(DiffIssueOccurrence,{'diff' : diff}).delete()
        if save:
            with self.project.backend.transaction():
                self.project.backend.save(diff)

        diff_file_revisions = []

        with self.project.backend.transaction():
            for key,file_revisions in file_revisions_diff.items():
                for file_revision in file_revisions:
                    hasher = Hasher()
                    hasher.add(file_revision.hash)
                    hasher.add(diff.hash)
                    hasher.add(key)
                    diff_file_revision = DiffFileRevision({
                                            'diff' : diff,
                                            'file_revision' : file_revision,
                                            'hash' : hasher.digest.hexdigest(),
                                            'key' : key})
                    if save:
                        self.project.backend.save(diff_file_revision)
                    diff_file_revisions.append(diff_file_revision)

        diff_issue_occurrences = []
        mapping = {'deleted' : 'fixed','added' : 'added'}
        with self.project.backend.transaction():
            for key,issue_occurrences in issue_occurrences_diff.items():
                if not key in mapping:
                    continue
                for issue_occurrence in issue_occurrences:
                    hasher = Hasher()
                    hasher.add(issue_occurrence.hash)
                    hasher.add(diff.hash)
                    hasher.add(mapping[key])
                    diff_issue_occurrence = DiffIssueOccurrence({
                            'diff' : diff,
                            'hash' : hasher.digest.hexdigest(),
                            'issue_occurrence' : issue_occurrence,
                            'key' : mapping[key]
                        })
                    if save:
                        self.project.backend.save(diff_issue_occurrence)
                    diff_issue_occurrences.append(diff_issue_occurrence)

        return diff,diff_file_revisions,diff_issue_occurrences