text:
package org.sleuthkit.autopsy.keywordsearch;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;

/**
 * Represents the fact that a file or an artifact associated with a file had a
 * keyword hit. All instances make both the document id of the Solr document
 * where the keyword was found and the object id of the file available to
 * clients. Keyword hits on the indexed text of an artifact also make the
 * artifact available to clients.
 */
class KeywordHit implements Comparable<KeywordHit> {

    private static final String GET_CONTENT_ID_FROM_ARTIFACT_ID = "SELECT obj_id FROM blackboard_artifacts WHERE artifact_id = ";

    private final String solrDocumentId;
    private final long solrObjectId;
    private final int chunkId;
    private final String snippet;
    private final long contentID;
    private final boolean hitOnArtifact;
    private final String hit;

    /**
     * Constructor
     *
     * @param solrDocumentId The id of the document this hit is in.
     * @param snippet        A small amount of text from the document containing
     *                       the hit.
     * @param hit            The exact text from the document that was the hit.
     *                       For some searches (ie substring, regex) this will be
     *                       different than the search term.
     *
     * @throws TskCoreException If there is a problem getting the underlying
     *                          content associated with a hit on the text of an
     *                          artifact.
     */
    KeywordHit(String solrDocumentId, String snippet, String hit) throws TskCoreException {
        this.snippet = StringUtils.stripToEmpty(snippet);
        this.hit = hit;
        this.solrDocumentId = solrDocumentId;

        /*
         * Parse the Solr document id to get the Solr object id and chunk id.
         * The Solr object id will either be the object id of a file id or an
         * artifact id from the case database.
         *
         * For every object (file or artifact) there will at least two Solr
         * documents. One contains object metadata (chunk #1) and the second and
         * subsequent documents contain chunks of the text.
         */
        String[] split = solrDocumentId.split(Server.CHUNK_ID_SEPARATOR);
        if (split.length == 1) {
            //chunk 0 has only the bare document id without the chunk id.
            this.solrObjectId = Long.parseLong(solrDocumentId);
            this.chunkId = 0;
        } else {
            this.solrObjectId = Long.parseLong(split[0]);
            this.chunkId = Integer.parseInt(split[1]);
        }

        //artifacts have negative obj ids
        hitOnArtifact = this.solrObjectId < 0;

        if (hitOnArtifact) {
            // If the hit was in an artifact, look up the source content for the artifact.
            SleuthkitCase caseDb = Case.getCurrentCase().getSleuthkitCase();
            try (SleuthkitCase.CaseDbQuery executeQuery =
                    caseDb.executeQuery(GET_CONTENT_ID_FROM_ARTIFACT_ID + this.solrObjectId);
                    ResultSet resultSet = executeQuery.getResultSet();) {
                if (resultSet.next()) {
                    contentID = resultSet.getLong("obj_id");
                } else {
                    throw new TskCoreException("Failed to get obj_id for artifact with artifact_id =" + this.solrObjectId + ".  No matching artifact was found.");
                }
            } catch (SQLException ex) {
                throw new TskCoreException("Error getting obj_id for artifact with artifact_id =" + this.solrObjectId, ex);
            }
        } else {
            //else the object id is for content.
            contentID = this.solrObjectId;
        }
    }

    String getHit() {
        return hit;
    }

    String getSolrDocumentId() {
        return this.solrDocumentId;
    }

    long getSolrObjectId() {
        return this.solrObjectId;
    }

    int getChunkId() {
        return this.chunkId;
    }

    boolean hasSnippet() {
        return StringUtils.isNotBlank(this.snippet);
    }

    String getSnippet() {
        return this.snippet;
    }

    long getContentID() {
        return this.contentID;
    }

    /**
     * Is this hit in the indexed text of an artifact.
     *
     * @return
     */
    boolean isArtifactHit() {
        return hitOnArtifact;
    }

    /**
     * If this hit is in the indexed text of an artifact, get that artifact.
     *
     * @return The artifact whose indexed text this hit is in.
     */
    Optional<Long> getArtifactID() {
        if (hitOnArtifact) {
            return Optional.of(solrObjectId);
        } else {
            return Optional.empty();
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (null == obj) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final KeywordHit other = (KeywordHit) obj;
        return this.compareTo(other) == 0;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 41 * hash + (int) this.solrObjectId + this.chunkId;
        return hash;
    }

    @Override
    public int compareTo(KeywordHit o) {
        return Comparator.comparing(KeywordHit::getSolrObjectId)
                .thenComparing(KeywordHit::getChunkId)
                .compare(this, o);
    }
}


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.modeshape.jcr;

import org.junit.Test;

/**
 * We don't test a lot of functionality here. It's the same provider as tested in the {@link LocalIndexProviderTest}, except that
 * in these tests we want to simply verify that the asynchronous indexing is working. (These asynchronous tests take a lot longer
 * since we have to wait an unknown amount of time after saving changes before we can issue the query.)
 *
 * @author Randall Hauch (rhauch@redhat.com)
 * @author Horia Chiorean (hchiorea@redhat.com)
 *
 * @see LocalIndexProviderTest
 */
public class LocalIndexProviderAsynchronousTest extends AbstractIndexProviderTest {

    @Override
    protected boolean useSynchronousIndexes() {
        return false;
    }

    @Override
    protected String providerName() {
        return "local";
    }

    // ---------------------------------------------------------------
    // Override these so that we can easily run them via JUnit runner.
    // ---------------------------------------------------------------

    @Override
    @Test
    public void shouldAllowRegisteringNewIndexDefinitionWithSingleStringColumn() throws Exception {
        super.shouldAllowRegisteringNewIndexDefinitionWithSingleStringColumn();
    }

    @Override
    @Test
    public void shouldUseSingleColumnStringIndexInQueryAgainstSameNodeType() throws Exception {
        super.shouldUseSingleColumnStringIndexInQueryAgainstSameNodeType();
    }

    @Override
    public void shouldSkipEntireBatches() throws Exception {
        super.shouldSkipEntireBatches();
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace ceres {
namespace internal {

// Templated Evaluator for Powell's function. The template parameters
// indicate which of the four variables/columns of the jacobian are
// active. This is equivalent to constructing a problem and using the
// SubsetLocalParameterization. This allows us to test the support for
// the Evaluator::Plus operation besides checking for the basic
// performance of the trust region algorithm.
template <bool col1, bool col2, bool col3, bool col4>
class PowellEvaluator2 : public Evaluator {
 public:
  PowellEvaluator2()
      : num_active_cols_(
          (col1 ? 1 : 0) +
          (col2 ? 1 : 0) +
          (col3 ? 1 : 0) +
          (col4 ? 1 : 0)) {
    VLOG(1) << "Columns: "
            << col1 << " "
            << col2 << " "
            << col3 << " "
            << col4;
  }

  virtual ~PowellEvaluator2() {}

  // Implementation of Evaluator interface.
  virtual SparseMatrix* CreateJacobian() const {
    CHECK(col1 || col2 || col3 || col4);
    DenseSparseMatrix* dense_jacobian =
        new DenseSparseMatrix(NumResiduals(), NumEffectiveParameters());
    dense_jacobian->SetZero();
    return dense_jacobian;
  }

  virtual bool Evaluate(const Evaluator::EvaluateOptions& evaluate_options,
                        const double* state,
                        double* cost,
                        double* residuals,
                        double* gradient,
                        SparseMatrix* jacobian) {
    const double x1 = state[0];
    const double x2 = state[1];
    const double x3 = state[2];
    const double x4 = state[3];

    VLOG(1) << "State: "
            << "x1=" << x1 << ", "
            << "x2=" << x2 << ", "
            << "x3=" << x3 << ", "
            << "x4=" << x4 << ".";

    const double f1 = x1 + 10.0 * x2;
    const double f2 = sqrt(5.0) * (x3 - x4);
    const double f3 = pow(x2 - 2.0 * x3, 2.0);
    const double f4 = sqrt(10.0) * pow(x1 - x4, 2.0);

    VLOG(1) << "Function: "
            << "f1=" << f1 << ", "
            << "f2=" << f2 << ", "
            << "f3=" << f3 << ", "
            << "f4=" << f4 << ".";

    *cost = (f1*f1 + f2*f2 + f3*f3 + f4*f4) / 2.0;

    VLOG(1) << "Cost: " << *cost;

    if (residuals != NULL) {
      residuals[0] = f1;
      residuals[1] = f2;
      residuals[2] = f3;
      residuals[3] = f4;
    }

    if (jacobian != NULL) {
      DenseSparseMatrix* dense_jacobian;
      dense_jacobian = down_cast<DenseSparseMatrix*>(jacobian);
      dense_jacobian->SetZero();

      ColMajorMatrixRef jacobian_matrix = dense_jacobian->mutable_matrix();
      CHECK_EQ(jacobian_matrix.cols(), num_active_cols_);

      int column_index = 0;
      if (col1) {
        jacobian_matrix.col(column_index++) <<
            1.0,
            0.0,
            0.0,
            sqrt(10.0) * 2.0 * (x1 - x4) * (1.0 - x4);
      }
      if (col2) {
        jacobian_matrix.col(column_index++) <<
            10.0,
            0.0,
            2.0*(x2 - 2.0*x3)*(1.0 - 2.0*x3),
            0.0;
      }

      if (col3) {
        jacobian_matrix.col(column_index++) <<
            0.0,
            sqrt(5.0),
            2.0*(x2 - 2.0*x3)*(x2 - 2.0),
            0.0;
      }

      if (col4) {
        jacobian_matrix.col(column_index++) <<
            0.0,
            -sqrt(5.0),
            0.0,
            sqrt(10.0) * 2.0 * (x1 - x4) * (x1 - 1.0);
      }
      VLOG(1) << "\n" << jacobian_matrix;
    }

    if (gradient != NULL) {
      int column_index = 0;
      if (col1) {
        gradient[column_index++] = f1  + f4 * sqrt(10.0) * 2.0 * (x1 - x4);
      }

      if (col2) {
        gradient[column_index++] = f1 * 10.0 + f3 * 2.0 * (x2 - 2.0 * x3);
      }

      if (col3) {
        gradient[column_index++] =
            f2 * sqrt(5.0) + f3 * (2.0 * 2.0 * (2.0 * x3 - x2));
      }

      if (col4) {
        gradient[column_index++] =
            -f2 * sqrt(5.0) + f4 * sqrt(10.0) * 2.0 * (x4 - x1);
      }
    }

    return true;
  }

  virtual bool Plus(const double* state,
                    const double* delta,
                    double* state_plus_delta) const {
    int delta_index = 0;
    state_plus_delta[0] = (col1  ? state[0] + delta[delta_index++] : state[0]);
    state_plus_delta[1] = (col2  ? state[1] + delta[delta_index++] : state[1]);
    state_plus_delta[2] = (col3  ? state[2] + delta[delta_index++] : state[2]);
    state_plus_delta[3] = (col4  ? state[3] + delta[delta_index++] : state[3]);
    return true;
  }

  virtual int NumEffectiveParameters() const { return num_active_cols_; }
  virtual int NumParameters()          const { return 4; }
  virtual int NumResiduals()           const { return 4; }

 private:
  const int num_active_cols_;
};

// Templated function to hold a subset of the columns fixed and check
// if the solver converges to the optimal values or not.
template<bool col1, bool col2, bool col3, bool col4>
void IsTrustRegionSolveSuccessful(TrustRegionStrategyType strategy_type) {
  Solver::Options solver_options;
  LinearSolver::Options linear_solver_options;
  DenseQRSolver linear_solver(linear_solver_options);

  double parameters[4] = { 3, -1, 0, 1.0 };

  // If the column is inactive, then set its value to the optimal
  // value.
  parameters[0] = (col1 ? parameters[0] : 0.0);
  parameters[1] = (col2 ? parameters[1] : 0.0);
  parameters[2] = (col3 ? parameters[2] : 0.0);
  parameters[3] = (col4 ? parameters[3] : 0.0);

  Minimizer::Options minimizer_options(solver_options);
  minimizer_options.gradient_tolerance = 1e-26;
  minimizer_options.function_tolerance = 1e-26;
  minimizer_options.parameter_tolerance = 1e-26;
  minimizer_options.evaluator.reset(new PowellEvaluator2<col1, col2, col3, col4>);
  minimizer_options.jacobian.reset(minimizer_options.evaluator->CreateJacobian());

  TrustRegionStrategy::Options trust_region_strategy_options;
  trust_region_strategy_options.trust_region_strategy_type = strategy_type;
  trust_region_strategy_options.linear_solver = &linear_solver;
  trust_region_strategy_options.initial_radius = 1e4;
  trust_region_strategy_options.max_radius = 1e20;
  trust_region_strategy_options.min_lm_diagonal = 1e-6;
  trust_region_strategy_options.max_lm_diagonal = 1e32;
  minimizer_options.trust_region_strategy.reset(
      TrustRegionStrategy::Create(trust_region_strategy_options));

  TrustRegionMinimizer minimizer;
  Solver::Summary summary;
  minimizer.Minimize(minimizer_options, parameters, &summary);

  // The minimum is at x1 = x2 = x3 = x4 = 0.
  EXPECT_NEAR(0.0, parameters[0], 0.001);
  EXPECT_NEAR(0.0, parameters[1], 0.001);
  EXPECT_NEAR(0.0, parameters[2], 0.001);
  EXPECT_NEAR(0.0, parameters[3], 0.001);
};

TEST(TrustRegionMinimizer, PowellsSingularFunctionUsingLevenbergMarquardt) {
  // This case is excluded because this has a local minimum and does
  // not find the optimum. This should not affect the correctness of
  // this test since we are testing all the other 14 combinations of
  // column activations.
  //
  //   IsSolveSuccessful<true, true, false, true>();

  const TrustRegionStrategyType kStrategy = LEVENBERG_MARQUARDT;
  IsTrustRegionSolveSuccessful<true,  true,  true,  true >(kStrategy);
  IsTrustRegionSolveSuccessful<true,  true,  true,  false>(kStrategy);
  IsTrustRegionSolveSuccessful<true,  false, true,  true >(kStrategy);
  IsTrustRegionSolveSuccessful<false, true,  true,  true >(kStrategy);
  IsTrustRegionSolveSuccessful<true,  true,  false, false>(kStrategy);
  IsTrustRegionSolveSuccessful<true,  false, true,  false>(kStrategy);
  IsTrustRegionSolveSuccessful<false, true,  true,  false>(kStrategy);
  IsTrustRegionSolveSuccessful<true,  false, false, true >(kStrategy);
  IsTrustRegionSolveSuccessful<false, true,  false, true >(kStrategy);
  IsTrustRegionSolveSuccessful<false, false, true,  true >(kStrategy);
  IsTrustRegionSolveSuccessful<true,  false, false, false>(kStrategy);
  IsTrustRegionSolveSuccessful<false, true,  false, false>(kStrategy);
  IsTrustRegionSolveSuccessful<false, false, true,  false>(kStrategy);
  IsTrustRegionSolveSuccessful<false, false, false, true >(kStrategy);
}

TEST(TrustRegionMinimizer, PowellsSingularFunctionUsingDogleg) {
  // The following two cases are excluded because they encounter a
  // local minimum.
  //
  //  IsTrustRegionSolveSuccessful<true, true, false, true >(kStrategy);
  //  IsTrustRegionSolveSuccessful<true,  true,  true,  true >(kStrategy);

  const TrustRegionStrategyType kStrategy = DOGLEG;
  IsTrustRegionSolveSuccessful<true,  true,  true,  false>(kStrategy);
  IsTrustRegionSolveSuccessful<true,  false, true,  true >(kStrategy);
  IsTrustRegionSolveSuccessful<false, true,  true,  true >(kStrategy);
  IsTrustRegionSolveSuccessful<true,  true,  false, false>(kStrategy);
  IsTrustRegionSolveSuccessful<true,  false, true,  false>(kStrategy);
  IsTrustRegionSolveSuccessful<false, true,  true,  false>(kStrategy);
  IsTrustRegionSolveSuccessful<true,  false, false, true >(kStrategy);
  IsTrustRegionSolveSuccessful<false, true,  false, true >(kStrategy);
  IsTrustRegionSolveSuccessful<false, false, true,  true >(kStrategy);
  IsTrustRegionSolveSuccessful<true,  false, false, false>(kStrategy);
  IsTrustRegionSolveSuccessful<false, true,  false, false>(kStrategy);
  IsTrustRegionSolveSuccessful<false, false, true,  false>(kStrategy);
  IsTrustRegionSolveSuccessful<false, false, false, true >(kStrategy);
}

class CurveCostFunction : public CostFunction {
 public:
  CurveCostFunction(int num_vertices, double target_length)
      : num_vertices_(num_vertices), target_length_(target_length) {
    set_num_residuals(1);
    for (int i = 0; i < num_vertices_; ++i) {
      mutable_parameter_block_sizes()->push_back(2);
    }
  }

  bool Evaluate(double const* const* parameters,
                double* residuals,
                double** jacobians) const {
    residuals[0] = target_length_;

    for (int i = 0; i < num_vertices_; ++i) {
      int prev = (num_vertices_ + i - 1) % num_vertices_;
      double length = 0.0;
      for (int dim = 0; dim < 2; dim++) {
        const double diff = parameters[prev][dim] - parameters[i][dim];
        length += diff * diff;
      }
      residuals[0] -= sqrt(length);
    }

    if (jacobians == NULL) {
      return true;
    }

    for (int i = 0; i < num_vertices_; ++i) {
      if (jacobians[i] != NULL) {
        int prev = (num_vertices_ + i - 1) % num_vertices_;
        int next = (i + 1) % num_vertices_;

        double u[2], v[2];
        double norm_u = 0., norm_v = 0.;
        for (int dim = 0; dim < 2; dim++) {
          u[dim] = parameters[i][dim] - parameters[prev][dim];
          norm_u += u[dim] * u[dim];
          v[dim] = parameters[next][dim] - parameters[i][dim];
          norm_v += v[dim] * v[dim];
        }

        norm_u = sqrt(norm_u);
        norm_v = sqrt(norm_v);

        for (int dim = 0; dim < 2; dim++) {
          jacobians[i][dim] = 0.;

          if (norm_u > std::numeric_limits< double >::min()) {
            jacobians[i][dim] -= u[dim] / norm_u;
          }

          if (norm_v > std::numeric_limits< double >::min()) {
            jacobians[i][dim] += v[dim] / norm_v;
          }
        }
      }
    }

    return true;
  }

 private:
  int     num_vertices_;
  double  target_length_;
};

TEST(TrustRegionMinimizer, JacobiScalingTest) {
  int N = 6;
  std::vector< double* > y(N);
  const double pi = 3.1415926535897932384626433;
  for (int i = 0; i < N; i++) {
    double theta = i * 2. * pi/ static_cast< double >(N);
    y[i] = new double[2];
    y[i][0] = cos(theta);
    y[i][1] = sin(theta);
  }

  Problem problem;
  problem.AddResidualBlock(new CurveCostFunction(N, 10.), NULL, y);
  Solver::Options options;
  options.linear_solver_type = ceres::DENSE_QR;
  Solver::Summary summary;
  Solve(options, &problem, &summary);
  EXPECT_LE(summary.final_cost, 1e-10);

  for (int i = 0; i < N; i++) {
    delete []y[i];
  }
}

}  // namespace internal
}  // namespace ceres


text:
/* eslint-disable import/no-unassigned-import */
import "../../components/dummy-child";
import "../../components/dummy-parent";

import CustomElement, { element } from "@surface/custom-element";
import template                   from "./index.html";
import style                      from "./index.scss";

@element("directives-view", { style, template })
export default class DirectivesView extends CustomElement
{
    private lastId: number = 0;

    protected text:    string  = "";
    protected visible: boolean = true;

    protected items: number[] = [];

    public toogle(): void
    {
        this.visible = !this.visible;
    }

    public increment(): void
    {
        this.items.push(++this.lastId);
    }

    public decrement(): void
    {
        this.lastId--;
        this.items.pop();
    }

    public multiply(): void
    {
        this.items = this.items.map(x => [3, 4, 5].includes(x) ? x : x * 10);
    }
}


text:
const riot = require('gulp-riot');
const gulp = require('gulp');
const concat = require("gulp-concat");
const less = require('gulp-less');
const sourcemaps = require("gulp-sourcemaps");
const through = require('through2');
const uglify = require('gulp-uglify');
const util = require('gulp-util');
const babel = require('gulp-babel');
const ncp = require('ncp');
const path = require("path");
const rev = require('gulp-rev');
const clean = require('gulp-clean');
const execSync = require('child_process').execSync;
const fs = require("fs");
const crypto = require('crypto');

module.exports = function(opts) {
  opts.js = opts.js || {}; // javascript and riot files
  opts.less = opts.less || {}; // css and less
  opts.static = opts.static || []; // files to be directly copied over
  opts.mustache = opts.mustache || []; // mustache templates to be processed
  const build_tasks = ['cp-static','git-version'];
  const results = [];
  for (let key in opts.js) {
    results.push(key + '-built.js');
    build_tasks.push("build-"+key);
    const dirs = key.split("/");
    const name = dirs.pop();
    const dest = path.normalize(opts.DEST+"/"+dirs.join("/"));
    gulp.task('build-'+key, function () {
      if (key == "vendor") { // vendor files are already minified and babel-ifiied
        return gulp.src(opts.js[key]).pipe(concat(key + '-built.js')).pipe(gulp.dest(dest));
      }
      return gulp.src(opts.js[key])
        .pipe(sourcemaps.init())
        .pipe(riot())
        .pipe(babel({
          presets: [ 'es2017' ],
          plugins: [ "transform-object-rest-spread" ],
        }))
        .pipe(concat(name + '-built.js'))
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest(dest))
    });
  }

  for (let key in opts.less) {
    build_tasks.push("build-"+key+"-css");
    results.push(key+'-built.css')
    gulp.task("build-"+key+"-css", function () {
      return gulp.src(opts.less[key])
        .pipe(less({}))
        .pipe(concat(key+'-built.css'))
        .pipe(gulp.dest(opts.DEST));
    });
  }

  gulp.task('clean', function() {
    return gulp.src(opts.DEST+"/*",{read: false})
      .pipe(clean())
  })

  gulp.task("cp-static",function() {
    let DEST = opts.DEST;
    if (!DEST.startsWith("/")) {
      DEST = path.join(__dirname,opts.DEST);
    }
    opts.static.forEach(function(file_or_directory) {
      let source = path.join(__dirname,file_or_directory);
      let dest = path.join(DEST,file_or_directory.replace(/src\//,''));
      ncp(source, dest);
    });
    (opts.renames || []).forEach((r) => {
      ncp(path.join(__dirname,r[0]),path.join(DEST,r[1]));
    });
  });

  gulp.task('build-revision', build_tasks.slice(), function() {
    return gulp.src(results.map(s => path.join(opts.DEST,s)))
      .pipe(rev())
      .pipe(gulp.dest(opts.DEST))
      .pipe(rev.manifest())
      .pipe(gulp.dest(opts.DEST))
  })
  build_tasks.push('build-revision');
  const watch_tasks = ['build-revision','git-version']

  const getGit = () => {
    const md5sum = crypto.createHash('md5');
    const dirty = execSync("git diff").toString().trim();
    return {
      git_hash: execSync("git rev-parse HEAD").toString().trim().slice(0,7),
      dirty: dirty && md5sum.update(dirty).digest('hex').slice(0,7),
    }
  }

  gulp.task("git-version",() => {
    !fs.existsSync(opts.DEST) && fs.mkdirSync(opts.DEST)
    const data = getGit();
    fs.writeFileSync(path.join(opts.DEST,'git-version.js'),JSON.stringify(data))
  })

  if (opts.mustache.length) {
    const mustache = require("gulp-mustache");

    gulp.task("build-mustache",build_tasks.slice(),function() {
      const manifest = JSON.parse(fs.readFileSync(path.join(opts.DEST,"rev-manifest.json")));
      const _package = JSON.parse(fs.readFileSync("package.json"));
      for (let key in manifest) {
        manifest[key.replace("-","").replace(".","")] = manifest[key]
      }
      return gulp.src(opts.mustache)
        .pipe(mustache({
          manifest: manifest,
          DEBUG: opts.environment == "development",
          package: JSON.stringify({
            version: _package.version,
            environment: opts.environment,
            ...getGit(),
          }),
        }))
        .pipe(gulp.dest(opts.DEST));
    });
    build_tasks.push('build-mustache');
    watch_tasks.push('build-mustache');
  }

  gulp.task('watch', ['default'], function() {
    for (let key in opts.js) {
      gulp.watch(opts.js[key], ['build-'+key].concat(watch_tasks))
    }
    for (let key in opts.less) {
      let watch_files = opts.less[key].map((name) => name.match(/.*\//)[0]+"*");
      gulp.watch(watch_files, ['build-'+key+'-css'].concat(watch_tasks))
    }
    gulp.watch(opts.static.map(d => d.replace(/\/$/,"/**")),['cp-static','git-version']);
  });

  gulp.task('default', build_tasks)
  gulp.task('deploy', build_tasks);
}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.action;

import com.intellij.execution.Executor;
import com.intellij.execution.RunManager;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.ide.actions.runAnything.RunAnythingManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.externalSystem.action.ExternalSystemAction;
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys;
import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings;
import com.intellij.openapi.externalSystem.model.execution.ExternalTaskExecutionInfo;
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemNotificationManager;
import com.intellij.openapi.externalSystem.service.notification.NotificationCategory;
import com.intellij.openapi.externalSystem.service.notification.NotificationData;
import com.intellij.openapi.externalSystem.service.notification.NotificationSource;
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
import com.intellij.openapi.externalSystem.view.ExternalProjectsView;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.text.StringUtil;
import org.gradle.cli.CommandLineArgumentException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.util.GradleBundle;
import org.jetbrains.plugins.gradle.util.GradleCommandLine;
import org.jetbrains.plugins.gradle.util.GradleConstants;

import static org.jetbrains.plugins.gradle.execution.GradleRunAnythingProvider.HELP_COMMAND;

/**
 * @author Vladislav.Soroka
 */
public class GradleExecuteTaskAction extends ExternalSystemAction {

  @Override
  protected boolean isVisible(@NotNull AnActionEvent e) {
    if (!super.isVisible(e)) return false;
    final ExternalProjectsView projectsView = e.getData(ExternalSystemDataKeys.VIEW);
    return projectsView == null || GradleConstants.SYSTEM_ID.equals(getSystemId(e));
  }

  @Override
  protected boolean isEnabled(@NotNull AnActionEvent e) {
    return true;
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    Presentation p = e.getPresentation();
    p.setVisible(isVisible(e));
    p.setEnabled(isEnabled(e));
  }

  @Override
  public void actionPerformed(@NotNull final AnActionEvent e) {
    final Project project = e.getProject();
    if (project == null) return;
    RunAnythingManager runAnythingManager = RunAnythingManager.getInstance(project);
    runAnythingManager.show(HELP_COMMAND + " ", false, e);
  }

  public static void runGradle(@NotNull Project project,
                               @Nullable Executor executor,
                               @NotNull String workDirectory,
                               @NotNull @NlsSafe String fullCommandLine) {
    final ExternalTaskExecutionInfo taskExecutionInfo;
    try {
      taskExecutionInfo = buildTaskInfo(workDirectory, fullCommandLine, executor);
    }
    catch (CommandLineArgumentException ex) {
      @NlsSafe String italicFormat = "<i>%s</i> \n";
      final NotificationData notificationData = new NotificationData(
        GradleBundle.message("gradle.command.line.parse.error.invalid.arguments"),
        String.format(italicFormat, fullCommandLine) + ex.getMessage(),
        NotificationCategory.WARNING, NotificationSource.TASK_EXECUTION
      );
      notificationData.setBalloonNotification(true);
      ExternalSystemNotificationManager.getInstance(project).showNotification(GradleConstants.SYSTEM_ID, notificationData);
      return;
    }

    ExternalSystemUtil.runTask(taskExecutionInfo.getSettings(), taskExecutionInfo.getExecutorId(), project, GradleConstants.SYSTEM_ID);

    RunnerAndConfigurationSettings configuration =
      ExternalSystemUtil.createExternalSystemRunnerAndConfigurationSettings(taskExecutionInfo.getSettings(),
                                                                            project, GradleConstants.SYSTEM_ID);
    if (configuration == null) return;

    RunManager runManager = RunManager.getInstance(project);
    final RunnerAndConfigurationSettings existingConfiguration =
      runManager.findConfigurationByTypeAndName(configuration.getType(), configuration.getName());
    if (existingConfiguration == null) {
      runManager.setTemporaryConfiguration(configuration);
    }
    else {
      runManager.setSelectedConfiguration(existingConfiguration);
    }
  }

  private static ExternalTaskExecutionInfo buildTaskInfo(
    @NotNull String projectPath,
    @NotNull String fullCommandLine,
    @Nullable Executor executor
  ) throws CommandLineArgumentException {
    GradleCommandLine commandLine = GradleCommandLine.parse(fullCommandLine);
    ExternalSystemTaskExecutionSettings settings = new ExternalSystemTaskExecutionSettings();
    settings.setExternalProjectPath(projectPath);
    settings.setTaskNames(commandLine.getTasksAndArguments().toList());
    settings.setScriptParameters(commandLine.getScriptParameters().toString());
    settings.setExternalSystemIdString(GradleConstants.SYSTEM_ID.toString());
    return new ExternalTaskExecutionInfo(settings, executor == null ? DefaultRunExecutor.EXECUTOR_ID : executor.getId());
  }
}


text:
var SettingsRoute = Ember.Route.extend({});

export default SettingsRoute;


text:
package org.jetbrains.idea.svn16;

import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.VcsTestUtil;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.LocalChangeList;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.vcs.DuringChangeListManagerUpdateTestScheme;
import junit.framework.Assert;
import org.junit.Test;

import java.util.Collection;

public class SvnConcurrentChangeListManagerTest extends Svn16TestCase {
  private DuringChangeListManagerUpdateTestScheme myScheme;
  private String myDefaulListName;

  @Override
  public void setUp() throws Exception {
    super.setUp();
    myDefaulListName = LocalChangeList.DEFAULT_NAME;

    myScheme = new DuringChangeListManagerUpdateTestScheme(myProject, myTempDirFixture.getTempDirPath());
  }

  @Test
  public void testRenameList() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    changeListManager.ensureUpToDate(false);

    final LocalChangeList list = changeListManager.addChangeList("test", null);
    changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)});

    final String newName = "renamed";

    myScheme.doTest(() -> {
      changeListManager.editName(list.getName(), newName);
      checkFilesAreInList(new VirtualFile[] {file}, newName, changeListManager);
    });

    checkFilesAreInList(new VirtualFile[] {file}, newName, changeListManager);

    changeListManager.ensureUpToDate(false);
    checkFilesAreInList(new VirtualFile[] {file}, newName, changeListManager);
  }

  @Test
  public void testSwitchedFileAndFolder() throws Exception {
    final String branchUrl = prepareBranchesStructure();

    final SubTree tree = new SubTree(myWorkingCopyDir);

    runInAndVerifyIgnoreOutput("switch", branchUrl + "/root/source/s1.txt", tree.myS1File.getPath());
    runInAndVerifyIgnoreOutput("switch", branchUrl + "/root/target", tree.myTargetDir.getPath());

    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
    changeListManager.ensureUpToDate(false);

    final Runnable check = () -> {
      Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myS1File));
      Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File));
      Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir));
      Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir));
      Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1)));
    };
    myScheme.doTest(check);

    changeListManager.ensureUpToDate(false);
    check.run();

    VcsTestUtil.editFileInCommand(myProject, tree.myS1File, "1234543534543 3543 ");
    VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
    changeListManager.ensureUpToDate(false);

    final Runnable check2 = () -> {
      Assert.assertEquals(FileStatus.MODIFIED, changeListManager.getStatus(tree.myS1File));
      Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File));
      Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir));
      Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir));
      Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1)));
    };
    myScheme.doTest(check2);

    changeListManager.ensureUpToDate(false);
    check2.run();
  }

  @Test
  public void testEditComment() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    changeListManager.ensureUpToDate(false);

    final String listName = "test";
    final LocalChangeList list = changeListManager.addChangeList(listName, null);
    changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)});

    final String finalText = "final text";

    myScheme.doTest(() -> {
      final String intermediate = "intermediate text";
      changeListManager.editComment(list.getName(), intermediate);
      assert changeListManager.findChangeList(listName) != null;
      LocalChangeList list1 = changeListManager.findChangeList(listName);
      assert intermediate.equals(list1.getComment());

      changeListManager.editComment(list1.getName(), finalText);
      list1 = changeListManager.findChangeList(listName);
      assert finalText.equals(list1.getComment());
    });

    LocalChangeList changedList = changeListManager.findChangeList(listName);
    assert finalText.equals(changedList.getComment());

    changeListManager.ensureUpToDate(false);
    changedList = changeListManager.findChangeList(listName);
    assert finalText.equals(changedList.getComment());
  }

  @Test
  public void testMove() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    changeListManager.ensureUpToDate(false);

    final LocalChangeList list = changeListManager.addChangeList("test", null);
    final LocalChangeList target = changeListManager.addChangeList("target", null);
    changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)});

    myScheme.doTest(() -> {
      changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)});
      checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager);
    });

    checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager);

    changeListManager.ensureUpToDate(false);
    checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager);
  }

  @Test
  public void testSetActive() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    changeListManager.ensureUpToDate(false);

    final LocalChangeList list = changeListManager.addChangeList("test", null);
    final LocalChangeList target = changeListManager.addChangeList("target", null);
    changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)});

    myScheme.doTest(() -> {
      changeListManager.setDefaultChangeList(target);
      assert changeListManager.getDefaultChangeList().getName().equals(target.getName());
    });

    assert changeListManager.getDefaultChangeList().getName().equals(target.getName());

    changeListManager.ensureUpToDate(false);
    assert changeListManager.getDefaultChangeList().getName().equals(target.getName());
  }

  @Test
  public void testRemove() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final VirtualFile fileB = createFileInCommand("b.txt", "old content");
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    changeListManager.ensureUpToDate(false);

    final LocalChangeList list = changeListManager.addChangeList("test", null);
    changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)});

    myScheme.doTest(() -> {
      changeListManager.removeChangeList(list.getName());
      assert changeListManager.findChangeList(list.getName()) == null;
      checkFilesAreInList(new VirtualFile[] {file, fileB}, myDefaulListName, changeListManager);
    });

    assert changeListManager.findChangeList(list.getName()) == null;
    checkFilesAreInList(new VirtualFile[] {file, fileB}, myDefaulListName, changeListManager);

    changeListManager.ensureUpToDate(false);
    assert changeListManager.findChangeList(list.getName()) == null;
    checkFilesAreInList(new VirtualFile[] {file, fileB}, myDefaulListName, changeListManager);
  }

  @Test
  public void testDoubleMove() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    changeListManager.ensureUpToDate(false);

    final LocalChangeList list = changeListManager.addChangeList("test", null);
    final LocalChangeList target = changeListManager.addChangeList("target", null);
    final LocalChangeList target2 = changeListManager.addChangeList("target2", null);
    changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)});

    myScheme.doTest(() -> {
      changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)});
      checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager);
      changeListManager.moveChangesTo(target2, new Change[] {changeListManager.getChange(file)});
      checkFilesAreInList(new VirtualFile[] {file}, target2.getName(), changeListManager);
    });

    checkFilesAreInList(new VirtualFile[] {file}, target2.getName(), changeListManager);

    changeListManager.ensureUpToDate(false);
    checkFilesAreInList(new VirtualFile[] {file}, target2.getName(), changeListManager);
  }

  @Test
  public void testDoubleMoveBack() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    changeListManager.ensureUpToDate(false);

    final LocalChangeList list = changeListManager.addChangeList("test", null);
    final LocalChangeList target = changeListManager.addChangeList("target", null);
    changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)});

    myScheme.doTest(() -> {
      changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)});
      checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager);
      changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)});
      checkFilesAreInList(new VirtualFile[] {file}, list.getName(), changeListManager);
    });

    checkFilesAreInList(new VirtualFile[] {file}, list.getName(), changeListManager);

    changeListManager.ensureUpToDate(false);
    checkFilesAreInList(new VirtualFile[] {file}, list.getName(), changeListManager);
  }

  @Test
  public void testAddPlusMove() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    changeListManager.ensureUpToDate(false);

    final LocalChangeList list = changeListManager.addChangeList("test", null);
    changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)});

    final String targetName = "target";

    myScheme.doTest(() -> {
      final LocalChangeList target = changeListManager.addChangeList(targetName, null);
      changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)});
      checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager);
    });

    checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager);

    changeListManager.ensureUpToDate(false);
    checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager);
  }

  @Test
  public void testAddListBySvn() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);

    final String targetName = "target";
    // not parralel, just test of correct detection
    runSvn("changelist", targetName, file.getPath());

    VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
    changeListManager.ensureUpToDate(false);
    checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager);
  }

  @Test
  public void testComplex() throws Exception {
    enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
    final VirtualFile file = createFileInCommand("a.txt", "old content");
    final VirtualFile fileB = createFileInCommand("b.txt", "old content");
    final VirtualFile fileC = createFileInCommand("c.txt", "old content");
    final VirtualFile fileD = createFileInCommand("d.txt", "old content");

    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);

    final LocalChangeList list = changeListManager.addChangeList("test", null);
    final LocalChangeList toBeDeletedList = changeListManager.addChangeList("toBeDeletedList", null);
    changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file), changeListManager.getChange(fileB)});
    changeListManager.moveChangesTo(toBeDeletedList, new Change[] {changeListManager.getChange(fileC), changeListManager.getChange(fileD)});
    changeListManager.ensureUpToDate(false);

    final String targetName = "target";
    final String finalName = "final list name";

    myScheme.doTest(() -> {
      final LocalChangeList target = changeListManager.addChangeList(targetName, null);
      changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file), changeListManager.getChange(fileB)});
      checkFilesAreInList(new VirtualFile[] {file, fileB}, targetName, changeListManager);
      changeListManager.editName(targetName, finalName);
      checkFilesAreInList(new VirtualFile[] {file, fileB}, finalName, changeListManager);
      changeListManager.removeChangeList(toBeDeletedList.getName());
      checkFilesAreInList(new VirtualFile[] {fileC, fileD}, myDefaulListName, changeListManager);
      changeListManager.moveChangesTo(LocalChangeList.createEmptyChangeList(myProject, finalName),
                                      new Change[] {changeListManager.getChange(fileC)});
      checkFilesAreInList(new VirtualFile[] {file, fileB, fileC}, finalName, changeListManager);
      checkFilesAreInList(new VirtualFile[] {fileD}, myDefaulListName, changeListManager);
    });

    checkFilesAreInList(new VirtualFile[] {file, fileB, fileC}, finalName, changeListManager);
    checkFilesAreInList(new VirtualFile[] {fileD}, myDefaulListName, changeListManager);

    changeListManager.ensureUpToDate(false);
    checkFilesAreInList(new VirtualFile[] {file, fileB, fileC}, finalName, changeListManager);
    checkFilesAreInList(new VirtualFile[] {fileD}, myDefaulListName, changeListManager);
  }

  private void checkFilesAreInList(final VirtualFile[] files, final String listName, final ChangeListManager manager) {
    System.out.println("Checking files for list: " + listName);
    assert manager.findChangeList(listName) != null;
    final Collection<Change> changes = manager.findChangeList(listName).getChanges();
    assert changes.size() == files.length;

    for (Change change : changes) {
      final VirtualFile vf = change.getAfterRevision().getFile().getVirtualFile();
      boolean found = false;
      for (VirtualFile file : files) {
        if (file.equals(vf)) {
          found = true;
          break;
        }
      }
      assert found == true;
    }
  }
}


text:
package openapi2

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"strings"
)

// Specification represents a Swagger 2.0 specification.
type Specification struct {
	Swagger                        string                          `json:"swagger,omitempty"`
	Host                           string                          `json:"host,omitempty"`
	Info                           *Info                           `json:"info,omitempty"`
	BasePath                       string                          `json:"basePath,omitempty"`
	Schemes                        []string                        `json:"schemes,omitempty"`
	Tags                           []Tag                           `json:"tags,omitempty"`
	Paths                          map[string]Path                 `json:"paths,omitempty"`
	Definitions                    map[string]Definition           `json:"definitions,omitempty"`
	XAmazonApigatewayDocumentation *XAmazonApigatewayDocumentation `json:"x-amazon-apigateway-documentation,omitempty"`
}

// NewSpecificationFromBytes returns a Swagger Specification from a byte array.
func NewSpecificationFromBytes(data []byte) (Specification, error) {
	spec := Specification{}
	err := json.Unmarshal(data, &spec)
	return spec, err
}

/*
// ReadSwagger2Spec returns a Swagger Specification from a filepath.
func ReadSwagger2Spec(filepath string) (Specification, error) {
	bytes, err := ioutil.ReadFile(filepath)
	if err != nil {
		return Specification{}, err
	}
	return NewSpecificationFromBytes(bytes)
}*/

// Info represents a Swagger 2.0 spec info object.
type Info struct {
	Description    string `json:"description,omitempty"`
	Version        string `json:"version,omitempty"`
	Title          string `json:"title,omitempty"`
	TermsOfService string `json:"termsOfService,omitempty"`
}

// Tag represents a Swagger 2.0 spec tag object.
type Tag struct {
	Name         string        `json:"name,omitempty"`
	Description  string        `json:"description,omitempty"`
	ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"`
}

// ExternalDocs represents a Swagger 2.0 spec tag object. The
// URL property is required.
type ExternalDocs struct {
	Description string `json:"description,omitempty"`
	URL         string `json:"url,omitempty"`
}

// Path represents a Swagger 2.0 spec path object.
type Path struct {
	Delete  *Endpoint `json:"delete,omitempty"`
	Get     *Endpoint `json:"get,omitempty"`
	Head    *Endpoint `json:"head,omitempty"`
	Options *Endpoint `json:"options,omitempty"`
	Patch   *Endpoint `json:"patch,omitempty"`
	Post    *Endpoint `json:"post,omitempty"`
	Put     *Endpoint `json:"put,omitempty"`
	Ref     string    `json:"$ref,omitempty"`
}

func (p *Path) HasMethodWithTag(method string) bool {
	switch strings.ToUpper(strings.TrimSpace(method)) {
	case http.MethodGet:
		if p.Get != nil && len(p.Get.Tags) > 0 && len(strings.TrimSpace(p.Get.Tags[0])) > 0 {
			return true
		}
	case http.MethodPatch:
		if p.Patch != nil && len(p.Patch.Tags) > 0 && len(strings.TrimSpace(p.Patch.Tags[0])) > 0 {
			return true
		}
	case http.MethodPost:
		if p.Post != nil && len(p.Post.Tags) > 0 && len(strings.TrimSpace(p.Post.Tags[0])) > 0 {
			return true
		}
	case http.MethodPut:
		if p.Put != nil && len(p.Put.Tags) > 0 && len(strings.TrimSpace(p.Put.Tags[0])) > 0 {
			return true
		}
	case http.MethodDelete:
		if p.Delete != nil && len(p.Delete.Tags) > 0 && len(strings.TrimSpace(p.Delete.Tags[0])) > 0 {
			return true
		}
	}
	return false
}

func (p *Path) SetEndpoint(method string, endpoint Endpoint) error {
	switch strings.ToUpper(strings.TrimSpace(method)) {
	case http.MethodDelete:
		p.Delete = &endpoint
	case http.MethodGet:
		p.Get = &endpoint
	case http.MethodHead:
		p.Head = &endpoint
	case http.MethodOptions:
		p.Options = &endpoint
	case http.MethodPatch:
		p.Patch = &endpoint
	case http.MethodPost:
		p.Post = &endpoint
	case http.MethodPut:
		p.Put = &endpoint

	default:
		return fmt.Errorf("Method [%v] not supported.", method)
	}
	return nil
}

// Endpoint represents a Swagger 2.0 spec endpoint object.
type Endpoint struct {
	Tags                         []string                      `json:"tags,omitempty"`
	Summary                      string                        `json:"summary,omitempty"`
	OperationID                  string                        `json:"operationId,omitempty"`
	Description                  string                        `json:"description,omitempty"`
	Consumes                     []string                      `json:"consumes,omitempty"`
	Produces                     []string                      `json:"produces,omitempty"`
	Parameters                   []Parameter                   `json:"parameters,omitempty"`
	Responses                    map[string]Response           `json:"responses,omitempty"`
	XAmazonApigatewayIntegration *XAmazonApigatewayIntegration `json:"x-amazon-apigateway-integration,omitempty"`
}

func (ep *Endpoint) IsEmpty() bool {
	if len(ep.Tags) > 0 ||
		len(ep.Summary) > 0 ||
		len(ep.OperationID) > 0 ||
		len(ep.Description) > 0 ||
		len(ep.Consumes) > 0 ||
		len(ep.Produces) > 0 ||
		len(ep.Parameters) > 0 ||
		len(ep.Responses) > 0 {
		return false
	}
	return true
}

type Response struct {
	Description string            `json:"description,omitempty"`
	Schema      *Schema           `json:"schema,omitempty"`
	Headers     map[string]Header `json:"headers,omitempty"`
	Examples    map[string]string `json:"examples,omitempty"`
}

type Schema struct {
	Ref string `json:"$ref,omitempty"`
}

type Header struct {
	Type        string `json:"type,omitempty"`
	Description string `json:"description,omitempty"`
}

type Definition struct {
	Type       string              `json:"type,omitempty"`
	Properties map[string]Property `json:"properties,omitempty"`
}

type Property struct {
	Description string `json:"description,omitempty"`
	Format      string `json:"format,omitempty"`
	Items       *Items `json:"items,omitempty"`
	Type        string `json:"type,omitempty"`
	Ref         string `json:"$ref,omitempty"`
}

type Items struct {
	Type string `json:"type,omitempty"`
	Ref  string `json:"$ref,omitempty"`
}

func (items *Items) IsEmpty() bool {
	if len(strings.TrimSpace(items.Type)) == 0 && len(strings.TrimSpace(items.Ref)) == 0 {
		return true
	}
	return false
}

type XAmazonApigatewayIntegration struct {
	Responses           map[string]XAmazonApigatewayIntegrationResponse `json:"responses,omitempty"`
	PassthroughBehavior string                                          `json:"passthroughBehavior,omitempty"`
	RequestTemplates    map[string]string                               `json:"requestTemplates,omitempty"`
	Type                string                                          `json:"type,omitempty"`
}

type XAmazonApigatewayIntegrationResponse struct {
	StatusCode         string            `json:"statusCode,omitempty"`
	ResponseParameters map[string]string `json:"responseParameters,omitempty"`
	ResponseTemplates  map[string]string `json:"responseTemplates,omitempty"`
}

type XAmazonApigatewayDocumentation struct {
	Version            string              `json:"version,omitempty"`
	CreatedDate        string              `json:"createdDate,omitempty"`
	DocumentationParts []DocumentationPart `json:"documentationParts,omitempty"`
}

type DocumentationPart struct {
	Location   XAmazonApigatewayDocumentationPartLocation   `json:"location,omitempty"`
	Properties XAmazonApigatewayDocumentationPartProperties `json:"properties,omitempty"`
}

type XAmazonApigatewayDocumentationPartLocation struct {
	Type       string `json:"type,omitempty"`
	Method     string `json:"method,omitempty"`
	Path       string `json:"path,omitempty"`
	StatusCode string `json:"statusCode,omitempty"`
	Name       string `json:"name,omitempty"`
}

type XAmazonApigatewayDocumentationPartProperties struct {
	Tags        []string                                `json:"tags,omitempty"`
	Summary     string                                  `json:"summary,omitempty"`
	Description string                                  `json:"description,omitempty"`
	Info        *XAmazonApigatewayDocumentationPartInfo `json:"info,omitempty"`
}

type XAmazonApigatewayDocumentationPartInfo struct {
	Description string `json:"description,omitempty"`
}

// Parameter represents a Swagger 2.0 spec parameter object.
type Parameter struct {
	Name             string            `json:"name,omitempty"`
	Type             string            `json:"type,omitempty"`
	In               string            `json:"in,omitempty"`
	Description      string            `json:"description,omitempty"`
	Schema           *Schema           `json:"schema,omitempty"`
	Required         bool              `json:"required,omitempty"`
	CollectionFormat string            `json:"collectionFormat,omitempty"`
	Items            *Items            `json:"items,omitempty"`
	Default          interface{}       `json:"default,omitempty"`
	XExamples        map[string]string `json:"x-examples,omitempty"`
}

func GetJsonBodyParameterExampleForKey(params []Parameter, exampleKey string) (string, error) {
	exampleKey = strings.TrimSpace(exampleKey)
	if len(exampleKey) == 0 {
		return "", errors.New("exampleKey is empty")
	}
	for _, param := range params {
		if strings.ToLower(strings.TrimSpace(param.In)) != "body" {
			continue
		}
		if len(param.XExamples) == 0 {
			return "", fmt.Errorf("No `x-examples` in param name [%s]", param.Name)
		}
		if example, ok := param.XExamples[exampleKey]; !ok {
			return "", fmt.Errorf("no `x-examples` key [%s] in param name [%s]", exampleKey, param.Name)
		} else {
			return example, nil
		}
	}
	return "", fmt.Errorf("No `in=body` param in [%d] count params]", len(params))
}


text:
var mongoose = require('mongoose');

var reportSchema = mongoose.Schema({
	// id: Schema.ObjectId,
	description: String,
	createdAt: Date,
	date: Date,
	time: Date,
	busLine: String,
	transportCompany: String,
	location: {
		coords:{
			lat: Number,
			lon: Number,
		},
		city: String,
		address: String
	},
	complaint: String,
	name: String,
	email: String,
	telephone: String,
	images: [String],
	note: String
});

module.exports = mongoose.model('Report', reportSchema);


text:
/*!
 * \file dot.cc
 * \brief CPU Implementation of matrix dot
 */

#include "./dot-inl.h"

namespace mxnet {
namespace op {
DMLC_REGISTER_PARAMETER(DotParam);

NNVM_REGISTER_OP(dot)
MXNET_ADD_SPARSE_OP_ALIAS(dot)
.describe(R"doc(Dot product of two arrays.

``dot``'s behavior depends on the input array dimensions:

- 1-D arrays: inner product of vectors
- 2-D arrays: matrix multiplication
- N-D arrays: a sum product over the last axis of the first input and the first
  axis of the second input

  For example, given 3-D ``x`` with shape `(n,m,k)` and ``y`` with shape `(k,r,s)`, the
  result array will have shape `(n,m,r,s)`. It is computed by::

    dot(x,y)[i,j,a,b] = sum(x[i,j,:]*y[:,a,b])

  Example::

    x = reshape([0,1,2,3,4,5,6,7], shape=(2,2,2))
    y = reshape([7,6,5,4,3,2,1,0], shape=(2,2,2))
    dot(x,y)[0,0,1,1] = 0
    sum(x[0,0,:]*y[:,1,1]) = 0

The storage type of ``dot`` output depends on storage types of inputs, transpose option and
forward_stype option for output storage type. Implemented sparse operations include:

- dot(default, default, transpose_a=True/False, transpose_b=True/False) = default
- dot(csr, default, transpose_a=True) = default
- dot(csr, default, transpose_a=True) = row_sparse
- dot(csr, default) = default
- dot(csr, row_sparse) = default
- dot(default, csr) = csr (CPU only)
- dot(default, csr, forward_stype='default') = default
- dot(default, csr, transpose_b=True, forward_stype='default') = default

If the combination of input storage types and forward_stype does not match any of the
above patterns, ``dot`` will fallback and generate output with default storage.

.. Note::

    If the storage type of the lhs is "csr", the storage type of gradient w.r.t rhs will be
    "row_sparse". Only a subset of optimizers support sparse gradients, including SGD, AdaGrad
    and Adam. Note that by default lazy updates is turned on, which may perform differently
    from standard updates. For more details, please check the Optimization API at:
    https://mxnet.incubator.apache.org/api/python/optimization/optimization.html

)doc" ADD_FILELINE)
.set_num_inputs(2)
.set_num_outputs(1)
.set_attr_parser(ParamParser<DotParam>)
.set_attr<nnvm::FListInputNames>("FListInputNames",
  [](const NodeAttrs& attrs) {
    return std::vector<std::string>{"lhs", "rhs"};
  })
.set_attr<mxnet::FInferShape>("FInferShape", DotShape)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>)
.set_attr<FInferStorageType>("FInferStorageType", DotForwardInferStorageType)
.set_attr<FResourceRequest>("FResourceRequest",
  [](const NodeAttrs& attrs) {
    return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
  })
.set_attr<FCompute>("FCompute<cpu>", DotForward_<cpu>)
.set_attr<FComputeEx>("FComputeEx<cpu>", DotForwardEx<cpu>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_dot"})
.add_argument("lhs", "NDArray-or-Symbol", "The first input")
.add_argument("rhs", "NDArray-or-Symbol", "The second input")
.add_arguments(DotParam::__FIELDS__());

NNVM_REGISTER_OP(_backward_dot)
.set_num_inputs(3)
.set_num_outputs(2)
.set_attr_parser(ParamParser<DotParam>)
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
.set_attr<FInferStorageType>("FInferStorageType", DotBackwardInferStorageType)
.set_attr<FResourceRequest>("FResourceRequest",
  [](const NodeAttrs& attrs) {
    return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
  })
.set_attr<FCompute>("FCompute<cpu>", DotBackward_<cpu>)
.set_attr<FComputeEx>("FComputeEx<cpu>", DotBackwardEx<cpu>)
.add_arguments(DotParam::__FIELDS__());

NNVM_REGISTER_OP(batch_dot)
.describe(R"doc(Batchwise dot product.

``batch_dot`` is used to compute dot product of ``x`` and ``y`` when ``x`` and
``y`` are data in batch, namely 3D arrays in shape of `(batch_size, :, :)`.

For example, given ``x`` with shape `(batch_size, n, m)` and ``y`` with shape
`(batch_size, m, k)`, the result array will have shape `(batch_size, n, k)`,
which is computed by::

   batch_dot(x,y)[i,:,:] = dot(x[i,:,:], y[i,:,:])

)doc" ADD_FILELINE)
.set_num_inputs(2)
.set_num_outputs(1)
.set_attr_parser(ParamParser<DotParam>)
.set_attr<nnvm::FListInputNames>("FListInputNames",
  [](const NodeAttrs& attrs) {
    return std::vector<std::string>{"lhs", "rhs"};
  })
.set_attr<mxnet::FInferShape>("FInferShape", BatchDotShape)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>)
.set_attr<FResourceRequest>("FResourceRequest",
  [](const NodeAttrs& attrs) {
    return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
  })
.set_attr<FCompute>("FCompute<cpu>", BatchDotForward_<cpu>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_batch_dot"})
.add_argument("lhs", "NDArray-or-Symbol", "The first input")
.add_argument("rhs", "NDArray-or-Symbol", "The second input")
.add_arguments(DotParam::__FIELDS__());

NNVM_REGISTER_OP(_backward_batch_dot)
.set_num_inputs(3)
.set_num_outputs(2)
.set_attr_parser(ParamParser<DotParam>)
.set_attr<FResourceRequest>("FResourceRequest",
  [](const NodeAttrs& attrs) {
    return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
  })
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
.set_attr<FCompute>("FCompute<cpu>", BatchDotBackward_<cpu>);

}  // namespace op
}  // namespace mxnet


text:
<Widget xmlns="sx.widgets">

    <Widget id="dips" left="10dip" />
    <Widget id="pixels" left="10px" />
    <Widget id="percents" left="10%" />
    <Widget id="negative" left="-50%" />

</Widget>


text:
include(FindPackageHandleStandardArgs)

if(DEFINED ENV{CUDNN_ROOT_DIR})
  set(CUDNN_ROOT_DIR $ENV{CUDNN_ROOT_DIR})
else()
  set(CUDNN_ROOT_DIR "" CACHE PATH "Folder contains NVIDIA cuDNN")
endif()

if(DEFINED ENV{CUDNN_INCLUDE_DIR})
  set(CUDNN_INCLUDE_DIR $ENV{CUDNN_INCLUDE_DIR})
else()
  find_path(CUDNN_INCLUDE_DIR cudnn.h
    HINTS ${CUDNN_ROOT_DIR} ${CUDA_TOOLKIT_ROOT_DIR}
    PATH_SUFFIXES cuda/include include)
endif()

if(DEFINED ENV{USE_STATIC_CUDNN})
  MESSAGE(STATUS "USE_STATIC_CUDNN detected. Linking against static CUDNN library")
  set(CUDNN_LIBNAME "libcudnn_static.a")
else()
  set(CUDNN_LIBNAME "cudnn")
endif()

if(DEFINED ENV{CUDNN_LIBRARY})
  SET(CUDNN_LIBRARY $ENV{CUDNN_LIBRARY})
else()
  find_library(CUDNN_LIBRARY ${CUDNN_LIBNAME}
    HINTS ${CUDNN_LIB_DIR} ${CUDNN_ROOT_DIR} ${CUDA_TOOLKIT_ROOT_DIR}
    PATH_SUFFIXES lib lib64 cuda/lib cuda/lib64 lib/x64)
endif()

if(CUDNN_INCLUDE_DIR AND CUDNN_LIBRARY)
	# get cuDNN version
  file(READ ${CUDNN_INCLUDE_DIR}/cudnn.h CUDNN_HEADER_CONTENTS)
	string(REGEX MATCH "define CUDNN_MAJOR * +([0-9]+)"
				 CUDNN_VERSION_MAJOR "${CUDNN_HEADER_CONTENTS}")
	string(REGEX REPLACE "define CUDNN_MAJOR * +([0-9]+)" "\\1"
				 CUDNN_VERSION_MAJOR "${CUDNN_VERSION_MAJOR}")
	string(REGEX MATCH "define CUDNN_MINOR * +([0-9]+)"
				 CUDNN_VERSION_MINOR "${CUDNN_HEADER_CONTENTS}")
	string(REGEX REPLACE "define CUDNN_MINOR * +([0-9]+)" "\\1"
				 CUDNN_VERSION_MINOR "${CUDNN_VERSION_MINOR}")
	string(REGEX MATCH "define CUDNN_PATCHLEVEL * +([0-9]+)"
				 CUDNN_VERSION_PATCH "${CUDNN_HEADER_CONTENTS}")
	string(REGEX REPLACE "define CUDNN_PATCHLEVEL * +([0-9]+)" "\\1"
				 CUDNN_VERSION_PATCH "${CUDNN_VERSION_PATCH}")
  # Assemble cuDNN version
  if(NOT CUDNN_VERSION_MAJOR)
    set(CUDNN_VERSION "?")
  else()
    set(CUDNN_VERSION "${CUDNN_VERSION_MAJOR}.${CUDNN_VERSION_MINOR}.${CUDNN_VERSION_PATCH}")
  endif()

  set(CUDNN_INCLUDE_DIRS ${CUDNN_INCLUDE_DIR})
  set(CUDNN_LIBRARIES ${CUDNN_LIBRARY})
  message(STATUS "Found cuDNN: v${CUDNN_VERSION}  (include: ${CUDNN_INCLUDE_DIR}, library: ${CUDNN_LIBRARY})")
  mark_as_advanced(CUDNN_ROOT_DIR CUDNN_LIBRARY CUDNN_INCLUDE_DIR)
endif()

find_package_handle_standard_args(
    CuDNN
    VERSION_VAR CUDNN_VERSION
    REQUIRED_VARS CUDNN_INCLUDE_DIR CUDNN_LIBRARY
    FAIL_MESSAGE "Failed to find cuDNN in path: ${CUDNN_ROOT_DIR} (Did you set CUDNN_ROOT_DIR properly?)"
)


text:
class Basis < ActiveRecord::Migration
  def change

  create_table "breaches", force: true do |t|
    t.integer  "playground_id"
    t.integer  "business_rule_id"
    t.integer  "application_id"
    t.text     "pk_values"
    t.integer  "business_object_id"
    t.integer  "record_id"
    t.integer  "period_id"
    t.integer  "organisation_id"
    t.integer  "territory_id"
    t.string   "name"
    t.text     "description"
    t.integer  "breach_type_id"
    t.integer  "breach_status_id"
    t.string   "message_source"
    t.string   "object_name"
    t.text     "observation"
    t.text     "error_message"
    t.text     "current_values"
    t.text     "proposed_values"
    t.boolean  "is_whitelisted"
    t.date     "opened_at"
    t.date     "expected_at"
    t.date     "closed_at"
    t.integer  "responsible_id"
    t.integer  "requestor_id"
    t.integer  "approver_id"
    t.datetime "approved_at"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "business_areas", force: true do |t|
    t.integer  "playground_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.string   "hierarchy"
    t.string   "pcf_index"
    t.string   "pcf_reference"
    t.integer  "status_id"
    t.integer  "owner_id"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
  end

  add_index "business_areas", ["code"], name: "index_business_areas_on_code", unique: true, using: :btree
  add_index "business_areas", ["name"], name: "index_business_areas_on_name", unique: true, using: :btree

  create_table "business_flows", force: true do |t|
    t.integer  "playground_id"
    t.integer  "business_area_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.string   "hierarchy"
    t.string   "pcf_index"
    t.string   "pcf_reference"
    t.integer  "status_id"
    t.integer  "owner_id"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false
  end

  create_table "business_objects", force: true do |t|
    t.integer  "playground_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.integer  "organisation_level"
    t.integer  "territory_level"
    t.string   "hierarchy"
    t.integer  "status_id"
    t.integer  "owner_id"
    t.string   "db_technology"
    t.string   "db_connection"
    t.string   "db_owner_schema"
    t.string   "structure_name"
    t.text     "key_columns"
    t.text     "published_columns"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
    t.integer  "business_area_id"
  end

  create_table "business_processes", force: true do |t|
    t.integer  "playground_id"
    t.integer  "business_flow_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.string   "hierarchy"
    t.string   "pcf_index"
    t.string   "pcf_reference"
    t.integer  "status_id"
    t.integer  "owner_id"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false
  end

  create_table "business_rules", force: true do |t|
    t.integer  "playground_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.text     "business_value"
    t.string   "hierarchy"
    t.integer  "status_id"
    t.integer  "owner_id"
    t.text     "check_description"
    t.text     "check_script"
    t.text     "correction_method"
    t.text     "correction_script"
    t.string   "correction_batch"
    t.text     "white_list"
    t.text     "condition"
    t.decimal  "added_value"
    t.decimal  "maintenance_cost"
    t.decimal  "maintenance_duration"
    t.string   "version"
    t.integer  "approver_id"
    t.datetime "approved_at"
    t.integer  "business_process_id"
    t.integer  "business_object_id"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",           null: false
    t.datetime "updated_at",           null: false
    t.integer  "rule_type_id"
    t.integer  "severity_id"
    t.integer  "complexity_id"
  end

  create_table "data_policies", force: true do |t|
    t.integer  "playground_id"
    t.integer  "landscape_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.text     "organisations_list"
    t.text     "territories_list"
    t.text     "business_rules_list"
    t.text     "date_limitations"
    t.text     "policy_matrix"
    t.string   "status_id"
    t.string   "owner_id"
    t.datetime "active_from"
    t.datetime "active_to"
    t.integer  "scope_id"
    t.integer  "business_process_id"
    t.integer  "approver_id"
    t.datetime "approved_at"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
  end

  create_table "landscapes", force: true do |t|
    t.integer  "playground_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.string   "hierarchy"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
    t.integer  "status_id"
    t.integer  "owner_id"
  end

  create_table "mappings", force: true do |t|
    t.integer  "playground_id"
    t.integer  "mappings_list_id"
    t.string   "source_software"
    t.string   "source_table"
    t.string   "source_value_id"
    t.string   "source_code"
    t.string   "target_software"
    t.string   "target_table"
    t.string   "target_value_id"
    t.string   "target_code"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "source_caption"
    t.string   "target_caption"
    t.integer  "owner_id"
  end

  create_table "mappings_lists", force: true do |t|
    t.integer  "playground_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.string   "created_by"
    t.string   "updated_by"
    t.integer  "owner_id"
    t.integer  "source_list_id"
    t.integer  "target_list_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "organisations", force: true do |t|
    t.integer  "playground_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.integer  "organisation_level"
    t.string   "hierarchy"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
    t.integer  "status_id"
    t.integer  "owner_id"
    t.integer  "parent_id"
  end

  create_table "parameters", force: true do |t|
    t.integer  "playground_id"
    t.string   "name"
    t.text     "description"
    t.datetime "active_from"
    t.datetime "active_to"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "parent_list"
    t.string   "param_value"
    t.integer  "parameters_list_id"
    t.string   "param_code"
  end

  add_index "parameters", ["name"], name: "index_parameters_on_name", using: :btree

  create_table "parameters_lists", force: true do |t|
    t.integer  "playground_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.string   "created_by"
    t.string   "updated_by"
    t.integer  "owner_id"
    t.boolean  "is_user_specific"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "playgrounds", force: true do |t|
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.string   "hierarchy"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "status_id"
    t.integer  "owner_id"
  end

  create_table "roles", force: true do |t|
    t.integer  "playground_id"
    t.integer  "code"
    t.string   "role"
    t.datetime "active_from"
    t.datetime "active_to"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
  end

  create_table "scopes", force: true do |t|
    t.integer  "playground_id"
    t.integer  "landscape_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.text     "SQL_query"
    t.string   "load_interface"
    t.integer  "organisation_level"
    t.integer  "territory_level"
    t.integer  "business_object_id"
    t.integer  "business_process_id"
    t.string   "hierarchy"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",              null: false
    t.datetime "updated_at",              null: false
    t.integer  "status_id"
    t.integer  "owner_id"
  end

  create_table "territories", force: true do |t|
    t.integer  "playground_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.integer  "territory_level"
    t.string   "hierarchy"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.integer  "status_id"
    t.integer  "owner_id"
    t.integer  "parent_id"
  end

  create_table "time_scales", force: true do |t|
    t.integer  "playground_id"
    t.integer  "day_number"
    t.integer  "day_of_week"
    t.integer  "day_of_month"
    t.integer  "day_of_year"
    t.integer  "week_number"
    t.integer  "week_of_month"
    t.integer  "week_of_year"
    t.integer  "month_number"
    t.integer  "month_of_year"
    t.integer  "quarter_number"
    t.integer  "quarter"
    t.integer  "semester_number"
    t.integer  "semester"
    t.integer  "year_number"
    t.integer  "year"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

  create_table "user_accesses", force: true do |t|
    t.integer  "playground_id"
    t.integer  "user_id"
    t.integer  "organisation_id"
    t.integer  "territory_id"
    t.integer  "business_area_id"
    t.integer  "business_flow_id"
    t.integer  "business_process_id"
    t.integer  "business_object_id"
    t.text     "description"
    t.integer  "organisation_level"
    t.integer  "territory_level"
    t.datetime "active_from"
    t.datetime "active_to"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
  end

  create_table "user_roles", force: true do |t|
    t.integer  "playground_id"
    t.integer  "user_id"
    t.string   "role_id"
    t.datetime "active_from"
    t.datetime "active_to"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
  end

  create_table "users", force: true do |t|
    t.integer  "playground_id"
    t.integer  "default_playground_id"
    t.integer  "current_playground_id"
    t.integer  "current_landscape_id"
    t.string   "directory_id"
    t.string   "login"
    t.string   "email"
    t.string   "first_name"
    t.string   "last_name"
    t.text     "description"
    t.datetime "active_from"
    t.datetime "active_to"
    t.boolean  "is_admin"
    t.string   "password_digest"
    t.string   "remember_token"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at",            null: false
    t.datetime "updated_at",            null: false
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["login"], name: "index_users_on_login", unique: true, using: :btree
  add_index "users", ["remember_token"], name: "index_users_on_remember_token", using: :btree

  create_table "values", force: true do |t|
    t.integer  "playground_id"
    t.integer  "values_list_id"
    t.string   "name"
    t.text     "description"
    t.string   "value_code"
    t.string   "value_caption"
    t.string   "created_by"
    t.string   "updated_by"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "values_lists", force: true do |t|
    t.integer  "playground_id"
    t.string   "code"
    t.string   "name"
    t.text     "description"
    t.string   "created_by"
    t.string   "updated_by"
    t.integer  "owner_id"
    t.string   "table_name"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "software_id"
    t.string   "software_name"
  end

  end
end


text:
<?php
namespace Chamilo\Core\Repository\Quota\Rights\Table\Entity;

use Chamilo\Core\Repository\Quota\Rights\Manager;
use Chamilo\Core\Rights\Entity\PlatformGroupEntity;
use Chamilo\Core\Rights\Entity\UserEntity;
use Chamilo\Libraries\Format\Structure\Toolbar;
use Chamilo\Libraries\Format\Structure\ToolbarItem;
use Chamilo\Libraries\Format\Table\Extension\DataClassTable\DataClassTableCellRenderer;
use Chamilo\Libraries\Format\Table\Interfaces\TableCellRendererActionsColumnSupport;
use Chamilo\Libraries\Format\Theme;
use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Utilities\Utilities;

class EntityTableCellRenderer extends DataClassTableCellRenderer implements TableCellRendererActionsColumnSupport
{

    public function render_cell($column, $object)
    {
        switch ($column->get_name())
        {
            case Translation::get('Type') :
                $location_entity_right = $object->get_location_entity_right();

                switch ($location_entity_right->get_entity_type())
                {
                    case UserEntity::ENTITY_TYPE :
                        $context = \Chamilo\Core\User\Storage\DataClass\User::context();
                        break;
                    case PlatformGroupEntity::ENTITY_TYPE :
                        $context = \Chamilo\Core\Group\Storage\DataClass\Group::context();
                        break;
                }

                return Theme::getInstance()->getImage(
                    'Logo/16',
                    'png',
                    Translation::get('TypeName', null, $context),
                    null,
                    ToolbarItem::DISPLAY_ICON,
                    false,
                    $context);
            case Translation::get('Entity') :
                $location_entity_right = $object->get_location_entity_right();
                switch ($location_entity_right->get_entity_type())
                {
                    case UserEntity::ENTITY_TYPE :
                        return \Chamilo\Core\User\Storage\DataManager::retrieve_by_id(
                            \Chamilo\Core\User\Storage\DataClass\User::class_name(),
                            (int) $location_entity_right->get_entity_id())->get_fullname();
                    case PlatformGroupEntity::ENTITY_TYPE :
                        return \Chamilo\Core\Group\Storage\DataManager::retrieve_by_id(
                            \Chamilo\Core\Group\Storage\DataClass\Group::class_name(),
                            (int) $location_entity_right->get_entity_id())->get_name();
                }
            case Translation::get('Group') :
                return $object->get_group()->get_name();
            case Translation::get('Path') :
                return $object->get_group()->get_fully_qualified_name();
        }

        return parent::render_cell($column, $object);
    }

    public function get_actions($object)
    {
        $toolbar = new Toolbar();

        if ($this->get_component()->get_user()->is_platform_admin())
        {
            $toolbar->add_item(
                new ToolbarItem(
                    Translation::get('Delete', null, Utilities::COMMON_LIBRARIES),
                    Theme::getInstance()->getCommonImagePath('Action/Delete'),
                    $this->get_component()->get_url(
                        array(
                            Manager::PARAM_ACTION => Manager::ACTION_DELETE,
                            Manager::PARAM_LOCATION_ENTITY_RIGHT_GROUP_ID => $object->get_id())),
                    ToolbarItem::DISPLAY_ICON));
        }

        return $toolbar->as_html();
    }
}


text:
<?php

declare(strict_types=1);

namespace Symplify\EasyCodingStandard\SniffRunner\Tests\File;

use PHP_CodeSniffer\Files\File as PhpCodeSnifferFile;
use PHP_CodeSniffer\Fixer;
use Symplify\EasyCodingStandard\HttpKernel\EasyCodingStandardKernel;
use Symplify\EasyCodingStandard\SniffRunner\File\FileFactory;
use Symplify\EasyCodingStandard\SniffRunner\ValueObject\File;
use Symplify\PackageBuilder\Tests\AbstractKernelTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;

final class FileFactoryTest extends AbstractKernelTestCase
{
    /**
     * @var FileFactory
     */
    private $fileFactory;

    protected function setUp(): void
    {
        $this->bootKernel(EasyCodingStandardKernel::class);
        $this->fileFactory = self::$container->get(FileFactory::class);
    }

    public function test(): void
    {
        $fileInfo = new SmartFileInfo(__DIR__ . '/FileFactorySource/SomeFile.php');
        $file = $this->fileFactory->createFromFileInfo($fileInfo);
        $this->assertInstanceOf(File::class, $file);
        $this->assertInstanceOf(PhpCodeSnifferFile::class, $file);
        $this->assertInstanceOf(Fixer::class, $file->fixer);
    }
}


text:
package com.edgar.assertj.guava;

import static org.assertj.guava.api.Assertions.assertThat;
import java.io.IOException;

import com.edgar.assertj.AbstractAssertionsExamples;
import org.junit.Test;
import com.google.common.io.ByteSource;
/**
* {@link ByteSource} assertions example.
*
* @author Andrew Gaul
*/
public class ByteSourceAssertionsExamples extends AbstractAssertionsExamples {
@Test
public void bytesource_assertions_examples() throws IOException {
int size = 1;
ByteSource actual = ByteSource.wrap(new byte[size]);
assertThat(actual).hasSize(size);
assertThat(actual).hasSameContentAs(ByteSource.wrap(new byte[size]));
ByteSource emptyByteSource = ByteSource.wrap(new byte[0]);
assertThat(emptyByteSource).isEmpty();
}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CQLQuery xmlns="http://CQL.caBIG/1/gov.nih.nci.cagrid.CQLQuery">
    <Target name="edu.wustl.catissuecore.domain.Participant" />
    <QueryModifier countOnly="false">
        <AttributeNames>lastName</AttributeNames>
        <AttributeNames>sexGenotype</AttributeNames>
		<AttributeNames>id</AttributeNames>
    </QueryModifier>
</CQLQuery>


text:
var path = require('path');

function isNodeModule(name) {
  return name[0] !== '.';
}

function makeAddStaticModule(scope) {
  return function addStaticModule(name, content) {
    var module = scope.modules.get(name);

    if (!module) {
      module = content
    }

    scope.modules.add(name, module);

    return scope.modules.get(name);
  }
}

module.exports = function overrideRequire(scope, req, filename) {
  var addStaticModule = makeAddStaticModule(scope);

  return function overrideRequire(name) {
    if (isNodeModule(name)) {
      return addStaticModule(name, req(name));
    }

    var fullName = path.resolve(path.dirname(filename), name);

    if (fullName.indexOf(scope.baseDir) === 0) {
      fullName = fullName.slice(scope.baseDir.length);
    }

    // Try to find stored proxy by name
    var proxy = scope.proxies.get(fullName);

    // If succeeded, return proxied component
    if (proxy) {
      return proxy.get();
    }

    // Otherwise try to include a module
    if (module = scope.modules.get(fullName || name)) {
      return module;
    }

    var module = req(name);

    // And then proxy it
    proxy = scope.proxies.add(fullName, module);

    if (proxy) {
      return proxy.get();
    }

    // if it's not proxible, add it to static
    addStaticModule(fullName, module);

    return module;
  };
};


text:
/**
 * The sources model.
 */
@Namespace ( prefix = "gx", reference = GedcomxConstants.GEDCOMX_NAMESPACE )
package org.gedcomx.source;

import org.gedcomx.rt.GedcomxConstants;
import org.simpleframework.xml.Namespace;


text:
module DropboxStore

	module Datastores

		#
		#  List all datastores
		#
		def self.list(ctx)
			result = DropboxStore::message(ctx, 'datastores/list_datastores')
			raise result["error"] if result["error"]

			return {
			  names: result["datastores"].collect { |store| store["dsid"] },
			  stores: result["datastores"]
			}
		end

		#
		#  Get a handle to a datastore with name 'dsid'
		#
		def self.get(ctx, dsid)
			result = DropboxStore::message(ctx, 'datastores/get_datastore', { :dsid => dsid })

			raise result["notfound"] if result["notfound"]

			ctx.active_store = {
				dsid: dsid,
				rev: result['rev'],
				handle: result['handle']
			}
		end

		#
		# 	Create a local datastore (user-specific) with name 'dsid'
		#
		def self.create_local(ctx, dsid, &block)
			result = DropboxStore::message(ctx, 'datastores/get_or_create_datastore', { :dsid => dsid })

			if !result["rev"] then
				raise "Unable to create local database #{dsid}, server response: #{result.inspect}"
			end

			if result["created"] and block then
				yield ctx
			end

			ctx.active_store = {
				dsid: dsid,
				rev: result['rev'],
				handle: result['handle']
			}
		end

		#
		#   Create a global datastore (application specific) with name 'dsid'
		#
		def self.create_global(ctx, dsid, &block)
			result = DropboxStore::message(ctx, 'datastores/create_datastore', { :dsid => dsid })

			if !result["rev"] then
				raise "Unable to create global database #{dsid}, server response: #{result.inspect}"
			end

			if result["created"] and block then
				yield ctx
			end

			ctx.active_store = {
				dsid: dsid,
				rev: result['rev'],
				handle: result['handle']
			}

		end

		#
		#   Delete a data-store
		#
		def self.delete(ctx, names)

			names = [names].flatten

			stores = list(ctx)

			names.each do |dsid|
				store_with_id = stores[:stores].find { |s_info| s_info["dsid"] == dsid }
				if not store_with_id then
					raise "no datastore with dsid `#{dsid}` found"
				end

				handle = store_with_id["handle"]
				result = DropboxStore::message(ctx, 'datastores/delete_datastore', { :handle => handle })
				raise result["notfound"] if result["notfound"]

				# unset active store if we just deleted our current one
				if ctx.active_store and ctx.active_store[:dsid] == dsid then
					ctx.active_store = nil
				end
			end

			true
		end

	end

end


text:
//-----------------------------------------------------------------------
// <copyright file="TraceLogger.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System.Diagnostics;
using Akka.Actor;

namespace Akka.Event
{
    /// <summary>
    /// This class represents an event logger that logs its messages using a configured trace listener.
    ///
    /// <remarks>
    /// To use activate this logger, modify the loggers section in your Akka.NET configuration like so,
    ///
    /// <code>
    /// akka {
    ///   ...
    ///   loggers = [""Akka.Event.TraceLogger, Akka""]
    ///   ...
    /// }
    /// </code>
    ///
    /// Further configuration may be required in your main configuration (e.g. app.config or web.config)
    /// to properly set up the trace. See <see href="https://msdn.microsoft.com/en-us/library/zs6s4h68.aspx">here</see>
    /// for more information regarding .NET tracing.
    /// </remarks>
    /// </summary>
    public class TraceLogger : UntypedActor
    {
        protected override void OnReceive(object message)
        {
            message.Match()
                 .With<InitializeLogger>(m => Sender.Tell(new LoggerInitialized()))
                 .With<Error>(m => Trace.TraceError(m.ToString()))
                 .With<Warning>(m => Trace.TraceWarning(m.ToString()))
                 .With<DeadLetter>(m => Trace.TraceWarning(string.Format("Deadletter - unable to send message {0} from {1} to {2}", m.Message, m.Sender, m.Sender), typeof(DeadLetter).ToString()))
                 .With<UnhandledMessage>(m => Trace.TraceWarning("Unhandled message!"))
                 .Default(m =>
                 {
                     if (m != null)
                         Trace.TraceInformation(m.ToString());
                 });
        }
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/aliasLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="horizontal"
        android:focusable="true"
        android:focusableInTouchMode="true" >

        <TextView
            android:id="@+id/aliasLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/alias"
            android:textAppearance="@android:style/TextAppearance.Medium" />

        <EditText
            android:id="@+id/aliasField"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:hint="@string/aliasHint"
            android:maxLength="12" >
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/listHeaderLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/aliasLayout"
        android:orientation="horizontal"
        android:layout_marginTop="10dp" >

        <TextView
            android:id="@+id/serversLabel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="@string/availableServers"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Button
            android:id="@+id/refreshButton"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:onClick="refreshServerList"
            android:text="@string/refresh" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/listLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_below="@+id/listHeaderLayout"
        android:layout_marginTop="10dp"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/serverListView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </ListView>
    </LinearLayout>

</RelativeLayout>


text:
import argparse, pyDNase
from clint.textui import puts, progress
parser = argparse.ArgumentParser(description='Writes a JSON file of DNase I cuts for regions from a BED file')
parser.add_argument("-w", "--window_size", help="Resize all regions to a specific length",default = 0, type=int)
parser.add_argument("-i",action="store_true", help="Ignores strand information in BED file",default=False)
parser.add_argument("-A",action="store_true", help="ATAC-seq mode (default: False)",default=False)
parser.add_argument("regions", help="BED file of the regions")
parser.add_argument("reads", help="BAM file containing the read data")
parser.add_argument("output", help="filename to write the JSON output to")
args = parser.parse_args()

reads = pyDNase.BAMHandler(args.reads, ATAC=args.A)
regions = pyDNase.GenomicIntervalSet(args.regions)

if args.i:
    for each in regions:
        each.strand = "+"

if args.window_size:
    puts("Resizing Regions to {0}".format(args.window_size))
    regions.resizeRegions(toSize=args.window_size)

#TODO: this will load everything everything into memory, it's probably worth making the option to write directly to disk

outfile = open(args.output,"w")
outarr = []
puts("Generating JSON output...")
for i in progress.bar(sorted(regions, key = lambda x : x.importorder)):
    cuts = reads[i]
    outarr.append({"location":i.chromosome + ":" + str(i.startbp) + ":" + str(i.endbp), "positive strand cuts":cuts["+"] , "negative strand cuts":cuts["-"]})
puts("Writing JSON to disk...")
outfile.write(str(outarr))
outfile.close()


text:
<?php

namespace RobatuDinero\DataBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Accusation
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="RobatuDinero\DataBundle\Entity\AccusationRepository")
 */
class Accusation
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var Incident
     *
     * @ORM\ManyToOne(targetEntity="Incident", inversedBy="accusations")
     * @ORM\JoinColumn(name="incident_id", referencedColumnName="id", nullable=false)
     */
    private $incident;

    /**
     * @var Individual[]
     *
     * @ORM\ManyToMany(targetEntity="Individual", mappedBy="accusations")
     */
    private $accused;

    /**
     * @var Grade
     *
     * @ORM\OneToOne(targetEntity="Grade")
     * @ORM\JoinColumn(name="grade_id", referencedColumnName="id", nullable=false)
     */
    private $grade;

    /**
     * @var Evidence[]
     *
     * @ORM\OneToMany(targetEntity="Evidence", mappedBy="accusation")
     */
    private $evidences;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="published", type="date")
     */
    private $published;

    /**
     * Construct
     */
    public function __construct()
    {
        $this->accused = new ArrayCollection();
        $this->evidences = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set published
     *
     * @param \DateTime $published
     * @return Accusation
     */
    public function setPublished($published)
    {
        $this->published = $published;

        return $this;
    }

    /**
     * Get published
     *
     * @return \DateTime
     */
    public function getPublished()
    {
        return $this->published;
    }

    /**
     * Set incident
     *
     * @param \RobatuDinero\DataBundle\Entity\Incident $incident
     * @return Accusation
     */
    public function setIncident(\RobatuDinero\DataBundle\Entity\Incident $incident)
    {
        $this->incident = $incident;

        return $this;
    }

    /**
     * Get incident
     *
     * @return \RobatuDinero\DataBundle\Entity\Incident
     */
    public function getIncident()
    {
        return $this->incident;
    }

    /**
     * Add accused
     *
     * @param \RobatuDinero\DataBundle\Entity\Individual $accused
     * @return Accusation
     */
    public function addAccused(\RobatuDinero\DataBundle\Entity\Individual $accused)
    {
        $this->accused[] = $accused;

        return $this;
    }

    /**
     * Remove accused
     *
     * @param \RobatuDinero\DataBundle\Entity\Individual $accused
     */
    public function removeAccused(\RobatuDinero\DataBundle\Entity\Individual $accused)
    {
        $this->accused->removeElement($accused);
    }

    /**
     * Get accused
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAccused()
    {
        return $this->accused;
    }

    /**
     * Set grade
     *
     * @param \RobatuDinero\DataBundle\Entity\Grade $grade
     * @return Accusation
     */
    public function setGrade(\RobatuDinero\DataBundle\Entity\Grade $grade)
    {
        $this->grade = $grade;

        return $this;
    }

    /**
     * Get grade
     *
     * @return \RobatuDinero\DataBundle\Entity\Grade
     */
    public function getGrade()
    {
        return $this->grade;
    }

    /**
     * Add evidences
     *
     * @param \RobatuDinero\DataBundle\Entity\Evidence $evidences
     * @return Accusation
     */
    public function addEvidence(\RobatuDinero\DataBundle\Entity\Evidence $evidences)
    {
        $this->evidences[] = $evidences;

        return $this;
    }

    /**
     * Remove evidences
     *
     * @param \RobatuDinero\DataBundle\Entity\Evidence $evidences
     */
    public function removeEvidence(\RobatuDinero\DataBundle\Entity\Evidence $evidences)
    {
        $this->evidences->removeElement($evidences);
    }

    /**
     * Get evidences
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getEvidences()
    {
        return $this->evidences;
    }
}


text:
from rest_framework import serializers
from fcm.utils import get_device_model
Device = get_device_model()

class DeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Device
        fields = '__all__'