text:
package org.diirt.graphene.profile.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import org.diirt.graphene.profile.ProfileGraph2D;
import org.diirt.graphene.profile.io.CSVFinder;
import org.diirt.graphene.profile.io.CSVReader;
import org.diirt.graphene.profile.io.CSVWriter;
import org.diirt.graphene.profile.io.DateUtils;

/**
 * Provides the tools necessary for comparing the output tables of profiling
 * to determine changes in the results.
 *

 * Provides options to analyze the two tables types:
 *

 *
ProfileGraph2D 1D tables

 *
MultiLevelProfiler 2D tables

 *

 *

 * The ProfileAnalysis class is purely static and unable
 * to be instantiated.
 *

 * WARNING: the analysis operations assume the preconditions
 * are satisfied with only minor checks.  Therefore it essential
 * that the appropriate file types are selected.
 *
 * @author asbarber
 */
public class ProfileAnalysis {

    /**
     * Private constructor; cannot be instantiated.
     */
    private ProfileAnalysis(){};

    /**
     * Percent level in which difference in values are considered statistically
     * significant and thus take appropriate (warning) action.
     */
    public static final double STATISTICALLY_SIGNIFICANT = 0.05;

    /**
     * Brings a dialog box to ask the user to select two table based
     * CSV files and compares the differences of the tables.
     *

     * Computes the difference of each cell between the first file selected
     * and the second file (first - second).
     *

     * Precondition: both files selected are MultiLevelProfiler
     * table files of the same graph type.
     */
    public static void compareTables2D(){
        String message = "Select two Graphene table files (*.csv) to compute"
                       + " the timing differences of.";
        String hint    = "Note that the differences are calculated by:"
                       + " first file cell minus second file cell.";

        JOptionPane.showMessageDialog(null, message);
        JOptionPane.showMessageDialog(null, hint);

        File fileA, fileB;

        fileA = CSVFinder.browseCSV();
        if (fileA == null){ return; }

        fileB = CSVFinder.browseCSV();
        if (fileB == null){ return; }

        compareTables2D(fileA, fileB);
    }

    /**
     * Computes the difference of each cell between the first file selected
     * and the second file (first - second).
     *

     * Precondition: both files selected are MultiLevelProfiler
     * table files of the same graph type.
     *
     * @param fileA .CSV MultiLevelProfiler formatted file,
     *              considered initial file (compares fileA - fileB)
     * @param fileB .CSV MultiLevelProfiler formatted file,
     *              considered initial file (compares fileA - fileB)
     */
    public static void compareTables2D(File fileA, File fileB){
        CSVReader.validate2DTablesNames(fileA, fileB);

        List<List<String>> dataA = CSVReader.parseCSV(fileA);
        List<List<String>> dataB = CSVReader.parseCSV(fileB);

        CSVReader.validate2DTables(dataA, dataB);
        if (dataA.isEmpty() || dataB.isEmpty()){ return; }

        String badCell = "*Error in reading this cell*";
        List<List> output = new ArrayList<>();

        //Header
        List<String> outputHeader = new ArrayList<>();
        for (int c = 0; c < dataA.get(0).size(); ++c){
            //Entry in both headers are the same
            if (dataA.get(0).get(c).equals(dataB.get(0).get(c))){
                outputHeader.add(dataA.get(0).get(c));
            }
            //Different entry in dataA vs dataB
            else{
                outputHeader.add(badCell);
            }
        }
        output.add(outputHeader);

        //Rows
        for (int r = 1; r < dataA.size(); ++r){
            List<String> outputRow = new ArrayList<>();

            for (int c = 0; c < dataA.get(r).size(); ++c){
                try{
                    double numA = Double.parseDouble(dataA.get(r).get(c));
                    double numB = Double.parseDouble(dataB.get(r).get(c));
                    double diff = (numA - numB) / numA * 100;
                    outputRow.add(String.format("%.3f", diff + "%"));
                }
                catch (NumberFormatException ex){
                    outputRow.add(badCell);
                }
            }

            output.add(outputRow);
        }

        //Saving
        String[] compA = fileA.getName().split("-");
        String[] compB = fileB.getName().split("-");

        String date = DateUtils.getDate(DateUtils.DateFormat.NONDELIMITED),
               dateA = compA[0],
               dateB = compB[0],
               graphType = compA[1];

        File outputFile = CSVWriter.createNewFile(  ProfileGraph2D.LOG_FILEPATH +
                                                    date +
                                                    "-" +
                                                    graphType +
                                                    "-Table2D Difference-" +
                                                    dateA +
                                                    "vs" +
                                                    dateB +
                                                    ".csv");

        CSVWriter.writeData(outputFile, output);
    }

    /**
     * Computes the difference between the last two records
     * in each 1D table and analyzes whether the change was significant.
     *

     * Conditions to Analyze:
     *

     *
Supported files can be found

     *
The 1D tables are in the right .CSV format

     *
The file has two rows of data to compare

     *

     *
     * @return a list of:
     *         for each 1D table analyzed,
     *         a generated analysis message
     *         including the graph profile and the
     *         the results of the analysis (significant increase/decrease)
     */
    public static List<String> analyzeTables1D(){
        List<File>              files = CSVFinder.findTables1D();
        List<String>            results = new ArrayList<>();

        //All files that are supported and found
        for (File tableFile: files){
            if (tableFile != null){
                List<List<String>> tableRows = CSVReader.parseCSV(tableFile);

                //Includes a header plus two rows of data
                if (tableRows.size() > 2){
                    List<String> previous = tableRows.get(tableRows.size() - 2);
                    List<String> recent = tableRows.get(tableRows.size() - 1);

                    //Graph Type
                    String graphType = previous.get(0);

                    //Average Time
                    double percentChange = percentChange(
                            Double.parseDouble(previous.get(2)),
                            Double.parseDouble(recent.get(2))
                    );

                    //Performance Change
                    String performance = performanceChange(
                            Double.parseDouble(previous.get(2)),
                            Double.parseDouble(recent.get(2))
                    );

                    //Analysis
                    results.add(graphType +
                                ": " +
                                performance +
                                ": " +
                                String.format("%.3f", percentChange) +
                                "% changed"
                   );
                }
            }
        }

        results.add("\n" + results.size() + " files analyzed.");
        return results;
    }

    /**
     * Calculates the percent change from initial to final.
     * @param valInit initial value
     * @param valFinal final value
     * @return percent change (as decimal)
     */
    public static double percentChange(double valInit, double valFinal){
        return (valFinal - valInit) / valInit * 100;
    }

    /**
     * Determines the significance of the change from the initial value to
     * the final value.
     * @param valInit initial value
     * @param valFinal final value
     * @return message about the change in performance
     */
    public static String performanceChange(double valInit, double valFinal){
        double percentChange = percentChange(valInit, valFinal);

        //Signficant performance decrease
        if (percentChange > ProfileAnalysis.STATISTICALLY_SIGNIFICANT*100){
            return "Performance Decrease";
        }
        //Significant performance increase
        else if (percentChange < ProfileAnalysis.STATISTICALLY_SIGNIFICANT*100){
            return "Performance Increase";
        }
        //No Significant performance change
        else{
            return "Performance Stable";
        }
    }

}


text:
namespace RayTrace {

class Object {
 public:
  Object() { transform_ = Matrix4D::identity(); }

  virtual ~Object() { }

  Object *parent() const { return parent_; }
  void setParent(Object *parent) { parent_ = parent; }

  const Matrix4D &transform() const { return transform_; }
  void setTransform(const Matrix4D &v) { transform_ = v; }

  Material &material() { return material_; }
  const Material &material() const { return material_; }
  void setMaterial(const Material &v) { material_ = v; }

  void transform(const Matrix4D &t) {
    transform_ *= t;
  }

  void preTransform(const Matrix4D &t) {
    transform_ = t*transform_;
  }

  Intersections intersect(const Ray &ray) const {
    Ray localRay = ray.transform(transform().inverted());

    return intersectInternal(localRay);
  }

  Vector pointNormal(const Point &point) const {
    Point localPoint = transformPoint(point);

    Vector localNormal = pointNormalInternal(localPoint);

    return transformNormal(localNormal);
  }

  Vector pointNormal(const Point &point, const Intersection &intersection) const {
    Point localPoint = transformPoint(point);

    Vector localNormal = pointNormalInternal(localPoint, intersection);

    return transformNormal(localNormal);
  }

  Point transformPoint(const Point &point) const {
    Point point1 = (parent_ ? parent_->transformPoint(point) : point);

    return transform_.inverted()*point1;
  }

  Vector transformNormal(const Vector &normal) const {
    Tuple tuple = transform_.inverted().transposed()*normal;

    Vector normal1 = Vector(tuple.x(), tuple.y(), tuple.z()).normalized();

    return (parent_ ? parent_->transformNormal(normal1) : normal1);
  }

  virtual bool hasObject(const Object *object) const {
    return (object == this);
  }

 protected:
  virtual Intersections intersectInternal(const Ray &ray) const = 0;

  virtual Vector pointNormalInternal(const Point &point) const = 0;

  virtual Vector pointNormalInternal(const Point &point, const Intersection &) const {
    return pointNormalInternal(point);
  }

 protected:
  Object*  parent_ { nullptr };
  Matrix4D transform_;
  Material material_;
};

//---

class TestObject : public Object {
 public:
  TestObject() { }

  const Ray &saveRay() const { return saveRay_; }

  const Point &savePoint() const { return savePoint_; }

 private:
  Intersections intersectInternal(const Ray &ray) const override {
    saveRay_ = ray;

    return Intersections();
  }

  Vector pointNormalInternal(const Point &point) const override {
    savePoint_ = point;

    return Vector(point.x(), point.y(), point.z());
  }

 private:
  mutable Ray   saveRay_;
  mutable Point savePoint_;
};

using TestObjectP = std::shared_ptr<TestObject>;

}

#endif

redpajama_set_name: RedPajamaGithub


text:
/* eslint-disable func-names, space-before-function-paren, wrap-iife, prefer-arrow-callback, no-var, comma-dangle, object-shorthand, one-var, one-var-declaration-per-line, no-else-return, quotes, max-len */
/* global Api */

(function() {
  this.ProjectSelect = (function() {
    function ProjectSelect() {
      $('.js-projects-dropdown-toggle').each(function(i, dropdown) {
        var $dropdown;
        $dropdown = $(dropdown);
        return $dropdown.glDropdown({
          filterable: true,
          filterRemote: true,
          search: {
            fields: ['name_with_namespace']
          },
          data: function(term, callback) {
            var finalCallback, projectsCallback;
            var orderBy = $dropdown.data('order-by');
            finalCallback = function(projects) {
              return callback(projects);
            };
            if (this.includeGroups) {
              projectsCallback = function(projects) {
                var groupsCallback;
                groupsCallback = function(groups) {
                  var data;
                  data = groups.concat(projects);
                  return finalCallback(data);
                };
                return Api.groups(term, {}, groupsCallback);
              };
            } else {
              projectsCallback = finalCallback;
            }
            if (this.groupId) {
              return Api.groupProjects(this.groupId, term, projectsCallback);
            } else {
              return Api.projects(term, orderBy, projectsCallback);
            }
          },
          url: function(project) {
            return project.web_url;
          },
          text: function(project) {
            return project.name_with_namespace;
          }
        });
      });
      $('.ajax-project-select').each(function(i, select) {
        var placeholder;
        this.groupId = $(select).data('group-id');
        this.includeGroups = $(select).data('include-groups');
        this.orderBy = $(select).data('order-by') || 'id';
        placeholder = "Search for project";
        if (this.includeGroups) {
          placeholder += " or group";
        }
        return $(select).select2({
          placeholder: placeholder,
          minimumInputLength: 0,
          query: (function(_this) {
            return function(query) {
              var finalCallback, projectsCallback;
              finalCallback = function(projects) {
                var data;
                data = {
                  results: projects
                };
                return query.callback(data);
              };
              if (_this.includeGroups) {
                projectsCallback = function(projects) {
                  var groupsCallback;
                  groupsCallback = function(groups) {
                    var data;
                    data = groups.concat(projects);
                    return finalCallback(data);
                  };
                  return Api.groups(query.term, {}, groupsCallback);
                };
              } else {
                projectsCallback = finalCallback;
              }
              if (_this.groupId) {
                return Api.groupProjects(_this.groupId, query.term, projectsCallback);
              } else {
                return Api.projects(query.term, _this.orderBy, projectsCallback);
              }
            };
          })(this),
          id: function(project) {
            return project.web_url;
          },
          text: function(project) {
            return project.name_with_namespace || project.name;
          },
          dropdownCssClass: "ajax-project-dropdown"
        });
      });
    }

    return ProjectSelect;
  })();
}).call(window);


text:
using System;

namespace Cmd.Net
{
    /// <summary>
    /// Specifies a name for an enum value.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field)]
    public sealed class FlagAttribute : Attribute
    {
        #region Fields

        private readonly char name;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="T:Cmd.Net.FlagAttribute" /> class using the specified flag name.
        /// </summary>
        /// <param name="name">The name for an argument.</param>
        /// <exception cref="T:System.ArgumentException"><paramref name="name" /> contains one or more invalid characters.</exception>
        /// <remarks>
        /// A <paramref name="name" /> can be null, an empty string (""), or can contain letters, digits and underscore characters.
        /// </remarks>
        public FlagAttribute(char name)
        {
            name = char.ToUpperInvariant(name);
            CommandHelpers.ValidateFlagName("name", name);

            this.name = name;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the name stored in this attribute.
        /// </summary>
        /// <value>The name stored in this attribute.</value>
        public char Name
        {
            get { return name; }
        }

        #endregion
    }
}


text:
package edu.gemini.spModel.io.impl;

import edu.gemini.pot.sp.*;
import edu.gemini.pot.sp.version.JavaVersionMapOps;
import edu.gemini.pot.sp.version.LifespanId;
import edu.gemini.shared.util.VersionVector;
import edu.gemini.spModel.core.SPBadIDException;
import edu.gemini.spModel.core.SPProgramID;
import edu.gemini.spModel.data.Encrypted;
import edu.gemini.spModel.data.ISPDataObject;
import edu.gemini.spModel.gemini.init.ObservationNI;
import edu.gemini.spModel.gemini.obscomp.SPProgram;
import edu.gemini.spModel.gemini.phase1.GsaPhase1Data;
import edu.gemini.spModel.io.impl.migration.to2009B.To2009B;
import edu.gemini.spModel.io.impl.migration.to2010B.ToGnirsAtGn;
import edu.gemini.spModel.io.impl.migration.to2014A.AddMissingStaticInstrumentParams;
import edu.gemini.spModel.io.impl.migration.to2014A.To2014A;
import edu.gemini.spModel.io.impl.migration.to2015A.To2015A;
import edu.gemini.spModel.io.impl.migration.to2015B.To2015B;
import edu.gemini.spModel.io.impl.migration.to2016A.To2016A;
import edu.gemini.spModel.io.impl.migration.toPalote.Grillo2Palote;
import edu.gemini.spModel.obs.SPObservation;
import edu.gemini.spModel.obscomp.SPGroup;
import edu.gemini.spModel.obscomp.SPNote;
import edu.gemini.spModel.pio.*;
import edu.gemini.spModel.pio.xml.PioXmlUtil;
import edu.gemini.spModel.seqcomp.InstrumentSequenceSync;

import java.io.*;
import java.util.*;
import java.util.logging.Logger;
import java.util.logging.Level;

public final class PioSpXmlParser {

    private static final Logger LOG = Logger.getLogger(PioSpXmlParser.class.getName());

    private interface NodeBuilder<T extends ISPNode> {
        boolean matches(Container c);
        T makeNode(ISPFactory f, ISPProgram p, Container c, List<ISPNode> children) throws SPException;
    }

    private static abstract class SimpleNodeBuilder<T extends ISPNode> implements NodeBuilder<T> {
        private final String tag;
        SimpleNodeBuilder(String tag) { this.tag = tag; }

        @Override public boolean matches(Container c) { return tag.equals(c.getKind()); }

        @Override public T makeNode(ISPFactory f, ISPProgram p, Container c, List<ISPNode> children) throws SPException {
            final T t = createEmpty(f, p, c, key(c));
            if (t instanceof ISPContainerNode) {
                ((ISPContainerNode) t).setChildren(children);
            } else if ((t != null) && (children.size() > 0)) {
                throw new RuntimeException("Cannot add children to a " + t.getClass().getName());
            }
            return t;
        }
        protected abstract T createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException;
    }

    private static final NodeBuilder<ISPGroup> GROUP_BUILDER = new SimpleNodeBuilder<ISPGroup>(SpIOTags.GROUP) {
        @Override protected ISPGroup createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException {
            return f.createGroup(p, k);
        }
    };

    private static final NodeBuilder<ISPConflictFolder> CONFLICT_FOLDER_BUILDER = new SimpleNodeBuilder<ISPConflictFolder>(SpIOTags.CONFLICT_FOLDER) {
        @Override protected ISPConflictFolder createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException {
            return f.createConflictFolder(p, k);
        }
    };

    private static final NodeBuilder<ISPTemplateFolder> TEMPLATE_FOLDER_BUILDER = new SimpleNodeBuilder<ISPTemplateFolder>(SpIOTags.TEMPLATE_FOLDER) {
        @Override protected ISPTemplateFolder createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException {
            return f.createTemplateFolder(p, k);
        }
    };

    private static final NodeBuilder<ISPTemplateGroup> TEMPLATE_GROUP_BUILDER = new SimpleNodeBuilder<ISPTemplateGroup>(SpIOTags.TEMPLATE_GROUP) {
        @Override protected ISPTemplateGroup createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException {
            return f.createTemplateGroup(p, k);
        }
    };

    private static final NodeBuilder<ISPTemplateParameters> TEMPLATE_PARAMETERS_BUILDER = new SimpleNodeBuilder<ISPTemplateParameters>(SpIOTags.TEMPLATE_PARAMETERS) {
        @Override protected ISPTemplateParameters createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException {
            return f.createTemplateParameters(p, k);
        }
    };

    private static final NodeBuilder<ISPObservation> OBSERVATION_BUILDER = new NodeBuilder<ISPObservation>() {
        @Override public boolean matches(Container c) {
            return SpIOTags.OBSERVATION.equals(c.getKind());
        }

        @Override public ISPObservation makeNode(ISPFactory f, ISPProgram p, Container c, List<ISPNode> children) throws SPException {
            final String obsIdStr = c.getName();
            final int index;
            try {
                index = ((obsIdStr != null) && (obsIdStr.length() > 0)) ?
                        (new SPObservationID(obsIdStr)).getObservationNumber() : -1;
            } catch (SPBadIDException e) {
                throw new SPException("Could not parse observation id: " + obsIdStr);
            }

            final ISPObservation obs = f.createObservation(p, index, ObservationNI.NO_CHILDREN_INSTANCE, key(c));
            obs.setChildren(children);
            return obs;
        }
    };

    private static boolean isOldObsLogComponent(Container c) {
        return "ObsLog".equals(c.getType()) && "complete".equals(c.getSubtype());
    }

    private static final NodeBuilder<ISPObsQaLog> OBS_QA_LOG_BUILDER = new SimpleNodeBuilder<ISPObsQaLog>(SpIOTags.OBS_QA_LOG) {
        @Override protected ISPObsQaLog createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException {
            return f.createObsQaLog(p, k);
        }
    };

    private static final NodeBuilder<ISPObsExecLog> OBS_EXEC_LOG_BUILDER = new SimpleNodeBuilder<ISPObsExecLog>(SpIOTags.OBS_EXEC_LOG) {
        @Override protected ISPObsExecLog createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException {
            return f.createObsExecLog(p, k);
        }
    };

    private static final NodeBuilder<ISPObsComponent> OBS_COMPONENT_BUILDER = new SimpleNodeBuilder<ISPObsComponent>(SpIOTags.OBSCOMP) {
        @Override public boolean matches(Container c) {
            if (super.matches(c)) {
                return !isOldObsLogComponent(c);
            } else {
                return false;
            }
        }
        @Override public ISPObsComponent createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException {
            final SPComponentType ct = getType(c);
            return (ct == null) ? null : f.createObsComponent(p, ct, k);
        }
    };

    private static final NodeBuilder<ISPSeqComponent> SEQ_COMPONENT_BUILDER = new SimpleNodeBuilder<ISPSeqComponent>(SpIOTags.SEQCOMP) {
        @Override public ISPSeqComponent createEmpty(ISPFactory f, ISPProgram p, Container c, SPNodeKey k) throws SPException {
            final SPComponentType ct = getType(c);
            return (ct == null) ? null : f.createSeqComponent(p, ct, k);
        }
    };

    private static final List<NodeBuilder<? extends ISPNode>> BUILDERS;

    static {
        List<NodeBuilder<? extends ISPNode>> l = new ArrayList<NodeBuilder<? extends ISPNode>>();
        l.add(CONFLICT_FOLDER_BUILDER);
        l.add(GROUP_BUILDER);
        l.add(OBS_COMPONENT_BUILDER);
        l.add(OBSERVATION_BUILDER);
        l.add(OBS_QA_LOG_BUILDER);
        l.add(OBS_EXEC_LOG_BUILDER);
        l.add(SEQ_COMPONENT_BUILDER);
        l.add(TEMPLATE_FOLDER_BUILDER);
        l.add(TEMPLATE_GROUP_BUILDER);
        l.add(TEMPLATE_PARAMETERS_BUILDER);
        BUILDERS = Collections.unmodifiableList(l);
    }

    private static NodeBuilder<? extends ISPNode> builderFor(Container c) {
        for (NodeBuilder<? extends ISPNode> nb : BUILDERS) {
            if (nb.matches(c)) return nb;
        }
        return null;
    }

    // The factory to use for making science program nodes
    private final ISPFactory _factory;

    /**
     * Constructs the parser with the factory and subject.
     */
    public PioSpXmlParser(ISPFactory factory) {
        _factory = factory;
    }

    public ISPRootNode parseDocument(File file) throws Exception {
        return parseDocument(PioXmlUtil.read(file));
    }

    public ISPRootNode parseDocument(Reader reader) throws Exception {
        return parseDocument(PioXmlUtil.read(reader));
    }

    public ISPRootNode parseDocument(PioNode doc) throws Exception {
        return _parseDocument((Document) doc);
    }

    // There is a difference between a node not appearing in the version map
    // (meaning it is unknown in the program) vs appearing with empty node
    // versions (meaning it simply hasn't been modified since being imported
    // from an older XML version).
    private scala.collection.immutable.Map<SPNodeKey, VersionVector<LifespanId, Integer>> completeVersions(ISPNode node, scala.collection.immutable.Map<SPNodeKey, VersionVector<LifespanId, Integer>> versions) {
        final VersionVector<LifespanId, Integer> v = JavaVersionMapOps.getOrNull(versions, node.getNodeKey());
        if (v == null) versions = versions.updated(node.getNodeKey(), JavaVersionMapOps.emptyNodeVersions().incr(node.getLifespanId()));

        if (node instanceof ISPContainerNode) {
            for (ISPNode child : ((ISPContainerNode) node).getChildren()) {
                versions = completeVersions(child, versions);
            }
        }
        return versions;
    }

    // Parse the top level document element
    private ISPRootNode _parseDocument(Document doc) throws Exception {
        // Mutate pre-2015A template folders to be readable.
        To2015A.updateProgram(doc);

        // Update pre-2015B target model
        To2015B.updateProgram(doc);

        // Update pre-2016A programs
        To2016A.updateProgram(doc);

        // We will special case the Phase 1 container.
        Container p1Container = null;

        scala.collection.immutable.Map<SPNodeKey, VersionVector<LifespanId, Integer>> versions = JavaVersionMapOps.emptyVersionMap();

        // A document may contain zero or more containers
        ISPRootNode root = null;
        for (Object o : doc.getContainers()) {
            final Container c = (Container) o;
            final String kind = c.getKind();
            if (SpIOTags.PHASE1.equalsIgnoreCase(kind)) {
                p1Container = c;
            } else if (VersionVectorPio.kind().equalsIgnoreCase(kind)) {
                versions = VersionVectorPio.toVersions(c);
            } else if (SpIOTags.PROGRAM.equalsIgnoreCase(kind)) {
                root = _makeProgramNode(c, c.getName(), key(c));
            } else if (kind.equals(SpIOTags.NIGHTLY_PLAN)) {
                root = _makeNightlyRecordNode(c, c.getName(), key(c));
            } else {
                throw new RuntimeException(String.format("Could not parse top-level container '%s'", kind));
            }
        }

        if (!(root instanceof ISPProgram)) return root;
        final ISPProgram prog = (ISPProgram) root;
        if (p1Container != null) {
            final GsaPhase1Data gsa = getGsaPhase1Data(p1Container);
            if (gsa != null) {
                final SPProgram obj = (SPProgram) root.getDataObject();
                obj.setGsaPhase1Data(gsa);
                root.setDataObject(obj);
            }
        }
        syncIteratorFirstRow(prog);

        prog.setVersions(completeVersions(prog, versions));

        return root;
    }

    // Convert the old Phase 1 model information into the 12B format.
    private GsaPhase1Data.Abstract getP1Abstract(Container c) {
        return new GsaPhase1Data.Abstract(Pio.getValue(c, "phase1Document/common/abstract", ""));
    }

    private GsaPhase1Data.Category getP1Category(Container c) {
        return new GsaPhase1Data.Category(Pio.getValue(c, "phase1Document/common/keywords/keywords-attributes/category", ""));
    }

    private Collection<GsaPhase1Data.Keyword> getP1Keywords(Container c) {
        final ParamSet kps = c.lookupParamSet(new PioPath("phase1Document/common/keywords"));
        if (kps == null) return Collections.emptyList();

        @SuppressWarnings("unchecked") List<Param> keywords = (List<Param>) kps.getParams("keyword");

        // keywords.map(new GsaPhase1Data.Keyword(_))
        final List<GsaPhase1Data.Keyword> lst = new ArrayList<GsaPhase1Data.Keyword>(keywords.size());
        for (Param p : keywords) {
            final String keyword = p.getValue();
            if (keyword != null) lst.add(new GsaPhase1Data.Keyword(keyword));
        }
        return Collections.unmodifiableCollection(lst);
    }

    private GsaPhase1Data.Investigator getInvestigator(ParamSet ps) {
        final String first = Pio.getValue(ps, "name/first", "");
        final String last  = Pio.getValue(ps, "name/last", "");
        final String email = Pio.getValue(ps, "contact/email", "");
        return new GsaPhase1Data.Investigator(first, last, email);
    }

    private GsaPhase1Data.Investigator getP1Pi(Container c) {
        final ParamSet ps = c.lookupParamSet(new PioPath("phase1Document/common/investigators/pi"));
        return ps == null ? new GsaPhase1Data.Investigator("", "", "") : getInvestigator(ps);
    }

    private Collection<GsaPhase1Data.Investigator> getP1Cois(Container c) {
        final ParamSet ps = c.lookupParamSet(new PioPath("phase1Document/common/investigators"));
        if (ps == null) return Collections.emptyList();

        final List<GsaPhase1Data.Investigator> cois = new ArrayList<GsaPhase1Data.Investigator>();
        for (ParamSet cps : ps.getParamSets("coi")) {
            cois.add(getInvestigator(cps));
        }
        return Collections.unmodifiableCollection(cois);
    }

    private GsaPhase1Data getGsaPhase1Data(Container c) {
        return new GsaPhase1Data(
                getP1Abstract(c),
                getP1Category(c),
                getP1Keywords(c),
                getP1Pi(c),
                getP1Cois(c)
        );
    }

    // Awful synchronization of the first step of an iterator with the
    // instrument node itself.  This needs to be done on import and before
    // program versions are stored because it has the potential to modify
    // default values in an instrument node that are not in sync with the
    // sequence.  These modifications are not really changes to the data,
    // just corrections to the incomplete XML information we store so they
    // shouldn't count as modifications.
    private static void syncIteratorFirstRow(ISPProgram prog) {
        for (ISPObservation obs : prog.getAllObservations()) {
            InstrumentSequenceSync.syncFromIterator(obs);
        }
    }

    // Parse the given container element and add nodes for it to the given
    // parent node (parent may be null if at the root of the science program).
    private ISPNode _parseContainer(ISPProgram program, Container container) throws Exception {

        // Handle updating the observation container as necessary to migrate data
        if (SpIOTags.OBSERVATION.equals(container.getKind())) {
            ToGnirsAtGn.instance.update(container);
            AddMissingStaticInstrumentParams.update(container);
        }

        // Map the child containers into ISPNode.
        final List<ISPNode> children = parseChildren(program, container);

        // Now put together the subtree rooted at this node.
        final ISPNode node = _makeContainerNode(program, container, children);
        if (node == null) return null;  // no longer using this node

        // Set the data object, etc.
        addParamSets(node, container);

        // More hacks to handle backwards compatibility.
        if (node instanceof ISPObservation) {
            final ISPObservation o = (ISPObservation) node;
            Grillo2Palote.toPalote(o, container, _factory);
            To2009B.instance.update(o, container);
            To2014A.update(_factory, o, container);
        } else if (node instanceof ISPTemplateFolder) {
            To2014A.update((ISPTemplateFolder) node, container);
        }

        return node;
    }

    private List<ISPNode> parseChildren(ISPProgram p, Container c) throws Exception {
        final List<ISPNode> children = new ArrayList<ISPNode>();
        for (Object o : c.getContainers()) {
            final ISPNode n = _parseContainer(p, (Container) o);
            if (n != null) children.add(n);
        }
        return children;
    }

    private boolean isEncrypted(ParamSet ps, ISPDataObject dataObject) {
        // encryption is new in 2014A so existing XML will be in clear text
        // even if the data object now implements Encrypted
        return (dataObject instanceof Encrypted) && ps.getParam(Encryption.ParamName()) != null;
    }

    private ParamSet decrypt(SPNodeKey key, ParamSet ps) {
        final String encrypted = ps.getParam(Encryption.ParamName()).getValue();
        final String clearText = Encryption.decrypt(key, encrypted);
        try {
            return (ParamSet) PioXmlUtil.read(clearText);
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, "Could not parse encrypted object", ex);
            throw new RuntimeException(ex);
        }
    }

    private void addParamSets(ISPNode n, Container c) throws Exception {
        final SPNodeKey key = n.getNodeKey();
        for (Object o : c.getParamSets()) {
            final ParamSet ps = (ParamSet) o;
            final String kind = ps.getKind();
            final ISPDataObject dataObj = n.getDataObject();

            if (kind != null) {
                if (kind.equals(ISPDataObject.PARAM_SET_KIND)) {
                    final ParamSet ps0 = isEncrypted(ps, dataObj) ? decrypt(key, ps) : ps;
                    dataObj.setParamSet(ps0);
                    _groupCheck(n, dataObj);
                    n.setDataObject(dataObj);
                } else if (kind.equals(SpIOTags.USEROBJ)) {
                    _addUserObject(n, ps);
                } else if (kind.equals(ConflictPio.conflictsParamSet())) {
                    final ParamSet ps0 = isEncrypted(ps, dataObj) ? decrypt(key, ps) : ps;
                    n.setConflicts(ConflictPio.toConflicts(ps0, n));
                }
            }
        }
    }

    private static SPNodeKey key(Container c) {
        final String s = c.getKey();
        return (s == null) ? null : new SPNodeKey(s);
    }

    private ISPNode _makeContainerNode(ISPProgram p, Container c, List<ISPNode> children) throws Exception {
        final NodeBuilder<? extends ISPNode> nb = builderFor(c);
        if (nb == null) {
            LOG.log(Level.WARNING, "Unexpected value for: " + c.getKind() + "/" + c.getType() + "/" + c.getSubtype());
            return null;
        } else {
            return nb.makeNode(_factory, p, c, children);
        }
    }

    private static SPComponentType getType(Container c) {
        try {
            return SPComponentType.getInstance(c.getType(), c.getSubtype());
        } catch (NoSuchElementException ex) {
            LOG.log(Level.WARNING, "Ignoring container with unknown type: type=" + c.getType() + ", subtype=" + c.getSubtype() + ", name=" + c.getName());
            return null;
        }
    }

    // Create and return a program node with the given id and key
    private ISPProgram _makeProgramNode(Container c, String progIdStr, SPNodeKey nodeKey) throws Exception {
        final SPProgramID progId;
        if (progIdStr != null && progIdStr.length() != 0) {
            progId = SPProgramID.toProgramID(progIdStr);
        } else {
            progId = null;
        }
        final ISPProgram p = _factory.createProgram(nodeKey, progId);
        addParamSets(p, c);
        p.setChildren(parseChildren(p, c));
        return p;
    }

    // Create and return a nightly plan node with the given id and key.
    // Note that the caller has to add it to the database at some point.
    private ISPNightlyRecord _makeNightlyRecordNode(Container c, String progIdStr, SPNodeKey nodeKey) throws Exception {
        final SPProgramID progId;
        if (progIdStr != null && progIdStr.length() != 0) {
            progId = SPProgramID.toProgramID(progIdStr);
        } else {
            progId = null;
        }
        final ISPNightlyRecord record = _factory.createNightlyRecord(nodeKey, progId);
        addParamSets(record, c);
        return record;
    }

    // This code is for backward compatibility, since top level notes and phase1 objects
    // are now in an ISPObsComponent under the program or a group node. They used to be
    // stored as user objects in the top level program or group node.
    private void _addUserObject(ISPNode node, ParamSet paramSet)
            throws Exception {
        PioNode pioNode = paramSet.getParent();
        Container containerElement = (Container) pioNode;
        String type = containerElement.getType();
        String subtype = containerElement.getSubtype();

        if (type.equals(SPNote.SP_TYPE.broadType.toString()) && subtype.equals(SPNote.SP_TYPE.narrowType)) {
            ISPProgram prog = (ISPProgram) node;
            SPNote note = new SPNote();
            note.setParamSet(paramSet);
            ISPObsComponent noteNode = _factory.createObsComponent(prog,
                    SPNote.SP_TYPE, new SPNodeKey());
            prog.addObsComponent(0, noteNode);
            _groupCheck(noteNode, note);
            noteNode.setDataObject(note);
        }
    }

    // This code is for backward compatibility, since groups used to be implemented as
    // just a group name property of an observation or note. Now groups are regular nodes.
    // If the given node, with its data object, belong in a group, create the group if needed
    // and move the node there.
    private void _groupCheck(ISPNode node, ISPDataObject dataObj) throws Exception {
        if (dataObj instanceof SPObservation) {
            SPObservation spObs = (SPObservation) dataObj;
            String group = spObs.getGroup();
            if (group != null) {
                spObs.setGroup(null);
                _moveToGroup(group, node);
            }
        } else if (dataObj instanceof SPNote) {
            SPNote note = (SPNote) dataObj;
            String group = note.getGroup();
            if (group != null) {
                note.setGroup(null);
                _moveToGroup(group, node);
            }
        }
    }

    // This code is for backward compatibility.
    // Add a new node to the given node in a group with the given name, creating the group
    // if it doesn't already exist.
    private void _moveToGroup(String group, ISPNode node) throws Exception {
        // parent must be a program if node was in group
        ISPNode parent = node.getParent();
        if (parent instanceof ISPProgram) {
            ISPProgram prog = (ISPProgram) parent;
            ISPGroup groupNode = _getGroupNode(prog, group);
            if (node instanceof ISPObservation) {
                ISPObservation obs = (ISPObservation) node;
                prog.removeObservation(obs);
                groupNode.addObservation(obs);
            } else if (node instanceof ISPObsComponent) {
                ISPObsComponent obsComp = (ISPObsComponent) node;
                prog.removeObsComponent(obsComp);
                groupNode.addObsComponent(obsComp);
            }
        }
    }

    // This code is for backward compatibility.
    // Find and return a group node with the given name, creating the group
    // if it doesn't already exist.
    private ISPGroup _getGroupNode(ISPProgram prog, String group) throws Exception {
        for (Object o : prog.getGroups()) {
            ISPGroup groupNode = (ISPGroup) o;
            SPGroup spGroup = (SPGroup) groupNode.getDataObject();
            if (group.equals(spGroup.getGroup())) {
                return groupNode;
            }
        }
        // No existing group node found: create one
        ISPGroup groupNode = _factory.createGroup(prog, null);
        SPGroup spGroup = (SPGroup) groupNode.getDataObject();
        spGroup.setGroup(group);
        groupNode.setDataObject(spGroup);
        prog.addGroup(groupNode);
        return groupNode;
    }
}


text:
`check-js.py` is a Python script designed to help assist finding, fixing, and annotating (as safe or ignorable) usages of DOM api's innerHTML, or methods in the jQuery which modify the DOM and may use arbitrary strings, or usage of preact's dangerouslySetInnerHTML.

The script will report counts of detected safe usages, and annotations which mark usage as safe or ignorable.

## Usage

Within this codebase:

```shell
npm run check-js
```

or

```shell
sh tools/dom-safe/check-js.sh
```

To apply to any codebase:

```shell
python tools/dom-safe/check-js.py DIRECTORY [EXCLUDE-PATTERN]
```

For example:

```shell
python tools/dom-safe/check-js.py /Users/erikpearson/Work/KBase/2022/helpdesk/PTV-1620/narrative/kbase-extension/static "(ext_components)|(ext_modules)|(ext_packages)"
```

will check the javascript within the Narrative codebase, excluding paths which contain `ext_components`, `ext_modules`, or `ext_packages`.

An internal setting controls whether the output is verbose or not. In verbose mode or if cases are detected, the statistics from each scan are printed. For each scan, if cases are detected, all cases from the file with the most reported cases are printed. This facilitates iterative fixing, without overwhelming the display.

Since this is a Python script, it is easy to tweak if options are not exposed.

## Safe usage heuristics

The script applies some simple heuristics to determine safe usage of these potentially unsafe methods. It is not very smart, but does save some work.

Lines which contain more than one instance of a given jquery function are not subject to the hueristics, simply to keep the script simpler.

There is not very much usage of DOM's innerHTML or preact's dangerouslySetInnerHTML, so there is less safe usage detection for them.

- Using within a line comment (not block comments). Applied to all detections.

  ```javascript
  // this is safe $x.html('<div>i am safe</div>')
  ```

The following only apply to jQuery methods:

- Input is a simple string (single or double-quoted) without markup (angle brackets)
  ```javascript
  .html('hello')
  ```
- Input is a simple string (single or double-quoted) with simple markup which doesn't include "script"
  ```javascript
  .html('<div/>')
  ```
  Note that this is very strict, no spaces allowed within the function call
- Input is a jQuery object which itself takes a simple tag which isn't "script"
  ```javascript
  .append($('<div>'))
  ```
  or
  ```javascript
  .append($('<div>')
  ```
  Note that in the second form the final closing parentheses may be omitted; these functions take only a single argument and are often used in a chaining style.
- Input contains a call to `domSafeText`, which encodes the given text by using an anonymous div node to set the content with innerHTML and reading back as innerText.
- Input contains a call to `domSafeValue`, which coerces the given value to text first (otherwise same as above)
- Input contains a call to `domSafeErrorMessage`, which returns a dom safe string from a given error string or object.
- Input contains a call to `DOMPurity.sanitize`, which scrubs an arbitrary string for dangerous html usage.

> I didn't add the simple tag detection until I had manually annotated many instances of such. In reality, the workflow is often to jump into the file to be inspected and manually search for the jquery function, quickly adding the "xss safe" annotation for simply cases.

## Annotated usage

Annotations may be added above a detected unsafe usage to mark the usage as either safe or ignorable

### Safe usage

Safe usage is annotated by preceding the line with a comment like `\\ xss safe`, which may be followed by any other text. Applied to all detections other than preact.

Note that any number of spaces may be present within the comment.

```javascript
// xss safe
container.innerHTML = layout;
```

Note that in this example, the safe usgae is explained.

```javascript
// xss safe - as long as usage of createBSPanel is safe!
$node.html(
```

### Ignorable "usage"

Usage which is detected but is a false positive may be preceded with a comment like `\\ xss ignore`, which may be followed by other text. Applied to all detections other than preact.

      Note that any number of spaces may be present within the comment.

      Like `xss safe`, this causes the following line to be ignored, however it records it as ignored rather than safe.

      E.g. This definition of `wrap` is confused with the jQuery `wrap` method. (Yes, some heuristics could differentiate them, but probably not worth it given so few instances)

      ```javascript
      // xss ignore
      function wrap(text, width) {
      ```

## Fixes

Here we note common types of fixes.

### Annotation

- Add `\\ xss safe` annotation if the usage is considered safe

- Add `\\ xss ignore` annotation if the usage was caught by the script but is a false positive; e.g. not really a gquery method

### Code fixes

Any externally derived data, including all data from api calls, should generally be placed into the dom via DOM `innerText` or jquery `text()`. In the very few cases in which external data is expected to have html markup, it should be wrapped in a call to `DOMPurity.santize()`.

In many cases, though, html markup involving external data is built via interpolated or concatenated strings. In such cases, the safe "text" methods cannot be used. A set of utility functions should be used. Each of them uses a technique involving `innerHTML` and `innerText` to ensure that such values do not contain any html tags.

The technique:

- applies to any direct external value or string including an external value, but not including the actual markup
- create an unattached `div` tag.
- invoke DOM creation by setting `.innerHTML` for this tag with the subject string
- extract the text nodes of this string by getting the `.innerText` for this tag.
- this has the effect of "stripping" out any html tags from the content

The first method, `domSafeText` applies this technique to a string, setting the innerHTML directly from the provided value.

The second, `domSafeValue`, attempts to coerce the value first to a string, and then sets innerHTML. It throws an error if the value is not a simple Javascript value string, number, or boolean. (In reality, innerHTML does a great job of coercing values, so this is really not necessary - I may go back and remove this function and replace all usages with domSafeText. For one, this would not throw an error in cases of unexpected values.)

A common use case is to use an error message string in an error display. This is often done by simple string interpolation or concatenation. For such cases there are several approaches.

- wrap the message in domSafeText()
- extract the message using errorMessage from domUtils.js. This pokes at the given error object to determine where the message is best derived from. It handles string, JSONRPC exception, general Error-derived exception, or an object which looks like a KBase JSONRPC error response. It wraps the resulting message in domSafeTExt.
- create an error alert using $errorAlert from jqueryUtils.js. This uses errorMessage to extract the message, and displays the message in a bootstrap alert with danger style.

For data provided by ca

## Considerations

- could improve safe usage heuristics to avoid so many safe usage comments. There are many usages of jquery which are inherently safe, such as using a jquery object as input to `html()`.

- on the other hand, these are sometimes indications of complex chains of DOM construction which need tracing. Essentially, one wants to determine that the markup being generated is being safely done, and that is by its nature situational.

- For example:
  - usage of string variables as input
  - usage of jquery objects as input
  - usage of jquery global call as input

Of course it would be possible to detect many more safe cases, but that would be quite complex and involve static analysis, a bit beyond this scope.

Code fixes involving patching jquery were not considered.

In some cases, code was found to be unused and was simply removed.

Ultimately the best solution for the vast majority of cases would be rewriting in a safe manner using modern techniques. For instance:

- replace all usage of string-building with jquery-building, using `text()` where possible
- replace all usage of jquery with preact, which makes unsafe usage harder and rarer


text:
<?php
namespace LapayGroup\RussianPost\Enum;

/**
 * Class PaymentMethods
 * @package LapayGroup\RussianPost
 * @see https://otpravka.pochta.ru/specification#/enums-payment-methods (Данные из спецификации)
 */
class PaymentMethods
{
    const CASHLESS             = 'CASHLESS';            // Безналичный расчет
    const STAMP                = 'STAMP';               // Оплата марками
    const FRANKING             = 'FRANKING';            // Франкирование
    const TO_FRANKING          = 'TO_FRANKING';         // На франкировку
    const ONLINE_PAYMENT_MARK  = 'ONLINE_PAYMENT_MARK'; // Знак онлайн оплаты
}


text:
int main(int, char**)
{
    std::ios ios(0);
    assert(static_cast<bool>(ios) == !ios.fail());
    ios.setstate(std::ios::failbit);
    assert(static_cast<bool>(ios) == !ios.fail());
    static_assert((!std::is_convertible<std::ios, void*>::value), "");
    static_assert((!std::is_convertible<std::ios, int>::value), "");
    static_assert((!std::is_convertible<std::ios const&, int>::value), "");
#if TEST_STD_VER >= 11
    static_assert((!std::is_convertible<std::ios, bool>::value), "");
#endif

  return 0;
}


text:
.letter-effect {
	display: -webkit-flex;
	display: -ms-flexbox;
	display: flex;
	-webkit-flex-direction: row;
	-ms-flex-direction: row;
	flex-direction: row;
	-webkit-align-items: center;
	-ms-flex-align: center;
	align-items: center;
	-webkit-flex-wrap: wrap;
	-ms-flex-wrap: wrap;
	flex-wrap: wrap
}


text:
struct IntMultiplier {
  int value;

  int byTwo() {
    return value*2;
  }

  int byThree() {
    return value*3;
  }

  int byFactor(int f) {
    return value*f;
  }
};

int main()
{
  std::function<int(IntMultiplier&)> doubler = std::mem_fn(&IntMultiplier::byTwo);
  std::function<int(IntMultiplier&)> tripler = std::mem_fn(&IntMultiplier::byThree);
  std::function<int(IntMultiplier&, int)> factor = std::mem_fn(&IntMultiplier::byFactor);

  IntMultiplier foo = {5};

  return ((doubler(foo) == 10) &&
          (tripler(foo) == 15) &&
          (factor(foo,2) == 10)) ? 0 : 1;
}


text:
package com.aos.clientewatson.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.aos.clientewatson.modelos.Response;
import com.google.gson.Gson;
import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.speech_to_text.v1.SpeechToText;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults;
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback;

/**
 * Servlet implementation class ControladorServlet
 */
@WebServlet("/ControladorServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*10, 	// 10 MB
				maxFileSize=1024*1024*50,      	// 50 MB
				maxRequestSize=1024*1024*100)
public class ControladorServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static CountDownLatch lock = new CountDownLatch(1);
	private static String resultado;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ControladorServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("antes de colocar el content type");
		response.setContentType( "application/json");
		System.out.println("gson");
		Gson gson = new Gson();
		System.out.println("Response");
		Response resp = new Response();
		System.out.println("resultado.equals()");
		if(resultado.equals(""))
			resp.setMensaje("No ha termnado la traduccion");
		else
			resp.setMensaje(resultado);

		System.out.println("finalizando para escribir la respuesta del get");
		response.getWriter( ).println( gson.toJson( resp));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		Part partArchivo = request.getPart("userfile");

		InputStream is = null;

		for (Part part : request.getParts())
		{
			//if(!part.getName().equals("") && part.getName().equals("userfile"))
			//{
				is = part.getInputStream();
				/*
				byte[] buffer = new byte[is.available()];
				is.read(buffer);

			    File targetFile = new File("/Users/sergioalexandermendietaarias/Documents/ServidoresAplicacion/jboss-eap-6.1_original/bin/audio.wav");
			    OutputStream outStream = new FileOutputStream(targetFile);
			    outStream.write(buffer);

			    if(outStream != null)
			    	outStream.close();
			    */
			//}
        }

		System.out.println("antes de llamar a la api sppect to text");
		SpeechToText service = new SpeechToText();
		System.out.println("colocando el usuario y el password");
	    service.setUsernameAndPassword("290ee3c4-358a-42b2-91d5-c330431cda85", "dZjzQlJCMWrQ");
	    /*
	    RecognizeOptions options = new RecognizeOptions.Builder().continuous(true).interimResults(true)
	            .contentType(HttpMediaType.AUDIO_WAV).model("es-ES_BroadbandModel").build();
	    */
	    RecognizeOptions options = new RecognizeOptions.Builder().continuous(true).interimResults(true)
	            .contentType(HttpMediaType.AUDIO_WAV).model("es-ES_NarrowbandModel").build();

	    System.out.println("despues de crear las opciones");

	    service.recognizeUsingWebSocket(is, options, new BaseRecognizeCallback() {
	      @Override
	      public void onTranscription(SpeechResults speechResults)
	      {
	    	  System.out.println("transcripcio termino");
	    	  System.out.println(speechResults);
	    	  resultado = speechResults.toString();
	      }

	      @Override
	      public void onDisconnected() {
	        lock.countDown();
	      }
	    });

	    try
	    {
			lock.await(1, TimeUnit.MINUTES);
		}
	    catch (InterruptedException e)
	    {
	    	System.out.println("hubo una interrupcion del servicio " + e.getMessage());
		}
	    System.out.println("esperando a que el servicio termine");
	}

}


text:
{{<govuk_template}}

{{$pageTitle}} View your driving licence information {{/pageTitle}}

{{$head}}
	{{>includes/head}}

{{/head}}

{{$propositionHeader}}
	{{>includes/propositional_navigation}}
{{/propositionHeader}}

{{$headerClass}}with-proposition{{/headerClass}}

{{$content}}
<form action="code" method="get" class="form">

We welcome your feedback feedback  to help us improve this service.

Logout

Your details

Vehicles you can drive

Penalties and disqualifications

<input type="submit" class="fake" value="Share your licence">

						<input type="submit" class="fake" value="information">

To find out more visit the penalty points and disqualifications sections on GOV.UK

				You have
				3 current penalty points

    			You have
				0 disqualifications

To find out more visit the penalty points and disqualifications sections on GOV.UK

</form>
{{/content}}

{{$bodyEnd}}{{/bodyEnd}}

{{$footerTop}}{{/footerTop}}

{{$footerSupportLinks}}

Support links

		Feedback

Cookies

Terms & Conditions

Privacy Policy

Cymraeg

Built by the Driver and Vehicle Licensing Agency

{{/footerSupportLinks}}

{{/govuk_template}}


text:
({
    handleClick: function(cmp, event) {
        var a = $A.expressionService.get(cmp, "c.getString");
        a.setCallback(cmp, function(action) {
            var actionReturnValue = action.getReturnValue();
            cmp.set("v.label", actionReturnValue);
        });
        $A.enqueueAction(a);
    }
})


text:
using ui::mojom::ImeTextSpanThickness;
using ui::mojom::ImeTextSpanUnderlineStyle;

namespace blink {

class CompositionMarkerTest : public testing::Test {};

TEST_F(CompositionMarkerTest, MarkerType) {
  DocumentMarker* marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kTransparent, ImeTextSpanThickness::kNone,
      ImeTextSpanUnderlineStyle::kNone, Color::kTransparent,
      Color::kTransparent);
  EXPECT_EQ(DocumentMarker::kComposition, marker->GetType());
}

TEST_F(CompositionMarkerTest, IsStyleableMarker) {
  DocumentMarker* marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kTransparent, ImeTextSpanThickness::kNone,
      ImeTextSpanUnderlineStyle::kNone, Color::kTransparent,
      Color::kTransparent);
  EXPECT_TRUE(IsStyleableMarker(*marker));
}

TEST_F(CompositionMarkerTest, ConstructorAndGetters) {
  CompositionMarker* marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kDarkGray, ImeTextSpanThickness::kThin,
      ImeTextSpanUnderlineStyle::kSolid, Color::kTransparent, Color::kGray);
  EXPECT_EQ(Color::kDarkGray, marker->UnderlineColor());
  EXPECT_TRUE(marker->HasThicknessThin());
  EXPECT_EQ(ImeTextSpanUnderlineStyle::kSolid, marker->UnderlineStyle());
  EXPECT_EQ(Color::kTransparent, marker->TextColor());
  EXPECT_EQ(Color::kGray, marker->BackgroundColor());

  CompositionMarker* thick_marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kDarkGray, ImeTextSpanThickness::kThick,
      ImeTextSpanUnderlineStyle::kSolid, Color::kTransparent, Color::kGray);
  EXPECT_TRUE(thick_marker->HasThicknessThick());
  EXPECT_EQ(ImeTextSpanUnderlineStyle::kSolid, marker->UnderlineStyle());
  EXPECT_EQ(Color::kTransparent, marker->TextColor());
}

TEST_F(CompositionMarkerTest, UnderlineStyleDottedAndGrayText) {
  CompositionMarker* marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kDarkGray, ImeTextSpanThickness::kThin,
      ImeTextSpanUnderlineStyle::kDot, Color::kGray, Color::kGray);
  EXPECT_EQ(Color::kDarkGray, marker->UnderlineColor());
  EXPECT_TRUE(marker->HasThicknessThin());
  EXPECT_EQ(ImeTextSpanUnderlineStyle::kDot, marker->UnderlineStyle());
  EXPECT_EQ(Color::kGray, marker->TextColor());
  EXPECT_EQ(Color::kGray, marker->BackgroundColor());

  CompositionMarker* thick_marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kDarkGray, ImeTextSpanThickness::kThick,
      ImeTextSpanUnderlineStyle::kDot, Color::kGray, Color::kGray);
  EXPECT_TRUE(thick_marker->HasThicknessThick());
  EXPECT_EQ(ImeTextSpanUnderlineStyle::kDot, marker->UnderlineStyle());
  EXPECT_EQ(Color::kGray, marker->TextColor());
}

TEST_F(CompositionMarkerTest, UnderlineStyleDashed) {
  CompositionMarker* marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kDarkGray, ImeTextSpanThickness::kThin,
      ImeTextSpanUnderlineStyle::kDash, Color::kTransparent, Color::kGray);
  EXPECT_EQ(Color::kDarkGray, marker->UnderlineColor());
  EXPECT_TRUE(marker->HasThicknessThin());
  EXPECT_EQ(ImeTextSpanUnderlineStyle::kDash, marker->UnderlineStyle());
  EXPECT_EQ(Color::kTransparent, marker->TextColor());
  EXPECT_EQ(Color::kGray, marker->BackgroundColor());

  CompositionMarker* thick_marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kDarkGray, ImeTextSpanThickness::kThick,
      ImeTextSpanUnderlineStyle::kDash, Color::kTransparent, Color::kGray);
  EXPECT_TRUE(thick_marker->HasThicknessThick());
  EXPECT_EQ(ImeTextSpanUnderlineStyle::kDash, marker->UnderlineStyle());
  EXPECT_EQ(Color::kTransparent, marker->TextColor());
}

TEST_F(CompositionMarkerTest, UnderlineStyleSquiggled) {
  CompositionMarker* marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kDarkGray, ImeTextSpanThickness::kThin,
      ImeTextSpanUnderlineStyle::kSquiggle, Color::kTransparent, Color::kGray);
  EXPECT_EQ(Color::kDarkGray, marker->UnderlineColor());
  EXPECT_TRUE(marker->HasThicknessThin());
  EXPECT_EQ(ImeTextSpanUnderlineStyle::kSquiggle, marker->UnderlineStyle());
  EXPECT_EQ(Color::kTransparent, marker->TextColor());
  EXPECT_EQ(Color::kGray, marker->BackgroundColor());

  CompositionMarker* thick_marker = MakeGarbageCollected<CompositionMarker>(
      0, 1, Color::kDarkGray, ImeTextSpanThickness::kThick,
      ImeTextSpanUnderlineStyle::kSquiggle, Color::kTransparent, Color::kGray);
  EXPECT_TRUE(thick_marker->HasThicknessThick());
  EXPECT_EQ(ImeTextSpanUnderlineStyle::kSquiggle, marker->UnderlineStyle());
  EXPECT_EQ(Color::kTransparent, marker->TextColor());
}

}  // namespace blink


text:
package org.dswarm.persistence.model.job.utils;

import org.dswarm.persistence.model.job.Function;
import org.dswarm.persistence.model.utils.ExtendedBasicDMPJPAObjectUtils;

/**
 * @author tgaengler
 */
public class BasicFunctionUtils<POJOCLASS extends Function> extends ExtendedBasicDMPJPAObjectUtils<POJOCLASS> {

}


text:
package com.notronix.lw.impl.method.stock;

import com.google.api.client.http.HttpContent;
import com.google.gson.Gson;
import com.notronix.lw.api.model.VariationGroup;
import com.notronix.lw.api.model.VariationGroupTemplate;
import com.notronix.lw.impl.method.AbstractLinnworksAPIMethod;

import static com.notronix.lw.impl.method.MethodUtils.urlEncode;
import static java.util.Objects.requireNonNull;

public class CreateVariationGroupMethod extends AbstractLinnworksAPIMethod<VariationGroup>
{
    private VariationGroupTemplate template;

    @Override
    public String getURI() {
        return "Stock/CreateVariationGroup";
    }

    @Override
    public HttpContent getContent(Gson gson) {
        return urlEncode("template", gson.toJson(requireNonNull(template)));
    }

    @Override
    public VariationGroup getResponse(Gson gson, String jsonPayload) {
        return gson.fromJson(jsonPayload, VariationGroup.class);
    }

    public VariationGroupTemplate getTemplate() {
        return template;
    }

    public void setTemplate(VariationGroupTemplate template) {
        this.template = template;
    }

    public CreateVariationGroupMethod withTemplate(VariationGroupTemplate template) {
        this.template = template;
        return this;
    }
}


text:
package com.sksamuel.scrimage.color;

import java.util.Objects;

public class Grayscale implements Color {

    public final int gray;
    public final int alpha;

    public Grayscale(int gray) {
        this(gray, 0);
    }

    public Grayscale(int gray, int alpha) {
        this.gray = gray;
        this.alpha = alpha;
    }

    public RGBColor toRGB() {
        return new RGBColor(gray, gray, gray, alpha);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Grayscale grayscale = (Grayscale) o;
        return gray == grayscale.gray &&
                alpha == grayscale.alpha;
    }

    @Override
    public int hashCode() {
        return Objects.hash(gray, alpha);
    }
}


text:
fireratingdb is
a [Node](https://nodejs.org) web server driving
a [MongoDB](https://www.mongodb.org) database.

It interacts with
the [FireRatingCloud](https://github.com/jeremytammik/FireRatingCloud) Revit C# add-in, which is a REST client.

For more information, please refer to that repository.

## Installation

The simplest way to install fireratingdb is to host it on a public node.js hosting platform such
as [Heroku](http://heroku.com)
and set up the database on a MongoDB hosting platform such as [mongolab](https://mongolab.com).

The currently running sample installation does just that, and the links to the two
are [fireratingdb.herokuapp.com](http://fireratingdb.herokuapp.com)
and [mongolab.com/databases/firerating](https://mongolab.com/databases/firerating).

You can run either or both components locally on your own system as well, or anywhere else you like, in which case you need to install and
run [MongoDB](https://www.mongodb.org)
and/or [Node](https://nodejs.org) and
the fireratingdb app as needed.

Here is a button to immediately and fully automatically deploy and run this app on your Heroku account for you, creating a new free account for you on the fly if needed:

## Author

Jeremy Tammik,
[The Building Coder](http://thebuildingcoder.typepad.com) and
[The 3D Web Coder](http://the3dwebcoder.typepad.com),
[ADN](http://www.autodesk.com/adn)
[Open](http://www.autodesk.com/adnopen),
[Autodesk Inc.](http://www.autodesk.com)

## License

This sample is licensed under the terms of the [MIT License](http://opensource.org/licenses/MIT).
Please see the [LICENSE](LICENSE) file for full details.


text:
package lombok.javac.apt;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.nio.file.Path;

import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;

import com.sun.tools.javac.file.BaseFileManager;

class Javac9BaseFileObjectWrapper extends com.sun.tools.javac.file.PathFileObject {
	private final LombokFileObject delegate;

	public Javac9BaseFileObjectWrapper(BaseFileManager fileManager, Path path, LombokFileObject delegate) {
		super(fileManager, path);
		this.delegate = delegate;
	}

	@Override public boolean isNameCompatible(String simpleName, Kind kind) {
		return delegate.isNameCompatible(simpleName, kind);
	}

	@Override public URI toUri() {
		return delegate.toUri();
	}

	@SuppressWarnings("all")
	@Override public String getName() {
		return delegate.getName();
	}

	@Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
		return delegate.getCharContent(ignoreEncodingErrors);
	}

	@Override public InputStream openInputStream() throws IOException {
		return delegate.openInputStream();
	}

	@Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
		return delegate.openReader(ignoreEncodingErrors);
	}

	@Override public Writer openWriter() throws IOException {
		return delegate.openWriter();
	}

	@Override public OutputStream openOutputStream() throws IOException {
		return delegate.openOutputStream();
	}

	@Override public long getLastModified() {
		return delegate.getLastModified();
	}

	@Override public boolean delete() {
		return delegate.delete();
	}

	@Override public Kind getKind() {
		return delegate.getKind();
	}

	@Override public NestingKind getNestingKind() {
		return delegate.getNestingKind();
	}

	@Override public Modifier getAccessLevel() {
		return delegate.getAccessLevel();
	}

	@Override public boolean equals(Object obj) {
		if (!(obj instanceof Javac9BaseFileObjectWrapper)) {
			return false;
		}
		return delegate.equals(((Javac9BaseFileObjectWrapper)obj).delegate);
	}

	@Override public int hashCode() {
		return delegate.hashCode();
	}

	@Override public String toString() {
		return delegate.toString();
	}
}


text:
<?php

namespace Google\AdsApi\AdManager\v202211;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class DeliveryData
{

    /**
     * @var int[] $units
     */
    protected $units = null;

    /**
     * @param int[] $units
     */
    public function __construct(array $units = null)
    {
      $this->units = $units;
    }

    /**
     * @return int[]
     */
    public function getUnits()
    {
      return $this->units;
    }

    /**
     * @param int[]|null $units
     * @return \Google\AdsApi\AdManager\v202211\DeliveryData
     */
    public function setUnits(array $units = null)
    {
      $this->units = $units;
      return $this;
    }

}


text:
<?php declare(strict_types = 1);

namespace Nextras\Orm\Collection\Functions;

use Nextras\Orm\Collection\Aggregations\IArrayAggregator;
use Nextras\Orm\Collection\Helpers\ArrayCollectionHelper;
use Nextras\Orm\Collection\Helpers\ArrayPropertyValueReference;
use Nextras\Orm\Entity\IEntity;

/**
 * Collection function implementation for ArrayCollection.
 * Processes expression and reuse its result for further evaluation.
 */
interface IArrayFunction
{
	/**
	 * Returns a value depending on values of entity; the expression passed by args is evaluated during this method
	 * execution.
	 * Usually returns a boolean for filtering evaluation.
	 * @phpstan-param array<int|string, mixed> $args
	 * @phpstan-param IArrayAggregator<mixed>|null $aggregator
	 */
	public function processArrayExpression(
		ArrayCollectionHelper $helper,
		IEntity $entity,
		array $args,
		?IArrayAggregator $aggregator = null
	): ArrayPropertyValueReference;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:background="@color/white">

    <TextView
        android:id="@+id/indeterminate_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Processing..."
        android:textColor="@color/colorPrimaryDark"
        android:textSize="20sp"
        tools:text="Uploading ..."
        android:layout_margin="16dp"
        />

    <ProgressBar
        android:id="@+id/indeterminate_pb"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/indeterminate_tv"
        style="@android:style/Widget.Material.ProgressBar"
        android:layout_margin="16dp"
        android:layout_centerHorizontal="true"/>

    <Button
        android:id="@+id/indeterminate_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel"
        android:layout_below="@id/indeterminate_pb"
        android:layout_alignParentEnd="true"
        android:layout_margin="16dp"/>
</RelativeLayout>


text:
package com.google.api.tools.framework.util;

import com.google.api.tools.framework.util.buildervisitor.BuilderVisitorNodeInfo;
import com.google.api.tools.framework.util.buildervisitor.FileNodeInfo;
import com.google.api.tools.framework.util.buildervisitor.MessageNodeInfo;
import com.google.common.base.Strings;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
import com.google.protobuf.DescriptorProtos.EnumDescriptorProto;
import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.DescriptorProtos.FileDescriptorSet;
import com.google.protobuf.DescriptorProtos.MethodDescriptorProto;
import com.google.protobuf.DescriptorProtos.ServiceDescriptorProto;
import com.google.protobuf.DescriptorProtos.SourceCodeInfo;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Message;
import java.util.Stack;
import java.util.stream.Collectors;

/**
 * A visitor base class for protocol buffer builders. Implements all the accept methods for
 * traversing children.
 */
public abstract class BuilderVisitor extends GenericVisitor<Message.Builder> {
  // Configuration for the operation of this instance.
  private final boolean manageSourceCodeInfo;

  // Current state of this visitor instance.
  private final Stack<BuilderVisitorNodeInfo> ancestors = new Stack<>();
  private final Stack<String> fullyQualifiedNameComponents = new Stack<>();
  private boolean modified = false;
  private FileNodeInfo currentFile = null;

  public BuilderVisitor() {
    this(false);
  }

  public BuilderVisitor(boolean manageSourceCodeInfo) {
    super(Message.Builder.class);
    this.manageSourceCodeInfo = manageSourceCodeInfo;
  }

  /**
   * Get an ancestor of the node currently being visited.
   *
   * <p>Specify 'generationsToSkip' as 0 for immediate parent, 1 for the grandparent, etc.
   */
  public Message.Builder getAncestor(int generationsToSkip) {
    return getAncestorInfo(generationsToSkip).node();
  }

  public String getAncestorFullyQualifiedName(int generationsToSkip) {
    return getAncestorInfo(generationsToSkip).getFullyQualifiedName();
  }

  private BuilderVisitorNodeInfo getAncestorInfo(int generationsToSkip) {
    int index = ancestors.size() - 1 - generationsToSkip;
    if (index < 0 || index >= ancestors.size()) {
      throw new RuntimeException(
          String.format(
              "getAncestorInfo(%d) called with %d ancestors on stack",
              generationsToSkip, ancestors.size()));
    }
    return ancestors.elementAt(index);
  }

  public int getNumAncestors() {
    return ancestors.size();
  }

  public Message.Builder getParent() {
    return getAncestor(0);
  }

  public FileDescriptorProto.Builder getCurrentFile() {
    if (currentFile != null) {
      return (FileDescriptorProto.Builder) currentFile.node();
    }
    return null;
  }

  public String getFullyQualifiedName() {
    return fullyQualifiedNameComponents
        .stream()
        .filter(s -> !Strings.isNullOrEmpty(s.trim()))
        .collect(Collectors.joining("."));
  }

  public String getCurrentContext() {
    StringBuilder currContext = new StringBuilder();
    for (BuilderVisitorNodeInfo ancestorInfo : ancestors) {
      currContext.append(".").append(ProtoHelpers.getContextName(ancestorInfo.node()));
    }
    return currContext.toString();
  }

  public boolean isModified() {
    return modified;
  }

  protected void setModified(boolean flag) {
    modified = flag;
  }

  protected BuilderVisitorNodeInfo pushParent(BuilderVisitorNodeInfo pushed) {
    ancestors.push(pushed);

    if (pushed instanceof FileNodeInfo) {
      currentFile = (FileNodeInfo) pushed;
      fullyQualifiedNameComponents.push(((FileDescriptorProto.Builder) pushed.node()).getPackage());
    } else {
      fullyQualifiedNameComponents.push(ProtoHelpers.getName(pushed.node()));
    }
    pushed.setFullyQualifiedName(getFullyQualifiedName());
    return pushed;
  }

  protected BuilderVisitorNodeInfo popParent() {
    BuilderVisitorNodeInfo popped = ancestors.pop();
    popped.cleanup();

    if (popped instanceof FileNodeInfo) {
      // Reset the currentFile state -- assumes that we can't have nested File nodes.
      currentFile = null;
    }
    fullyQualifiedNameComponents.pop();
    return popped;
  }

  @SuppressWarnings("ReferenceEquality")
  protected BuilderVisitorNodeInfo popExpectedParent(Message.Builder expectedParent) {
    BuilderVisitorNodeInfo oldParent = popParent();

    // The point here is to make sure that the stack hasn't been corrupted, so the caller is
    // passing an object reference and expecting that reference to be exactly what was pushed onto
    // the stack earlier and is being popped off now. (so suppressing "ReferenceEquality" warning
    // above)
    if (expectedParent != oldParent.node()) {
      throw new RuntimeException(
          String.format(
              "Ancestor stack corruption: got %s but expected %s",
              oldParent.node(), expectedParent));
    }
    return oldParent;
  }

  protected void deleteThisChild(Message.Builder element) {
    ancestors.peek().addChildToBeDeleted(element);
    setModified(true);
  }

  protected void deleteAncestor(int generationsToSkip) {
    BuilderVisitorNodeInfo ancestorInfo = getAncestorInfo(generationsToSkip);
    BuilderVisitorNodeInfo ancestorParentInfo = getAncestorInfo(generationsToSkip + 1);
    ancestorParentInfo.addChildToBeDeleted(ancestorInfo.node());
    setModified(true);
  }

  protected void addFieldToMessageParent(FieldDescriptorProto.Builder fieldDesc) {
    addFieldToMessageAncestor(0, fieldDesc, null);
  }

  protected void addFieldToMessageParent(
      FieldDescriptorProto.Builder fieldDesc, SourceCodeInfo.Location location) {
    addFieldToMessageAncestor(0, fieldDesc, location);
  }

  protected void addFieldToMessageAncestor(
      int generationsToSkip, FieldDescriptorProto.Builder fieldDesc) {
    addFieldToMessageAncestor(generationsToSkip, fieldDesc, null);
  }

  protected void addFieldToMessageAncestor(
      int generationsToSkip,
      FieldDescriptorProto.Builder fieldDesc,
      SourceCodeInfo.Location location) {
    BuilderVisitorNodeInfo ancestorInfo = getAncestorInfo(generationsToSkip);
    if (ancestorInfo instanceof MessageNodeInfo) {
      ((MessageNodeInfo) ancestorInfo).addNewField(fieldDesc, location);
      setModified(true);
    } else {
      throw new RuntimeException(
          String.format(
              "Tried to add a field to a %s, but can only add to %s",
              ancestorInfo.node().getClass(), DescriptorProto.Builder.class));
    }
  }

  protected void visitRepeated(int fieldNumber) {
    BuilderVisitorNodeInfo parentInfo = ancestors.peek();
    Message.Builder parentBuilder = (Message.Builder) parentInfo.node();

    FieldDescriptor fieldDesc = parentBuilder.getDescriptorForType().findFieldByNumber(fieldNumber);
    if (fieldDesc == null) {
      throw new RuntimeException(
          String.format(
              "BuilderVisitor internal error - bad field number %d for type %s",
              fieldNumber, parentBuilder.getDescriptorForType().getFullName()));
    }

    int fieldCount = parentBuilder.getRepeatedFieldCount(fieldDesc);
    for (int i = 0; i < fieldCount; i++) {
      Message.Builder element = parentBuilder.getRepeatedFieldBuilder(fieldDesc, i);
      // If we got in here via a FileDescriptor, let it know where we are in the traversal so it
      // can build up its path <-> proto element mappings.
      if (currentFile != null) {
        currentFile.pushChildPath(element, fieldNumber, i);
      }
      try {
        visit(element);
      } finally {
        if (currentFile != null) {
          currentFile.popChildPath();
        }
      }
    }

    parentInfo.processDeletedChildren(fieldDesc);
  }

  @Accepts
  protected void accept(final FileDescriptorSet.Builder files) {
    pushParent(BuilderVisitorNodeInfo.create(files));
    visitRepeated(FileDescriptorSet.FILE_FIELD_NUMBER);
    popExpectedParent(files);
  }

  @Accepts
  protected void accept(final FileDescriptorProto.Builder file) {
    pushParent(BuilderVisitorNodeInfo.create(file));
    currentFile.setManageSourceCodeInfo(manageSourceCodeInfo);

    visitRepeated(FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER);
    visitRepeated(FileDescriptorProto.ENUM_TYPE_FIELD_NUMBER);
    visitRepeated(FileDescriptorProto.EXTENSION_FIELD_NUMBER);
    visitRepeated(FileDescriptorProto.SERVICE_FIELD_NUMBER);

    visit(file.getOptionsBuilder());

    popExpectedParent(file);
  }

  @Accepts
  protected void accept(DescriptorProto.Builder message) {
    MessageNodeInfo messageInfo =
        (MessageNodeInfo) pushParent(BuilderVisitorNodeInfo.create(message, currentFile));

    visitRepeated(DescriptorProto.FIELD_FIELD_NUMBER);
    visitRepeated(DescriptorProto.NESTED_TYPE_FIELD_NUMBER);
    visitRepeated(DescriptorProto.ENUM_TYPE_FIELD_NUMBER);
    visitRepeated(DescriptorProto.EXTENSION_FIELD_NUMBER);

    visit(message.getOptionsBuilder());

    popExpectedParent(message);
  }

  @Accepts
  protected void accept(FieldDescriptorProto.Builder field) {
    pushParent(BuilderVisitorNodeInfo.create(field, currentFile));
    visit(field.getOptionsBuilder());
    popExpectedParent(field);
  }

  @Accepts
  protected void accept(EnumDescriptorProto.Builder enumType) {
    pushParent(BuilderVisitorNodeInfo.create(enumType, currentFile));
    visitRepeated(EnumDescriptorProto.VALUE_FIELD_NUMBER);
    visit(enumType.getOptionsBuilder());
    popExpectedParent(enumType);
  }

  @Accepts
  protected void accept(EnumValueDescriptorProto.Builder val) {
    pushParent(BuilderVisitorNodeInfo.create(val, currentFile));
    visit(val.getOptionsBuilder());
    popExpectedParent(val);
  }

  @Accepts
  protected void accept(ServiceDescriptorProto.Builder service) {
    pushParent(BuilderVisitorNodeInfo.create(service, currentFile));
    visitRepeated(ServiceDescriptorProto.METHOD_FIELD_NUMBER);
    visit(service.getOptionsBuilder());
    popExpectedParent(service);
  }

  @Accepts
  protected void accept(MethodDescriptorProto.Builder method) {
    pushParent(BuilderVisitorNodeInfo.create(method, currentFile));
    visit(method.getOptionsBuilder());
    popExpectedParent(method);
  }
}


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using CKS.Contracts;
using Microsoft.Practices.Unity;

namespace CKS.Prototype
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801
    [ExcludeFromCodeCoverage]
    public class MvcApplication : System.Web.HttpApplication
    {
        private IUnityContainer _container;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            _container = UnityConfig.BuildUnityContainer();
            DatabaseConfig.InitializeDatabase(_container.Resolve<ILogger>());
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(_container);
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var exc = Server.GetLastError();
            _container = UnityConfig.BuildUnityContainer();
            _container.Resolve<ILogger>().ErrorException("Application Error", exc);
        }
    }
}


text:
extern NSString* const kInfobarBannerViewIdentifier;
// Accessibility identifier of the Banner Accept Button.
extern NSString* const kInfobarBannerAcceptButtonIdentifier;
// Accessibility identifier of the Banner Open Modal Button.
extern NSString* const kInfobarBannerOpenModalButtonIdentifier;

#endif  // IOS_CHROME_BROWSER_UI_INFOBARS_BANNERS_INFOBAR_BANNER_CONSTANTS_H_


text:
package io.netty.handler.ssl;

import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;

import io.netty.util.internal.EmptyArrays;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.util.Arrays;

/**
 * This pseudorandom function (PRF) takes as input a secret, a seed, and
 * an identifying label and produces an output of arbitrary length.
 *
 * This is used by the TLS RFC to construct/deconstruct an array of bytes into
 * composite secrets.
 *
 * {@link rfc5246}
 */
final class PseudoRandomFunction {

    /**
     * Constructor never to be called.
     */
    private PseudoRandomFunction() {
    }

    /**
     * Use a single hash function to expand a secret and seed into an
     * arbitrary quantity of output.
     *
     * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
     *                        HMAC_hash(secret, A(2) + seed) +
     *                        HMAC_hash(secret, A(3) + seed) + ...
     * where + indicates concatenation.
     * A() is defined as:
     *       A(0) = seed
     *       A(i) = HMAC_hash(secret, A(i-1))
     * @param secret The starting secret to use for expansion
     * @param label An ascii string without a length byte or trailing null character.
     * @param seed The seed of the hash
     * @param length The number of bytes to return
     * @param algo the hmac algorithm to use
     * @return The expanded secrets
     * @throws IllegalArgumentException if the algo could not be found.
     */
    static byte[] hash(byte[] secret, byte[] label, byte[] seed, int length, String algo) {
        checkPositiveOrZero(length, "length");
        try {
            Mac hmac = Mac.getInstance(algo);
            hmac.init(new SecretKeySpec(secret, algo));
            /*
             * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
             * HMAC_hash(secret, A(2) + seed) + HMAC_hash(secret, A(3) + seed) + ...
             * where + indicates concatenation. A() is defined as: A(0) = seed, A(i)
             * = HMAC_hash(secret, A(i-1))
             */

            int iterations = (int) Math.ceil(length / (double) hmac.getMacLength());
            byte[] expansion = EmptyArrays.EMPTY_BYTES;
            byte[] data = concat(label, seed);
            byte[] A = data;
            for (int i = 0; i < iterations; i++) {
                A = hmac.doFinal(A);
                expansion = concat(expansion, hmac.doFinal(concat(A, data)));
            }
            return Arrays.copyOf(expansion, length);
        } catch (GeneralSecurityException e) {
            throw new IllegalArgumentException("Could not find algo: " + algo, e);
        }
    }

    private static byte[] concat(byte[] first, byte[] second) {
        byte[] result = Arrays.copyOf(first, first.length + second.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }
}


text:
<?php

namespace app\modules\article\models;

use yii\db\ActiveQuery;

/**
 * Scope class for dmpaper which allows to view only none deleted records
 */

class PriceQuery extends ActiveQuery
{
    public function active($state = NULL)
    {
        $this->andWhere(['time_deleted' => $state]);
        return $this;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>io.github.jeddict</groupId>
        <artifactId>jeddict</artifactId>
        <version>6.1.0</version>
    </parent>
    <artifactId>jeddict-tests</artifactId>
    <name>Jeddict Tests</name>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>jpa-modeler</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>orm-generator</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>reverse-engineering</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>jcode-util</artifactId>
            <version>${project.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>javaee</groupId>
                    <artifactId>javaee-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.netbeans.modules</groupId>
            <artifactId>org-netbeans-modules-projectapi-nb</artifactId>
            <version>${netbeans.version}</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.modules</groupId>
            <artifactId>org-netbeans-insane</artifactId>
            <version>${netbeans.version}</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.api</groupId>
            <artifactId>org-openide-filesystems</artifactId>
            <version>${netbeans.version}</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.api</groupId>
            <artifactId>org-netbeans-modules-nbjunit</artifactId>
            <version>${netbeans.version}</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.modules</groupId>
            <artifactId>org-netbeans-libs-freemarker</artifactId>
            <version>${netbeans.version}</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.api</groupId>
            <artifactId>org-netbeans-modules-xml-xdm</artifactId>
            <version>${netbeans.version}</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.api</groupId>
            <artifactId>org-netbeans-modules-extexecution-base</artifactId>
            <version>${netbeans.version}</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.modules</groupId>
            <artifactId>org-netbeans-modules-parsing-nb</artifactId>
            <version>${netbeans.version}</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.api</groupId>
            <artifactId>org-openide-util-lookup</artifactId>
            <version>${netbeans.version}</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.api</groupId>
            <artifactId>org-netbeans-modules-j2ee-eclipselink</artifactId>
            <version>${netbeans.version}</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.jnosql.artemis</groupId>
            <artifactId>artemis-core</artifactId>
            <version>0.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.netbeans.modules</groupId>
            <artifactId>org-netbeans-modules-maven-embedder</artifactId>
            <version>${netbeans.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.maven.shared</groupId>
                    <artifactId>maven-dependency-tree</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>3.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.sun.istack</groupId>
            <artifactId>istack-commons-runtime</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.dukescript.nbjavac</groupId>
            <artifactId>nb-javac</artifactId>
            <version>17.0.0.0</version>
            <classifier>api</classifier>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration combine.self="override" />
            </plugin>
            <plugin>
                <groupId>org.apache.netbeans.utilities</groupId>
                <artifactId>nbm-maven-plugin</artifactId>
                <configuration>
                    <skipNbm>true</skipNbm>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <printSummary>true</printSummary>
<!--                    <includes>
                        <include>OrderColumnModelTest*</include>
                    </includes>-->
                    <!--<argLine>${argLine} -Xms256m -Xmx2048m</argLine>
                    <forkCount>1</forkCount>
                    <runOrder>random</runOrder>-->
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.2</version>
                <executions>
                    <execution>
                        <id>jacoco-initialize</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>report-aggregate</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report-aggregate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
package org.locationtech.geowave.test.basic;

import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.locationtech.geowave.core.store.cli.store.DataStorePluginOptions;
import org.locationtech.geowave.test.TestUtils;

public abstract class AbstractGeoWaveIT {
  protected abstract DataStorePluginOptions getDataStorePluginOptions();

  @Before
  public void cleanBefore() throws IOException {
    TestUtils.deleteAll(getDataStorePluginOptions());
  }

  @After
  public void cleanAfter() throws IOException {
    TestUtils.deleteAll(getDataStorePluginOptions());
  }
}


text:
package org.graphwalker.core.condition;

import org.graphwalker.core.machine.Context;
import org.graphwalker.core.machine.RequirementStatus;

/**
 * @author Nils Olsson
 */
public final class RequirementCoverage extends BaseCondition {

    private final double percent;

    public RequirementCoverage(int percent) {
        this.percent = (double)percent/100;
    }

    public int getPercent() {
        return (int)(percent * 100);
    }

    @Override
    public boolean isFulfilled(Context context) {
        return getFulfilment(context) >= FULFILLMENT_LEVEL && super.isFulfilled(context);
    }

    @Override
    public double getFulfilment(Context context) {
        double totalCount = context.getRequirements().size();
        if (0 == totalCount) {
            return 1.0;
        }
        double passedCount = context.getRequirements(RequirementStatus.PASSED).size();
        double failedCount = context.getRequirements(RequirementStatus.FAILED).size();
        return ((passedCount+failedCount) / totalCount) / percent;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Symb. bot. upsal. 24(no. 2): 115 (1985)

#### Original name
Caeoma destruens Schltdl., 1824

### Remarks
null


text:
/**
 * Created by wangdi on 4/11/16.
 */
'use strict';

import React, {Component, PropTypes} from 'react';
import {Text, View, StyleSheet, Platform, TouchableHighlight, TouchableNativeFeedback} from 'react-native';
import px2dp from '../util/px2dp';
import theme from '../config/theme';

export default class Button extends Component{
    static propTypes = {
        text: PropTypes.string.isRequired,
        onPress: PropTypes.func
    };

    render(){
        if(Platform.OS === 'android') {
            return (
                <TouchableNativeFeedback
                    onPress={this.props.onPress}>
                    {this._renderContent()}
                </TouchableNativeFeedback>
            );
        }else if(Platform.OS === 'ios'){
            return(
                <TouchableHighlight
                    style={{flex: 1, height: px2dp(45)}}
                    onPress={this.props.onPress}
                    activeOpacity={theme.btnActiveOpacity}>
                    {this._renderContent()}
                </TouchableHighlight>
            );
        }
    }

    _renderContent(){
        return(
            <View style={{flex: 1, height: px2dp(45), backgroundColor: '#046ada', alignItems:'center', justifyContent:'center',
                borderRadius: 3}}>
                <Text style={styles.text}>{this.props.text}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
   text:{
       color: 'white',
       fontSize: px2dp(13)
   }
});


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "Bitly" do
  it "fails" do
    fail "No specs! living on the edge"
  end
end